ms-adtools 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ms_adtools/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """AutoDock preparation (ligand, receptor, flexible residues, poses) on RDKit and gemmi."""
2
+ import importlib
3
+
4
+ __all__ = ["prepare_ligand", "prepare_reactive_ligand", "prepare_receptor", "prepare_flexreceptor",
5
+ "pdbqt_to_rdkit", "dlg_to_pdbqt", "flexres_models", "add_zinc_pseudo_atoms"]
6
+ _WHERE = {"prepare_ligand": "ligand", "prepare_reactive_ligand": "ligand", "pdbqt_to_rdkit": "poses",
7
+ "dlg_to_pdbqt": "poses", "flexres_models": "poses",
8
+ "prepare_receptor": "receptor", "prepare_flexreceptor": "receptor",
9
+ "add_zinc_pseudo_atoms": "zinc"}
10
+
11
+
12
+ def __getattr__(name): # load a submodule on first use: a pose reader does not import the receptor path
13
+ if name in _WHERE:
14
+ return getattr(importlib.import_module("ms_adtools." + _WHERE[name]), name)
15
+ raise AttributeError(name)
ms_adtools/ccd.py ADDED
@@ -0,0 +1,221 @@
1
+ """Types and charges of non-standard receptor residues from their CCD component.
2
+
3
+ prepare_receptor guesses a bare cofactor's or modified residue's chemistry; the Chemical Component
4
+ Dictionary has its bond orders and formal charges, keyed by the residue name. The component's
5
+ types and Gasteiger charges are computed as for a ligand and given to the residue's atoms by
6
+ name. Where meeko rejects a residue that does not match its template, the match here is lenient:
7
+ an acid hydrogen the structure lacks (phosphate, carboxylic, sulfonic) ionizes its acid, other
8
+ missing hydrogens fold their charge into their heavy atom (as merged non-polar ones do), a
9
+ hydrogen named otherwise takes a missing one of its heavy atom, one the template has no place
10
+ for is made inert (charge 0, type H), atoms the template does not know keep their values, and a
11
+ residue that cannot be matched keeps them all.
12
+ """
13
+ import os
14
+ import urllib.error
15
+ import urllib.request
16
+ import warnings
17
+ from pathlib import Path
18
+
19
+ import gemmi
20
+ import numpy as np
21
+ from rdkit import Chem, rdBase
22
+
23
+ URL = "https://files.rcsb.org/ligands/download/{}.cif"
24
+ STANDARD = frozenset(
25
+ "ALA ARG ASN ASP CYS GLN GLU GLY HIS ILE LEU LYS MET PHE PRO SER THR TRP TYR VAL "
26
+ "HID HIE HIP HSD HSE HSP CYX CYM ASH GLH LYN DA DC DG DT DU A C G U HOH WAT".split())
27
+ _BOND = {"SING": Chem.BondType.SINGLE, "DOUB": Chem.BondType.DOUBLE, "TRIP": Chem.BondType.TRIPLE,
28
+ "QUAD": Chem.BondType.QUADRUPLE, "AROM": Chem.BondType.AROMATIC}
29
+ _METALS = frozenset(range(3, 5)) | frozenset(range(11, 14)) | frozenset(range(19, 32)) \
30
+ | frozenset(range(37, 51)) | frozenset(range(55, 85))
31
+ _offline, _missing = False, set() # per process: offline, one timeout; a name the RCSB lacks, one ask
32
+
33
+
34
+ def cache_dir():
35
+ return Path(os.environ.get("MOLSUITE_HOME") or Path.home() / ".molsuite") / "cache" / "ccd"
36
+
37
+
38
+ def component_file(resname, where=None):
39
+ """CIF of the CCD component ``resname``: ``where/<RESNAME>.cif`` if given (own or offline
40
+ templates), else the cache, fetched once from the RCSB (components never change). None if absent."""
41
+ global _offline
42
+ code = resname.strip().upper()
43
+ if where is not None:
44
+ path = Path(where) / f"{code}.cif"
45
+ return path if path.exists() else None
46
+ path = cache_dir() / f"{code}.cif"
47
+ if path.exists() or not code.isalnum():
48
+ return path if path.exists() else None
49
+ if _offline or code in _missing or os.environ.get("MOLSUITE_OFFLINE"):
50
+ return None
51
+ try:
52
+ req = urllib.request.Request(URL.format(code), headers={"User-Agent": "ms_adtools"})
53
+ with urllib.request.urlopen(req, timeout=5) as r:
54
+ data = r.read()
55
+ except urllib.error.HTTPError:
56
+ _missing.add(code)
57
+ return None
58
+ except (urllib.error.URLError, OSError, ValueError):
59
+ _offline = True
60
+ return None
61
+ if not data.startswith(b"data_"):
62
+ return None
63
+ path.parent.mkdir(parents=True, exist_ok=True)
64
+ part = path.with_name(f"{path.name}.{os.getpid()}.part") # atomic: parallel preparations fetch alike
65
+ part.write_bytes(data)
66
+ os.replace(part, path)
67
+ return path
68
+
69
+
70
+ def _charge_from_valence(mol):
71
+ for a in mol.GetAtoms():
72
+ if a.GetSymbol() in ("N", "O"):
73
+ a.SetFormalCharge(int(sum(b.GetBondTypeAsDouble() for b in a.GetBonds())) - {"N": 3, "O": 2}[a.GetSymbol()])
74
+
75
+
76
+ def template(block, code=None):
77
+ """(RDKit molecule with every atom, hydrogens too, atom names, {metal name: charge}) of the
78
+ chem_comp tables of a CIF ``block``: a CCD component, or the component ``code`` of an entry
79
+ mmCIF that carries them. Metals are left out (Gasteiger has no parameters for them); their
80
+ charge is the one their bonded atoms lost to them in the drawing (HEC: two N-1 -> Fe +2)."""
81
+ s = gemmi.cif.as_string
82
+ table = block.find("_chem_comp_atom.", ["atom_id", "type_symbol", "?charge", "?comp_id"])
83
+ rows = [r for r in table if code is None or not r.has(3) or s(r[3]) == code]
84
+ if not rows:
85
+ raise ValueError(f"no chem_comp atoms for {code}")
86
+ charge = lambda r: int(s(r[2])) if r.has(2) and s(r[2]) not in ("?", ".", "") else 0
87
+ atoms = [(s(r[0]), s(r[1]).capitalize(), charge(r)) for r in rows]
88
+ pt = Chem.GetPeriodicTable()
89
+ metal = {a[0] for a in atoms if pt.GetAtomicNumber(a[1]) in _METALS}
90
+ mol, index, links = Chem.RWMol(), {}, {}
91
+ for name, element, q in atoms:
92
+ if name not in metal:
93
+ atom = Chem.Atom(element)
94
+ atom.SetFormalCharge(q)
95
+ atom.SetNoImplicit(True) # the component lists every hydrogen
96
+ index[name] = mol.AddAtom(atom)
97
+ for r in block.find("_chem_comp_bond.", ["atom_id_1", "atom_id_2", "value_order", "?comp_id"]):
98
+ if code is not None and r.has(3) and s(r[3]) != code:
99
+ continue
100
+ x, y = s(r[0]), s(r[1])
101
+ if x in index and y in index:
102
+ mol.AddBond(index[x], index[y], _BOND.get(s(r[2]).upper(), Chem.BondType.SINGLE))
103
+ elif {x, y} & metal and {x, y} - metal:
104
+ links.setdefault(*({x, y} & metal), []).append(index.get(*({x, y} - metal)))
105
+ mol = mol.GetMol()
106
+ if not table.has_column(2): # an entry mmCIF's tables have no formal charges
107
+ _charge_from_valence(mol)
108
+ quiet = rdBase.BlockLogs() # noqa: F841 - the retry below answers RDKit's complaint
109
+ try:
110
+ Chem.SanitizeMol(mol)
111
+ except Exception: # ponytail: inconsistent charges (HEC's O-1 that keeps its H): N/O charges from valence, aromatic bonds aside
112
+ _charge_from_valence(mol)
113
+ Chem.SanitizeMol(mol)
114
+ metals = {m: -sum(mol.GetAtomWithIdx(i).GetFormalCharge() for i in links.get(m, ()) if i is not None)
115
+ for m in metal}
116
+ return mol, [a[0] for a in atoms if a[0] not in metal], metals
117
+
118
+
119
+ _ACID_H = Chem.MolFromSmarts("[#1]-[OX2]-[P,$([#6,#16]=O)]") # H of a phosphate, carboxylic or sulfonic acid
120
+
121
+
122
+ def _apply(lines, mol, names, metals, metal_charges=False):
123
+ """The residue's PDBQT ``lines`` retyped and recharged from the template; None if they do not match."""
124
+ from ms_adtools.ligand import _charges, _types
125
+ at = {n: i for i, n in enumerate(names)}
126
+ name = lambda l: l[12:16].strip()
127
+ is_h = lambda l: l[77:].strip() in ("H", "HD", "HS")
128
+ hydrogens = lambda i: [x.GetIdx() for x in mol.GetAtomWithIdx(i).GetNeighbors() if x.GetAtomicNum() == 1]
129
+ heavy = [n for n, l in enumerate(lines) if not is_h(l)]
130
+ matched = {n: at[name(lines[n])] for n in heavy
131
+ if name(lines[n]) in at and mol.GetAtomWithIdx(at[name(lines[n])]).GetAtomicNum() > 1}
132
+ if not heavy or len(matched) * 2 < len(heavy):
133
+ return None
134
+ xyz = np.array([[float(l[c:c + 8]) for c in (30, 38, 46)] for l in lines])
135
+ hs = [n for n, l in enumerate(lines) if is_h(l)]
136
+ parent = {n: matched.get(min(heavy, key=lambda h: np.linalg.norm(xyz[h] - xyz[n]))) for n in hs}
137
+ taken = set()
138
+ for n in hs: # named as in the template and on the same atom
139
+ i = at.get(name(lines[n]))
140
+ if parent[n] is not None and i in hydrogens(parent[n]):
141
+ matched[n] = i
142
+ taken.add(i)
143
+ extra = []
144
+ for n in hs: # named otherwise: a missing H of its atom; one the template has no room for is extra
145
+ if n in matched or parent[n] is None:
146
+ continue
147
+ free = [i for i in hydrogens(parent[n]) if i not in taken]
148
+ if free:
149
+ matched[n] = free[0]
150
+ taken.add(free[0])
151
+ else:
152
+ extra.append(n)
153
+ present = set(matched.values())
154
+ # an acid H the structure lacks on an atom it has: the acid is ionized (the CCD draws it neutral)
155
+ drop = sorted({h for h, o, _ in mol.GetSubstructMatches(_ACID_H) if h not in taken and o in present}, reverse=True)
156
+ rw = Chem.RWMol(mol)
157
+ for h in drop:
158
+ o = rw.GetAtomWithIdx(h).GetNeighbors()[0]
159
+ o.SetFormalCharge(o.GetFormalCharge() - 1)
160
+ rw.RemoveAtom(h)
161
+ ionized = rw.GetMol()
162
+ Chem.SanitizeMol(ionized)
163
+ new = {i: k for k, i in enumerate(i for i in range(mol.GetNumAtoms()) if i not in drop)}
164
+ types, charges = _types(ionized), _charges(ionized)
165
+ q = {n: charges[new[i]] for n, i in matched.items()}
166
+ owner = {i: n for n, i in matched.items()}
167
+ for i in new: # other template H the structure lacks: merged into their atom
168
+ a = mol.GetAtomWithIdx(i)
169
+ if a.GetAtomicNum() == 1 and i not in taken and a.GetDegree():
170
+ p = owner.get(a.GetNeighbors()[0].GetIdx())
171
+ if p is not None:
172
+ q[p] += charges[new[i]]
173
+ out = list(lines)
174
+ for n, i in matched.items():
175
+ out[n] = "%s%6.3f %-2s" % (lines[n][:70], q[n], types[new[i]])
176
+ if metal_charges:
177
+ for n, l in enumerate(lines):
178
+ if name(l) in metals:
179
+ out[n] = "%s%6.3f %-2s" % (l[:70], metals[name(l)], l[77:].strip())
180
+ for n in extra: # ponytail: an H the chemistry has no place for (an aromatic N protonated by guess) is made inert, not deleted
181
+ out[n] = "%s%6.3f %-2s" % (lines[n][:70], 0.0, "H")
182
+ return out
183
+
184
+
185
+ def apply_ccd(pdbqt, where=None, structure=None, metal_charges=False):
186
+ """Receptor PDBQT with each non-standard residue typed and charged from its chemical component:
187
+ the chem_comp tables of ``structure`` (the receptor's mmCIF) when it has them, else
188
+ ``component_file(resname, where)``; residues without a usable component keep their values.
189
+ ``metal_charges`` also gives a metal of the component (heme Fe) the charge its bonds took."""
190
+ lines = pdbqt.splitlines()
191
+ groups = {}
192
+ for n, l in enumerate(lines):
193
+ if l.startswith(("ATOM", "HETATM")) and l[17:20].strip() not in STANDARD:
194
+ groups.setdefault((l[21], l[22:27], l[17:20].strip()), []).append(n)
195
+ own, comps = None, set()
196
+ if structure is not None and str(structure).lower().endswith((".cif", ".mmcif", ".cif.gz")):
197
+ own = gemmi.cif.read(str(structure)).sole_block()
198
+ comps = set(own.find_values("_chem_comp_bond.comp_id")) & set(own.find_values("_chem_comp_atom.comp_id"))
199
+ cache = {}
200
+ for (chain, num, resname), rows in groups.items():
201
+ if len(rows) == 1: # ions: the single atom is right as it is
202
+ continue
203
+ if resname not in cache:
204
+ try:
205
+ if resname in comps:
206
+ cache[resname] = template(own, resname)
207
+ else:
208
+ path = component_file(resname, where)
209
+ cache[resname] = template(gemmi.cif.read(str(path)).sole_block()) if path else None
210
+ except Exception as e: # ponytail: an unusable component (odd valences) keeps the receptor's chemistry
211
+ warnings.warn(f"CCD {resname}: {e}; the receptor's types and charges kept")
212
+ cache[resname] = None
213
+ if cache[resname] is None:
214
+ continue
215
+ got = _apply([lines[n] for n in rows], *cache[resname], metal_charges=metal_charges)
216
+ if got is None:
217
+ warnings.warn(f"{resname} {chain}{num.strip()}: too few atoms named as in its CCD component; the receptor's kept")
218
+ continue
219
+ for n, l in zip(rows, got):
220
+ lines[n] = l
221
+ return "\n".join(lines) + "\n"
ms_adtools/cli.py ADDED
@@ -0,0 +1,129 @@
1
+ """ms_adtools command line: ligand, receptor, flexreceptor, poses."""
2
+ import argparse
3
+ import sys
4
+ import warnings
5
+ from pathlib import Path
6
+
7
+
8
+ def _ligands(path):
9
+ """(name, 3D mol) of each molecule in an SDF/MOL/mol2 file, or of each SMILES line of a .smi."""
10
+ from rdkit import Chem
11
+ from rdkit.Chem import AllChem
12
+ suffix = path.suffix.lower()
13
+ if suffix in (".smi", ".smiles", ".txt"):
14
+ for n, line in enumerate(path.read_text().splitlines(), 1):
15
+ if not line.strip():
16
+ continue
17
+ smiles, _, name = line.strip().partition(" ")
18
+ mol = Chem.MolFromSmiles(smiles)
19
+ if mol is not None:
20
+ mol = Chem.AddHs(mol)
21
+ if AllChem.EmbedMolecule(mol, randomSeed=0xf00d) != 0:
22
+ mol = None
23
+ else:
24
+ AllChem.MMFFOptimizeMolecule(mol)
25
+ yield name.strip() or f"ligand_{n}", mol
26
+ elif suffix == ".mol2":
27
+ yield path.stem, Chem.MolFromMol2File(str(path), removeHs=False)
28
+ else:
29
+ for n, mol in enumerate(Chem.SDMolSupplier(str(path), removeHs=False), 1):
30
+ yield (mol.GetProp("_Name").strip() if mol is not None and mol.HasProp("_Name") else "") \
31
+ or f"ligand_{n}", mol
32
+
33
+
34
+ def _ligand(a):
35
+ from ms_adtools import prepare_ligand
36
+ mols = list(_ligands(a.input))
37
+ single = len(mols) == 1
38
+ out = Path(a.output or (a.input.with_suffix(".pdbqt") if single else a.input.with_suffix("")))
39
+ if not single:
40
+ out.mkdir(parents=True, exist_ok=True)
41
+ failed = 0
42
+ for name, mol in mols:
43
+ try:
44
+ if mol is None:
45
+ raise ValueError("RDKit could not read it")
46
+ text = prepare_ligand(mol, open_macrocycles=a.macrocycles, hydrate=a.hydrate,
47
+ flexible_amides=a.flexible_amides)
48
+ except Exception as exc: # one bad molecule does not stop a library
49
+ failed += 1
50
+ print(f"{name}: {exc}", file=sys.stderr)
51
+ continue
52
+ (out if single else out / f"{name}.pdbqt").write_text(text)
53
+ return 1 if failed else 0
54
+
55
+
56
+ def _receptor(a):
57
+ from ms_adtools import prepare_receptor
58
+ text = prepare_receptor(a.input, repairs=a.repairs, charges=a.charges, cleanup=a.cleanup,
59
+ zinc="auto" if a.zinc else False, ccd=a.ccd)
60
+ Path(a.output or a.input.with_suffix(".pdbqt")).write_text(text)
61
+ return 0
62
+
63
+
64
+ def _flexreceptor(a):
65
+ from ms_adtools import prepare_flexreceptor
66
+ rigid, flex = prepare_flexreceptor(a.input, a.residues, reactive=a.reactive or ())
67
+ stem = a.output or str(a.input.with_suffix(""))
68
+ Path(stem + "_rigid.pdbqt").write_text(rigid)
69
+ Path(stem + "_flex.pdbqt").write_text(flex)
70
+ return 0
71
+
72
+
73
+ def _poses(a):
74
+ from rdkit import Chem
75
+ from ms_adtools import dlg_to_pdbqt, pdbqt_to_rdkit
76
+ text = a.input.read_text()
77
+ mol = pdbqt_to_rdkit(dlg_to_pdbqt(text) if a.input.suffix.lower() == ".dlg" else text)
78
+ with Chem.SDWriter(str(a.output or a.input.with_suffix(".sdf"))) as writer:
79
+ for conf in mol.GetConformers():
80
+ for name, value in conf.GetPropsAsDict().items():
81
+ mol.SetProp(name, str(value))
82
+ writer.write(mol, confId=conf.GetId())
83
+ return 0
84
+
85
+
86
+ def main(argv=None):
87
+ parser = argparse.ArgumentParser(prog="ms_adtools", description=__doc__)
88
+ sub = parser.add_subparsers(dest="command", required=True)
89
+
90
+ p = sub.add_parser("ligand", help="ligand PDBQT from an SDF, MOL, mol2 or SMILES (.smi) file")
91
+ p.add_argument("input", type=Path)
92
+ p.add_argument("-o", "--output", help="PDBQT file; a directory when the input holds several molecules")
93
+ p.add_argument("--macrocycles", action="store_true", help="open macrocycles (Vina scoring only)")
94
+ p.add_argument("--hydrate", action="store_true", help="add the W atoms of hydrated docking")
95
+ p.add_argument("--flexible-amides", action="store_true", help="let amide bonds rotate")
96
+ p.set_defaults(run=_ligand)
97
+
98
+ p = sub.add_parser("receptor", help="receptor PDBQT from a PDB, mmCIF, PQR, PDBQT or mol2 file")
99
+ p.add_argument("input", type=Path)
100
+ p.add_argument("-o", "--output")
101
+ p.add_argument("--repairs", default="", help='"hydrogens": add them to residues that have none')
102
+ p.add_argument("--charges", choices=("gasteiger", "keep"), help="default: keep a PQR/mol2's, else Gasteiger")
103
+ p.add_argument("--cleanup", default="nphs_lps_waters_nonstdres", help="as prepare_receptor4.py -U")
104
+ p.add_argument("--zinc", action="store_true", help="add AutoDock4Zn TZ pseudo-atoms")
105
+ p.add_argument("--ccd", action="store_true", help="type non-standard residues from their CCD component")
106
+ p.set_defaults(run=_receptor)
107
+
108
+ p = sub.add_parser("flexreceptor", help="rigid and flexible PDBQT pair for flexible-residue docking")
109
+ p.add_argument("input", type=Path)
110
+ p.add_argument("-r", "--residues", required=True, help='e.g. "A:2-10,B:20", "A:239,315", "A:ARG239"')
111
+ p.add_argument("--reactive", nargs="+", help='reactive residues, e.g. "A:SER203" "A:HIS57=NE2"')
112
+ p.add_argument("-o", "--output", help="prefix: writes PREFIX_rigid.pdbqt and PREFIX_flex.pdbqt")
113
+ p.set_defaults(run=_flexreceptor)
114
+
115
+ p = sub.add_parser("poses", help="docked poses (PDBQT or DLG) to an SDF, one record per pose")
116
+ p.add_argument("input", type=Path)
117
+ p.add_argument("-o", "--output")
118
+ p.set_defaults(run=_poses)
119
+
120
+ a = parser.parse_args(argv)
121
+ warnings.formatwarning = lambda message, *_a, **_k: f"warning: {message}\n"
122
+ try:
123
+ return a.run(a)
124
+ except (OSError, ValueError) as exc:
125
+ parser.exit(1, f"ms_adtools {a.command}: {exc}\n")
126
+
127
+
128
+ if __name__ == "__main__":
129
+ sys.exit(main())