Coverage for biobb_chemistry/babelm/common.py: 21%
78 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-02 09:19 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-02 09:19 +0000
1"""Common functions for package biobb_chemistry.babel"""
3import re
4from pathlib import Path, PurePath
6from biobb_common.generic.biobb_object import BiobbObject
7from biobb_common.tools import file_utils as fu
10class BabelBase(BiobbObject):
11 """Base class of the obabel blocks: goes from the properties to the obabel command, and removes
12 from a PDBQT output the records Open Babel copies from the input."""
14 def prepare(self) -> None:
15 """Checks the formats, the coordinates and the pH"""
16 self.fs_input = fu.str_to_list(self.fs_input)
17 self.fs_output = fu.str_to_list(self.fs_output)
18 self.input_format = get_input_format(self.input_format, self.io_dict["in"]["input_path"], self.out_log)
19 self.output_format = get_output_format(self.output_format, self.io_dict["out"]["output_path"], self.out_log)
21 if self.coordinates is not None and str(self.coordinates) not in ("2", "3"):
22 fu.log("Value %s is not compatible as a coordinates value" % self.coordinates, self.out_log)
23 self.coordinates = None
25 if self.ph == "":
26 self.ph = None
27 if self.ph is not None and not isinstance(self.ph, (int, float)):
28 fu.log("Incorrect format for pH, no value assigned", self.out_log)
29 self.ph = None
31 def obabel_flags(self) -> list[str]:
32 """Goes from the properties of the block to its own obabel flags, written after the coordinates"""
33 return []
35 def run(self) -> None:
36 """Runs obabel and removes the input PDB records that Open Babel >= 3.2 copies to a PDBQT output"""
37 self.cmd = [self.binary_path,
38 "-i" + self.input_format, self.stage_io_dict["in"]["input_path"],
39 "-o" + self.output_format, "-O" + self.stage_io_dict["out"]["output_path"]]
40 if self.coordinates is not None:
41 self.cmd.append("--gen%sd" % self.coordinates)
42 self.cmd += self.obabel_flags()
43 self.cmd += ["-a" + fsi for fsi in self.fs_input or []]
44 self.cmd += ["-x" + fso for fso in self.fs_output or []]
45 # effort only for 3D coordinates
46 if str(self.coordinates) == "3":
47 self.cmd.append("--" + self.effort)
49 self.run_biobb()
51 remove_non_pdbqt_records(self.output_format, self.sandbox_file("output_path"), self.out_log)
54def get_input_format(input_format, input_path, out_log):
55 """Checks if provided input format is correct"""
56 infr = input_format
57 if not is_valid_input(infr):
58 file_extension = PurePath(input_path).suffix
59 if infr is not None:
60 fu.log(
61 "Format %s is not compatible as an input format, assigned input file extension: %s"
62 % (infr, file_extension[1:]),
63 out_log,
64 )
65 infr = file_extension[1:]
67 return infr
70def get_output_format(output_format, output_path, out_log):
71 """Checks if provided output format is correct"""
72 oufr = output_format
73 if not is_valid_output(oufr):
74 file_extension = PurePath(output_path).suffix
75 if oufr is not None:
76 fu.log(
77 "Format %s is not compatible as an output format, assigned output file extension: %s"
78 % (oufr, file_extension[1:]),
79 out_log,
80 )
81 oufr = file_extension[1:]
83 return oufr
86# Records of the PDBQT format (AutoDock / Vina). Open Babel >= 3.2 also copies the
87# PDB records of the input it does not use (HEADER, COMPND, AUTHOR, SEQRES...) to a
88# PDBQT output, and Vina rejects them: "Unknown or inappropriate tag found".
89PDBQT_RECORDS = ("ATOM", "HETATM", "REMARK", "ROOT", "ENDROOT", "BRANCH", "ENDBRANCH",
90 "TORSDOF", "BEGIN_RES", "END_RES", "MODEL", "ENDMDL", "TER", "END")
93def remove_non_pdbqt_records(output_format, output_path, out_log):
94 """Removes from a PDBQT output file the lines that are not PDBQT records"""
95 if not is_valid_output(output_format):
96 output_format = PurePath(output_path).suffix[1:]
97 if output_format != "pdbqt" or not Path(output_path).exists():
98 return
100 lines = Path(output_path).read_text().splitlines(keepends=True)
101 pdbqt_lines = [line for line in lines if not line.strip() or line.startswith(PDBQT_RECORDS)]
102 if len(pdbqt_lines) < len(lines):
103 Path(output_path).write_text("".join(pdbqt_lines))
104 fu.log(
105 "Removed %d non PDBQT records (copied from the input by Open Babel) from %s"
106 % (len(lines) - len(pdbqt_lines), output_path),
107 out_log,
108 )
111# obminimize options: property -> (flag, type or accepted values). The options not set or not
112# valid are left out: obminimize uses its own default
113MINIMIZE_OPTIONS = {
114 "criteria": ("-c {}", float),
115 "method": ("-{}", ["cg", "sd"]),
116 "force_field": ("-ff {}", ["GAFF", "Ghemical", "MMFF94", "MMFF94s", "UFF"]),
117 "hydrogens": ("-h", bool),
118 "steps": ("-n {}", int),
119 "cutoff": ("-cut", bool),
120 "rvdw": ("-rvdw {}", float),
121 "rele": ("-rele {}", float),
122 "frequency": ("-pf {}", int),
123}
126def is_valid_minimize_value(value, kind) -> bool:
127 """Goes from the value of an obminimize option and its type or accepted values to whether it is valid"""
128 value = str(value)
129 if isinstance(kind, list):
130 return value in kind
131 if kind is bool:
132 return value in ("True", "False")
133 if kind is int:
134 return re.fullmatch(r"\d+", value) is not None
135 try:
136 float(value)
137 return True
138 except ValueError:
139 return False
142def is_valid_input(ext):
143 """Checks if input file format is compatible with Open Babel"""
144 formats = [
145 "dat",
146 "ent",
147 "fa",
148 "fasta",
149 "gro",
150 "inp",
151 "log",
152 "mcif",
153 "mdl",
154 "mmcif",
155 "mol",
156 "mol2",
157 "pdb",
158 "pdbqt",
159 "png",
160 "sdf",
161 "smi",
162 "smiles",
163 "txt",
164 "xml",
165 "xtc",
166 ]
167 return ext in formats
170def is_valid_output(ext):
171 """Checks if output file format is compatible with Open Babel"""
172 formats = [
173 "ent",
174 "fa",
175 "fasta",
176 "gro",
177 "inp",
178 "mcif",
179 "mdl",
180 "mmcif",
181 "mol",
182 "mol2",
183 "pdb",
184 "pdbqt",
185 "png",
186 "sdf",
187 "smi",
188 "smiles",
189 "txt",
190 ]
191 return ext in formats