-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1290 lines (1032 loc) · 37.8 KB
/
utils.py
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2023. RadonPy developers. All rights reserved.
# Use of this source code is governed by a BSD-3-style
# license that can be found in the LICENSE file.
# ******************************************************************************
# core.utils module
# ******************************************************************************
import os
import psutil
from copy import deepcopy
from itertools import permutations
import numpy as np
import pickle
import json
from rdkit import Chem
from rdkit.Chem import AllChem
import const
from ff import ff_class
__version__ = '0.2.8'
class Angle():
"""
utils.Angle() object
"""
def __init__(self, a, b, c, ff):
self.a = a
self.b = b
self.c = c
self.ff = ff
def to_dict(self):
dic = {
'a': int(self.a),
'b': int(self.b),
'c': int(self.c),
'ff': self.ff.to_dict()
}
return dic
class Dihedral():
"""
utils.Dihedral() object
"""
def __init__(self, a, b, c, d, ff):
self.a = a
self.b = b
self.c = c
self.d = d
self.ff = ff
def to_dict(self):
dic = {
'a': int(self.a),
'b': int(self.b),
'c': int(self.c),
'd': int(self.d),
'ff': self.ff.to_dict()
}
return dic
class Improper():
"""
utils.Improper() object
"""
def __init__(self, a, b, c, d, ff):
self.a = a
self.b = b
self.c = c
self.d = d
self.ff = ff
def to_dict(self):
dic = {
'a': int(self.a),
'b': int(self.b),
'c': int(self.c),
'd': int(self.d),
'ff': self.ff.to_dict()
}
return dic
class Cell():
def __init__(self, xhi, xlo, yhi, ylo, zhi, zlo):
self.xhi = xhi
self.xlo = xlo
self.yhi = yhi
self.ylo = ylo
self.zhi = zhi
self.zlo = zlo
self.dx = xhi-xlo
self.dy = yhi-ylo
self.dz = zhi-zlo
self.volume = self.dx * self.dy * self.dz
def to_dict(self):
dic = {
'xhi': float(self.xhi),
'xlo': float(self.xlo),
'yhi': float(self.yhi),
'ylo': float(self.ylo),
'zhi': float(self.zhi),
'zlo': float(self.zlo),
}
return dic
class RadonPyError(Exception):
pass
def radon_print(text, level=0):
if level == 0:
text = 'RadonPy debug info: '+text
elif level == 1:
text = 'RadonPy info: '+text
elif level == 2:
text = 'RadonPy warning: '+text
elif level == 3:
raise RadonPyError(text)
if level >= const.print_level or const.debug:
print(text, flush=True)
def set_mol_id(mol, pdb=True):
"""
utils.set_mol_id
Set molecular ID
Args:
mol: RDkit Mol object
Optional args:
pdb: Update the ChainId of PDB (boolean)
Returns:
Rdkit Mol object
"""
molid = 1
# Clear mol_id
for atom in mol.GetAtoms():
atom.SetIntProp('mol_id', 0)
def recursive_set_mol_id(atom, molid):
for na in atom.GetNeighbors():
if na.GetIntProp('mol_id') == 0:
na.SetIntProp('mol_id', molid)
if pdb and na.GetPDBResidueInfo() is not None:
if molid <= len(const.pdb_id):
na.GetPDBResidueInfo().SetChainId(const.pdb_id[molid-1])
recursive_set_mol_id(na, molid)
for atom in mol.GetAtoms():
if atom.GetIntProp('mol_id') == 0:
atom.SetIntProp('mol_id', molid)
if pdb and atom.GetPDBResidueInfo() is not None:
if molid <= len(const.pdb_id):
atom.GetPDBResidueInfo().SetChainId(const.pdb_id[molid-1])
recursive_set_mol_id(atom, molid)
molid += 1
return mol
def count_mols(mol):
"""
utils.count_mols
Count number of molecules
Args:
mol: RDkit Mol object
Returns:
Number of molecules (int)
Examples:
>>> mol = Chem.MolFromSmiles("CC.C=C")
>>> count_mols(mol)
2
>>> mol = Chem.MolFromSmiles("c1ccccc1")
>>> count_mols(mol)
1
"""
fragments = Chem.GetMolFrags(mol, asMols=True)
return len(fragments)
def remove_atom(mol, idx):
"""
utils.remove_atom
Remove a specific atom from RDkit Mol object
Args:
mol: RDkit Mol object
idx: Atom index of removing atom in RDkit Mol object
Returns:
RDkit Mol object
"""
angles_copy = []
dihedrals_copy = []
impropers_copy = []
cell_copy = None
if hasattr(mol, 'cell'):
cell_copy = mol.cell
if hasattr(mol, 'impropers'):
for imp in mol.impropers:
if idx in [imp.a, imp.b, imp.c, imp.d]:
continue
idx_a = imp.a if imp.a < idx else imp.a-1
idx_b = imp.b if imp.b < idx else imp.b-1
idx_c = imp.c if imp.c < idx else imp.c-1
idx_d = imp.d if imp.d < idx else imp.d-1
impropers_copy.append(
Improper(
a=idx_a,
b=idx_b,
c=idx_c,
d=idx_d,
ff=deepcopy(imp.ff)
)
)
if hasattr(mol, 'dihedrals'):
for dih in mol.dihedrals:
if idx in [dih.a, dih.b, dih.c, dih.d]:
continue
idx_a = dih.a if dih.a < idx else dih.a-1
idx_b = dih.b if dih.b < idx else dih.b-1
idx_c = dih.c if dih.c < idx else dih.c-1
idx_d = dih.d if dih.d < idx else dih.d-1
dihedrals_copy.append(
Dihedral(
a=idx_a,
b=idx_b,
c=idx_c,
d=idx_d,
ff=deepcopy(dih.ff)
)
)
if hasattr(mol, 'angles'):
for angle in mol.angles:
if idx in [angle.a, angle.b, angle.c]:
continue
idx_a = angle.a if angle.a < idx else angle.a-1
idx_b = angle.b if angle.b < idx else angle.b-1
idx_c = angle.c if angle.c < idx else angle.c-1
angles_copy.append(
Angle(
a=idx_a,
b=idx_b,
c=idx_c,
ff=deepcopy(angle.ff)
)
)
rwmol = Chem.RWMol(mol)
for pb in mol.GetAtomWithIdx(idx).GetNeighbors():
rwmol.RemoveBond(idx, pb.GetIdx())
rwmol.RemoveAtom(idx)
mol = rwmol.GetMol()
setattr(mol, 'angles', angles_copy)
setattr(mol, 'dihedrals', dihedrals_copy)
setattr(mol, 'impropers', impropers_copy)
if cell_copy is not None: setattr(mol, 'cell', cell_copy)
return mol
def add_bond(mol, idx1, idx2, order=Chem.rdchem.BondType.SINGLE):
"""
utils.add_bond
Add a new bond in RDkit Mol object
Args:
mol: RDkit Mol object
idx1, idx2: Atom index adding a new bond (int)
order: bond order (RDkit BondType object, ex. Chem.rdchem.BondType.SINGLE)
Returns:
RDkit Mol object
"""
# Copy the extended attributes
angles_copy = mol.angles if hasattr(mol, 'angles') else []
dihedrals_copy = mol.dihedrals if hasattr(mol, 'dihedrals') else []
impropers_copy = mol.impropers if hasattr(mol, 'impropers') else []
cell_copy = mol.cell if hasattr(mol, 'cell') else None
rwmol = Chem.RWMol(mol)
rwmol.AddBond(idx1, idx2, order=order)
mol = rwmol.GetMol()
setattr(mol, 'angles', angles_copy)
setattr(mol, 'dihedrals', dihedrals_copy)
setattr(mol, 'impropers', impropers_copy)
if cell_copy is not None: setattr(mol, 'cell', cell_copy)
return mol
def remove_bond(mol, idx1, idx2):
"""
utils.remove_bond
Remove a specific bond in RDkit Mol object
Args:
mol: RDkit Mol object
idx1, idx2: Atom index removing a specific bond (int)
Returns:
RDkit Mol object
"""
# Copy the extended attributes
angles_copy = mol.angles if hasattr(mol, 'angles') else []
dihedrals_copy = mol.dihedrals if hasattr(mol, 'dihedrals') else []
impropers_copy = mol.impropers if hasattr(mol, 'impropers') else []
cell_copy = mol.cell if hasattr(mol, 'cell') else None
rwmol = Chem.RWMol(mol)
rwmol.RemoveBond(idx1, idx2)
mol = rwmol.GetMol()
setattr(mol, 'angles', angles_copy)
setattr(mol, 'dihedrals', dihedrals_copy)
setattr(mol, 'impropers', impropers_copy)
if cell_copy is not None: setattr(mol, 'cell', cell_copy)
return mol
def add_angle(mol, a, b, c, ff=None):
"""
utils.add_angle
Add a new angle in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index adding a new angle (int)
Returns:
boolean
"""
if not hasattr(mol, 'angles'):
setattr(mol, 'angles', [])
mol.angles.append(
Angle(
a=a,
b=b,
c=c,
ff=ff
)
)
return True
def remove_angle(mol, a, b, c):
"""
utils.remove_angle
Remove a specific angle in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific angle (int)
Returns:
boolean
"""
if not hasattr(mol, 'angles'):
return False
for i, angle in enumerate(mol.angles):
if ((angle.a == a and angle.b == b and angle.c == c) or
(angle.c == a and angle.b == b and angle.a == c)):
del mol.angles[i]
break
return True
def add_dihedral(mol, a, b, c, d, ff=None):
"""
utils.add_dihedral
Add a new dihedral in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c, d: Atom index adding a new dihedral (int)
Returns:
boolean
"""
if not hasattr(mol, 'dihedrals'):
setattr(mol, 'dihedrals', [])
mol.dihedrals.append(
Dihedral(
a=a,
b=b,
c=c,
d=d,
ff=ff
)
)
return True
def remove_dihedral(mol, a, b, c, d):
"""
utils.remove_dihedral
Remove a specific dihedral in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific dihedral (int)
Returns:
boolean
"""
if not hasattr(mol, 'dihedrals'):
return False
for i, dihedral in enumerate(mol.dihedrals):
if ((dihedral.a == a and dihedral.b == b and dihedral.c == c and dihedral.d == d) or
(dihedral.d == a and dihedral.c == b and dihedral.b == c and dihedral.a == d)):
del mol.dihedrals[i]
break
return True
def add_improper(mol, a, b, c, d, ff=None):
"""
utils.add_improper
Add a new imploper in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c, d: Atom index adding a new imploper (int)
Returns:
boolean
"""
if not hasattr(mol, 'impropers'):
setattr(mol, 'impropers', [])
mol.impropers.append(
Improper(
a=a,
b=b,
c=c,
d=d,
ff=ff
)
)
return True
def remove_improper(mol, a, b, c, d):
"""
utils.remove_improper
Remove a specific improper in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific improper (int)
Returns:
boolean
"""
if not hasattr(mol, 'impropers'):
return False
match = False
for i, improper in enumerate(mol.impropers):
if improper.a == a:
for perm in permutations([b, c, d], 3):
if improper.b == perm[0] and improper.c == perm[1] and improper.d == perm[2]:
del mol.impropers[i]
match = True
break
if match: break
return True
def MolToPDBBlock(mol, confId=0):
"""
utils.MolToPDBBlock
Convert RDKit Mol object to PDB block
Args:
mol: RDkit Mol object
Optional args:
confId: Target conformer ID (int)
Returns:
PDB block (str, array)
"""
coord = mol.GetConformer(confId).GetPositions()
PDBBlock = ['TITLE pdb written using RadonPy']
conect = []
serial = 0
ter = 0
chainid_pre = 1
chainid_pdb_pre = ''
for i, atom in enumerate(mol.GetAtoms()):
serial += 1
resinfo = atom.GetPDBResidueInfo()
if resinfo is None: return None
chainid_pdb = resinfo.GetChainId()
chainid = atom.GetIntProp('mol_id')
if chainid != chainid_pre:
if chainid_pdb_pre:
PDBBlock.append('TER %5i %3s %1s%4i%1s' % (serial, resname, chainid_pdb_pre, resnum, icode))
else:
PDBBlock.append('TER %5i %3s %1s%4i%1s' % (serial, resname, '*', resnum, icode))
ter += 1
serial += 1
record = 'HETATM' if resinfo.GetIsHeteroAtom() else 'ATOM '
name = atom.GetProp('ff_type') if atom.HasProp('ff_type') else atom.GetSymbol()
altLoc = resinfo.GetAltLoc()
resname = resinfo.GetResidueName()
resnum = resinfo.GetResidueNumber()
icode = resinfo.GetInsertionCode()
x = coord[i][0]
y = coord[i][1]
z = coord[i][2]
occ = resinfo.GetOccupancy() if resinfo.GetOccupancy() else 1.0
tempf = resinfo.GetTempFactor() if resinfo.GetTempFactor() else 0.0
if chainid_pdb:
line = '%-6s%5i %4s%1s%3s %1s%4i%1s %8.3f%8.3f%8.3f%6.2f%6.2f %2s' % (
record, serial, name, altLoc, resname, chainid_pdb, resnum, icode, x, y, z, occ, tempf, atom.GetSymbol())
else:
line = '%-6s%5i %4s%1s%3s %1s%4i%1s %8.3f%8.3f%8.3f%6.2f%6.2f %2s' % (
record, serial, name, altLoc, resname, '*', resnum, icode, x, y, z, occ, tempf, atom.GetSymbol())
PDBBlock.append(line)
chainid_pre = chainid
chainid_pdb_pre = chainid_pdb
if len(atom.GetNeighbors()) > 0:
flag = False
conect_line = 'CONECT%5i' % (serial)
for na in atom.GetNeighbors():
if atom.GetIdx() < na.GetIdx():
conect_line += '%5i' % (na.GetIdx()+1+ter)
flag = True
if flag:
conect.append(conect_line)
PDBBlock.append('TER %5i %3s %1s%4i%1s' % (serial+1, resname, chainid_pre, resnum, icode))
PDBBlock.extend(conect)
PDBBlock.append('END')
return PDBBlock
def MolToPDBFile(mol, filename, confId=0):
"""
utils.MolToPDBFile
Convert RDKit Mol object to PDB file
Args:
mol: RDkit Mol object
filename: Output pdb filename (str)
Optional args:
confId: Target conformer ID (int)
Returns:
Success or fail (boolean)
"""
mol = set_mol_id(mol)
PDBBlock = MolToPDBBlock(mol, confId=confId)
if PDBBlock is None: return False
with open(filename, 'w') as fh:
fh.write('\n'.join(PDBBlock)+'\n')
fh.flush()
if hasattr(os, 'fdatasync'):
os.fdatasync(fh.fileno())
else:
os.fsync(fh.fileno())
return True
def StructureFromXYZFile(filename):
with open(filename, 'r') as fh:
lines = [s.strip() for s in fh.readlines()]
strucs = []
struc = []
t_flag = False
n_flag = False
n_atom = 0
c_atom = 0
for line in lines:
if not n_flag:
if line.isdecimal():
n_atom = line
n_flag = True
elif not t_flag:
t_flag = True
continue
else:
c_atom += 1
element, x, y, z = line.split()
struc.append([element, x, y, z])
if c_atom >= n_atom:
strucs.append(struc)
t_flag = False
n_flag = False
n_atom = 0
c_atom = 0
return strucs
def MolToExXYZBlock(mol, confId=0):
XYZBlock = Chem.MolToXYZBlock(mol, confId=confId)
XYZBlock = XYZBlock.split('\n')
if mol.GetConformer(confId).HasProp('cell_xhi'):
conf = mol.GetConformer(confId)
cell_line = 'Lattice=\"%.4f 0.0 0.0 0.0 %.4f 0.0 0.0 0.0 %.4f\"' % (
conf.GetDoubleProp('cell_dx'), conf.GetDoubleProp('cell_dy'), conf.GetDoubleProp('cell_dz'))
XYZBlock[1] = cell_line
elif hasattr(mol, 'cell'):
cell_line = 'Lattice=\"%.4f 0.0 0.0 0.0 %.4f 0.0 0.0 0.0 %.4f\"' % (mol.cell.dx, mol.cell.dy, mol.cell.dz)
XYZBlock[1] = cell_line
return XYZBlock
def MolToExXYZFile(mol, filename, confId=0):
XYZBlock = MolToExXYZBlock(mol, confId=confId)
if XYZBlock is None: return False
with open(filename, 'w') as fh:
fh.write('\n'.join(XYZBlock)+'\n')
fh.flush()
if hasattr(os, 'fdatasync'):
os.fdatasync(fh.fileno())
else:
os.fsync(fh.fileno())
return True
def MolToJSON(mol, file, useRDKitExtensions=False):
json_dict = MolToJSON_dict(mol, useRDKitExtensions=useRDKitExtensions)
with open(file, mode='w') as f:
json.dump(json_dict, f, indent=2)
def MolToJSON_dict(mol, useRDKitExtensions=False):
Chem.SanitizeMol(mol)
if hasattr(Chem.rdMolInterchange, 'JSONWriteParameters'):
params = Chem.rdMolInterchange.JSONWriteParameters()
params.useRDKitExtensions = useRDKitExtensions
json_str = Chem.rdMolInterchange.MolToJSON(mol, params=params)
else:
json_str = Chem.rdMolInterchange.MolToJSON(mol)
json_dict = json.loads(json_str)
radonpy_ext = {
'name': 'radonpy_extention',
"formatVersion": 1,
'lib_version': __version__,
}
atom_prop = []
for a in mol.GetAtoms():
atom_data = {}
# FF on atoms
if a.HasProp('ff_type'):
atom_data['ff_type'] = a.GetProp('ff_type')
if a.HasProp('ff_epsilon'):
atom_data['ff_epsilon'] = a.GetDoubleProp('ff_epsilon')
if a.HasProp('ff_sigma'):
atom_data['ff_sigma'] = a.GetDoubleProp('ff_sigma')
# charge
if a.HasProp('AtomicCharge'):
atom_data['AtomicCharge'] = a.GetDoubleProp('AtomicCharge')
if a.HasProp('RESP'):
atom_data['RESP'] = a.GetDoubleProp('RESP')
if a.HasProp('ESP'):
atom_data['ESP'] = a.GetDoubleProp('ESP')
if a.HasProp('Mulliken'):
atom_data['Mulliken'] = a.GetDoubleProp('Mulliken')
if a.HasProp('Lowdin'):
atom_data['Lowdin'] = a.GetDoubleProp('Lowdin')
if a.HasProp('_GasteigerCharge'):
atom_data['_GasteigerCharge'] = a.GetProp('_GasteigerCharge')
# velocity
if a.HasProp('vx'):
atom_data['vx'] = a.GetDoubleProp('vx')
atom_data['vy'] = a.GetDoubleProp('vy')
atom_data['vz'] = a.GetDoubleProp('vz')
# others
atom_data['isotope'] = a.GetIsotope()
if a.HasProp('mol_id'):
atom_data['mol_id'] = a.GetIntProp('mol_id')
# PDB
resinfo = a.GetPDBResidueInfo()
if resinfo is not None:
atom_data['ResidueName'] = resinfo.GetResidueName()
atom_data['ResidueNumber'] = resinfo.GetResidueNumber()
atom_prop.append(atom_data)
radonpy_ext['atoms'] = atom_prop
bond_prop = []
for b in mol.GetBonds():
bond_data = {}
# FF on bonds
if b.HasProp('ff_type'):
bond_data['ff_type'] = b.GetProp('ff_type')
if b.HasProp('ff_k'):
bond_data['ff_k'] = b.GetDoubleProp('ff_k')
if b.HasProp('ff_r0'):
bond_data['ff_r0'] = b.GetDoubleProp('ff_r0')
bond_prop.append(bond_data)
radonpy_ext['bonds'] = bond_prop
# angle
if hasattr(mol, 'angles'):
# if len(mol.angles) > 0 and hasattr(mol.angles[list(mol.angles.keys())[0]], 'to_dict'):
angle_prop = [ang.to_dict() for ang in mol.angles]
radonpy_ext['angles'] = angle_prop
# else:
# angle_prop = []
# for key, ang in mol.angles.items():
# dic = {
# 'a': ang.a,
# 'b': ang.b,
# 'c': ang.c,
# 'ff': {
# 'ff_type': ang.ff.type,
# 'k': ang.ff.k,
# 'theta0': ang.ff.theta0,
# }
# }
# angle_prop.append(dic)
else:
angle_prop = []
# dihedral
if hasattr(mol, 'dihedrals'):
# if len(mol.dihedrals) > 0 and hasattr(mol.dihedrals[list(mol.dihedrals.keys())[0]], 'to_dict'):
dihedral_prop = [dih.to_dict() for dih in mol.dihedrals]
radonpy_ext['dihedrals'] = dihedral_prop
# else:
# dihedral_prop = []
# for key, dih in mol.dihedrals.items():
# dic = {
# 'a': dih.a,
# 'b': dih.b,
# 'c': dih.c,
# 'd': dih.d,
# 'ff': {
# 'ff_type': dih.ff.type,
# 'k': dih.ff.k,
# 'd0': dih.ff.d0,
# 'm': dih.ff.m,
# 'n': dih.ff.n,
# }
# }
# dihedral_prop.append(dic)
else:
dihedral_prop = []
# improper
if hasattr(mol, 'impropers'):
# if len(mol.impropers) > 0 and hasattr(mol.impropers[list(mol.impropers.keys())[0]], 'to_dict'):
improper_prop = [imp.to_dict() for imp in mol.impropers]
radonpy_ext['impropers'] = improper_prop
# else:
# improper_prop = []
# for key, imp in mol.impropers.items():
# dic = {
# 'a': imp.a,
# 'b': imp.b,
# 'c': imp.c,
# 'd': imp.d,
# 'ff': {
# 'ff_type': imp.ff.type,
# 'k': imp.ff.k,
# 'd0': imp.ff.d0,
# 'n': imp.ff.n,
# }
# }
# improper_prop.append(dic)
else:
improper_prop = []
# cell
if hasattr(mol, 'cell'):
# if hasattr(mol.cell, 'to_dict'):
cell_prop = mol.cell.to_dict()
radonpy_ext['cell'] = cell_prop
# else:
# cell_prop = {
# 'xhi': mol.cell.xhi,
# 'xlo': mol.cell.xlo,
# 'yhi': mol.cell.yhi,
# 'ylo': mol.cell.ylo,
# 'zhi': mol.cell.zhi,
# 'zlo': mol.cell.zlo,
# }
json_dict['molecules'][0]['extensions'].append(radonpy_ext)
return json_dict
def JSONToMol(file):
with open(file, mode='r') as f:
json_dict = json.load(f)
radonpy_ext = None
for ext in json_dict['molecules'][0]['extensions']:
if 'name' in ext and ext['name'] == 'radonpy_extention':
radonpy_ext = ext
if radonpy_ext is None:
radon_print('RadonPy extention data was not found in JSON file.', level=3)
mol = Chem.rdMolInterchange.JSONToMols(json.dumps(json_dict))[0]
Chem.SanitizeMol(mol)
for i, a in enumerate(mol.GetAtoms()):
atom_data = radonpy_ext['atoms'][i]
# FF on atoms
if 'ff_type' in atom_data:
a.SetProp('ff_type', str(atom_data['ff_type']))
if 'ff_epsilon' in atom_data:
a.SetDoubleProp('ff_epsilon', float(atom_data['ff_epsilon']))
if 'ff_sigma' in atom_data:
a.SetDoubleProp('ff_sigma', float(atom_data['ff_sigma']))
# charge
if 'AtomicCharge' in atom_data:
a.SetDoubleProp('AtomicCharge', float(atom_data['AtomicCharge']))
if 'RESP' in atom_data:
a.SetDoubleProp('RESP', float(atom_data['RESP']))
if 'ESP' in atom_data:
a.SetDoubleProp('ESP', float(atom_data['ESP']))
if 'Mulliken' in atom_data:
a.SetDoubleProp('Mulliken', float(atom_data['Mulliken']))
if 'Lowdin' in atom_data:
a.SetDoubleProp('Lowdin', float(atom_data['Lowdin']))
if '_GasteigerCharge' in atom_data:
a.SetProp('_GasteigerCharge', str(atom_data['_GasteigerCharge']))
# velocity
if 'vx' in atom_data:
a.SetDoubleProp('vx', float(atom_data['vx']))
a.SetDoubleProp('vy', float(atom_data['vy']))
a.SetDoubleProp('vz', float(atom_data['vz']))
# others
a.SetIsotope(int(atom_data['isotope']))
if 'mol_id' in atom_data:
a.SetIntProp('mol_id', int(atom_data['mol_id']))
# PDB
atom_name = str(atom_data['ff_type']) if 'ff_type' in atom_data else a.GetSymbol()
if 'ResidueName' in atom_data and 'ResidueNumber' in atom_data:
a.SetMonomerInfo(
Chem.AtomPDBResidueInfo(
atom_name,
residueName=atom_data['ResidueName'],
residueNumber=atom_data['ResidueNumber'],
isHeteroAtom=False
)
)
for i, b in enumerate(mol.GetBonds()):
bond_data = radonpy_ext['bonds'][i]
# FF on bonds
if 'ff_type' in bond_data:
b.SetProp('ff_type', str(bond_data['ff_type']))
if 'ff_k' in bond_data:
b.SetDoubleProp('ff_k', float(bond_data['ff_k']))
if 'ff_r0' in bond_data:
b.SetDoubleProp('ff_r0', float(bond_data['ff_r0']))
if 'angles' in radonpy_ext:
if hasattr(mol, 'angle_style') and mol.angle_style == 'harmonic':
angle_class = ff_class.GAFF_Angle
else:
angle_class = ff_class.GAFF_Angle
angle_prop = []
for ang in radonpy_ext['angles']:
key = '%i,%i,%i' % (int(ang['a']), int(ang['b']), int(ang['c']))
angle_prop.append(
Angle(
a = int(ang['a']),
b = int(ang['b']),
c = int(ang['c']),
ff = angle_class(**ang['ff'])
)
)
setattr(mol, 'angles', angle_prop)
if 'dihedrals' in radonpy_ext:
if hasattr(mol, 'dihedral_style') and mol.dihedral_style == 'fourier':
dihedral_class = ff_class.GAFF_Dihedral
else:
dihedral_class = ff_class.GAFF_Dihedral
dihedral_prop = []
for dih in radonpy_ext['dihedrals']:
key = '%i,%i,%i,%i' % (int(dih['a']), int(dih['b']), int(dih['c']), int(dih['d']))
dihedral_prop.append(
Dihedral(
a = int(dih['a']),
b = int(dih['b']),
c = int(dih['c']),
d = int(dih['d']),
ff = dihedral_class(**dih['ff'])
)
)
setattr(mol, 'dihedrals', dihedral_prop)
if 'impropers' in radonpy_ext:
if hasattr(mol, 'improper_style') and mol.improper_style == 'cvff':
improper_class = ff_class.GAFF_Improper
else:
improper_class = ff_class.GAFF_Improper
improper_prop = []
for imp in radonpy_ext['impropers']:
key = '%i,%i,%i,%i' % (int(imp['a']), int(imp['b']), int(imp['c']), int(imp['d']))
improper_prop.append(
Improper(
a = int(imp['a']),
b = int(imp['b']),