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 | class NonbondedJaxGenerator:
def __init__(self, ff: Hamiltonian):
self.name = "NonbondedForce"
self.ff = ff
self.fftree = ff.fftree
self.paramtree = ff.paramtree
self.paramtree[self.name] = {}
self.paramtree[self.name]["sigfix"] = jnp.array([])
self.paramtree[self.name]["epsfix"] = jnp.array([])
self.from_force = []
self.from_residue = []
self.ra2idx = {}
self.idx2rai = {}
self.useBCC = False
self.useVsite = False
def extract(self):
self.from_residue = self.fftree.get_attribs(
"NonbondedForce/UseAttributeFromResidue", "name")
self.from_force = [
i for i in ["charge", "sigma", "epsilon"]
if i not in self.from_residue
]
# Build per-atom array for from_force
for prm in self.from_force:
vals = self.fftree.get_attribs("NonbondedForce/Atom", prm)
self.paramtree[self.name][prm] = jnp.array(vals)
# Build per-atom array for from_residue
residues = self.fftree.get_nodes("Residues/Residue")
resvals = {k: [] for k in self.from_residue}
for resnode in residues:
resname = resnode.attrs["name"]
resvals[resname] = []
atomname = resnode.get_attribs("Atom", "name")
shift = len(self.ra2idx)
for natom, aname in enumerate(atomname):
self.ra2idx[(resname, natom)] = shift + natom
self.idx2rai[shift + natom] = (resname, atomname, natom)
for prm in self.from_residue:
atomval = resnode.get_attribs("Atom", prm)
resvals[prm].extend(atomval)
for prm in self.from_residue:
self.paramtree[self.name][prm] = jnp.array(resvals[prm])
# Build coulomb14scale and lj14scale
coulomb14scale, lj14scale = self.fftree.get_attribs(
"NonbondedForce", ["coulomb14scale", "lj14scale"])[0]
self.paramtree[self.name]["coulomb14scale"] = jnp.array(
[coulomb14scale])
self.paramtree[self.name]["lj14scale"] = jnp.array([lj14scale])
# Build BondChargeCorrection
bccs = self.fftree.get_attribs("NonbondedForce/BondChargeCorrection", "bcc")
self.paramtree[self.name]['bcc'] = jnp.array(bccs).reshape(-1, 1)
self.useBCC = len(bccs) > 0
# Build VirtualSite
vsite_types = self.fftree.get_attribs("NonbondedForce/VirtualSite", "vtype")
self.paramtree[self.name]['vsite_types'] = jnp.array(vsite_types, dtype=int)
vsite_distance = self.fftree.get_attribs("NonbondedForce/VirtualSite", "distance")
self.paramtree[self.name]['vsite_distances'] = jnp.array(vsite_distance)
self.useVsite = len(vsite_types) > 0
def overwrite(self):
# write coulomb14scale
self.fftree.set_attrib("NonbondedForce", "coulomb14scale",
self.paramtree[self.name]["coulomb14scale"])
# write lj14scale
self.fftree.set_attrib("NonbondedForce", "lj14scale",
self.paramtree[self.name]["lj14scale"])
# write prm from force
for prm in self.from_force:
self.fftree.set_attrib("NonbondedForce/Atom", prm,
self.paramtree[self.name][prm])
# write prm from residue
residues = self.fftree.get_nodes("Residues/Residue")
for prm in self.from_residue:
vals = self.paramtree[self.name][prm]
data = []
for idx in range(vals.shape[0]):
rname, atomname, aidx = self.idx2rai[idx]
data.append((rname, aidx, vals[idx]))
for resnode in residues:
tmp = sorted(
[d for d in data if d[0] == resnode.attrs["name"]],
key=lambda x: x[1])
resnode.set_attrib("Atom", prm, [t[2] for t in tmp])
# write BCC
if self.useBCC:
self.fftree.set_attrib(
"NonbondedForce/BondChargeCorrection", "bcc",
self.paramtree[self.name]['bcc']
)
def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):
# Build Covalent Map
self.covalent_map = build_covalent_map(data, 6)
methodMap = {
app.NoCutoff: "NoCutoff",
app.CutoffPeriodic: "CutoffPeriodic",
app.CutoffNonPeriodic: "CutoffNonPeriodic",
app.PME: "PME",
}
if nonbondedMethod not in methodMap:
raise DMFFException("Illegal nonbonded method for NonbondedForce")
isNoCut = False
if nonbondedMethod is app.NoCutoff:
isNoCut = True
mscales_coul = jnp.array([0.0, 0.0, 0.0, 1.0, 1.0,
1.0]) # mscale for PME
mscales_coul = mscales_coul.at[2].set(
self.paramtree[self.name]["coulomb14scale"][0])
mscales_lj = jnp.array([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]) # mscale for LJ
mscales_lj = mscales_lj.at[2].set(
self.paramtree[self.name]["lj14scale"][0])
# set PBC
if nonbondedMethod not in [app.NoCutoff, app.CutoffNonPeriodic]:
ifPBC = True
else:
ifPBC = False
nbmatcher = TypeMatcher(self.fftree, "NonbondedForce/Atom")
rdmol = args.get("rdmol", None)
if self.useVsite:
vsitematcher = TypeMatcher(self.fftree, "NonbondedForce/VirtualSite")
vsite_matches_dict = vsitematcher.matchSmirksNoSort(rdmol)
vsiteObj = VirtualSite(vsite_matches_dict)
def addVsiteFunc(pos, params):
func = vsiteObj.getAddVirtualSiteFunc()
newpos = func(pos, params[self.name]['vsite_types'], params[self.name]['vsite_distances'])
return newpos
self._addVsiteFunc = addVsiteFunc
rdmol = vsiteObj.addVirtualSiteToMol(rdmol)
self.vsiteObj = vsiteObj
# expand covalent map
ori_dim = self.covalent_map.shape[0]
new_dim = ori_dim + len(vsite_matches_dict)
cov_map = np.zeros((new_dim, new_dim), dtype=int)
cov_map[:ori_dim, :ori_dim] += np.array(self.covalent_map, dtype=int)
map_to_parents = np.arange(new_dim)
for i, match in enumerate(vsite_matches_dict.keys()):
map_to_parents[ori_dim + i] = match[0]
for i in range(len(vsite_matches_dict)):
parent_i = map_to_parents[ori_dim + i]
for j in range(new_dim):
parent_j = map_to_parents[j]
cov_map[ori_dim + i, j] = cov_map[parent_i, parent_j]
cov_map[j, ori_dim + i] = cov_map[parent_j, parent_i]
# keep diagonal 0
cov_map[ori_dim + i, ori_dim + i] = 0
# keep vsite and its parent atom 1
cov_map[parent_i, ori_dim + i] = 1
cov_map[ori_dim + i, parent_i] = 1
self.covalent_map = jnp.array(cov_map)
# Load Lennard-Jones parameters
maps = {}
if not nbmatcher.useSmirks:
for prm in self.from_force:
maps[prm] = []
for atom in data.atoms:
atype = data.atomType[atom]
ifFound, _, nnode = nbmatcher.matchGeneral([atype])
if not ifFound:
raise DMFFException(
"AtomType of %s mismatched in NonbondedForce" %
(str(atom)))
maps[prm].append(nnode)
maps[prm] = jnp.array(maps[prm], dtype=int)
else:
lj_matches_dict = nbmatcher.matchSmirks(rdmol)
for prm in self.from_force:
maps[prm] = []
for i in range(rdmol.GetNumAtoms()):
try:
maps[prm].append(lj_matches_dict[(i,)])
except KeyError as e:
raise DMFFException(
f"No parameter for atom {i}"
)
maps[prm] = jnp.array(maps[prm], dtype=int)
for prm in self.from_residue:
maps[prm] = []
for atom in data.atoms:
templateName = self.ff.templateNameForResidue[atom.residue.index]
aidx = data.atomTemplateIndexes[atom]
resname, aname = templateName, atom.name
maps[prm].append(self.ra2idx[(resname, aidx)])
# Virtual Site
if self.useVsite:
# expand charges
chg = jnp.zeros(
(len(self.paramtree[self.name]['charge']) + len(vsite_matches_dict),),
dtype=self.paramtree[self.name]['charge'].dtype
)
self.paramtree[self.name]['charge'] = chg.at[:len(self.paramtree[self.name]['charge'])].set(
self.paramtree[self.name]['charge']
)
maps_chg = [int(x) for x in maps['charge']]
for i in range(len(vsite_matches_dict)):
maps_chg.append(len(maps['charge']) + i)
maps['charge'] = jnp.array(maps_chg, dtype=int)
# BCC parameters
if self.useBCC:
bccmatcher = TypeMatcher(self.fftree, "NonbondedForce/BondChargeCorrection")
if bccmatcher.useSmirks:
bcc_matches_dict = bccmatcher.matchSmirksBCC(rdmol)
self.top_mat = np.zeros((rdmol.GetNumAtoms(), self.paramtree[self.name]['bcc'].shape[0]))
for bond in rdmol.GetBonds():
beginAtomIdx = bond.GetBeginAtomIdx()
endAtomIdx = bond.GetEndAtomIdx()
query1, query2 = (beginAtomIdx, endAtomIdx), (endAtomIdx, beginAtomIdx)
if query1 in bcc_matches_dict:
nnode = bcc_matches_dict[query1]
self.top_mat[query1[0], nnode] += 1
self.top_mat[query1[1], nnode] -= 1
elif query2 in bcc_matches_dict:
nnode = bcc_matches_dict[query2]
self.top_mat[query2[0], nnode] += 1
self.top_mat[query2[1], nnode] -= 1
else:
warnings.warn(
f"No BCC parameter for bond between Atom{beginAtomIdx} and Atom{endAtomIdx}"
)
else:
raise DMFFException(
"Only SMIRKS-based parametrization is supported for BCC"
)
else:
self.top_mat = None
# NBFIX
map_nbfix = []
map_nbfix = jnp.array(map_nbfix, dtype=jnp.int32).reshape(-1, 2)
if unit.is_quantity(nonbondedCutoff):
r_cut = nonbondedCutoff.value_in_unit(unit.nanometer)
else:
r_cut = nonbondedCutoff
if "switchDistance" in args and args["switchDistance"] is not None:
r_switch = args["switchDistance"]
r_switch = (r_switch if not unit.is_quantity(r_switch) else
r_switch.value_in_unit(unit.nanometer))
ifSwitch = True
else:
r_switch = r_cut
ifSwitch = False
# PME Settings
if nonbondedMethod is app.PME:
a, b, c = system.getDefaultPeriodicBoxVectors()
box = jnp.array([a._value, b._value, c._value])
self.ethresh = args.get("ethresh", 1e-6)
self.coeff_method = args.get("PmeCoeffMethod", "openmm")
self.fourier_spacing = args.get("PmeSpacing", 0.1)
kappa, K1, K2, K3 = setup_ewald_parameters(r_cut, self.ethresh,
box,
self.fourier_spacing,
self.coeff_method)
map_lj = jnp.array(maps["sigma"])
map_charge = jnp.array(maps["charge"])
# Free Energy Settings #
isFreeEnergy = args.get("isFreeEnergy", False)
if isFreeEnergy:
vdwLambda = args.get("vdwLambda", 0.0)
coulLambda = args.get("coulLambda", 0.0)
ifStateA = args.get("ifStateA", True)
# soft-cores
vdwSoftCore = args.get("vdwSoftCore", False)
coulSoftCore = args.get("coulSoftCore", False)
scAlpha = args.get("scAlpha", 0.0)
scSigma = args.get("scSigma", 0.0)
# couple
coupleIndex = args.get("coupleIndex", [])
if len(coupleIndex) > 0:
coupleMask = [False for _ in range(len(data.atoms))]
for atomIndex in coupleIndex:
coupleMask[atomIndex] = True
coupleMask = jnp.array(coupleMask, dtype=bool)
else:
coupleMask = None
if not isFreeEnergy:
ljforce = LennardJonesForce(r_switch,
r_cut,
map_lj,
map_nbfix,
isSwitch=ifSwitch,
isPBC=ifPBC,
isNoCut=isNoCut)
else:
ljforce = LennardJonesFreeEnergyForce(r_switch,
r_cut,
map_lj,
map_nbfix,
isSwitch=ifSwitch,
isPBC=ifPBC,
isNoCut=isNoCut,
feLambda=vdwLambda,
coupleMask=coupleMask,
useSoftCore=vdwSoftCore,
ifStateA=ifStateA,
sc_alpha=scAlpha,
sc_sigma=scSigma)
ljenergy = ljforce.generate_get_energy()
# dispersion correction
useDispersionCorrection = args.get("useDispersionCorrection", False)
if useDispersionCorrection:
numTypes = self.paramtree[self.name]["sigma"].shape[0]
countVec = np.zeros(numTypes, dtype=int)
countMat = np.zeros((numTypes, numTypes), dtype=int)
types, count = np.unique(map_lj, return_counts=True)
for typ, cnt in zip(types, count):
countVec[typ] += cnt
for i in range(numTypes):
for j in range(i, numTypes):
if i != j:
countMat[i, j] = countVec[i] * countVec[j]
else:
countMat[i, i] = countVec[i] * (countVec[i] - 1) // 2
assert np.sum(countMat) == len(map_lj) * (len(map_lj) - 1) // 2
colv_pairs = np.argwhere(
np.logical_and(self.covalent_map > 0, self.covalent_map <= 3))
for pair in colv_pairs:
if pair[0] <= pair[1]:
tmp = (map_lj[pair[0]], map_lj[pair[1]])
t1, t2 = min(tmp), max(tmp)
countMat[t1, t2] -= 1
if not isFreeEnergy:
ljDispCorrForce = LennardJonesLongRangeForce(
r_cut, map_lj, map_nbfix, countMat)
else:
ljDispCorrForce = LennardJonesLongRangeFreeEnergyForce(
r_cut, map_lj, map_nbfix, countMat, vdwLambda, ifStateA,
coupleMask)
ljDispEnergyFn = ljDispCorrForce.generate_get_energy()
if not isFreeEnergy:
if nonbondedMethod is not app.PME:
# do not use PME
if nonbondedMethod in [
app.CutoffPeriodic, app.CutoffNonPeriodic
]:
# use Reaction Field
coulforce = CoulReactionFieldForce(r_cut,
map_charge,
isPBC=ifPBC,
topology_matrix=self.top_mat)
if nonbondedMethod is app.NoCutoff:
# use NoCutoff
coulforce = CoulNoCutoffForce(map_charge, topology_matrix=self.top_mat)
else:
coulforce = CoulombPMEForce(r_cut, map_charge, kappa,
(K1, K2, K3), topology_matrix=self.top_mat)
else:
assert nonbondedMethod is app.PME, "Only PME is supported in free energy calculations"
assert not self.useBCC, "BCC usage in free energy calculations is not supported yet"
coulforce = CoulombPMEFreeEnergyForce(r_cut,
map_charge,
kappa, (K1, K2, K3),
coulLambda,
ifStateA=ifStateA,
coupleMask=coupleMask,
useSoftCore=coulSoftCore,
sc_alpha=scAlpha,
sc_sigma=scSigma)
coulenergy = coulforce.generate_get_energy()
if not isFreeEnergy:
def potential_fn(positions, box, pairs, params):
# check whether args passed into potential_fn are jnp.array and differentiable
# note this check will be optimized away by jit
# it is jit-compatiable
isinstance_jnp(positions, box, params)
ljE = ljenergy(positions, box, pairs,
params[self.name]["epsilon"],
params[self.name]["sigma"],
params[self.name]["epsfix"],
params[self.name]["sigfix"], mscales_lj)
if not self.useBCC:
coulE = coulenergy(positions, box, pairs,
params[self.name]["charge"], mscales_coul)
else:
coulE = coulenergy(positions, box, pairs,
params[self.name]["charge"], params[self.name]["bcc"], mscales_coul)
if useDispersionCorrection:
ljDispEnergy = ljDispEnergyFn(box,
params[self.name]['epsilon'],
params[self.name]['sigma'],
params[self.name]['epsfix'],
params[self.name]['sigfix'])
return ljE + coulE + ljDispEnergy
else:
return ljE + coulE
self._jaxPotential = potential_fn
else:
# Free Energy
@jit_condition()
def potential_fn(positions, box, pairs, params, vdwLambda,
coulLambda):
ljE = ljenergy(positions, box, pairs,
params[self.name]["epsilon"],
params[self.name]["sigma"],
params[self.name]["epsfix"],
params[self.name]["sigfix"], mscales_lj,
vdwLambda)
coulE = coulenergy(positions, box, pairs,
params[self.name]["charge"], mscales_coul,
coulLambda)
if useDispersionCorrection:
ljDispEnergy = ljDispEnergyFn(box,
params[self.name]['epsilon'],
params[self.name]['sigma'],
params[self.name]['epsfix'],
params[self.name]['sigfix'],
vdwLambda)
return ljE + coulE + ljDispEnergy
else:
return ljE + coulE
self._jaxPotential = potential_fn
def getJaxPotential(self):
return self._jaxPotential
def getAddVsiteFunc(self):
"""
Get function to add coordinates for virtual sites
"""
return self._addVsiteFunc
def getVsiteObj(self):
"""
Get `dmff.classical.vsite.VirtualSite` object
"""
if self.useVsite:
return self.vsiteObj
else:
return None
def getTopologyMatrix(self):
"""
Get topology Matrix
"""
return self.top_mat
|