MolGNNForce

Source code in dmff/sgnn/gnn.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
class MolGNNForce:

    def __init__(self,
                 G,
                 n_layers=(3, 2),
                 sizes=[(40, 20, 20), (20, 10)],
                 nn=1,
                 sigma=162.13039087945623,
                 mu=117.41975505778706,
                 seed=12345):
        """ Constructor for MolGNNForce

        Parameters
        ----------
        G: TopGraph object
            The topological graph object, created using dmff.sgnn.graph.TopGraph
        n_layers: int tuple, optional
            Number of hidden layers before and after message passing
            default = (3, 2)
        sizes: [tuple, tuple], optional
            sizes (numbers of hidden neurons) of the network before and after message passing
            default = [(40, 20, 20), (20, 10)]
        nn: int, optional
            size of the subgraphs, i.e., how many neighbors to include around the central bond
            default = 1
        sigma: float, optional
            final scaling factor of the energy.
            default = 162.13039087945623
        mu: float, optional
            a constant shift
            the final total energy would be ${(E_{NN} + \mu) * \sigma}
        seed: int: optional
            random seed used in network initialization
            default = 12345

        """
        self.nn = nn
        self.G = G
        self.G.get_all_subgraphs(nn, typify=True)
        self.G.prepare_subgraph_feature_calc()
        params = OrderedDict()
        key = jax.random.PRNGKey(seed)
        params['w'] = jax.random.uniform(key)
        self.n_layers = n_layers
        self.sizes = sizes
        dim_in = G.n_features
        initializer = jax.nn.initializers.he_uniform()
        for i_nn, n_layers in enumerate(n_layers):
            nn_name = 'fc%d' % i_nn
            params[nn_name + '.weight'] = []
            params[nn_name + '.bias'] = []
            for i_layer in range(n_layers):
                layer_name = nn_name + '.' + '%d' % i_layer
                dim_out = sizes[i_nn][i_layer]
                # params[nn_name+'.weight'].append(jnp.array(np.random.random((dim_out, dim_in))))
                # params[nn_name+'.bias'].append(jnp.array(np.random.random(dim_out)))
                key, subkey = jax.random.split(key)
                params[nn_name + '.weight'].append(
                    initializer(subkey, (dim_out, dim_in)))
                params[nn_name + '.bias'].append(jnp.zeros(dim_out))
                dim_in = dim_out
        key, subkey = jax.random.split(key)
        params['fc_final.weight'] = jnp.array(initializer(subkey, (1, dim_in)))
        key, subkey = jax.random.split(key)
        params['fc_final.bias'] = jax.random.uniform(subkey)
        self.params = params
        self.sigma = sigma
        self.mu = mu

        # generate the forward functions
        @jit_condition(static_argnums=3)
        def forward(positions, box, params, nn):
            features = self.G.calc_subgraph_features(positions, box)

            @jit_condition(static_argnums=())
            @partial(vmap, in_axes=(0, None), out_axes=(0))
            @partial(vmap, in_axes=(0, None), out_axes=(0))
            def fc0(f_in, params):
                f = f_in
                for i in range(self.n_layers[0]):
                    f = jnp.tanh(params['fc0.weight'][i].dot(f) +
                                 params['fc0.bias'][i])
                return f

            @jit_condition(static_argnums=())
            @partial(vmap, in_axes=(0, None), out_axes=(0))
            def fc1(f_in, params):
                f = f_in
                for i in range(self.n_layers[1]):
                    f = jnp.tanh(params['fc1.weight'][i].dot(f) +
                                 params['fc1.bias'][i])
                return f

            @jit_condition(static_argnums=())
            @partial(vmap, in_axes=(0, None), out_axes=(0))
            def fc_final(f_in, params):
                return params['fc_final.weight'].dot(
                    f_in) + params['fc_final.bias']

            # @jit_condition(static_argnums=(3))
            @partial(vmap, in_axes=(0, 0, None, None), out_axes=(0))
            def message_pass(f_in, nb_connect, w, nn):
                if nn == 0:
                    return f_in[0]
                elif nn == 1:
                    nb_connect0 = nb_connect[0:MAX_VALENCE - 1]
                    nb_connect1 = nb_connect[MAX_VALENCE - 1:2 *
                                             (MAX_VALENCE - 1)]
                    nb0 = jnp.sum(nb_connect0)
                    nb1 = jnp.sum(nb_connect1)
                    f = f_in[0] * (1 - jnp.heaviside(nb0, 0)*w - jnp.heaviside(nb1, 0)*w) + \
                        w * nb_connect0.dot(f_in[1:MAX_VALENCE, :]) / jnp.piecewise(nb0, [nb0<1e-5, nb0>=1e-5], [lambda x: jnp.array(1e-5), lambda x: x]) + \
                        w * nb_connect1.dot(f_in[MAX_VALENCE:2*MAX_VALENCE-1, :])/ jnp.piecewise(nb1, [nb1<1e-5, nb1>=1e-5], [lambda x: jnp.array(1e-5), lambda x: x])
                    return f

            features = fc0(features, params)
            features = message_pass(features, self.G.nb_connect, params['w'],
                                    self.G.nn)
            features = fc1(features, params)
            energies = fc_final(features, params)

            return self.G.weights.dot(energies)[0] * self.sigma + self.mu

        self.forward = partial(forward, nn=self.G.nn)
        self.batch_forward = vmap(self.forward,
                                  in_axes=(0, 0, None),
                                  out_axes=(0))

        # provide the get_energy function, to be consistent with the other parts of DMFF
        self.get_energy = self.forward

        return

    def load_params(self, ifn):
        """ Load the network parameters from saved file

        Parameters
        ----------
        ifn: string
            the input file name

        """
        with open(ifn, 'rb') as ifile:
            params = pickle.load(ifile)
        for k in params.keys():
            params[k] = jnp.array(params[k])
        # transform format
        keys = list(params.keys())
        for i_nn in [0, 1]:
            nn_name = 'fc%d' % i_nn
            keys_weight = []
            keys_bias = []
            for k in keys:
                if re.search(nn_name + '.[0-9]+.weight', k) is not None:
                    keys_weight.append(k)
                elif re.search(nn_name + '.[0-9]+.bias', k) is not None:
                    keys_bias.append(k)
            if len(keys_weight) != self.n_layers[i_nn] or len(
                    keys_bias) != self.n_layers[i_nn]:
                sys.exit(
                    'Error while loading GNN params, inconsistent inputs with the GNN structure, check your input!'
                )
            params['%s.weight' % nn_name] = []
            params['%s.bias' % nn_name] = []
            for i_layer in range(self.n_layers[i_nn]):
                k_w = '%s.%d.weight' % (nn_name, i_layer)
                k_b = '%s.%d.bias' % (nn_name, i_layer)
                params['%s.weight' % nn_name].append(params.pop(k_w, None))
                params['%s.bias' % nn_name].append(params.pop(k_b, None))
            # params[nn_name]
        self.params = params
        return

    def save_params(self, ofn):
        """ Save the network parameters to a pickle file

        Parameters
        ----------
        ofn: string
            the output file name

        """
        # transform format
        params = {}
        params['w'] = self.params['w']
        params['fc_final.weight'] = self.params['fc_final.weight']
        params['fc_final.bias'] = self.params['fc_final.bias']
        for i_nn in range(2):
            nn_name = 'fc%d' % i_nn
            for i_layer in range(self.n_layers[i_nn]):
                params[nn_name + '.%d.weight' %
                       i_layer] = self.params[nn_name + '.weight'][i_layer]
                params[nn_name +
                       '.%d.bias' % i_layer] = self.params[nn_name +
                                                           '.bias'][i_layer]
        with open(ofn, 'wb') as ofile:
            pickle.dump(params, ofile)
        return

__init__(G, n_layers=(3, 2), sizes=[(40, 20, 20), (20, 10)], nn=1, sigma=162.13039087945623, mu=117.41975505778706, seed=12345)

Constructor for MolGNNForce

Parameters
TopGraph object

The topological graph object, created using dmff.sgnn.graph.TopGraph

int tuple, optional

Number of hidden layers before and after message passing default = (3, 2)

[tuple, tuple], optional

sizes (numbers of hidden neurons) of the network before and after message passing default = [(40, 20, 20), (20, 10)]

int, optional

size of the subgraphs, i.e., how many neighbors to include around the central bond default = 1

float, optional

final scaling factor of the energy. default = 162.13039087945623

float, optional

a constant shift the final total energy would be ${(E_{NN} + \mu) * \sigma}

int: optional

random seed used in network initialization default = 12345

Source code in dmff/sgnn/gnn.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def __init__(self,
             G,
             n_layers=(3, 2),
             sizes=[(40, 20, 20), (20, 10)],
             nn=1,
             sigma=162.13039087945623,
             mu=117.41975505778706,
             seed=12345):
    """ Constructor for MolGNNForce

    Parameters
    ----------
    G: TopGraph object
        The topological graph object, created using dmff.sgnn.graph.TopGraph
    n_layers: int tuple, optional
        Number of hidden layers before and after message passing
        default = (3, 2)
    sizes: [tuple, tuple], optional
        sizes (numbers of hidden neurons) of the network before and after message passing
        default = [(40, 20, 20), (20, 10)]
    nn: int, optional
        size of the subgraphs, i.e., how many neighbors to include around the central bond
        default = 1
    sigma: float, optional
        final scaling factor of the energy.
        default = 162.13039087945623
    mu: float, optional
        a constant shift
        the final total energy would be ${(E_{NN} + \mu) * \sigma}
    seed: int: optional
        random seed used in network initialization
        default = 12345

    """
    self.nn = nn
    self.G = G
    self.G.get_all_subgraphs(nn, typify=True)
    self.G.prepare_subgraph_feature_calc()
    params = OrderedDict()
    key = jax.random.PRNGKey(seed)
    params['w'] = jax.random.uniform(key)
    self.n_layers = n_layers
    self.sizes = sizes
    dim_in = G.n_features
    initializer = jax.nn.initializers.he_uniform()
    for i_nn, n_layers in enumerate(n_layers):
        nn_name = 'fc%d' % i_nn
        params[nn_name + '.weight'] = []
        params[nn_name + '.bias'] = []
        for i_layer in range(n_layers):
            layer_name = nn_name + '.' + '%d' % i_layer
            dim_out = sizes[i_nn][i_layer]
            # params[nn_name+'.weight'].append(jnp.array(np.random.random((dim_out, dim_in))))
            # params[nn_name+'.bias'].append(jnp.array(np.random.random(dim_out)))
            key, subkey = jax.random.split(key)
            params[nn_name + '.weight'].append(
                initializer(subkey, (dim_out, dim_in)))
            params[nn_name + '.bias'].append(jnp.zeros(dim_out))
            dim_in = dim_out
    key, subkey = jax.random.split(key)
    params['fc_final.weight'] = jnp.array(initializer(subkey, (1, dim_in)))
    key, subkey = jax.random.split(key)
    params['fc_final.bias'] = jax.random.uniform(subkey)
    self.params = params
    self.sigma = sigma
    self.mu = mu

    # generate the forward functions
    @jit_condition(static_argnums=3)
    def forward(positions, box, params, nn):
        features = self.G.calc_subgraph_features(positions, box)

        @jit_condition(static_argnums=())
        @partial(vmap, in_axes=(0, None), out_axes=(0))
        @partial(vmap, in_axes=(0, None), out_axes=(0))
        def fc0(f_in, params):
            f = f_in
            for i in range(self.n_layers[0]):
                f = jnp.tanh(params['fc0.weight'][i].dot(f) +
                             params['fc0.bias'][i])
            return f

        @jit_condition(static_argnums=())
        @partial(vmap, in_axes=(0, None), out_axes=(0))
        def fc1(f_in, params):
            f = f_in
            for i in range(self.n_layers[1]):
                f = jnp.tanh(params['fc1.weight'][i].dot(f) +
                             params['fc1.bias'][i])
            return f

        @jit_condition(static_argnums=())
        @partial(vmap, in_axes=(0, None), out_axes=(0))
        def fc_final(f_in, params):
            return params['fc_final.weight'].dot(
                f_in) + params['fc_final.bias']

        # @jit_condition(static_argnums=(3))
        @partial(vmap, in_axes=(0, 0, None, None), out_axes=(0))
        def message_pass(f_in, nb_connect, w, nn):
            if nn == 0:
                return f_in[0]
            elif nn == 1:
                nb_connect0 = nb_connect[0:MAX_VALENCE - 1]
                nb_connect1 = nb_connect[MAX_VALENCE - 1:2 *
                                         (MAX_VALENCE - 1)]
                nb0 = jnp.sum(nb_connect0)
                nb1 = jnp.sum(nb_connect1)
                f = f_in[0] * (1 - jnp.heaviside(nb0, 0)*w - jnp.heaviside(nb1, 0)*w) + \
                    w * nb_connect0.dot(f_in[1:MAX_VALENCE, :]) / jnp.piecewise(nb0, [nb0<1e-5, nb0>=1e-5], [lambda x: jnp.array(1e-5), lambda x: x]) + \
                    w * nb_connect1.dot(f_in[MAX_VALENCE:2*MAX_VALENCE-1, :])/ jnp.piecewise(nb1, [nb1<1e-5, nb1>=1e-5], [lambda x: jnp.array(1e-5), lambda x: x])
                return f

        features = fc0(features, params)
        features = message_pass(features, self.G.nb_connect, params['w'],
                                self.G.nn)
        features = fc1(features, params)
        energies = fc_final(features, params)

        return self.G.weights.dot(energies)[0] * self.sigma + self.mu

    self.forward = partial(forward, nn=self.G.nn)
    self.batch_forward = vmap(self.forward,
                              in_axes=(0, 0, None),
                              out_axes=(0))

    # provide the get_energy function, to be consistent with the other parts of DMFF
    self.get_energy = self.forward

    return

load_params(ifn)

Load the network parameters from saved file

Parameters
string

the input file name

Source code in dmff/sgnn/gnn.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def load_params(self, ifn):
    """ Load the network parameters from saved file

    Parameters
    ----------
    ifn: string
        the input file name

    """
    with open(ifn, 'rb') as ifile:
        params = pickle.load(ifile)
    for k in params.keys():
        params[k] = jnp.array(params[k])
    # transform format
    keys = list(params.keys())
    for i_nn in [0, 1]:
        nn_name = 'fc%d' % i_nn
        keys_weight = []
        keys_bias = []
        for k in keys:
            if re.search(nn_name + '.[0-9]+.weight', k) is not None:
                keys_weight.append(k)
            elif re.search(nn_name + '.[0-9]+.bias', k) is not None:
                keys_bias.append(k)
        if len(keys_weight) != self.n_layers[i_nn] or len(
                keys_bias) != self.n_layers[i_nn]:
            sys.exit(
                'Error while loading GNN params, inconsistent inputs with the GNN structure, check your input!'
            )
        params['%s.weight' % nn_name] = []
        params['%s.bias' % nn_name] = []
        for i_layer in range(self.n_layers[i_nn]):
            k_w = '%s.%d.weight' % (nn_name, i_layer)
            k_b = '%s.%d.bias' % (nn_name, i_layer)
            params['%s.weight' % nn_name].append(params.pop(k_w, None))
            params['%s.bias' % nn_name].append(params.pop(k_b, None))
        # params[nn_name]
    self.params = params
    return

save_params(ofn)

Save the network parameters to a pickle file

Parameters
string

the output file name

Source code in dmff/sgnn/gnn.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def save_params(self, ofn):
    """ Save the network parameters to a pickle file

    Parameters
    ----------
    ofn: string
        the output file name

    """
    # transform format
    params = {}
    params['w'] = self.params['w']
    params['fc_final.weight'] = self.params['fc_final.weight']
    params['fc_final.bias'] = self.params['fc_final.bias']
    for i_nn in range(2):
        nn_name = 'fc%d' % i_nn
        for i_layer in range(self.n_layers[i_nn]):
            params[nn_name + '.%d.weight' %
                   i_layer] = self.params[nn_name + '.weight'][i_layer]
            params[nn_name +
                   '.%d.bias' % i_layer] = self.params[nn_name +
                                                       '.bias'][i_layer]
    with open(ofn, 'wb') as ofile:
        pickle.dump(params, ofile)
    return