-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathneutralize.py
More file actions
executable file
·80 lines (63 loc) · 2.79 KB
/
Copy pathneutralize.py
File metadata and controls
executable file
·80 lines (63 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python3
__author__ = 'NAME SURNAME'
import argparse
import sys
from read_input import read_input
from rdkit import Chem
from multiprocessing import Pool, cpu_count
pattern = Chem.MolFromSmarts("[+1!h0!$([*]~[-1,-2,-3,-4]),-1!$([*]~[+1,+2,+3,+4])]")
def neutralize_atoms(mol):
# https://www.rdkit.org/docs/Cookbook.html#neutralizing-molecules
mol = Chem.RemoveHs(mol)
at_matches = mol.GetSubstructMatches(pattern)
at_matches_list = [y[0] for y in at_matches]
if len(at_matches_list) > 0:
for at_idx in at_matches_list:
atom = mol.GetAtomWithIdx(at_idx)
chg = atom.GetFormalCharge()
hcount = atom.GetTotalNumHs()
atom.SetFormalCharge(0)
atom.SetNumExplicitHs(hcount - chg)
atom.UpdatePropertyCache()
return mol
def neutralize_item(item):
mol, mol_name = item
try:
mol = neutralize_atoms(mol)
output = Chem.MolToSmiles(mol, isomericSmiles=True, canonical=True) + '\t' + mol_name + '\n'
except:
output = None
return output
def neutralize(input_fname, output_fname, ncpu, verbose):
pool = Pool(max(min(cpu_count(), ncpu), 1))
input_format = 'smi' if input_fname is None else None
fo = open(output_fname, "wt") if output_fname is not None else sys.stdout
try:
for i, line in enumerate(pool.imap(neutralize_item,
read_input(input_fname, input_format=input_format),
chunksize=1), 1):
if line:
fo.write(line)
if verbose and i % 1000 == 0:
sys.stderr.write(f'\rProcessed {i}')
if verbose:
sys.stderr.write(f'\n')
finally:
if output_fname is not None:
fo.close()
def main():
parser = argparse.ArgumentParser(description='Neutralize input structures. Explicit hydrogens will be removed')
parser.add_argument('-i', '--input', metavar='FILENAME', required=False, default=None, type=str,
help='input SDF or SMILES file. If omitted STDIN will be read as SMILES.')
parser.add_argument('-o', '--output', metavar='FILENAME', required=False, default=None, type=str,
help='output SMILES file. If omitted output will be redirected to STDOUT.')
parser.add_argument('-c', '--ncpu', metavar='INTEGER', default=1, type=int,
help='number of cpu to use for calculation. Default: 1.')
parser.add_argument('-v', '--verbose', action='store_true', default=False,
help='print progress to STDERR.')
args = parser.parse_args()
if args.input == "/dev/stdin":
args.input = None
neutralize(args.input, args.output, args.ncpu, args.verbose)
if __name__ == '__main__':
main()