ADMPDispPmeGenerator

This one computes the undamped C6/C8/C10 interactions u = \sum_{ij} c6/r^6 + c8/r^8 + c10/r^10

Source code in dmff/api.py
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
class ADMPDispPmeGenerator:
    r"""
    This one computes the undamped C6/C8/C10 interactions
    u = \sum_{ij} c6/r^6 + c8/r^8 + c10/r^10
    """

    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.params = {"C6": [], "C8": [], "C10": []}
        self._jaxPotential = None
        self.types = []
        self.ethresh = 5e-4
        self.pmax = 10
        self.name = "ADMPDispPme"

    def registerAtomType(self, atom):
        self.types.append(atom["type"])
        self.params["C6"].append(float(atom["C6"]))
        self.params["C8"].append(float(atom["C8"]))
        self.params["C10"].append(float(atom["C10"]))

    @staticmethod
    def parseElement(element, hamiltonian):
        generator = ADMPDispPmeGenerator(hamiltonian)
        hamiltonian.registerGenerator(generator)
        # covalent scales
        mScales = []
        for i in range(2, 7):
            mScales.append(float(element.attrib["mScale1%d" % i]))
        mScales.append(1.0)
        generator.params["mScales"] = mScales
        for atomtype in element.findall("Atom"):
            generator.registerAtomType(atomtype.attrib)
        # jax it!
        for k in generator.params.keys():
            generator.params[k] = jnp.array(generator.params[k])
        generator.types = np.array(generator.types)

    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {
            app.CutoffPeriodic: "CutoffPeriodic",
            app.NoCutoff: "NoCutoff",
            app.PME: "PME",
        }
        if nonbondedMethod not in methodMap:
            raise ValueError("Illegal nonbonded method for ADMPDispPmeForce")
        if nonbondedMethod is app.CutoffPeriodic:
            self.lpme = False
        else:
            self.lpme = True

        n_atoms = len(data.atoms)
        # build index map
        map_atomtype = np.zeros(n_atoms, dtype=int)
        for i in range(n_atoms):
            atype = data.atomType[data.atoms[i]]
            map_atomtype[i] = np.where(self.types == atype)[0][0]
        self.map_atomtype = map_atomtype
        # build covalent map
        covalent_map = build_covalent_map(data, 6)

        # here box is only used to setup ewald parameters, no need to be differentiable
        a, b, c = system.getDefaultPeriodicBoxVectors()
        box = jnp.array([a._value, b._value, c._value]) * 10
        # get the admp calculator
        rc = nonbondedCutoff.value_in_unit(unit.angstrom)

        # get calculator
        if "ethresh" in args:
            self.ethresh = args["ethresh"]

        disp_force = ADMPDispPmeForce(
            box, covalent_map, rc, self.ethresh, self.pmax, self.lpme
        )
        self.disp_force = disp_force
        pot_fn_lr = disp_force.get_energy

        def potential_fn(positions, box, pairs, params):
            mScales = params["mScales"]
            C6_list = params["C6"][map_atomtype] * 1e6  # to kj/mol * A**6
            C8_list = params["C8"][map_atomtype] * 1e8
            C10_list = params["C10"][map_atomtype] * 1e10
            c6_list = jnp.sqrt(C6_list)
            c8_list = jnp.sqrt(C8_list)
            c10_list = jnp.sqrt(C10_list)
            c_list = jnp.vstack((c6_list, c8_list, c10_list))
            E_lr = pot_fn_lr(positions, box, pairs, c_list.T, mScales)
            return -E_lr

        self._jaxPotential = potential_fn
        # self._top_data = data

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        # generate xml force field file
        pass

ADMPPmeGenerator

Source code in dmff/api.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
class ADMPPmeGenerator:
    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.kStrings = {
            "kz": [],
            "kx": [],
            "ky": [],
        }
        self._input_params = {
            "c0": [],
            "dX": [],
            "dY": [],
            "dZ": [],
            "qXX": [],
            "qXY": [],
            "qYY": [],
            "qXZ": [],
            "qYZ": [],
            "qZZ": [],
            "oXXX": [],
            "oXXY": [],
            "oXYY": [],
            "oYYY": [],
            "oXXZ": [],
            "oXYZ": [],
            "oYYZ": [],
            "oXZZ": [],
            "oYZZ": [],
            "oZZZ": [],
            "thole": [],
            "polarizabilityXX": [],
            "polarizabilityYY": [],
            "polarizabilityZZ": [],
        }
        self.params = {
            "mScales": [],
            "pScales": [],
            "dScales": [],
        }
        # if more or optional input params
        # self._input_params = defaultDict(list)
        self._jaxPotential = None
        self.types = []
        self.ethresh = 5e-4
        self.step_pol = None
        self.lpol = False
        self.ref_dip = ""
        self.name = "ADMPPme"

    def registerAtomType(self, atom: dict):

        self.types.append(atom.pop("type"))

        kStrings = ["kz", "kx", "ky"]
        for kString in kStrings:
            if kString in atom:
                self.kStrings[kString].append(atom.pop(kString))
            else:
                self.kStrings[kString].append("0")

        for k, v in atom.items():
            self._input_params[k].append(float(v))

    @staticmethod
    def parseElement(element, hamiltonian):

        r"""parse admp related parameters in XML file

        example:

        <ADMPDispForce mScale12="0.00" mScale13="0.00" mScale14="0.00" mScale15="1.00" mScale16="1.00">
          <Atom type="380" A="1203470.743" B="37.81265679" Q="-0.741706" C6="0.001383816" C8="7.27065e-05" C10="1.8076465e-6"/>
          <Atom type="381" A="83.2283563" B="37.78544799"  Q="0.370853" C6="5.7929e-05" C8="1.416624e-06" C10="2.26525e-08"/>
        </ADMPDispForce>

        <ADMPPmeForce lmax="2" mScale12="0.00" mScale13="0.00" mScale14="0.00" mScale15="1.00" mScale16="1.00" pScale12="0.00" pScale13="0.00" pScale14="0.00" pScale15="1.00" pScale16="1.00" dScale12="0.00" dScale13="0.00" dScale14="0.00" dScale15="1.00" dScale16="1.00">

          <Atom type="380" kz="-381" kx="-381"
                        c0="-1.0614"
                        dX="0.0" dY="0.0"  dZ="-0.023671684"
                        qXX="0.000150963" qXY="0.0" qYY="0.00008707" qXZ="0.0" qYZ="0.0" qZZ="-0.000238034"
                        oXXX="0.0" oXXY="0.0" oXYY="0.0" oYYY="0.0" oXXZ="0.0000" oXYZ="0.0" oYYZ="0.00000" oXZZ="0.0" oYZZ="0.0" oZZZ="-0.0000"
                        />
          <Atom type="381" kz="380" kx="381"
                        c0="0.5307"
                        dX="0.0" dY="0.0"  dZ="0.0"
                        qXX="0.0" qXY="0.0" qYY="0.0" qXZ="0.0" qYZ="0.0" qZZ="0.0"
                        oXXX="0.0" oXXY="0.0" oXYY="0.0" oYYY="0.0" oXXZ="0.0" oXYZ="0.0" oYYZ="0.0" oXZZ="0.0" oYZZ="0.0" oZZZ="0.0"
                        />
          <Polarize type="380" polarizabilityXX="0.00088" polarizabilityYY="0.00088" polarizabilityZZ="0.00088" thole="8.0"/>
          <Polarize type="381" polarizabilityXX="0.000" polarizabilityYY="0.000" polarizabilityZZ="0.000" thole="0.0"/>
        </ADMPPmeForce>

        """

        generator = ADMPPmeGenerator(hamiltonian)
        generator.lmax = int(element.attrib.get("lmax"))
        generator.defaultTholeWidth = 5

        hamiltonian.registerGenerator(generator)

        for i in range(2, 7):
            generator.params["mScales"].append(float(element.attrib["mScale1%d" % i]))
            generator.params["pScales"].append(float(element.attrib["pScale1%d" % i]))
            generator.params["dScales"].append(float(element.attrib["dScale1%d" % i]))

        # make sure the last digit is 1.0
        generator.params["mScales"].append(1.0)
        generator.params["pScales"].append(1.0)
        generator.params["dScales"].append(1.0)

        if element.findall("Polarize"):
            generator.lpol = True
        else:
            generator.lpol = False

        for atomType in element.findall("Atom"):
            atomAttrib = atomType.attrib
            # if not set
            atomAttrib.update(
                {"polarizabilityXX": 0, "polarizabilityYY": 0, "polarizabilityZZ": 0}
            )
            for polarInfo in element.findall("Polarize"):
                polarAttrib = polarInfo.attrib
                if polarInfo.attrib["type"] == atomAttrib["type"]:
                    # cover default
                    atomAttrib.update(polarAttrib)
                    break
            generator.registerAtomType(atomAttrib)

        for k in generator._input_params.keys():
            generator._input_params[k] = jnp.array(generator._input_params[k])
        generator.types = np.array(generator.types)

        n_atoms = len(element.findall("Atom"))
        generator.n_atoms = n_atoms

        # map atom multipole moments
        if generator.lmax == 0:
            n_mtps = 1
        elif generator.lmax == 1:
            n_mtps = 4
        elif generator.lmax == 2:
            n_mtps = 10
        Q = np.zeros((n_atoms, n_mtps))

        Q[:, 0] = generator._input_params["c0"]
        if generator.lmax >= 1:
            Q[:, 1] = generator._input_params["dX"] * 10
            Q[:, 2] = generator._input_params["dY"] * 10
            Q[:, 3] = generator._input_params["dZ"] * 10
        if generator.lmax >= 2:
            Q[:, 4] = generator._input_params["qXX"] * 300
            Q[:, 5] = generator._input_params["qYY"] * 300
            Q[:, 6] = generator._input_params["qZZ"] * 300
            Q[:, 7] = generator._input_params["qXY"] * 300
            Q[:, 8] = generator._input_params["qXZ"] * 300
            Q[:, 9] = generator._input_params["qYZ"] * 300

        # add all differentiable params to self.params
        Q_local = convert_cart2harm(Q, generator.lmax)
        generator.params["Q_local"] = Q_local

        if generator.lpol:
            pol = jnp.vstack(
                (
                    generator._input_params["polarizabilityXX"],
                    generator._input_params["polarizabilityYY"],
                    generator._input_params["polarizabilityZZ"],
                )
            ).T
            pol = 1000 * jnp.mean(pol, axis=1)
            tholes = jnp.array(generator._input_params["thole"])
            generator.params["pol"] = pol
            generator.params["tholes"] = tholes
        else:
            pol = None
            tholes = None

        # generator.params['']
        for k in generator.params.keys():
            generator.params[k] = jnp.array(generator.params[k])

    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):

        methodMap = {
            app.CutoffPeriodic: "CutoffPeriodic",
            app.NoCutoff: "NoCutoff",
            app.PME: "PME",
        }
        if nonbondedMethod not in methodMap:
            raise ValueError("Illegal nonbonded method for ADMPPmeForce")
        if nonbondedMethod is app.CutoffPeriodic:
            self.lpme = False
        else:
            self.lpme = True

        n_atoms = len(data.atoms)
        map_atomtype = np.zeros(n_atoms, dtype=int)

        for i in range(n_atoms):
            atype = data.atomType[data.atoms[i]]
            map_atomtype[i] = np.where(self.types == atype)[0][0]
        self.map_atomtype = map_atomtype

        # here box is only used to setup ewald parameters, no need to be differentiable
        a, b, c = system.getDefaultPeriodicBoxVectors()
        box = jnp.array([a._value, b._value, c._value]) * 10

        # get the admp calculator
        rc = nonbondedCutoff.value_in_unit(unit.angstrom)

        # build covalent map
        covalent_map = build_covalent_map(data, 6)

        # build intra-molecule axis
        # the following code is the direct transplant of forcefield.py in openmm 7.4.0

        if self.lmax > 0:

            # setting up axis_indices and axis_type
            ZThenX = 0
            Bisector = 1
            ZBisect = 2
            ThreeFold = 3
            ZOnly = 4  # typo fix
            NoAxisType = 5
            LastAxisTypeIndex = 6

            self.axis_types = []
            self.axis_indices = []
            for i_atom in range(n_atoms):
                atom = data.atoms[i_atom]
                t = data.atomType[atom]
                # if t is in type list?
                if t in self.types:
                    itypes = np.where(self.types == t)[0]
                    hit = 0
                    # try to assign multipole parameters via only 1-2 connected atoms
                    for itype in itypes:
                        if hit != 0:
                            break
                        kz = int(self.kStrings["kz"][itype])
                        kx = int(self.kStrings["kx"][itype])
                        ky = int(self.kStrings["ky"][itype])
                        neighbors = np.where(covalent_map[i_atom] == 1)[0]
                        zaxis = -1
                        xaxis = -1
                        yaxis = -1
                        for z_index in neighbors:
                            if hit != 0:
                                break
                            z_type = int(data.atomType[data.atoms[z_index]])
                            if z_type == abs(
                                kz
                            ):  # find the z atom, start searching for x
                                for x_index in neighbors:
                                    if x_index == z_index or hit != 0:
                                        continue
                                    x_type = int(data.atomType[data.atoms[x_index]])
                                    if x_type == abs(
                                        kx
                                    ):  # find the x atom, start searching for y
                                        if ky == 0:
                                            zaxis = z_index
                                            xaxis = x_index
                                            # cannot ditinguish x and z? use the smaller index for z, and the larger index for x
                                            if x_type == z_type and xaxis < zaxis:
                                                swap = z_axis
                                                z_axis = x_axis
                                                x_axis = swap
                                            # otherwise, try to see if we can find an even smaller index for x?
                                            else:
                                                for x_index in neighbors:
                                                    x_type1 = int(
                                                        data.atomType[
                                                            data.atoms[x_index]
                                                        ]
                                                    )
                                                    if (
                                                        x_type1 == abs(kx)
                                                        and x_index != z_index
                                                        and x_index < xaxis
                                                    ):
                                                        xaxis = x_index
                                            hit = 1  # hit, finish matching
                                            matched_itype = itype
                                        else:
                                            for y_index in neighbors:
                                                if (
                                                    y_index == z_index
                                                    or y_index == x_index
                                                    or hit != 0
                                                ):
                                                    continue
                                                y_type = int(
                                                    data.atomType[data.atoms[y_index]]
                                                )
                                                if y_type == abs(ky):
                                                    zaxis = z_index
                                                    xaxis = x_index
                                                    yaxis = y_index
                                                    hit = 2
                                                    matched_itype = itype
                    # assign multipole parameters via 1-2 and 1-3 connected atoms
                    for itype in itypes:
                        if hit != 0:
                            break
                        kz = int(self.kStrings["kz"][itype])
                        kx = int(self.kStrings["kx"][itype])
                        ky = int(self.kStrings["ky"][itype])
                        neighbors_1st = np.where(covalent_map[i_atom] == 1)[0]
                        neighbors_2nd = np.where(covalent_map[i_atom] == 2)[0]
                        zaxis = -1
                        xaxis = -1
                        yaxis = -1
                        for z_index in neighbors_1st:
                            if hit != 0:
                                break
                            z_type = int(data.atomType[data.atoms[z_index]])
                            if z_type == abs(kz):
                                for x_index in neighbors_2nd:
                                    if x_index == z_index or hit != 0:
                                        continue
                                    x_type = int(data.atomType[data.atoms[x_index]])
                                    # we ask x to be in 2'nd neighbor, and x is z's neighbor
                                    if (
                                        x_type == abs(kx)
                                        and covalent_map[z_index, x_index] == 1
                                    ):
                                        if ky == 0:
                                            zaxis = z_index
                                            xaxis = x_index
                                            # select smallest x index
                                            for x_index in neighbors_2nd:
                                                x_type1 = int(
                                                    data.atomType[data.atoms[x_index]]
                                                )
                                                if (
                                                    x_type1 == abs(kx)
                                                    and x_index != z_index
                                                    and covalent_map[x_index, z_index]
                                                    == 1
                                                    and x_index < xaxis
                                                ):
                                                    xaxis = x_index
                                            hit = 3
                                            matched_itype = itype
                                        else:
                                            for y_index in neighbors_2nd:
                                                if (
                                                    y_index == z_index
                                                    or y_index == x_index
                                                    or hit != 0
                                                ):
                                                    continue
                                                y_type = int(
                                                    data.atomType[data.atoms[y_index]]
                                                )
                                                if (
                                                    y_type == abs(ky)
                                                    and covalent_map[y_index, z_index]
                                                    == 1
                                                ):
                                                    zaxis = z_index
                                                    xaxis = x_index
                                                    yaxis = y_index
                                                    hit = 4
                                                    matched_itype = itype
                    # assign multipole parameters via only a z-defining atom
                    for itype in itypes:
                        if hit != 0:
                            break
                        kz = int(self.kStrings["kz"][itype])
                        kx = int(self.kStrings["kx"][itype])
                        zaxis = -1
                        xaxis = -1
                        yaxis = -1
                        neighbors = np.where(covalent_map[i_atom] == 1)[0]
                        for z_index in neighbors:
                            if hit != 0:
                                break
                            z_type = int(data.atomType[data.atoms[z_index]])
                            if kx == 0 and z_type == abs(kz):
                                zaxis = z_index
                                hit = 5
                                matched_itype = itype
                    # assign multipole parameters via no connected atoms
                    for itype in itypes:
                        if hit != 0:
                            break
                        kz = int(self.kStrings["kz"][itype])
                        zaxis = -1
                        xaxis = -1
                        yaxis = -1
                        if kz == 0:
                            hit = 6
                            matched_itype = itype
                    # add particle if there was a hit
                    if hit != 0:
                        map_atomtype[i_atom] = matched_itype
                        self.axis_indices.append([zaxis, xaxis, yaxis])

                        kz = int(self.kStrings["kz"][matched_itype])
                        kx = int(self.kStrings["kx"][matched_itype])
                        ky = int(self.kStrings["ky"][matched_itype])
                        axisType = ZThenX
                        if kz == 0:
                            axisType = NoAxisType
                        if kz != 0 and kx == 0:
                            axisType = ZOnly
                        if kz < 0 or kx < 0:
                            axisType = Bisector
                        if kx < 0 and ky < 0:
                            axisType = ZBisect
                        if kz < 0 and kx < 0 and ky < 0:
                            axisType = ThreeFold
                        self.axis_types.append(axisType)

                    else:
                        sys.exit("Atom %d not matched in forcefield!" % i_atom)

                else:
                    sys.exit("Atom %d not matched in forcefield!" % i_atom)
            self.axis_indices = np.array(self.axis_indices)
            self.axis_types = np.array(self.axis_types)
        else:
            self.axis_types = None
            self.axis_indices = None

        if "ethresh" in args:
            self.ethresh = args["ethresh"]
        if "step_pol" in args:
            self.step_pol = args["step_pol"]

        pme_force = ADMPPmeForce(
            box,
            self.axis_types,
            self.axis_indices,
            covalent_map,
            rc,
            self.ethresh,
            self.lmax,
            self.lpol,
            self.lpme,
            self.step_pol
        )
        self.pme_force = pme_force

        def potential_fn(positions, box, pairs, params):

            mScales = params["mScales"]
            Q_local = params["Q_local"][map_atomtype]
            if self.lpol:
                pScales = params["pScales"]
                dScales = params["dScales"]
                pol = params["pol"][map_atomtype]
                tholes = params["tholes"][map_atomtype]

                return pme_force.get_energy(
                    positions,
                    box,
                    pairs,
                    Q_local,
                    pol,
                    tholes,
                    mScales,
                    pScales,
                    dScales,
                    pme_force.U_ind,
                )
            else:
                return pme_force.get_energy(positions, box, pairs, Q_local, mScales)

        self._jaxPotential = potential_fn

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        # <ADMPPmeForce>

        finfo = XMLNodeInfo("ADMPPmeForce")
        finfo.addAttribute("lmax", str(self.lmax))
        outputparams = deepcopy(self.params)
        mScales = outputparams.pop("mScales")
        pScales = outputparams.pop("pScales")
        dScales = outputparams.pop("dScales")
        for i in range(len(mScales)):
            finfo.addAttribute(f"mScale1{i+2}", str(mScales[i]))
        for i in range(len(pScales)):
            finfo.addAttribute(f"pScale{i+1}", str(pScales[i]))
        for i in range(len(dScales)):
            finfo.addAttribute(f"dScale{i+1}", str(dScales[i]))

        Q = outputparams["Q_local"]
        Q_global = convert_harm2cart(Q, self.lmax)

        # <Atom>
        for atom in range(self.n_atoms):
            info = {"type": self.map_atomtype[atom]}
            info.update(
                {ktype: self.kStrings[ktype][atom] for ktype in ["kz", "kx", "ky"]}
            )
            for i, key in enumerate(
                ["c0", "dX", "dY", "dZ", "qXX", "qXY", "qXZ", "qYY", "qYZ", "qZZ"]
            ):
                info[key] = "%.8f" % Q_global[atom][i]
            finfo.addElement("Atom", info)

        # <Polarize>
        for t in range(len(self.types)):
            info = {"type": self.types[t]}
            info.update(
                {
                    p: "%.8f" % self.params["pol"][t]
                    for p in [
                        "polarizabilityXX",
                        "polarizabilityYY",
                        "polarizabilityZZ",
                    ]
                }
            )
            finfo.addElement("Polarize", info)

        return finfo

parseElement(element, hamiltonian) staticmethod

parse admp related parameters in XML file

example:

Source code in dmff/api.py
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
@staticmethod
def parseElement(element, hamiltonian):

    r"""parse admp related parameters in XML file

    example:

    <ADMPDispForce mScale12="0.00" mScale13="0.00" mScale14="0.00" mScale15="1.00" mScale16="1.00">
      <Atom type="380" A="1203470.743" B="37.81265679" Q="-0.741706" C6="0.001383816" C8="7.27065e-05" C10="1.8076465e-6"/>
      <Atom type="381" A="83.2283563" B="37.78544799"  Q="0.370853" C6="5.7929e-05" C8="1.416624e-06" C10="2.26525e-08"/>
    </ADMPDispForce>

    <ADMPPmeForce lmax="2" mScale12="0.00" mScale13="0.00" mScale14="0.00" mScale15="1.00" mScale16="1.00" pScale12="0.00" pScale13="0.00" pScale14="0.00" pScale15="1.00" pScale16="1.00" dScale12="0.00" dScale13="0.00" dScale14="0.00" dScale15="1.00" dScale16="1.00">

      <Atom type="380" kz="-381" kx="-381"
                    c0="-1.0614"
                    dX="0.0" dY="0.0"  dZ="-0.023671684"
                    qXX="0.000150963" qXY="0.0" qYY="0.00008707" qXZ="0.0" qYZ="0.0" qZZ="-0.000238034"
                    oXXX="0.0" oXXY="0.0" oXYY="0.0" oYYY="0.0" oXXZ="0.0000" oXYZ="0.0" oYYZ="0.00000" oXZZ="0.0" oYZZ="0.0" oZZZ="-0.0000"
                    />
      <Atom type="381" kz="380" kx="381"
                    c0="0.5307"
                    dX="0.0" dY="0.0"  dZ="0.0"
                    qXX="0.0" qXY="0.0" qYY="0.0" qXZ="0.0" qYZ="0.0" qZZ="0.0"
                    oXXX="0.0" oXXY="0.0" oXYY="0.0" oYYY="0.0" oXXZ="0.0" oXYZ="0.0" oYYZ="0.0" oXZZ="0.0" oYZZ="0.0" oZZZ="0.0"
                    />
      <Polarize type="380" polarizabilityXX="0.00088" polarizabilityYY="0.00088" polarizabilityZZ="0.00088" thole="8.0"/>
      <Polarize type="381" polarizabilityXX="0.000" polarizabilityYY="0.000" polarizabilityZZ="0.000" thole="0.0"/>
    </ADMPPmeForce>

    """

    generator = ADMPPmeGenerator(hamiltonian)
    generator.lmax = int(element.attrib.get("lmax"))
    generator.defaultTholeWidth = 5

    hamiltonian.registerGenerator(generator)

    for i in range(2, 7):
        generator.params["mScales"].append(float(element.attrib["mScale1%d" % i]))
        generator.params["pScales"].append(float(element.attrib["pScale1%d" % i]))
        generator.params["dScales"].append(float(element.attrib["dScale1%d" % i]))

    # make sure the last digit is 1.0
    generator.params["mScales"].append(1.0)
    generator.params["pScales"].append(1.0)
    generator.params["dScales"].append(1.0)

    if element.findall("Polarize"):
        generator.lpol = True
    else:
        generator.lpol = False

    for atomType in element.findall("Atom"):
        atomAttrib = atomType.attrib
        # if not set
        atomAttrib.update(
            {"polarizabilityXX": 0, "polarizabilityYY": 0, "polarizabilityZZ": 0}
        )
        for polarInfo in element.findall("Polarize"):
            polarAttrib = polarInfo.attrib
            if polarInfo.attrib["type"] == atomAttrib["type"]:
                # cover default
                atomAttrib.update(polarAttrib)
                break
        generator.registerAtomType(atomAttrib)

    for k in generator._input_params.keys():
        generator._input_params[k] = jnp.array(generator._input_params[k])
    generator.types = np.array(generator.types)

    n_atoms = len(element.findall("Atom"))
    generator.n_atoms = n_atoms

    # map atom multipole moments
    if generator.lmax == 0:
        n_mtps = 1
    elif generator.lmax == 1:
        n_mtps = 4
    elif generator.lmax == 2:
        n_mtps = 10
    Q = np.zeros((n_atoms, n_mtps))

    Q[:, 0] = generator._input_params["c0"]
    if generator.lmax >= 1:
        Q[:, 1] = generator._input_params["dX"] * 10
        Q[:, 2] = generator._input_params["dY"] * 10
        Q[:, 3] = generator._input_params["dZ"] * 10
    if generator.lmax >= 2:
        Q[:, 4] = generator._input_params["qXX"] * 300
        Q[:, 5] = generator._input_params["qYY"] * 300
        Q[:, 6] = generator._input_params["qZZ"] * 300
        Q[:, 7] = generator._input_params["qXY"] * 300
        Q[:, 8] = generator._input_params["qXZ"] * 300
        Q[:, 9] = generator._input_params["qYZ"] * 300

    # add all differentiable params to self.params
    Q_local = convert_cart2harm(Q, generator.lmax)
    generator.params["Q_local"] = Q_local

    if generator.lpol:
        pol = jnp.vstack(
            (
                generator._input_params["polarizabilityXX"],
                generator._input_params["polarizabilityYY"],
                generator._input_params["polarizabilityZZ"],
            )
        ).T
        pol = 1000 * jnp.mean(pol, axis=1)
        tholes = jnp.array(generator._input_params["thole"])
        generator.params["pol"] = pol
        generator.params["tholes"] = tholes
    else:
        pol = None
        tholes = None

    # generator.params['']
    for k in generator.params.keys():
        generator.params[k] = jnp.array(generator.params[k])

HarmonicAngleJaxGenerator

Source code in dmff/api.py
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
class HarmonicAngleJaxGenerator:
    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.params = {"k": [], "angle": []}
        self._jaxPotential = None
        self.types = []
        self.name = "HarmonicAngle"

    def registerAngleType(self, angle):
        types = self.ff._findAtomTypes(angle, 3)
        if None not in types:
            self.types.append(types)
            self.params["k"].append(float(angle["k"]))
            self.params["angle"].append(float(angle["angle"]))

    @staticmethod
    def parseElement(element, hamiltonian):
        r"""parse <HarmonicAngleForce> section in XML file

        example:
          <HarmonicAngleForce>
            <Angle type1="hw" type2="ow" type3="hw" angle="1.8242181341844732" k="836.8000000000001"/>
            <Angle type1="hw" type2="hw" type3="ow" angle="2.2294835864975564" k="0.0"/>
          <\HarmonicAngleForce>

        """
        existing = [f for f in hamiltonian._forces if isinstance(f, HarmonicAngleJaxGenerator)]
        if len(existing) == 0:
            generator = HarmonicAngleJaxGenerator(hamiltonian)
            hamiltonian.registerGenerator(generator)
        else:
            generator = existing[0]
        for angletype in element.findall("Angle"):
            generator.registerAngleType(angletype.attrib)

    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):

        # jax it!
        for k in self.params.keys():
            self.params[k] = jnp.array(self.params[k])
        self.types = np.array(self.types)

        max_angles = len(data.angles)
        n_angles = 0
        # build map
        map_atom1 = np.zeros(max_angles, dtype=int)
        map_atom2 = np.zeros(max_angles, dtype=int)
        map_atom3 = np.zeros(max_angles, dtype=int)
        map_param = np.zeros(max_angles, dtype=int)
        for i in range(max_angles):
            idx1 = data.angles[i][0]
            idx2 = data.angles[i][1]
            idx3 = data.angles[i][2]
            type1 = data.atomType[data.atoms[idx1]]
            type2 = data.atomType[data.atoms[idx2]]
            type3 = data.atomType[data.atoms[idx3]]
            ifFound = False
            for ii in range(len(self.types)):
                if type2 in self.types[ii][1]:
                    if (type1 in self.types[ii][0] and type3 in self.types[ii][2]) or (
                        type1 in self.types[ii][2] and type3 in self.types[ii][0]
                    ):
                        map_atom1[n_angles] = idx1
                        map_atom2[n_angles] = idx2
                        map_atom3[n_angles] = idx3
                        map_param[n_angles] = ii
                        ifFound = True
                        n_angles += 1
                        break
            if not ifFound:
                warnings.warn(
                    "No parameter for angle %i - %i - %i" % (idx1, idx2, idx3)
                )

        map_atom1 = map_atom1[:n_angles]
        map_atom2 = map_atom2[:n_angles]
        map_atom3 = map_atom3[:n_angles]
        map_param = map_param[:n_angles]

        aforce = HarmonicAngleJaxForce(map_atom1, map_atom2, map_atom3, map_param)

        def potential_fn(positions, box, pairs, params):
            return aforce.get_energy(
                positions, box, pairs, params["k"], params["angle"]
            )

        self._jaxPotential = potential_fn
        # self._top_data = data

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        # generate xml force field file
        finfo = XMLNodeInfo("HarmonicAngleForce")
        for i, type in enumerate(self.types):
            t1, t2, t3 = type
            ainfo = {
                "type1": t1,
                "type2": t2,
                "type3": t3,
                "k": self.params["k"][i],
                "angle": self.params["angle"][i],
            }
            finfo.addElement("Angle", ainfo)

        return finfo

parseElement(element, hamiltonian) staticmethod

parse section in XML file

example

<\HarmonicAngleForce>

Source code in dmff/api.py
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
@staticmethod
def parseElement(element, hamiltonian):
    r"""parse <HarmonicAngleForce> section in XML file

    example:
      <HarmonicAngleForce>
        <Angle type1="hw" type2="ow" type3="hw" angle="1.8242181341844732" k="836.8000000000001"/>
        <Angle type1="hw" type2="hw" type3="ow" angle="2.2294835864975564" k="0.0"/>
      <\HarmonicAngleForce>

    """
    existing = [f for f in hamiltonian._forces if isinstance(f, HarmonicAngleJaxGenerator)]
    if len(existing) == 0:
        generator = HarmonicAngleJaxGenerator(hamiltonian)
        hamiltonian.registerGenerator(generator)
    else:
        generator = existing[0]
    for angletype in element.findall("Angle"):
        generator.registerAngleType(angletype.attrib)

HarmonicBondJaxGenerator

Source code in dmff/api.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
class HarmonicBondJaxGenerator:
    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.params = {"k": [], "length": []}
        self._jaxPotential = None
        self.types = []
        self.typetexts = []
        self.name = "HarmonicBond"

    def registerBondType(self, bond):
        typetxt = findAtomTypeTexts(bond, 2)
        types = self.ff._findAtomTypes(bond, 2)
        if None not in types:
            self.types.append(types)
            self.typetexts.append(typetxt)
            self.params["k"].append(float(bond["k"]))
            self.params["length"].append(float(bond["length"]))  # length := r0

    @staticmethod
    def parseElement(element, hamiltonian):

        r"""parse <HarmonicBondForce> section in XML file

        example:

          <HarmonicBondForce>
            <Bond type1="ow" type2="hw" length="0.09572000000000001" k="462750.3999999999"/>
            <Bond type1="hw" type2="hw" length="0.15136000000000002" k="462750.3999999999"/>
          <\HarmonicBondForce>

        """
        existing = [f for f in hamiltonian._forces if isinstance(f, HarmonicBondJaxGenerator)]
        if len(existing) == 0:
            generator = HarmonicBondJaxGenerator(hamiltonian)
            hamiltonian.registerGenerator(generator)
        else:
            generator = existing[0]
        for bondtype in element.findall("Bond"):
            generator.registerBondType(bondtype.attrib)

    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):
        # jax it!
        for k in self.params.keys():
            self.params[k] = jnp.array(self.params[k])
        self.types = np.array(self.types)

        n_bonds = len(data.bonds)
        # build map
        map_atom1 = np.zeros(n_bonds, dtype=int)
        map_atom2 = np.zeros(n_bonds, dtype=int)
        map_param = np.zeros(n_bonds, dtype=int)
        for i in range(n_bonds):
            idx1 = data.bonds[i].atom1
            idx2 = data.bonds[i].atom2
            type1 = data.atomType[data.atoms[idx1]]
            type2 = data.atomType[data.atoms[idx2]]
            ifFound = False
            for ii in range(len(self.types)):
                if (type1 in self.types[ii][0] and type2 in self.types[ii][1]) or (
                    type1 in self.types[ii][1] and type2 in self.types[ii][0]
                ):
                    map_atom1[i] = idx1
                    map_atom2[i] = idx2
                    map_param[i] = ii
                    ifFound = True
                    break
            if not ifFound:
                raise BaseException("No parameter for bond %i - %i" % (idx1, idx2))

        bforce = HarmonicBondJaxForce(map_atom1, map_atom2, map_param)

        def potential_fn(positions, box, pairs, params):
            return bforce.get_energy(
                positions, box, pairs, params["k"], params["length"]
            )

        self._jaxPotential = potential_fn
        # self._top_data = data

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        # generate xml force field file
        finfo = XMLNodeInfo("HarmonicBondForce")
        for ntype in range(len(self.types)):
            binfo = {}
            k1, v1 = self.typetexts[ntype][0]
            k2, v2 = self.typetexts[ntype][1]
            binfo[k1] = v1
            binfo[k2] = v2
            for key in self.params.keys():
                binfo[key] = "%.8f" % self.params[key][ntype]
            finfo.addElement("Bond", binfo)
        return finfo

parseElement(element, hamiltonian) staticmethod

parse section in XML file

example

<\HarmonicBondForce>

Source code in dmff/api.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
@staticmethod
def parseElement(element, hamiltonian):

    r"""parse <HarmonicBondForce> section in XML file

    example:

      <HarmonicBondForce>
        <Bond type1="ow" type2="hw" length="0.09572000000000001" k="462750.3999999999"/>
        <Bond type1="hw" type2="hw" length="0.15136000000000002" k="462750.3999999999"/>
      <\HarmonicBondForce>

    """
    existing = [f for f in hamiltonian._forces if isinstance(f, HarmonicBondJaxGenerator)]
    if len(existing) == 0:
        generator = HarmonicBondJaxGenerator(hamiltonian)
        hamiltonian.registerGenerator(generator)
    else:
        generator = existing[0]
    for bondtype in element.findall("Bond"):
        generator.registerBondType(bondtype.attrib)

NonbondJaxGenerator

Source code in dmff/api.py
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
class NonbondJaxGenerator:

    SCALETOL = 1e-3

    def __init__(self, hamiltionian, coulomb14scale, lj14scale):

        self.ff = hamiltionian
        self.coulomb14scale = coulomb14scale
        self.lj14scale = lj14scale
        # self.params = app.ForceField._AtomTypeParameters(hamiltionian, 'NonbondedForce', 'Atom', ('charge', 'sigma', 'epsilon'))
        self.params = {
            "sigma": [],
            "epsilon": [],
            "epsfix": [],
            "sigfix": [],
            "charge": [],
            "coulomb14scale": [coulomb14scale],
            "lj14scale": [lj14scale],
        }
        self.types = []
        self.useAttributeFromResidue = []
        self.name = "Nonbond"


    def registerAtom(self, atom):
        # use types in nb cards or resname+atomname in residue cards
        types = self.ff._findAtomTypes(atom, 1)[0]
        if None not in types:
            self.types.append(types)

        for key in ["sigma", "epsilon", "charge"]:
            if key not in self.useAttributeFromResidue:
                self.params[key].append(float(atom[key]))

    @staticmethod
    def parseElement(element, ff):
        """parse <NonbondedForce> section in XML file

        example:

          <NonbondedForce coulomb14scale="0.8333333333333334" lj14scale="0.5">
              <UseAttributeFromResidue name="charge"/>
              <Atom type="c" sigma="0.3315212309943831" epsilon="0.4133792"/>
          </NonbondedForce>

        """
        existing = [f for f in ff._forces if isinstance(f, NonbondJaxGenerator)]

        if len(existing) == 0:
            generator = NonbondJaxGenerator(
                ff,
                float(element.attrib["coulomb14scale"]),
                float(element.attrib["lj14scale"]),
                # useDispersionCorrection
            )
            ff.registerGenerator(generator)
        else:
            generator = existing[0]

            if (abs(generator.coulomb14scale - float(element.attrib['coulomb14scale'])) > NonbondJaxGenerator.SCALETOL
                or abs(generator.lj14scale - float(element.attrib['lj14scale'])) > NonbondJaxGenerator.SCALETOL
            ):
                raise ValueError('Found multiple NonbondedForce tags with different 1-4 scales')
        excludedParams = [
            node.attrib["name"] for node in element.findall("UseAttributeFromResidue")
        ]
        for eprm in excludedParams:
            if eprm not in generator.useAttributeFromResidue:
                generator.useAttributeFromResidue.append(eprm)
        for atom in element.findall("Atom"):
            generator.registerAtom(atom.attrib)

        generator.n_atoms = len(element.findall("Atom"))

    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {
            app.NoCutoff: "NoCutoff",
            app.CutoffPeriodic: "CutoffPeriodic",
            app.CutoffNonPeriodic: "CutoffNonPeriodic",
            app.PME: "PME",
        }
        if nonbondedMethod not in methodMap:
            raise ValueError("Illegal nonbonded method for NonbondedForce")
        isNoCut = False
        if nonbondedMethod is app.NoCutoff:
            isNoCut = True

        # Jax prms!
        for k in self.params.keys():
            self.params[k] = jnp.array(self.params[k])

        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.params["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.params["lj14scale"][0])

        # Coulomb: only support PME for now
        # set PBC
        if nonbondedMethod not in [app.NoCutoff, app.CutoffNonPeriodic]:
            ifPBC = True
        else:
            ifPBC = False

        # load LJ from types
        map_lj = []
        for atom in data.atoms:
            types = data.atomType[atom]
            ifFound = False
            for ntp, tp in enumerate(self.types):
                if types in tp:
                    map_lj.append(ntp)
                    ifFound = True
                    break
            if not ifFound:
                raise mm.OpenMMException(
                    "AtomType of %s mismatched in NonbondedForce" % (str(atom))
                )
        map_lj = jnp.array(map_lj, dtype=int)

        self.ifChargeFromResidue = False
        if "charge" in self.useAttributeFromResidue:
            # load charge from residue cards
            self.ifChargeFromResidue = True
            chargeinfo = {}
            for atom in data.atoms:
                resname, aname = atom.residue.name, atom.name
                prm = data.atomParameters[atom]
                chargeinfo[resname + "+" + aname] = prm["charge"]
            ckeys = [k for k in chargeinfo.keys()]
            self.params["charge"] = [chargeinfo[k] for k in chargeinfo.keys()]
            chargeidx = {}
            for n, i in enumerate(ckeys):
                chargeidx[i] = n
            map_charge = []
            for na in range(len(data.atoms)):
                key = data.atoms[na].residue.name + "+" + data.atoms[na].name
                if key in chargeidx:
                    map_charge.append(chargeidx[key])
            map_charge = np.array(map_charge, dtype=int)
            self.params["charge"] = jnp.array(self.params["charge"])
        else:
            map_charge = map_lj

        # TODO: implement NBFIX
        map_nbfix = []
        map_nbfix = np.array(map_nbfix, dtype=int).reshape((-1, 2))

        colv_map = build_covalent_map(data, 6)

        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(map_lj)
        map_nbfix = jnp.array(map_nbfix)
        map_charge = jnp.array(map_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,
                colv_map,
                isSwitch=ifSwitch,
                isPBC=ifPBC,
                isNoCut=isNoCut
            )
        else:
            ljforce = LennardJonesFreeEnergyForce(
                r_switch,
                r_cut,
                map_lj,
                map_nbfix,
                colv_map,
                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 = len(self.types)
            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(colv_map > 0, colv_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, colv_map, isPBC=ifPBC)
                if nonbondedMethod is app.NoCutoff:
                    # use NoCutoff
                    coulforce = CoulNoCutoffForce(map_charge, colv_map)
            else:
                coulforce = CoulombPMEForce(r_cut, map_charge, colv_map, kappa, (K1, K2, K3))
        else:
            assert nonbondedMethod is app.PME, "Only PME is supported in free energy calculations"
            coulforce = CoulombPMEFreeEnergyForce(
                r_cut,
                map_charge,
                colv_map,
                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["epsilon"],
                    params["sigma"],
                    params["epsfix"],
                    params["sigfix"],
                    mscales_lj
                )
                coulE = coulenergy(
                    positions, 
                    box, 
                    pairs, 
                    params["charge"], 
                    mscales_coul
                )

                if useDispersionCorrection:
                    ljDispEnergy = ljDispEnergyFn(
                        box, 
                        params['epsilon'], 
                        params['sigma'], 
                        params['epsfix'], 
                        params['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["epsilon"],
                    params["sigma"],
                    params["epsfix"],
                    params["sigfix"],
                    mscales_lj,
                    vdwLambda
                )
                coulE = coulenergy(
                    positions, 
                    box, 
                    pairs, 
                    params["charge"], 
                    mscales_coul,
                    coulLambda
                )

                if useDispersionCorrection:
                    ljDispEnergy = ljDispEnergyFn(
                        box, 
                        params['epsilon'], 
                        params['sigma'], 
                        params['epsfix'], 
                        params['sigfix'],
                        vdwLambda
                    )
                    return ljE + coulE + ljDispEnergy
                else:    
                    return ljE + coulE

            self._jaxPotential = potential_fn

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):

        # <NonbondedForce>
        finfo = XMLNodeInfo("NonbondedForce")
        finfo.addAttribute("coulomb14scale", str(self.coulomb14scale))
        finfo.addAttribute("lj14scale", str(self.lj14scale))

        for atom in range(self.n_atoms):
            info = {
                "type": self.types[atom],
                "charge": self.params["charge"][atom],
                "sigma": self.params["sigma"][atom],
                "epsilon": self.params["epsilon"][atom],
            }
            finfo.addElement("Atom", info)

        return finfo

parseElement(element, ff) staticmethod

parse section in XML file

example

Source code in dmff/api.py
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
@staticmethod
def parseElement(element, ff):
    """parse <NonbondedForce> section in XML file

    example:

      <NonbondedForce coulomb14scale="0.8333333333333334" lj14scale="0.5">
          <UseAttributeFromResidue name="charge"/>
          <Atom type="c" sigma="0.3315212309943831" epsilon="0.4133792"/>
      </NonbondedForce>

    """
    existing = [f for f in ff._forces if isinstance(f, NonbondJaxGenerator)]

    if len(existing) == 0:
        generator = NonbondJaxGenerator(
            ff,
            float(element.attrib["coulomb14scale"]),
            float(element.attrib["lj14scale"]),
            # useDispersionCorrection
        )
        ff.registerGenerator(generator)
    else:
        generator = existing[0]

        if (abs(generator.coulomb14scale - float(element.attrib['coulomb14scale'])) > NonbondJaxGenerator.SCALETOL
            or abs(generator.lj14scale - float(element.attrib['lj14scale'])) > NonbondJaxGenerator.SCALETOL
        ):
            raise ValueError('Found multiple NonbondedForce tags with different 1-4 scales')
    excludedParams = [
        node.attrib["name"] for node in element.findall("UseAttributeFromResidue")
    ]
    for eprm in excludedParams:
        if eprm not in generator.useAttributeFromResidue:
            generator.useAttributeFromResidue.append(eprm)
    for atom in element.findall("Atom"):
        generator.registerAtom(atom.attrib)

    generator.n_atoms = len(element.findall("Atom"))

PeriodicTorsion

Bases: object

A PeriodicTorsion records the information for a periodic torsion definition.

Source code in dmff/api.py
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
class PeriodicTorsion(object):
    """A PeriodicTorsion records the information for a periodic torsion definition."""

    def __init__(self, types):
        self.types1 = types[0]
        self.types2 = types[1]
        self.types3 = types[2]
        self.types4 = types[3]
        self.periodicity = []
        self.phase = []
        self.k = []
        self.points = []
        self.ordering = "default"

PeriodicTorsionJaxGenerator

Bases: object

A PeriodicTorsionGenerator constructs a PeriodicTorsionForce.

Source code in dmff/api.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
class PeriodicTorsionJaxGenerator(object):
    """A PeriodicTorsionGenerator constructs a PeriodicTorsionForce."""

    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.p_types = []
        self.i_types = []
        self.params = {
            "k1_p": [],
            "psi1_p": [],
            "k2_p": [],
            "psi2_p": [],
            "k3_p": [],
            "psi3_p": [],
            "k4_p": [],
            "psi4_p": [],
            "k1_i": [],
            "psi1_i": [],
            "k2_i": [],
            "psi2_i": [],
            "k3_i": [],
            "psi3_i": [],
            "k4_i": [],
            "psi4_i": [],
        }
        self.proper = []
        self.improper = []
        self.propersForAtomType = defaultdict(set)
        self.n_proper = 0
        self.n_improper = 0
        self.name = "PeriodicTorsion"

    def registerProperTorsion(self, parameters):
        torsion = _parseTorsion(self.ff, parameters)
        if torsion is not None:
            index = len(self.proper)
            self.proper.append(torsion)
            for t in torsion.types2:
                self.propersForAtomType[t].add(index)
            for t in torsion.types3:
                self.propersForAtomType[t].add(index)

    def registerImproperTorsion(self, parameters, ordering="default"):
        torsion = _parseTorsion(self.ff, parameters)
        if torsion is not None:
            if ordering in ["default", "charmm", "amber"]:
                torsion.ordering = ordering
            else:
                raise ValueError(
                    "Illegal ordering type %s for improper torsion %s"
                    % (ordering, torsion)
                )
            self.improper.append(torsion)

    @staticmethod
    def parseElement(element, ff):
        """parse <PeriodicTorsionForce> section in XML file

        example:

          <PeriodicTorsionForce ordering="amber">
            <Proper type1="" type2="c" type3="c" type4="" periodicity1="2" phase1="3.141592653589793" k1="1.2552"/>
            <Improper type1="" type2="c" type3="c1" type4="" periodicity1="2" phase1="3.141592653589793" k1="0.0"/>
        </PeriodicTorsionForce>

        """
        existing = [f for f in ff._forces if isinstance(f, PeriodicTorsionJaxGenerator)]
        if len(existing) == 0:
            generator = PeriodicTorsionJaxGenerator(ff)
            ff.registerGenerator(generator)
        else:
            generator = existing[0]
        for torsion in element.findall("Proper"):
            generator.registerProperTorsion(torsion.attrib)
        for torsion in element.findall("Improper"):
            if "ordering" in element.attrib:
                generator.registerImproperTorsion(
                    torsion.attrib, element.attrib["ordering"]
                )
            else:
                generator.registerImproperTorsion(torsion.attrib)

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):

        # pump proper params
        for tor in self.proper:
            for i in range(len(tor.phase)):
                if tor.periodicity[i] == 1:
                    self.params["k1_p"].append(tor.k[i])
                    self.params["psi1_p"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k1_p"]) - 1
                if tor.periodicity[i] == 2:
                    self.params["k2_p"].append(tor.k[i])
                    self.params["psi2_p"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k2_p"]) - 1
                if tor.periodicity[i] == 3:
                    self.params["k3_p"].append(tor.k[i])
                    self.params["psi3_p"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k3_p"]) - 1
                if tor.periodicity[i] == 4:
                    self.params["k4_p"].append(tor.k[i])
                    self.params["psi4_p"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k4_p"]) - 1
        # pump impr params
        for tor in self.improper:
            for i in range(len(tor.phase)):
                if tor.periodicity[i] == 1:
                    self.params["k1_i"].append(tor.k[i])
                    self.params["psi1_i"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k1_i"]) - 1
                if tor.periodicity[i] == 2:
                    self.params["k2_i"].append(tor.k[i])
                    self.params["psi2_i"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k2_i"]) - 1
                if tor.periodicity[i] == 3:
                    self.params["k3_i"].append(tor.k[i])
                    self.params["psi3_i"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k3_i"]) - 1
                if tor.periodicity[i] == 4:
                    self.params["k4_i"].append(tor.k[i])
                    self.params["psi4_i"].append(tor.phase[i])
                    tor.points[i] = len(self.params["k4_i"]) - 1

        # jax it!
        for k in self.params.keys():
            self.params[k] = jnp.array(self.params[k])

        map_a1_1_p = []
        map_a2_1_p = []
        map_a3_1_p = []
        map_a4_1_p = []
        prm1_p = []
        map_a1_2_p = []
        map_a2_2_p = []
        map_a3_2_p = []
        map_a4_2_p = []
        prm2_p = []
        map_a1_3_p = []
        map_a2_3_p = []
        map_a3_3_p = []
        map_a4_3_p = []
        prm3_p = []
        map_a1_4_p = []
        map_a2_4_p = []
        map_a3_4_p = []
        map_a4_4_p = []
        prm4_p = []

        wildcard = self.ff._atomClasses[""]
        proper_cache = {}
        for torsion in data.propers:
            type1, type2, type3, type4 = [
                data.atomType[data.atoms[torsion[i]]] for i in range(4)
            ]
            sig = (type1, type2, type3, type4)
            sig = frozenset((sig, sig[::-1]))
            match = proper_cache.get(sig, None)
            if match == -1:
                continue
            if match is None:
                for index in self.propersForAtomType[type2]:
                    tordef = self.proper[index]
                    types1 = tordef.types1
                    types2 = tordef.types2
                    types3 = tordef.types3
                    types4 = tordef.types4
                    if (
                        type2 in types2
                        and type3 in types3
                        and type4 in types4
                        and type1 in types1
                    ) or (
                        type2 in types3
                        and type3 in types2
                        and type4 in types1
                        and type1 in types4
                    ):
                        hasWildcard = wildcard in (types1, types2, types3, types4)
                        if (
                            match is None or not hasWildcard
                        ):  # Prefer specific definitions over ones with wildcards
                            match = tordef
                        if not hasWildcard:
                            break
                if match is None:
                    proper_cache[sig] = -1
                else:
                    proper_cache[sig] = match
            if match is not None:
                for i in range(len(match.phase)):
                    if match.k[i] != 0:
                        if match.periodicity[i] == 1:
                            map_a1_1_p.append(torsion[0])
                            map_a2_1_p.append(torsion[1])
                            map_a3_1_p.append(torsion[2])
                            map_a4_1_p.append(torsion[3])
                            prm1_p.append(match.points[i])
                            assert match.points[i] != -1
                        if match.periodicity[i] == 2:
                            map_a1_2_p.append(torsion[0])
                            map_a2_2_p.append(torsion[1])
                            map_a3_2_p.append(torsion[2])
                            map_a4_2_p.append(torsion[3])
                            prm2_p.append(match.points[i])
                            assert match.points[i] != -1
                        if match.periodicity[i] == 3:
                            map_a1_3_p.append(torsion[0])
                            map_a2_3_p.append(torsion[1])
                            map_a3_3_p.append(torsion[2])
                            map_a4_3_p.append(torsion[3])
                            prm3_p.append(match.points[i])
                            assert match.points[i] != -1
                        if match.periodicity[i] == 4:
                            map_a1_4_p.append(torsion[0])
                            map_a2_4_p.append(torsion[1])
                            map_a3_4_p.append(torsion[2])
                            map_a4_4_p.append(torsion[3])
                            prm4_p.append(match.points[i])
                            assert match.points[i] != -1

        map_a1_1_i = []
        map_a2_1_i = []
        map_a3_1_i = []
        map_a4_1_i = []
        prm1_i = []
        map_a1_2_i = []
        map_a2_2_i = []
        map_a3_2_i = []
        map_a4_2_i = []
        prm2_i = []
        map_a1_3_i = []
        map_a2_3_i = []
        map_a3_3_i = []
        map_a4_3_i = []
        prm3_i = []
        map_a1_4_i = []
        map_a2_4_i = []
        map_a3_4_i = []
        map_a4_4_i = []
        prm4_i = []

        impr_cache = {}
        for torsion in data.impropers:
            t1, t2, t3, t4 = [data.atomType[data.atoms[torsion[i]]] for i in range(4)]
            sig = (t1, t2, t3, t4)
            match = impr_cache.get(sig, None)
            if match == -1:
                # Previously checked, and doesn't appear in the database
                continue
            elif match:
                i1, i2, i3, i4, tordef = match
                a1, a2, a3, a4 = (torsion[i] for i in (i1, i2, i3, i4))
                match = (a1, a2, a3, a4, tordef)
            if match is None:
                match = _matchImproper(data, torsion, self)
                if match is not None:
                    order = match[:4]
                    i1, i2, i3, i4 = tuple(torsion.index(a) for a in order)
                    impr_cache[sig] = (i1, i2, i3, i4, match[-1])
                else:
                    impr_cache[sig] = -1
            if match is not None:
                (a1, a2, a3, a4, tordef) = match
                for i in range(len(tordef.phase)):
                    if tordef.k[i] != 0:
                        if tordef.periodicity[i] == 1:
                            map_a1_1_i.append(a1)
                            map_a2_1_i.append(a2)
                            map_a3_1_i.append(a3)
                            map_a4_1_i.append(a4)
                            prm1_i.append(tordef.points[i])
                            assert tordef.points[i] != -1
                        if tordef.periodicity[i] == 2:
                            map_a1_2_i.append(a1)
                            map_a2_2_i.append(a2)
                            map_a3_2_i.append(a3)
                            map_a4_2_i.append(a4)
                            prm2_i.append(tordef.points[i])
                            assert tordef.points[i] != -1
                        if tordef.periodicity[i] == 3:
                            map_a1_3_i.append(a1)
                            map_a2_3_i.append(a2)
                            map_a3_3_i.append(a3)
                            map_a4_3_i.append(a4)
                            prm3_i.append(tordef.points[i])
                            assert tordef.points[i] != -1
                        if tordef.periodicity[i] == 4:
                            map_a1_4_i.append(a1)
                            map_a2_4_i.append(a2)
                            map_a3_4_i.append(a3)
                            map_a4_4_i.append(a4)
                            prm4_i.append(tordef.points[i])
                            assert tordef.points[i] != -1

        map_a1_1_p = np.array(map_a1_1_p, dtype=int)
        map_a2_1_p = np.array(map_a2_1_p, dtype=int)
        map_a3_1_p = np.array(map_a3_1_p, dtype=int)
        map_a4_1_p = np.array(map_a4_1_p, dtype=int)
        map_a1_2_p = np.array(map_a1_2_p, dtype=int)
        map_a2_2_p = np.array(map_a2_2_p, dtype=int)
        map_a3_2_p = np.array(map_a3_2_p, dtype=int)
        map_a4_2_p = np.array(map_a4_2_p, dtype=int)
        map_a1_3_p = np.array(map_a1_3_p, dtype=int)
        map_a2_3_p = np.array(map_a2_3_p, dtype=int)
        map_a3_3_p = np.array(map_a3_3_p, dtype=int)
        map_a4_3_p = np.array(map_a4_3_p, dtype=int)
        map_a1_4_p = np.array(map_a1_4_p, dtype=int)
        map_a2_4_p = np.array(map_a2_4_p, dtype=int)
        map_a3_4_p = np.array(map_a3_4_p, dtype=int)
        map_a4_4_p = np.array(map_a4_4_p, dtype=int)
        prm1_p = np.array(prm1_p, dtype=int)
        prm2_p = np.array(prm2_p, dtype=int)
        prm3_p = np.array(prm3_p, dtype=int)
        prm4_p = np.array(prm4_p, dtype=int)

        map_a1_1_i = np.array(map_a1_1_i, dtype=int)
        map_a2_1_i = np.array(map_a2_1_i, dtype=int)
        map_a3_1_i = np.array(map_a3_1_i, dtype=int)
        map_a4_1_i = np.array(map_a4_1_i, dtype=int)
        map_a1_2_i = np.array(map_a1_2_i, dtype=int)
        map_a2_2_i = np.array(map_a2_2_i, dtype=int)
        map_a3_2_i = np.array(map_a3_2_i, dtype=int)
        map_a4_2_i = np.array(map_a4_2_i, dtype=int)
        map_a1_3_i = np.array(map_a1_3_i, dtype=int)
        map_a2_3_i = np.array(map_a2_3_i, dtype=int)
        map_a3_3_i = np.array(map_a3_3_i, dtype=int)
        map_a4_3_i = np.array(map_a4_3_i, dtype=int)
        map_a1_4_i = np.array(map_a1_4_i, dtype=int)
        map_a2_4_i = np.array(map_a2_4_i, dtype=int)
        map_a3_4_i = np.array(map_a3_4_i, dtype=int)
        map_a4_4_i = np.array(map_a4_4_i, dtype=int)
        prm1_i = np.array(prm1_i, dtype=int)
        prm2_i = np.array(prm2_i, dtype=int)
        prm3_i = np.array(prm3_i, dtype=int)
        prm4_i = np.array(prm4_i, dtype=int)

        prop1 = PeriodicTorsionJaxForce(
            map_a1_1_p, map_a2_1_p, map_a3_1_p, map_a4_1_p, prm1_p, 1
        )
        prop2 = PeriodicTorsionJaxForce(
            map_a1_2_p, map_a2_2_p, map_a3_2_p, map_a4_2_p, prm2_p, 2
        )
        prop3 = PeriodicTorsionJaxForce(
            map_a1_3_p, map_a2_3_p, map_a3_3_p, map_a4_3_p, prm3_p, 3
        )
        prop4 = PeriodicTorsionJaxForce(
            map_a1_4_p, map_a2_4_p, map_a3_4_p, map_a4_4_p, prm4_p, 4
        )

        impr1 = PeriodicTorsionJaxForce(
            map_a1_1_i, map_a2_1_i, map_a3_1_i, map_a4_1_i, prm1_i, 1
        )
        impr2 = PeriodicTorsionJaxForce(
            map_a1_2_i, map_a2_2_i, map_a3_2_i, map_a4_2_i, prm2_i, 2
        )
        impr3 = PeriodicTorsionJaxForce(
            map_a1_3_i, map_a2_3_i, map_a3_3_i, map_a4_3_i, prm3_i, 3
        )
        impr4 = PeriodicTorsionJaxForce(
            map_a1_4_i, map_a2_4_i, map_a3_4_i, map_a4_4_i, prm4_i, 4
        )

        def potential_fn(positions, box, pairs, params):
            p1e = prop1.get_energy(
                positions, box, pairs, params["k1_p"], params["psi1_p"]
            )
            p2e = prop2.get_energy(
                positions, box, pairs, params["k2_p"], params["psi2_p"]
            )
            p3e = prop3.get_energy(
                positions, box, pairs, params["k3_p"], params["psi3_p"]
            )
            p4e = prop4.get_energy(
                positions, box, pairs, params["k4_p"], params["psi4_p"]
            )

            i1e = impr1.get_energy(
                positions, box, pairs, params["k1_i"], params["psi1_i"]
            )
            i2e = impr2.get_energy(
                positions, box, pairs, params["k2_i"], params["psi2_i"]
            )
            i3e = impr3.get_energy(
                positions, box, pairs, params["k3_i"], params["psi3_i"]
            )
            i4e = impr4.get_energy(
                positions, box, pairs, params["k4_i"], params["psi4_i"]
            )

            return p1e + p2e + p3e + p4e + i1e + i2e + i3e + i4e

        self._jaxPotential = potential_fn
        # self._top_data = data

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        params = self.params
        # generate xml force field file
        finfo = XMLNodeInfo("PeriodicTorsionForce")
        for i in range(len(self.proper)):
            proper = self.proper[i]

            finfo.addElement(
                "Proper",
                {
                    "type1": proper.types1,
                    "type2": proper.types2,
                    "type3": proper.types3,
                    "type4": proper.types4,
                    "periodicity1": proper.periodicity[0],
                    "phase1": params["psi1_p"][i],
                    "k1": params["k1_p"][i],
                    "periodicity2": proper.periodicity[1],
                    "phase2": params["psi2_p"][i],
                    "k2": params["k2_p"][i],
                    "periodicity3": proper.periodicity[2],
                    "phase3": params["psi3_p"][i],
                    "k3": params["k3_p"][i],
                    "periodicity4": proper.periodicity[3],
                    "phase4": params["psi4_p"][i],
                    "k4": params["k4_p"][i],
                },
            )

        for i in range(len(self.improper)):

            improper = self.improper[i]

            finfo.addElement(
                "Improper",
                {
                    "type1": improper.types1,
                    "type2": improper.types2,
                    "type3": improper.types3,
                    "type4": improper.types4,
                    "periodicity1": improper.periodicity[0],
                    "phase1": params["psi1_i"][i],
                    "k1": params["k1_i"][i],
                    "periodicity2": proper.periodicity[1],
                    "phase2": params["psi2_i"][i],
                    "k2": params["k2_i"][i],
                    "periodicity3": proper.periodicity[2],
                    "phase3": params["psi3_i"][i],
                    "k3": params["k3_i"][i],
                    "periodicity4": proper.periodicity[3],
                    "phase4": params["psi4_i"][i],
                    "k4": params["k4_i"][i],
                },
            )

        return finfo

parseElement(element, ff) staticmethod

parse section in XML file

example

Source code in dmff/api.py
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
@staticmethod
def parseElement(element, ff):
    """parse <PeriodicTorsionForce> section in XML file

    example:

      <PeriodicTorsionForce ordering="amber">
        <Proper type1="" type2="c" type3="c" type4="" periodicity1="2" phase1="3.141592653589793" k1="1.2552"/>
        <Improper type1="" type2="c" type3="c1" type4="" periodicity1="2" phase1="3.141592653589793" k1="0.0"/>
    </PeriodicTorsionForce>

    """
    existing = [f for f in ff._forces if isinstance(f, PeriodicTorsionJaxGenerator)]
    if len(existing) == 0:
        generator = PeriodicTorsionJaxGenerator(ff)
        ff.registerGenerator(generator)
    else:
        generator = existing[0]
    for torsion in element.findall("Proper"):
        generator.registerProperTorsion(torsion.attrib)
    for torsion in element.findall("Improper"):
        if "ordering" in element.attrib:
            generator.registerImproperTorsion(
                torsion.attrib, element.attrib["ordering"]
            )
        else:
            generator.registerImproperTorsion(torsion.attrib)

QqTtDampingGenerator

This one calculates the tang-tonnies damping of charge-charge interaction E = \sum_ij exp(-Br)(1+Br)q_i*q_j/r

Source code in dmff/api.py
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
class QqTtDampingGenerator:
    r"""
    This one calculates the tang-tonnies damping of charge-charge interaction
    E = \sum_ij exp(-B*r)*(1+B*r)*q_i*q_j/r
    """

    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.params = {
            "B": [],
            "Q": [],
        }
        self._jaxPotential = None
        self.types = []
        self.name = "QqTtDamping"

    def registerAtomType(self, atom):
        self.types.append(atom["type"])
        self.params["B"].append(float(atom["B"]))
        self.params["Q"].append(float(atom["Q"]))

    @staticmethod
    def parseElement(element, hamiltonian):
        generator = QqTtDampingGenerator(hamiltonian)
        hamiltonian.registerGenerator(generator)
        # covalent scales
        mScales = []
        for i in range(2, 7):
            mScales.append(float(element.attrib["mScale1%d" % i]))
        mScales.append(1.0)
        generator.params["mScales"] = mScales
        for atomtype in element.findall("Atom"):
            generator.registerAtomType(atomtype.attrib)
        # jax it!
        for k in generator.params.keys():
            generator.params[k] = jnp.array(generator.params[k])
        generator.types = np.array(generator.types)

    # on working
    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):

        n_atoms = len(data.atoms)
        # build index map
        map_atomtype = np.zeros(n_atoms, dtype=int)
        for i in range(n_atoms):
            atype = data.atomType[data.atoms[i]]
            map_atomtype[i] = np.where(self.types == atype)[0][0]
        self.map_atomtype = map_atomtype
        # build covalent map
        covalent_map = build_covalent_map(data, 6)

        pot_fn_sr = generate_pairwise_interaction(
            TT_damping_qq_kernel, covalent_map, static_args={}
        )

        def potential_fn(positions, box, pairs, params):
            mScales = params["mScales"]
            b_list = params["B"][map_atomtype] / 10  # convert to A^-1
            q_list = params["Q"][map_atomtype]

            E_sr = pot_fn_sr(positions, box, pairs, mScales, b_list, q_list)
            return E_sr

        self._jaxPotential = potential_fn
        # self._top_data = data

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        # generate xml force field file
        pass

SlaterDampingGenerator

This one computes the slater-type damping function for c6/c8/c10 dispersion E = \sum_ij (f6-1)c6/r6 + (f8-1)c8/r8 + (f10-1)c10/r10 fn = f_tt(x, n) x = br - (2br2 + 3br) / (br2 + 3br + 3)

Source code in dmff/api.py
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
class SlaterDampingGenerator:
    r"""
    This one computes the slater-type damping function for c6/c8/c10 dispersion
    E = \sum_ij (f6-1)*c6/r6 + (f8-1)*c8/r8 + (f10-1)*c10/r10
    fn = f_tt(x, n)
    x = br - (2*br2 + 3*br) / (br2 + 3*br + 3)
    """

    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.params = {
            "B": [],
            "C6": [],
            "C8": [],
            "C10": [],
        }
        self._jaxPotential = None
        self.types = []
        self.name = "SlaterDamping"

    def registerAtomType(self, atom):
        self.types.append(atom["type"])
        self.params["B"].append(float(atom["B"]))
        self.params["C6"].append(float(atom["C6"]))
        self.params["C8"].append(float(atom["C8"]))
        self.params["C10"].append(float(atom["C10"]))

    @staticmethod
    def parseElement(element, hamiltonian):
        generator = SlaterDampingGenerator(hamiltonian)
        hamiltonian.registerGenerator(generator)
        # covalent scales
        mScales = []
        for i in range(2, 7):
            mScales.append(float(element.attrib["mScale1%d" % i]))
        mScales.append(1.0)
        generator.params["mScales"] = mScales
        for atomtype in element.findall("Atom"):
            generator.registerAtomType(atomtype.attrib)
        # jax it!
        for k in generator.params.keys():
            generator.params[k] = jnp.array(generator.params[k])
        generator.types = np.array(generator.types)

    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):

        n_atoms = len(data.atoms)
        # build index map
        map_atomtype = np.zeros(n_atoms, dtype=int)
        for i in range(n_atoms):
            atype = data.atomType[data.atoms[i]]
            map_atomtype[i] = np.where(self.types == atype)[0][0]
        self.map_atomtype = map_atomtype
        # build covalent map
        covalent_map = build_covalent_map(data, 6)

        # WORKING
        pot_fn_sr = generate_pairwise_interaction(
            slater_disp_damping_kernel, covalent_map, static_args={}
        )

        def potential_fn(positions, box, pairs, params):
            mScales = params["mScales"]
            b_list = params["B"][map_atomtype] / 10  # convert to A^-1
            c6_list = jnp.sqrt(params["C6"][map_atomtype] * 1e6)  # to kj/mol * A**6
            c8_list = jnp.sqrt(params["C8"][map_atomtype] * 1e8)
            c10_list = jnp.sqrt(params["C10"][map_atomtype] * 1e10)
            E_sr = pot_fn_sr(
                positions, box, pairs, mScales, b_list, c6_list, c8_list, c10_list
            )
            return E_sr

        self._jaxPotential = potential_fn
        # self._top_data = data

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        # generate xml force field file
        pass

SlaterExGenerator

This one computes the Slater-ISA type exchange interaction u = \sum_ij A * (1/3*(Br)^2 + Br + 1)

Source code in dmff/api.py
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
class SlaterExGenerator:
    r"""
    This one computes the Slater-ISA type exchange interaction
    u = \sum_ij A * (1/3*(Br)^2 + Br + 1)
    """

    def __init__(self, hamiltonian):
        self.ff = hamiltonian
        self.params = {
            "A": [],
            "B": [],
        }
        self._jaxPotential = None
        self.types = []
        self.name = "SlaterEx"

    def registerAtomType(self, atom):
        self.types.append(atom["type"])
        self.params["A"].append(float(atom["A"]))
        self.params["B"].append(float(atom["B"]))

    @staticmethod
    def parseElement(element, hamiltonian):
        generator = SlaterExGenerator(hamiltonian)
        hamiltonian.registerGenerator(generator)
        # covalent scales
        mScales = []
        for i in range(2, 7):
            mScales.append(float(element.attrib["mScale1%d" % i]))
        mScales.append(1.0)
        generator.params["mScales"] = mScales
        for atomtype in element.findall("Atom"):
            generator.registerAtomType(atomtype.attrib)
        # jax it!
        for k in generator.params.keys():
            generator.params[k] = jnp.array(generator.params[k])
        generator.types = np.array(generator.types)

    def createForce(self, system, data, nonbondedMethod, nonbondedCutoff, args):

        n_atoms = len(data.atoms)
        # build index map
        map_atomtype = np.zeros(n_atoms, dtype=int)
        for i in range(n_atoms):
            atype = data.atomType[data.atoms[i]]
            map_atomtype[i] = np.where(self.types == atype)[0][0]
        self.map_atomtype = map_atomtype
        # build covalent map
        covalent_map = build_covalent_map(data, 6)

        pot_fn_sr = generate_pairwise_interaction(
            slater_sr_kernel, covalent_map, static_args={}
        )

        def potential_fn(positions, box, pairs, params):
            mScales = params["mScales"]
            a_list = params["A"][map_atomtype]
            b_list = params["B"][map_atomtype] / 10  # nm^-1 to A^-1

            return pot_fn_sr(positions, box, pairs, mScales, a_list, b_list)

        self._jaxPotential = potential_fn
        # self._top_data = data

    def getJaxPotential(self):
        return self._jaxPotential

    def renderXML(self):
        # generate xml force field file
        pass

XMLNodeInfo

Source code in dmff/api.py
 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
class XMLNodeInfo:
    @staticmethod
    def to_str(value) -> str:
        """convert value to string if it can"""
        if isinstance(value, str):
            return value
        elif isinstance(value, (jnp.ndarray, np.ndarray)):
            if value.ndim == 0:
                return str(value)
            else:
                return str(value[0])
        elif isinstance(value, list):
            return value[0]  # strip [] of value
        else:
            return str(value)

    class XMLElementInfo:
        def __init__(self, name):
            self.name = name
            self.attributes = {}

        def addAttribute(self, key, value):
            self.attributes[key] = XMLNodeInfo.to_str(value)

        def __repr__(self):
            return f'<{self.name} {" ".join([f"{k}={v}" for k, v in self.attributes.items()])}>'

        def __getitem__(self, name):
            return self.attributes[name]

    def __init__(self, name):
        self.name = name
        self.attributes = {}
        self.elements = []

    def __getitem__(self, name):
        if isinstance(name, str):
            return self.attributes[name]
        elif isinstance(name, int):
            return self.elements[name]

    def addAttribute(self, key, value):
        self.attributes[key] = XMLNodeInfo.to_str(value)

    def addElement(self, name, info):
        element = self.XMLElementInfo(name)
        for k, v in info.items():
            element.addAttribute(k, v)
        self.elements.append(element)

    def modResidue(self, residue, atom, key, value):
        pass

    def __repr__(self):
        # tricy string formatting
        left = f'<{self.name} {" ".join([f"{k}={v}" for k, v in self.attributes.items()])}> \n\t'
        right = f"<\\{self.name}>"
        content = "\n\t".join([repr(e) for e in self.elements])
        return left + content + "\n" + right

to_str(value) staticmethod

convert value to string if it can

Source code in dmff/api.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@staticmethod
def to_str(value) -> str:
    """convert value to string if it can"""
    if isinstance(value, str):
        return value
    elif isinstance(value, (jnp.ndarray, np.ndarray)):
        if value.ndim == 0:
            return str(value)
        else:
            return str(value[0])
    elif isinstance(value, list):
        return value[0]  # strip [] of value
    else:
        return str(value)