forked from SofiaBariami/qube_project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnew_align_merge.py
2552 lines (2035 loc) · 101 KB
/
new_align_merge.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
import tempfile as _tempfile
import os as _os
import subprocess as _subprocess
import tempfile as _tempfile
import warnings as _warnings
# Suppress numpy warnings from RDKit import.
_warnings.filterwarnings("ignore", message="numpy.dtype size changed")
_warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# Suppress duplicate to-Python converted warnings.
# Both Sire and RDKit register the same converter.
with _warnings.catch_warnings():
_warnings.filterwarnings("ignore")
from rdkit import Chem as _Chem
from rdkit.Chem import rdFMCS as _rdFMCS
from Sire import Base as _SireBase
from Sire import Maths as _SireMaths
from Sire import Mol as _SireMol
from Sire import Units as _SireUnits
from BioSimSpace._Exceptions import AlignmentError as _AlignmentError
from BioSimSpace._Exceptions import MissingSoftwareError as _MissingSoftwareError
from BioSimSpace._SireWrappers import Molecule as _Molecule
from BioSimSpace import IO as _IO
from BioSimSpace import Units as _Units
from BioSimSpace import _Utils as _Utils
import os
import re
import sys
import argparse
from Sire.Base import *
from datetime import datetime
# Make sure that the OPENMM_PLUGIN_DIR enviroment variable is set correctly.
os.environ["OPENMM_PLUGIN_DIR"] = getLibDir() + "/plugins"
from Sire.IO import *
from Sire.Mol import *
from Sire.CAS import *
from Sire.System import *
from Sire.Move import *
from Sire.MM import *
from Sire.FF import *
from Sire.Units import *
from Sire.Vol import *
from Sire.Maths import *
from Sire.Qt import *
from Sire.ID import *
from Sire.Config import *
from Sire.Analysis import *
from Sire.Tools.DCDFile import *
from Sire.Tools import Parameter, resolveParameters
import Sire.Stream
import time
import numpy as np
#########################################
# Config file parameters #
#########################################
combining_rules = Parameter("combining rules", "geometric",
"""Combining rules to use for the non-bonded interactions.""")
cutoff_type = Parameter("cutoff type", "nocutoff", """The cutoff method to use during the simulation.""")
cutoff_dist = Parameter("cutoff distance", 500 * angstrom,
"""The cutoff distance to use for the non-bonded interactions.""")
use_restraints = Parameter("use restraints", False, """Whether or not to use harmonic restaints on the solute atoms.""")
def createSystem(molecules):
#print("Applying flexibility and zmatrix templates...")
print("Creating the system...")
moleculeNumbers = molecules.molNums()
moleculeList = []
for moleculeNumber in moleculeNumbers:
molecule = molecules.molecule(moleculeNumber)[0].molecule()
moleculeList.append(molecule)
molecules = MoleculeGroup("molecules")
ions = MoleculeGroup("ions")
for molecule in moleculeList:
natoms = molecule.nAtoms()
if natoms == 1:
ions.add(molecule)
else:
molecules.add(molecule)
all = MoleculeGroup("all")
all.add(molecules)
all.add(ions)
# Add these groups to the System
system = System()
system.add(all)
system.add(molecules)
system.add(ions)
return system
def setupForcefields(system, space):
print("Creating force fields... ")
all = system[MGName("all")]
molecules = system[MGName("molecules")]
ions = system[MGName("ions")]
# - first solvent-solvent coulomb/LJ (CLJ) energy
internonbondedff = InterCLJFF("molecules:molecules")
if (cutoff_type.val != "nocutoff"):
internonbondedff.setUseReactionField(True)
internonbondedff.setReactionFieldDielectric(rf_dielectric.val)
internonbondedff.add(molecules)
inter_ions_nonbondedff = InterCLJFF("ions:ions")
if (cutoff_type.val != "nocutoff"):
inter_ions_nonbondedff.setUseReactionField(True)
inter_ions_nonbondedff.setReactionFieldDielectric(rf_dielectric.val)
inter_ions_nonbondedff.add(ions)
inter_ions_molecules_nonbondedff = InterGroupCLJFF("ions:molecules")
if (cutoff_type.val != "nocutoff"):
inter_ions_molecules_nonbondedff.setUseReactionField(True)
inter_ions_molecules_nonbondedff.setReactionFieldDielectric(rf_dielectric.val)
inter_ions_molecules_nonbondedff.add(ions, MGIdx(0))
inter_ions_molecules_nonbondedff.add(molecules, MGIdx(1))
# Now solute bond, angle, dihedral energy
intrabondedff = InternalFF("molecules-intrabonded")
intrabondedff.add(molecules)
# Now solute intramolecular CLJ energy
intranonbondedff = IntraCLJFF("molecules-intranonbonded")
if (cutoff_type.val != "nocutoff"):
intranonbondedff.setUseReactionField(True)
intranonbondedff.setReactionFieldDielectric(rf_dielectric.val)
intranonbondedff.add(molecules)
# solute restraint energy
#
# We restrain atoms based ont he contents of the property "restrainedatoms"
#
restraintff = RestraintFF("restraint")
if use_restraints.val:
molnums = molecules.molecules().molNums()
for molnum in molnums:
mol = molecules.molecule(molnum)[0].molecule()
try:
mol_restrained_atoms = propertyToAtomNumVectorList(mol.property("restrainedatoms"))
except UserWarning as error:
error_type = re.search(r"(Sire\w*::\w*)", str(error)).group(0)
if error_type == "SireBase::missing_property":
continue
else:
raise error
for restrained_line in mol_restrained_atoms:
atnum = restrained_line[0]
restraint_atom = mol.select(atnum)
restraint_coords = restrained_line[1]
restraint_k = restrained_line[2] * kcal_per_mol / (angstrom * angstrom)
restraint = DistanceRestraint.harmonic(restraint_atom, restraint_coords, restraint_k)
restraintff.add(restraint)
# Here is the list of all forcefields
forcefields = [internonbondedff, intrabondedff, intranonbondedff, inter_ions_nonbondedff,
inter_ions_molecules_nonbondedff, restraintff]
for forcefield in forcefields:
system.add(forcefield)
system.setProperty("space", space)
system.setProperty("switchingFunction", CHARMMSwitchingFunction(cutoff_dist.val))
system.setProperty("combiningRules", VariantProperty(combining_rules.val))
total_nrg = internonbondedff.components().total() + \
intranonbondedff.components().total() + intrabondedff.components().total() + \
inter_ions_nonbondedff.components().total() + inter_ions_molecules_nonbondedff.components().total() + \
restraintff.components().total()
e_total = system.totalComponent()
system.setComponent(e_total, total_nrg)
# Add a monitor that calculates the average total energy and average energy
# deltas - we will collect both a mean average and an zwanzig average
system.add("total_energy", MonitorComponent(e_total, Average()))
return system
def vsiteListToProperty(list):
prop = Properties()
i = 0
for entry in list:
for key, value in entry.items():
prop.setProperty("%s(%d)" % (key,i), VariantProperty(value))
i += 1
prop.setProperty("nvirtualsites",VariantProperty(i))
return prop
def readXmlParameters(pdbfile, xmlfile):
# 1) Read a pdb file describing the system to simulate
p = PDB2(pdbfile)
s = p.toSystem()
molecules = s.molecules()
#print (molecules)
with open (pdbfile, "r") as f:
for line in f:
if line.split()[0] == "CRYST1" :
print (line)
pbc_x = float(line.split()[1])
pbc_y = float(line.split()[2])
pbc_z = float(line.split()[3])
space = PeriodicBox(Vector(pbc_x, pbc_y, pbc_z))
break
else:
space = Cartesian()
#print("space:", space)
system = System()
# 2) Now we read the xml file, and store parameters for each molecule
import xml.dom.minidom as minidom
xmldoc = minidom.parse(xmlfile)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: TYPE ~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_type = xmldoc.getElementsByTagName('Type')
dicts_type = []
for items in itemlist_type:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_type.append(d)
dicts_tp = str(dicts_type).split()
#print (dicts_tp)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: ATOM ~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_atom = xmldoc.getElementsByTagName('Atom')
dicts_atom = []
for items in itemlist_atom:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_atom.append(d)
dicts_at = str(dicts_atom).split()
#print (dicts_at)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: BOND ~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_bond = xmldoc.getElementsByTagName('Bond')
dicts_bond = []
for items in itemlist_bond:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_bond.append(d)
dicts_b = str(dicts_bond).split()
#print (dicts_b)
nbond = itemlist_bond.length
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: ANGLE ~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_angle = xmldoc.getElementsByTagName('Angle')
dicts_angle = []
for items in itemlist_angle:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_angle.append(d)
dicts_ang = str(dicts_angle).split()
#print (dicts_angle)
nAngles= itemlist_angle.length
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: PROPER ~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_proper = xmldoc.getElementsByTagName('Proper')
dicts_proper = []
for items in itemlist_proper:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_proper.append(d)
dicts_pr = str(dicts_proper).split()
#print (dicts_pr)
nProper = itemlist_proper.length
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: IMPROPER ~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_improper = xmldoc.getElementsByTagName('Improper')
dicts_improper = []
for items in itemlist_improper:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_improper.append(d)
dicts_impr = str(dicts_improper).split()
#print (dicts_impr)
nImproper = itemlist_improper.length
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: VIRTUAL SITES ~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_VirtualSite = xmldoc.getElementsByTagName('VirtualSite')
dicts_virtualsite = []
for items in itemlist_VirtualSite:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_virtualsite.append(d)
#dicts_vs = str(dicts_virtualsite).split()
#print (dicts_vs)
nVirtualSites = itemlist_VirtualSite.length
v_site_CLJ = []
for i in range(0, int(len(dicts_atom))):
if dicts_atom[i]['type'][0] == 'v':
v_site_CLJ = dicts_atom[i]
dicts_virtualsite.append(v_site_CLJ)
for i in range(0, len(itemlist_VirtualSite)):
dicts_virtualsite[i].update(dicts_virtualsite[i+len(itemlist_VirtualSite)])
dicts_virtualsite[i].update(dicts_virtualsite[i+2*len(itemlist_VirtualSite)])
dict_vs = []
for i in range(0, len(itemlist_VirtualSite)):
dicts_virtualsite[i]
dict_vs.append(dicts_virtualsite[i])
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~ TAG NAME: RESIDUE ~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_residue = xmldoc.getElementsByTagName('Residue')
dicts_residue = []
for items in itemlist_residue:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_residue.append(d)
dicts_res = str(dicts_residue).split()
#print (dicts_res)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~ TAG NAME: NON BONDED FORCE ~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
itemlist_nonbond = xmldoc.getElementsByTagName('NonbondedForce')
dicts_nonb = []
for items in itemlist_nonbond:
d = {}
for a in items.attributes.values():
d[a.name] = a.value
dicts_nonb.append(d)
dicts_nb = str(dicts_nonb).split()
#print (dicts_nb)
nNonBonded = itemlist_nonbond.length
# 3) Now we create an Amberparameters object for each molecule
molnums = molecules.molNums()
newmolecules = Molecules()
for molnum in molnums:
mol = molecules.at(molnum)
#print (mol)
# Add potential virtual site parameters
if len(dicts_virtualsite) > 0:
mol = mol.edit().setProperty("virtual-sites", vsiteListToProperty(dict_vs)).commit()
# We populate the Amberparameters object with a list of bond, angle, dihedrals
# We look up parameters from the contents of the xml file
# We also have to set the atomic parameters (q, sigma, epsilon)
editmol = mol.edit()
mol_params = AmberParameters(editmol) #SireMol::AmberParameters()
atoms = editmol.atoms()
# We update atom parameters see setAtomParameters in SireIO/amber.cpp l2122
natoms = editmol.nAtoms()
#print("number of atoms is %s" %natoms)
#natoms don't include the virtual sites!
# Loop over each molecule in the molecules object
opls=[]
for i in range (0, int(len(dicts_atom)/2)):
opl={}
opl = dicts_atom[i]['type']
opls.append(opl)
name=[]
for i in range (0, int(len(dicts_atom)/2)):
nm={}
nm = dicts_atom[i]['name']
name.append(nm)
two=[]
#print(len(name))
for i in range(0, len(name)):
t=(opls[i],name[i])
two.append(t)
import numpy as np
atom_sorted = []
for j in range(0, len(two)):
for i in range(int(len(dicts_atom)/2), len(dicts_atom)):
if dicts_atom[i]['type'] == two[j][0]:
dic_a = {}
dic_a = dicts_atom[i]
atom_sorted.append(dic_a)
type_sorted = []
for j in range(0, len(two)):
for i in range(0, int(len(dicts_type))):
if dicts_type[i]['name'] == two[j][0]:
dic_t = {}
dic_t = dicts_type[i]
type_sorted.append(dic_t)
print(" ")
print("There are ",natoms," atoms in this molecule. ")
print("*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*")
for atom in atoms:
editatom = editmol.atom(atom.index())
i = int(str(atom.number()).split('(')[1].replace(")" , " "))
editatom.setProperty("charge", float(atom_sorted[i-1]['charge']) * mod_electron)
editatom.setProperty("mass", float(type_sorted[i-1]['mass']) * g_per_mol)
editatom.setProperty("LJ", LJParameter( float(atom_sorted[i-1]['sigma'])*10 * angstrom , float(atom_sorted[i-1]['epsilon'])/4.184 * kcal_per_mol))
editatom.setProperty("ambertype", dicts_atom[i-1]['type'])
editmol = editatom.molecule()
# Now we create a connectivity see setConnectivity in SireIO/amber.cpp l2144
# XML data tells us how atoms are bonded in the molecule (Bond 'from' and 'to')
if natoms > 1:
print("Set up connectivity")
con = []
for i in range(0,int(nbond/2)):
if natoms > 1:
connect_prop= {}
connect_prop = dicts_bond[i]['from'], dicts_bond[i]['to']
con.append(connect_prop)
conn = Connectivity(editmol.info()).edit()
for j in range(0,len(con)):
conn.connect(atoms[int(con[j][0]) ].index(), atoms[int(con[j][1]) ].index())
editmol.setProperty("connectivity", conn.commit()).commit()
mol = editmol.setProperty("connectivity", conn.commit()).commit()
system.update(mol)
# Now we add bond parameters to the Sire molecule. We also update amberparameters see SireIO/amber.cpp l2154
internalff = InternalFF()
bondfuncs = TwoAtomFunctions(mol)
r = internalff.symbols().bond().r()
for j in range(0,len(con)):
bondfuncs.set(atoms[int(con[j][0]) ].index(), atoms[int(con[j][1]) ].index(), float(dicts_bond[j+len(con)]['k'])/(2*100*4.184)* (float(dicts_bond[j+len(con)]['length'])*10 - r) **2 )
bond_id = BondID(atoms[int(con[j][0])].index(), atoms[int(con[j][1])].index())
mol_params.add(bond_id, float(dicts_bond[j+len(con)]['k'])/(2*100*4.184), float(dicts_bond[j+len(con)]['length'])*10 )
editmol.setProperty("bonds", bondfuncs).commit()
molecule = editmol.commit()
mol_params.getAllBonds()
editmol.setProperty("amberparameters", mol_params).commit() # Weird, should work - investigate ?
molecule = editmol.commit()
# Now we add angle parameters to the Sire molecule. We also update amberparameters see SireIO/amber.cpp L2172
if natoms > 2:
print("Set up angles")
anglefuncs = ThreeAtomFunctions(mol)
at1 = []
for i in range(0, nAngles):
a1 = {}
to_str1 = str(re.findall(r"\d+",str(dicts_angle[i]['class1'])))
if dicts_atom[i]['type'][0] == 'o': #if opls_
a1 = int(to_str1.replace("[","").replace("]","").replace("'","") )-800
else:#if QUBE_
a1 = int(to_str1.replace("[","").replace("]","").replace("'","") )
at1.append(a1)
at2 = []
for i in range(0, nAngles):
a2 = {}
to_str2 = str(re.findall(r"\d+",str(dicts_angle[i]['class2'])))
if dicts_atom[i]['type'][0] == 'o': #if opls_
a2 = int(to_str2.replace("[","").replace("]","").replace("'","") )-800
else: #if QUBE_
a2 = int(to_str2.replace("[","").replace("]","").replace("'","") )
at2.append(a2)
at3 = []
for i in range(0, nAngles):
a3 = {}
to_str3 = str(re.findall(r"\d+",str(dicts_angle[i]['class3'])))
if dicts_atom[i]['type'][0] == 'o': #if opls_
a3 = int(to_str3.replace("[","").replace("]","").replace("'","") )-800
else: #if QUBE_
a3 = int(to_str3.replace("[","").replace("]","").replace("'","") )
at3.append(a3)
theta = internalff.symbols().angle().theta()
for j in range(0,nAngles):
anglefuncs.set( atoms[at1[j]].index(), atoms[at2[j]].index(), atoms[at3[j]].index(), float(dicts_angle[j]['k'])/(2*4.184) * ( (float(dicts_angle[j]['angle']) - theta )**2 ))
angle_id = AngleID( atoms[int(at1[j])].index(), atoms[int(at2[j])].index(), atoms[int(at3[j])].index())
mol_params.add(angle_id, float(dicts_angle[j]['k'])/(2*4.184), float(dicts_angle[j]['angle']) )
# Now we add dihedral parameters to the Sire molecule. We also update amberparameters see SireIO/amber.cpp L2190
if natoms > 3:
print("Set up dihedrals")
di1 = []
for i in range(0, nProper):
d1 = {}
to_str1 = str(re.findall(r"\d+",str(dicts_proper[i]['class1'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d1 = int(to_str1.replace("[","").replace("]","").replace("'","") )-800
else: #if QUBE_
d1 = int(to_str1.replace("[","").replace("]","").replace("'","") )
di1.append(d1)
di2 = []
for i in range(0, nProper):
d2 = {}
to_str2 = str(re.findall(r"\d+",str(dicts_proper[i]['class2'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d2 = int(to_str2.replace("[","").replace("]","").replace("'","") )-800
else: #if QUBE_
d2 = int(to_str2.replace("[","").replace("]","").replace("'","") )
di2.append(d2)
di3 = []
for i in range(0, nProper):
d3 = {}
to_str3 = str(re.findall(r"\d+",str(dicts_proper[i]['class3'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d3 = int(to_str3.replace("[","").replace("]","").replace("'","") )-800
else: #if QUBE_
d3 = int(to_str3.replace("[","").replace("]","").replace("'","") )
di3.append(d3)
di4 = []
for i in range(0, nProper):
d4 = {}
to_str4 = str(re.findall(r"\d+",str(dicts_proper[i]['class4'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d4 = int(to_str4.replace("[","").replace("]","").replace("'","") )-800
else: #if QUBE_
d4 = int(to_str4.replace("[","").replace("]","").replace("'","") )
di4.append(d4)
dihedralfuncs = FourAtomFunctions(mol)
phi = internalff.symbols().dihedral().phi()
for i in range(0,nProper):
if atoms[int(di1[i])].index() != atoms[int(di4[i])].index():
dihedral_id = DihedralID( atoms[int(di1[i])].index(), atoms[int(di2[i])].index(), atoms[int(di3[i])].index(), atoms[int(di4[i])].index())
dih1= float(dicts_proper[i]['k1'])/4.184*(1+Cos(int(dicts_proper[i]['periodicity1'])* phi- float(dicts_proper[i]['phase1'])))
dih2= float(dicts_proper[i]['k2'])/4.184*(1+Cos(int(dicts_proper[i]['periodicity2'])* phi- float(dicts_proper[i]['phase2'])))
dih3= float(dicts_proper[i]['k3'])/4.184*(1+Cos(int(dicts_proper[i]['periodicity3'])* phi- float(dicts_proper[i]['phase3'])))
dih4= float(dicts_proper[i]['k4'])/4.184*(1+Cos(int(dicts_proper[i]['periodicity4'])* phi- float(dicts_proper[i]['phase4'])))
dih_fun = dih1 + dih2 +dih3 +dih4
dihedralfuncs.set(dihedral_id, dih_fun)
for t in range(1,5):
mol_params.add(dihedral_id, float(dicts_proper[i]['k%s'%t])/4.184, int(dicts_proper[i]['periodicity%s'%t]), float(dicts_proper[i]['phase%s'%t]) )
print("Set up impropers")
di_im1 = []
for i in range(0, nImproper):
d1 = {}
to_str1 = str(re.findall(r"\d+",str(dicts_improper[i]['class1'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d1 = int(to_str1.replace("[","").replace("]","").replace("'","") )-800
else:
d1 = int(to_str1.replace("[","").replace("]","").replace("'","") )
di_im1.append(d1)
di_im2 = []
for i in range(0, nImproper):
d2 = {}
to_str2 = str(re.findall(r"\d+",str(dicts_improper[i]['class2'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d2 = int(to_str2.replace("[","").replace("]","").replace("'","") )-800
else:
d2 = int(to_str2.replace("[","").replace("]","").replace("'","") )
di_im2.append(d2)
di_im3 = []
for i in range(0, nImproper):
d3 = {}
to_str3 = str(re.findall(r"\d+",str(dicts_improper[i]['class3'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d3 = int(to_str3.replace("[","").replace("]","").replace("'","") )-800
else:
d3 = int(to_str3.replace("[","").replace("]","").replace("'","") )
di_im3.append(d3)
di_im4 = []
for i in range(0, nImproper):
d4 = {}
to_str4 = str(re.findall(r"\d+",str(dicts_improper[i]['class4'])))
if dicts_atom[0]['type'][0] == 'o':#if opls_
d4 = int(to_str4.replace("[","").replace("]","").replace("'","") )-800
else:
d4 = int(to_str4.replace("[","").replace("]","").replace("'","") )
di_im4.append(d4)
improperfuncs = FourAtomFunctions(mol)
phi_im = internalff.symbols().improper().phi()
for i in range(0,nImproper):
improper_id = ImproperID( atoms[int(di_im2[i])].index(), atoms[int(di_im3[i])].index(), atoms[int(di_im1[i])].index(), atoms[int(di_im4[i])].index())
imp1= float(dicts_improper[i]['k1'])*(1/4.184)*(1+Cos(int(dicts_improper[i]['periodicity1'])* phi_im - float(dicts_improper[i]['phase1'])))
imp2= float(dicts_improper[i]['k2'])*(1/4.184)*(1+Cos(int(dicts_improper[i]['periodicity2'])* phi_im - float(dicts_improper[i]['phase2'])))
imp3= float(dicts_improper[i]['k3'])*(1/4.184)*(1+Cos(int(dicts_improper[i]['periodicity3'])* phi_im - float(dicts_improper[i]['phase3'])))
imp4= float(dicts_improper[i]['k4'])*(1/4.184)*(1+Cos(int(dicts_improper[i]['periodicity4'])* phi_im - float(dicts_improper[i]['phase4'])))
imp_fun = imp1 + imp2 +imp3 +imp4
improperfuncs.set(improper_id, imp_fun)
#print(improperfuncs.potentials())
for t in range(1,5):
mol_params.add(improper_id, float(dicts_improper[i]['k%s'%t])*(1/4.184), int(dicts_improper[i]['periodicity%s'%t]), float(dicts_improper[i]['phase%s'%t]) )
mol = editmol.setProperty("bond", bondfuncs).commit()
mol = editmol.setProperty("angle" , anglefuncs).commit()
mol = editmol.setProperty("dihedral" , dihedralfuncs).commit()
mol = editmol.setProperty("improper" , improperfuncs).commit()
system.update(mol)
# Now we work out non bonded pairs see SireIO/amber.cpp L2213
print("Set up nbpairs")
print("*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*")
## Define the bonded pairs in a list that is called are12
#print("Now calculating 1-2 intercactions")
are12 = []
for i in range(0, natoms):
for j in range (0, natoms):
if conn.areBonded(atoms[i].index(), atoms[j].index()) == True:
#ij = {}
ij= (i,j)
are12.append(ij)
are12_bckup = are12[:]
#print("Now calculating 1-3 intercactions")
are13 = []
for i in range(0, natoms):
for j in range (0, natoms):
if conn.areAngled(atoms[i].index(), atoms[j].index()) == True:
ij = {}
ij= (i,j)
are13.append(ij)
are13_bckup = are13[:]
# print("Now calculating 1-4 intercactions")
are14 = []
for i in range(0, natoms):
for j in range (0, natoms):
if conn.areDihedraled(atoms[i].index(), atoms[j].index()) == True and conn.areAngled(atoms[i].index(), atoms[j].index()) == False:
ij = {}
ij= (i,j)
are14.append(ij)
are14_bckup = are14[:]
# print("Now calculating the non-bonded intercactions")
bonded_pairs_list = are12_bckup + are13_bckup + are14_bckup
nb_pair_list =[]
for i in range(0, natoms):
#print("i=",i)
for j in range (0, natoms):
if i != j and (i,j) not in bonded_pairs_list:
nb_pair_list.append((i,j))
are_nb_bckup = nb_pair_list[:]
nbpairs = CLJNBPairs(editmol.info(), CLJScaleFactor(0,0))
#print("Now setting 1-2 intercactions")
for i in range(0, len(are12)):
scale_factor1 = 0
scale_factor2 = 0
nbpairs.set(atoms.index( int(are12[i][0])), atoms.index(int(are12[i][1])), CLJScaleFactor(scale_factor1,scale_factor2))
#print("Now setting 1-3 intercactions")
for i in range(0, len(are13)):
scale_factor1 = 0
scale_factor2 = 0
nbpairs.set(atoms.index( int(are13[i][0])), atoms.index(int(are13[i][1])), CLJScaleFactor(scale_factor1,scale_factor2))
# print("Now setting 1-4 intercactions")
for i in range(0, len(are14)):
scale_factor1 = 1/2
scale_factor2 = 1/2
nbpairs.set(atoms.index( int(are14[i][0])), atoms.index(int(are14[i][1])), CLJScaleFactor(scale_factor1,scale_factor2))
mol_params.add14Pair(BondID(atoms.index( int(are14[i][0])), atoms.index( int(are14[i][1]))),scale_factor1 , scale_factor2)
# print("Now setting non-bonded intercactions")
#print("*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*")
for i in range(0, len(nb_pair_list)):
scale_factor1 = 1
scale_factor2 = 1
nbpairs.set(atoms.index( int(nb_pair_list[i][0])), atoms.index(int(nb_pair_list[i][1])), CLJScaleFactor(scale_factor1,scale_factor2))
# print("~~~~~~~~~~~~~~~~~~`")
mol = editmol.setProperty("intrascale" , nbpairs).commit()
system.update(mol)
#print("Setup name of qube FF")
mol = mol.edit().setProperty("forcefield", ffToProperty("qube")).commit()
system.update(mol)
molecule = editmol.commit()
newmolecules.add(molecule)
return (newmolecules, space)
def ffToProperty(string):
prop = Properties()
prop.setProperty("forcefield",VariantProperty("qube"))
return prop
xmlfile = "G1_4a.xml"
pdbfile = "G1_4a.pdb"
(molecules, space) = readXmlParameters(pdbfile, xmlfile)
xmlfile1 = "G1_4f.xml"
pdbfile1 = "G1_4f.pdb"
(molecules1, space1) = readXmlParameters(pdbfile1, xmlfile1)
mol1 = molecules.molecule(MolNum(1))
mol2 = molecules1.molecule(MolNum(2))
prematch = {}
import BioSimSpace as BSS
bss_mol1 = BSS.IO.readMolecules(pdbfile)
bss_mol2 = BSS.IO.readMolecules(pdbfile1)
def _score_rdkit_mappings(molecule0, molecule1, rdkit_molecule0, rdkit_molecule1,
mcs_smarts, prematch, scoring_function, property_map0, property_map1):
"""Internal function to score atom mappings based on the root mean squared
displacement (RMSD) between mapped atoms in two molecules. Optionally,
molecule0 can first be aligned to molecule1 based on the mapping prior
to computing the RMSD. The function returns the mappings sorted based
on their score from best to worst, along with a list containing the
scores for each mapping.
Parameters
----------
molecule0 : Sire.Molecule.Molecule
The first molecule (Sire representation).
molecule0 : Sire.Molecule.Molecule
The second molecule (Sire representation).
rdkit_mol0 : RDKit.Chem.Mol
The first molecule (RDKit representation).
rdkit_mol1 : RDKit.Chem.Mol
The second molecule (RDKit representation).
mcs_smarts : RDKit.Chem.MolFromSmarts
The smarts string representing the maximum common substructure of
the two molecules.
prematch : dict
A dictionary of atom mappings that must be included in the match.
scoring_function : str
The RMSD scoring function.
property_map0 : dict
A dictionary that maps "properties" in molecule0 to their user
defined values. This allows the user to refer to properties
with their own naming scheme, e.g. { "charge" : "my-charge" }
property_map1 : dict
A dictionary that maps "properties" in molecule1 to their user
defined values.
Returns
-------
mapping, scores : ([dict], list)
The ranked mappings and corresponding scores.
"""
# Adapted from FESetup: https://github.com/CCPBioSim/fesetup
# Make sure to re-map the coordinates property in both molecules, otherwise
# the move and align functions from Sire will not work.
prop0 = property_map0.get("coordinates", "coordinates")
prop1 = property_map1.get("coordinates", "coordinates")
if prop0 != "coordinates":
molecule0 = molecule0.edit().setProperty("coordinates", molecule0.property(prop0)).commit()
if prop1 != "coordinates":
molecule1 = molecule1.edit().setProperty("coordinates", molecule1.property(prop1)).commit()
# Get the set of matching substructures in each molecule. For some reason
# setting uniquify to True removes valid matches, in some cases even the
# best match! As such, we set uniquify to False and account ignore duplicate
# mappings in the code below.
matches0 = rdkit_molecule0.GetSubstructMatches(mcs_smarts, uniquify=False, maxMatches=1000, useChirality=False)
matches1 = rdkit_molecule1.GetSubstructMatches(mcs_smarts, uniquify=False, maxMatches=1000, useChirality=False)
# Swap the order of the matches.
if len(matches0) < len(matches1):
matches0, matches1 = matches1, matches0
is_swapped = True
else:
is_swapped = False
# Initialise a list to hold the mappings.
mappings = []
# Initialise a list of to hold the score for each mapping.
scores = []
# Loop over all matches from mol0.
for x in range(len(matches0)):
match0 = matches0[x]
# Loop over all matches from mol1.
for y in range(len(matches1)):
match1 = matches1[y]
# Initialise the mapping for this match.
mapping = {}
sire_mapping = {}
# Loop over all atoms in the match.
for i, idx0 in enumerate(match0):
idx1 = match1[i]
# Add to the mapping.
if is_swapped:
mapping[idx1] = idx0
sire_mapping[_SireMol.AtomIdx(idx1)] = _SireMol.AtomIdx(idx0)
else:
mapping[idx0] = idx1
sire_mapping[_SireMol.AtomIdx(idx0)] = _SireMol.AtomIdx(idx1)
# This is a new mapping:
if not mapping in mappings:
# Check that the mapping contains the pre-match.
is_valid = True
for idx0, idx1 in prematch.items():
# Pre-match isn't found, return to top of loop.
if idx0 not in mapping or mapping[idx0] != idx1:
is_valid = False
break
if is_valid:
# Rigidly align molecule0 to molecule1 based on the mapping.
if scoring_function == "RMSDALIGN":
try:
molecule0 = molecule0.move().align(molecule1, _SireMol.AtomResultMatcher(sire_mapping)).molecule()
except Exception as e:
msg = "Failed to align molecules when scoring based on mapping: %r" % mapping
if _isVerbose():
raise _AlignmentError(msg) from e
else:
raise _AlignmentError(msg) from None
# Flexibly align molecule0 to molecule1 based on the mapping.
elif scoring_function == "RMSDFLEXALIGN":
molecule0 = flexAlign(_Molecule(molecule0), _Molecule(molecule1), mapping,
property_map0=property_map0, property_map1=property_map1)._sire_object
# Append the mapping to the list.
mappings.append(mapping)
# We now compute the RMSD between the coordinates of the matched atoms
# in molecule0 and molecule1.
# Initialise lists to hold the coordinates.
c0 = []
c1 = []
# Loop over each atom index in the map.
for idx0, idx1 in sire_mapping.items():
# Append the coordinates of the matched atom in molecule0.
c0.append(molecule0.atom(idx0).property("coordinates"))
# Append the coordinates of atom in molecule1 to which it maps.
c1.append(molecule1.atom(idx1).property("coordinates"))
# Compute the RMSD between the two sets of coordinates.
scores.append(_SireMaths.getRMSD(c0, c1))
# No mappings were found.
if len(mappings) == 0:
if len(prematch) == 0:
return ([{}], [])
else:
return ([prematch], [])
# Sort the scores and return the sorted keys. (Smaller RMSD is best)
keys = sorted(range(len(scores)), key=lambda k: scores[k])
# Sort the mappings.
mappings = [mappings[x] for x in keys]
# Sort the scores and convert to Angstroms.
scores = [scores[x] * _Units.Length.angstrom for x in keys]
# Return the sorted mappings and their scores.
return (mappings, scores)
def _validate_mapping(molecule0, molecule1, mapping, name):
"""Internal function to validate that a mapping contains key:value pairs
of the correct type.
Parameters
----------
molecule0 : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>`
The molecule of interest.
molecule1 : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>`