repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
UString | UString-master/src/Models.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
from torch.nn.parameter import Parameter
import torch
import torch.nn as nn
from src.utils import glorot, zeros, uniform, reset
from torch_geometric.utils import remove_self_loops, add_self_loops
import torch_scatter
from torch_scatter import scatter_mean, scatter_max, scatter_add
from torch.autograd import Variable
import torch.nn.functional as F
from src.BayesModels import BayesianLinear
class MessagePassing(torch.nn.Module):
r"""Base class for creating message passing layers
.. math::
\mathbf{x}_i^{\prime} = \gamma_{\mathbf{\Theta}} \left( \mathbf{x}_i,
\square_{j \in \mathcal{N}(i)} \, \phi_{\mathbf{\Theta}}
\left(\mathbf{x}_i, \mathbf{x}_j,\mathbf{e}_{i,j}\right) \right),
where :math:`\square` denotes a differentiable, permutation invariant
function, *e.g.*, sum, mean or max, and :math:`\gamma_{\mathbf{\Theta}}`
and :math:`\phi_{\mathbf{\Theta}}` denote differentiable functions such as
MLPs.
See `here <https://rusty1s.github.io/pytorch_geometric/build/html/notes/
create_gnn.html>`__ for the accompanying tutorial.
"""
def __init__(self, aggr='add'):
super(MessagePassing, self).__init__()
self.message_args = inspect.getargspec(self.message)[0][1:]
self.update_args = inspect.getargspec(self.update)[0][2:]
def propagate(self, aggr, edge_index, **kwargs):
r"""The initial call to start propagating messages.
Takes in an aggregation scheme (:obj:`"add"`, :obj:`"mean"` or
:obj:`"max"`), the edge indices, and all additional data which is
needed to construct messages and to update node embeddings."""
assert aggr in ['add', 'mean', 'max']
kwargs['edge_index'] = edge_index
size = None
message_args = []
for arg in self.message_args:
if arg[-2:] == '_i':
tmp = kwargs[arg[:-2]]
size = tmp.size(0)
message_args.append(tmp[edge_index[0]])
elif arg[-2:] == '_j':
tmp = kwargs[arg[:-2]]
size = tmp.size(0)
message_args.append(tmp[edge_index[1]])
else:
message_args.append(kwargs[arg])
update_args = [kwargs[arg] for arg in self.update_args]
out = self.message(*message_args)
out = scatter_(aggr, out, edge_index[0], dim_size=size)
out = self.update(out, *update_args)
return out
def message(self, x_j): # pragma: no cover
r"""Constructs messages in analogy to :math:`\phi_{\mathbf{\Theta}}`
for each edge in :math:`(i,j) \in \mathcal{E}`.
Can take any argument which was initially passed to :meth:`propagate`.
In addition, features can be lifted to the source node :math:`i` and
target node :math:`j` by appending :obj:`_i` or :obj:`_j` to the
variable name, *.e.g.* :obj:`x_i` and :obj:`x_j`."""
return x_j
def update(self, aggr_out): # pragma: no cover
r"""Updates node embeddings in analogy to
:math:`\gamma_{\mathbf{\Theta}}` for each node
:math:`i \in \mathcal{V}`.
Takes in the output of aggregation as first argument and any argument
which was initially passed to :meth:`propagate`."""
return aggr_out
def scatter_(name, src, index, dim_size=None):
r"""Aggregates all values from the :attr:`src` tensor at the indices
specified in the :attr:`index` tensor along the first dimension.
If multiple indices reference the same location, their contributions
are aggregated according to :attr:`name` (either :obj:`"add"`,
:obj:`"mean"` or :obj:`"max"`).
Args:
name (string): The aggregation to use (:obj:`"add"`, :obj:`"mean"`,
:obj:`"max"`).
src (Tensor): The source tensor.
index (LongTensor): The indices of elements to scatter.
dim_size (int, optional): Automatically create output tensor with size
:attr:`dim_size` in the first dimension. If set to :attr:`None`, a
minimal sized output tensor is returned. (default: :obj:`None`)
:rtype: :class:`Tensor`
"""
assert name in ['add', 'mean', 'max']
op = getattr(torch_scatter, 'scatter_{}'.format(name))
fill_value = -1e38 if name is 'max' else 0
out = op(src, index, 0, None, dim_size, fill_value)
if isinstance(out, tuple):
out = out[0]
if name is 'max':
out[out == fill_value] = 0
return out
# layers
class GCNConv(MessagePassing):
def __init__(self, in_channels, out_channels, act=F.relu, improved=True, bias=False):
super(GCNConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.improved = improved
self.act = act
self.weight = Parameter(torch.Tensor(in_channels, out_channels))
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
glorot(self.weight)
zeros(self.bias)
def add_self_loops(self, edge_index, edge_weight=None, fill_value=1, num_nodes=None):
"""
:param edge_index: 10 x 2 x 171
:param edge_weight: 10 x 171
:param fill_value: 1
:param num_nodes: 20
:return:
"""
batch_size = edge_index.size(0)
num_nodes = edge_index.max().item() + 1 if num_nodes is None else num_nodes
loop_index = torch.arange(0, num_nodes, dtype=torch.long,
device=edge_index.device)
loop_index = loop_index.unsqueeze(0).repeat(2, 1)
loop_index = loop_index.unsqueeze(0).repeat(batch_size, 1, 1) # 10 x 2 x 20
if edge_weight is not None:
assert edge_weight.size(-1) == edge_index.size(-1)
loop_weight = edge_weight.new_full((num_nodes,), fill_value)
loop_weight = loop_weight.unsqueeze(0).repeat(batch_size, 1)
edge_weight = torch.cat([edge_weight, loop_weight], dim=-1)
edge_index = torch.cat([edge_index, loop_index], dim=-1)
return edge_index, edge_weight
def forward(self, x, edge_index, edge_weight=None):
if edge_weight is None:
edge_weight = torch.ones(
(edge_index.size(0), edge_index.size(-1), ), dtype=x.dtype, device=x.device)
# edge_weight = edge_weight.view(-1)
assert edge_weight.size(-1) == edge_index.size(-1)
# for pytorch 1.4, there are two outputs
edge_index, edge_weight = self.add_self_loops(edge_index, edge_weight=edge_weight, num_nodes=x.size(1))
out_batch = []
for i in range(edge_index.size(0)):
row, col = edge_index[i]
deg = scatter_add(edge_weight[i], row, dim=0, dim_size=x.size(1))
deg_inv = deg.pow(-0.5)
deg_inv[deg_inv == float('inf')] = 0
norm = deg_inv[row] * edge_weight[i] * deg_inv[col]
weight = self.weight.to(x.device)
x_w = torch.matmul(x[i], weight)
out = self.propagate('add', edge_index[i], x=x_w, norm=norm)
out_batch.append(self.act(out))
out_batch = torch.stack(out_batch)
return out_batch
def message(self, x_j, norm):
return norm.view(-1, 1) * x_j
def update(self, aggr_out):
if self.bias is not None:
bias = self.bias.to(aggr_out.device)
aggr_out = aggr_out + bias
return aggr_out
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.in_channels,
self.out_channels)
class Graph_GRU_GCN(nn.Module):
def __init__(self, input_size, hidden_size, n_layer, bias=True):
super(Graph_GRU_GCN, self).__init__()
self.hidden_size = hidden_size
self.n_layer = n_layer
# gru weights
self.weight_xz = []
self.weight_hz = []
self.weight_xr = []
self.weight_hr = []
self.weight_xh = []
self.weight_hh = []
for i in range(self.n_layer):
if i == 0:
self.weight_xz.append(GCNConv(input_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_hz.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_xr.append(GCNConv(input_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_hr.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_xh.append(GCNConv(input_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_hh.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
else:
self.weight_xz.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_hz.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_xr.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_hr.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_xh.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
self.weight_hh.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))
def forward(self, inp, edgidx, h, edge_weight=None):
h_out = torch.zeros(h.size())
h_out = h_out.to(inp.device)
for i in range(self.n_layer):
if i == 0:
z_g = torch.sigmoid(self.weight_xz[i](inp, edgidx, edge_weight) + self.weight_hz[i](h[i], edgidx, edge_weight))
r_g = torch.sigmoid(self.weight_xr[i](inp, edgidx, edge_weight) + self.weight_hr[i](h[i], edgidx, edge_weight))
h_tilde_g = torch.tanh(self.weight_xh[i](inp, edgidx, edge_weight) + self.weight_hh[i](r_g * h[i], edgidx, edge_weight))
h_out[i] = z_g * h[i] + (1 - z_g) * h_tilde_g
else:
z_g = torch.sigmoid(self.weight_xz[i](h_out[i - 1], edgidx, edge_weight) + self.weight_hz[i](h[i], edgidx, edge_weight))
r_g = torch.sigmoid(self.weight_xr[i](h_out[i - 1], edgidx, edge_weight) + self.weight_hr[i](h[i], edgidx, edge_weight))
h_tilde_g = torch.tanh(self.weight_xh[i](h_out[i - 1], edgidx, edge_weight) + self.weight_hh[i](r_g * h[i], edgidx, edge_weight))
h_out[i] = z_g * h[i] + (1 - z_g) * h_tilde_g
return h_out
class AccidentPredictor(nn.Module):
def __init__(self, input_dim, output_dim=2, act=torch.relu, dropout=[0, 0]):
super(AccidentPredictor, self).__init__()
self.act = act
self.dropout = dropout
self.dense1 = torch.nn.Linear(input_dim, 64)
self.dense2 = torch.nn.Linear(64, output_dim)
def forward(self, x):
x = F.dropout(x, self.dropout[0], training=self.training)
x = self.act(self.dense1(x))
x = F.dropout(x, self.dropout[1], training=self.training)
x = self.dense2(x)
return x
class SelfAttAggregate(torch.nn.Module):
def __init__(self, agg_dim):
super(SelfAttAggregate, self).__init__()
self.agg_dim = agg_dim
self.weight = nn.Parameter(torch.Tensor(agg_dim, 1)) # (100, 1)
self.softmax = nn.Softmax(dim=-1)
# initialize parameters
import math
torch.nn.init.kaiming_normal_(self.weight, a=math.sqrt(5))
def forward(self, hiddens, avgsum='sum'):
"""
hiddens: (10, 19, 256, 100)
"""
maxpool = torch.max(hiddens, dim=1)[0] # (10, 256, 100)
if avgsum=='sum':
avgpool = torch.sum(hiddens, dim=1)
else:
avgpool = torch.mean(hiddens, dim=1) # (10, 256, 100)
agg_spatial = torch.cat((avgpool, maxpool), dim=1) # (10, 512, 100)
# soft-attention
energy = torch.bmm(agg_spatial.permute([0, 2, 1]), agg_spatial) # (10, 100, 100)
attention = self.softmax(energy)
weighted_feat = torch.bmm(attention, agg_spatial.permute([0, 2, 1])) # (10, 100, 512)
weight = self.weight.unsqueeze(0).repeat([hiddens.size(0), 1, 1])
agg_feature = torch.bmm(weighted_feat.permute([0, 2, 1]), weight) # (10, 512, 1)
return agg_feature.squeeze(dim=-1) # (10, 512)
class BayesianPredictor(nn.Module):
def __init__(self, input_dim, output_dim=2, act=torch.relu, pi=0.5, sigma_1=None, sigma_2=None):
super(BayesianPredictor, self).__init__()
self.act = act
self.l1 = BayesianLinear(input_dim, 64, pi=pi, sigma_1=sigma_1, sigma_2=sigma_2)
self.l2 = BayesianLinear(64, output_dim, pi=pi, sigma_1=sigma_1, sigma_2=sigma_2)
def forward(self, x, sample=False):
x = self.act(self.l1(x, sample))
x = self.l2(x, sample)
return x
def log_prior(self):
return self.l1.log_prior + self.l2.log_prior
def log_variational_posterior(self):
return self.l1.log_variational_posterior + self.l2.log_variational_posterior
def sample_elbo(self, input, out_dim=2, npass=2, testing=False, eval_uncertain=False):
npass = npass + 1 if testing else npass
outputs = torch.zeros(npass, input.size(0), out_dim).to(input.device)
log_priors = torch.zeros(npass).to(input.device)
log_variational_posteriors = torch.zeros(npass).to(input.device)
for i in range(npass):
outputs[i] = self(input, sample=True)
log_priors[i] = self.log_prior()
log_variational_posteriors[i] = self.log_variational_posterior()
if testing:
outputs[npass] = self(input, sample=False)
output = outputs.mean(0)
log_prior = log_priors.mean()
log_variational_posterior = log_variational_posteriors.mean()
# predict the aleatoric and epistemic uncertainties
uncertain_alea = torch.zeros(input.size(0), out_dim, out_dim).to(input.device)
uncertain_epis = torch.zeros(input.size(0), out_dim, out_dim).to(input.device)
if eval_uncertain:
p = F.softmax(outputs, dim=-1) # N x B x C
# compute aleatoric uncertainty
p_diag = torch.diag_embed(p, offset=0, dim1=-2, dim2=-1) # N x B x C x C
p_cov = torch.matmul(p.unsqueeze(-1), p.unsqueeze(-1).permute(0, 1, 3, 2)) # N x B x C x C
uncertain_alea = torch.mean(p_diag - p_cov, dim=0) # B x C x C
# compute epistemic uncertainty
p_bar= torch.mean(p, dim=0) # B x C
p_diff_var = torch.matmul((p-p_bar).unsqueeze(-1), (p-p_bar).unsqueeze(-1).permute(0, 1, 3, 2)) # N x B x C x C
uncertain_epis = torch.mean(p_diff_var, dim=0) # B x C x C
output_dict = {'pred_mean': output,
'log_prior': log_prior,
'log_posterior': log_variational_posterior,
'aleatoric': uncertain_alea,
'epistemic': uncertain_epis}
return output_dict
class UString(nn.Module):
def __init__(self, x_dim, h_dim, z_dim, n_layers=1, n_obj=19, n_frames=100, fps=20.0, with_saa=True, uncertain_ranking=False):
super(UString, self).__init__()
self.x_dim = x_dim
self.h_dim = h_dim # 512 (-->256)
self.z_dim = z_dim # 256 (-->128)
self.n_layers = n_layers
self.n_obj = n_obj
self.n_frames = n_frames
self.fps = fps
self.with_saa = with_saa
self.uncertain_ranking = uncertain_ranking
self.phi_x = nn.Sequential(nn.Linear(x_dim, h_dim), nn.ReLU())
# GCN encoder
self.enc_gcn1 = GCNConv(h_dim + h_dim, h_dim)
self.enc_gcn2 = GCNConv(h_dim + h_dim, z_dim, act=lambda x: x)
# rnn layer
self.rnn = Graph_GRU_GCN(h_dim + h_dim + z_dim, h_dim, n_layers, bias=True)
# BNN decoder
self.predictor = BayesianPredictor(n_obj * z_dim, 2)
if self.with_saa:
# auxiliary branch
self.predictor_aux = AccidentPredictor(h_dim + h_dim, 2, dropout=[0.5, 0.0])
self.self_aggregation = SelfAttAggregate(self.n_frames)
# loss function
self.ce_loss = torch.nn.CrossEntropyLoss(reduction='none')
def forward(self, x, y, toa, graph, hidden_in=None, edge_weights=None, npass=2, nbatch=80, testing=False, eval_uncertain=False):
"""
:param x, (batchsize, nFrames, nBoxes, Xdim) = (10 x 100 x 20 x 4096)
:param y, (10 x 2)
:param toa, (10,)
"""
losses = {'cross_entropy': 0,
'log_posterior': 0,
'log_prior': 0,
'total_loss': 0}
if self.with_saa:
losses.update({'auxloss': 0})
if self.uncertain_ranking:
losses.update({'ranking': 0})
Ut = torch.zeros(x.size(0)).to(x.device) # B
all_outputs, all_hidden = [], []
# import ipdb; ipdb.set_trace()
if hidden_in is None:
h = Variable(torch.zeros(self.n_layers, x.size(0), self.n_obj, self.h_dim)) # 1 x 10 x 19 x 256
else:
h = Variable(hidden_in)
h = h.to(x.device)
for t in range(x.size(1)):
# reduce the dim of node feature (FC layer)
x_t = self.phi_x(x[:, t]) # 10 x 20 x 256
img_embed = x_t[:, 0, :].unsqueeze(1).repeat(1, self.n_obj, 1).contiguous() # 10 x 1 x 256
obj_embed = x_t[:, 1:, :] # 10 x 19 x 256
x_t = torch.cat([obj_embed, img_embed], dim=-1) # 10 x 19 x 512
# GCN encoder
enc = self.enc_gcn1(x_t, graph[:, t], edge_weight=edge_weights[:, t]) # 10 x 19 x 256 (512-->256)
z_t = self.enc_gcn2(torch.cat([enc, h[-1]], -1), graph[:, t], edge_weight=edge_weights[:, t]) # 10 x 19 x 128 (512-->128)
# BNN decoder
embed = z_t.view(z_t.size(0), -1) # 10 x (19 x 128)
output_dict = self.predictor.sample_elbo(embed, npass=npass, testing=testing, eval_uncertain=eval_uncertain) # B x 2
dec_t = output_dict['pred_mean']
# recurrence
h = self.rnn(torch.cat([x_t, z_t], -1), graph[:, t], h, edge_weight=edge_weights[:, t]) # rnn latent (640)-->256
# computing losses
L1 = output_dict['log_posterior'] / nbatch
L2 = output_dict['log_prior'] / nbatch
L3 = self._exp_loss(dec_t, y, t, toa=toa, fps=self.fps)
losses['log_posterior'] += L1
losses['log_prior'] += L2
losses['cross_entropy'] += L3
# uncertainty ranking loss
if self.uncertain_ranking:
L5, Ut = self._uncertainty_ranking(output_dict, Ut)
losses['ranking'] += L5
all_outputs.append(output_dict)
all_hidden.append(h[-1])
if self.with_saa:
# soft attention to aggregate hidden states of all frames
embed_video = self.self_aggregation(torch.stack(all_hidden, dim=-1), 'avg')
dec = self.predictor_aux(embed_video)
L4 = torch.mean(self.ce_loss(dec, y[:, 1].to(torch.long)))
losses['auxloss'] = L4
return losses, all_outputs, all_hidden
def _exp_loss(self, pred, target, time, toa, fps=20.0):
'''
:param pred:
:param target: onehot codings for binary classification
:param time:
:param toa:
:param fps:
:return:
'''
# positive example (exp_loss)
target_cls = target[:, 1]
target_cls = target_cls.to(torch.long)
penalty = -torch.max(torch.zeros_like(toa).to(toa.device, pred.dtype), (toa.to(pred.dtype) - time - 1) / fps)
pos_loss = -torch.mul(torch.exp(penalty), -self.ce_loss(pred, target_cls))
# negative example
neg_loss = self.ce_loss(pred, target_cls)
loss = torch.mean(torch.add(torch.mul(pos_loss, target[:, 1]), torch.mul(neg_loss, target[:, 0])))
return loss
def _uncertainty_ranking(self, output_dict, Ut, eU_only=True):
"""
:param label: 10 x 2
:param output_dict:
"""
aleatoric = output_dict['aleatoric'] # B x 2 x 2
epistemic = output_dict['epistemic'] # B x 2 x 2
if eU_only:
# here we use the trace of matrix to quantify uncertainty
uncertainty = epistemic[:, 0, 0] + epistemic[:, 1, 1]
else:
uncertainty = aleatoric[:, 1, 1] + epistemic[:, 1, 1] # B
loss = torch.mean(torch.max(torch.zeros_like(Ut).to(Ut.device), uncertainty - Ut))
return loss, uncertainty
| 20,930 | 41.03012 | 145 | py |
UString | UString-master/script/vis_dad_det.py | import os
import numpy as np
import cv2
def vis_det(data_path, video_path, phase='training'):
files_list = []
batch_id = 1
for filename in sorted(os.listdir(os.path.join(data_path, phase))):
filepath = os.path.join(data_path, phase, filename)
all_data = np.load(filepath)
features = all_data['data'] # 10 x 100 x 20 x 4096
labels = all_data['labels'] # 10 x 2
detections = all_data['det'] # 10 x 100 x 19 x 6
videos = all_data['ID'] # 10
nid = 1
for i, vid in enumerate(videos):
tag = 'positive' if labels[i, 1] > 0 else 'negative'
video_file = os.path.join(video_path, phase, tag, vid.decode('UTF-8') + '.mp4')
if not os.path.exists(video_file):
raise FileNotFoundError
bboxes = detections[i]
counter = 0
cap = cv2.VideoCapture(video_file)
ret, frame = cap.read()
text_color = (0, 0, 255) if labels[i, 1] > 0 else (0, 255, 255)
while (ret):
new_bboxes = bboxes[counter, :, :]
for num_box in range(new_bboxes.shape[0]):
cv2.rectangle(frame, (new_bboxes[num_box, 0], new_bboxes[num_box, 1]),
(new_bboxes[num_box, 2], new_bboxes[num_box, 3]), (255, 0, 0), 2)
cv2.putText(frame, tag, (int(frame.shape[1] / 2) - 60, 60), cv2.FONT_HERSHEY_SIMPLEX, 2,
text_color, 2, cv2.LINE_AA)
cv2.imshow('result', frame)
c = cv2.waitKey(50)
ret, frame = cap.read()
if c == ord('q') and c == 27 and ret:
break;
counter += 1
cv2.destroyAllWindows()
if __name__ == '__main__':
FEAT_PATH = '/data/DAD/features'
VIDEO_PATH = '/data/DAD/videos'
vis_det(FEAT_PATH, VIDEO_PATH)
| 1,915 | 41.577778 | 104 | py |
UString | UString-master/script/split_dad.py | import os
import numpy as np
def process(data_path, dest_path, phase):
files_list = []
batch_id = 1
for filename in sorted(os.listdir(os.path.join(data_path, phase))):
filepath = os.path.join(data_path, phase, filename)
all_data = np.load(filepath)
features = all_data['data'] # 10 x 100 x 20 x 4096
labels = all_data['labels'] # 10 x 2
detections = all_data['det'] # 10 x 100 x 19 x 6
videos = all_data['ID'] # 10
nid = 1
for i, vid in enumerate(videos):
vidname = 'b' + str(batch_id).zfill(3) + '_' + vid.decode('UTF-8')
if vidname in files_list:
vidname = vidname + '_' + str(nid).zfill(2)
nid += 1
feat_file = os.path.join(dest_path, vidname + '.npz')
if os.path.exists(feat_file):
continue
np.savez_compressed(feat_file, data=features[i], labels=labels[i], det=detections[i], ID=vidname)
print('batch: %03d, %s file: %s' % (batch_id, phase, vidname))
files_list.append(vidname)
batch_id += 1
return files_list
def split_dad(data_path, dest_path):
# prepare the result paths
train_path = os.path.join(dest_path, 'training')
if not os.path.exists(train_path):
os.makedirs(train_path)
test_path = os.path.join(dest_path, 'testing')
if not os.path.exists(test_path):
os.makedirs(test_path)
# process training set
train_list = process(data_path, train_path, 'training')
print('Training samples: %d'%(len(train_list)))
# process testing set
test_list = process(data_path, test_path, 'testing')
print('Testing samples: %d' % (len(test_list)))
if __name__ == '__main__':
DAD_PATH = '/data/DAD/features'
DEST_PATH = '/data/DAD/features_split'
split_dad(DAD_PATH, DEST_PATH)
| 1,870 | 37.183673 | 109 | py |
UString | UString-master/script/extract_res101_dad.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path as osp
import numpy as np
import os, cv2
import argparse, sys
from tqdm import tqdm
import torch
import torch.nn as nn
from torchvision import models, transforms
from torch.autograd import Variable
from PIL import Image
CLASSES = ('__background__', 'Car', 'Pedestrian', 'Cyclist')
class ResNet(nn.Module):
def __init__(self, n_layers=101):
super(ResNet, self).__init__()
if n_layers == 50:
self.net = models.resnet50(pretrained=True)
elif n_layers == 101:
self.net = models.resnet101(pretrained=True)
else:
raise NotImplementedError
self.dim_feat = 2048
def forward(self, input):
output = self.net.conv1(input)
output = self.net.bn1(output)
output = self.net.relu(output)
output = self.net.maxpool(output)
output = self.net.layer1(output)
output = self.net.layer2(output)
output = self.net.layer3(output)
output = self.net.layer4(output)
output = self.net.avgpool(output)
return output
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument('--dad_dir', dest='dad_dir', help='The directory to the Dashcam Accident Dataset', type=str)
parser.add_argument('--out_dir', dest='out_dir', help='The directory to the output files.', type=str)
parser.add_argument('--n_frames', dest='n_frames', help='The number of frames sampled from each video', default=100)
parser.add_argument('--n_boxes', dest='n_boxes', help='The number of bounding boxes for each frame', default=19)
parser.add_argument('--dim_feat', dest='dim_feat', help='The dimension of extracted ResNet101 features', default=2048)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
def get_video_frames(video_file, n_frames=100):
# get the video data
cap = cv2.VideoCapture(video_file)
ret, frame = cap.read()
video_data = []
counter = 0
while (ret):
video_data.append(frame)
ret, frame = cap.read()
counter += 1
assert counter == n_frames
return video_data
def bbox_to_imroi(bboxes, image):
"""
bboxes: (n, 4), ndarray
image: (H, W, 3), ndarray
"""
imroi_data = []
for bbox in bboxes:
imroi = image[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
imroi = transform(Image.fromarray(imroi)) # (3, 224, 224), torch.Tensor
imroi_data.append(imroi)
imroi_data = torch.stack(imroi_data)
return imroi_data
def get_boxes(dets_all, im_size):
bboxes = []
for bbox in dets_all:
x1, y1, x2, y2 = bbox[:4].astype(np.int32)
x1 = min(max(0, x1), im_size[1]-1) # 0<=x1<=W-1
y1 = min(max(0, y1), im_size[0]-1) # 0<=y1<=H-1
x2 = min(max(x1, x2), im_size[1]-1) # x1<=x2<=W-1
y2 = min(max(y1, y2), im_size[0]-1) # y1<=y2<=H-1
h = y2 - y1 + 1
w = x2 - x1 + 1
if h > 2 and w > 2: # the area is at least 9
bboxes.append([x1, y1, x2, y2])
bboxes = np.array(bboxes, dtype=np.int32)
return bboxes
def extract_features(data_path, video_path, dest_path, phase):
files_list = []
batch_id = 1
all_batches = os.listdir(os.path.join(data_path, phase))
for filename in sorted(all_batches):
filepath = os.path.join(data_path, phase, filename)
all_data = np.load(filepath)
# parse the original DAD dataset
labels = all_data['labels'] # 10 x 2
videos = all_data['ID'] # 10
# features_old = all_data['data'] # 10 x 100 x 20 x 4096 (will be replaced)
detections = all_data['det'] # 10 x 100 x 19 x 6
# start to process each video
nid = 1
for i, vid in tqdm(enumerate(videos), desc="The %d-th batch"%(batch_id), total=len(all_batches)):
vidname = 'b' + str(batch_id).zfill(3) + '_' + vid.decode('UTF-8')
if vidname in files_list:
vidname = vidname + '_' + str(nid).zfill(2)
nid += 1
feat_file = os.path.join(dest_path, vidname + '.npz')
if os.path.exists(feat_file):
continue
# continue on feature extraction
tag = 'positive' if labels[i, 1] > 0 else 'negative'
video_file = os.path.join(video_path, phase, tag, vid.decode('UTF-8') + '.mp4')
video_frames = get_video_frames(video_file, n_frames=args.n_frames)
# start to process each frame
features_res101 = np.zeros((args.n_frames, args.n_boxes + 1, args.dim_feat), dtype=np.float32) # (100 x 20 x 2048)
for j, frame in tqdm(enumerate(video_frames), desc="The %d-th video"%(i+1), total=len(video_frames)):
# find the non-empty boxes
bboxes = get_boxes(detections[i, j], frame.shape) # n x 4
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
with torch.no_grad():
# extract image feature
image = transform(Image.fromarray(frame))
ims_frame = torch.unsqueeze(image, dim=0).float().to(device=device)
feature_frame = torch.squeeze(feat_extractor(ims_frame))
features_res101[j, 0, :] = feature_frame.cpu().numpy() if feature_frame.is_cuda else feature_frame.detach().numpy()
# extract object feature
if len(bboxes) > 0:
# bboxes to roi data
ims_roi = bbox_to_imroi(bboxes, frame) # (n, 3, 224, 224)
ims_roi = ims_roi.float().to(device=device)
feature_roi = torch.squeeze(torch.squeeze(feat_extractor(ims_roi), dim=-1), dim=-1) # (2048,)
features_res101[j, 1:len(bboxes)+1,:] = feature_roi.cpu().numpy() if feature_roi.is_cuda else feature_roi.detach().numpy()
# we only update the features
np.savez_compressed(feat_file, data=features_res101, det=detections[i], labels=labels[i], ID=vidname)
files_list.append(vidname)
batch_id += 1
return files_list
def run(data_path, video_path, dest_path):
# prepare the result paths
train_path = os.path.join(dest_path, 'training')
if not os.path.exists(train_path):
os.makedirs(train_path)
test_path = os.path.join(dest_path, 'testing')
if not os.path.exists(test_path):
os.makedirs(test_path)
# process training set
train_list = extract_features(data_path, video_path, train_path, 'training')
print('Training samples: %d'%(len(train_list)))
# process testing set
test_list = extract_features(data_path, video_path, test_path, 'testing')
print('Testing samples: %d' % (len(test_list)))
if __name__ == "__main__":
args = parse_args()
# prepare faster rcnn detector
feat_extractor = ResNet(n_layers=101)
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
feat_extractor = feat_extractor.to(device=device)
feat_extractor.eval()
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor()]
)
data_path = osp.join(args.dad_dir, 'features') # /data/DAD/features
video_path = osp.join(args.dad_dir, 'videos') # /data/DAD/videos
run(data_path, video_path, args.out_dir) # out: /data/DAD/res101_features
print("Done!") | 7,692 | 38.654639 | 146 | py |
UString | UString-master/script/vis_crash_det.py | import os, cv2
import numpy as np
def get_video_frames(video_file, n_frames=50):
assert os.path.exists(video_file), video_file
# get the video data
cap = cv2.VideoCapture(video_file)
ret, frame = cap.read()
video_data = []
counter = 0
while (ret):
video_data.append(frame)
ret, frame = cap.read()
counter += 1
assert len(video_data) >= n_frames
video_data = video_data[:n_frames]
return video_data
def vis_det(feat_path, video_path, out_path, tag='positive'):
for filename in sorted(os.listdir(feat_path)):
vid = filename.strip().split('.')[0]
# load information
filepath = os.path.join(feat_path, filename)
all_data = np.load(filepath)
features = all_data['data'] # 50 x 20 x 2048
labels = all_data['labels'] # 1 x 2
detections = all_data['det'] # 50 x 19 x 6
videos = all_data['ID'] # 1
# visualize dets
video_file = os.path.join(video_path, vid + '.mp4')
frames = get_video_frames(video_file, n_frames=50)
# save_dir
save_dir = os.path.join(out_path, vid)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
text_color = (0, 0, 255) if labels[1] > 0 else (0, 255, 255)
for counter, frame in enumerate(frames):
new_bboxes = detections[counter, :, :]
for num_box in range(new_bboxes.shape[0]):
cv2.rectangle(frame, (int(new_bboxes[num_box, 0]), int(new_bboxes[num_box, 1])),
(int(new_bboxes[num_box, 2]), int(new_bboxes[num_box, 3])), (255, 0, 0), 2)
cv2.putText(frame, tag, (int(frame.shape[1] / 2) - 60, 60), cv2.FONT_HERSHEY_SIMPLEX, 2,
text_color, 2, cv2.LINE_AA)
cv2.imwrite(os.path.join(save_dir, str(counter) + '.jpg'), frame)
if __name__ == '__main__':
FEAT_PATH = './data/crash/vgg16_features/positive'
VIDEO_PATH = './data/crash/videos/Crash-1500'
OUT_PATH = './data/crash/vgg16_features/vis_dets'
vis_det(FEAT_PATH, VIDEO_PATH, OUT_PATH, tag='positive') | 2,125 | 39.884615 | 111 | py |
SelfDeblur | SelfDeblur-master/selfdeblur_levin_reproduce.py |
# coding: utf-8
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
import cv2
import torch
import torch.optim
import glob
from skimage.io import imread
from skimage.io import imsave
import warnings
from tqdm import tqdm
from torch.optim.lr_scheduler import MultiStepLR
from utils.common_utils import *
from SSIM import SSIM
parser = argparse.ArgumentParser()
parser.add_argument("--preprocess", type=bool, default=False, help='run prepare_data or not')
parser.add_argument('--num_iter', type=int, default=2, help='number of epochs of training')
parser.add_argument('--img_size', type=int, default=[256, 256], help='size of each image dimension')
parser.add_argument('--kernel_size', type=int, default=[21, 21], help='size of blur kernel [height, width]')
parser.add_argument('--data_path', type=str, default="imgs/levin/", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/levin_reproduce/", help='path to save results')
parser.add_argument('--save_frequency', type=int, default=1, help='frequency to save results')
opt = parser.parse_args()
#print(opt)
#os.environ['CUDA_VISIBLE_DEVICES'] = '1'
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark =True
dtype = torch.cuda.FloatTensor
warnings.filterwarnings("ignore")
files_source = glob.glob(os.path.join(opt.data_path, '*.png'))
files_source.sort()
save_path = opt.save_path
os.makedirs(save_path, exist_ok=True)
# start #image
for f in files_source:
INPUT = 'noise'
pad = 'reflection'
LR = 0.0001
num_iter = opt.num_iter
reg_noise_std = 0.001
path_to_image = f
imgname = os.path.basename(f)
imgname = os.path.splitext(imgname)[0]
if imgname.find('kernel1') != -1:
opt.kernel_size = [17, 17]
if imgname.find('kernel2') != -1:
opt.kernel_size = [15, 15]
if imgname.find('kernel3') != -1:
opt.kernel_size = [13, 13]
if imgname.find('kernel4') != -1:
opt.kernel_size = [27, 27]
if imgname.find('kernel5') != -1:
opt.kernel_size = [11, 11]
if imgname.find('kernel6') != -1:
opt.kernel_size = [19, 19]
if imgname.find('kernel7') != -1:
opt.kernel_size = [21, 21]
if imgname.find('kernel8') != -1:
opt.kernel_size = [21, 21]
_, imgs = get_image(path_to_image, -1) # load image and convert to np.
y = np_to_torch(imgs).type(dtype)
img_size = imgs.shape
print(imgname)
# ######################################################################
padh, padw = opt.kernel_size[0]-1, opt.kernel_size[1]-1
opt.img_size[0], opt.img_size[1] = img_size[1]+padh, img_size[2]+padw
'''
x_net:
'''
input_depth = 8
net_input = get_noise(input_depth, INPUT, (opt.img_size[0], opt.img_size[1])).type(dtype)
net = torch.load(os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
net = net.type(dtype)
n_k = 200
net_input_kernel = get_noise(n_k, INPUT, (1, 1)).type(dtype)
net_input_kernel.squeeze_()
net_kernel = torch.load(os.path.join(opt.save_path, "%s_knet.pth" % imgname))
net_kernel = net_kernel.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
L1 = torch.nn.L1Loss(reduction='sum').type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params':net.parameters()},{'params':net_kernel.parameters(),'lr':0e-4}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[700, 800, 900], gamma=0.5) # learning rates
# initilization inputs
net_input_saved = net_input.detach().clone()
net_input_kernel_saved = net_input_kernel.detach().clone()
### start SelfDeblur
for step in tqdm(range(num_iter)):
# input regularization
net_input = net_input_saved + reg_noise_std*torch.zeros(net_input_saved.shape).type_as(net_input_saved.data).normal_()
# net_input_kernel = net_input_kernel_saved + reg_noise_std*torch.zeros(net_input_kernel_saved.shape).type_as(net_input_kernel_saved.data).normal_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
out_k = net_kernel(net_input_kernel)
out_k_m = out_k.view(-1,1,opt.kernel_size[0],opt.kernel_size[1])
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k_m, padding=0, bias=None)
if step < 0:
total_loss = mse(out_y, y)
else:
total_loss = 1 - ssim(out_y, y) # + tv_loss(out_x) #+ tv_loss2(out_k_m)
total_loss.backward()
optimizer.step()
if (step+1) % opt.save_frequency == 0:
#print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png'%imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
out_x_np = out_x_np[padh//2:padh//2+img_size[1], padw//2:padw//2+img_size[2]]
#out_x_np = np.uint8(out_x_np*255)
#cv2.imwrite(save_path, out_x_np)
imsave(save_path, out_x_np)
save_path = os.path.join(opt.save_path, '%s_k.png'%imgname)
out_k_np = torch_to_np(out_k_m)
out_k_np = out_k_np.squeeze()
out_k_np /= np.max(out_k_np)
imsave(save_path, out_k_np)
#torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
#torch.save(net_kernel, os.path.join(opt.save_path, "%s_knet.pth" % imgname))
| 5,559 | 33.75 | 156 | py |
SelfDeblur | SelfDeblur-master/SSIM.py | import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from math import exp
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
return gauss / gauss.sum()
def create_window(window_size, channel):
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())
return window
def _ssim(img1, img2, window, window_size, channel, size_average=True):
mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)
mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq
sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq
sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2
C1 = 0.01 ** 2
C2 = 0.03 ** 2
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
if size_average:
return ssim_map.mean()
else:
return ssim_map.mean(1).mean(1).mean(1)
class SSIM(torch.nn.Module):
def __init__(self, window_size=11, size_average=True):
super(SSIM, self).__init__()
self.window_size = window_size
self.size_average = size_average
self.channel = 1
self.window = create_window(window_size, self.channel)
def forward(self, img1, img2):
(_, channel, _, _) = img1.size()
if channel == self.channel and self.window.data.type() == img1.data.type():
window = self.window
else:
window = create_window(self.window_size, channel)
if img1.is_cuda:
window = window.cuda(img1.get_device())
window = window.type_as(img1)
self.window = window
self.channel = channel
return _ssim(img1, img2, window, self.window_size, channel, self.size_average)
def ssim(img1, img2, window_size=11, size_average=True):
(_, channel, _, _) = img1.size()
window = create_window(window_size, channel)
if img1.is_cuda:
window = window.cuda(img1.get_device())
window = window.type_as(img1)
return _ssim(img1, img2, window, window_size, channel, size_average) | 2,620 | 33.038961 | 114 | py |
SelfDeblur | SelfDeblur-master/selfdeblur_lai_reproduce.py |
# coding: utf-8
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
import cv2
import torch
import torch.optim
import glob
from skimage.io import imread
from skimage.io import imsave
import warnings
from tqdm import tqdm
from torch.optim.lr_scheduler import MultiStepLR
from utils.common_utils import *
from SSIM import SSIM
parser = argparse.ArgumentParser()
parser.add_argument("--preprocess", type=bool, default=False, help='run prepare_data or not')
parser.add_argument('--num_iter', type=int, default=2, help='number of epochs of training')
parser.add_argument('--img_size', type=int, default=[256, 256], help='size of each image dimension')
parser.add_argument('--kernel_size', type=int, default=[21, 21], help='size of blur kernel [height, width]')
parser.add_argument('--data_path', type=str, default="imgs/lai/uniform_ycbcr/", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/lai/uniform_reproduce/", help='path to save results')
parser.add_argument('--save_frequency', type=int, default=1, help='lfrequency to save results')
opt = parser.parse_args()
#print(opt)
#os.environ['CUDA_VISIBLE_DEVICES'] = '1'
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark =True
dtype = torch.cuda.FloatTensor
warnings.filterwarnings("ignore")
files_source = glob.glob(os.path.join(opt.data_path, '*.png'))
files_source.sort()
save_path = opt.save_path
os.makedirs(save_path, exist_ok=True)
# start #image
for f in files_source:
INPUT = 'noise'
pad = 'reflection'
LR = 0.0001
num_iter = opt.num_iter
reg_noise_std = 0.001
path_to_image = f
imgname = os.path.basename(f)
imgname = os.path.splitext(imgname)[0]
if imgname.find('kernel_01') != -1:
opt.kernel_size = [31, 31]
if imgname.find('kernel_02') != -1:
opt.kernel_size = [51, 51]
if imgname.find('kernel_03') != -1:
opt.kernel_size = [55, 55]
if imgname.find('kernel_04') != -1:
opt.kernel_size = [75, 75]
_, imgs = get_image(path_to_image, -1) # load image and convert to np.
y = np_to_torch(imgs).type(dtype)
img_size = imgs.shape
print(imgname)
# ######################################################################
padh, padw = opt.kernel_size[0]-1, opt.kernel_size[1]-1
opt.img_size[0], opt.img_size[1] = img_size[1]+padh, img_size[2]+padw
'''
x_net:
'''
input_depth = 8
net_input = get_noise(input_depth, INPUT, (opt.img_size[0], opt.img_size[1])).type(dtype)
net = torch.load(os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
net = net.type(dtype)
n_k = 200
net_input_kernel = get_noise(n_k, INPUT, (1, 1)).type(dtype)
net_input_kernel.squeeze_()
net_kernel = torch.load(os.path.join(opt.save_path, "%s_knet.pth" % imgname))
net_kernel = net_kernel.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
L1 = torch.nn.L1Loss(reduction='sum').type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params':net.parameters()},{'params':net_kernel.parameters(),'lr':0e-4}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[700, 800, 900], gamma=0.5) # learning rates
# initilization inputs
net_input_saved = net_input.detach().clone()
net_input_kernel_saved = net_input_kernel.detach().clone()
### start SelfDeblur
for step in tqdm(range(num_iter)):
# input regularization
net_input = net_input_saved + reg_noise_std*torch.zeros(net_input_saved.shape).type_as(net_input_saved.data).normal_()
# net_input_kernel = net_input_kernel_saved + reg_noise_std*torch.zeros(net_input_kernel_saved.shape).type_as(net_input_kernel_saved.data).normal_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
out_k = net_kernel(net_input_kernel)
out_k_m = out_k.view(-1,1,opt.kernel_size[0],opt.kernel_size[1])
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k_m, padding=0, bias=None)
if step < 0:
total_loss = mse(out_y, y)
else:
total_loss = 1 - ssim(out_y, y) # + tv_loss(out_x) #+ tv_loss2(out_k_m)
total_loss.backward()
optimizer.step()
if (step+1) % opt.save_frequency == 0:
#print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png'%imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
out_x_np = out_x_np[padh//2:padh//2+img_size[1], padw//2:padw//2+img_size[2]]
#out_x_np = np.uint8(out_x_np*255)
#cv2.imwrite(save_path, out_x_np)
imsave(save_path, out_x_np)
save_path = os.path.join(opt.save_path, '%s_k.png'%imgname)
out_k_np = torch_to_np(out_k_m)
out_k_np = out_k_np.squeeze()
out_k_np /= np.max(out_k_np)
imsave(save_path, out_k_np)
#torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
#torch.save(net_kernel, os.path.join(opt.save_path, "%s_knet.pth" % imgname))
| 5,294 | 33.835526 | 156 | py |
SelfDeblur | SelfDeblur-master/selfdeblur_lai.py |
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
from networks.skip import skip
from networks.fcn import *
import cv2
import torch
import torch.optim
import glob
from skimage.io import imread
from skimage.io import imsave
import warnings
from tqdm import tqdm
from torch.optim.lr_scheduler import MultiStepLR
from utils.common_utils import *
from SSIM import SSIM
parser = argparse.ArgumentParser()
parser.add_argument('--num_iter', type=int, default=5000, help='number of epochs of training')
parser.add_argument('--img_size', type=int, default=[256, 256], help='size of each image dimension')
parser.add_argument('--kernel_size', type=int, default=[21, 21], help='size of blur kernel [height, width]')
parser.add_argument('--data_path', type=str, default="datasets/lai/uniform_ycbcr/", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/lai/uniform", help='path to save results')
parser.add_argument('--save_frequency', type=int, default=100, help='lfrequency to save results')
opt = parser.parse_args()
#print(opt)
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark =True
dtype = torch.cuda.FloatTensor
warnings.filterwarnings("ignore")
files_source = glob.glob(os.path.join(opt.data_path, '*.png'))
files_source.sort()
save_path = opt.save_path
os.makedirs(save_path, exist_ok=True)
# start #image
for f in files_source:
INPUT = 'noise'
pad = 'reflection'
LR = 0.01
num_iter = opt.num_iter
reg_noise_std = 0.001
path_to_image = f
imgname = os.path.basename(f)
imgname = os.path.splitext(imgname)[0]
if imgname.find('kernel_01') != -1:
opt.kernel_size = [31, 31]
if imgname.find('kernel_02') != -1:
opt.kernel_size = [51, 51]
if imgname.find('kernel_03') != -1:
opt.kernel_size = [55, 55]
if imgname.find('kernel_04') != -1:
opt.kernel_size = [75, 75]
_, imgs = get_image(path_to_image, -1) # load image and convert to np.
y = np_to_torch(imgs).type(dtype)
img_size = imgs.shape
print(imgname)
# ######################################################################
padh, padw = opt.kernel_size[0]-1, opt.kernel_size[1]-1
opt.img_size[0], opt.img_size[1] = img_size[1]+padh, img_size[2]+padw
'''
x_net:
'''
input_depth = 8
net_input = get_noise(input_depth, INPUT, (opt.img_size[0], opt.img_size[1])).type(dtype)
net = skip( input_depth, 1,
num_channels_down = [128, 128, 128, 128, 128],
num_channels_up = [128, 128, 128, 128, 128],
num_channels_skip = [16, 16, 16, 16, 16],
upsample_mode='bilinear',
need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU')
net = net.type(dtype)
n_k = 200
net_input_kernel = get_noise(n_k, INPUT, (1, 1)).type(dtype)
net_input_kernel.squeeze_()
net_kernel = fcn(n_k, opt.kernel_size[0]*opt.kernel_size[1])
net_kernel = net_kernel.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params':net.parameters()},{'params':net_kernel.parameters(),'lr':1e-4}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[2000, 3000, 4000], gamma=0.5) # learning rates
#
net_input_saved = net_input.detach().clone()
net_input_kernel_saved = net_input_kernel.detach().clone()
### start SelfDeblur
for step in tqdm(range(num_iter)):
# input regularization
net_input = net_input_saved + reg_noise_std*torch.zeros(net_input_saved.shape).type_as(net_input_saved.data).normal_()
# net_input_kernel = net_input_kernel_saved + reg_noise_std*torch.zeros(net_input_kernel_saved.shape).type_as(net_input_kernel_saved.data).normal_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
out_k = net_kernel(net_input_kernel)
out_k_m = out_k.view(-1,1,opt.kernel_size[0],opt.kernel_size[1])
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k_m, padding=0, bias=None)
if step < 500:
total_loss = mse(out_y, y)
else:
total_loss = 1 - ssim(out_y, y)
total_loss.backward()
optimizer.step()
if (step+1) % opt.save_frequency == 0:
#print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png'%imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
out_x_np = out_x_np[padh//2:padh//2+img_size[1], padw//2:padw//2+img_size[2]]
imsave(save_path, out_x_np)
save_path = os.path.join(opt.save_path, '%s_k.png'%imgname)
out_k_np = torch_to_np(out_k_m)
out_k_np = out_k_np.squeeze()
out_k_np /= np.max(out_k_np)
imsave(save_path, out_k_np)
torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
torch.save(net_kernel, os.path.join(opt.save_path, "%s_knet.pth" % imgname))
| 5,242 | 33.045455 | 156 | py |
SelfDeblur | SelfDeblur-master/selfdeblur_nonblind.py |
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
from networks.skip import skip
from networks.fcn import *
import cv2
import torch
import torch.optim
import glob
from skimage.io import imread
from skimage.io import imsave
import warnings
from tqdm import tqdm
from torch.optim.lr_scheduler import MultiStepLR
from utils.common_utils import *
from SSIM import SSIM
parser = argparse.ArgumentParser()
parser.add_argument("--preprocess", type=bool, default=False, help='run prepare_data or not')
parser.add_argument('--num_iter', type=int, default=1000, help='number of epochs of training')
parser.add_argument('--img_size', type=int, default=[256, 256], help='size of each image dimension')
parser.add_argument('--kernel_size', type=int, default=[21, 21], help='size of blur kernel [height, width]')
parser.add_argument('--data_path', type=str, default="results/lai/uniform/nonblind/blurry/", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/lai/uniform/nonblind/blurry/results", help='path to save results')
parser.add_argument('--save_frequency', type=int, default=100, help='lfrequency to save results')
opt = parser.parse_args()
#print(opt)
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark =True
dtype = torch.cuda.FloatTensor
warnings.filterwarnings("ignore")
files_source = glob.glob(os.path.join(opt.data_path, '*.png'))
files_source.sort()
save_path = opt.save_path
os.makedirs(save_path, exist_ok=True)
# start #image
for f in files_source:
INPUT = 'noise'
pad = 'reflection'
LR = 0.01
num_iter = opt.num_iter
reg_noise_std = 0.001
path_to_image = f
imgname = os.path.basename(f)
imgname = os.path.splitext(imgname)[0]
if imgname.find('kernel_01') != -1:
opt.kernel_size = [31, 31]
if imgname.find('kernel_02') != -1:
opt.kernel_size = [51, 51]
if imgname.find('kernel_03') != -1:
opt.kernel_size = [55, 55]
if imgname.find('kernel_04') != -1:
opt.kernel_size = [75, 75]
_, imgs = get_image(path_to_image, -1) # load image and convert to np.
y = np_to_torch(imgs).type(dtype)
img_size = imgs.shape
path_to_kernel = os.path.join(opt.save_path, "%s_k.png" % imgname)
out_k = cv2.imread(path_to_kernel,cv2.IMREAD_GRAYSCALE)
out_k = np.expand_dims(np.float32(out_k/255.),0)
out_k = np_to_torch(out_k).type(dtype)
out_k = torch.clamp(out_k, 0., 1.)
out_k /= torch.sum(out_k)
opt.kernel_size = [out_k.shape[2], out_k.shape[3]]
print(imgname)
# ######################################################################
padh, padw = opt.kernel_size[0]-1, opt.kernel_size[1]-1
opt.img_size[0], opt.img_size[1] = img_size[1]+padh, img_size[2]+padw
'''
x_net:
'''
input_depth = 8
net_input = get_noise(input_depth, INPUT, (opt.img_size[0], opt.img_size[1])).type(dtype)
net = skip( input_depth, 1,
num_channels_down = [128, 128, 128, 128, 128],
num_channels_up = [128, 128, 128, 128, 128],
num_channels_skip = [16, 16, 16, 16, 16],
upsample_mode='bilinear',
need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU')
net = net.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params':net.parameters()}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[700, 800, 900], gamma=0.5) # learning rates
# initilization inputs
net_input_saved = net_input.detach().clone()
### start SelfDeblur
for step in tqdm(range(num_iter)):
# input regularization
net_input = net_input_saved + reg_noise_std*torch.zeros(net_input_saved.shape).type_as(net_input_saved.data).normal_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k, padding=0, bias=None)
total_loss = 1 - ssim(out_y, y)
total_loss.backward()
optimizer.step()
if (step+1) % opt.save_frequency == 0:
#print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png'%imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
out_x_np = out_x_np[padh//2:padh//2+img_size[1], padw//2:padw//2+img_size[2]]
imsave(save_path, out_x_np)
torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
| 4,721 | 32.489362 | 128 | py |
SelfDeblur | SelfDeblur-master/selfdeblur_ycbcr.py |
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
from networks.skip import skip
from networks.fcn import fcn
import cv2
import torch
import torch.optim
from torch.autograd import Variable
import glob
from skimage.io import imread
from skimage.io import imsave
from PIL import Image
import warnings
from tqdm import tqdm
from torch.optim.lr_scheduler import MultiStepLR
from utils.common_utils import *
from SSIM import SSIM
parser = argparse.ArgumentParser()
parser.add_argument('--num_iter', type=int, default=2500, help='number of epochs of training')
parser.add_argument('--img_size', type=int, default=[256, 256], help='size of each image dimension')
parser.add_argument('--kernel_size', type=int, default=[31, 31], help='size of blur kernel [height, width]')
parser.add_argument('--data_path', type=str, default="datasets/real", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/real/", help='path to deblurring results')
parser.add_argument('--save_frequency', type=int, default=100, help='lfrequency to save results')
opt = parser.parse_args()
# print(opt)
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
dtype = torch.cuda.FloatTensor
warnings.filterwarnings("ignore")
files_source = glob.glob(os.path.join(opt.data_path, '*.jpg'))
files_source.sort()
save_path = opt.save_path
os.makedirs(save_path, exist_ok=True)
# start #image
for f in files_source:
INPUT = 'noise'
pad = 'reflection'
LR = 0.01
num_iter = opt.num_iter
reg_noise_std = 0.001
path_to_image = f
imgname = os.path.basename(f)
imgname = os.path.splitext(imgname)[0]
if imgname.find('fish') != -1:
opt.kernel_size = [41, 41]
if imgname.find('flower') != -1:
opt.kernel_size = [25, 25]
if imgname.find('house') != -1:
opt.kernel_size = [51, 51]
img, y, cb, cr = readimg(path_to_image)
y = np.float32(y / 255.0)
y = np.expand_dims(y, 0)
img_size = y.shape
print(imgname)
# ######################################################################
padw, padh = opt.kernel_size[0]-1, opt.kernel_size[1]-1
opt.img_size[0], opt.img_size[1] = img_size[1]+padw, img_size[2]+padh
#y = y[:, padh//2:img_size[1]-padh//2, padw//2:img_size[2]-padw//2]
y = np_to_torch(y).type(dtype)
input_depth = 8
net_input = get_noise(input_depth, INPUT, (opt.img_size[0], opt.img_size[1])).type(dtype)
net = skip(input_depth, 1,
num_channels_down=[128, 128, 128, 128, 128],
num_channels_up=[128, 128, 128, 128, 128],
num_channels_skip=[16, 16, 16, 16, 16],
upsample_mode='bilinear',
need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU')
net = net.type(dtype)
n_k = 200
net_input_kernel = get_noise(n_k, INPUT, (1, 1)).type(dtype)
net_input_kernel.squeeze_()
net_kernel = fcn(n_k, opt.kernel_size[0] * opt.kernel_size[1])
net_kernel = net_kernel.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params': net.parameters()}, {'params': net_kernel.parameters(), 'lr': 1e-4}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[1600, 1900, 2200], gamma=0.5) # learning rates
# initilization inputs
net_input_saved = net_input.detach().clone()
net_input_kernel_saved = net_input_kernel.detach().clone()
### start SelfDeblur
for step in tqdm(range(num_iter)):
# input regularization
net_input = net_input_saved + reg_noise_std * torch.zeros(net_input_saved.shape).type_as(
net_input_saved.data).normal_()
# net_input_kernel = net_input_kernel_saved + reg_noise_std*torch.zeros(net_input_kernel_saved.shape).type_as(net_input_kernel_saved.data).normal_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
out_k = net_kernel(net_input_kernel)
out_k_m = out_k.view(-1, 1, opt.kernel_size[0], opt.kernel_size[1])
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k_m, padding=0, bias=None)
y_size = out_y.shape
cropw = y_size[2]-img_size[1]
croph = y_size[3]-img_size[2]
out_y = out_y[:,:,cropw//2:cropw//2+img_size[1],croph//2:croph//2+img_size[2]]
if step < 500:
total_loss = mse(out_y, y)
else:
total_loss = 1 - ssim(out_y, y)
total_loss.backward()
optimizer.step()
if (step + 1) % opt.save_frequency == 0:
# print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png' % imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
cropw, croph = padw, padh
out_x_np = out_x_np[cropw//2:cropw//2+img_size[1], croph//2:croph//2+img_size[2]]
out_x_np = np.uint8(255 * out_x_np)
out_x_np = cv2.merge([out_x_np, cr, cb])
out_x_np = cv2.cvtColor(out_x_np, cv2.COLOR_YCrCb2BGR)
cv2.imwrite(save_path, out_x_np)
save_path = os.path.join(opt.save_path, '%s_k.png' % imgname)
out_k_np = torch_to_np(out_k_m)
out_k_np = out_k_np.squeeze()
out_k_np /= np.max(out_k_np)
imsave(save_path, out_k_np)
torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
torch.save(net_kernel, os.path.join(opt.save_path, "%s_knet.pth" % imgname))
| 5,714 | 34.06135 | 156 | py |
SelfDeblur | SelfDeblur-master/selfdeblur_levin.py |
from __future__ import print_function
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np
from networks.skip import skip
from networks.fcn import fcn
import cv2
import torch
import torch.optim
import glob
from skimage.io import imread
from skimage.io import imsave
import warnings
from tqdm import tqdm
from torch.optim.lr_scheduler import MultiStepLR
from utils.common_utils import *
from SSIM import SSIM
parser = argparse.ArgumentParser()
parser.add_argument('--num_iter', type=int, default=5000, help='number of epochs of training')
parser.add_argument('--img_size', type=int, default=[256, 256], help='size of each image dimension')
parser.add_argument('--kernel_size', type=int, default=[21, 21], help='size of blur kernel [height, width]')
parser.add_argument('--data_path', type=str, default="datasets/levin/", help='path to blurry image')
parser.add_argument('--save_path', type=str, default="results/levin/", help='path to save results')
parser.add_argument('--save_frequency', type=int, default=100, help='lfrequency to save results')
opt = parser.parse_args()
#print(opt)
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark =True
dtype = torch.cuda.FloatTensor
warnings.filterwarnings("ignore")
files_source = glob.glob(os.path.join(opt.data_path, '*.png'))
files_source.sort()
save_path = opt.save_path
os.makedirs(save_path, exist_ok=True)
# start #image
for f in files_source:
INPUT = 'noise'
pad = 'reflection'
LR = 0.01
num_iter = opt.num_iter
reg_noise_std = 0.001
path_to_image = f
imgname = os.path.basename(f)
imgname = os.path.splitext(imgname)[0]
if imgname.find('kernel1') != -1:
opt.kernel_size = [17, 17]
if imgname.find('kernel2') != -1:
opt.kernel_size = [15, 15]
if imgname.find('kernel3') != -1:
opt.kernel_size = [13, 13]
if imgname.find('kernel4') != -1:
opt.kernel_size = [27, 27]
if imgname.find('kernel5') != -1:
opt.kernel_size = [11, 11]
if imgname.find('kernel6') != -1:
opt.kernel_size = [19, 19]
if imgname.find('kernel7') != -1:
opt.kernel_size = [21, 21]
if imgname.find('kernel8') != -1:
opt.kernel_size = [21, 21]
_, imgs = get_image(path_to_image, -1) # load image and convert to np.
y = np_to_torch(imgs).type(dtype)
img_size = imgs.shape
print(imgname)
# ######################################################################
padh, padw = opt.kernel_size[0]-1, opt.kernel_size[1]-1
opt.img_size[0], opt.img_size[1] = img_size[1]+padh, img_size[2]+padw
'''
x_net:
'''
input_depth = 8
net_input = get_noise(input_depth, INPUT, (opt.img_size[0], opt.img_size[1])).type(dtype)
net = skip( input_depth, 1,
num_channels_down = [128, 128, 128, 128, 128],
num_channels_up = [128, 128, 128, 128, 128],
num_channels_skip = [16, 16, 16, 16, 16],
upsample_mode='bilinear',
need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU')
net = net.type(dtype)
'''
k_net:
'''
n_k = 200
net_input_kernel = get_noise(n_k, INPUT, (1, 1)).type(dtype)
net_input_kernel.squeeze_()
net_kernel = fcn(n_k, opt.kernel_size[0]*opt.kernel_size[1])
net_kernel = net_kernel.type(dtype)
# Losses
mse = torch.nn.MSELoss().type(dtype)
ssim = SSIM().type(dtype)
# optimizer
optimizer = torch.optim.Adam([{'params':net.parameters()},{'params':net_kernel.parameters(),'lr':1e-4}], lr=LR)
scheduler = MultiStepLR(optimizer, milestones=[2000, 3000, 4000], gamma=0.5) # learning rates
# initilization inputs
net_input_saved = net_input.detach().clone()
net_input_kernel_saved = net_input_kernel.detach().clone()
### start SelfDeblur
for step in tqdm(range(num_iter)):
# input regularization
net_input = net_input_saved + reg_noise_std*torch.zeros(net_input_saved.shape).type_as(net_input_saved.data).normal_()
# change the learning rate
scheduler.step(step)
optimizer.zero_grad()
# get the network output
out_x = net(net_input)
out_k = net_kernel(net_input_kernel)
out_k_m = out_k.view(-1,1,opt.kernel_size[0],opt.kernel_size[1])
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k_m, padding=0, bias=None)
if step < 1000:
total_loss = mse(out_y,y)
else:
total_loss = 1-ssim(out_y, y)
total_loss.backward()
optimizer.step()
if (step+1) % opt.save_frequency == 0:
#print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png'%imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
out_x_np = out_x_np[padh//2:padh//2+img_size[1], padw//2:padw//2+img_size[2]]
imsave(save_path, out_x_np)
save_path = os.path.join(opt.save_path, '%s_k.png'%imgname)
out_k_np = torch_to_np(out_k_m)
out_k_np = out_k_np.squeeze()
out_k_np /= np.max(out_k_np)
imsave(save_path, out_k_np)
torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
torch.save(net_kernel, os.path.join(opt.save_path, "%s_knet.pth" % imgname))
| 5,395 | 32.515528 | 126 | py |
SelfDeblur | SelfDeblur-master/networks/fcn.py | import torch
import torch.nn as nn
from .common import *
def fcn(num_input_channels=200, num_output_channels=1, num_hidden=1000):
model = nn.Sequential()
model.add(nn.Linear(num_input_channels, num_hidden,bias=True))
model.add(nn.ReLU6())
#
model.add(nn.Linear(num_hidden, num_output_channels))
# model.add(nn.ReLU())
model.add(nn.Softmax())
#
return model
| 398 | 13.25 | 72 | py |
SelfDeblur | SelfDeblur-master/networks/non_local_embedded_gaussian.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = nn.Sequential(self.phi, max_pool_layer)
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)
theta_x = theta_x.permute(0, 2, 1)
phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)
f = torch.matmul(theta_x, phi_x)
f_div_C = F.softmax(f, dim=-1)
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 4,916 | 36.25 | 102 | py |
SelfDeblur | SelfDeblur-master/networks/skip.py | import torch
import torch.nn as nn
from .common import *
#from .non_local_embedded_gaussian import NONLocalBlock2D
#from .non_local_concatenation import NONLocalBlock2D
#from .non_local_gaussian import NONLocalBlock2D
from .non_local_dot_product import NONLocalBlock2D
def skip(
num_input_channels=2, num_output_channels=3,
num_channels_down=[16, 32, 64, 128, 128], num_channels_up=[16, 32, 64, 128, 128], num_channels_skip=[4, 4, 4, 4, 4],
filter_size_down=3, filter_size_up=3, filter_skip_size=1,
need_sigmoid=True, need_bias=True,
pad='zero', upsample_mode='nearest', downsample_mode='stride', act_fun='LeakyReLU',
need1x1_up=True):
"""Assembles encoder-decoder with skip connections.
Arguments:
act_fun: Either string 'LeakyReLU|Swish|ELU|none' or module (e.g. nn.ReLU)
pad (string): zero|reflection (default: 'zero')
upsample_mode (string): 'nearest|bilinear' (default: 'nearest')
downsample_mode (string): 'stride|avg|max|lanczos2' (default: 'stride')
"""
assert len(num_channels_down) == len(num_channels_up) == len(num_channels_skip)
n_scales = len(num_channels_down)
if not (isinstance(upsample_mode, list) or isinstance(upsample_mode, tuple)):
upsample_mode = [upsample_mode]*n_scales
if not (isinstance(downsample_mode, list) or isinstance(downsample_mode, tuple)):
downsample_mode = [downsample_mode]*n_scales
if not (isinstance(filter_size_down, list) or isinstance(filter_size_down, tuple)):
filter_size_down = [filter_size_down]*n_scales
if not (isinstance(filter_size_up, list) or isinstance(filter_size_up, tuple)):
filter_size_up = [filter_size_up]*n_scales
last_scale = n_scales - 1
cur_depth = None
model = nn.Sequential()
model_tmp = model
input_depth = num_input_channels
for i in range(len(num_channels_down)):
deeper = nn.Sequential()
skip = nn.Sequential()
if num_channels_skip[i] != 0:
model_tmp.add(Concat(1, skip, deeper))
else:
model_tmp.add(deeper)
model_tmp.add(bn(num_channels_skip[i] + (num_channels_up[i + 1] if i < last_scale else num_channels_down[i])))
if num_channels_skip[i] != 0:
skip.add(conv(input_depth, num_channels_skip[i], filter_skip_size, bias=need_bias, pad=pad))
skip.add(bn(num_channels_skip[i]))
skip.add(act(act_fun))
# skip.add(Concat(2, GenNoise(nums_noise[i]), skip_part))
deeper.add(conv(input_depth, num_channels_down[i], filter_size_down[i], 2, bias=need_bias, pad=pad, downsample_mode=downsample_mode[i]))
deeper.add(bn(num_channels_down[i]))
deeper.add(act(act_fun))
if i>1:
deeper.add(NONLocalBlock2D(in_channels=num_channels_down[i]))
deeper.add(conv(num_channels_down[i], num_channels_down[i], filter_size_down[i], bias=need_bias, pad=pad))
deeper.add(bn(num_channels_down[i]))
deeper.add(act(act_fun))
deeper_main = nn.Sequential()
if i == len(num_channels_down) - 1:
# The deepest
k = num_channels_down[i]
else:
deeper.add(deeper_main)
k = num_channels_up[i + 1]
deeper.add(nn.Upsample(scale_factor=2, mode=upsample_mode[i]))
model_tmp.add(conv(num_channels_skip[i] + k, num_channels_up[i], filter_size_up[i], 1, bias=need_bias, pad=pad))
model_tmp.add(bn(num_channels_up[i]))
model_tmp.add(act(act_fun))
if need1x1_up:
model_tmp.add(conv(num_channels_up[i], num_channels_up[i], 1, bias=need_bias, pad=pad))
model_tmp.add(bn(num_channels_up[i]))
model_tmp.add(act(act_fun))
input_depth = num_channels_down[i]
model_tmp = deeper_main
model.add(conv(num_channels_up[0], num_output_channels, 1, bias=need_bias, pad=pad))
if need_sigmoid:
model.add(nn.Sigmoid())
return model
| 4,045 | 36.119266 | 144 | py |
SelfDeblur | SelfDeblur-master/networks/resnet.py | import torch
import torch.nn as nn
from numpy.random import normal
from numpy.linalg import svd
from math import sqrt
import torch.nn.init
from .common import *
class ResidualSequential(nn.Sequential):
def __init__(self, *args):
super(ResidualSequential, self).__init__(*args)
def forward(self, x):
out = super(ResidualSequential, self).forward(x)
# print(x.size(), out.size())
x_ = None
if out.size(2) != x.size(2) or out.size(3) != x.size(3):
diff2 = x.size(2) - out.size(2)
diff3 = x.size(3) - out.size(3)
# print(1)
x_ = x[:, :, diff2 /2:out.size(2) + diff2 / 2, diff3 / 2:out.size(3) + diff3 / 2]
else:
x_ = x
return out + x_
def eval(self):
print(2)
for m in self.modules():
m.eval()
exit()
def get_block(num_channels, norm_layer, act_fun):
layers = [
nn.Conv2d(num_channels, num_channels, 3, 1, 1, bias=False),
norm_layer(num_channels, affine=True),
act(act_fun),
nn.Conv2d(num_channels, num_channels, 3, 1, 1, bias=False),
norm_layer(num_channels, affine=True),
]
return layers
class ResNet(nn.Module):
def __init__(self, num_input_channels, num_output_channels, num_blocks, num_channels, need_residual=True, act_fun='LeakyReLU', need_sigmoid=True, norm_layer=nn.BatchNorm2d, pad='reflection'):
'''
pad = 'start|zero|replication'
'''
super(ResNet, self).__init__()
if need_residual:
s = ResidualSequential
else:
s = nn.Sequential
# stride = 1
# First layers
layers = [
# nn.ReplicationPad2d(num_blocks * 2 * stride + 3),
conv(num_input_channels, num_channels, 3, stride=1, bias=True, pad=pad),
act(act_fun)
]
# Residual blocks
# layers_residual = []
for i in range(num_blocks):
layers += [s(*get_block(num_channels, norm_layer, act_fun))]
layers += [
nn.Conv2d(num_channels, num_channels, 3, 1, 1),
norm_layer(num_channels, affine=True)
]
# if need_residual:
# layers += [ResidualSequential(*layers_residual)]
# else:
# layers += [Sequential(*layers_residual)]
# if factor >= 2:
# # Do upsampling if needed
# layers += [
# nn.Conv2d(num_channels, num_channels *
# factor ** 2, 3, 1),
# nn.PixelShuffle(factor),
# act(act_fun)
# ]
layers += [
conv(num_channels, num_output_channels, 3, 1, bias=True, pad=pad),
nn.Sigmoid()
]
self.model = nn.Sequential(*layers)
def forward(self, input):
return self.model(input)
def eval(self):
self.model.eval()
| 2,945 | 29.371134 | 195 | py |
SelfDeblur | SelfDeblur-master/networks/downsampler.py | import numpy as np
import torch
import torch.nn as nn
class Downsampler(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes, factor, kernel_type, phase=0, kernel_width=None, support=None, sigma=None, preserve_size=False):
super(Downsampler, self).__init__()
assert phase in [0, 0.5], 'phase should be 0 or 0.5'
if kernel_type == 'lanczos2':
support = 2
kernel_width = 4 * factor + 1
kernel_type_ = 'lanczos'
elif kernel_type == 'lanczos3':
support = 3
kernel_width = 6 * factor + 1
kernel_type_ = 'lanczos'
elif kernel_type == 'gauss12':
kernel_width = 7
sigma = 1/2
kernel_type_ = 'gauss'
elif kernel_type == 'gauss1sq2':
kernel_width = 9
sigma = 1./np.sqrt(2)
kernel_type_ = 'gauss'
elif kernel_type in ['lanczos', 'gauss', 'box']:
kernel_type_ = kernel_type
else:
assert False, 'wrong name kernel'
# note that `kernel width` will be different to actual size for phase = 1/2
self.kernel = get_kernel(factor, kernel_type_, phase, kernel_width, support=support, sigma=sigma)
downsampler = nn.Conv2d(n_planes, n_planes, kernel_size=self.kernel.shape, stride=factor, padding=0)
downsampler.weight.data[:] = 0
downsampler.bias.data[:] = 0
kernel_torch = torch.from_numpy(self.kernel)
for i in range(n_planes):
downsampler.weight.data[i, i] = kernel_torch
self.downsampler_ = downsampler
if preserve_size:
if self.kernel.shape[0] % 2 == 1:
pad = int((self.kernel.shape[0] - 1) / 2.)
else:
pad = int((self.kernel.shape[0] - factor) / 2.)
self.padding = nn.ReplicationPad2d(pad)
self.preserve_size = preserve_size
def forward(self, input):
if self.preserve_size:
x = self.padding(input)
else:
x= input
self.x = x
return self.downsampler_(x)
class Blurconv(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes=1, preserve_size=False):
super(Blurconv, self).__init__()
# self.kernel = kernel
# blurconv = nn.Conv2d(n_planes, n_planes, kernel_size=self.kernel.shape, stride=1, padding=0)
# blurconvr.weight.data = self.kernel
# blurconv.bias.data[:] = 0
self.n_planes = n_planes
self.preserve_size = preserve_size
# kernel_torch = torch.from_numpy(self.kernel)
# for i in range(n_planes):
# blurconv.weight.data[i, i] = kernel_torch
# self.blurconv_ = blurconv
#
# if preserve_size:
#
# if self.kernel.shape[0] % 2 == 1:
# pad = int((self.kernel.shape[0] - 1) / 2.)
# else:
# pad = int((self.kernel.shape[0] - factor) / 2.)
#
# self.padding = nn.ReplicationPad2d(pad)
#
# self.preserve_size = preserve_size
def forward(self, input, kernel):
if self.preserve_size:
if kernel.shape[0] % 2 == 1:
pad = int((kernel.shape[3] - 1) / 2.)
else:
pad = int((kernel.shape[3] - 1.) / 2.)
padding = nn.ReplicationPad2d(pad)
x = padding(input)
else:
x= input
blurconv = nn.Conv2d(self.n_planes, self.n_planes, kernel_size=kernel.size(3), stride=1, padding=0, bias=False).cuda()
blurconv.weight.data[:] = kernel
return blurconv(x)
class Blurconv2(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes=1, preserve_size=False, k_size=21):
super(Blurconv2, self).__init__()
self.n_planes = n_planes
self.k_size = k_size
self.preserve_size = preserve_size
self.blurconv = nn.Conv2d(self.n_planes, self.n_planes, kernel_size=k_size, stride=1, padding=0, bias=False)
# self.blurconv.weight.data[:] /= self.blurconv.weight.data.sum()
def forward(self, input):
if self.preserve_size:
pad = int((self.k_size - 1.) / 2.)
padding = nn.ReplicationPad2d(pad)
x = padding(input)
else:
x= input
#self.blurconv.weight.data[:] /= self.blurconv.weight.data.sum()
return self.blurconv(x)
def get_kernel(factor, kernel_type, phase, kernel_width, support=None, sigma=None):
assert kernel_type in ['lanczos', 'gauss', 'box']
# factor = float(factor)
if phase == 0.5 and kernel_type != 'box':
kernel = np.zeros([kernel_width - 1, kernel_width - 1])
else:
kernel = np.zeros([kernel_width, kernel_width])
if kernel_type == 'box':
assert phase == 0.5, 'Box filter is always half-phased'
kernel[:] = 1./(kernel_width * kernel_width)
elif kernel_type == 'gauss':
assert sigma, 'sigma is not specified'
assert phase != 0.5, 'phase 1/2 for gauss not implemented'
center = (kernel_width + 1.)/2.
print(center, kernel_width)
sigma_sq = sigma * sigma
for i in range(1, kernel.shape[0] + 1):
for j in range(1, kernel.shape[1] + 1):
di = (i - center)/2.
dj = (j - center)/2.
kernel[i - 1][j - 1] = np.exp(-(di * di + dj * dj)/(2 * sigma_sq))
kernel[i - 1][j - 1] = kernel[i - 1][j - 1]/(2. * np.pi * sigma_sq)
elif kernel_type == 'lanczos':
assert support, 'support is not specified'
center = (kernel_width + 1) / 2.
for i in range(1, kernel.shape[0] + 1):
for j in range(1, kernel.shape[1] + 1):
if phase == 0.5:
di = abs(i + 0.5 - center) / factor
dj = abs(j + 0.5 - center) / factor
else:
di = abs(i - center) / factor
dj = abs(j - center) / factor
pi_sq = np.pi * np.pi
val = 1
if di != 0:
val = val * support * np.sin(np.pi * di) * np.sin(np.pi * di / support)
val = val / (np.pi * np.pi * di * di)
if dj != 0:
val = val * support * np.sin(np.pi * dj) * np.sin(np.pi * dj / support)
val = val / (np.pi * np.pi * dj * dj)
kernel[i - 1][j - 1] = val
else:
assert False, 'wrong method name'
kernel /= kernel.sum()
return kernel
#a = Downsampler(n_planes=3, factor=2, kernel_type='lanczos2', phase='1', preserve_size=True)
#################
# Learnable downsampler
# KS = 32
# dow = nn.Sequential(nn.ReplicationPad2d(int((KS - factor) / 2.)), nn.Conv2d(1,1,KS,factor))
# class Apply(nn.Module):
# def __init__(self, what, dim, *args):
# super(Apply, self).__init__()
# self.dim = dim
# self.what = what
# def forward(self, input):
# inputs = []
# for i in range(input.size(self.dim)):
# inputs.append(self.what(input.narrow(self.dim, i, 1)))
# return torch.cat(inputs, dim=self.dim)
# def __len__(self):
# return len(self._modules)
# downs = Apply(dow, 1)
# downs.type(dtype)(net_input.type(dtype)).size()
| 7,872 | 31.66805 | 129 | py |
SelfDeblur | SelfDeblur-master/networks/non_local_dot_product.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = nn.Sequential(self.phi, max_pool_layer)
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)
theta_x = theta_x.permute(0, 2, 1)
phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)
f = torch.matmul(theta_x, phi_x)
N = f.size(-1)
f_div_C = f / N
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 4,926 | 35.496296 | 102 | py |
SelfDeblur | SelfDeblur-master/networks/non_local_concatenation.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.concat_project = nn.Sequential(
nn.Conv2d(self.inter_channels * 2, 1, 1, 1, 0, bias=False),
nn.ReLU()
)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = nn.Sequential(self.phi, max_pool_layer)
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
# (b, c, N, 1)
theta_x = self.theta(x).view(batch_size, self.inter_channels, -1, 1)
# (b, c, 1, N)
phi_x = self.phi(x).view(batch_size, self.inter_channels, 1, -1)
h = theta_x.size(2)
w = phi_x.size(3)
theta_x = theta_x.repeat(1, 1, 1, w)
phi_x = phi_x.repeat(1, 1, h, 1)
concat_feature = torch.cat([theta_x, phi_x], dim=1)
f = self.concat_project(concat_feature)
b, _, h, w = f.size()
f = f.view(b, h, w)
N = f.size(-1)
f_div_C = f / N
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 5,350 | 35.155405 | 102 | py |
SelfDeblur | SelfDeblur-master/networks/common.py | import torch
import torch.nn as nn
import numpy as np
from .downsampler import Downsampler
def add_module(self, module):
self.add_module(str(len(self) + 1), module)
torch.nn.Module.add = add_module
class Concat(nn.Module):
def __init__(self, dim, *args):
super(Concat, self).__init__()
self.dim = dim
for idx, module in enumerate(args):
self.add_module(str(idx), module)
def forward(self, input):
inputs = []
for module in self._modules.values():
inputs.append(module(input))
inputs_shapes2 = [x.shape[2] for x in inputs]
inputs_shapes3 = [x.shape[3] for x in inputs]
if np.all(np.array(inputs_shapes2) == min(inputs_shapes2)) and np.all(np.array(inputs_shapes3) == min(inputs_shapes3)):
inputs_ = inputs
else:
target_shape2 = min(inputs_shapes2)
target_shape3 = min(inputs_shapes3)
inputs_ = []
for inp in inputs:
diff2 = (inp.size(2) - target_shape2) // 2
diff3 = (inp.size(3) - target_shape3) // 2
inputs_.append(inp[:, :, diff2: diff2 + target_shape2, diff3:diff3 + target_shape3])
return torch.cat(inputs_, dim=self.dim)
def __len__(self):
return len(self._modules)
class GenNoise(nn.Module):
def __init__(self, dim2):
super(GenNoise, self).__init__()
self.dim2 = dim2
def forward(self, input):
a = list(input.size())
a[1] = self.dim2
# print (input.data.type())
b = torch.zeros(a).type_as(input.data)
b.normal_()
x = torch.autograd.Variable(b)
return x
class Swish(nn.Module):
"""
https://arxiv.org/abs/1710.05941
The hype was so huge that I could not help but try it
"""
def __init__(self):
super(Swish, self).__init__()
self.s = nn.Sigmoid()
def forward(self, x):
return x * self.s(x)
def act(act_fun = 'LeakyReLU'):
'''
Either string defining an activation function or module (e.g. nn.ReLU)
'''
if isinstance(act_fun, str):
if act_fun == 'LeakyReLU':
return nn.LeakyReLU(0.2, inplace=True)
elif act_fun == 'Swish':
return Swish()
elif act_fun == 'ELU':
return nn.ELU()
elif act_fun == 'none':
return nn.Sequential()
else:
assert False
else:
return act_fun()
def bn(num_features):
return nn.BatchNorm2d(num_features)
def conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero', downsample_mode='stride'):
downsampler = None
if stride != 1 and downsample_mode != 'stride':
if downsample_mode == 'avg':
downsampler = nn.AvgPool2d(stride, stride)
elif downsample_mode == 'max':
downsampler = nn.MaxPool2d(stride, stride)
elif downsample_mode in ['lanczos2', 'lanczos3']:
downsampler = Downsampler(n_planes=out_f, factor=stride, kernel_type=downsample_mode, phase=0.5, preserve_size=True)
else:
assert False
stride = 1
padder = None
to_pad = int((kernel_size - 1) / 2)
if pad == 'reflection':
padder = nn.ReflectionPad2d(to_pad)
to_pad = 0
convolver = nn.Conv2d(in_f, out_f, kernel_size, stride, padding=to_pad, bias=bias)
layers = filter(lambda x: x is not None, [padder, convolver, downsampler])
return nn.Sequential(*layers) | 3,531 | 27.483871 | 128 | py |
SelfDeblur | SelfDeblur-master/networks/unet.py | import torch.nn as nn
import torch
import torch.nn as nn
import torch.nn.functional as F
from .common import *
class ListModule(nn.Module):
def __init__(self, *args):
super(ListModule, self).__init__()
idx = 0
for module in args:
self.add_module(str(idx), module)
idx += 1
def __getitem__(self, idx):
if idx >= len(self._modules):
raise IndexError('index {} is out of range'.format(idx))
if idx < 0:
idx = len(self) + idx
it = iter(self._modules.values())
for i in range(idx):
next(it)
return next(it)
def __iter__(self):
return iter(self._modules.values())
def __len__(self):
return len(self._modules)
class UNet(nn.Module):
'''
upsample_mode in ['deconv', 'nearest', 'bilinear']
pad in ['zero', 'replication', 'none']
'''
def __init__(self, num_input_channels=3, num_output_channels=3,
feature_scale=4, more_layers=0, concat_x=False,
upsample_mode='deconv', pad='zero', norm_layer=nn.InstanceNorm2d, need_sigmoid=True, need_bias=True):
super(UNet, self).__init__()
self.feature_scale = feature_scale
self.more_layers = more_layers
self.concat_x = concat_x
filters = [64, 128, 256, 512, 1024]
filters = [x // self.feature_scale for x in filters]
self.start = unetConv2(num_input_channels, filters[0] if not concat_x else filters[0] - num_input_channels, norm_layer, need_bias, pad)
self.down1 = unetDown(filters[0], filters[1] if not concat_x else filters[1] - num_input_channels, norm_layer, need_bias, pad)
self.down2 = unetDown(filters[1], filters[2] if not concat_x else filters[2] - num_input_channels, norm_layer, need_bias, pad)
self.down3 = unetDown(filters[2], filters[3] if not concat_x else filters[3] - num_input_channels, norm_layer, need_bias, pad)
self.down4 = unetDown(filters[3], filters[4] if not concat_x else filters[4] - num_input_channels, norm_layer, need_bias, pad)
# more downsampling layers
if self.more_layers > 0:
self.more_downs = [
unetDown(filters[4], filters[4] if not concat_x else filters[4] - num_input_channels , norm_layer, need_bias, pad) for i in range(self.more_layers)]
self.more_ups = [unetUp(filters[4], upsample_mode, need_bias, pad, same_num_filt =True) for i in range(self.more_layers)]
self.more_downs = ListModule(*self.more_downs)
self.more_ups = ListModule(*self.more_ups)
self.up4 = unetUp(filters[3], upsample_mode, need_bias, pad)
self.up3 = unetUp(filters[2], upsample_mode, need_bias, pad)
self.up2 = unetUp(filters[1], upsample_mode, need_bias, pad)
self.up1 = unetUp(filters[0], upsample_mode, need_bias, pad)
self.final = conv(filters[0], num_output_channels, 1, bias=need_bias, pad=pad)
if need_sigmoid:
self.final = nn.Sequential(self.final, nn.Sigmoid())
def forward(self, inputs):
# Downsample
downs = [inputs]
down = nn.AvgPool2d(2, 2)
for i in range(4 + self.more_layers):
downs.append(down(downs[-1]))
in64 = self.start(inputs)
if self.concat_x:
in64 = torch.cat([in64, downs[0]], 1)
down1 = self.down1(in64)
if self.concat_x:
down1 = torch.cat([down1, downs[1]], 1)
down2 = self.down2(down1)
if self.concat_x:
down2 = torch.cat([down2, downs[2]], 1)
down3 = self.down3(down2)
if self.concat_x:
down3 = torch.cat([down3, downs[3]], 1)
down4 = self.down4(down3)
if self.concat_x:
down4 = torch.cat([down4, downs[4]], 1)
if self.more_layers > 0:
prevs = [down4]
for kk, d in enumerate(self.more_downs):
# print(prevs[-1].size())
out = d(prevs[-1])
if self.concat_x:
out = torch.cat([out, downs[kk + 5]], 1)
prevs.append(out)
up_ = self.more_ups[-1](prevs[-1], prevs[-2])
for idx in range(self.more_layers - 1):
l = self.more_ups[self.more - idx - 2]
up_= l(up_, prevs[self.more - idx - 2])
else:
up_= down4
up4= self.up4(up_, down3)
up3= self.up3(up4, down2)
up2= self.up2(up3, down1)
up1= self.up1(up2, in64)
return self.final(up1)
class unetConv2(nn.Module):
def __init__(self, in_size, out_size, norm_layer, need_bias, pad):
super(unetConv2, self).__init__()
print(pad)
if norm_layer is not None:
self.conv1= nn.Sequential(conv(in_size, out_size, 3, bias=need_bias, pad=pad),
norm_layer(out_size),
nn.ReLU(),)
self.conv2= nn.Sequential(conv(out_size, out_size, 3, bias=need_bias, pad=pad),
norm_layer(out_size),
nn.ReLU(),)
else:
self.conv1= nn.Sequential(conv(in_size, out_size, 3, bias=need_bias, pad=pad),
nn.ReLU(),)
self.conv2= nn.Sequential(conv(out_size, out_size, 3, bias=need_bias, pad=pad),
nn.ReLU(),)
def forward(self, inputs):
outputs= self.conv1(inputs)
outputs= self.conv2(outputs)
return outputs
class unetDown(nn.Module):
def __init__(self, in_size, out_size, norm_layer, need_bias, pad):
super(unetDown, self).__init__()
self.conv= unetConv2(in_size, out_size, norm_layer, need_bias, pad)
self.down= nn.MaxPool2d(2, 2)
def forward(self, inputs):
outputs= self.down(inputs)
outputs= self.conv(outputs)
return outputs
class unetUp(nn.Module):
def __init__(self, out_size, upsample_mode, need_bias, pad, same_num_filt=False):
super(unetUp, self).__init__()
num_filt = out_size if same_num_filt else out_size * 2
if upsample_mode == 'deconv':
self.up= nn.ConvTranspose2d(num_filt, out_size, 4, stride=2, padding=1)
self.conv= unetConv2(out_size * 2, out_size, None, need_bias, pad)
elif upsample_mode=='bilinear' or upsample_mode=='nearest':
self.up = nn.Sequential(nn.Upsample(scale_factor=2, mode=upsample_mode),
conv(num_filt, out_size, 3, bias=need_bias, pad=pad))
self.conv= unetConv2(out_size * 2, out_size, None, need_bias, pad)
else:
assert False
def forward(self, inputs1, inputs2):
in1_up= self.up(inputs1)
if (inputs2.size(2) != in1_up.size(2)) or (inputs2.size(3) != in1_up.size(3)):
diff2 = (inputs2.size(2) - in1_up.size(2)) // 2
diff3 = (inputs2.size(3) - in1_up.size(3)) // 2
inputs2_ = inputs2[:, :, diff2 : diff2 + in1_up.size(2), diff3 : diff3 + in1_up.size(3)]
else:
inputs2_ = inputs2
output= self.conv(torch.cat([in1_up, inputs2_], 1))
return output
if __name__ =='__main__':
print(1)
# net = UNet()
# print(net.forward) | 7,408 | 36.045 | 164 | py |
SelfDeblur | SelfDeblur-master/networks/non_local_gaussian.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = max_pool_layer
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
theta_x = x.view(batch_size, self.in_channels, -1)
theta_x = theta_x.permute(0, 2, 1)
if self.sub_sample:
phi_x = self.phi(x).view(batch_size, self.in_channels, -1)
else:
phi_x = x.view(batch_size, self.in_channels, -1)
f = torch.matmul(theta_x, phi_x)
f_div_C = F.softmax(f, dim=-1)
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 4,674 | 33.124088 | 102 | py |
SelfDeblur | SelfDeblur-master/models/skipfc.py | import torch
import torch.nn as nn
from .common import *
def skipfc(num_input_channels=2, num_output_channels=3,
num_channels_down=[16, 32, 64, 128, 128], num_channels_up=[16, 32, 64, 128, 128], num_channels_skip=[4, 4, 4, 4, 4],
filter_size_down=3, filter_size_up=1, filter_skip_size=1,
need_sigmoid=True, need_bias=True,
pad='zero', upsample_mode='nearest', downsample_mode='stride', act_fun='LeakyReLU',
need1x1_up=True):
"""Assembles encoder-decoder with skip connections.
Arguments:
act_fun: Either string 'LeakyReLU|Swish|ELU|none' or module (e.g. nn.ReLU)
pad (string): zero|reflection (default: 'zero')
upsample_mode (string): 'nearest|bilinear' (default: 'nearest')
downsample_mode (string): 'stride|avg|max|lanczos2' (default: 'stride')
"""
# assert len(num_channels_down) == len(num_channels_up) == len(num_channels_skip)
#
# n_scales = len(num_channels_down)
#
# if not (isinstance(upsample_mode, list) or isinstance(upsample_mode, tuple)):
# upsample_mode = [upsample_mode]*n_scales
#
# if not (isinstance(downsample_mode, list) or isinstance(downsample_mode, tuple)):
# downsample_mode = [downsample_mode]*n_scales
#
# if not (isinstance(filter_size_down, list) or isinstance(filter_size_down, tuple)):
# filter_size_down = [filter_size_down]*n_scales
#
# if not (isinstance(filter_size_up, list) or isinstance(filter_size_up, tuple)):
# filter_size_up = [filter_size_up]*n_scales
#
# last_scale = n_scales - 1
#
# cur_depth = None
#
# model = nn.Sequential()
# model_tmp = model
#
# input_depth = num_input_channels
# for i in range(len(num_channels_down)):
#
# deeper = nn.Sequential()
# skip = nn.Sequential()
#
# if num_channels_skip[i] != 0:
# model_tmp.add(Concat(1, skip, deeper))
# else:
# model_tmp.add(deeper)
#
# model_tmp.add(bn(num_channels_skip[i] + (num_channels_up[i + 1] if i < last_scale else num_channels_down[i])))
#
# if num_channels_skip[i] != 0:
# skip.add(nn.Linear(input_depth, num_channels_skip[i]))
# skip.add(bn(num_channels_skip[i]))
# skip.add(act(act_fun))
#
# # skip.add(Concat(2, GenNoise(nums_noise[i]), skip_part))
#
# deeper.add(nn.Linear(input_depth, num_channels_down[i]))
# deeper.add(bn(num_channels_down[i]))
# deeper.add(act(act_fun))
#
# deeper.add(nn.Linear(num_channels_down[i], num_channels_down[i]))
# deeper.add(bn(num_channels_down[i]))
# deeper.add(act(act_fun))
#
# deeper_main = nn.Sequential()
#
# if i == len(num_channels_down) - 1:
# # The deepest
# k = num_channels_down[i]
# else:
# deeper.add(deeper_main)
# k = num_channels_up[i + 1]
#
# deeper.add(nn.Upsample(scale_factor=2, mode=upsample_mode[i]))
#
# model_tmp.add(nn.Linear(num_channels_skip[i] + k, num_channels_up[i]))
# model_tmp.add(bn(num_channels_up[i]))
# model_tmp.add(act(act_fun))
#
#
# if need1x1_up:
# model_tmp.add(nn.Linear(num_channels_up[i], num_channels_up[i]))
# model_tmp.add(bn(num_channels_up[i]))
# model_tmp.add(act(act_fun))
#
# input_depth = num_channels_down[i]
# model_tmp = deeper_main
#
# model.add(nn.Linear(num_channels_up[0], num_output_channels))
# if need_sigmoid:
# model.add(nn.Softmax())
#
# return model
model = nn.Sequential()
model.add(nn.Linear(num_input_channels, num_channels_down[0],bias=True))
model.add(nn.ReLU6())
# model.add(nn.Tanh())
# model.add(nn.Linear(num_channels_down[0], num_channels_down[0],bias=True))
# model.add(nn.ReLU6())
# model.add(nn.Linear(num_channels_down[0], num_channels_down[0],bias=True))
# model.add(nn.ReLU6())
# model.add(nn.Linear(num_channels_down[0], num_channels_down[0],bias=True))
# model.add(nn.ReLU6())
# model.add(nn.Linear(num_channels_down[0], num_channels_down[0],bias=True))
# model.add(nn.ReLU6())
# model.add(nn.Linear(num_channels_down[0], num_channels_down[0],bias=True))
# model.add(nn.ReLU6())
# model.add(nn.Linear(num_channels_down[0], num_channels_down[1]))
# model.add(act(act_fun))
# model.add(nn.Linear(num_channels_down[1], num_channels_down[2]))
# model.add(act(act_fun))
# model.add(nn.Linear(num_channels_down[2], num_channels_down[3]))
# model.add(act(act_fun))
# model.add(nn.Linear(num_channels_down[3], num_channels_up[3]))
# model.add(act(act_fun))
# model.add(nn.Linear(num_channels_up[3], num_channels_up[2]))
# model.add(act(act_fun))
# model.add(nn.Linear(num_channels_up[2], num_channels_up[1]))
# model.add(act(act_fun))
# model.add(nn.Linear(num_channels_up[1], num_channels_up[0]))
# model.add(act(act_fun))
model.add(nn.Linear(num_channels_down[0], num_output_channels))
# model.add(nn.ReLU())
model.add(nn.Softmax())
# model.add(nn.Threshold(0.00001, 0))
return model
| 5,145 | 34.489655 | 128 | py |
SelfDeblur | SelfDeblur-master/models/non_local_embedded_gaussian.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = nn.Sequential(self.phi, max_pool_layer)
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)
theta_x = theta_x.permute(0, 2, 1)
phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)
f = torch.matmul(theta_x, phi_x)
f_div_C = F.softmax(f, dim=-1)
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 4,916 | 36.25 | 102 | py |
SelfDeblur | SelfDeblur-master/models/skip.py | import torch
import torch.nn as nn
from .common import *
from .non_local_dot_product import NONLocalBlock2D
def skip(
num_input_channels=2, num_output_channels=3,
num_channels_down=[16, 32, 64, 128, 128], num_channels_up=[16, 32, 64, 128, 128], num_channels_skip=[4, 4, 4, 4, 4],
filter_size_down=3, filter_size_up=3, filter_skip_size=1,
need_sigmoid=True, need_bias=True,
pad='zero', upsample_mode='nearest', downsample_mode='stride', act_fun='LeakyReLU',
need1x1_up=True):
"""Assembles encoder-decoder with skip connections.
Arguments:
act_fun: Either string 'LeakyReLU|Swish|ELU|none' or module (e.g. nn.ReLU)
pad (string): zero|reflection (default: 'zero')
upsample_mode (string): 'nearest|bilinear' (default: 'nearest')
downsample_mode (string): 'stride|avg|max|lanczos2' (default: 'stride')
"""
assert len(num_channels_down) == len(num_channels_up) == len(num_channels_skip)
n_scales = len(num_channels_down)
if not (isinstance(upsample_mode, list) or isinstance(upsample_mode, tuple)):
upsample_mode = [upsample_mode]*n_scales
if not (isinstance(downsample_mode, list) or isinstance(downsample_mode, tuple)):
downsample_mode = [downsample_mode]*n_scales
if not (isinstance(filter_size_down, list) or isinstance(filter_size_down, tuple)):
filter_size_down = [filter_size_down]*n_scales
if not (isinstance(filter_size_up, list) or isinstance(filter_size_up, tuple)):
filter_size_up = [filter_size_up]*n_scales
last_scale = n_scales - 1
cur_depth = None
model = nn.Sequential()
model_tmp = model
input_depth = num_input_channels
for i in range(len(num_channels_down)):
deeper = nn.Sequential()
skip = nn.Sequential()
if num_channels_skip[i] != 0:
model_tmp.add(Concat(1, skip, deeper))
else:
model_tmp.add(deeper)
model_tmp.add(bn(num_channels_skip[i] + (num_channels_up[i + 1] if i < last_scale else num_channels_down[i])))
if num_channels_skip[i] != 0:
skip.add(conv(input_depth, num_channels_skip[i], filter_skip_size, bias=need_bias, pad=pad))
skip.add(bn(num_channels_skip[i]))
skip.add(act(act_fun))
# skip.add(Concat(2, GenNoise(nums_noise[i]), skip_part))
deeper.add(conv(input_depth, num_channels_down[i], filter_size_down[i], 2, bias=need_bias, pad=pad, downsample_mode=downsample_mode[i]))
deeper.add(bn(num_channels_down[i]))
deeper.add(act(act_fun))
if i>1:
deeper.add(NONLocalBlock2D(in_channels=num_channels_down[i]))
deeper.add(conv(num_channels_down[i], num_channels_down[i], filter_size_down[i], bias=need_bias, pad=pad))
deeper.add(bn(num_channels_down[i]))
deeper.add(act(act_fun))
deeper_main = nn.Sequential()
if i == len(num_channels_down) - 1:
# The deepest
k = num_channels_down[i]
else:
deeper.add(deeper_main)
k = num_channels_up[i + 1]
deeper.add(nn.Upsample(scale_factor=2, mode=upsample_mode[i]))
model_tmp.add(conv(num_channels_skip[i] + k, num_channels_up[i], filter_size_up[i], 1, bias=need_bias, pad=pad))
model_tmp.add(bn(num_channels_up[i]))
model_tmp.add(act(act_fun))
if need1x1_up:
model_tmp.add(conv(num_channels_up[i], num_channels_up[i], 1, bias=need_bias, pad=pad))
model_tmp.add(bn(num_channels_up[i]))
model_tmp.add(act(act_fun))
input_depth = num_channels_down[i]
model_tmp = deeper_main
model.add(conv(num_channels_up[0], num_output_channels, 1, bias=need_bias, pad=pad))
if need_sigmoid:
model.add(nn.Sigmoid())
return model
| 3,885 | 35.317757 | 144 | py |
SelfDeblur | SelfDeblur-master/models/resnet.py | import torch
import torch.nn as nn
from numpy.random import normal
from numpy.linalg import svd
from math import sqrt
import torch.nn.init
from .common import *
class ResidualSequential(nn.Sequential):
def __init__(self, *args):
super(ResidualSequential, self).__init__(*args)
def forward(self, x):
out = super(ResidualSequential, self).forward(x)
# print(x.size(), out.size())
x_ = None
if out.size(2) != x.size(2) or out.size(3) != x.size(3):
diff2 = x.size(2) - out.size(2)
diff3 = x.size(3) - out.size(3)
# print(1)
x_ = x[:, :, diff2 /2:out.size(2) + diff2 / 2, diff3 / 2:out.size(3) + diff3 / 2]
else:
x_ = x
return out + x_
def eval(self):
print(2)
for m in self.modules():
m.eval()
exit()
def get_block(num_channels, norm_layer, act_fun):
layers = [
nn.Conv2d(num_channels, num_channels, 3, 1, 1, bias=False),
norm_layer(num_channels, affine=True),
act(act_fun),
nn.Conv2d(num_channels, num_channels, 3, 1, 1, bias=False),
norm_layer(num_channels, affine=True),
]
return layers
class ResNet(nn.Module):
def __init__(self, num_input_channels, num_output_channels, num_blocks, num_channels, need_residual=True, act_fun='LeakyReLU', need_sigmoid=True, norm_layer=nn.BatchNorm2d, pad='reflection'):
'''
pad = 'start|zero|replication'
'''
super(ResNet, self).__init__()
if need_residual:
s = ResidualSequential
else:
s = nn.Sequential
# stride = 1
# First layers
layers = [
# nn.ReplicationPad2d(num_blocks * 2 * stride + 3),
conv(num_input_channels, num_channels, 3, stride=1, bias=True, pad=pad),
act(act_fun)
]
# Residual blocks
# layers_residual = []
for i in range(num_blocks):
layers += [s(*get_block(num_channels, norm_layer, act_fun))]
layers += [
nn.Conv2d(num_channels, num_channels, 3, 1, 1),
norm_layer(num_channels, affine=True)
]
# if need_residual:
# layers += [ResidualSequential(*layers_residual)]
# else:
# layers += [Sequential(*layers_residual)]
# if factor >= 2:
# # Do upsampling if needed
# layers += [
# nn.Conv2d(num_channels, num_channels *
# factor ** 2, 3, 1),
# nn.PixelShuffle(factor),
# act(act_fun)
# ]
layers += [
conv(num_channels, num_output_channels, 3, 1, bias=True, pad=pad),
nn.Sigmoid()
]
self.model = nn.Sequential(*layers)
def forward(self, input):
return self.model(input)
def eval(self):
self.model.eval()
| 2,945 | 29.371134 | 195 | py |
SelfDeblur | SelfDeblur-master/models/downsampler.py | import numpy as np
import torch
import torch.nn as nn
class Downsampler(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes, factor, kernel_type, phase=0, kernel_width=None, support=None, sigma=None, preserve_size=False):
super(Downsampler, self).__init__()
assert phase in [0, 0.5], 'phase should be 0 or 0.5'
if kernel_type == 'lanczos2':
support = 2
kernel_width = 4 * factor + 1
kernel_type_ = 'lanczos'
elif kernel_type == 'lanczos3':
support = 3
kernel_width = 6 * factor + 1
kernel_type_ = 'lanczos'
elif kernel_type == 'gauss12':
kernel_width = 7
sigma = 1/2
kernel_type_ = 'gauss'
elif kernel_type == 'gauss1sq2':
kernel_width = 9
sigma = 1./np.sqrt(2)
kernel_type_ = 'gauss'
elif kernel_type in ['lanczos', 'gauss', 'box']:
kernel_type_ = kernel_type
else:
assert False, 'wrong name kernel'
# note that `kernel width` will be different to actual size for phase = 1/2
self.kernel = get_kernel(factor, kernel_type_, phase, kernel_width, support=support, sigma=sigma)
downsampler = nn.Conv2d(n_planes, n_planes, kernel_size=self.kernel.shape, stride=factor, padding=0)
downsampler.weight.data[:] = 0
downsampler.bias.data[:] = 0
kernel_torch = torch.from_numpy(self.kernel)
for i in range(n_planes):
downsampler.weight.data[i, i] = kernel_torch
self.downsampler_ = downsampler
if preserve_size:
if self.kernel.shape[0] % 2 == 1:
pad = int((self.kernel.shape[0] - 1) / 2.)
else:
pad = int((self.kernel.shape[0] - factor) / 2.)
self.padding = nn.ReplicationPad2d(pad)
self.preserve_size = preserve_size
def forward(self, input):
if self.preserve_size:
x = self.padding(input)
else:
x= input
self.x = x
return self.downsampler_(x)
class Blurconv(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes=1, preserve_size=False):
super(Blurconv, self).__init__()
# self.kernel = kernel
# blurconv = nn.Conv2d(n_planes, n_planes, kernel_size=self.kernel.shape, stride=1, padding=0)
# blurconvr.weight.data = self.kernel
# blurconv.bias.data[:] = 0
self.n_planes = n_planes
self.preserve_size = preserve_size
# kernel_torch = torch.from_numpy(self.kernel)
# for i in range(n_planes):
# blurconv.weight.data[i, i] = kernel_torch
# self.blurconv_ = blurconv
#
# if preserve_size:
#
# if self.kernel.shape[0] % 2 == 1:
# pad = int((self.kernel.shape[0] - 1) / 2.)
# else:
# pad = int((self.kernel.shape[0] - factor) / 2.)
#
# self.padding = nn.ReplicationPad2d(pad)
#
# self.preserve_size = preserve_size
def forward(self, input, kernel):
if self.preserve_size:
if kernel.shape[0] % 2 == 1:
pad = int((kernel.shape[3] - 1) / 2.)
else:
pad = int((kernel.shape[3] - 1.) / 2.)
padding = nn.ReplicationPad2d(pad)
x = padding(input)
else:
x= input
blurconv = nn.Conv2d(self.n_planes, self.n_planes, kernel_size=kernel.size(3), stride=1, padding=0, bias=False).cuda()
blurconv.weight.data[:] = kernel
return blurconv(x)
class Blurconv2(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes=1, preserve_size=False, k_size=21):
super(Blurconv2, self).__init__()
self.n_planes = n_planes
self.k_size = k_size
self.preserve_size = preserve_size
self.blurconv = nn.Conv2d(self.n_planes, self.n_planes, kernel_size=k_size, stride=1, padding=0, bias=False)
# self.blurconv.weight.data[:] /= self.blurconv.weight.data.sum()
def forward(self, input):
if self.preserve_size:
pad = int((self.k_size - 1.) / 2.)
padding = nn.ReplicationPad2d(pad)
x = padding(input)
else:
x= input
#self.blurconv.weight.data[:] /= self.blurconv.weight.data.sum()
return self.blurconv(x)
def get_kernel(factor, kernel_type, phase, kernel_width, support=None, sigma=None):
assert kernel_type in ['lanczos', 'gauss', 'box']
# factor = float(factor)
if phase == 0.5 and kernel_type != 'box':
kernel = np.zeros([kernel_width - 1, kernel_width - 1])
else:
kernel = np.zeros([kernel_width, kernel_width])
if kernel_type == 'box':
assert phase == 0.5, 'Box filter is always half-phased'
kernel[:] = 1./(kernel_width * kernel_width)
elif kernel_type == 'gauss':
assert sigma, 'sigma is not specified'
assert phase != 0.5, 'phase 1/2 for gauss not implemented'
center = (kernel_width + 1.)/2.
print(center, kernel_width)
sigma_sq = sigma * sigma
for i in range(1, kernel.shape[0] + 1):
for j in range(1, kernel.shape[1] + 1):
di = (i - center)/2.
dj = (j - center)/2.
kernel[i - 1][j - 1] = np.exp(-(di * di + dj * dj)/(2 * sigma_sq))
kernel[i - 1][j - 1] = kernel[i - 1][j - 1]/(2. * np.pi * sigma_sq)
elif kernel_type == 'lanczos':
assert support, 'support is not specified'
center = (kernel_width + 1) / 2.
for i in range(1, kernel.shape[0] + 1):
for j in range(1, kernel.shape[1] + 1):
if phase == 0.5:
di = abs(i + 0.5 - center) / factor
dj = abs(j + 0.5 - center) / factor
else:
di = abs(i - center) / factor
dj = abs(j - center) / factor
pi_sq = np.pi * np.pi
val = 1
if di != 0:
val = val * support * np.sin(np.pi * di) * np.sin(np.pi * di / support)
val = val / (np.pi * np.pi * di * di)
if dj != 0:
val = val * support * np.sin(np.pi * dj) * np.sin(np.pi * dj / support)
val = val / (np.pi * np.pi * dj * dj)
kernel[i - 1][j - 1] = val
else:
assert False, 'wrong method name'
kernel /= kernel.sum()
return kernel
#a = Downsampler(n_planes=3, factor=2, kernel_type='lanczos2', phase='1', preserve_size=True)
#################
# Learnable downsampler
# KS = 32
# dow = nn.Sequential(nn.ReplicationPad2d(int((KS - factor) / 2.)), nn.Conv2d(1,1,KS,factor))
# class Apply(nn.Module):
# def __init__(self, what, dim, *args):
# super(Apply, self).__init__()
# self.dim = dim
# self.what = what
# def forward(self, input):
# inputs = []
# for i in range(input.size(self.dim)):
# inputs.append(self.what(input.narrow(self.dim, i, 1)))
# return torch.cat(inputs, dim=self.dim)
# def __len__(self):
# return len(self._modules)
# downs = Apply(dow, 1)
# downs.type(dtype)(net_input.type(dtype)).size()
| 7,872 | 31.66805 | 129 | py |
SelfDeblur | SelfDeblur-master/models/non_local_dot_product.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = nn.Sequential(self.phi, max_pool_layer)
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)
theta_x = theta_x.permute(0, 2, 1)
phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)
f = torch.matmul(theta_x, phi_x)
N = f.size(-1)
f_div_C = f / N
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 4,926 | 35.496296 | 102 | py |
SelfDeblur | SelfDeblur-master/models/texture_nets.py | import torch
import torch.nn as nn
from .common import *
normalization = nn.BatchNorm2d
def conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero'):
if pad == 'zero':
return nn.Conv2d(in_f, out_f, kernel_size, stride, padding=(kernel_size - 1) / 2, bias=bias)
elif pad == 'reflection':
layers = [nn.ReflectionPad2d((kernel_size - 1) / 2),
nn.Conv2d(in_f, out_f, kernel_size, stride, padding=0, bias=bias)]
return nn.Sequential(*layers)
def get_texture_nets(inp=3, ratios = [32, 16, 8, 4, 2, 1], fill_noise=False, pad='zero', need_sigmoid=False, conv_num=8, upsample_mode='nearest'):
for i in range(len(ratios)):
j = i + 1
seq = nn.Sequential()
tmp = nn.AvgPool2d(ratios[i], ratios[i])
seq.add(tmp)
if fill_noise:
seq.add(GenNoise(inp))
seq.add(conv(inp, conv_num, 3, pad=pad))
seq.add(normalization(conv_num))
seq.add(act())
seq.add(conv(conv_num, conv_num, 3, pad=pad))
seq.add(normalization(conv_num))
seq.add(act())
seq.add(conv(conv_num, conv_num, 1, pad=pad))
seq.add(normalization(conv_num))
seq.add(act())
if i == 0:
seq.add(nn.Upsample(scale_factor=2, mode=upsample_mode))
cur = seq
else:
cur_temp = cur
cur = nn.Sequential()
# Batch norm before merging
seq.add(normalization(conv_num))
cur_temp.add(normalization(conv_num * (j - 1)))
cur.add(Concat(1, cur_temp, seq))
cur.add(conv(conv_num * j, conv_num * j, 3, pad=pad))
cur.add(normalization(conv_num * j))
cur.add(act())
cur.add(conv(conv_num * j, conv_num * j, 3, pad=pad))
cur.add(normalization(conv_num * j))
cur.add(act())
cur.add(conv(conv_num * j, conv_num * j, 1, pad=pad))
cur.add(normalization(conv_num * j))
cur.add(act())
if i == len(ratios) - 1:
cur.add(conv(conv_num * j, 3, 1, pad=pad))
else:
cur.add(nn.Upsample(scale_factor=2, mode=upsample_mode))
model = cur
if need_sigmoid:
model.add(nn.Sigmoid())
return model
| 2,315 | 27.95 | 146 | py |
SelfDeblur | SelfDeblur-master/models/non_local_concatenation.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
self.concat_project = nn.Sequential(
nn.Conv2d(self.inter_channels * 2, 1, 1, 1, 0, bias=False),
nn.ReLU()
)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = nn.Sequential(self.phi, max_pool_layer)
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
# (b, c, N, 1)
theta_x = self.theta(x).view(batch_size, self.inter_channels, -1, 1)
# (b, c, 1, N)
phi_x = self.phi(x).view(batch_size, self.inter_channels, 1, -1)
h = theta_x.size(2)
w = phi_x.size(3)
theta_x = theta_x.repeat(1, 1, 1, w)
phi_x = phi_x.repeat(1, 1, h, 1)
concat_feature = torch.cat([theta_x, phi_x], dim=1)
f = self.concat_project(concat_feature)
b, _, h, w = f.size()
f = f.view(b, h, w)
N = f.size(-1)
f_div_C = f / N
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 5,350 | 35.155405 | 102 | py |
SelfDeblur | SelfDeblur-master/models/common.py | import torch
import torch.nn as nn
import numpy as np
from .downsampler import Downsampler
def add_module(self, module):
self.add_module(str(len(self) + 1), module)
torch.nn.Module.add = add_module
class Concat(nn.Module):
def __init__(self, dim, *args):
super(Concat, self).__init__()
self.dim = dim
for idx, module in enumerate(args):
self.add_module(str(idx), module)
def forward(self, input):
inputs = []
for module in self._modules.values():
inputs.append(module(input))
inputs_shapes2 = [x.shape[2] for x in inputs]
inputs_shapes3 = [x.shape[3] for x in inputs]
if np.all(np.array(inputs_shapes2) == min(inputs_shapes2)) and np.all(np.array(inputs_shapes3) == min(inputs_shapes3)):
inputs_ = inputs
else:
target_shape2 = min(inputs_shapes2)
target_shape3 = min(inputs_shapes3)
inputs_ = []
for inp in inputs:
diff2 = (inp.size(2) - target_shape2) // 2
diff3 = (inp.size(3) - target_shape3) // 2
inputs_.append(inp[:, :, diff2: diff2 + target_shape2, diff3:diff3 + target_shape3])
return torch.cat(inputs_, dim=self.dim)
def __len__(self):
return len(self._modules)
class GenNoise(nn.Module):
def __init__(self, dim2):
super(GenNoise, self).__init__()
self.dim2 = dim2
def forward(self, input):
a = list(input.size())
a[1] = self.dim2
# print (input.data.type())
b = torch.zeros(a).type_as(input.data)
b.normal_()
x = torch.autograd.Variable(b)
return x
class Swish(nn.Module):
"""
https://arxiv.org/abs/1710.05941
The hype was so huge that I could not help but try it
"""
def __init__(self):
super(Swish, self).__init__()
self.s = nn.Sigmoid()
def forward(self, x):
return x * self.s(x)
def act(act_fun = 'LeakyReLU'):
'''
Either string defining an activation function or module (e.g. nn.ReLU)
'''
if isinstance(act_fun, str):
if act_fun == 'LeakyReLU':
return nn.LeakyReLU(0.2, inplace=True)
elif act_fun == 'Swish':
return Swish()
elif act_fun == 'ELU':
return nn.ELU()
elif act_fun == 'none':
return nn.Sequential()
else:
assert False
else:
return act_fun()
def bn(num_features):
return nn.BatchNorm2d(num_features)
def conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero', downsample_mode='stride'):
downsampler = None
if stride != 1 and downsample_mode != 'stride':
if downsample_mode == 'avg':
downsampler = nn.AvgPool2d(stride, stride)
elif downsample_mode == 'max':
downsampler = nn.MaxPool2d(stride, stride)
elif downsample_mode in ['lanczos2', 'lanczos3']:
downsampler = Downsampler(n_planes=out_f, factor=stride, kernel_type=downsample_mode, phase=0.5, preserve_size=True)
else:
assert False
stride = 1
padder = None
to_pad = int((kernel_size - 1) / 2)
if pad == 'reflection':
padder = nn.ReflectionPad2d(to_pad)
to_pad = 0
convolver = nn.Conv2d(in_f, out_f, kernel_size, stride, padding=to_pad, bias=bias)
layers = filter(lambda x: x is not None, [padder, convolver, downsampler])
return nn.Sequential(*layers) | 3,531 | 27.483871 | 128 | py |
SelfDeblur | SelfDeblur-master/models/unet.py | import torch.nn as nn
import torch
import torch.nn as nn
import torch.nn.functional as F
from .common import *
class ListModule(nn.Module):
def __init__(self, *args):
super(ListModule, self).__init__()
idx = 0
for module in args:
self.add_module(str(idx), module)
idx += 1
def __getitem__(self, idx):
if idx >= len(self._modules):
raise IndexError('index {} is out of range'.format(idx))
if idx < 0:
idx = len(self) + idx
it = iter(self._modules.values())
for i in range(idx):
next(it)
return next(it)
def __iter__(self):
return iter(self._modules.values())
def __len__(self):
return len(self._modules)
class UNet(nn.Module):
'''
upsample_mode in ['deconv', 'nearest', 'bilinear']
pad in ['zero', 'replication', 'none']
'''
def __init__(self, num_input_channels=3, num_output_channels=3,
feature_scale=4, more_layers=0, concat_x=False,
upsample_mode='deconv', pad='zero', norm_layer=nn.InstanceNorm2d, need_sigmoid=True, need_bias=True):
super(UNet, self).__init__()
self.feature_scale = feature_scale
self.more_layers = more_layers
self.concat_x = concat_x
filters = [64, 128, 256, 512, 1024]
filters = [x // self.feature_scale for x in filters]
self.start = unetConv2(num_input_channels, filters[0] if not concat_x else filters[0] - num_input_channels, norm_layer, need_bias, pad)
self.down1 = unetDown(filters[0], filters[1] if not concat_x else filters[1] - num_input_channels, norm_layer, need_bias, pad)
self.down2 = unetDown(filters[1], filters[2] if not concat_x else filters[2] - num_input_channels, norm_layer, need_bias, pad)
self.down3 = unetDown(filters[2], filters[3] if not concat_x else filters[3] - num_input_channels, norm_layer, need_bias, pad)
self.down4 = unetDown(filters[3], filters[4] if not concat_x else filters[4] - num_input_channels, norm_layer, need_bias, pad)
# more downsampling layers
if self.more_layers > 0:
self.more_downs = [
unetDown(filters[4], filters[4] if not concat_x else filters[4] - num_input_channels , norm_layer, need_bias, pad) for i in range(self.more_layers)]
self.more_ups = [unetUp(filters[4], upsample_mode, need_bias, pad, same_num_filt =True) for i in range(self.more_layers)]
self.more_downs = ListModule(*self.more_downs)
self.more_ups = ListModule(*self.more_ups)
self.up4 = unetUp(filters[3], upsample_mode, need_bias, pad)
self.up3 = unetUp(filters[2], upsample_mode, need_bias, pad)
self.up2 = unetUp(filters[1], upsample_mode, need_bias, pad)
self.up1 = unetUp(filters[0], upsample_mode, need_bias, pad)
self.final = conv(filters[0], num_output_channels, 1, bias=need_bias, pad=pad)
if need_sigmoid:
self.final = nn.Sequential(self.final, nn.Sigmoid())
def forward(self, inputs):
# Downsample
downs = [inputs]
down = nn.AvgPool2d(2, 2)
for i in range(4 + self.more_layers):
downs.append(down(downs[-1]))
in64 = self.start(inputs)
if self.concat_x:
in64 = torch.cat([in64, downs[0]], 1)
down1 = self.down1(in64)
if self.concat_x:
down1 = torch.cat([down1, downs[1]], 1)
down2 = self.down2(down1)
if self.concat_x:
down2 = torch.cat([down2, downs[2]], 1)
down3 = self.down3(down2)
if self.concat_x:
down3 = torch.cat([down3, downs[3]], 1)
down4 = self.down4(down3)
if self.concat_x:
down4 = torch.cat([down4, downs[4]], 1)
if self.more_layers > 0:
prevs = [down4]
for kk, d in enumerate(self.more_downs):
# print(prevs[-1].size())
out = d(prevs[-1])
if self.concat_x:
out = torch.cat([out, downs[kk + 5]], 1)
prevs.append(out)
up_ = self.more_ups[-1](prevs[-1], prevs[-2])
for idx in range(self.more_layers - 1):
l = self.more_ups[self.more - idx - 2]
up_= l(up_, prevs[self.more - idx - 2])
else:
up_= down4
up4= self.up4(up_, down3)
up3= self.up3(up4, down2)
up2= self.up2(up3, down1)
up1= self.up1(up2, in64)
return self.final(up1)
class unetConv2(nn.Module):
def __init__(self, in_size, out_size, norm_layer, need_bias, pad):
super(unetConv2, self).__init__()
print(pad)
if norm_layer is not None:
self.conv1= nn.Sequential(conv(in_size, out_size, 3, bias=need_bias, pad=pad),
norm_layer(out_size),
nn.ReLU(),)
self.conv2= nn.Sequential(conv(out_size, out_size, 3, bias=need_bias, pad=pad),
norm_layer(out_size),
nn.ReLU(),)
else:
self.conv1= nn.Sequential(conv(in_size, out_size, 3, bias=need_bias, pad=pad),
nn.ReLU(),)
self.conv2= nn.Sequential(conv(out_size, out_size, 3, bias=need_bias, pad=pad),
nn.ReLU(),)
def forward(self, inputs):
outputs= self.conv1(inputs)
outputs= self.conv2(outputs)
return outputs
class unetDown(nn.Module):
def __init__(self, in_size, out_size, norm_layer, need_bias, pad):
super(unetDown, self).__init__()
self.conv= unetConv2(in_size, out_size, norm_layer, need_bias, pad)
self.down= nn.MaxPool2d(2, 2)
def forward(self, inputs):
outputs= self.down(inputs)
outputs= self.conv(outputs)
return outputs
class unetUp(nn.Module):
def __init__(self, out_size, upsample_mode, need_bias, pad, same_num_filt=False):
super(unetUp, self).__init__()
num_filt = out_size if same_num_filt else out_size * 2
if upsample_mode == 'deconv':
self.up= nn.ConvTranspose2d(num_filt, out_size, 4, stride=2, padding=1)
self.conv= unetConv2(out_size * 2, out_size, None, need_bias, pad)
elif upsample_mode=='bilinear' or upsample_mode=='nearest':
self.up = nn.Sequential(nn.Upsample(scale_factor=2, mode=upsample_mode),
conv(num_filt, out_size, 3, bias=need_bias, pad=pad))
self.conv= unetConv2(out_size * 2, out_size, None, need_bias, pad)
else:
assert False
def forward(self, inputs1, inputs2):
in1_up= self.up(inputs1)
if (inputs2.size(2) != in1_up.size(2)) or (inputs2.size(3) != in1_up.size(3)):
diff2 = (inputs2.size(2) - in1_up.size(2)) // 2
diff3 = (inputs2.size(3) - in1_up.size(3)) // 2
inputs2_ = inputs2[:, :, diff2 : diff2 + in1_up.size(2), diff3 : diff3 + in1_up.size(3)]
else:
inputs2_ = inputs2
output= self.conv(torch.cat([in1_up, inputs2_], 1))
return output
if __name__ =='__main__':
print(1)
# net = UNet()
# print(net.forward) | 7,408 | 36.045 | 164 | py |
SelfDeblur | SelfDeblur-master/models/__init__.py | from .skip import skip
from .texture_nets import get_texture_nets
from .resnet import ResNet
from .unet import UNet
import torch.nn as nn
def get_net(input_depth, NET_TYPE, pad, upsample_mode, n_channels=3, act_fun='LeakyReLU', skip_n33d=128, skip_n33u=128, skip_n11=4, num_scales=5, downsample_mode='stride'):
if NET_TYPE == 'ResNet':
# TODO
net = ResNet(input_depth, 3, 10, 16, 1, nn.BatchNorm2d, False)
elif NET_TYPE == 'skip':
net = skip(input_depth, n_channels, num_channels_down = [skip_n33d]*num_scales if isinstance(skip_n33d, int) else skip_n33d,
num_channels_up = [skip_n33u]*num_scales if isinstance(skip_n33u, int) else skip_n33u,
num_channels_skip = [skip_n11]*num_scales if isinstance(skip_n11, int) else skip_n11,
upsample_mode=upsample_mode, downsample_mode=downsample_mode,
need_sigmoid=True, need_bias=True, pad=pad, act_fun=act_fun)
elif NET_TYPE == 'texture_nets':
net = get_texture_nets(inp=input_depth, ratios = [32, 16, 8, 4, 2, 1], fill_noise=False,pad=pad)
elif NET_TYPE =='UNet':
net = UNet(num_input_channels=input_depth, num_output_channels=3,
feature_scale=4, more_layers=0, concat_x=False,
upsample_mode=upsample_mode, pad=pad, norm_layer=nn.BatchNorm2d, need_sigmoid=True, need_bias=True)
elif NET_TYPE == 'identity':
assert input_depth == 3
net = nn.Sequential()
else:
assert False
return net | 1,639 | 50.25 | 172 | py |
SelfDeblur | SelfDeblur-master/models/non_local_gaussian.py | import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
self.dimension = dimension
self.sub_sample = sub_sample
self.in_channels = in_channels
self.inter_channels = inter_channels
if self.inter_channels is None:
self.inter_channels = in_channels // 2
if self.inter_channels == 0:
self.inter_channels = 1
if dimension == 3:
conv_nd = nn.Conv3d
max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))
bn = nn.BatchNorm3d
elif dimension == 2:
conv_nd = nn.Conv2d
max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))
bn = nn.BatchNorm2d
else:
conv_nd = nn.Conv1d
max_pool_layer = nn.MaxPool1d(kernel_size=(2))
bn = nn.BatchNorm1d
self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,
kernel_size=1, stride=1, padding=0)
if bn_layer:
self.W = nn.Sequential(
conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0),
bn(self.in_channels)
)
nn.init.constant_(self.W[1].weight, 0)
nn.init.constant_(self.W[1].bias, 0)
else:
self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,
kernel_size=1, stride=1, padding=0)
nn.init.constant_(self.W.weight, 0)
nn.init.constant_(self.W.bias, 0)
if sub_sample:
self.g = nn.Sequential(self.g, max_pool_layer)
self.phi = max_pool_layer
def forward(self, x):
'''
:param x: (b, c, t, h, w)
:return:
'''
batch_size = x.size(0)
g_x = self.g(x).view(batch_size, self.inter_channels, -1)
g_x = g_x.permute(0, 2, 1)
theta_x = x.view(batch_size, self.in_channels, -1)
theta_x = theta_x.permute(0, 2, 1)
if self.sub_sample:
phi_x = self.phi(x).view(batch_size, self.in_channels, -1)
else:
phi_x = x.view(batch_size, self.in_channels, -1)
f = torch.matmul(theta_x, phi_x)
f_div_C = F.softmax(f, dim=-1)
y = torch.matmul(f_div_C, g_x)
y = y.permute(0, 2, 1).contiguous()
y = y.view(batch_size, self.inter_channels, *x.size()[2:])
W_y = self.W(y)
z = W_y + x
return z
class NONLocalBlock1D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock1D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=1, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=2, sub_sample=sub_sample,
bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock3D, self).__init__(in_channels,
inter_channels=inter_channels,
dimension=3, sub_sample=sub_sample,
bn_layer=bn_layer)
if __name__ == '__main__':
import torch
for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]:
img = torch.zeros(2, 3, 20)
net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.zeros(2, 3, 20, 20)
net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
img = torch.randn(2, 3, 8, 20, 20)
net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer)
out = net(img)
print(out.size())
| 4,674 | 33.124088 | 102 | py |
SelfDeblur | SelfDeblur-master/utils/common_utils.py | import torch
import torch.nn as nn
import torchvision
import sys
import cv2
import numpy as np
from PIL import Image
import PIL
import numpy as np
import matplotlib.pyplot as plt
import random
def crop_image(img, d=32):
'''Make dimensions divisible by `d`'''
imgsize = img.shape
new_size = (imgsize[0] - imgsize[0] % d,
imgsize[1] - imgsize[1] % d)
bbox = [
int((imgsize[0] - new_size[0])/2),
int((imgsize[1] - new_size[1])/2),
int((imgsize[0] + new_size[0])/2),
int((imgsize[1] + new_size[1])/2),
]
img_cropped = img[0:new_size[0],0:new_size[1],:]
return img_cropped
def get_params(opt_over, net, net_input, downsampler=None):
'''Returns parameters that we want to optimize over.
Args:
opt_over: comma separated list, e.g. "net,input" or "net"
net: network
net_input: torch.Tensor that stores input `z`
'''
opt_over_list = opt_over.split(',')
params = []
for opt in opt_over_list:
if opt == 'net':
params += [x for x in net.parameters()]
elif opt=='down':
assert downsampler is not None
params += [x for x in downsampler.parameters()]
elif opt == 'input':
net_input.requires_grad = True
params += [net_input]
else:
assert False, 'what is it?'
return params
def get_image_grid(images_np, nrow=8):
'''Creates a grid from a list of images by concatenating them.'''
images_torch = [torch.from_numpy(x) for x in images_np]
torch_grid = torchvision.utils.make_grid(images_torch, nrow)
return torch_grid.numpy()
def plot_image_grid(images_np, nrow =8, factor=1, interpolation='lanczos'):
"""Draws images in a grid
Args:
images_np: list of images, each image is np.array of size 3xHxW of 1xHxW
nrow: how many images will be in one row
factor: size if the plt.figure
interpolation: interpolation used in plt.imshow
"""
n_channels = max(x.shape[0] for x in images_np)
assert (n_channels == 3) or (n_channels == 1), "images should have 1 or 3 channels"
images_np = [x if (x.shape[0] == n_channels) else np.concatenate([x, x, x], axis=0) for x in images_np]
grid = get_image_grid(images_np, nrow)
plt.figure(figsize=(len(images_np) + factor, 12 + factor))
if images_np[0].shape[0] == 1:
plt.imshow(grid[0], cmap='gray', interpolation=interpolation)
else:
plt.imshow(grid.transpose(1, 2, 0), interpolation=interpolation)
plt.show()
return grid
def load(path):
"""Load PIL image."""
img = Image.open(path)
return img
def get_image(path, imsize=-1):
"""Load an image and resize to a cpecific size.
Args:
path: path to image
imsize: tuple or scalar with dimensions; -1 for `no resize`
"""
img = load(path)
if isinstance(imsize, int):
imsize = (imsize, imsize)
if imsize[0]!= -1 and img.size != imsize:
if imsize[0] > img.size[0]:
img = img.resize(imsize, Image.BICUBIC)
else:
img = img.resize(imsize, Image.ANTIALIAS)
img_np = pil_to_np(img)
return img, img_np
def fill_noise(x, noise_type):
"""Fills tensor `x` with noise of type `noise_type`."""
torch.manual_seed(0)
if noise_type == 'u':
x.uniform_()
elif noise_type == 'n':
x.normal_()
else:
assert False
def get_noise(input_depth, method, spatial_size, noise_type='u', var=1./10):
"""Returns a pytorch.Tensor of size (1 x `input_depth` x `spatial_size[0]` x `spatial_size[1]`)
initialized in a specific way.
Args:
input_depth: number of channels in the tensor
method: `noise` for fillting tensor with noise; `meshgrid` for np.meshgrid
spatial_size: spatial size of the tensor to initialize
noise_type: 'u' for uniform; 'n' for normal
var: a factor, a noise will be multiplicated by. Basically it is standard deviation scaler.
"""
if isinstance(spatial_size, int):
spatial_size = (spatial_size, spatial_size)
if method == 'noise':
shape = [1, input_depth, spatial_size[0], spatial_size[1]]
net_input = torch.zeros(shape)
fill_noise(net_input, noise_type)
net_input *= var
elif method == 'meshgrid':
assert input_depth == 2
X, Y = np.meshgrid(np.arange(0, spatial_size[1])/float(spatial_size[1]-1), np.arange(0, spatial_size[0])/float(spatial_size[0]-1))
meshgrid = np.concatenate([X[None, :], Y[None, :]])
net_input = np_to_torch(meshgrid)
else:
assert False
return net_input
def pil_to_np(img_PIL):
'''Converts image in PIL format to np.array.
From W x H x C [0...255] to C x W x H [0..1]
'''
ar = np.array(img_PIL)
if len(ar.shape) == 3:
ar = ar.transpose(2,0,1)
else:
ar = ar[None, ...]
return ar.astype(np.float32) / 255.
def np_to_pil(img_np):
'''Converts image in np.array format to PIL image.
From C x W x H [0..1] to W x H x C [0...255]
'''
ar = np.clip(img_np*255,0,255).astype(np.uint8)
if img_np.shape[0] == 1:
ar = ar[0]
else:
ar = ar.transpose(1, 2, 0)
return Image.fromarray(ar)
def np_to_torch(img_np):
'''Converts image in numpy.array to torch.Tensor.
From C x W x H [0..1] to C x W x H [0..1]
'''
return torch.from_numpy(img_np)[None, :]
def torch_to_np(img_var):
'''Converts an image in torch.Tensor format to np.array.
From 1 x C x W x H [0..1] to C x W x H [0..1]
'''
return img_var.detach().cpu().numpy()[0]
def optimize(optimizer_type, parameters, closure, LR, num_iter):
"""Runs optimization loop.
Args:
optimizer_type: 'LBFGS' of 'adam'
parameters: list of Tensors to optimize over
closure: function, that returns loss variable
LR: learning rate
num_iter: number of iterations
"""
if optimizer_type == 'LBFGS':
# Do several steps with adam first
optimizer = torch.optim.Adam(parameters, lr=0.001)
for j in range(100):
optimizer.zero_grad()
closure()
optimizer.step()
print('Starting optimization with LBFGS')
def closure2():
optimizer.zero_grad()
return closure()
optimizer = torch.optim.LBFGS(parameters, max_iter=num_iter, lr=LR, tolerance_grad=-1, tolerance_change=-1)
optimizer.step(closure2)
elif optimizer_type == 'adam':
print('Starting optimization with ADAM')
optimizer = torch.optim.Adam(parameters, lr=LR)
from torch.optim.lr_scheduler import MultiStepLR
scheduler = MultiStepLR(optimizer, milestones=[5000, 10000, 15000], gamma=0.1) # learning rates
for j in range(num_iter):
scheduler.step(j)
optimizer.zero_grad()
closure()
optimizer.step()
else:
assert False
def pixelshuffle(image, scale):
'''
Discription: Given an image, return a reversible sub-sampling
[Input]: Image ndarray float
[Return]: A mosic image of shuffled pixels
'''
if scale == 1:
return image
w, h, c = image.shape
mosaic = np.array([])
for ws in range(scale):
band = np.array([])
for hs in range(scale):
temp = image[ws::scale, hs::scale, :] # get the sub-sampled image
band = np.concatenate((band, temp), axis=1) if band.size else temp
mosaic = np.concatenate((mosaic, band), axis=0) if mosaic.size else band
return mosaic
def reverse_pixelshuffle(image, scale, fill=0, fill_image=0, ind=[0, 0]):
'''
Discription: Given a mosaic image of subsampling, recombine it to a full image
[Input]: Image
[Return]: Recombine it using different portions of pixels
'''
w, h, c = image.shape
real = np.zeros((w, h, c)) # real image
wf = 0
hf = 0
for ws in range(scale):
hf = 0
for hs in range(scale):
temp = real[ws::scale, hs::scale, :]
wc, hc, cc = temp.shape # get the shpae of the current images
if fill == 1 and ws == ind[0] and hs == ind[1]:
real[ws::scale, hs::scale, :] = fill_image[wf:wf + wc, hf:hf + hc, :]
else:
real[ws::scale, hs::scale, :] = image[wf:wf + wc, hf:hf + hc, :]
hf = hf + hc
wf = wf + wc
return real
def readimg(path_to_image):
img = cv2.imread(path_to_image)
x = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
y, cr, cb = cv2.split(x)
return img, y, cb, cr
| 8,824 | 28.915254 | 138 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/eval_analyze.py | # Rdkit import should be first, do not move it
try:
from rdkit import Chem
except ModuleNotFoundError:
pass
import utils
import argparse
from qm9 import dataset
from qm9.models import get_model
import os
from equivariant_diffusion.utils import assert_mean_zero_with_mask, remove_mean_with_mask,\
assert_correctly_masked
import torch
import time
import pickle
from configs.datasets_config import get_dataset_info
from os.path import join
from qm9.sampling import sample
from qm9.analyze import analyze_stability_for_molecules, analyze_node_distribution
from qm9.utils import prepare_context, compute_mean_mad
from qm9 import visualizer as qm9_visualizer
import qm9.losses as losses
try:
from qm9 import rdkit_functions
except ModuleNotFoundError:
print('Not importing rdkit functions.')
def check_mask_correct(variables, node_mask):
for variable in variables:
assert_correctly_masked(variable, node_mask)
def analyze_and_save(args, eval_args, device, generative_model,
nodes_dist, prop_dist, dataset_info, n_samples=10,
batch_size=10, save_to_xyz=False):
batch_size = min(batch_size, n_samples)
assert n_samples % batch_size == 0
molecules = {'one_hot': [], 'x': [], 'node_mask': []}
start_time = time.time()
for i in range(int(n_samples/batch_size)):
nodesxsample = nodes_dist.sample(batch_size)
one_hot, charges, x, node_mask = sample(
args, device, generative_model, dataset_info, prop_dist=prop_dist, nodesxsample=nodesxsample)
molecules['one_hot'].append(one_hot.detach().cpu())
molecules['x'].append(x.detach().cpu())
molecules['node_mask'].append(node_mask.detach().cpu())
current_num_samples = (i+1) * batch_size
secs_per_sample = (time.time() - start_time) / current_num_samples
print('\t %d/%d Molecules generated at %.2f secs/sample' % (
current_num_samples, n_samples, secs_per_sample))
if save_to_xyz:
id_from = i * batch_size
qm9_visualizer.save_xyz_file(
join(eval_args.model_path, 'eval/analyzed_molecules/'),
one_hot, charges, x, dataset_info, id_from, name='molecule',
node_mask=node_mask)
molecules = {key: torch.cat(molecules[key], dim=0) for key in molecules}
stability_dict, rdkit_metrics = analyze_stability_for_molecules(
molecules, dataset_info)
return stability_dict, rdkit_metrics
def test(args, flow_dp, nodes_dist, device, dtype, loader, partition='Test', num_passes=1):
flow_dp.eval()
nll_epoch = 0
n_samples = 0
for pass_number in range(num_passes):
with torch.no_grad():
for i, data in enumerate(loader):
# Get data
x = data['positions'].to(device, dtype)
node_mask = data['atom_mask'].to(device, dtype).unsqueeze(2)
edge_mask = data['edge_mask'].to(device, dtype)
one_hot = data['one_hot'].to(device, dtype)
charges = (data['charges'] if args.include_charges else torch.zeros(0)).to(device, dtype)
batch_size = x.size(0)
x = remove_mean_with_mask(x, node_mask)
check_mask_correct([x, one_hot], node_mask)
assert_mean_zero_with_mask(x, node_mask)
h = {'categorical': one_hot, 'integer': charges}
if len(args.conditioning) > 0:
context = prepare_context(args.conditioning, data).to(device, dtype)
assert_correctly_masked(context, node_mask)
else:
context = None
# transform batch through flow
nll, _, _ = losses.compute_loss_and_nll(args, flow_dp, nodes_dist, x, h, node_mask,
edge_mask, context)
# standard nll from forward KL
nll_epoch += nll.item() * batch_size
n_samples += batch_size
if i % args.n_report_steps == 0:
print(f"\r {partition} NLL \t, iter: {i}/{len(loader)}, "
f"NLL: {nll_epoch/n_samples:.2f}")
return nll_epoch/n_samples
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', type=str, default="outputs/edm_1",
help='Specify model path')
parser.add_argument('--n_samples', type=int, default=100,
help='Specify model path')
parser.add_argument('--batch_size_gen', type=int, default=100,
help='Specify model path')
parser.add_argument('--save_to_xyz', type=eval, default=False,
help='Should save samples to xyz files.')
eval_args, unparsed_args = parser.parse_known_args()
assert eval_args.model_path is not None
with open(join(eval_args.model_path, 'args.pickle'), 'rb') as f:
args = pickle.load(f)
# CAREFUL with this -->
if not hasattr(args, 'normalization_factor'):
args.normalization_factor = 1
if not hasattr(args, 'aggregation_method'):
args.aggregation_method = 'sum'
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if args.cuda else "cpu")
args.device = device
dtype = torch.float32
utils.create_folders(args)
print(args)
# Retrieve QM9 dataloaders
dataloaders, charge_scale = dataset.retrieve_dataloaders(args)
dataset_info = get_dataset_info(args.dataset, args.remove_h)
# Load model
generative_model, nodes_dist, prop_dist = get_model(args, device, dataset_info, dataloaders['train'])
if prop_dist is not None:
property_norms = compute_mean_mad(dataloaders, args.conditioning, args.dataset)
prop_dist.set_normalizer(property_norms)
generative_model.to(device)
fn = 'generative_model_ema.npy' if args.ema_decay > 0 else 'generative_model.npy'
flow_state_dict = torch.load(join(eval_args.model_path, fn), map_location=device)
generative_model.load_state_dict(flow_state_dict)
# Analyze stability, validity, uniqueness and novelty
stability_dict, rdkit_metrics = analyze_and_save(
args, eval_args, device, generative_model, nodes_dist,
prop_dist, dataset_info, n_samples=eval_args.n_samples,
batch_size=eval_args.batch_size_gen, save_to_xyz=eval_args.save_to_xyz)
print(stability_dict)
if rdkit_metrics is not None:
rdkit_metrics = rdkit_metrics[0]
print("Validity %.4f, Uniqueness: %.4f, Novelty: %.4f" % (rdkit_metrics[0], rdkit_metrics[1], rdkit_metrics[2]))
else:
print("Install rdkit roolkit to obtain Validity, Uniqueness, Novelty")
# In GEOM-Drugs the validation partition is named 'val', not 'valid'.
if args.dataset == 'geom':
val_name = 'val'
num_passes = 1
else:
val_name = 'valid'
num_passes = 5
# Evaluate negative log-likelihood for the validation and test partitions
val_nll = test(args, generative_model, nodes_dist, device, dtype,
dataloaders[val_name],
partition='Val')
print(f'Final val nll {val_nll}')
test_nll = test(args, generative_model, nodes_dist, device, dtype,
dataloaders['test'],
partition='Test', num_passes=num_passes)
print(f'Final test nll {test_nll}')
print(f'Overview: val nll {val_nll} test nll {test_nll}', stability_dict)
with open(join(eval_args.model_path, 'eval_log.txt'), 'w') as f:
print(f'Overview: val nll {val_nll} test nll {test_nll}',
stability_dict,
file=f)
if __name__ == "__main__":
main()
| 7,795 | 38.175879 | 120 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/analyse_geom.py | from rdkit import Chem
import os
import numpy as np
import torch
from torch.utils.data import BatchSampler, DataLoader, Dataset, SequentialSampler
import argparse
import collections
import pickle
import os
import json
from tqdm import tqdm
from IPython.display import display
from matplotlib import pyplot as plt
import numpy as np
from qm9.analyze import check_stability
from qm9.rdkit_functions import BasicMolecularMetrics
import configs.datasets_config
atomic_number_list = [1, 5, 6, 7, 8, 9, 13, 14, 15, 16, 17, 33, 35, 53, 80, 83]
inverse = {1: 0, 5: 1, 6: 2, 7: 3, 8: 4, 9: 5, 13: 6, 14: 7, 15: 8, 16: 9, 17: 10, 33: 11, 35: 12, 53: 13,
80: 14, 83: 15}
atom_name = ['H', 'B', 'C', 'N', 'O', 'F', 'Al', 'Si', 'P', 'S', 'Cl', 'As', 'Br', 'I', 'Hg', 'Bi']
n_atom_types = len(atomic_number_list)
n_bond_types = 4
def extract_conformers(args):
Counter = collections.Counter
bond_length_dict = {0: Counter(), 1: Counter(), 2: Counter(), 3: Counter()}
summary_file = os.path.join(args.data_dir, args.data_file)
with open(summary_file, "r") as f:
drugs_summ = json.load(f)
all_paths = []
for smiles, sub_dic in drugs_summ.items():
if 'pickle_path' in sub_dic:
pickle_path = os.path.join(args.data_dir, "rdkit_folder", sub_dic["pickle_path"])
all_paths.append(pickle_path)
for i, mol_path in tqdm(enumerate(all_paths)):
with open(mol_path, "rb") as f:
dic = pickle.load(f)
# Get the energy of each conformer. Keep only the lowest values
conformers = dic['conformers']
all_energies = []
for conformer in conformers:
all_energies.append(conformer['totalenergy'])
all_energies = np.array(all_energies)
argsort = np.argsort(all_energies)
lowest_energies = argsort[:args.conformations]
for id in lowest_energies:
conformer = conformers[id]
rd_mol = conformer["rd_mol"]
atoms = rd_mol.GetAtoms()
atom_nums = []
for atom in atoms:
atom_nums.append(atom.GetAtomicNum())
rd_conf = rd_mol.GetConformers()[0]
coords = rd_conf.GetPositions() # list of elts of size 3?
bonds = [bond for bond in rd_mol.GetBonds()]
for bond in bonds:
atom1, atom2 = [bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()]
# bond length
c1 = coords[atom1]
c2 = coords[atom2]
dist = np.linalg.norm(c1 - c2)
# Bin the distance
dist = int(dist * 100)
# atom types
at1_type = atom_nums[atom1]
at2_type = atom_nums[atom2]
if at1_type > at2_type: # Sort the pairs to avoid redundancy
temp = at2_type
at2_type = at1_type
at1_type = temp
bond_type = bond.GetBondType().name.lower()
if bond_type == 'single':
type = 0
elif bond_type == 'double':
type = 1
elif bond_type == 'triple':
type = 2
elif bond_type == 'aromatic':
type = 3
else:
raise ValueError("Unknown bond type", bond_type)
bond_length_dict[type][(at1_type, at2_type, dist)] += 1
if i % 5000 == 0:
print("Current state of the bond length dictionary", bond_length_dict)
if os.path.exists('bond_length_dict.pkl'):
os.remove('bond_length_dict.pkl')
with open('bond_length_dict', 'wb') as bond_dictionary_file:
pickle.dump(bond_length_dict, bond_dictionary_file)
def create_matrix(args):
with open('bond_length_dict', 'rb') as bond_dictionary_file:
all_bond_types = pickle.load(bond_dictionary_file)
x = np.zeros((n_atom_types, n_atom_types, n_bond_types, 350))
for bond_type, d in all_bond_types.items():
for key, count in d.items():
at1, at2, bond_len = key
x[inverse[at1], inverse[at2], bond_type, bond_len - 50] = count
np.save('bond_length_matrix', x)
def create_histograms(args):
x = np.load('./data/geom/bond_length_matrix.npy')
x = x[:, :, :, :307]
label_list = ['single', 'double', 'triple', 'aromatic']
for j in range(n_atom_types):
for i in range(j + 1):
if np.sum(x[i, j]) == 0: # Bond does not exist
continue
# Remove outliers
y = x[i, j]
y[y < 0.02 * np.sum(y, axis=0)] = 0
plt.figure()
existing_bond_lengths = np.array(np.nonzero(y))[1]
mini, maxi = existing_bond_lengths.min(), existing_bond_lengths.max()
y = y[:, mini: maxi + 1]
x_range = np.arange(mini, maxi + 1)
for k in range(n_bond_types):
if np.sum(y[k]) > 0:
plt.plot(x_range, y[k], label=label_list[k])
plt.xlabel("Bond length")
plt.ylabel("Count")
plt.title(f'{atom_name[i]} - {atom_name[j]} bonds')
plt.legend()
plt.savefig(f'./figures/{atom_name[i]}-{atom_name[j]}-hist.png')
plt.close()
def analyse_geom_stability():
data_file = './data/geom/geom_drugs_30.npy'
dataset_info = configs.datasets_config.get_dataset_info('geom', remove_h=False)
atom_dict = dataset_info['atom_decoder']
bond_dict = [None, Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE,
Chem.rdchem.BondType.AROMATIC]
x = np.load(data_file)
mol_id = x[:, 0].astype(int)
all_atom_types = x[:, 1].astype(int)
all_positions = x[:, 2:]
# Get ids corresponding to new molecules
split_indices = np.nonzero(mol_id[:-1] - mol_id[1:])[0] + 1
all_atom_types_split = np.split(all_atom_types, split_indices)
all_positions_split = np.split(all_positions, split_indices)
atomic_nb_list = torch.Tensor(dataset_info['atomic_nb'])[None, :].long()
num_stable_mols = 0
num_mols = 0
num_stable_atoms_total = 0
num_atoms_total = 0
formatted_data = []
for i, (p, at_types) in tqdm(enumerate(zip(all_positions_split, all_atom_types_split))):
p = torch.from_numpy(p)
at_types = torch.from_numpy(at_types)[:, None]
one_hot = torch.eq(at_types, atomic_nb_list).int()
at_types = torch.argmax(one_hot, dim=1) # Between 0 and 15
formatted_data.append([p, at_types])
mol_is_stable, num_stable_atoms, num_atoms = check_stability(p, at_types, dataset_info)
num_mols += 1
num_stable_mols += mol_is_stable
num_stable_atoms_total += num_stable_atoms
num_atoms_total += num_atoms
if i % 5000 == 0:
print(f"IN PROGRESS -- Stable molecules: {num_stable_mols} / {num_mols}"
f" = {num_stable_mols / num_mols * 100} %")
print(
f"IN PROGRESS -- Stable atoms: {num_stable_atoms_total} / {num_atoms_total}"
f" = {num_stable_atoms_total / num_atoms_total * 100} %")
print(f"Stable molecules: {num_stable_mols} / {num_mols} = {num_stable_mols / num_mols * 100} %")
print(f"Stable atoms: {num_stable_atoms_total} / {num_atoms_total} = {num_stable_atoms_total / num_atoms_total * 100} %")
metrics = BasicMolecularMetrics(dataset_info)
metrics.evaluate(formatted_data)
def debug_geom_stability(num_atoms=100000):
data_file = './data/geom/geom_drugs_30.npy'
dataset_info = configs.datasets_config.get_dataset_info('geom', remove_h=False)
atom_dict = dataset_info['atom_decoder']
bond_dict = [None, Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE,
Chem.rdchem.BondType.AROMATIC]
x = np.load(data_file)
x = x[:num_atoms]
# Print non hydrogen atoms
x = x[x[:, 1] != 1.0, :]
mol_id = x[:, 0].astype(int)
max_mol_id = mol_id.max()
may_be_incomplete = mol_id == max_mol_id
x = x[~may_be_incomplete]
mol_id = mol_id[~may_be_incomplete]
all_atom_types = x[:, 1].astype(int)
all_positions = x[:, 2:]
# Get ids corresponding to new molecules
split_indices = np.nonzero(mol_id[:-1] - mol_id[1:])[0] + 1
all_atom_types_split = np.split(all_atom_types, split_indices)
all_positions_split = np.split(all_positions, split_indices)
atomic_nb_list = torch.Tensor(dataset_info['atomic_nb'])[None, :].long()
formatted_data = []
for p, at_types in zip(all_positions_split, all_atom_types_split):
p = torch.from_numpy(p)
at_types = torch.from_numpy(at_types)[:, None]
one_hot = torch.eq(at_types, atomic_nb_list).int()
at_types = torch.argmax(one_hot, dim=1) # Between 0 and 15
formatted_data.append([p, at_types])
metrics = BasicMolecularMetrics(atom_dict, bond_dict, dataset_info)
m, smiles_list = metrics.evaluate(formatted_data)
print(smiles_list)
def compute_n_nodes_dict(file='./data/geom/geom_drugs_30.npy', remove_hydrogens=True):
all_data = np.load(file)
atom_types = all_data[:, 1]
if remove_hydrogens:
hydrogens = np.equal(atom_types, 1.0)
all_data = all_data[~hydrogens]
# Get the size of each molecule
mol_id = all_data[:, 0].astype(int)
max_id = mol_id.max()
mol_id_counter = np.zeros(max_id + 1, dtype=int)
for id in mol_id:
mol_id_counter[id] += 1
unique_sizes, size_count = np.unique(mol_id_counter, return_counts=True)
sizes_dict = {}
for size, count in zip(unique_sizes, size_count):
sizes_dict[size] = count
print(sizes_dict)
return sizes_dict
if __name__ == '__main__':
# parser = argparse.ArgumentParser()
# parser.add_argument("--conformations", type=int, default=30,
# help="Max number of conformations kept for each molecule.")
# parser.add_argument("--data_dir", type=str, default='/home/vignac/diffusion/data/geom/')
# parser.add_argument("--data_file", type=str, default="rdkit_folder/summary_drugs.json")
# args = parser.parse_args()
# # extract_conformers(args)
# # create_histograms(args)
#
analyse_geom_stability()
# compute_n_nodes_dict() | 10,412 | 37.283088 | 125 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/setup.py | from setuptools import setup, find_packages
setup(
name='EN_diffusion',
version='1.0.0',
url=None,
author='Author Name',
author_email='[email protected]',
description='Description of my package',
packages=find_packages(),
install_requires=['numpy >= 1.11.1', 'matplotlib >= 1.5.1']
) | 315 | 25.333333 | 63 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/utils.py | import numpy as np
import getpass
import os
import torch
# Folders
def create_folders(args):
try:
os.makedirs('outputs')
except OSError:
pass
try:
os.makedirs('outputs/' + args.exp_name)
except OSError:
pass
# Model checkpoints
def save_model(model, path):
torch.save(model.state_dict(), path)
def load_model(model, path):
model.load_state_dict(torch.load(path))
model.eval()
return model
#Gradient clipping
class Queue():
def __init__(self, max_len=50):
self.items = []
self.max_len = max_len
def __len__(self):
return len(self.items)
def add(self, item):
self.items.insert(0, item)
if len(self) > self.max_len:
self.items.pop()
def mean(self):
return np.mean(self.items)
def std(self):
return np.std(self.items)
def gradient_clipping(flow, gradnorm_queue):
# Allow gradient norm to be 150% + 2 * stdev of the recent history.
max_grad_norm = 1.5 * gradnorm_queue.mean() + 2 * gradnorm_queue.std()
# Clips gradient and returns the norm
grad_norm = torch.nn.utils.clip_grad_norm_(
flow.parameters(), max_norm=max_grad_norm, norm_type=2.0)
if float(grad_norm) > max_grad_norm:
gradnorm_queue.add(float(max_grad_norm))
else:
gradnorm_queue.add(float(grad_norm))
if float(grad_norm) > max_grad_norm:
print(f'Clipped gradient with value {grad_norm:.1f} '
f'while allowed {max_grad_norm:.1f}')
return grad_norm
# Rotation data augmntation
def random_rotation(x):
bs, n_nodes, n_dims = x.size()
device = x.device
angle_range = np.pi * 2
if n_dims == 2:
theta = torch.rand(bs, 1, 1).to(device) * angle_range - np.pi
cos_theta = torch.cos(theta)
sin_theta = torch.sin(theta)
R_row0 = torch.cat([cos_theta, -sin_theta], dim=2)
R_row1 = torch.cat([sin_theta, cos_theta], dim=2)
R = torch.cat([R_row0, R_row1], dim=1)
x = x.transpose(1, 2)
x = torch.matmul(R, x)
x = x.transpose(1, 2)
elif n_dims == 3:
# Build Rx
Rx = torch.eye(3).unsqueeze(0).repeat(bs, 1, 1).to(device)
theta = torch.rand(bs, 1, 1).to(device) * angle_range - np.pi
cos = torch.cos(theta)
sin = torch.sin(theta)
Rx[:, 1:2, 1:2] = cos
Rx[:, 1:2, 2:3] = sin
Rx[:, 2:3, 1:2] = - sin
Rx[:, 2:3, 2:3] = cos
# Build Ry
Ry = torch.eye(3).unsqueeze(0).repeat(bs, 1, 1).to(device)
theta = torch.rand(bs, 1, 1).to(device) * angle_range - np.pi
cos = torch.cos(theta)
sin = torch.sin(theta)
Ry[:, 0:1, 0:1] = cos
Ry[:, 0:1, 2:3] = -sin
Ry[:, 2:3, 0:1] = sin
Ry[:, 2:3, 2:3] = cos
# Build Rz
Rz = torch.eye(3).unsqueeze(0).repeat(bs, 1, 1).to(device)
theta = torch.rand(bs, 1, 1).to(device) * angle_range - np.pi
cos = torch.cos(theta)
sin = torch.sin(theta)
Rz[:, 0:1, 0:1] = cos
Rz[:, 0:1, 1:2] = sin
Rz[:, 1:2, 0:1] = -sin
Rz[:, 1:2, 1:2] = cos
x = x.transpose(1, 2)
x = torch.matmul(Rx, x)
#x = torch.matmul(Rx.transpose(1, 2), x)
x = torch.matmul(Ry, x)
#x = torch.matmul(Ry.transpose(1, 2), x)
x = torch.matmul(Rz, x)
#x = torch.matmul(Rz.transpose(1, 2), x)
x = x.transpose(1, 2)
else:
raise Exception("Not implemented Error")
return x.contiguous()
# Other utilities
def get_wandb_username(username):
if username == 'cvignac':
return 'cvignac'
current_user = getpass.getuser()
if current_user == 'victor' or current_user == 'garciasa':
return 'vgsatorras'
else:
return username
if __name__ == "__main__":
## Test random_rotation
bs = 2
n_nodes = 16
n_dims = 3
x = torch.randn(bs, n_nodes, n_dims)
print(x)
x = random_rotation(x)
#print(x)
| 4,012 | 25.058442 | 74 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/build_geom_dataset.py | import msgpack
import os
import numpy as np
import torch
from torch.utils.data import BatchSampler, DataLoader, Dataset, SequentialSampler
import argparse
from qm9.data import collate as qm9_collate
def extract_conformers(args):
drugs_file = os.path.join(args.data_dir, args.data_file)
save_file = f"geom_drugs_{'no_h_' if args.remove_h else ''}{args.conformations}"
smiles_list_file = 'geom_drugs_smiles.txt'
number_atoms_file = f"geom_drugs_n_{'no_h_' if args.remove_h else ''}{args.conformations}"
unpacker = msgpack.Unpacker(open(drugs_file, "rb"))
all_smiles = []
all_number_atoms = []
dataset_conformers = []
mol_id = 0
for i, drugs_1k in enumerate(unpacker):
print(f"Unpacking file {i}...")
for smiles, all_info in drugs_1k.items():
all_smiles.append(smiles)
conformers = all_info['conformers']
# Get the energy of each conformer. Keep only the lowest values
all_energies = []
for conformer in conformers:
all_energies.append(conformer['totalenergy'])
all_energies = np.array(all_energies)
argsort = np.argsort(all_energies)
lowest_energies = argsort[:args.conformations]
for id in lowest_energies:
conformer = conformers[id]
coords = np.array(conformer['xyz']).astype(float) # n x 4
if args.remove_h:
mask = coords[:, 0] != 1.0
coords = coords[mask]
n = coords.shape[0]
all_number_atoms.append(n)
mol_id_arr = mol_id * np.ones((n, 1), dtype=float)
id_coords = np.hstack((mol_id_arr, coords))
dataset_conformers.append(id_coords)
mol_id += 1
print("Total number of conformers saved", mol_id)
all_number_atoms = np.array(all_number_atoms)
dataset = np.vstack(dataset_conformers)
print("Total number of atoms in the dataset", dataset.shape[0])
print("Average number of atoms per molecule", dataset.shape[0] / mol_id)
# Save conformations
np.save(os.path.join(args.data_dir, save_file), dataset)
# Save SMILES
with open(os.path.join(args.data_dir, smiles_list_file), 'w') as f:
for s in all_smiles:
f.write(s)
f.write('\n')
# Save number of atoms per conformation
np.save(os.path.join(args.data_dir, number_atoms_file), all_number_atoms)
print("Dataset processed.")
def load_split_data(conformation_file, val_proportion=0.1, test_proportion=0.1,
filter_size=None):
from pathlib import Path
path = Path(conformation_file)
base_path = path.parent.absolute()
# base_path = os.path.dirname(conformation_file)
all_data = np.load(conformation_file) # 2d array: num_atoms x 5
mol_id = all_data[:, 0].astype(int)
conformers = all_data[:, 1:]
# Get ids corresponding to new molecules
split_indices = np.nonzero(mol_id[:-1] - mol_id[1:])[0] + 1
data_list = np.split(conformers, split_indices)
# Filter based on molecule size.
if filter_size is not None:
# Keep only molecules <= filter_size
data_list = [molecule for molecule in data_list
if molecule.shape[0] <= filter_size]
assert len(data_list) > 0, 'No molecules left after filter.'
# CAREFUL! Only for first time run:
# perm = np.random.permutation(len(data_list)).astype('int32')
# print('Warning, currently taking a random permutation for '
# 'train/val/test partitions, this needs to be fixed for'
# 'reproducibility.')
# assert not os.path.exists(os.path.join(base_path, 'geom_permutation.npy'))
# np.save(os.path.join(base_path, 'geom_permutation.npy'), perm)
# del perm
perm = np.load(os.path.join(base_path, 'geom_permutation.npy'))
data_list = [data_list[i] for i in perm]
num_mol = len(data_list)
val_index = int(num_mol * val_proportion)
test_index = val_index + int(num_mol * test_proportion)
val_data, test_data, train_data = np.split(data_list, [val_index, test_index])
return train_data, val_data, test_data
class GeomDrugsDataset(Dataset):
def __init__(self, data_list, transform=None):
"""
Args:
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.transform = transform
# Sort the data list by size
lengths = [s.shape[0] for s in data_list]
argsort = np.argsort(lengths) # Sort by decreasing size
self.data_list = [data_list[i] for i in argsort]
# Store indices where the size changes
self.split_indices = np.unique(np.sort(lengths), return_index=True)[1][1:]
def __len__(self):
return len(self.data_list)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
sample = self.data_list[idx]
if self.transform:
sample = self.transform(sample)
return sample
class CustomBatchSampler(BatchSampler):
""" Creates batches where all sets have the same size. """
def __init__(self, sampler, batch_size, drop_last, split_indices):
super().__init__(sampler, batch_size, drop_last)
self.split_indices = split_indices
def __iter__(self):
batch = []
for idx in self.sampler:
batch.append(idx)
if len(batch) == self.batch_size or idx + 1 in self.split_indices:
yield batch
batch = []
if len(batch) > 0 and not self.drop_last:
yield batch
def __len__(self):
count = 0
batch = 0
for idx in self.sampler:
batch += 1
if batch == self.batch_size or idx + 1 in self.split_indices:
count += 1
batch = 0
if batch > 0 and not self.drop_last:
count += 1
return count
def collate_fn(batch):
batch = {prop: qm9_collate.batch_stack([mol[prop] for mol in batch])
for prop in batch[0].keys()}
atom_mask = batch['atom_mask']
# Obtain edges
batch_size, n_nodes = atom_mask.size()
edge_mask = atom_mask.unsqueeze(1) * atom_mask.unsqueeze(2)
# mask diagonal
diag_mask = ~torch.eye(edge_mask.size(1), dtype=torch.bool,
device=edge_mask.device).unsqueeze(0)
edge_mask *= diag_mask
# edge_mask = atom_mask.unsqueeze(1) * atom_mask.unsqueeze(2)
batch['edge_mask'] = edge_mask.view(batch_size * n_nodes * n_nodes, 1)
return batch
class GeomDrugsDataLoader(DataLoader):
def __init__(self, sequential, dataset, batch_size, shuffle, drop_last=False):
if sequential:
# This goes over the data sequentially, advantage is that it takes
# less memory for smaller molecules, but disadvantage is that the
# model sees very specific orders of data.
assert not shuffle
sampler = SequentialSampler(dataset)
batch_sampler = CustomBatchSampler(sampler, batch_size, drop_last,
dataset.split_indices)
super().__init__(dataset, batch_sampler=batch_sampler)
else:
# Dataloader goes through data randomly and pads the molecules to
# the largest molecule size.
super().__init__(dataset, batch_size, shuffle=shuffle,
collate_fn=collate_fn, drop_last=drop_last)
class GeomDrugsTransform(object):
def __init__(self, dataset_info, include_charges, device, sequential):
self.atomic_number_list = torch.Tensor(dataset_info['atomic_nb'])[None, :]
self.device = device
self.include_charges = include_charges
self.sequential = sequential
def __call__(self, data):
n = data.shape[0]
new_data = {}
new_data['positions'] = torch.from_numpy(data[:, -3:])
atom_types = torch.from_numpy(data[:, 0].astype(int)[:, None])
one_hot = atom_types == self.atomic_number_list
new_data['one_hot'] = one_hot
if self.include_charges:
new_data['charges'] = torch.zeros(n, 1, device=self.device)
else:
new_data['charges'] = torch.zeros(0, device=self.device)
new_data['atom_mask'] = torch.ones(n, device=self.device)
if self.sequential:
edge_mask = torch.ones((n, n), device=self.device)
edge_mask[~torch.eye(edge_mask.shape[0], dtype=torch.bool)] = 0
new_data['edge_mask'] = edge_mask.flatten()
return new_data
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--conformations", type=int, default=30,
help="Max number of conformations kept for each molecule.")
parser.add_argument("--remove_h", action='store_true', help="Remove hydrogens from the dataset.")
parser.add_argument("--data_dir", type=str, default='~/diffusion/data/geom/')
parser.add_argument("--data_file", type=str, default="drugs_crude.msgpack")
args = parser.parse_args()
extract_conformers(args)
| 9,281 | 36.885714 | 101 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/main_geom_drugs.py | # Rdkit import should be first, do not move it
try:
from rdkit import Chem
except ModuleNotFoundError:
pass
import build_geom_dataset
from configs.datasets_config import geom_with_h
import copy
import utils
import argparse
import wandb
from os.path import join
from qm9.models import get_optim, get_model
from equivariant_diffusion import en_diffusion
from equivariant_diffusion import utils as diffusion_utils
import torch
import time
import pickle
from qm9.utils import prepare_context, compute_mean_mad
import train_test
parser = argparse.ArgumentParser(description='e3_diffusion')
parser.add_argument('--exp_name', type=str, default='debug_10')
parser.add_argument('--model', type=str, default='egnn_dynamics',
help='our_dynamics | schnet | simple_dynamics | '
'kernel_dynamics | egnn_dynamics |gnn_dynamics')
parser.add_argument('--probabilistic_model', type=str, default='diffusion',
help='diffusion')
# Training complexity is O(1) (unaffected), but sampling complexity O(steps).
parser.add_argument('--diffusion_steps', type=int, default=500)
parser.add_argument('--diffusion_noise_schedule', type=str, default='polynomial_2',
help='learned, cosine')
parser.add_argument('--diffusion_loss_type', type=str, default='l2',
help='vlb, l2')
parser.add_argument('--diffusion_noise_precision', type=float, default=1e-5)
parser.add_argument('--n_epochs', type=int, default=10000)
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--lr', type=float, default=5e-5)
parser.add_argument('--break_train_epoch', type=eval, default=False,
help='True | False')
parser.add_argument('--dp', type=eval, default=True,
help='True | False')
parser.add_argument('--condition_time', type=eval, default=True,
help='True | False')
parser.add_argument('--clip_grad', type=eval, default=True,
help='True | False')
parser.add_argument('--trace', type=str, default='hutch',
help='hutch | exact')
# EGNN args -->
parser.add_argument('--n_layers', type=int, default=6,
help='number of layers')
parser.add_argument('--inv_sublayers', type=int, default=1,
help='number of layers')
parser.add_argument('--nf', type=int, default=192,
help='number of layers')
parser.add_argument('--tanh', type=eval, default=True,
help='use tanh in the coord_mlp')
parser.add_argument('--attention', type=eval, default=True,
help='use attention in the EGNN')
parser.add_argument('--norm_constant', type=float, default=1,
help='diff/(|diff| + norm_constant)')
parser.add_argument('--sin_embedding', type=eval, default=False,
help='whether using or not the sin embedding')
# <-- EGNN args
parser.add_argument('--ode_regularization', type=float, default=1e-3)
parser.add_argument('--dataset', type=str, default='geom',
help='dataset name')
parser.add_argument('--filter_n_atoms', type=int, default=None,
help='When set to an integer value, QM9 will only contain molecules of that amount of atoms')
parser.add_argument('--dequantization', type=str, default='argmax_variational',
help='uniform | variational | argmax_variational | deterministic')
parser.add_argument('--n_report_steps', type=int, default=50)
parser.add_argument('--wandb_usr', type=str)
parser.add_argument('--no_wandb', action='store_true', help='Disable wandb')
parser.add_argument('--online', type=bool, default=True, help='True = wandb online -- False = wandb offline')
parser.add_argument('--no-cuda', action='store_true', default=False, help='disable CUDA training')
parser.add_argument('--save_model', type=eval, default=True, help='save model')
parser.add_argument('--generate_epochs', type=int, default=1)
parser.add_argument('--num_workers', type=int, default=0,
help='Number of worker for the dataloader')
parser.add_argument('--test_epochs', type=int, default=1)
parser.add_argument('--data_augmentation', type=eval, default=False,
help='use attention in the EGNN')
parser.add_argument("--conditioning", nargs='+', default=[],
help='multiple arguments can be passed, '
'including: homo | onehot | lumo | num_atoms | etc. '
'usage: "--conditioning H_thermo homo onehot H_thermo"')
parser.add_argument('--resume', type=str, default=None,
help='')
parser.add_argument('--start_epoch', type=int, default=0,
help='')
parser.add_argument('--ema_decay', type=float, default=0, # TODO
help='Amount of EMA decay, 0 means off. A reasonable value'
' is 0.999.')
parser.add_argument('--augment_noise', type=float, default=0)
parser.add_argument('--n_stability_samples', type=int, default=20,
help='Number of samples to compute the stability')
parser.add_argument('--normalize_factors', type=eval, default=[1, 4, 10],
help='normalize factors for [x, categorical, integer]')
parser.add_argument('--remove_h', action='store_true')
parser.add_argument('--include_charges', type=eval, default=False, help='include atom charge or not')
parser.add_argument('--visualize_every_batch', type=int, default=5000)
parser.add_argument('--normalization_factor', type=float,
default=100, help="Normalize the sum aggregation of EGNN")
parser.add_argument('--aggregation_method', type=str, default='sum',
help='"sum" or "mean" aggregation for the graph network')
parser.add_argument('--filter_molecule_size', type=int, default=None,
help="Only use molecules below this size.")
parser.add_argument('--sequential', action='store_true',
help='Organize data by size to reduce average memory usage.')
args = parser.parse_args()
data_file = './data/geom/geom_drugs_30.npy'
if args.remove_h:
raise NotImplementedError()
else:
dataset_info = geom_with_h
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if args.cuda else "cpu")
dtype = torch.float32
split_data = build_geom_dataset.load_split_data(data_file, val_proportion=0.1, test_proportion=0.1, filter_size=args.filter_molecule_size)
transform = build_geom_dataset.GeomDrugsTransform(dataset_info, args.include_charges, device, args.sequential)
dataloaders = {}
for key, data_list in zip(['train', 'val', 'test'], split_data):
dataset = build_geom_dataset.GeomDrugsDataset(data_list, transform=transform)
shuffle = (key == 'train') and not args.sequential
# Sequential dataloading disabled for now.
dataloaders[key] = build_geom_dataset.GeomDrugsDataLoader(
sequential=args.sequential, dataset=dataset, batch_size=args.batch_size,
shuffle=shuffle)
del split_data
atom_encoder = dataset_info['atom_encoder']
atom_decoder = dataset_info['atom_decoder']
# args, unparsed_args = parser.parse_known_args()
args.wandb_usr = utils.get_wandb_username(args.wandb_usr)
if args.resume is not None:
exp_name = args.exp_name + '_resume'
start_epoch = args.start_epoch
resume = args.resume
wandb_usr = args.wandb_usr
with open(join(args.resume, 'args.pickle'), 'rb') as f:
args = pickle.load(f)
args.resume = resume
args.break_train_epoch = False
args.exp_name = exp_name
args.start_epoch = start_epoch
args.wandb_usr = wandb_usr
print(args)
utils.create_folders(args)
print(args)
# Wandb config
if args.no_wandb:
mode = 'disabled'
else:
mode = 'online' if args.online else 'offline'
kwargs = {'entity': args.wandb_usr, 'name': args.exp_name, 'project': 'e3_diffusion_geom', 'config': args,
'settings': wandb.Settings(_disable_stats=True), 'reinit': True, 'mode': mode}
wandb.init(**kwargs)
wandb.save('*.txt')
data_dummy = next(iter(dataloaders['train']))
if len(args.conditioning) > 0:
print(f'Conditioning on {args.conditioning}')
property_norms = compute_mean_mad(dataloaders, args.conditioning)
context_dummy = prepare_context(args.conditioning, data_dummy, property_norms)
context_node_nf = context_dummy.size(2)
else:
context_node_nf = 0
property_norms = None
args.context_node_nf = context_node_nf
# Create EGNN flow
model, nodes_dist, prop_dist = get_model(args, device, dataset_info, dataloader_train=dataloaders['train'])
model = model.to(device)
optim = get_optim(args, model)
# print(model)
gradnorm_queue = utils.Queue()
gradnorm_queue.add(3000) # Add large value that will be flushed.
def main():
if args.resume is not None:
flow_state_dict = torch.load(join(args.resume, 'flow.npy'))
dequantizer_state_dict = torch.load(join(args.resume, 'dequantizer.npy'))
optim_state_dict = torch.load(join(args.resume, 'optim.npy'))
model.load_state_dict(flow_state_dict)
optim.load_state_dict(optim_state_dict)
# Initialize dataparallel if enabled and possible.
if args.dp and torch.cuda.device_count() > 1 and args.cuda:
print(f'Training using {torch.cuda.device_count()} GPUs')
model_dp = torch.nn.DataParallel(model.cpu())
model_dp = model_dp.cuda()
else:
model_dp = model
# Initialize model copy for exponential moving average of params.
if args.ema_decay > 0:
model_ema = copy.deepcopy(model)
ema = diffusion_utils.EMA(args.ema_decay)
if args.dp and torch.cuda.device_count() > 1:
model_ema_dp = torch.nn.DataParallel(model_ema)
else:
model_ema_dp = model_ema
else:
ema = None
model_ema = model
model_ema_dp = model_dp
best_nll_val = 1e8
best_nll_test = 1e8
for epoch in range(args.start_epoch, args.n_epochs):
start_epoch = time.time()
train_test.train_epoch(args, dataloaders['train'], epoch, model, model_dp, model_ema, ema, device, dtype,
property_norms, optim, nodes_dist, gradnorm_queue, dataset_info,
prop_dist)
print(f"Epoch took {time.time() - start_epoch:.1f} seconds.")
if epoch % args.test_epochs == 0:
if isinstance(model, en_diffusion.EnVariationalDiffusion):
wandb.log(model.log_info(), commit=True)
if not args.break_train_epoch:
train_test.analyze_and_save(epoch, model_ema, nodes_dist, args, device,
dataset_info, prop_dist, n_samples=args.n_stability_samples)
nll_val = train_test.test(args, dataloaders['val'], epoch, model_ema_dp, device, dtype,
property_norms, nodes_dist, partition='Val')
nll_test = train_test.test(args, dataloaders['test'], epoch, model_ema_dp, device, dtype,
property_norms, nodes_dist, partition='Test')
if nll_val < best_nll_val:
best_nll_val = nll_val
best_nll_test = nll_test
if args.save_model:
args.current_epoch = epoch + 1
utils.save_model(optim, 'outputs/%s/optim.npy' % args.exp_name)
utils.save_model(model, 'outputs/%s/generative_model.npy' % args.exp_name)
if args.ema_decay > 0:
utils.save_model(model_ema, 'outputs/%s/generative_model_ema.npy' % args.exp_name)
with open('outputs/%s/args.pickle' % args.exp_name, 'wb') as f:
pickle.dump(args, f)
if args.save_model:
utils.save_model(optim, 'outputs/%s/optim_%d.npy' % (args.exp_name, epoch))
utils.save_model(model, 'outputs/%s/generative_model_%d.npy' % (args.exp_name, epoch))
if args.ema_decay > 0:
utils.save_model(model_ema, 'outputs/%s/generative_model_ema_%d.npy' % (args.exp_name, epoch))
with open('outputs/%s/args_%d.pickle' % (args.exp_name, epoch), 'wb') as f:
pickle.dump(args, f)
print('Val loss: %.4f \t Test loss: %.4f' % (nll_val, nll_test))
print('Best val loss: %.4f \t Best test loss: %.4f' % (best_nll_val, best_nll_test))
wandb.log({"Val loss ": nll_val}, commit=True)
wandb.log({"Test loss ": nll_test}, commit=True)
wandb.log({"Best cross-validated test loss ": best_nll_test}, commit=True)
if __name__ == "__main__":
main()
| 12,752 | 44.384342 | 138 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/eval_conditional_qm9.py | import argparse
from os.path import join
import torch
import pickle
from qm9.models import get_model
from configs.datasets_config import get_dataset_info
from qm9 import dataset
from qm9.utils import compute_mean_mad
from qm9.sampling import sample
from qm9.property_prediction.main_qm9_prop import test
from qm9.property_prediction import main_qm9_prop
from qm9.sampling import sample_chain, sample, sample_sweep_conditional
import qm9.visualizer as vis
def get_classifier(dir_path='', device='cpu'):
with open(join(dir_path, 'args.pickle'), 'rb') as f:
args_classifier = pickle.load(f)
args_classifier.device = device
args_classifier.model_name = 'egnn'
classifier = main_qm9_prop.get_model(args_classifier)
classifier_state_dict = torch.load(join(dir_path, 'best_checkpoint.npy'), map_location=torch.device('cpu'))
classifier.load_state_dict(classifier_state_dict)
return classifier
def get_args_gen(dir_path):
with open(join(dir_path, 'args.pickle'), 'rb') as f:
args_gen = pickle.load(f)
assert args_gen.dataset == 'qm9_second_half'
# Add missing args!
if not hasattr(args_gen, 'normalization_factor'):
args_gen.normalization_factor = 1
if not hasattr(args_gen, 'aggregation_method'):
args_gen.aggregation_method = 'sum'
return args_gen
def get_generator(dir_path, dataloaders, device, args_gen, property_norms):
dataset_info = get_dataset_info(args_gen.dataset, args_gen.remove_h)
model, nodes_dist, prop_dist = get_model(args_gen, device, dataset_info, dataloaders['train'])
fn = 'generative_model_ema.npy' if args_gen.ema_decay > 0 else 'generative_model.npy'
model_state_dict = torch.load(join(dir_path, fn), map_location='cpu')
model.load_state_dict(model_state_dict)
# The following function be computes the normalization parameters using the 'valid' partition
if prop_dist is not None:
prop_dist.set_normalizer(property_norms)
return model.to(device), nodes_dist, prop_dist, dataset_info
def get_dataloader(args_gen):
dataloaders, charge_scale = dataset.retrieve_dataloaders(args_gen)
return dataloaders
class DiffusionDataloader:
def __init__(self, args_gen, model, nodes_dist, prop_dist, device, unkown_labels=False,
batch_size=1, iterations=200):
self.args_gen = args_gen
self.model = model
self.nodes_dist = nodes_dist
self.prop_dist = prop_dist
self.batch_size = batch_size
self.iterations = iterations
self.device = device
self.unkown_labels = unkown_labels
self.dataset_info = get_dataset_info(self.args_gen.dataset, self.args_gen.remove_h)
self.i = 0
def __iter__(self):
return self
def sample(self):
nodesxsample = self.nodes_dist.sample(self.batch_size)
context = self.prop_dist.sample_batch(nodesxsample).to(self.device)
one_hot, charges, x, node_mask = sample(self.args_gen, self.device, self.model,
self.dataset_info, self.prop_dist, nodesxsample=nodesxsample,
context=context)
node_mask = node_mask.squeeze(2)
context = context.squeeze(1)
# edge_mask
bs, n_nodes = node_mask.size()
edge_mask = node_mask.unsqueeze(1) * node_mask.unsqueeze(2)
diag_mask = ~torch.eye(edge_mask.size(1), dtype=torch.bool).unsqueeze(0)
diag_mask = diag_mask.to(self.device)
edge_mask *= diag_mask
edge_mask = edge_mask.view(bs * n_nodes * n_nodes, 1)
prop_key = self.prop_dist.properties[0]
if self.unkown_labels:
context[:] = self.prop_dist.normalizer[prop_key]['mean']
else:
context = context * self.prop_dist.normalizer[prop_key]['mad'] + self.prop_dist.normalizer[prop_key]['mean']
data = {
'positions': x.detach(),
'atom_mask': node_mask.detach(),
'edge_mask': edge_mask.detach(),
'one_hot': one_hot.detach(),
prop_key: context.detach()
}
return data
def __next__(self):
if self.i <= self.iterations:
self.i += 1
return self.sample()
else:
self.i = 0
raise StopIteration
def __len__(self):
return self.iterations
def main_quantitative(args):
# Get classifier
#if args.task == "numnodes":
# class_dir = args.classifiers_path[:-6] + "numnodes_%s" % args.property
#else:
class_dir = args.classifiers_path
classifier = get_classifier(class_dir).to(args.device)
# Get generator and dataloader used to train the generator and evalute the classifier
args_gen = get_args_gen(args.generators_path)
# Careful with this -->
if not hasattr(args_gen, 'diffusion_noise_precision'):
args_gen.normalization_factor = 1e-4
if not hasattr(args_gen, 'normalization_factor'):
args_gen.normalization_factor = 1
if not hasattr(args_gen, 'aggregation_method'):
args_gen.aggregation_method = 'sum'
dataloaders = get_dataloader(args_gen)
property_norms = compute_mean_mad(dataloaders, args_gen.conditioning, args_gen.dataset)
model, nodes_dist, prop_dist, _ = get_generator(args.generators_path, dataloaders,
args.device, args_gen, property_norms)
# Create a dataloader with the generator
mean, mad = property_norms[args.property]['mean'], property_norms[args.property]['mad']
if args.task == 'edm':
diffusion_dataloader = DiffusionDataloader(args_gen, model, nodes_dist, prop_dist,
args.device, batch_size=args.batch_size, iterations=args.iterations)
print("EDM: We evaluate the classifier on our generated samples")
loss = test(classifier, 0, diffusion_dataloader, mean, mad, args.property, args.device, 1, args.debug_break)
print("Loss classifier on Generated samples: %.4f" % loss)
elif args.task == 'qm9_second_half':
print("qm9_second_half: We evaluate the classifier on QM9")
loss = test(classifier, 0, dataloaders['train'], mean, mad, args.property, args.device, args.log_interval,
args.debug_break)
print("Loss classifier on qm9_second_half: %.4f" % loss)
elif args.task == 'naive':
print("Naive: We evaluate the classifier on QM9")
length = dataloaders['train'].dataset.data[args.property].size(0)
idxs = torch.randperm(length)
dataloaders['train'].dataset.data[args.property] = dataloaders['train'].dataset.data[args.property][idxs]
loss = test(classifier, 0, dataloaders['train'], mean, mad, args.property, args.device, args.log_interval,
args.debug_break)
print("Loss classifier on naive: %.4f" % loss)
#elif args.task == 'numnodes':
# print("Numnodes: We evaluate the numnodes classifier on EDM samples")
# diffusion_dataloader = DiffusionDataloader(args_gen, model, nodes_dist, prop_dist, device,
# batch_size=args.batch_size, iterations=args.iterations)
# loss = test(classifier, 0, diffusion_dataloader, mean, mad, args.property, args.device, 1, args.debug_break)
# print("Loss numnodes classifier on EDM generated samples: %.4f" % loss)
def save_and_sample_conditional(args, device, model, prop_dist, dataset_info, epoch=0, id_from=0):
one_hot, charges, x, node_mask = sample_sweep_conditional(args, device, model, dataset_info, prop_dist)
vis.save_xyz_file(
'outputs/%s/analysis/run%s/' % (args.exp_name, epoch), one_hot, charges, x, dataset_info,
id_from, name='conditional', node_mask=node_mask)
vis.visualize_chain("outputs/%s/analysis/run%s/" % (args.exp_name, epoch), dataset_info,
wandb=None, mode='conditional', spheres_3d=True)
return one_hot, charges, x
def main_qualitative(args):
args_gen = get_args_gen(args.generators_path)
dataloaders = get_dataloader(args_gen)
property_norms = compute_mean_mad(dataloaders, args_gen.conditioning, args_gen.dataset)
model, nodes_dist, prop_dist, dataset_info = get_generator(args.generators_path,
dataloaders, args.device, args_gen,
property_norms)
for i in range(args.n_sweeps):
print("Sampling sweep %d/%d" % (i+1, args.n_sweeps))
save_and_sample_conditional(args_gen, device, model, prop_dist, dataset_info, epoch=i, id_from=0)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--exp_name', type=str, default='debug_alpha')
parser.add_argument('--generators_path', type=str, default='outputs/exp_cond_alpha_pretrained')
parser.add_argument('--classifiers_path', type=str, default='qm9/property_prediction/outputs/exp_class_alpha_pretrained')
parser.add_argument('--property', type=str, default='alpha',
help="'alpha', 'homo', 'lumo', 'gap', 'mu', 'Cv'")
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--debug_break', type=eval, default=False,
help='break point or not')
parser.add_argument('--log_interval', type=int, default=5,
help='break point or not')
parser.add_argument('--batch_size', type=int, default=1,
help='break point or not')
parser.add_argument('--iterations', type=int, default=20,
help='break point or not')
parser.add_argument('--task', type=str, default='qualitative',
help='naive, edm, qm9_second_half, qualitative')
parser.add_argument('--n_sweeps', type=int, default=10,
help='number of sweeps for the qualitative conditional experiment')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if args.cuda else "cpu")
args.device = device
if args.task == 'qualitative':
main_qualitative(args)
else:
main_quantitative(args)
| 10,394 | 43.613734 | 125 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/eval_sample.py | # Rdkit import should be first, do not move it
try:
from rdkit import Chem
except ModuleNotFoundError:
pass
import utils
import argparse
from configs.datasets_config import qm9_with_h, qm9_without_h
from qm9 import dataset
from qm9.models import get_model
from equivariant_diffusion.utils import assert_correctly_masked
import torch
import pickle
import qm9.visualizer as vis
from qm9.analyze import check_stability
from os.path import join
from qm9.sampling import sample_chain, sample
from configs.datasets_config import get_dataset_info
def check_mask_correct(variables, node_mask):
for variable in variables:
assert_correctly_masked(variable, node_mask)
def save_and_sample_chain(args, eval_args, device, flow,
n_tries, n_nodes, dataset_info, id_from=0,
num_chains=100):
for i in range(num_chains):
target_path = f'eval/chain_{i}/'
one_hot, charges, x = sample_chain(
args, device, flow, n_tries, dataset_info)
vis.save_xyz_file(
join(eval_args.model_path, target_path), one_hot, charges, x,
dataset_info, id_from, name='chain')
vis.visualize_chain_uncertainty(
join(eval_args.model_path, target_path), dataset_info,
spheres_3d=True)
return one_hot, charges, x
def sample_different_sizes_and_save(args, eval_args, device, generative_model,
nodes_dist, dataset_info, n_samples=10):
nodesxsample = nodes_dist.sample(n_samples)
one_hot, charges, x, node_mask = sample(
args, device, generative_model, dataset_info,
nodesxsample=nodesxsample)
vis.save_xyz_file(
join(eval_args.model_path, 'eval/molecules/'), one_hot, charges, x,
id_from=0, name='molecule', dataset_info=dataset_info,
node_mask=node_mask)
def sample_only_stable_different_sizes_and_save(
args, eval_args, device, flow, nodes_dist,
dataset_info, n_samples=10, n_tries=50):
assert n_tries > n_samples
nodesxsample = nodes_dist.sample(n_tries)
one_hot, charges, x, node_mask = sample(
args, device, flow, dataset_info,
nodesxsample=nodesxsample)
counter = 0
for i in range(n_tries):
num_atoms = int(node_mask[i:i+1].sum().item())
atom_type = one_hot[i:i+1, :num_atoms].argmax(2).squeeze(0).cpu().detach().numpy()
x_squeeze = x[i:i+1, :num_atoms].squeeze(0).cpu().detach().numpy()
mol_stable = check_stability(x_squeeze, atom_type, dataset_info)[0]
num_remaining_attempts = n_tries - i - 1
num_remaining_samples = n_samples - counter
if mol_stable or num_remaining_attempts <= num_remaining_samples:
if mol_stable:
print('Found stable mol.')
vis.save_xyz_file(
join(eval_args.model_path, 'eval/molecules/'),
one_hot[i:i+1], charges[i:i+1], x[i:i+1],
id_from=counter, name='molecule_stable',
dataset_info=dataset_info,
node_mask=node_mask[i:i+1])
counter += 1
if counter >= n_samples:
break
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', type=str,
default="outputs/edm_1",
help='Specify model path')
parser.add_argument(
'--n_tries', type=int, default=10,
help='N tries to find stable molecule for gif animation')
parser.add_argument('--n_nodes', type=int, default=19,
help='number of atoms in molecule for gif animation')
eval_args, unparsed_args = parser.parse_known_args()
assert eval_args.model_path is not None
with open(join(eval_args.model_path, 'args.pickle'), 'rb') as f:
args = pickle.load(f)
# CAREFUL with this -->
if not hasattr(args, 'normalization_factor'):
args.normalization_factor = 1
if not hasattr(args, 'aggregation_method'):
args.aggregation_method = 'sum'
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if args.cuda else "cpu")
args.device = device
dtype = torch.float32
utils.create_folders(args)
print(args)
dataset_info = get_dataset_info(args.dataset, args.remove_h)
dataloaders, charge_scale = dataset.retrieve_dataloaders(args)
flow, nodes_dist, prop_dist = get_model(
args, device, dataset_info, dataloaders['train'])
flow.to(device)
fn = 'generative_model_ema.npy' if args.ema_decay > 0 else 'generative_model.npy'
flow_state_dict = torch.load(join(eval_args.model_path, fn),
map_location=device)
flow.load_state_dict(flow_state_dict)
print('Sampling handful of molecules.')
sample_different_sizes_and_save(
args, eval_args, device, flow, nodes_dist,
dataset_info=dataset_info, n_samples=30)
print('Sampling stable molecules.')
sample_only_stable_different_sizes_and_save(
args, eval_args, device, flow, nodes_dist,
dataset_info=dataset_info, n_samples=10, n_tries=2*10)
print('Visualizing molecules.')
vis.visualize(
join(eval_args.model_path, 'eval/molecules/'), dataset_info,
max_num=100, spheres_3d=True)
print('Sampling visualization chain.')
save_and_sample_chain(
args, eval_args, device, flow,
n_tries=eval_args.n_tries, n_nodes=eval_args.n_nodes,
dataset_info=dataset_info)
if __name__ == "__main__":
main()
| 5,606 | 32.981818 | 90 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/main_qm9.py | # Rdkit import should be first, do not move it
try:
from rdkit import Chem
except ModuleNotFoundError:
pass
import copy
import utils
import argparse
import wandb
from configs.datasets_config import get_dataset_info
from os.path import join
from qm9 import dataset
from qm9.models import get_optim, get_model
from equivariant_diffusion import en_diffusion
from equivariant_diffusion.utils import assert_correctly_masked
from equivariant_diffusion import utils as flow_utils
import torch
import time
import pickle
from qm9.utils import prepare_context, compute_mean_mad
from train_test import train_epoch, test, analyze_and_save
parser = argparse.ArgumentParser(description='E3Diffusion')
parser.add_argument('--exp_name', type=str, default='debug_10')
parser.add_argument('--model', type=str, default='egnn_dynamics',
help='our_dynamics | schnet | simple_dynamics | '
'kernel_dynamics | egnn_dynamics |gnn_dynamics')
parser.add_argument('--probabilistic_model', type=str, default='diffusion',
help='diffusion')
# Training complexity is O(1) (unaffected), but sampling complexity is O(steps).
parser.add_argument('--diffusion_steps', type=int, default=500)
parser.add_argument('--diffusion_noise_schedule', type=str, default='polynomial_2',
help='learned, cosine')
parser.add_argument('--diffusion_noise_precision', type=float, default=1e-5,
)
parser.add_argument('--diffusion_loss_type', type=str, default='l2',
help='vlb, l2')
parser.add_argument('--n_epochs', type=int, default=200)
parser.add_argument('--batch_size', type=int, default=128)
parser.add_argument('--lr', type=float, default=2e-4)
parser.add_argument('--brute_force', type=eval, default=False,
help='True | False')
parser.add_argument('--actnorm', type=eval, default=True,
help='True | False')
parser.add_argument('--break_train_epoch', type=eval, default=False,
help='True | False')
parser.add_argument('--dp', type=eval, default=True,
help='True | False')
parser.add_argument('--condition_time', type=eval, default=True,
help='True | False')
parser.add_argument('--clip_grad', type=eval, default=True,
help='True | False')
parser.add_argument('--trace', type=str, default='hutch',
help='hutch | exact')
# EGNN args -->
parser.add_argument('--n_layers', type=int, default=6,
help='number of layers')
parser.add_argument('--inv_sublayers', type=int, default=1,
help='number of layers')
parser.add_argument('--nf', type=int, default=128,
help='number of layers')
parser.add_argument('--tanh', type=eval, default=True,
help='use tanh in the coord_mlp')
parser.add_argument('--attention', type=eval, default=True,
help='use attention in the EGNN')
parser.add_argument('--norm_constant', type=float, default=1,
help='diff/(|diff| + norm_constant)')
parser.add_argument('--sin_embedding', type=eval, default=False,
help='whether using or not the sin embedding')
# <-- EGNN args
parser.add_argument('--ode_regularization', type=float, default=1e-3)
parser.add_argument('--dataset', type=str, default='qm9',
help='qm9 | qm9_second_half (train only on the last 50K samples of the training dataset)')
parser.add_argument('--datadir', type=str, default='qm9/temp',
help='qm9 directory')
parser.add_argument('--filter_n_atoms', type=int, default=None,
help='When set to an integer value, QM9 will only contain molecules of that amount of atoms')
parser.add_argument('--dequantization', type=str, default='argmax_variational',
help='uniform | variational | argmax_variational | deterministic')
parser.add_argument('--n_report_steps', type=int, default=1)
parser.add_argument('--wandb_usr', type=str)
parser.add_argument('--no_wandb', action='store_true', help='Disable wandb')
parser.add_argument('--online', type=bool, default=True, help='True = wandb online -- False = wandb offline')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--save_model', type=eval, default=True,
help='save model')
parser.add_argument('--generate_epochs', type=int, default=1,
help='save model')
parser.add_argument('--num_workers', type=int, default=0, help='Number of worker for the dataloader')
parser.add_argument('--test_epochs', type=int, default=10)
parser.add_argument('--data_augmentation', type=eval, default=False, help='use attention in the EGNN')
parser.add_argument("--conditioning", nargs='+', default=[],
help='arguments : homo | lumo | alpha | gap | mu | Cv' )
parser.add_argument('--resume', type=str, default=None,
help='')
parser.add_argument('--start_epoch', type=int, default=0,
help='')
parser.add_argument('--ema_decay', type=float, default=0.999,
help='Amount of EMA decay, 0 means off. A reasonable value'
' is 0.999.')
parser.add_argument('--augment_noise', type=float, default=0)
parser.add_argument('--n_stability_samples', type=int, default=500,
help='Number of samples to compute the stability')
parser.add_argument('--normalize_factors', type=eval, default=[1, 4, 1],
help='normalize factors for [x, categorical, integer]')
parser.add_argument('--remove_h', action='store_true')
parser.add_argument('--include_charges', type=eval, default=True,
help='include atom charge or not')
parser.add_argument('--visualize_every_batch', type=int, default=1e8,
help="Can be used to visualize multiple times per epoch")
parser.add_argument('--normalization_factor', type=float, default=1,
help="Normalize the sum aggregation of EGNN")
parser.add_argument('--aggregation_method', type=str, default='sum',
help='"sum" or "mean"')
args = parser.parse_args()
dataset_info = get_dataset_info(args.dataset, args.remove_h)
atom_encoder = dataset_info['atom_encoder']
atom_decoder = dataset_info['atom_decoder']
# args, unparsed_args = parser.parse_known_args()
args.wandb_usr = utils.get_wandb_username(args.wandb_usr)
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if args.cuda else "cpu")
dtype = torch.float32
if args.resume is not None:
exp_name = args.exp_name + '_resume'
start_epoch = args.start_epoch
resume = args.resume
wandb_usr = args.wandb_usr
normalization_factor = args.normalization_factor
aggregation_method = args.aggregation_method
with open(join(args.resume, 'args.pickle'), 'rb') as f:
args = pickle.load(f)
args.resume = resume
args.break_train_epoch = False
args.exp_name = exp_name
args.start_epoch = start_epoch
args.wandb_usr = wandb_usr
# Careful with this -->
if not hasattr(args, 'normalization_factor'):
args.normalization_factor = normalization_factor
if not hasattr(args, 'aggregation_method'):
args.aggregation_method = aggregation_method
print(args)
utils.create_folders(args)
# print(args)
# Wandb config
if args.no_wandb:
mode = 'disabled'
else:
mode = 'online' if args.online else 'offline'
kwargs = {'entity': args.wandb_usr, 'name': args.exp_name, 'project': 'e3_diffusion', 'config': args,
'settings': wandb.Settings(_disable_stats=True), 'reinit': True, 'mode': mode}
wandb.init(**kwargs)
wandb.save('*.txt')
# Retrieve QM9 dataloaders
dataloaders, charge_scale = dataset.retrieve_dataloaders(args)
data_dummy = next(iter(dataloaders['train']))
if len(args.conditioning) > 0:
print(f'Conditioning on {args.conditioning}')
property_norms = compute_mean_mad(dataloaders, args.conditioning, args.dataset)
context_dummy = prepare_context(args.conditioning, data_dummy, property_norms)
context_node_nf = context_dummy.size(2)
else:
context_node_nf = 0
property_norms = None
args.context_node_nf = context_node_nf
# Create EGNN flow
model, nodes_dist, prop_dist = get_model(args, device, dataset_info, dataloaders['train'])
if prop_dist is not None:
prop_dist.set_normalizer(property_norms)
model = model.to(device)
optim = get_optim(args, model)
# print(model)
gradnorm_queue = utils.Queue()
gradnorm_queue.add(3000) # Add large value that will be flushed.
def check_mask_correct(variables, node_mask):
for variable in variables:
if len(variable) > 0:
assert_correctly_masked(variable, node_mask)
def main():
if args.resume is not None:
flow_state_dict = torch.load(join(args.resume, 'flow.npy'))
optim_state_dict = torch.load(join(args.resume, 'optim.npy'))
model.load_state_dict(flow_state_dict)
optim.load_state_dict(optim_state_dict)
# Initialize dataparallel if enabled and possible.
if args.dp and torch.cuda.device_count() > 1:
print(f'Training using {torch.cuda.device_count()} GPUs')
model_dp = torch.nn.DataParallel(model.cpu())
model_dp = model_dp.cuda()
else:
model_dp = model
# Initialize model copy for exponential moving average of params.
if args.ema_decay > 0:
model_ema = copy.deepcopy(model)
ema = flow_utils.EMA(args.ema_decay)
if args.dp and torch.cuda.device_count() > 1:
model_ema_dp = torch.nn.DataParallel(model_ema)
else:
model_ema_dp = model_ema
else:
ema = None
model_ema = model
model_ema_dp = model_dp
best_nll_val = 1e8
best_nll_test = 1e8
for epoch in range(args.start_epoch, args.n_epochs):
start_epoch = time.time()
train_epoch(args=args, loader=dataloaders['train'], epoch=epoch, model=model, model_dp=model_dp,
model_ema=model_ema, ema=ema, device=device, dtype=dtype, property_norms=property_norms,
nodes_dist=nodes_dist, dataset_info=dataset_info,
gradnorm_queue=gradnorm_queue, optim=optim, prop_dist=prop_dist)
print(f"Epoch took {time.time() - start_epoch:.1f} seconds.")
if epoch % args.test_epochs == 0:
if isinstance(model, en_diffusion.EnVariationalDiffusion):
wandb.log(model.log_info(), commit=True)
if not args.break_train_epoch:
analyze_and_save(args=args, epoch=epoch, model_sample=model_ema, nodes_dist=nodes_dist,
dataset_info=dataset_info, device=device,
prop_dist=prop_dist, n_samples=args.n_stability_samples)
nll_val = test(args=args, loader=dataloaders['valid'], epoch=epoch, eval_model=model_ema_dp,
partition='Val', device=device, dtype=dtype, nodes_dist=nodes_dist,
property_norms=property_norms)
nll_test = test(args=args, loader=dataloaders['test'], epoch=epoch, eval_model=model_ema_dp,
partition='Test', device=device, dtype=dtype,
nodes_dist=nodes_dist, property_norms=property_norms)
if nll_val < best_nll_val:
best_nll_val = nll_val
best_nll_test = nll_test
if args.save_model:
args.current_epoch = epoch + 1
utils.save_model(optim, 'outputs/%s/optim.npy' % args.exp_name)
utils.save_model(model, 'outputs/%s/generative_model.npy' % args.exp_name)
if args.ema_decay > 0:
utils.save_model(model_ema, 'outputs/%s/generative_model_ema.npy' % args.exp_name)
with open('outputs/%s/args.pickle' % args.exp_name, 'wb') as f:
pickle.dump(args, f)
if args.save_model:
utils.save_model(optim, 'outputs/%s/optim_%d.npy' % (args.exp_name, epoch))
utils.save_model(model, 'outputs/%s/generative_model_%d.npy' % (args.exp_name, epoch))
if args.ema_decay > 0:
utils.save_model(model_ema, 'outputs/%s/generative_model_ema_%d.npy' % (args.exp_name, epoch))
with open('outputs/%s/args_%d.pickle' % (args.exp_name, epoch), 'wb') as f:
pickle.dump(args, f)
print('Val loss: %.4f \t Test loss: %.4f' % (nll_val, nll_test))
print('Best val loss: %.4f \t Best test loss: %.4f' % (best_nll_val, best_nll_test))
wandb.log({"Val loss ": nll_val}, commit=True)
wandb.log({"Test loss ": nll_test}, commit=True)
wandb.log({"Best cross-validated test loss ": best_nll_test}, commit=True)
if __name__ == "__main__":
main()
| 13,079 | 44.103448 | 118 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/train_test.py | import wandb
from equivariant_diffusion.utils import assert_mean_zero_with_mask, remove_mean_with_mask,\
assert_correctly_masked, sample_center_gravity_zero_gaussian_with_mask
import numpy as np
import qm9.visualizer as vis
from qm9.analyze import analyze_stability_for_molecules
from qm9.sampling import sample_chain, sample, sample_sweep_conditional
import utils
import qm9.utils as qm9utils
from qm9 import losses
import time
import torch
def train_epoch(args, loader, epoch, model, model_dp, model_ema, ema, device, dtype, property_norms, optim,
nodes_dist, gradnorm_queue, dataset_info, prop_dist):
model_dp.train()
model.train()
nll_epoch = []
n_iterations = len(loader)
for i, data in enumerate(loader):
x = data['positions'].to(device, dtype)
node_mask = data['atom_mask'].to(device, dtype).unsqueeze(2)
edge_mask = data['edge_mask'].to(device, dtype)
one_hot = data['one_hot'].to(device, dtype)
charges = (data['charges'] if args.include_charges else torch.zeros(0)).to(device, dtype)
x = remove_mean_with_mask(x, node_mask)
if args.augment_noise > 0:
# Add noise eps ~ N(0, augment_noise) around points.
eps = sample_center_gravity_zero_gaussian_with_mask(x.size(), x.device, node_mask)
x = x + eps * args.augment_noise
x = remove_mean_with_mask(x, node_mask)
if args.data_augmentation:
x = utils.random_rotation(x).detach()
check_mask_correct([x, one_hot, charges], node_mask)
assert_mean_zero_with_mask(x, node_mask)
h = {'categorical': one_hot, 'integer': charges}
if len(args.conditioning) > 0:
context = qm9utils.prepare_context(args.conditioning, data, property_norms).to(device, dtype)
assert_correctly_masked(context, node_mask)
else:
context = None
optim.zero_grad()
# transform batch through flow
nll, reg_term, mean_abs_z = losses.compute_loss_and_nll(args, model_dp, nodes_dist,
x, h, node_mask, edge_mask, context)
# standard nll from forward KL
loss = nll + args.ode_regularization * reg_term
loss.backward()
if args.clip_grad:
grad_norm = utils.gradient_clipping(model, gradnorm_queue)
else:
grad_norm = 0.
optim.step()
# Update EMA if enabled.
if args.ema_decay > 0:
ema.update_model_average(model_ema, model)
if i % args.n_report_steps == 0:
print(f"\rEpoch: {epoch}, iter: {i}/{n_iterations}, "
f"Loss {loss.item():.2f}, NLL: {nll.item():.2f}, "
f"RegTerm: {reg_term.item():.1f}, "
f"GradNorm: {grad_norm:.1f}")
nll_epoch.append(nll.item())
if (epoch % args.test_epochs == 0) and (i % args.visualize_every_batch == 0) and not (epoch == 0 and i == 0):
start = time.time()
if len(args.conditioning) > 0:
save_and_sample_conditional(args, device, model_ema, prop_dist, dataset_info, epoch=epoch)
save_and_sample_chain(model_ema, args, device, dataset_info, prop_dist, epoch=epoch,
batch_id=str(i))
sample_different_sizes_and_save(model_ema, nodes_dist, args, device, dataset_info,
prop_dist, epoch=epoch)
print(f'Sampling took {time.time() - start:.2f} seconds')
vis.visualize(f"outputs/{args.exp_name}/epoch_{epoch}_{i}", dataset_info=dataset_info, wandb=wandb)
vis.visualize_chain(f"outputs/{args.exp_name}/epoch_{epoch}_{i}/chain/", dataset_info, wandb=wandb)
if len(args.conditioning) > 0:
vis.visualize_chain("outputs/%s/epoch_%d/conditional/" % (args.exp_name, epoch), dataset_info,
wandb=wandb, mode='conditional')
wandb.log({"Batch NLL": nll.item()}, commit=True)
if args.break_train_epoch:
break
wandb.log({"Train Epoch NLL": np.mean(nll_epoch)}, commit=False)
def check_mask_correct(variables, node_mask):
for i, variable in enumerate(variables):
if len(variable) > 0:
assert_correctly_masked(variable, node_mask)
def test(args, loader, epoch, eval_model, device, dtype, property_norms, nodes_dist, partition='Test'):
eval_model.eval()
with torch.no_grad():
nll_epoch = 0
n_samples = 0
n_iterations = len(loader)
for i, data in enumerate(loader):
x = data['positions'].to(device, dtype)
batch_size = x.size(0)
node_mask = data['atom_mask'].to(device, dtype).unsqueeze(2)
edge_mask = data['edge_mask'].to(device, dtype)
one_hot = data['one_hot'].to(device, dtype)
charges = (data['charges'] if args.include_charges else torch.zeros(0)).to(device, dtype)
if args.augment_noise > 0:
# Add noise eps ~ N(0, augment_noise) around points.
eps = sample_center_gravity_zero_gaussian_with_mask(x.size(),
x.device,
node_mask)
x = x + eps * args.augment_noise
x = remove_mean_with_mask(x, node_mask)
check_mask_correct([x, one_hot, charges], node_mask)
assert_mean_zero_with_mask(x, node_mask)
h = {'categorical': one_hot, 'integer': charges}
if len(args.conditioning) > 0:
context = qm9utils.prepare_context(args.conditioning, data, property_norms).to(device, dtype)
assert_correctly_masked(context, node_mask)
else:
context = None
# transform batch through flow
nll, _, _ = losses.compute_loss_and_nll(args, eval_model, nodes_dist, x, h,
node_mask, edge_mask, context)
# standard nll from forward KL
nll_epoch += nll.item() * batch_size
n_samples += batch_size
if i % args.n_report_steps == 0:
print(f"\r {partition} NLL \t epoch: {epoch}, iter: {i}/{n_iterations}, "
f"NLL: {nll_epoch/n_samples:.2f}")
return nll_epoch/n_samples
def save_and_sample_chain(model, args, device, dataset_info, prop_dist,
epoch=0, id_from=0, batch_id=''):
one_hot, charges, x = sample_chain(args=args, device=device, flow=model,
n_tries=1, dataset_info=dataset_info, prop_dist=prop_dist)
vis.save_xyz_file(f'outputs/{args.exp_name}/epoch_{epoch}_{batch_id}/chain/',
one_hot, charges, x, dataset_info, id_from, name='chain')
return one_hot, charges, x
def sample_different_sizes_and_save(model, nodes_dist, args, device, dataset_info, prop_dist,
n_samples=5, epoch=0, batch_size=100, batch_id=''):
batch_size = min(batch_size, n_samples)
for counter in range(int(n_samples/batch_size)):
nodesxsample = nodes_dist.sample(batch_size)
one_hot, charges, x, node_mask = sample(args, device, model, prop_dist=prop_dist,
nodesxsample=nodesxsample,
dataset_info=dataset_info)
print(f"Generated molecule: Positions {x[:-1, :, :]}")
vis.save_xyz_file(f'outputs/{args.exp_name}/epoch_{epoch}_{batch_id}/', one_hot, charges, x, dataset_info,
batch_size * counter, name='molecule')
def analyze_and_save(epoch, model_sample, nodes_dist, args, device, dataset_info, prop_dist,
n_samples=1000, batch_size=100):
print(f'Analyzing molecule stability at epoch {epoch}...')
batch_size = min(batch_size, n_samples)
assert n_samples % batch_size == 0
molecules = {'one_hot': [], 'x': [], 'node_mask': []}
for i in range(int(n_samples/batch_size)):
nodesxsample = nodes_dist.sample(batch_size)
one_hot, charges, x, node_mask = sample(args, device, model_sample, dataset_info, prop_dist,
nodesxsample=nodesxsample)
molecules['one_hot'].append(one_hot.detach().cpu())
molecules['x'].append(x.detach().cpu())
molecules['node_mask'].append(node_mask.detach().cpu())
molecules = {key: torch.cat(molecules[key], dim=0) for key in molecules}
validity_dict, rdkit_tuple = analyze_stability_for_molecules(molecules, dataset_info)
wandb.log(validity_dict)
if rdkit_tuple is not None:
wandb.log({'Validity': rdkit_tuple[0][0], 'Uniqueness': rdkit_tuple[0][1], 'Novelty': rdkit_tuple[0][2]})
return validity_dict
def save_and_sample_conditional(args, device, model, prop_dist, dataset_info, epoch=0, id_from=0):
one_hot, charges, x, node_mask = sample_sweep_conditional(args, device, model, dataset_info, prop_dist)
vis.save_xyz_file(
'outputs/%s/epoch_%d/conditional/' % (args.exp_name, epoch), one_hot, charges, x, dataset_info,
id_from, name='conditional', node_mask=node_mask)
return one_hot, charges, x
| 9,409 | 44.240385 | 117 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/configs/datasets_config.py |
qm9_with_h = {
'name': 'qm9',
'atom_encoder': {'H': 0, 'C': 1, 'N': 2, 'O': 3, 'F': 4},
'atom_decoder': ['H', 'C', 'N', 'O', 'F'],
'n_nodes': {22: 3393, 17: 13025, 23: 4848, 21: 9970, 19: 13832, 20: 9482, 16: 10644, 13: 3060,
15: 7796, 25: 1506, 18: 13364, 12: 1689, 11: 807, 24: 539, 14: 5136, 26: 48, 7: 16, 10: 362,
8: 49, 9: 124, 27: 266, 4: 4, 29: 25, 6: 9, 5: 5, 3: 1},
'max_n_nodes': 29,
'atom_types': {1: 635559, 2: 101476, 0: 923537, 3: 140202, 4: 2323},
'distances': [903054, 307308, 111994, 57474, 40384, 29170, 47152, 414344, 2202212, 573726,
1490786, 2970978, 756818, 969276, 489242, 1265402, 4587994, 3187130, 2454868, 2647422,
2098884,
2001974, 1625206, 1754172, 1620830, 1710042, 2133746, 1852492, 1415318, 1421064, 1223156,
1322256,
1380656, 1239244, 1084358, 981076, 896904, 762008, 659298, 604676, 523580, 437464, 413974,
352372,
291886, 271948, 231328, 188484, 160026, 136322, 117850, 103546, 87192, 76562, 61840,
49666, 43100,
33876, 26686, 22402, 18358, 15518, 13600, 12128, 9480, 7458, 5088, 4726, 3696, 3362, 3396,
2484,
1988, 1490, 984, 734, 600, 456, 482, 378, 362, 168, 124, 94, 88, 52, 44, 40, 18, 16, 8, 6,
2,
0, 0, 0, 0,
0,
0, 0],
'colors_dic': ['#FFFFFF99', 'C7', 'C0', 'C3', 'C1'],
'radius_dic': [0.46, 0.77, 0.77, 0.77, 0.77],
'with_h': True}
# 'bond1_radius': {'H': 31, 'C': 76, 'N': 71, 'O': 66, 'F': 57},
# 'bond1_stdv': {'H': 5, 'C': 2, 'N': 2, 'O': 2, 'F': 3},
# 'bond2_radius': {'H': -1000, 'C': 67, 'N': 60, 'O': 57, 'F': 59},
# 'bond3_radius': {'H': -1000, 'C': 60, 'N': 54, 'O': 53, 'F': 53}}
qm9_without_h = {
'name': 'qm9',
'atom_encoder': {'C': 0, 'N': 1, 'O': 2, 'F': 3},
'atom_decoder': ['C', 'N', 'O', 'F'],
'max_n_nodes': 29,
'n_nodes': {9: 83366, 8: 13625, 7: 2404, 6: 475, 5: 91, 4: 25, 3: 7, 1: 2, 2: 5},
'atom_types': {0: 635559, 2: 140202, 1: 101476, 3: 2323},
'distances': [594, 1232, 3706, 4736, 5478, 9156, 8762, 13260, 45674, 174676, 469292,
1182942, 126722, 25768, 28532, 51696, 232014, 299916, 686590, 677506,
379264, 162794, 158732, 156404, 161742, 156486, 236176, 310918, 245558,
164688, 98830, 81786, 89318, 91104, 92788, 83772, 81572, 85032, 56296,
32930, 22640, 24124, 24010, 22120, 19730, 21968, 18176, 12576, 8224,
6772,
3906, 4416, 4306, 4110, 3700, 3592, 3134, 2268, 774, 674, 514, 594, 622,
672, 642, 472, 300, 170, 104, 48, 54, 78, 78, 56, 48, 36, 26, 4, 2, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'colors_dic': ['C7', 'C0', 'C3', 'C1'],
'radius_dic': [0.77, 0.77, 0.77, 0.77],
'with_h': False}
# 'bond1_radius': {'C': 76, 'N': 71, 'O': 66, 'F': 57},
# 'bond1_stdv': {'C': 2, 'N': 2, 'O': 2, 'F': 3},
# 'bond2_radius': {'C': 67, 'N': 60, 'O': 57, 'F': 59},
# 'bond3_radius': {'C': 60, 'N': 54, 'O': 53, 'F': 53}}
qm9_second_half = {
'name': 'qm9_second_half',
'atom_encoder': {'H': 0, 'C': 1, 'N': 2, 'O': 3, 'F': 4},
'atom_decoder': ['H', 'C', 'N', 'O', 'F'],
'n_nodes': {19: 6944, 12: 845, 20: 4794, 21: 4962, 27: 132, 25: 754, 18: 6695, 14: 2587, 15: 3865, 22: 1701, 17: 6461, 16: 5344, 23: 2380, 13: 1541, 24: 267, 10: 178, 7: 7, 11: 412, 8: 25, 9: 62, 29: 15, 26: 17, 4: 3, 3: 1, 6: 5, 5: 3},
'atom_types': {1: 317604, 2: 50852, 3: 70033, 0: 461622, 4: 1164},
'distances': [457374, 153688, 55626, 28284, 20414, 15010, 24412, 208012, 1105440, 285830, 748876, 1496486, 384178, 484194, 245688, 635534, 2307642, 1603762, 1231044, 1329758, 1053612, 1006742, 813504, 880670, 811616, 855082, 1066434, 931672, 709810, 711032, 608446, 660538, 692382, 619084, 544200, 490740, 450576, 380662, 328150, 303008, 263888, 218820, 207414, 175452, 145636, 135646, 116184, 94622, 80358, 68230, 58706, 51216, 44020, 38212, 30492, 24886, 21210, 17270, 13056, 11156, 9082, 7534, 6958, 6060, 4632, 3760, 2500, 2342, 1816, 1726, 1768, 1102, 974, 670, 474, 446, 286, 246, 242, 156, 176, 90, 66, 66, 38, 28, 24, 14, 10, 2, 6, 0, 2, 0, 0, 0, 0, 0, 0, 0],
'colors_dic': ['#FFFFFF99', 'C7', 'C0', 'C3', 'C1'],
'radius_dic': [0.46, 0.77, 0.77, 0.77, 0.77],
'max_n_nodes': 29,
'with_h': True}
# 'bond1_radius': {'H': 31, 'C': 76, 'N': 71, 'O': 66, 'F': 57},
# 'bond1_stdv': {'H': 5, 'C': 2, 'N': 2, 'O': 2, 'F': 3},
# 'bond2_radius': {'H': -1000, 'C': 67, 'N': 60, 'O': 57, 'F': 59},
# 'bond3_radius': {'H': -1000, 'C': 60, 'N': 54, 'O': 53, 'F': 53}}
geom_with_h = {
'name': 'geom',
'atom_encoder': {'H': 0, 'B': 1, 'C': 2, 'N': 3, 'O': 4, 'F': 5, 'Al': 6, 'Si': 7,
'P': 8, 'S': 9, 'Cl': 10, 'As': 11, 'Br': 12, 'I': 13, 'Hg': 14, 'Bi': 15},
'atomic_nb': [1, 5, 6, 7, 8, 9, 13, 14, 15, 16, 17, 33, 35, 53, 80, 83],
'atom_decoder': ['H', 'B', 'C', 'N', 'O', 'F', 'Al', 'Si', 'P', 'S', 'Cl', 'As', 'Br', 'I', 'Hg', 'Bi'],
'max_n_nodes': 181,
'n_nodes': {3: 1, 4: 3, 5: 9, 6: 2, 7: 8, 8: 23, 9: 23, 10: 50, 11: 109, 12: 168, 13: 280, 14: 402, 15: 583, 16: 597,
17: 949, 18: 1284, 19: 1862, 20: 2674, 21: 3599, 22: 6109, 23: 8693, 24: 13604, 25: 17419, 26: 25672,
27: 31647, 28: 43809, 29: 56697, 30: 70400, 31: 82655, 32: 104100, 33: 122776, 34: 140834, 35: 164888,
36: 185451, 37: 194541, 38: 218549, 39: 231232, 40: 243300, 41: 253349, 42: 268341, 43: 272081,
44: 276917, 45: 276839, 46: 274747, 47: 272126, 48: 262709, 49: 250157, 50: 244781, 51: 228898,
52: 215338, 53: 203728, 54: 191697, 55: 180518, 56: 163843, 57: 152055, 58: 136536, 59: 120393,
60: 107292, 61: 94635, 62: 83179, 63: 68384, 64: 61517, 65: 48867, 66: 37685, 67: 32859, 68: 27367,
69: 20981, 70: 18699, 71: 14791, 72: 11921, 73: 9933, 74: 9037, 75: 6538, 76: 6374, 77: 4036, 78: 4189,
79: 3842, 80: 3277, 81: 2925, 82: 1843, 83: 2060, 84: 1394, 85: 1514, 86: 1357, 87: 1346, 88: 999,
89: 300, 90: 390, 91: 510, 92: 510, 93: 240, 94: 721, 95: 360, 96: 360, 97: 390, 98: 330, 99: 540,
100: 258, 101: 210, 102: 60, 103: 180, 104: 206, 105: 60, 106: 390, 107: 180, 108: 180, 109: 150,
110: 120, 111: 360, 112: 120, 113: 210, 114: 60, 115: 30, 116: 210, 117: 270, 118: 450, 119: 240,
120: 228, 121: 120, 122: 30, 123: 420, 124: 240, 125: 210, 126: 158, 127: 180, 128: 60, 129: 30,
130: 120, 131: 30, 132: 120, 133: 60, 134: 240, 135: 169, 136: 240, 137: 30, 138: 270, 139: 180,
140: 270, 141: 150, 142: 60, 143: 60, 144: 240, 145: 180, 146: 150, 147: 150, 148: 90, 149: 90,
151: 30, 152: 60, 155: 90, 159: 30, 160: 60, 165: 30, 171: 30, 175: 30, 176: 60, 181: 30},
'atom_types':{0: 143905848, 1: 290, 2: 129988623, 3: 20266722, 4: 21669359, 5: 1481844, 6: 1,
7: 250, 8: 36290, 9: 3999872, 10: 1224394, 11: 4, 12: 298702, 13: 5377, 14: 13, 15: 34},
'colors_dic': ['#FFFFFF99',
'C2', 'C7', 'C0', 'C3', 'C1', 'C5',
'C6', 'C4', 'C8', 'C9', 'C10',
'C11', 'C12', 'C13', 'C14'],
'radius_dic': [0.3, 0.6, 0.6, 0.6, 0.6,
0.6, 0.6, 0.6, 0.6, 0.6,
0.6, 0.6, 0.6, 0.6, 0.6,
0.6],
'with_h': True}
geom_no_h = {
'name': 'geom',
'atom_encoder': {'B': 0, 'C': 1, 'N': 2, 'O': 3, 'F': 4, 'Al': 5, 'Si': 6, 'P': 7, 'S': 8, 'Cl': 9, 'As': 10,
'Br': 11, 'I': 12, 'Hg': 13, 'Bi': 14},
'atomic_nb': [5, 6, 7, 8, 9, 13, 14, 15, 16, 17, 33, 35, 53, 80, 83],
'atom_decoder': ['B', 'C', 'N', 'O', 'F', 'Al', 'Si', 'P', 'S', 'Cl', 'As', 'Br', 'I', 'Hg', 'Bi'],
'max_n_nodes': 91,
'n_nodes': {1: 3, 2: 5, 3: 8, 4: 89, 5: 166, 6: 370, 7: 613, 8: 1214, 9: 1680, 10: 3315, 11: 5115, 12: 9873,
13: 15422, 14: 28088, 15: 50643, 16: 82299, 17: 124341, 18: 178417, 19: 240446, 20: 308209, 21: 372900,
22: 429257, 23: 477423, 24: 508377, 25: 522385, 26: 522000, 27: 507882, 28: 476702, 29: 426308,
30: 375819, 31: 310124, 32: 255179, 33: 204441, 34: 149383, 35: 109343, 36: 71701, 37: 44050,
38: 31437, 39: 20242, 40: 14971, 41: 10078, 42: 8049, 43: 4476, 44: 3130, 45: 1736, 46: 2030,
47: 1110, 48: 840, 49: 750, 50: 540, 51: 810, 52: 591, 53: 453, 54: 540, 55: 720, 56: 300, 57: 360,
58: 714, 59: 390, 60: 519, 61: 210, 62: 449, 63: 210, 64: 289, 65: 589, 66: 227, 67: 180, 68: 330,
69: 330, 70: 150, 71: 60, 72: 210, 73: 60, 74: 180, 75: 120, 76: 30, 77: 150, 78: 30, 79: 60, 82: 60,
85: 60, 86: 6, 87: 60, 90: 60, 91: 30},
'atom_types': {0: 290, 1: 129988623, 2: 20266722, 3: 21669359, 4: 1481844, 5: 1, 6: 250, 7: 36290, 8: 3999872,
9: 1224394, 10: 4, 11: 298702, 12: 5377, 13: 13, 14: 34},
'colors_dic': ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'C11', 'C12', 'C13', 'C14'],
'radius_dic': [0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3],
'with_h': False}
def get_dataset_info(dataset_name, remove_h):
if dataset_name == 'qm9':
if not remove_h:
return qm9_with_h
else:
return qm9_without_h
elif dataset_name == 'geom':
if not remove_h:
return geom_with_h
else:
raise Exception('Missing config for %s without hydrogens' % dataset_name)
elif dataset_name == 'qm9_second_half':
if not remove_h:
return qm9_second_half
else:
raise Exception('Missing config for %s without hydrogens' % dataset_name)
else:
raise Exception("Wrong dataset %s" % dataset_name)
| 10,128 | 64.348387 | 671 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/equivariant_diffusion/distributions.py | import torch
from equivariant_diffusion.utils import \
center_gravity_zero_gaussian_log_likelihood_with_mask, \
standard_gaussian_log_likelihood_with_mask, \
center_gravity_zero_gaussian_log_likelihood, \
sample_center_gravity_zero_gaussian_with_mask, \
sample_center_gravity_zero_gaussian, \
sample_gaussian_with_mask
class PositionFeaturePrior(torch.nn.Module):
def __init__(self, n_dim, in_node_nf):
super().__init__()
self.n_dim = n_dim
self.in_node_nf = in_node_nf
def forward(self, z_x, z_h, node_mask=None):
assert len(z_x.size()) == 3
assert len(node_mask.size()) == 3
assert node_mask.size()[:2] == z_x.size()[:2]
assert (z_x * (1 - node_mask)).sum() < 1e-8 and \
(z_h * (1 - node_mask)).sum() < 1e-8, \
'These variables should be properly masked.'
log_pz_x = center_gravity_zero_gaussian_log_likelihood_with_mask(
z_x, node_mask
)
log_pz_h = standard_gaussian_log_likelihood_with_mask(
z_h, node_mask
)
log_pz = log_pz_x + log_pz_h
return log_pz
def sample(self, n_samples, n_nodes, node_mask):
z_x = sample_center_gravity_zero_gaussian_with_mask(
size=(n_samples, n_nodes, self.n_dim), device=node_mask.device,
node_mask=node_mask)
z_h = sample_gaussian_with_mask(
size=(n_samples, n_nodes, self.in_node_nf), device=node_mask.device,
node_mask=node_mask)
return z_x, z_h
class PositionPrior(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return center_gravity_zero_gaussian_log_likelihood(x)
def sample(self, size, device):
samples = sample_center_gravity_zero_gaussian(size, device)
return samples
| 1,865 | 31.172414 | 80 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/equivariant_diffusion/utils.py | import torch
import numpy as np
class EMA():
def __init__(self, beta):
super().__init__()
self.beta = beta
def update_model_average(self, ma_model, current_model):
for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()):
old_weight, up_weight = ma_params.data, current_params.data
ma_params.data = self.update_average(old_weight, up_weight)
def update_average(self, old, new):
if old is None:
return new
return old * self.beta + (1 - self.beta) * new
def sum_except_batch(x):
return x.reshape(x.size(0), -1).sum(dim=-1)
def remove_mean(x):
mean = torch.mean(x, dim=1, keepdim=True)
x = x - mean
return x
def remove_mean_with_mask(x, node_mask):
masked_max_abs_value = (x * (1 - node_mask)).abs().sum().item()
assert masked_max_abs_value < 1e-5, f'Error {masked_max_abs_value} too high'
N = node_mask.sum(1, keepdims=True)
mean = torch.sum(x, dim=1, keepdim=True) / N
x = x - mean * node_mask
return x
def assert_mean_zero(x):
mean = torch.mean(x, dim=1, keepdim=True)
assert mean.abs().max().item() < 1e-4
def assert_mean_zero_with_mask(x, node_mask, eps=1e-10):
assert_correctly_masked(x, node_mask)
largest_value = x.abs().max().item()
error = torch.sum(x, dim=1, keepdim=True).abs().max().item()
rel_error = error / (largest_value + eps)
assert rel_error < 1e-2, f'Mean is not zero, relative_error {rel_error}'
def assert_correctly_masked(variable, node_mask):
assert (variable * (1 - node_mask)).abs().max().item() < 1e-4, \
'Variables not masked properly.'
def center_gravity_zero_gaussian_log_likelihood(x):
assert len(x.size()) == 3
B, N, D = x.size()
assert_mean_zero(x)
# r is invariant to a basis change in the relevant hyperplane.
r2 = sum_except_batch(x.pow(2))
# The relevant hyperplane is (N-1) * D dimensional.
degrees_of_freedom = (N-1) * D
# Normalizing constant and logpx are computed:
log_normalizing_constant = -0.5 * degrees_of_freedom * np.log(2*np.pi)
log_px = -0.5 * r2 + log_normalizing_constant
return log_px
def sample_center_gravity_zero_gaussian(size, device):
assert len(size) == 3
x = torch.randn(size, device=device)
# This projection only works because Gaussian is rotation invariant around
# zero and samples are independent!
x_projected = remove_mean(x)
return x_projected
def center_gravity_zero_gaussian_log_likelihood_with_mask(x, node_mask):
assert len(x.size()) == 3
B, N_embedded, D = x.size()
assert_mean_zero_with_mask(x, node_mask)
# r is invariant to a basis change in the relevant hyperplane, the masked
# out values will have zero contribution.
r2 = sum_except_batch(x.pow(2))
# The relevant hyperplane is (N-1) * D dimensional.
N = node_mask.squeeze(2).sum(1) # N has shape [B]
degrees_of_freedom = (N-1) * D
# Normalizing constant and logpx are computed:
log_normalizing_constant = -0.5 * degrees_of_freedom * np.log(2*np.pi)
log_px = -0.5 * r2 + log_normalizing_constant
return log_px
def sample_center_gravity_zero_gaussian_with_mask(size, device, node_mask):
assert len(size) == 3
x = torch.randn(size, device=device)
x_masked = x * node_mask
# This projection only works because Gaussian is rotation invariant around
# zero and samples are independent!
x_projected = remove_mean_with_mask(x_masked, node_mask)
return x_projected
def standard_gaussian_log_likelihood(x):
# Normalizing constant and logpx are computed:
log_px = sum_except_batch(-0.5 * x * x - 0.5 * np.log(2*np.pi))
return log_px
def sample_gaussian(size, device):
x = torch.randn(size, device=device)
return x
def standard_gaussian_log_likelihood_with_mask(x, node_mask):
# Normalizing constant and logpx are computed:
log_px_elementwise = -0.5 * x * x - 0.5 * np.log(2*np.pi)
log_px = sum_except_batch(log_px_elementwise * node_mask)
return log_px
def sample_gaussian_with_mask(size, device, node_mask):
x = torch.randn(size, device=device)
x_masked = x * node_mask
return x_masked
| 4,243 | 29.099291 | 96 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/equivariant_diffusion/__init__.py | 0 | 0 | 0 | py |
|
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/equivariant_diffusion/en_diffusion.py | from equivariant_diffusion import utils
import numpy as np
import math
import torch
from egnn import models
from torch.nn import functional as F
from equivariant_diffusion import utils as diffusion_utils
# Defining some useful util functions.
def expm1(x: torch.Tensor) -> torch.Tensor:
return torch.expm1(x)
def softplus(x: torch.Tensor) -> torch.Tensor:
return F.softplus(x)
def sum_except_batch(x):
return x.view(x.size(0), -1).sum(-1)
def clip_noise_schedule(alphas2, clip_value=0.001):
"""
For a noise schedule given by alpha^2, this clips alpha_t / alpha_t-1. This may help improve stability during
sampling.
"""
alphas2 = np.concatenate([np.ones(1), alphas2], axis=0)
alphas_step = (alphas2[1:] / alphas2[:-1])
alphas_step = np.clip(alphas_step, a_min=clip_value, a_max=1.)
alphas2 = np.cumprod(alphas_step, axis=0)
return alphas2
def polynomial_schedule(timesteps: int, s=1e-4, power=3.):
"""
A noise schedule based on a simple polynomial equation: 1 - x^power.
"""
steps = timesteps + 1
x = np.linspace(0, steps, steps)
alphas2 = (1 - np.power(x / steps, power))**2
alphas2 = clip_noise_schedule(alphas2, clip_value=0.001)
precision = 1 - 2 * s
alphas2 = precision * alphas2 + s
return alphas2
def cosine_beta_schedule(timesteps, s=0.008, raise_to_power: float = 1):
"""
cosine schedule
as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
"""
steps = timesteps + 2
x = np.linspace(0, steps, steps)
alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
betas = np.clip(betas, a_min=0, a_max=0.999)
alphas = 1. - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
if raise_to_power != 1:
alphas_cumprod = np.power(alphas_cumprod, raise_to_power)
return alphas_cumprod
def gaussian_entropy(mu, sigma):
# In case sigma needed to be broadcast (which is very likely in this code).
zeros = torch.zeros_like(mu)
return sum_except_batch(
zeros + 0.5 * torch.log(2 * np.pi * sigma**2) + 0.5
)
def gaussian_KL(q_mu, q_sigma, p_mu, p_sigma, node_mask):
"""Computes the KL distance between two normal distributions.
Args:
q_mu: Mean of distribution q.
q_sigma: Standard deviation of distribution q.
p_mu: Mean of distribution p.
p_sigma: Standard deviation of distribution p.
Returns:
The KL distance, summed over all dimensions except the batch dim.
"""
return sum_except_batch(
(
torch.log(p_sigma / q_sigma)
+ 0.5 * (q_sigma**2 + (q_mu - p_mu)**2) / (p_sigma**2)
- 0.5
) * node_mask
)
def gaussian_KL_for_dimension(q_mu, q_sigma, p_mu, p_sigma, d):
"""Computes the KL distance between two normal distributions.
Args:
q_mu: Mean of distribution q.
q_sigma: Standard deviation of distribution q.
p_mu: Mean of distribution p.
p_sigma: Standard deviation of distribution p.
Returns:
The KL distance, summed over all dimensions except the batch dim.
"""
mu_norm2 = sum_except_batch((q_mu - p_mu)**2)
assert len(q_sigma.size()) == 1
assert len(p_sigma.size()) == 1
return d * torch.log(p_sigma / q_sigma) + 0.5 * (d * q_sigma**2 + mu_norm2) / (p_sigma**2) - 0.5 * d
class PositiveLinear(torch.nn.Module):
"""Linear layer with weights forced to be positive."""
def __init__(self, in_features: int, out_features: int, bias: bool = True,
weight_init_offset: int = -2):
super(PositiveLinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = torch.nn.Parameter(
torch.empty((out_features, in_features)))
if bias:
self.bias = torch.nn.Parameter(torch.empty(out_features))
else:
self.register_parameter('bias', None)
self.weight_init_offset = weight_init_offset
self.reset_parameters()
def reset_parameters(self) -> None:
torch.nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
with torch.no_grad():
self.weight.add_(self.weight_init_offset)
if self.bias is not None:
fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
torch.nn.init.uniform_(self.bias, -bound, bound)
def forward(self, input):
positive_weight = softplus(self.weight)
return F.linear(input, positive_weight, self.bias)
class SinusoidalPosEmb(torch.nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, x):
x = x.squeeze() * 1000
assert len(x.shape) == 1
device = x.device
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
emb = x[:, None] * emb[None, :]
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
return emb
class PredefinedNoiseSchedule(torch.nn.Module):
"""
Predefined noise schedule. Essentially creates a lookup array for predefined (non-learned) noise schedules.
"""
def __init__(self, noise_schedule, timesteps, precision):
super(PredefinedNoiseSchedule, self).__init__()
self.timesteps = timesteps
if noise_schedule == 'cosine':
alphas2 = cosine_beta_schedule(timesteps)
elif 'polynomial' in noise_schedule:
splits = noise_schedule.split('_')
assert len(splits) == 2
power = float(splits[1])
alphas2 = polynomial_schedule(timesteps, s=precision, power=power)
else:
raise ValueError(noise_schedule)
print('alphas2', alphas2)
sigmas2 = 1 - alphas2
log_alphas2 = np.log(alphas2)
log_sigmas2 = np.log(sigmas2)
log_alphas2_to_sigmas2 = log_alphas2 - log_sigmas2
print('gamma', -log_alphas2_to_sigmas2)
self.gamma = torch.nn.Parameter(
torch.from_numpy(-log_alphas2_to_sigmas2).float(),
requires_grad=False)
def forward(self, t):
t_int = torch.round(t * self.timesteps).long()
return self.gamma[t_int]
class GammaNetwork(torch.nn.Module):
"""The gamma network models a monotonic increasing function. Construction as in the VDM paper."""
def __init__(self):
super().__init__()
self.l1 = PositiveLinear(1, 1)
self.l2 = PositiveLinear(1, 1024)
self.l3 = PositiveLinear(1024, 1)
self.gamma_0 = torch.nn.Parameter(torch.tensor([-5.]))
self.gamma_1 = torch.nn.Parameter(torch.tensor([10.]))
self.show_schedule()
def show_schedule(self, num_steps=50):
t = torch.linspace(0, 1, num_steps).view(num_steps, 1)
gamma = self.forward(t)
print('Gamma schedule:')
print(gamma.detach().cpu().numpy().reshape(num_steps))
def gamma_tilde(self, t):
l1_t = self.l1(t)
return l1_t + self.l3(torch.sigmoid(self.l2(l1_t)))
def forward(self, t):
zeros, ones = torch.zeros_like(t), torch.ones_like(t)
# Not super efficient.
gamma_tilde_0 = self.gamma_tilde(zeros)
gamma_tilde_1 = self.gamma_tilde(ones)
gamma_tilde_t = self.gamma_tilde(t)
# Normalize to [0, 1]
normalized_gamma = (gamma_tilde_t - gamma_tilde_0) / (
gamma_tilde_1 - gamma_tilde_0)
# Rescale to [gamma_0, gamma_1]
gamma = self.gamma_0 + (self.gamma_1 - self.gamma_0) * normalized_gamma
return gamma
def cdf_standard_gaussian(x):
return 0.5 * (1. + torch.erf(x / math.sqrt(2)))
class EnVariationalDiffusion(torch.nn.Module):
"""
The E(n) Diffusion Module.
"""
def __init__(
self,
dynamics: models.EGNN_dynamics_QM9, in_node_nf: int, n_dims: int,
timesteps: int = 1000, parametrization='eps', noise_schedule='learned',
noise_precision=1e-4, loss_type='vlb', norm_values=(1., 1., 1.),
norm_biases=(None, 0., 0.), include_charges=True):
super().__init__()
assert loss_type in {'vlb', 'l2'}
self.loss_type = loss_type
self.include_charges = include_charges
if noise_schedule == 'learned':
assert loss_type == 'vlb', 'A noise schedule can only be learned' \
' with a vlb objective.'
# Only supported parametrization.
assert parametrization == 'eps'
if noise_schedule == 'learned':
self.gamma = GammaNetwork()
else:
self.gamma = PredefinedNoiseSchedule(noise_schedule, timesteps=timesteps,
precision=noise_precision)
# The network that will predict the denoising.
self.dynamics = dynamics
self.in_node_nf = in_node_nf
self.n_dims = n_dims
self.num_classes = self.in_node_nf - self.include_charges
self.T = timesteps
self.parametrization = parametrization
self.norm_values = norm_values
self.norm_biases = norm_biases
self.register_buffer('buffer', torch.zeros(1))
if noise_schedule != 'learned':
self.check_issues_norm_values()
def check_issues_norm_values(self, num_stdevs=8):
zeros = torch.zeros((1, 1))
gamma_0 = self.gamma(zeros)
sigma_0 = self.sigma(gamma_0, target_tensor=zeros).item()
# Checked if 1 / norm_value is still larger than 10 * standard
# deviation.
max_norm_value = max(self.norm_values[1], self.norm_values[2])
if sigma_0 * num_stdevs > 1. / max_norm_value:
raise ValueError(
f'Value for normalization value {max_norm_value} probably too '
f'large with sigma_0 {sigma_0:.5f} and '
f'1 / norm_value = {1. / max_norm_value}')
def phi(self, x, t, node_mask, edge_mask, context):
net_out = self.dynamics._forward(t, x, node_mask, edge_mask, context)
return net_out
def inflate_batch_array(self, array, target):
"""
Inflates the batch array (array) with only a single axis (i.e. shape = (batch_size,), or possibly more empty
axes (i.e. shape (batch_size, 1, ..., 1)) to match the target shape.
"""
target_shape = (array.size(0),) + (1,) * (len(target.size()) - 1)
return array.view(target_shape)
def sigma(self, gamma, target_tensor):
"""Computes sigma given gamma."""
return self.inflate_batch_array(torch.sqrt(torch.sigmoid(gamma)), target_tensor)
def alpha(self, gamma, target_tensor):
"""Computes alpha given gamma."""
return self.inflate_batch_array(torch.sqrt(torch.sigmoid(-gamma)), target_tensor)
def SNR(self, gamma):
"""Computes signal to noise ratio (alpha^2/sigma^2) given gamma."""
return torch.exp(-gamma)
def subspace_dimensionality(self, node_mask):
"""Compute the dimensionality on translation-invariant linear subspace where distributions on x are defined."""
number_of_nodes = torch.sum(node_mask.squeeze(2), dim=1)
return (number_of_nodes - 1) * self.n_dims
def normalize(self, x, h, node_mask):
x = x / self.norm_values[0]
delta_log_px = -self.subspace_dimensionality(node_mask) * np.log(self.norm_values[0])
# Casting to float in case h still has long or int type.
h_cat = (h['categorical'].float() - self.norm_biases[1]) / self.norm_values[1] * node_mask
h_int = (h['integer'].float() - self.norm_biases[2]) / self.norm_values[2]
if self.include_charges:
h_int = h_int * node_mask
# Create new h dictionary.
h = {'categorical': h_cat, 'integer': h_int}
return x, h, delta_log_px
def unnormalize(self, x, h_cat, h_int, node_mask):
x = x * self.norm_values[0]
h_cat = h_cat * self.norm_values[1] + self.norm_biases[1]
h_cat = h_cat * node_mask
h_int = h_int * self.norm_values[2] + self.norm_biases[2]
if self.include_charges:
h_int = h_int * node_mask
return x, h_cat, h_int
def unnormalize_z(self, z, node_mask):
# Parse from z
x, h_cat = z[:, :, 0:self.n_dims], z[:, :, self.n_dims:self.n_dims+self.num_classes]
h_int = z[:, :, self.n_dims+self.num_classes:self.n_dims+self.num_classes+1]
assert h_int.size(2) == self.include_charges
# Unnormalize
x, h_cat, h_int = self.unnormalize(x, h_cat, h_int, node_mask)
output = torch.cat([x, h_cat, h_int], dim=2)
return output
def sigma_and_alpha_t_given_s(self, gamma_t: torch.Tensor, gamma_s: torch.Tensor, target_tensor: torch.Tensor):
"""
Computes sigma t given s, using gamma_t and gamma_s. Used during sampling.
These are defined as:
alpha t given s = alpha t / alpha s,
sigma t given s = sqrt(1 - (alpha t given s) ^2 ).
"""
sigma2_t_given_s = self.inflate_batch_array(
-expm1(softplus(gamma_s) - softplus(gamma_t)), target_tensor
)
# alpha_t_given_s = alpha_t / alpha_s
log_alpha2_t = F.logsigmoid(-gamma_t)
log_alpha2_s = F.logsigmoid(-gamma_s)
log_alpha2_t_given_s = log_alpha2_t - log_alpha2_s
alpha_t_given_s = torch.exp(0.5 * log_alpha2_t_given_s)
alpha_t_given_s = self.inflate_batch_array(
alpha_t_given_s, target_tensor)
sigma_t_given_s = torch.sqrt(sigma2_t_given_s)
return sigma2_t_given_s, sigma_t_given_s, alpha_t_given_s
def kl_prior(self, xh, node_mask):
"""Computes the KL between q(z1 | x) and the prior p(z1) = Normal(0, 1).
This is essentially a lot of work for something that is in practice negligible in the loss. However, you
compute it so that you see it when you've made a mistake in your noise schedule.
"""
# Compute the last alpha value, alpha_T.
ones = torch.ones((xh.size(0), 1), device=xh.device)
gamma_T = self.gamma(ones)
alpha_T = self.alpha(gamma_T, xh)
# Compute means.
mu_T = alpha_T * xh
mu_T_x, mu_T_h = mu_T[:, :, :self.n_dims], mu_T[:, :, self.n_dims:]
# Compute standard deviations (only batch axis for x-part, inflated for h-part).
sigma_T_x = self.sigma(gamma_T, mu_T_x).squeeze() # Remove inflate, only keep batch dimension for x-part.
sigma_T_h = self.sigma(gamma_T, mu_T_h)
# Compute KL for h-part.
zeros, ones = torch.zeros_like(mu_T_h), torch.ones_like(sigma_T_h)
kl_distance_h = gaussian_KL(mu_T_h, sigma_T_h, zeros, ones, node_mask)
# Compute KL for x-part.
zeros, ones = torch.zeros_like(mu_T_x), torch.ones_like(sigma_T_x)
subspace_d = self.subspace_dimensionality(node_mask)
kl_distance_x = gaussian_KL_for_dimension(mu_T_x, sigma_T_x, zeros, ones, d=subspace_d)
return kl_distance_x + kl_distance_h
def compute_x_pred(self, net_out, zt, gamma_t):
"""Commputes x_pred, i.e. the most likely prediction of x."""
if self.parametrization == 'x':
x_pred = net_out
elif self.parametrization == 'eps':
sigma_t = self.sigma(gamma_t, target_tensor=net_out)
alpha_t = self.alpha(gamma_t, target_tensor=net_out)
eps_t = net_out
x_pred = 1. / alpha_t * (zt - sigma_t * eps_t)
else:
raise ValueError(self.parametrization)
return x_pred
def compute_error(self, net_out, gamma_t, eps):
"""Computes error, i.e. the most likely prediction of x."""
eps_t = net_out
if self.training and self.loss_type == 'l2':
denom = (self.n_dims + self.in_node_nf) * eps_t.shape[1]
error = sum_except_batch((eps - eps_t) ** 2) / denom
else:
error = sum_except_batch((eps - eps_t) ** 2)
return error
def log_constants_p_x_given_z0(self, x, node_mask):
"""Computes p(x|z0)."""
batch_size = x.size(0)
n_nodes = node_mask.squeeze(2).sum(1) # N has shape [B]
assert n_nodes.size() == (batch_size,)
degrees_of_freedom_x = (n_nodes - 1) * self.n_dims
zeros = torch.zeros((x.size(0), 1), device=x.device)
gamma_0 = self.gamma(zeros)
# Recall that sigma_x = sqrt(sigma_0^2 / alpha_0^2) = SNR(-0.5 gamma_0).
log_sigma_x = 0.5 * gamma_0.view(batch_size)
return degrees_of_freedom_x * (- log_sigma_x - 0.5 * np.log(2 * np.pi))
def sample_p_xh_given_z0(self, z0, node_mask, edge_mask, context, fix_noise=False):
"""Samples x ~ p(x|z0)."""
zeros = torch.zeros(size=(z0.size(0), 1), device=z0.device)
gamma_0 = self.gamma(zeros)
# Computes sqrt(sigma_0^2 / alpha_0^2)
sigma_x = self.SNR(-0.5 * gamma_0).unsqueeze(1)
net_out = self.phi(z0, zeros, node_mask, edge_mask, context)
# Compute mu for p(zs | zt).
mu_x = self.compute_x_pred(net_out, z0, gamma_0)
xh = self.sample_normal(mu=mu_x, sigma=sigma_x, node_mask=node_mask, fix_noise=fix_noise)
x = xh[:, :, :self.n_dims]
h_int = z0[:, :, -1:] if self.include_charges else torch.zeros(0).to(z0.device)
x, h_cat, h_int = self.unnormalize(x, z0[:, :, self.n_dims:-1], h_int, node_mask)
h_cat = F.one_hot(torch.argmax(h_cat, dim=2), self.num_classes) * node_mask
h_int = torch.round(h_int).long() * node_mask
h = {'integer': h_int, 'categorical': h_cat}
return x, h
def sample_normal(self, mu, sigma, node_mask, fix_noise=False):
"""Samples from a Normal distribution."""
bs = 1 if fix_noise else mu.size(0)
eps = self.sample_combined_position_feature_noise(bs, mu.size(1), node_mask)
return mu + sigma * eps
def log_pxh_given_z0_without_constants(
self, x, h, z_t, gamma_0, eps, net_out, node_mask, epsilon=1e-10):
# Discrete properties are predicted directly from z_t.
z_h_cat = z_t[:, :, self.n_dims:-1] if self.include_charges else z_t[:, :, self.n_dims:]
z_h_int = z_t[:, :, -1:] if self.include_charges else torch.zeros(0).to(z_t.device)
# Take only part over x.
eps_x = eps[:, :, :self.n_dims]
net_x = net_out[:, :, :self.n_dims]
# Compute sigma_0 and rescale to the integer scale of the data.
sigma_0 = self.sigma(gamma_0, target_tensor=z_t)
sigma_0_cat = sigma_0 * self.norm_values[1]
sigma_0_int = sigma_0 * self.norm_values[2]
# Computes the error for the distribution N(x | 1 / alpha_0 z_0 + sigma_0/alpha_0 eps_0, sigma_0 / alpha_0),
# the weighting in the epsilon parametrization is exactly '1'.
log_p_x_given_z_without_constants = -0.5 * self.compute_error(net_x, gamma_0, eps_x)
# Compute delta indicator masks.
h_integer = torch.round(h['integer'] * self.norm_values[2] + self.norm_biases[2]).long()
onehot = h['categorical'] * self.norm_values[1] + self.norm_biases[1]
estimated_h_integer = z_h_int * self.norm_values[2] + self.norm_biases[2]
estimated_h_cat = z_h_cat * self.norm_values[1] + self.norm_biases[1]
assert h_integer.size() == estimated_h_integer.size()
h_integer_centered = h_integer - estimated_h_integer
# Compute integral from -0.5 to 0.5 of the normal distribution
# N(mean=h_integer_centered, stdev=sigma_0_int)
log_ph_integer = torch.log(
cdf_standard_gaussian((h_integer_centered + 0.5) / sigma_0_int)
- cdf_standard_gaussian((h_integer_centered - 0.5) / sigma_0_int)
+ epsilon)
log_ph_integer = sum_except_batch(log_ph_integer * node_mask)
# Centered h_cat around 1, since onehot encoded.
centered_h_cat = estimated_h_cat - 1
# Compute integrals from 0.5 to 1.5 of the normal distribution
# N(mean=z_h_cat, stdev=sigma_0_cat)
log_ph_cat_proportional = torch.log(
cdf_standard_gaussian((centered_h_cat + 0.5) / sigma_0_cat)
- cdf_standard_gaussian((centered_h_cat - 0.5) / sigma_0_cat)
+ epsilon)
# Normalize the distribution over the categories.
log_Z = torch.logsumexp(log_ph_cat_proportional, dim=2, keepdim=True)
log_probabilities = log_ph_cat_proportional - log_Z
# Select the log_prob of the current category usign the onehot
# representation.
log_ph_cat = sum_except_batch(log_probabilities * onehot * node_mask)
# Combine categorical and integer log-probabilities.
log_p_h_given_z = log_ph_integer + log_ph_cat
# Combine log probabilities for x and h.
log_p_xh_given_z = log_p_x_given_z_without_constants + log_p_h_given_z
return log_p_xh_given_z
def compute_loss(self, x, h, node_mask, edge_mask, context, t0_always):
"""Computes an estimator for the variational lower bound, or the simple loss (MSE)."""
# This part is about whether to include loss term 0 always.
if t0_always:
# loss_term_0 will be computed separately.
# estimator = loss_0 + loss_t, where t ~ U({1, ..., T})
lowest_t = 1
else:
# estimator = loss_t, where t ~ U({0, ..., T})
lowest_t = 0
# Sample a timestep t.
t_int = torch.randint(
lowest_t, self.T + 1, size=(x.size(0), 1), device=x.device).float()
s_int = t_int - 1
t_is_zero = (t_int == 0).float() # Important to compute log p(x | z0).
# Normalize t to [0, 1]. Note that the negative
# step of s will never be used, since then p(x | z0) is computed.
s = s_int / self.T
t = t_int / self.T
# Compute gamma_s and gamma_t via the network.
gamma_s = self.inflate_batch_array(self.gamma(s), x)
gamma_t = self.inflate_batch_array(self.gamma(t), x)
# Compute alpha_t and sigma_t from gamma.
alpha_t = self.alpha(gamma_t, x)
sigma_t = self.sigma(gamma_t, x)
# Sample zt ~ Normal(alpha_t x, sigma_t)
eps = self.sample_combined_position_feature_noise(
n_samples=x.size(0), n_nodes=x.size(1), node_mask=node_mask)
# Concatenate x, h[integer] and h[categorical].
xh = torch.cat([x, h['categorical'], h['integer']], dim=2)
# Sample z_t given x, h for timestep t, from q(z_t | x, h)
z_t = alpha_t * xh + sigma_t * eps
diffusion_utils.assert_mean_zero_with_mask(z_t[:, :, :self.n_dims], node_mask)
# Neural net prediction.
net_out = self.phi(z_t, t, node_mask, edge_mask, context)
# Compute the error.
error = self.compute_error(net_out, gamma_t, eps)
if self.training and self.loss_type == 'l2':
SNR_weight = torch.ones_like(error)
else:
# Compute weighting with SNR: (SNR(s-t) - 1) for epsilon parametrization.
SNR_weight = (self.SNR(gamma_s - gamma_t) - 1).squeeze(1).squeeze(1)
assert error.size() == SNR_weight.size()
loss_t_larger_than_zero = 0.5 * SNR_weight * error
# The _constants_ depending on sigma_0 from the
# cross entropy term E_q(z0 | x) [log p(x | z0)].
neg_log_constants = -self.log_constants_p_x_given_z0(x, node_mask)
# Reset constants during training with l2 loss.
if self.training and self.loss_type == 'l2':
neg_log_constants = torch.zeros_like(neg_log_constants)
# The KL between q(z1 | x) and p(z1) = Normal(0, 1). Should be close to zero.
kl_prior = self.kl_prior(xh, node_mask)
# Combining the terms
if t0_always:
loss_t = loss_t_larger_than_zero
num_terms = self.T # Since t=0 is not included here.
estimator_loss_terms = num_terms * loss_t
# Compute noise values for t = 0.
t_zeros = torch.zeros_like(s)
gamma_0 = self.inflate_batch_array(self.gamma(t_zeros), x)
alpha_0 = self.alpha(gamma_0, x)
sigma_0 = self.sigma(gamma_0, x)
# Sample z_0 given x, h for timestep t, from q(z_t | x, h)
eps_0 = self.sample_combined_position_feature_noise(
n_samples=x.size(0), n_nodes=x.size(1), node_mask=node_mask)
z_0 = alpha_0 * xh + sigma_0 * eps_0
net_out = self.phi(z_0, t_zeros, node_mask, edge_mask, context)
loss_term_0 = -self.log_pxh_given_z0_without_constants(
x, h, z_0, gamma_0, eps_0, net_out, node_mask)
assert kl_prior.size() == estimator_loss_terms.size()
assert kl_prior.size() == neg_log_constants.size()
assert kl_prior.size() == loss_term_0.size()
loss = kl_prior + estimator_loss_terms + neg_log_constants + loss_term_0
else:
# Computes the L_0 term (even if gamma_t is not actually gamma_0)
# and this will later be selected via masking.
loss_term_0 = -self.log_pxh_given_z0_without_constants(
x, h, z_t, gamma_t, eps, net_out, node_mask)
t_is_not_zero = 1 - t_is_zero
loss_t = loss_term_0 * t_is_zero.squeeze() + t_is_not_zero.squeeze() * loss_t_larger_than_zero
# Only upweigh estimator if using the vlb objective.
if self.training and self.loss_type == 'l2':
estimator_loss_terms = loss_t
else:
num_terms = self.T + 1 # Includes t = 0.
estimator_loss_terms = num_terms * loss_t
assert kl_prior.size() == estimator_loss_terms.size()
assert kl_prior.size() == neg_log_constants.size()
loss = kl_prior + estimator_loss_terms + neg_log_constants
assert len(loss.shape) == 1, f'{loss.shape} has more than only batch dim.'
return loss, {'t': t_int.squeeze(), 'loss_t': loss.squeeze(),
'error': error.squeeze()}
def forward(self, x, h, node_mask=None, edge_mask=None, context=None):
"""
Computes the loss (type l2 or NLL) if training. And if eval then always computes NLL.
"""
# Normalize data, take into account volume change in x.
x, h, delta_log_px = self.normalize(x, h, node_mask)
# Reset delta_log_px if not vlb objective.
if self.training and self.loss_type == 'l2':
delta_log_px = torch.zeros_like(delta_log_px)
if self.training:
# Only 1 forward pass when t0_always is False.
loss, loss_dict = self.compute_loss(x, h, node_mask, edge_mask, context, t0_always=False)
else:
# Less variance in the estimator, costs two forward passes.
loss, loss_dict = self.compute_loss(x, h, node_mask, edge_mask, context, t0_always=True)
neg_log_pxh = loss
# Correct for normalization on x.
assert neg_log_pxh.size() == delta_log_px.size()
neg_log_pxh = neg_log_pxh - delta_log_px
return neg_log_pxh
def sample_p_zs_given_zt(self, s, t, zt, node_mask, edge_mask, context, fix_noise=False):
"""Samples from zs ~ p(zs | zt). Only used during sampling."""
gamma_s = self.gamma(s)
gamma_t = self.gamma(t)
sigma2_t_given_s, sigma_t_given_s, alpha_t_given_s = \
self.sigma_and_alpha_t_given_s(gamma_t, gamma_s, zt)
sigma_s = self.sigma(gamma_s, target_tensor=zt)
sigma_t = self.sigma(gamma_t, target_tensor=zt)
# Neural net prediction.
eps_t = self.phi(zt, t, node_mask, edge_mask, context)
# Compute mu for p(zs | zt).
""" These lines have been commented out!!!!!!!!!"""
#This may break everything
diffusion_utils.assert_mean_zero_with_mask(zt[:, :, :self.n_dims], node_mask)
diffusion_utils.assert_mean_zero_with_mask(eps_t[:, :, :self.n_dims], node_mask)
mu = zt / alpha_t_given_s - (sigma2_t_given_s / alpha_t_given_s / sigma_t) * eps_t
# Compute sigma for p(zs | zt).
sigma = sigma_t_given_s * sigma_s / sigma_t
# Sample zs given the paramters derived from zt.
zs = self.sample_normal(mu, sigma, node_mask, fix_noise)
# Project down to avoid numerical runaway of the center of gravity.
zs = torch.cat(
[diffusion_utils.remove_mean_with_mask(zs[:, :, :self.n_dims],
node_mask),
zs[:, :, self.n_dims:]], dim=2
)
return zs
def sample_combined_position_feature_noise(self, n_samples, n_nodes, node_mask):
"""
Samples mean-centered normal noise for z_x, and standard normal noise for z_h.
"""
z_x = utils.sample_center_gravity_zero_gaussian_with_mask(
size=(n_samples, n_nodes, self.n_dims), device=node_mask.device,
node_mask=node_mask)
z_h = utils.sample_gaussian_with_mask(
size=(n_samples, n_nodes, self.in_node_nf), device=node_mask.device,
node_mask=node_mask)
z = torch.cat([z_x, z_h], dim=2)
return z
@torch.no_grad()
def sample(self, n_samples, n_nodes, node_mask, edge_mask, context, fix_noise=False, silvr_rate=0.01, ref_coords=None,ref_node_mask=None,shift_centre=True,dataset_info=None):
"""
Draw samples from the generative model.
"""
#self.in_node_nf
#Additional column needs added to account for charge
#Either that, or the remaining reference coordinates have
#too many columns
if fix_noise:
# Noise is broadcasted over the batch axis, useful for visualizations.
z = self.sample_combined_position_feature_noise(1, n_nodes, node_mask)
else:
z = self.sample_combined_position_feature_noise(n_samples, n_nodes, node_mask)
#print("testing")
#print(z.size())
diffusion_utils.assert_mean_zero_with_mask(z[:, :, :self.n_dims], node_mask)
from equivariant_diffusion.utils import assert_mean_zero_with_mask, remove_mean_with_mask,\
assert_correctly_masked, sample_center_gravity_zero_gaussian_with_mask
data = np.asarray(ref_coords)
#hard coded
#I have removed self. from all other occurances
#self.atomic_number_list = torch.Tensor([5, 6, 7, 8, 9, 13, 14, 15, 16, 17, 33, 35, 53, 80, 83])[None, :]
#Due to previous hard coding this may break things
#The effect here is and additional 1 has been added to the beginning of the array/tensor
assert dataset_info
atomic_number_list = torch.Tensor(dataset_info["atomic_nb"])[None, :]
#print(atomic_number_list)
n_atom_types = atomic_number_list.size()[1]
#print(n_atom_types)
n = data.shape[0]
new_data = {}
new_data['positions'] = torch.from_numpy(data[:, -3:])
atom_types = torch.from_numpy(data[:, 0].astype(int)[:, None])
one_hot = atom_types == atomic_number_list
new_data['one_hot'] = one_hot
new_data['charges'] = torch.zeros(0,device=z.device)#, device=self.device
new_data['atom_mask'] = torch.ones(n,device=z.device)#, device=self.device
#r_node_mask = new_data['atom_mask'].unsqueeze(2)#.to(device, dtype).unsqueeze(2)
#r_edge_mask = new_data['edge_mask']#.to(device, dtype)
#r_charges = (new_data['charges'] if args.include_charges else torch.zeros(0))#.to(device, dtype)
#r_charges = torch.zeros(0)#This is hard coded as 19 atoms
#r_charges = torch.zeros((19,1)).to(device=z.device)
r_x = new_data['positions'].to(device=z.device)#.to(device, dtype)
r_node_mask = torch.unsqueeze(torch.ones(n), 1).to(device=z.device)
r_one_hot = new_data['one_hot'].to(device=z.device)#.to(device, dtype)
r_charges = torch.zeros((n,1)).to(device=z.device)
r_h = {'categorical': r_one_hot, 'integer': r_charges}
"""This should only need to be called once"""
#<start> was inside loop after sigma_t
# Concatenate x, h[integer] and h[categorical].
#Artifically increase tensor dimensions to 1,181,19
#Adding integer causes everything to break
#Don't know what do do here
#xh = torch.cat([r_x, r_h['categorical'], r_h['integer']], dim=1).to(device=z.device)#dim was 2
xh = torch.cat([r_x, r_h['categorical']], dim=1).to(device=z.device)#dim was 2
#This was previously hard coded as 19, now n_atom_types
#+3 for xyz coordinates and +1 for charge
xh = torch.cat([xh, torch.zeros(181-xh.shape[0], n_atom_types+3,device=z.device)], dim=0).to(device=z.device)
#making xh correct dimensions
xh = torch.unsqueeze(xh, 0).to(device=z.device)
#Centering reference at zero
#"Error 32.199 too high"
#xh = diffusion_utils.remove_mean_with_mask(xh, node_mask2)
#Node mask without assertion
#Make this ref_node_mask - not great
#xh_xyz_only = xh.clone()
xh_xyz_only = xh[:, :, :3]
masked_max_abs_value = (xh_xyz_only * (1 - node_mask)).abs().sum().item()#node_mask2
N = node_mask.sum(1, keepdims=True)#node_mask2
mean = torch.sum(xh_xyz_only, dim=1, keepdim=True) / N
number_of_zeroes = xh.size()[2]-3#Probably a better place to find this
zero_padding_tensor = torch.zeros(1, 1, number_of_zeroes).to(device=z.device)
mean = torch.cat([mean, zero_padding_tensor], dim=2)
total_gravity_center_shift = mean
xh = xh - mean * node_mask#node_mask2
#diffusion_utils.assert_mean_zero_with_mask(xh[:, :, :self.n_dims], node_mask2)
#Error: Not masked properly?
#<end> was inside loop after sigma_t
#This was also inside loop
# Sample zt ~ Normal(alpha_t x, sigma_t)
#self.n_dims = 19?
# Sample z_t given x, h for timestep t, from q(z_t | x, h)
ref_nodes = torch.sum(ref_node_mask)
nodes = torch.sum(node_mask)
if nodes != ref_nodes:
#outpaint_factor = ref_nodes / (nodes-ref_nodes)
outpaint_factor = nodes / (nodes-ref_nodes)
else:
outpaint_factor = 1
#print(outpaint_factor)
#print(torch.sum(node_mask)-torch.sum(ref_node_mask))
#print(torch.sum(ref_node_mask))
dummy_mask = node_mask - ref_node_mask
animation = False
animation_array = []#Animation
if animation:
import pickle
with open("/content/e3_diffusion_for_molecules/outputs/mask.txt", "wb") as writefile:
pickle.dump(node_mask, writefile)
print("Pickle File Dumped")
# Iteratively sample p(z_s | z_t) for t = 1, ..., T, with s = t - 1.
for s in reversed(range(0, self.T)):
if (s)%100==0:
pass
#print("sample loop: ", s+1)
#print(total_gravity_center_shift)
s_array = torch.full((n_samples, 1), fill_value=s, device=z.device)
t_array = s_array + 1
s_array = s_array / self.T
t_array = t_array / self.T
#ILVR variables
# Compute gamma_s and gamma_t via the network.
gamma_s = self.inflate_batch_array(self.gamma(s_array), r_x).to(device=z.device)#was s
gamma_t = self.inflate_batch_array(self.gamma(t_array), r_x).to(device=z.device)#was t
alpha_t = self.alpha(gamma_t, r_x).to(device=z.device)
sigma_t = self.sigma(gamma_t, r_x).to(device=z.device)
#Animation section
if animation:
total_gravity_center_shift = total_gravity_center_shift.type(z.dtype)
#Centre of gravity also takes into account atom type (for some reason)
#This might be a big
#Consider fixing
total_gravity_center_shift[:, :, 3:] = 0
z_in = z + total_gravity_center_shift*node_mask#node_mask2
animation_array.append(self.sample_p_xh_given_z0(z_in, node_mask, edge_mask, context, fix_noise=fix_noise))
##############
#---------Gravity Alignments--------
#---------centering z------
z_xyz_only = z[:, :, :3]
N = node_mask.sum(1, keepdims=True)#node_mask2
mean = torch.sum(z_xyz_only, dim=1, keepdim=True) / N
mean = torch.cat([mean, zero_padding_tensor], dim=2)
z = z - mean*node_mask#node_mask2
#---------centering xh------
#Method 1
#Considering dummy atoms
xh = xh*ref_node_mask + z*(ref_node_mask - node_mask)
xh_xyz_only = xh[:, :, :3]
N = node_mask.sum(1, keepdims=True)#node_mask2
mean = torch.sum(xh_xyz_only, dim=1, keepdim=True) / N
mean = torch.cat([mean, zero_padding_tensor], dim=2)
xh = xh - mean*ref_node_mask#node_mask2
#---------centering xh------
#Method 2
#as a function of z mean using "outpain factor"
#mean *= outpaint_factor
#xh = xh - mean*ref_node_mask#1.5 is good. and 40/9. 31/9
#-------Correction factor to reference--------
#When reference coordinates are translated
#Update this variable to allow product molecule to
#Be translated to binding site
total_gravity_center_shift += mean#*(outpaint_factor)#was minus
#--supressing one hot seemed to help previously--
#z_hot_only = z[:, :, 3:]
#N = node_mask.sum(1, keepdims=True)#node_mask2
#mean = torch.sum(z_hot_only, dim=1, keepdim=True) / N
#mean = torch.cat([zero_padding_tensor[:,:,:3], mean], dim=2)
#z = z - mean*node_mask
#--------Diffusion-----------
#sample reverse diffusion
#z must be centered at zero
z = self.sample_p_zs_given_zt(s_array, t_array, z, node_mask, edge_mask, context, fix_noise=fix_noise)
#----------SILVR----------
#was n_samples=1
eps = self.sample_combined_position_feature_noise(n_samples=n_samples,n_nodes=181, node_mask=node_mask).to(device=z.device)#node_mask2
z_t = alpha_t * xh + sigma_t * eps
z_t = z_t.to(torch.float32).to(device=z.device)
#SILVR equation
z = z - (z*alpha_t*ref_node_mask)*silvr_rate + (z_t*ref_node_mask)*silvr_rate#node_mask2
#Fix Atom ID
#fix_atom_id_mask = None
#z = z*(1-fix_atom_id_mask)
#-----------comments only------------
#This line is only used to determine if an explosion has occured
#Used in centering at zero
#masked_max_abs_value = (z_xyz_only * (1 - node_mask)).abs().sum().item()#node_mask2
#Error too high
"""
z_t = torch.cat(
[diffusion_utils.remove_mean_with_mask(z_t[:, :, :self.n_dims],
node_mask2),
z_t[:, :, self.n_dims:]], dim=2)
"""
#All were z_t
#Combine dummy atoms to z_t
"""
masked_max_abs_value = (z_t * (1 - node_mask)).abs().sum().item()#node_mask2
N = node_mask.sum(1, keepdims=True)#node_mask2
mean = torch.sum(z_t, dim=1, keepdim=True) / N
total_gravity_center_shift -= mean
z_t = z_t - mean * node_mask#node_mask2
"""
#Note: mean seems to consider atom identity
#and coordinates.
#Consider only modifying xyz
#Note: Cloning is likely slow
#This is still wrong. The center of mass is now taking
#16 columns as 0
#Calculate centre of mass with only first 3 columns
#z_xyz_only = z.clone()
#z_xyz_only[:, :, 3:] = 0
#print(z_xyz_only.size())
#print(z.size())
#----EDITED--------
#used to be z
#now z_xyz_only
#produced molecules seemed better when the mean
#Was subtracted accross the entire tensor
#and not just atom coordinates
#Maybe keep one hot low
#Works
#Only updating xyz
#Not as good
#z[:, :, :3] = z[:, :, :3] - mean[:, :, :3]*node_mask#node_mask2
#!!!!!! I have no idea why this line works
#After lots of trial and error I have found multiplying
#by a factor > 1 allows for singular molecules to be formed
#Only for outpainting
#This ratio could be related to levers and fulcrim
#Better molecule is produced when there is no xh correction
#However for outpainting it seems this is needed
#Consider xh correction only for dummy atoms?
#dummy_mask
#This might be lever rule
#Correction with outpaint_factor may bring fragment
#towards centre point of balance
#Hence having the effect of combining fragments together
#Error too high
"""
z = torch.cat(
[diffusion_utils.remove_mean_with_mask(z[:, :, :self.n_dims],
node_mask),
z[:, :, self.n_dims:]], dim=2)
"""
#----set xh additional atoms to that of the live z----
#additional_atom_mask = (node_mask - ref_node_mask)
#xh = xh*(1-additional_atom_mask) + z*additional_atom_mask#Who knows
#By tracking all the gravity shifts it should be
#possible to directly obtain the coordinated
#of the generated molecule in the save coordinate
#as the reference protein
if shift_centre:
#print("shifting centre")
#Only works when ref = no.mols
total_gravity_center_shift = total_gravity_center_shift.type(z.dtype)
#Centre of gravity also takes into account atom type (for some reason)
#This might be a big
#Consider fixing
total_gravity_center_shift[:, :, 3:] = 0
z = z + total_gravity_center_shift*node_mask#node_mask2
# Finally sample p(x, h | z_0).
x, h = self.sample_p_xh_given_z0(z, node_mask, edge_mask, context, fix_noise=fix_noise)
####Animation
if animation:
animation_array.append(self.sample_p_xh_given_z0(z, node_mask, edge_mask, context, fix_noise=fix_noise))
#animation_array.append(z_t*node_mask2)
#Final entry in animation array is the reference molecule - note nodemask2 is needed
#As z_t contains a dummy atom to account for centre of mass issue
import pickle
with open("/content/e3_diffusion_for_molecules/outputs/animation.txt", "wb") as writefile:
pickle.dump(animation_array, writefile)
print("Pickle File Dumped")
#######
#These lines fixed center of gravity
#commented out while experimenting
#Line has been commented out
#This may break things
#diffusion_utils.assert_mean_zero_with_mask(x, node_mask)
#I believe this centres the molecule at 0
#However we want the actual coordinates wrt protein
#and so I have delted the drifting correction
"""
max_cog = torch.sum(x, dim=1, keepdim=True).abs().max().item()
if max_cog > 5e-2:
print(f'Warning cog drift with error {max_cog:.3f}. Projecting '
f'the positions down.')
x = diffusion_utils.remove_mean_with_mask(x, node_mask)
"""
return x, h
@torch.no_grad()
def q_sample(self, x_start, t, noise=None):
"""
Diffuse the data for a given number of diffusion steps.
In other words, sample from q(x_t | x_0).
:param x_start: the initial data batch.
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
:param noise: if specified, the split-out normal noise.
:return: A noisy version of x_start.
"""
if noise is None:
noise = th.randn_like(x_start)
assert noise.shape == x_start.shape
return (
_extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
+ _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
* noise
)
@torch.no_grad()
def _extract_into_tensor(arr, timesteps, broadcast_shape):
"""
Extract values from a 1-D numpy array for a batch of indices.
:param arr: the 1-D numpy array.
:param timesteps: a tensor of indices into the array to extract.
:param broadcast_shape: a larger shape of K dimensions with the batch
dimension equal to the length of timesteps.
:return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
"""
res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
while len(res.shape) < len(broadcast_shape):
res = res[..., None]
return res.expand(broadcast_shape)
#------------------End of new code--------------------------
@torch.no_grad()
def sample_chain(self, n_samples, n_nodes, node_mask, edge_mask, context, keep_frames=None):
"""
Draw samples from the generative model, keep the intermediate states for visualization purposes.
"""
z = self.sample_combined_position_feature_noise(n_samples, n_nodes, node_mask)
diffusion_utils.assert_mean_zero_with_mask(z[:, :, :self.n_dims], node_mask)
if keep_frames is None:
keep_frames = self.T
else:
assert keep_frames <= self.T
chain = torch.zeros((keep_frames,) + z.size(), device=z.device)
# Iteratively sample p(z_s | z_t) for t = 1, ..., T, with s = t - 1.
for s in reversed(range(0, self.T)):
s_array = torch.full((n_samples, 1), fill_value=s, device=z.device)
t_array = s_array + 1
s_array = s_array / self.T
t_array = t_array / self.T
z = self.sample_p_zs_given_zt(
s_array, t_array, z, node_mask, edge_mask, context)
diffusion_utils.assert_mean_zero_with_mask(z[:, :, :self.n_dims], node_mask)
# Write to chain tensor.
write_index = (s * keep_frames) // self.T
chain[write_index] = self.unnormalize_z(z, node_mask)
# Finally sample p(x, h | z_0).
x, h = self.sample_p_xh_given_z0(z, node_mask, edge_mask, context)
diffusion_utils.assert_mean_zero_with_mask(x[:, :, :self.n_dims], node_mask)
xh = torch.cat([x, h['categorical'], h['integer']], dim=2)
chain[0] = xh # Overwrite last frame with the resulting x and h.
chain_flat = chain.view(n_samples * keep_frames, *z.size()[1:])
return chain_flat
def log_info(self):
"""
Some info logging of the model.
"""
gamma_0 = self.gamma(torch.zeros(1, device=self.buffer.device))
gamma_1 = self.gamma(torch.ones(1, device=self.buffer.device))
log_SNR_max = -gamma_0
log_SNR_min = -gamma_1
info = {
'log_SNR_max': log_SNR_max.item(),
'log_SNR_min': log_SNR_min.item()}
print(info)
return info | 48,360 | 38.510621 | 178 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/losses.py | import torch
def sum_except_batch(x):
return x.view(x.size(0), -1).sum(dim=-1)
def assert_correctly_masked(variable, node_mask):
assert (variable * (1 - node_mask)).abs().sum().item() < 1e-8
def compute_loss_and_nll(args, generative_model, nodes_dist, x, h, node_mask, edge_mask, context):
bs, n_nodes, n_dims = x.size()
if args.probabilistic_model == 'diffusion':
edge_mask = edge_mask.view(bs, n_nodes * n_nodes)
assert_correctly_masked(x, node_mask)
# Here x is a position tensor, and h is a dictionary with keys
# 'categorical' and 'integer'.
nll = generative_model(x, h, node_mask, edge_mask, context)
N = node_mask.squeeze(2).sum(1).long()
log_pN = nodes_dist.log_prob(N)
assert nll.size() == log_pN.size()
nll = nll - log_pN
# Average over batch.
nll = nll.mean(0)
reg_term = torch.tensor([0.]).to(nll.device)
mean_abs_z = 0.
else:
raise ValueError(args.probabilistic_model)
return nll, reg_term, mean_abs_z
| 1,067 | 25.04878 | 98 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/rdkit_functions.py | from rdkit import Chem
import numpy as np
from qm9.bond_analyze import get_bond_order, geom_predictor
from . import dataset
import torch
from configs.datasets_config import get_dataset_info
import pickle
import os
def compute_qm9_smiles(dataset_name, remove_h):
'''
:param dataset_name: qm9 or qm9_second_half
:return:
'''
print("\tConverting QM9 dataset to SMILES ...")
class StaticArgs:
def __init__(self, dataset, remove_h):
self.dataset = dataset
self.batch_size = 1
self.num_workers = 1
self.filter_n_atoms = None
self.datadir = 'qm9/temp'
self.remove_h = remove_h
self.include_charges = True
args_dataset = StaticArgs(dataset_name, remove_h)
dataloaders, charge_scale = dataset.retrieve_dataloaders(args_dataset)
dataset_info = get_dataset_info(args_dataset.dataset, args_dataset.remove_h)
n_types = 4 if remove_h else 5
mols_smiles = []
for i, data in enumerate(dataloaders['train']):
positions = data['positions'][0].view(-1, 3).numpy()
one_hot = data['one_hot'][0].view(-1, n_types).type(torch.float32)
atom_type = torch.argmax(one_hot, dim=1).numpy()
mol = build_molecule(torch.tensor(positions), torch.tensor(atom_type), dataset_info)
mol = mol2smiles(mol)
if mol is not None:
mols_smiles.append(mol)
if i % 1000 == 0:
print("\tConverting QM9 dataset to SMILES {0:.2%}".format(float(i)/len(dataloaders['train'])))
return mols_smiles
def retrieve_qm9_smiles(dataset_info):
dataset_name = dataset_info['name']
if dataset_info['with_h']:
pickle_name = dataset_name
else:
pickle_name = dataset_name + '_noH'
file_name = 'qm9/temp/%s_smiles.pickle' % pickle_name
try:
with open(file_name, 'rb') as f:
qm9_smiles = pickle.load(f)
return qm9_smiles
except OSError:
try:
os.makedirs('qm9/temp')
except:
pass
qm9_smiles = compute_qm9_smiles(dataset_name, remove_h=not dataset_info['with_h'])
with open(file_name, 'wb') as f:
pickle.dump(qm9_smiles, f)
return qm9_smiles
#### New implementation ####
bond_dict = [None, Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE,
Chem.rdchem.BondType.AROMATIC]
class BasicMolecularMetrics(object):
def __init__(self, dataset_info, dataset_smiles_list=None):
self.atom_decoder = dataset_info['atom_decoder']
self.dataset_smiles_list = dataset_smiles_list
self.dataset_info = dataset_info
# Retrieve dataset smiles only for qm9 currently.
if dataset_smiles_list is None and 'qm9' in dataset_info['name']:
self.dataset_smiles_list = retrieve_qm9_smiles(
self.dataset_info)
def compute_validity(self, generated):
""" generated: list of couples (positions, atom_types)"""
valid = []
for graph in generated:
mol = build_molecule(*graph, self.dataset_info)
smiles = mol2smiles(mol)
if smiles is not None:
mol_frags = Chem.rdmolops.GetMolFrags(mol, asMols=True)
largest_mol = max(mol_frags, default=mol, key=lambda m: m.GetNumAtoms())
smiles = mol2smiles(largest_mol)
valid.append(smiles)
return valid, len(valid) / len(generated)
def compute_uniqueness(self, valid):
""" valid: list of SMILES strings."""
return list(set(valid)), len(set(valid)) / len(valid)
def compute_novelty(self, unique):
num_novel = 0
novel = []
for smiles in unique:
if smiles not in self.dataset_smiles_list:
novel.append(smiles)
num_novel += 1
return novel, num_novel / len(unique)
def evaluate(self, generated):
""" generated: list of pairs (positions: n x 3, atom_types: n [int])
the positions and atom types should already be masked. """
valid, validity = self.compute_validity(generated)
print(f"Validity over {len(generated)} molecules: {validity * 100 :.2f}%")
if validity > 0:
unique, uniqueness = self.compute_uniqueness(valid)
print(f"Uniqueness over {len(valid)} valid molecules: {uniqueness * 100 :.2f}%")
if self.dataset_smiles_list is not None:
_, novelty = self.compute_novelty(unique)
print(f"Novelty over {len(unique)} unique valid molecules: {novelty * 100 :.2f}%")
else:
novelty = 0.0
else:
novelty = 0.0
uniqueness = 0.0
unique = None
return [validity, uniqueness, novelty], unique
def mol2smiles(mol):
try:
Chem.SanitizeMol(mol)
except ValueError:
return None
return Chem.MolToSmiles(mol)
def build_molecule(positions, atom_types, dataset_info):
atom_decoder = dataset_info["atom_decoder"]
X, A, E = build_xae_molecule(positions, atom_types, dataset_info)
mol = Chem.RWMol()
for atom in X:
a = Chem.Atom(atom_decoder[atom.item()])
mol.AddAtom(a)
all_bonds = torch.nonzero(A)
for bond in all_bonds:
mol.AddBond(bond[0].item(), bond[1].item(), bond_dict[E[bond[0], bond[1]].item()])
return mol
def build_xae_molecule(positions, atom_types, dataset_info):
""" Returns a triplet (X, A, E): atom_types, adjacency matrix, edge_types
args:
positions: N x 3 (already masked to keep final number nodes)
atom_types: N
returns:
X: N (int)
A: N x N (bool) (binary adjacency matrix)
E: N x N (int) (bond type, 0 if no bond) such that A = E.bool()
"""
atom_decoder = dataset_info['atom_decoder']
n = positions.shape[0]
X = atom_types
A = torch.zeros((n, n), dtype=torch.bool)
E = torch.zeros((n, n), dtype=torch.int)
pos = positions.unsqueeze(0)
dists = torch.cdist(pos, pos, p=2).squeeze(0)
for i in range(n):
for j in range(i):
pair = sorted([atom_types[i], atom_types[j]])
if dataset_info['name'] == 'qm9' or dataset_info['name'] == 'qm9_second_half' or dataset_info['name'] == 'qm9_first_half':
order = get_bond_order(atom_decoder[pair[0]], atom_decoder[pair[1]], dists[i, j])
elif dataset_info['name'] == 'geom':
order = geom_predictor((atom_decoder[pair[0]], atom_decoder[pair[1]]), dists[i, j], limit_bonds_to_one=True)
# TODO: a batched version of get_bond_order to avoid the for loop
if order > 0:
# Warning: the graph should be DIRECTED
A[i, j] = 1
E[i, j] = order
return X, A, E
if __name__ == '__main__':
smiles_mol = 'C1CCC1'
print("Smiles mol %s" % smiles_mol)
chem_mol = Chem.MolFromSmiles(smiles_mol)
block_mol = Chem.MolToMolBlock(chem_mol)
print("Block mol:")
print(block_mol)
| 7,154 | 35.136364 | 134 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/utils.py | import torch
def compute_mean_mad(dataloaders, properties, dataset_name):
if dataset_name == 'qm9':
return compute_mean_mad_from_dataloader(dataloaders['train'], properties)
elif dataset_name == 'qm9_second_half' or dataset_name == 'qm9_second_half':
return compute_mean_mad_from_dataloader(dataloaders['valid'], properties)
else:
raise Exception('Wrong dataset name')
def compute_mean_mad_from_dataloader(dataloader, properties):
property_norms = {}
for property_key in properties:
values = dataloader.dataset.data[property_key]
mean = torch.mean(values)
ma = torch.abs(values - mean)
mad = torch.mean(ma)
property_norms[property_key] = {}
property_norms[property_key]['mean'] = mean
property_norms[property_key]['mad'] = mad
return property_norms
edges_dic = {}
def get_adj_matrix(n_nodes, batch_size, device):
if n_nodes in edges_dic:
edges_dic_b = edges_dic[n_nodes]
if batch_size in edges_dic_b:
return edges_dic_b[batch_size]
else:
# get edges for a single sample
rows, cols = [], []
for batch_idx in range(batch_size):
for i in range(n_nodes):
for j in range(n_nodes):
rows.append(i + batch_idx*n_nodes)
cols.append(j + batch_idx*n_nodes)
else:
edges_dic[n_nodes] = {}
return get_adj_matrix(n_nodes, batch_size, device)
edges = [torch.LongTensor(rows).to(device), torch.LongTensor(cols).to(device)]
return edges
def preprocess_input(one_hot, charges, charge_power, charge_scale, device):
charge_tensor = (charges.unsqueeze(-1) / charge_scale).pow(
torch.arange(charge_power + 1., device=device, dtype=torch.float32))
charge_tensor = charge_tensor.view(charges.shape + (1, charge_power + 1))
atom_scalars = (one_hot.unsqueeze(-1) * charge_tensor).view(charges.shape[:2] + (-1,))
return atom_scalars
def prepare_context(conditioning, minibatch, property_norms):
batch_size, n_nodes, _ = minibatch['positions'].size()
node_mask = minibatch['atom_mask'].unsqueeze(2)
context_node_nf = 0
context_list = []
for key in conditioning:
properties = minibatch[key]
properties = (properties - property_norms[key]['mean']) / property_norms[key]['mad']
if len(properties.size()) == 1:
# Global feature.
assert properties.size() == (batch_size,)
reshaped = properties.view(batch_size, 1, 1).repeat(1, n_nodes, 1)
context_list.append(reshaped)
context_node_nf += 1
elif len(properties.size()) == 2 or len(properties.size()) == 3:
# Node feature.
assert properties.size()[:2] == (batch_size, n_nodes)
context_key = properties
# Inflate if necessary.
if len(properties.size()) == 2:
context_key = context_key.unsqueeze(2)
context_list.append(context_key)
context_node_nf += context_key.size(2)
else:
raise ValueError('Invalid tensor size, more than 3 axes.')
# Concatenate
context = torch.cat(context_list, dim=2)
# Mask disabled nodes!
context = context * node_mask
assert context.size(2) == context_node_nf
return context
| 3,400 | 36.373626 | 92 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/dataset.py | from torch.utils.data import DataLoader
from qm9.data.args import init_argparse
from qm9.data.collate import PreprocessQM9
from qm9.data.utils import initialize_datasets
import os
def retrieve_dataloaders(cfg):
if 'qm9' in cfg.dataset:
batch_size = cfg.batch_size
num_workers = cfg.num_workers
filter_n_atoms = cfg.filter_n_atoms
# Initialize dataloader
args = init_argparse('qm9')
# data_dir = cfg.data_root_dir
args, datasets, num_species, charge_scale = initialize_datasets(args, cfg.datadir, cfg.dataset,
subtract_thermo=args.subtract_thermo,
force_download=args.force_download,
remove_h=cfg.remove_h)
qm9_to_eV = {'U0': 27.2114, 'U': 27.2114, 'G': 27.2114, 'H': 27.2114, 'zpve': 27211.4, 'gap': 27.2114, 'homo': 27.2114,
'lumo': 27.2114}
for dataset in datasets.values():
dataset.convert_units(qm9_to_eV)
if filter_n_atoms is not None:
print("Retrieving molecules with only %d atoms" % filter_n_atoms)
datasets = filter_atoms(datasets, filter_n_atoms)
# Construct PyTorch dataloaders from datasets
preprocess = PreprocessQM9(load_charges=cfg.include_charges)
dataloaders = {split: DataLoader(dataset,
batch_size=batch_size,
shuffle=args.shuffle if (split == 'train') else False,
num_workers=num_workers,
collate_fn=preprocess.collate_fn)
for split, dataset in datasets.items()}
elif 'geom' in cfg.dataset:
import build_geom_dataset
from configs.datasets_config import get_dataset_info
data_file = './data/geom/geom_drugs_30.npy'
dataset_info = get_dataset_info(cfg.dataset, cfg.remove_h)
# Retrieve QM9 dataloaders
split_data = build_geom_dataset.load_split_data(data_file,
val_proportion=0.1,
test_proportion=0.1,
filter_size=cfg.filter_molecule_size)
transform = build_geom_dataset.GeomDrugsTransform(dataset_info,
cfg.include_charges,
cfg.device,
cfg.sequential)
dataloaders = {}
for key, data_list in zip(['train', 'val', 'test'], split_data):
dataset = build_geom_dataset.GeomDrugsDataset(data_list,
transform=transform)
shuffle = (key == 'train') and not cfg.sequential
# Sequential dataloading disabled for now.
dataloaders[key] = build_geom_dataset.GeomDrugsDataLoader(
sequential=cfg.sequential, dataset=dataset,
batch_size=cfg.batch_size,
shuffle=shuffle)
del split_data
charge_scale = None
else:
raise ValueError(f'Unknown dataset {cfg.dataset}')
return dataloaders, charge_scale
def filter_atoms(datasets, n_nodes):
for key in datasets:
dataset = datasets[key]
idxs = dataset.data['num_atoms'] == n_nodes
for key2 in dataset.data:
dataset.data[key2] = dataset.data[key2][idxs]
datasets[key].num_pts = dataset.data['one_hot'].size(0)
datasets[key].perm = None
return datasets | 3,840 | 46.419753 | 127 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/sampling.py | import numpy as np
import torch
import torch.nn.functional as F
from equivariant_diffusion.utils import assert_mean_zero_with_mask, remove_mean_with_mask,\
assert_correctly_masked
from qm9.analyze import check_stability
def rotate_chain(z):
assert z.size(0) == 1
z_h = z[:, :, 3:]
n_steps = 30
theta = 0.6 * np.pi / n_steps
Qz = torch.tensor(
[[np.cos(theta), -np.sin(theta), 0.],
[np.sin(theta), np.cos(theta), 0.],
[0., 0., 1.]]
).float()
Qx = torch.tensor(
[[1., 0., 0.],
[0., np.cos(theta), -np.sin(theta)],
[0., np.sin(theta), np.cos(theta)]]
).float()
Qy = torch.tensor(
[[np.cos(theta), 0., np.sin(theta)],
[0., 1., 0.],
[-np.sin(theta), 0., np.cos(theta)]]
).float()
Q = torch.mm(torch.mm(Qz, Qx), Qy)
Q = Q.to(z.device)
results = []
results.append(z)
for i in range(n_steps):
z_x = results[-1][:, :, :3]
# print(z_x.size(), Q.size())
new_x = torch.matmul(z_x.view(-1, 3), Q.T).view(1, -1, 3)
# print(new_x.size())
new_z = torch.cat([new_x, z_h], dim=2)
results.append(new_z)
results = torch.cat(results, dim=0)
return results
def reverse_tensor(x):
return x[torch.arange(x.size(0) - 1, -1, -1)]
def sample_chain(args, device, flow, n_tries, dataset_info, prop_dist=None):
n_samples = 1
if args.dataset == 'qm9' or args.dataset == 'qm9_second_half' or args.dataset == 'qm9_first_half':
n_nodes = 19
elif args.dataset == 'geom':
n_nodes = 44
else:
raise ValueError()
# TODO FIX: This conditioning just zeros.
if args.context_node_nf > 0:
context = prop_dist.sample(n_nodes).unsqueeze(1).unsqueeze(0)
context = context.repeat(1, n_nodes, 1).to(device)
#context = torch.zeros(n_samples, n_nodes, args.context_node_nf).to(device)
else:
context = None
node_mask = torch.ones(n_samples, n_nodes, 1).to(device)
edge_mask = (1 - torch.eye(n_nodes)).unsqueeze(0)
edge_mask = edge_mask.repeat(n_samples, 1, 1).view(-1, 1).to(device)
if args.probabilistic_model == 'diffusion':
one_hot, charges, x = None, None, None
for i in range(n_tries):
chain = flow.sample_chain(n_samples, n_nodes, node_mask, edge_mask, context, keep_frames=100)
chain = reverse_tensor(chain)
# Repeat last frame to see final sample better.
chain = torch.cat([chain, chain[-1:].repeat(10, 1, 1)], dim=0)
x = chain[-1:, :, 0:3]
one_hot = chain[-1:, :, 3:-1]
one_hot = torch.argmax(one_hot, dim=2)
atom_type = one_hot.squeeze(0).cpu().detach().numpy()
x_squeeze = x.squeeze(0).cpu().detach().numpy()
mol_stable = check_stability(x_squeeze, atom_type, dataset_info)[0]
# Prepare entire chain.
x = chain[:, :, 0:3]
one_hot = chain[:, :, 3:-1]
one_hot = F.one_hot(torch.argmax(one_hot, dim=2), num_classes=len(dataset_info['atom_decoder']))
charges = torch.round(chain[:, :, -1:]).long()
if mol_stable:
print('Found stable molecule to visualize :)')
break
elif i == n_tries - 1:
print('Did not find stable molecule, showing last sample.')
else:
raise ValueError
return one_hot, charges, x
def sample(args, device, generative_model, dataset_info,
prop_dist=None, nodesxsample=torch.tensor([10]), context=None,
fix_noise=False):
max_n_nodes = dataset_info['max_n_nodes'] # this is the maximum node_size in QM9
assert int(torch.max(nodesxsample)) <= max_n_nodes
batch_size = len(nodesxsample)
node_mask = torch.zeros(batch_size, max_n_nodes)
for i in range(batch_size):
node_mask[i, 0:nodesxsample[i]] = 1
# Compute edge_mask
edge_mask = node_mask.unsqueeze(1) * node_mask.unsqueeze(2)
diag_mask = ~torch.eye(edge_mask.size(1), dtype=torch.bool).unsqueeze(0)
edge_mask *= diag_mask
edge_mask = edge_mask.view(batch_size * max_n_nodes * max_n_nodes, 1).to(device)
node_mask = node_mask.unsqueeze(2).to(device)
# TODO FIX: This conditioning just zeros.
if args.context_node_nf > 0:
if context is None:
context = prop_dist.sample_batch(nodesxsample)
context = context.unsqueeze(1).repeat(1, max_n_nodes, 1).to(device) * node_mask
else:
context = None
if args.probabilistic_model == 'diffusion':
x, h = generative_model.sample(batch_size, max_n_nodes, node_mask, edge_mask, context, fix_noise=fix_noise)
assert_correctly_masked(x, node_mask)
assert_mean_zero_with_mask(x, node_mask)
one_hot = h['categorical']
charges = h['integer']
assert_correctly_masked(one_hot.float(), node_mask)
if args.include_charges:
assert_correctly_masked(charges.float(), node_mask)
else:
raise ValueError(args.probabilistic_model)
return one_hot, charges, x, node_mask
def sample_sweep_conditional(args, device, generative_model, dataset_info, prop_dist, n_nodes=19, n_frames=100):
nodesxsample = torch.tensor([n_nodes] * n_frames)
context = []
for key in prop_dist.distributions:
min_val, max_val = prop_dist.distributions[key][n_nodes]['params']
mean, mad = prop_dist.normalizer[key]['mean'], prop_dist.normalizer[key]['mad']
min_val = (min_val - mean) / (mad)
max_val = (max_val - mean) / (mad)
context_row = torch.tensor(np.linspace(min_val, max_val, n_frames)).unsqueeze(1)
context.append(context_row)
context = torch.cat(context, dim=1).float().to(device)
one_hot, charges, x, node_mask = sample(args, device, generative_model, dataset_info, prop_dist, nodesxsample=nodesxsample, context=context, fix_noise=True)
return one_hot, charges, x, node_mask | 6,002 | 34.105263 | 160 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/visualizer.py | import torch
import numpy as np
import os
import glob
import random
import matplotlib
import imageio
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from qm9 import bond_analyze
##############
### Files ####
###########-->
def save_xyz_file(path, one_hot, charges, positions, dataset_info, id_from=0, name='molecule', node_mask=None):
try:
os.makedirs(path)
except OSError:
pass
if node_mask is not None:
atomsxmol = torch.sum(node_mask, dim=1)
else:
atomsxmol = [one_hot.size(1)] * one_hot.size(0)
for batch_i in range(one_hot.size(0)):
f = open(path + name + '_' + "%03d.txt" % (batch_i + id_from), "w")
f.write("%d\n\n" % atomsxmol[batch_i])
atoms = torch.argmax(one_hot[batch_i], dim=1)
n_atoms = int(atomsxmol[batch_i])
for atom_i in range(n_atoms):
atom = atoms[atom_i]
atom = dataset_info['atom_decoder'][atom]
f.write("%s %.9f %.9f %.9f\n" % (atom, positions[batch_i, atom_i, 0], positions[batch_i, atom_i, 1], positions[batch_i, atom_i, 2]))
f.close()
def load_molecule_xyz(file, dataset_info):
with open(file, encoding='utf8') as f:
n_atoms = int(f.readline())
one_hot = torch.zeros(n_atoms, len(dataset_info['atom_decoder']))
charges = torch.zeros(n_atoms, 1)
positions = torch.zeros(n_atoms, 3)
f.readline()
atoms = f.readlines()
for i in range(n_atoms):
atom = atoms[i].split(' ')
atom_type = atom[0]
one_hot[i, dataset_info['atom_encoder'][atom_type]] = 1
position = torch.Tensor([float(e) for e in atom[1:]])
positions[i, :] = position
return positions, one_hot, charges
def load_xyz_files(path, shuffle=True):
files = glob.glob(path + "/*.txt")
if shuffle:
random.shuffle(files)
return files
#<----########
### Files ####
##############
def draw_sphere(ax, x, y, z, size, color, alpha):
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
xs = size * np.outer(np.cos(u), np.sin(v))
ys = size * np.outer(np.sin(u), np.sin(v)) * 0.8 # Correct for matplotlib.
zs = size * np.outer(np.ones(np.size(u)), np.cos(v))
# for i in range(2):
# ax.plot_surface(x+random.randint(-5,5), y+random.randint(-5,5), z+random.randint(-5,5), rstride=4, cstride=4, color='b', linewidth=0, alpha=0.5)
ax.plot_surface(x + xs, y + ys, z + zs, rstride=2, cstride=2, color=color, linewidth=0,
alpha=alpha)
# # calculate vectors for "vertical" circle
# a = np.array([-np.sin(elev / 180 * np.pi), 0, np.cos(elev / 180 * np.pi)])
# b = np.array([0, 1, 0])
# b = b * np.cos(rot) + np.cross(a, b) * np.sin(rot) + a * np.dot(a, b) * (
# 1 - np.cos(rot))
# ax.plot(np.sin(u), np.cos(u), 0, color='k', linestyle='dashed')
# horiz_front = np.linspace(0, np.pi, 100)
# ax.plot(np.sin(horiz_front), np.cos(horiz_front), 0, color='k')
# vert_front = np.linspace(np.pi / 2, 3 * np.pi / 2, 100)
# ax.plot(a[0] * np.sin(u) + b[0] * np.cos(u), b[1] * np.cos(u),
# a[2] * np.sin(u) + b[2] * np.cos(u), color='k', linestyle='dashed')
# ax.plot(a[0] * np.sin(vert_front) + b[0] * np.cos(vert_front),
# b[1] * np.cos(vert_front),
# a[2] * np.sin(vert_front) + b[2] * np.cos(vert_front), color='k')
#
# ax.view_init(elev=elev, azim=0)
def plot_molecule(ax, positions, atom_type, alpha, spheres_3d, hex_bg_color,
dataset_info):
# draw_sphere(ax, 0, 0, 0, 1)
# draw_sphere(ax, 1, 1, 1, 1)
x = positions[:, 0]
y = positions[:, 1]
z = positions[:, 2]
# Hydrogen, Carbon, Nitrogen, Oxygen, Flourine
# ax.set_facecolor((1.0, 0.47, 0.42))
colors_dic = np.array(dataset_info['colors_dic'])
radius_dic = np.array(dataset_info['radius_dic'])
area_dic = 1500 * radius_dic ** 2
# areas_dic = sizes_dic * sizes_dic * 3.1416
areas = area_dic[atom_type]
radii = radius_dic[atom_type]
colors = colors_dic[atom_type]
if spheres_3d:
for i, j, k, s, c in zip(x, y, z, radii, colors):
draw_sphere(ax, i.item(), j.item(), k.item(), 0.7 * s, c, alpha)
else:
ax.scatter(x, y, z, s=areas, alpha=0.9 * alpha,
c=colors) # , linewidths=2, edgecolors='#FFFFFF')
for i in range(len(x)):
for j in range(i + 1, len(x)):
p1 = np.array([x[i], y[i], z[i]])
p2 = np.array([x[j], y[j], z[j]])
dist = np.sqrt(np.sum((p1 - p2) ** 2))
atom1, atom2 = dataset_info['atom_decoder'][atom_type[i]], \
dataset_info['atom_decoder'][atom_type[j]]
s = sorted((atom_type[i], atom_type[j]))
pair = (dataset_info['atom_decoder'][s[0]],
dataset_info['atom_decoder'][s[1]])
if 'qm9' in dataset_info['name']:
draw_edge_int = bond_analyze.get_bond_order(atom1, atom2, dist)
line_width = (3 - 2) * 2 * 2
elif dataset_info['name'] == 'geom':
draw_edge_int = bond_analyze.geom_predictor(pair, dist)
# Draw edge outputs 1 / -1 value, convert to True / False.
line_width = 2
else:
raise Exception('Wrong dataset_info name')
draw_edge = draw_edge_int > 0
if draw_edge:
if draw_edge_int == 4:
linewidth_factor = 1.5
else:
# linewidth_factor = draw_edge_int # Prop to number of
# edges.
linewidth_factor = 1
ax.plot([x[i], x[j]], [y[i], y[j]], [z[i], z[j]],
linewidth=line_width * linewidth_factor,
c=hex_bg_color, alpha=alpha)
def plot_data3d(positions, atom_type, dataset_info, camera_elev=0, camera_azim=0, save_path=None, spheres_3d=False,
bg='black', alpha=1.):
black = (0, 0, 0)
white = (1, 1, 1)
hex_bg_color = '#FFFFFF' if bg == 'black' else '#666666'
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_aspect('auto')
ax.view_init(elev=camera_elev, azim=camera_azim)
if bg == 'black':
ax.set_facecolor(black)
else:
ax.set_facecolor(white)
# ax.xaxis.pane.set_edgecolor('#D0D0D0')
ax.xaxis.pane.set_alpha(0)
ax.yaxis.pane.set_alpha(0)
ax.zaxis.pane.set_alpha(0)
ax._axis3don = False
if bg == 'black':
ax.w_xaxis.line.set_color("black")
else:
ax.w_xaxis.line.set_color("white")
plot_molecule(ax, positions, atom_type, alpha, spheres_3d,
hex_bg_color, dataset_info)
if 'qm9' in dataset_info['name']:
max_value = positions.abs().max().item()
# axis_lim = 3.2
axis_lim = min(40, max(max_value / 1.5 + 0.3, 3.2))
ax.set_xlim(-axis_lim, axis_lim)
ax.set_ylim(-axis_lim, axis_lim)
ax.set_zlim(-axis_lim, axis_lim)
elif dataset_info['name'] == 'geom':
max_value = positions.abs().max().item()
# axis_lim = 3.2
axis_lim = min(40, max(max_value / 1.5 + 0.3, 3.2))
ax.set_xlim(-axis_lim, axis_lim)
ax.set_ylim(-axis_lim, axis_lim)
ax.set_zlim(-axis_lim, axis_lim)
else:
raise ValueError(dataset_info['name'])
dpi = 120 if spheres_3d else 50
if save_path is not None:
plt.savefig(save_path, bbox_inches='tight', pad_inches=0.0, dpi=dpi)
if spheres_3d:
img = imageio.imread(save_path)
img_brighter = np.clip(img * 1.4, 0, 255).astype('uint8')
imageio.imsave(save_path, img_brighter)
else:
plt.show()
plt.close()
def plot_data3d_uncertainty(
all_positions, all_atom_types, dataset_info, camera_elev=0, camera_azim=0,
save_path=None, spheres_3d=False, bg='black', alpha=1.):
black = (0, 0, 0)
white = (1, 1, 1)
hex_bg_color = '#FFFFFF' if bg == 'black' else '#666666'
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_aspect('auto')
ax.view_init(elev=camera_elev, azim=camera_azim)
if bg == 'black':
ax.set_facecolor(black)
else:
ax.set_facecolor(white)
# ax.xaxis.pane.set_edgecolor('#D0D0D0')
ax.xaxis.pane.set_alpha(0)
ax.yaxis.pane.set_alpha(0)
ax.zaxis.pane.set_alpha(0)
ax._axis3don = False
if bg == 'black':
ax.w_xaxis.line.set_color("black")
else:
ax.w_xaxis.line.set_color("white")
for i in range(len(all_positions)):
positions = all_positions[i]
atom_type = all_atom_types[i]
plot_molecule(ax, positions, atom_type, alpha, spheres_3d,
hex_bg_color, dataset_info)
if 'qm9' in dataset_info['name']:
max_value = all_positions[0].abs().max().item()
# axis_lim = 3.2
axis_lim = min(40, max(max_value + 0.3, 3.2))
ax.set_xlim(-axis_lim, axis_lim)
ax.set_ylim(-axis_lim, axis_lim)
ax.set_zlim(-axis_lim, axis_lim)
elif dataset_info['name'] == 'geom':
max_value = all_positions[0].abs().max().item()
# axis_lim = 3.2
axis_lim = min(40, max(max_value / 2 + 0.3, 3.2))
ax.set_xlim(-axis_lim, axis_lim)
ax.set_ylim(-axis_lim, axis_lim)
ax.set_zlim(-axis_lim, axis_lim)
else:
raise ValueError(dataset_info['name'])
dpi = 120 if spheres_3d else 50
if save_path is not None:
plt.savefig(save_path, bbox_inches='tight', pad_inches=0.0, dpi=dpi)
if spheres_3d:
img = imageio.imread(save_path)
img_brighter = np.clip(img * 1.4, 0, 255).astype('uint8')
imageio.imsave(save_path, img_brighter)
else:
plt.show()
plt.close()
def plot_grid():
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)
fig = plt.figure(figsize=(10., 10.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(6, 6), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for ax, im in zip(grid, [im1, im2, im3, im4]):
# Iterating over the grid returns the Axes.
ax.imshow(im)
plt.show()
def visualize(path, dataset_info, max_num=25, wandb=None, spheres_3d=False):
files = load_xyz_files(path)[0:max_num]
for file in files:
positions, one_hot, charges = load_molecule_xyz(file, dataset_info)
atom_type = torch.argmax(one_hot, dim=1).numpy()
dists = torch.cdist(positions.unsqueeze(0), positions.unsqueeze(0)).squeeze(0)
dists = dists[dists > 0]
print("Average distance between atoms", dists.mean().item())
plot_data3d(positions, atom_type, dataset_info=dataset_info, save_path=file[:-4] + '.png',
spheres_3d=spheres_3d)
if wandb is not None:
path = file[:-4] + '.png'
# Log image(s)
im = plt.imread(path)
wandb.log({'molecule': [wandb.Image(im, caption=path)]})
def visualize_chain(path, dataset_info, wandb=None, spheres_3d=False,
mode="chain"):
files = load_xyz_files(path)
files = sorted(files)
save_paths = []
for i in range(len(files)):
file = files[i]
positions, one_hot, charges = load_molecule_xyz(file, dataset_info=dataset_info)
atom_type = torch.argmax(one_hot, dim=1).numpy()
fn = file[:-4] + '.png'
plot_data3d(positions, atom_type, dataset_info=dataset_info,
save_path=fn, spheres_3d=spheres_3d, alpha=1.0)
save_paths.append(fn)
imgs = [imageio.imread(fn) for fn in save_paths]
dirname = os.path.dirname(save_paths[0])
gif_path = dirname + '/output.gif'
print(f'Creating gif with {len(imgs)} images')
# Add the last frame 10 times so that the final result remains temporally.
# imgs.extend([imgs[-1]] * 10)
imageio.mimsave(gif_path, imgs, subrectangles=True)
if wandb is not None:
wandb.log({mode: [wandb.Video(gif_path, caption=gif_path)]})
def visualize_chain_uncertainty(
path, dataset_info, wandb=None, spheres_3d=False, mode="chain"):
files = load_xyz_files(path)
files = sorted(files)
save_paths = []
for i in range(len(files)):
if i + 2 == len(files):
break
file = files[i]
file2 = files[i+1]
file3 = files[i+2]
positions, one_hot, _ = load_molecule_xyz(file, dataset_info=dataset_info)
positions2, one_hot2, _ = load_molecule_xyz(
file2, dataset_info=dataset_info)
positions3, one_hot3, _ = load_molecule_xyz(
file3, dataset_info=dataset_info)
all_positions = torch.stack([positions, positions2, positions3], dim=0)
one_hot = torch.stack([one_hot, one_hot2, one_hot3], dim=0)
all_atom_type = torch.argmax(one_hot, dim=2).numpy()
fn = file[:-4] + '.png'
plot_data3d_uncertainty(
all_positions, all_atom_type, dataset_info=dataset_info,
save_path=fn, spheres_3d=spheres_3d, alpha=0.5)
save_paths.append(fn)
imgs = [imageio.imread(fn) for fn in save_paths]
dirname = os.path.dirname(save_paths[0])
gif_path = dirname + '/output.gif'
print(f'Creating gif with {len(imgs)} images')
# Add the last frame 10 times so that the final result remains temporally.
# imgs.extend([imgs[-1]] * 10)
imageio.mimsave(gif_path, imgs, subrectangles=True)
if wandb is not None:
wandb.log({mode: [wandb.Video(gif_path, caption=gif_path)]})
if __name__ == '__main__':
#plot_grid()
import qm9.dataset as dataset
from configs.datasets_config import qm9_with_h, geom_with_h
matplotlib.use('macosx')
task = "visualize_molecules"
task_dataset = 'geom'
if task_dataset == 'qm9':
dataset_info = qm9_with_h
class Args:
batch_size = 1
num_workers = 0
filter_n_atoms = None
datadir = 'qm9/temp'
dataset = 'qm9'
remove_h = False
include_charges = True
cfg = Args()
dataloaders, charge_scale = dataset.retrieve_dataloaders(cfg)
for i, data in enumerate(dataloaders['train']):
positions = data['positions'].view(-1, 3)
positions_centered = positions - positions.mean(dim=0, keepdim=True)
one_hot = data['one_hot'].view(-1, 5).type(torch.float32)
atom_type = torch.argmax(one_hot, dim=1).numpy()
plot_data3d(
positions_centered, atom_type, dataset_info=dataset_info,
spheres_3d=True)
elif task_dataset == 'geom':
files = load_xyz_files('outputs/data')
matplotlib.use('macosx')
for file in files:
x, one_hot, _ = load_molecule_xyz(file, dataset_info=geom_with_h)
positions = x.view(-1, 3)
positions_centered = positions - positions.mean(dim=0, keepdim=True)
one_hot = one_hot.view(-1, 16).type(torch.float32)
atom_type = torch.argmax(one_hot, dim=1).numpy()
mask = (x == 0).sum(1) != 3
positions_centered = positions_centered[mask]
atom_type = atom_type[mask]
plot_data3d(
positions_centered, atom_type, dataset_info=geom_with_h,
spheres_3d=False)
else:
raise ValueError(dataset)
| 15,855 | 34.002208 | 154 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/bond_analyze.py | # Bond lengths from:
# http://www.wiredchemist.com/chemistry/data/bond_energies_lengths.html
# And:
# http://chemistry-reference.com/tables/Bond%20Lengths%20and%20Enthalpies.pdf
bonds1 = {'H': {'H': 74, 'C': 109, 'N': 101, 'O': 96, 'F': 92,
'B': 119, 'Si': 148, 'P': 144, 'As': 152, 'S': 134,
'Cl': 127, 'Br': 141, 'I': 161},
'C': {'H': 109, 'C': 154, 'N': 147, 'O': 143, 'F': 135,
'Si': 185, 'P': 184, 'S': 182, 'Cl': 177, 'Br': 194,
'I': 214},
'N': {'H': 101, 'C': 147, 'N': 145, 'O': 140, 'F': 136,
'Cl': 175, 'Br': 214, 'S': 168, 'I': 222, 'P': 177},
'O': {'H': 96, 'C': 143, 'N': 140, 'O': 148, 'F': 142,
'Br': 172, 'S': 151, 'P': 163, 'Si': 163, 'Cl': 164,
'I': 194},
'F': {'H': 92, 'C': 135, 'N': 136, 'O': 142, 'F': 142,
'S': 158, 'Si': 160, 'Cl': 166, 'Br': 178, 'P': 156,
'I': 187},
'B': {'H': 119, 'Cl': 175},
'Si': {'Si': 233, 'H': 148, 'C': 185, 'O': 163, 'S': 200,
'F': 160, 'Cl': 202, 'Br': 215, 'I': 243 },
'Cl': {'Cl': 199, 'H': 127, 'C': 177, 'N': 175, 'O': 164,
'P': 203, 'S': 207, 'B': 175, 'Si': 202, 'F': 166,
'Br': 214},
'S': {'H': 134, 'C': 182, 'N': 168, 'O': 151, 'S': 204,
'F': 158, 'Cl': 207, 'Br': 225, 'Si': 200, 'P': 210,
'I': 234},
'Br': {'Br': 228, 'H': 141, 'C': 194, 'O': 172, 'N': 214,
'Si': 215, 'S': 225, 'F': 178, 'Cl': 214, 'P': 222},
'P': {'P': 221, 'H': 144, 'C': 184, 'O': 163, 'Cl': 203,
'S': 210, 'F': 156, 'N': 177, 'Br': 222},
'I': {'H': 161, 'C': 214, 'Si': 243, 'N': 222, 'O': 194,
'S': 234, 'F': 187, 'I': 266},
'As': {'H': 152}
}
bonds2 = {'C': {'C': 134, 'N': 129, 'O': 120, 'S': 160},
'N': {'C': 129, 'N': 125, 'O': 121},
'O': {'C': 120, 'N': 121, 'O': 121, 'P': 150},
'P': {'O': 150, 'S': 186},
'S': {'P': 186}}
bonds3 = {'C': {'C': 120, 'N': 116, 'O': 113},
'N': {'C': 116, 'N': 110},
'O': {'C': 113}}
def print_table(bonds_dict):
letters = ['H', 'C', 'O', 'N', 'P', 'S', 'F', 'Si', 'Cl', 'Br', 'I']
new_letters = []
for key in (letters + list(bonds_dict.keys())):
if key in bonds_dict.keys():
if key not in new_letters:
new_letters.append(key)
letters = new_letters
for j, y in enumerate(letters):
if j == 0:
for x in letters:
print(f'{x} & ', end='')
print()
for i, x in enumerate(letters):
if i == 0:
print(f'{y} & ', end='')
if x in bonds_dict[y]:
print(f'{bonds_dict[y][x]} & ', end='')
else:
print('- & ', end='')
print()
# print_table(bonds3)
def check_consistency_bond_dictionaries():
for bonds_dict in [bonds1, bonds2, bonds3]:
for atom1 in bonds1:
for atom2 in bonds_dict[atom1]:
bond = bonds_dict[atom1][atom2]
try:
bond_check = bonds_dict[atom2][atom1]
except KeyError:
raise ValueError('Not in dict ' + str((atom1, atom2)))
assert bond == bond_check, (
f'{bond} != {bond_check} for {atom1}, {atom2}')
stdv = {'H': 5, 'C': 1, 'N': 1, 'O': 2, 'F': 3}
margin1, margin2, margin3 = 10, 5, 3
allowed_bonds = {'H': 1, 'C': 4, 'N': 3, 'O': 2, 'F': 1, 'B': 3, 'Al': 3,
'Si': 4, 'P': [3, 5],
'S': 4, 'Cl': 1, 'As': 3, 'Br': 1, 'I': 1, 'Hg': [1, 2],
'Bi': [3, 5]}
def get_bond_order(atom1, atom2, distance, check_exists=False):
distance = 100 * distance # We change the metric
# Check exists for large molecules where some atom pairs do not have a
# typical bond length.
if check_exists:
if atom1 not in bonds1:
return 0
if atom2 not in bonds1[atom1]:
return 0
# margin1, margin2 and margin3 have been tuned to maximize the stability of
# the QM9 true samples.
if distance < bonds1[atom1][atom2] + margin1:
# Check if atoms in bonds2 dictionary.
if atom1 in bonds2 and atom2 in bonds2[atom1]:
thr_bond2 = bonds2[atom1][atom2] + margin2
if distance < thr_bond2:
if atom1 in bonds3 and atom2 in bonds3[atom1]:
thr_bond3 = bonds3[atom1][atom2] + margin3
if distance < thr_bond3:
return 3 # Triple
return 2 # Double
return 1 # Single
return 0 # No bond
def single_bond_only(threshold, length, margin1=5):
if length < threshold + margin1:
return 1
return 0
def geom_predictor(p, l, margin1=5, limit_bonds_to_one=False):
""" p: atom pair (couple of str)
l: bond length (float)"""
bond_order = get_bond_order(p[0], p[1], l, check_exists=True)
# If limit_bonds_to_one is enabled, every bond type will return 1.
if limit_bonds_to_one:
return 1 if bond_order > 0 else 0
else:
return bond_order
# l = l * 100 # to Angstrom.
# l = l - 50 # The histograms are shifted by 50
#
# if p == ('B', 'C'):
# return single_bond_only(115, l)
# if p == ('B', 'O'):
# return single_bond_only(145, l)
# if p == ('Br', 'Br'):
# return single_bond_only(264, l)
# if p == ('C', 'Bi'):
# return single_bond_only(237, l)
# if p == ('C', 'Br'):
# return single_bond_only(149, l)
# if p == ('C', 'C'):
# if l < 75:
# return 3
# if l < 84.5:
# return 2
# if l < 93.5:
# return 4
# if l < 115 + margin1:
# return 1
# return 0
# if p == ('C', 'Cl'):
# return single_bond_only(165, l)
# if p == ('C', 'F'):
# return single_bond_only(95, l)
# if p == ('C', 'I'):
# return single_bond_only(165, l)
# if p == ('C', 'N'):
# if l < 66.5:
# return 3
# if l < 77.5:
# return 2
# if l < 83.5:
# return 4
# if l < 126 + margin1:
# return 1
# return 0
# if p == ('C', 'O'):
# if l < 75.5:
# return 2
# if l < 125 + margin1:
# return 1
# return 0
# if p == ('C', 'P'):
# if l < 124.5:
# return 2
# if l < 135 + margin1:
# return 1
# return 0
# if p == ('C', 'S'):
# if l < 118.5:
# return 2
# if l < 126.5:
# return 4
# if l < 170 + margin1:
# return 1
# return 0
# if p == ('C', 'Si'):
# return single_bond_only(143, l)
# if p == ('F', 'P'):
# return single_bond_only(112, l)
# if p == ('F', 'S'):
# return single_bond_only(115, l)
# if p == ('H', 'C'):
# return single_bond_only(68, l)
# if p == ('H', 'F'):
# return single_bond_only(48, l)
# if p == ('H', 'N'):
# return single_bond_only(68, l)
# if p == ('H', 'O'):
# return single_bond_only(66, l)
# if p == ('H', 'S'):
# return single_bond_only(102, l)
# if p == ('I', 'I'):
# return single_bond_only(267, l)
# if p == ('N', 'Cl'):
# return single_bond_only(122, l)
# if p == ('N', 'N'):
# if l < 65:
# return 3
# if l < 69.5:
# return 1
# if l < 72.5:
# return 2
# if l < 85.5:
# return 4
# if l < 105 + margin1:
# return 1
# return 0
# if p == ('N', 'O'):
# if l < 70.5:
# return 2
# if l < 77:
# return 1
# if l < 86.5:
# return 4
# if l < 100 + margin1:
# return 1
# return 0
# if p == ('N', 'P'):
# if l < 111.5:
# return 2
# if l < 135 + margin1:
# return 1
# return 0
# if p == ('N', 'S'):
# if l < 104.5:
# return 2
# if l < 107.5:
# return 1
# if l < 110.5:
# return 4
# if l < 111.5:
# return 2
# if l < 166 + margin1:
# return 1
# return 0
# if p == ('O', 'Bi'):
# return single_bond_only(159, l)
# if p == ('O', 'I'):
# return single_bond_only(152, l)
# if p == ('O', 'O'):
# return single_bond_only(93, l)
# if p == ('O', 'P'):
# if l < 102:
# return 2
# if l < 130 + margin1:
# return 1
# return 0
# if p == ('O', 'S'):
# if l < 95.5:
# return 2
# if l < 170 + margin1:
# return 1
# return 0
# if p == ('O', 'Si'):
# if l < 110.5:
# return 2
# if l < 115 + margin1:
# return 1
# return 0
# if p == ('P', 'S'):
# if l < 154:
# return 2
# if l < 167 + margin1:
# return 1
# return 0
# if p == ('S', 'S'):
# if l < 153.5:
# return 1
# if l < 154.5:
# return 4
# if l < 158.5:
# return 1
# if l < 162.5:
# return 2
# if l < 215 + margin1:
# return 1
# return 0
# if p == ('Si', 'Si'):
# return single_bond_only(249, l)
# return 0
| 9,764 | 30.5 | 79 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/models.py | import torch
from torch.distributions.categorical import Categorical
import numpy as np
from egnn.models import EGNN_dynamics_QM9
from equivariant_diffusion.en_diffusion import EnVariationalDiffusion
def get_model(args, device, dataset_info, dataloader_train):
histogram = dataset_info['n_nodes']
in_node_nf = len(dataset_info['atom_decoder']) + int(args.include_charges)
nodes_dist = DistributionNodes(histogram)
prop_dist = None
if len(args.conditioning) > 0:
prop_dist = DistributionProperty(dataloader_train, args.conditioning)
if args.condition_time:
dynamics_in_node_nf = in_node_nf + 1
else:
print('Warning: dynamics model is _not_ conditioned on time.')
dynamics_in_node_nf = in_node_nf
net_dynamics = EGNN_dynamics_QM9(
in_node_nf=dynamics_in_node_nf, context_node_nf=args.context_node_nf,
n_dims=3, device=device, hidden_nf=args.nf,
act_fn=torch.nn.SiLU(), n_layers=args.n_layers,
attention=args.attention, tanh=args.tanh, mode=args.model, norm_constant=args.norm_constant,
inv_sublayers=args.inv_sublayers, sin_embedding=args.sin_embedding,
normalization_factor=args.normalization_factor, aggregation_method=args.aggregation_method)
if args.probabilistic_model == 'diffusion':
vdm = EnVariationalDiffusion(
dynamics=net_dynamics,
in_node_nf=in_node_nf,
n_dims=3,
timesteps=args.diffusion_steps,
noise_schedule=args.diffusion_noise_schedule,
noise_precision=args.diffusion_noise_precision,
loss_type=args.diffusion_loss_type,
norm_values=args.normalize_factors,
include_charges=args.include_charges
)
return vdm, nodes_dist, prop_dist
else:
raise ValueError(args.probabilistic_model)
def get_optim(args, generative_model):
optim = torch.optim.AdamW(
generative_model.parameters(),
lr=args.lr, amsgrad=True,
weight_decay=1e-12)
return optim
class DistributionNodes:
def __init__(self, histogram):
self.n_nodes = []
prob = []
self.keys = {}
for i, nodes in enumerate(histogram):
self.n_nodes.append(nodes)
self.keys[nodes] = i
prob.append(histogram[nodes])
self.n_nodes = torch.tensor(self.n_nodes)
prob = np.array(prob)
prob = prob/np.sum(prob)
self.prob = torch.from_numpy(prob).float()
entropy = torch.sum(self.prob * torch.log(self.prob + 1e-30))
print("Entropy of n_nodes: H[N]", entropy.item())
self.m = Categorical(torch.tensor(prob))
def sample(self, n_samples=1):
idx = self.m.sample((n_samples,))
return self.n_nodes[idx]
def log_prob(self, batch_n_nodes):
assert len(batch_n_nodes.size()) == 1
idcs = [self.keys[i.item()] for i in batch_n_nodes]
idcs = torch.tensor(idcs).to(batch_n_nodes.device)
log_p = torch.log(self.prob + 1e-30)
log_p = log_p.to(batch_n_nodes.device)
log_probs = log_p[idcs]
return log_probs
class DistributionProperty:
def __init__(self, dataloader, properties, num_bins=1000, normalizer=None):
self.num_bins = num_bins
self.distributions = {}
self.properties = properties
for prop in properties:
self.distributions[prop] = {}
self._create_prob_dist(dataloader.dataset.data['num_atoms'],
dataloader.dataset.data[prop],
self.distributions[prop])
self.normalizer = normalizer
def set_normalizer(self, normalizer):
self.normalizer = normalizer
def _create_prob_dist(self, nodes_arr, values, distribution):
min_nodes, max_nodes = torch.min(nodes_arr), torch.max(nodes_arr)
for n_nodes in range(int(min_nodes), int(max_nodes) + 1):
idxs = nodes_arr == n_nodes
values_filtered = values[idxs]
if len(values_filtered) > 0:
probs, params = self._create_prob_given_nodes(values_filtered)
distribution[n_nodes] = {'probs': probs, 'params': params}
def _create_prob_given_nodes(self, values):
n_bins = self.num_bins #min(self.num_bins, len(values))
prop_min, prop_max = torch.min(values), torch.max(values)
prop_range = prop_max - prop_min + 1e-12
histogram = torch.zeros(n_bins)
for val in values:
i = int((val - prop_min)/prop_range * n_bins)
# Because of numerical precision, one sample can fall in bin int(n_bins) instead of int(n_bins-1)
# We move it to bin int(n_bind-1 if tat happens)
if i == n_bins:
i = n_bins - 1
histogram[i] += 1
probs = histogram / torch.sum(histogram)
probs = Categorical(torch.tensor(probs))
params = [prop_min, prop_max]
return probs, params
def normalize_tensor(self, tensor, prop):
assert self.normalizer is not None
mean = self.normalizer[prop]['mean']
mad = self.normalizer[prop]['mad']
return (tensor - mean) / mad
def sample(self, n_nodes=19):
vals = []
for prop in self.properties:
dist = self.distributions[prop][n_nodes]
idx = dist['probs'].sample((1,))
val = self._idx2value(idx, dist['params'], len(dist['probs'].probs))
val = self.normalize_tensor(val, prop)
vals.append(val)
vals = torch.cat(vals)
return vals
def sample_batch(self, nodesxsample):
vals = []
for n_nodes in nodesxsample:
vals.append(self.sample(int(n_nodes)).unsqueeze(0))
vals = torch.cat(vals, dim=0)
return vals
def _idx2value(self, idx, params, n_bins):
prop_range = params[1] - params[0]
left = float(idx) / n_bins * prop_range + params[0]
right = float(idx + 1) / n_bins * prop_range + params[0]
val = torch.rand(1) * (right - left) + left
return val
if __name__ == '__main__':
dist_nodes = DistributionNodes()
print(dist_nodes.n_nodes)
print(dist_nodes.prob)
for i in range(10):
print(dist_nodes.sample())
| 6,334 | 34 | 109 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/__init__.py | 0 | 0 | 0 | py |
|
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/analyze.py | try:
from rdkit import Chem
from qm9.rdkit_functions import BasicMolecularMetrics
use_rdkit = True
except ModuleNotFoundError:
use_rdkit = False
import qm9.dataset as dataset
import torch
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as sp_stats
from qm9 import bond_analyze
# 'atom_decoder': ['H', 'B', 'C', 'N', 'O', 'F', 'Al', 'Si', 'P', 'S', 'Cl', 'As', 'Br', 'I', 'Hg', 'Bi'],
analyzed_19 ={'atom_types': {1: 93818, 3: 21212, 0: 139496, 2: 8251, 4: 26},
'distances': [0, 0, 0, 0, 0, 0, 0, 22566, 258690, 16534, 50256, 181302, 19676, 122590, 23874, 54834, 309290, 205426, 172004, 229940, 193180, 193058, 161294, 178292, 152184, 157242, 189186, 150298, 125750, 147020, 127574, 133654, 142696, 125906, 98168, 95340, 88632, 80694, 71750, 64466, 55740, 44570, 42850, 36084, 29310, 27268, 23696, 20254, 17112, 14130, 12220, 10660, 9112, 7640, 6378, 5350, 4384, 3650, 2840, 2362, 2050, 1662, 1414, 1216, 966, 856, 492, 516, 420, 326, 388, 326, 236, 140, 130, 92, 62, 52, 78, 56, 24, 8, 10, 12, 18, 2, 10, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}
class Histogram_discrete:
def __init__(self, name='histogram'):
self.name = name
self.bins = {}
def add(self, elements):
for e in elements:
if e in self.bins:
self.bins[e] += 1
else:
self.bins[e] = 1
def normalize(self):
total = 0.
for key in self.bins:
total += self.bins[key]
for key in self.bins:
self.bins[key] = self.bins[key] / total
def plot(self, save_path=None):
width = 1 # the width of the bars
fig, ax = plt.subplots()
x, y = [], []
for key in self.bins:
x.append(key)
y.append(self.bins[key])
ax.bar(x, y, width)
plt.title(self.name)
if save_path is not None:
plt.savefig(save_path)
else:
plt.show()
plt.close()
class Histogram_cont:
def __init__(self, num_bins=100, range=(0., 13.), name='histogram', ignore_zeros=False):
self.name = name
self.bins = [0] * num_bins
self.range = range
self.ignore_zeros = ignore_zeros
def add(self, elements):
for e in elements:
if not self.ignore_zeros or e > 1e-8:
i = int(float(e) / self.range[1] * len(self.bins))
i = min(i, len(self.bins) - 1)
self.bins[i] += 1
def plot(self, save_path=None):
width = (self.range[1] - self.range[0])/len(self.bins) # the width of the bars
fig, ax = plt.subplots()
x = np.linspace(self.range[0], self.range[1], num=len(self.bins) + 1)[:-1] + width / 2
ax.bar(x, self.bins, width)
plt.title(self.name)
if save_path is not None:
plt.savefig(save_path)
else:
plt.show()
plt.close()
def plot_both(self, hist_b, save_path=None, wandb=None):
## TO DO: Check if the relation of bins and linspace is correct
hist_a = normalize_histogram(self.bins)
hist_b = normalize_histogram(hist_b)
#width = (self.range[1] - self.range[0]) / len(self.bins) # the width of the bars
fig, ax = plt.subplots()
x = np.linspace(self.range[0], self.range[1], num=len(self.bins) + 1)[:-1]
ax.step(x, hist_b)
ax.step(x, hist_a)
ax.legend(['True', 'Learned'])
plt.title(self.name)
if save_path is not None:
plt.savefig(save_path)
if wandb is not None:
if wandb is not None:
# Log image(s)
im = plt.imread(save_path)
wandb.log({save_path: [wandb.Image(im, caption=save_path)]})
else:
plt.show()
plt.close()
def normalize_histogram(hist):
hist = np.array(hist)
prob = hist / np.sum(hist)
return prob
def coord2distances(x):
x = x.unsqueeze(2)
x_t = x.transpose(1, 2)
dist = (x - x_t) ** 2
dist = torch.sqrt(torch.sum(dist, 3))
dist = dist.flatten()
return dist
def earth_mover_distance(h1, h2):
p1 = normalize_histogram(h1)
p2 = normalize_histogram(h2)
distance = sp_stats.wasserstein_distance(p1, p2)
return distance
def kl_divergence(p1, p2):
return np.sum(p1*np.log(p1 / p2))
def kl_divergence_sym(h1, h2):
p1 = normalize_histogram(h1) + 1e-10
p2 = normalize_histogram(h2) + 1e-10
kl = kl_divergence(p1, p2)
kl_flipped = kl_divergence(p2, p1)
return (kl + kl_flipped) / 2.
def js_divergence(h1, h2):
p1 = normalize_histogram(h1) + 1e-10
p2 = normalize_histogram(h2) + 1e-10
M = (p1 + p2)/2
js = (kl_divergence(p1, M) + kl_divergence(p2, M)) / 2
return js
def main_analyze_qm9(remove_h: bool, dataset_name='qm9', n_atoms=None):
class DataLoaderConfig(object):
def __init__(self):
self.batch_size = 128
self.remove_h = remove_h
self.filter_n_atoms = n_atoms
self.num_workers = 0
self.include_charges = True
self.dataset = dataset_name #could be qm9, qm9_first_half or qm9_second_half
self.datadir = 'qm9/temp'
cfg = DataLoaderConfig()
dataloaders, charge_scale = dataset.retrieve_dataloaders(cfg)
hist_nodes = Histogram_discrete('Histogram # nodes')
hist_atom_type = Histogram_discrete('Histogram of atom types')
hist_dist = Histogram_cont(name='Histogram relative distances', ignore_zeros=True)
for i, data in enumerate(dataloaders['train']):
print(i * cfg.batch_size)
# Histogram num_nodes
num_nodes = torch.sum(data['atom_mask'], dim=1)
num_nodes = list(num_nodes.numpy())
hist_nodes.add(num_nodes)
#Histogram edge distances
x = data['positions'] * data['atom_mask'].unsqueeze(2)
dist = coord2distances(x)
hist_dist.add(list(dist.numpy()))
# Histogram of atom types
one_hot = data['one_hot'].double()
atom = torch.argmax(one_hot, 2)
atom = atom.flatten()
mask = data['atom_mask'].flatten()
masked_atoms = list(atom[mask].numpy())
hist_atom_type.add(masked_atoms)
hist_dist.plot()
hist_dist.plot_both(hist_dist.bins[::-1])
print("KL divergence A %.4f" % kl_divergence_sym(hist_dist.bins, hist_dist.bins[::-1]))
print("KL divergence B %.4f" % kl_divergence_sym(hist_dist.bins, hist_dist.bins))
print(hist_dist.bins)
hist_nodes.plot()
print("Histogram of the number of nodes", hist_nodes.bins)
hist_atom_type.plot()
print(" Histogram of the atom types (H (optional), C, N, O, F)", hist_atom_type.bins)
############################
# Validity and bond analysis
def check_stability(positions, atom_type, dataset_info, debug=False):
assert len(positions.shape) == 2
assert positions.shape[1] == 3
atom_decoder = dataset_info['atom_decoder']
x = positions[:, 0]
y = positions[:, 1]
z = positions[:, 2]
nr_bonds = np.zeros(len(x), dtype='int')
for i in range(len(x)):
for j in range(i + 1, len(x)):
p1 = np.array([x[i], y[i], z[i]])
p2 = np.array([x[j], y[j], z[j]])
dist = np.sqrt(np.sum((p1 - p2) ** 2))
atom1, atom2 = atom_decoder[atom_type[i]], atom_decoder[atom_type[j]]
pair = sorted([atom_type[i], atom_type[j]])
if dataset_info['name'] == 'qm9' or dataset_info['name'] == 'qm9_second_half' or dataset_info['name'] == 'qm9_first_half':
order = bond_analyze.get_bond_order(atom1, atom2, dist)
elif dataset_info['name'] == 'geom':
order = bond_analyze.geom_predictor(
(atom_decoder[pair[0]], atom_decoder[pair[1]]), dist)
nr_bonds[i] += order
nr_bonds[j] += order
nr_stable_bonds = 0
for atom_type_i, nr_bonds_i in zip(atom_type, nr_bonds):
possible_bonds = bond_analyze.allowed_bonds[atom_decoder[atom_type_i]]
if type(possible_bonds) == int:
is_stable = possible_bonds == nr_bonds_i
else:
is_stable = nr_bonds_i in possible_bonds
if not is_stable and debug:
print("Invalid bonds for molecule %s with %d bonds" % (atom_decoder[atom_type_i], nr_bonds_i))
nr_stable_bonds += int(is_stable)
molecule_stable = nr_stable_bonds == len(x)
return molecule_stable, nr_stable_bonds, len(x)
def process_loader(dataloader):
""" Mask atoms, return positions and atom types"""
out = []
for data in dataloader:
for i in range(data['positions'].size(0)):
positions = data['positions'][i].view(-1, 3)
one_hot = data['one_hot'][i].view(-1, 5).type(torch.float32)
mask = data['atom_mask'][i].flatten()
positions, one_hot = positions[mask], one_hot[mask]
atom_type = torch.argmax(one_hot, dim=1)
out.append((positions, atom_type))
return out
def main_check_stability(remove_h: bool, batch_size=32):
from configs import datasets_config
import qm9.dataset as dataset
class Config:
def __init__(self):
self.batch_size = batch_size
self.num_workers = 0
self.remove_h = remove_h
self.filter_n_atoms = None
self.datadir = 'qm9/temp'
self.dataset = 'qm9'
self.include_charges = True
self.filter_molecule_size = None
self.sequential = False
cfg = Config()
dataset_info = datasets_config.qm9_with_h
dataloaders, charge_scale = dataset.retrieve_dataloaders(cfg)
if use_rdkit:
from qm9.rdkit_functions import BasicMolecularMetrics
metrics = BasicMolecularMetrics(dataset_info)
atom_decoder = dataset_info['atom_decoder']
def test_validity_for(dataloader):
count_mol_stable = 0
count_atm_stable = 0
count_mol_total = 0
count_atm_total = 0
for [positions, atom_types] in dataloader:
is_stable, nr_stable, total = check_stability(
positions, atom_types, dataset_info)
count_atm_stable += nr_stable
count_atm_total += total
count_mol_stable += int(is_stable)
count_mol_total += 1
print(f"Stable molecules "
f"{100. * count_mol_stable/count_mol_total:.2f} \t"
f"Stable atoms: "
f"{100. * count_atm_stable/count_atm_total:.2f} \t"
f"Counted molecules {count_mol_total}/{len(dataloader)*batch_size}")
train_loader = process_loader(dataloaders['train'])
test_loader = process_loader(dataloaders['test'])
if use_rdkit:
print('For test')
metrics.evaluate(test_loader)
print('For train')
metrics.evaluate(train_loader)
else:
print('For train')
test_validity_for(train_loader)
print('For test')
test_validity_for(test_loader)
def analyze_stability_for_molecules(molecule_list, dataset_info):
one_hot = molecule_list['one_hot']
x = molecule_list['x']
node_mask = molecule_list['node_mask']
if isinstance(node_mask, torch.Tensor):
atomsxmol = torch.sum(node_mask, dim=1)
else:
atomsxmol = [torch.sum(m) for m in node_mask]
n_samples = len(x)
molecule_stable = 0
nr_stable_bonds = 0
n_atoms = 0
processed_list = []
for i in range(n_samples):
atom_type = one_hot[i].argmax(1).cpu().detach()
pos = x[i].cpu().detach()
atom_type = atom_type[0:int(atomsxmol[i])]
pos = pos[0:int(atomsxmol[i])]
processed_list.append((pos, atom_type))
for mol in processed_list:
pos, atom_type = mol
validity_results = check_stability(pos, atom_type, dataset_info)
molecule_stable += int(validity_results[0])
nr_stable_bonds += int(validity_results[1])
n_atoms += int(validity_results[2])
# Validity
fraction_mol_stable = molecule_stable / float(n_samples)
fraction_atm_stable = nr_stable_bonds / float(n_atoms)
validity_dict = {
'mol_stable': fraction_mol_stable,
'atm_stable': fraction_atm_stable,
}
if use_rdkit:
metrics = BasicMolecularMetrics(dataset_info)
rdkit_metrics = metrics.evaluate(processed_list)
#print("Unique molecules:", rdkit_metrics[1])
return validity_dict, rdkit_metrics
else:
return validity_dict, None
def analyze_node_distribution(mol_list, save_path):
hist_nodes = Histogram_discrete('Histogram # nodes (stable molecules)')
hist_atom_type = Histogram_discrete('Histogram of atom types')
for molecule in mol_list:
positions, atom_type = molecule
hist_nodes.add([positions.shape[0]])
hist_atom_type.add(atom_type)
print("Histogram of #nodes")
print(hist_nodes.bins)
print("Histogram of # atom types")
print(hist_atom_type.bins)
hist_nodes.normalize()
if __name__ == '__main__':
# main_analyze_qm9(remove_h=False, dataset_name='qm9')
main_check_stability(remove_h=False)
| 13,305 | 32.686076 | 594 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/property_prediction/main_qm9_prop.py | import sys, os
sys.path.append(os.path.abspath(os.path.join('../../')))
from qm9.property_prediction.models_property import EGNN, Naive, NumNodes
import torch
from torch import nn, optim
import argparse
from qm9.property_prediction import prop_utils
import json
from qm9 import dataset, utils
import pickle
loss_l1 = nn.L1Loss()
def train(model, epoch, loader, mean, mad, property, device, partition='train', optimizer=None, lr_scheduler=None, log_interval=20, debug_break=False):
if partition == 'train':
lr_scheduler.step()
res = {'loss': 0, 'counter': 0, 'loss_arr':[]}
for i, data in enumerate(loader):
if partition == 'train':
model.train()
optimizer.zero_grad()
else:
model.eval()
batch_size, n_nodes, _ = data['positions'].size()
atom_positions = data['positions'].view(batch_size * n_nodes, -1).to(device, torch.float32)
atom_mask = data['atom_mask'].view(batch_size * n_nodes, -1).to(device, torch.float32)
edge_mask = data['edge_mask'].to(device, torch.float32)
nodes = data['one_hot'].to(device, torch.float32)
#charges = data['charges'].to(device, dtype).squeeze(2)
#nodes = prop_utils.preprocess_input(one_hot, charges, args.charge_power, charge_scale, device)
nodes = nodes.view(batch_size * n_nodes, -1)
# nodes = torch.cat([one_hot, charges], dim=1)
edges = prop_utils.get_adj_matrix(n_nodes, batch_size, device)
label = data[property].to(device, torch.float32)
'''
print("Positions mean")
print(torch.mean(torch.abs(atom_positions)))
print("Positions max")
print(torch.max(atom_positions))
print("Positions min")
print(torch.min(atom_positions))
print("\nOne hot mean")
print(torch.mean(torch.abs(nodes)))
print("one_hot max")
print(torch.max(nodes))
print("one_hot min")
print(torch.min(nodes))
print("\nLabel mean")
print(torch.mean(torch.abs(label)))
print("label max")
print(torch.max(label))
print("label min")
print(torch.min(label))
'''
pred = model(h0=nodes, x=atom_positions, edges=edges, edge_attr=None, node_mask=atom_mask, edge_mask=edge_mask,
n_nodes=n_nodes)
# print("\nPred mean")
# print(torch.mean(torch.abs(pred)))
# print("Pred max")
# print(torch.max(pred))
# print("Pred min")
# print(torch.min(pred))
if partition == 'train':
loss = loss_l1(pred, (label - mean) / mad)
loss.backward()
optimizer.step()
else:
loss = loss_l1(mad * pred + mean, label)
res['loss'] += loss.item() * batch_size
res['counter'] += batch_size
res['loss_arr'].append(loss.item())
prefix = ""
if partition != 'train':
prefix = ">> %s \t" % partition
if i % log_interval == 0:
print(prefix + "Epoch %d \t Iteration %d \t loss %.4f" % (epoch, i, sum(res['loss_arr'][-10:])/len(res['loss_arr'][-10:])))
if debug_break:
break
return res['loss'] / res['counter']
def test(model, epoch, loader, mean, mad, property, device, log_interval, debug_break=False):
return train(model, epoch, loader, mean, mad, property, device, partition='test', log_interval=log_interval, debug_break=debug_break)
def get_model(args):
if args.model_name == 'egnn':
model = EGNN(in_node_nf=5, in_edge_nf=0, hidden_nf=args.nf, device=args.device, n_layers=args.n_layers,
coords_weight=1.0,
attention=args.attention, node_attr=args.node_attr)
elif args.model_name == 'naive':
model = Naive(device=args.device)
elif args.model_name == 'numnodes':
model = NumNodes(device=args.device)
else:
raise Exception("Wrong model name %s" % args.model_name)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='QM9 Example')
parser.add_argument('--exp_name', type=str, default='debug', metavar='N',
help='experiment_name')
parser.add_argument('--batch_size', type=int, default=96, metavar='N',
help='input batch size for training (default: 128)')
parser.add_argument('--epochs', type=int, default=1000, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log_interval', type=int, default=20, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--test_interval', type=int, default=1, metavar='N',
help='how many epochs to wait before logging test')
parser.add_argument('--outf', type=str, default='outputs', metavar='N',
help='folder to output vae')
parser.add_argument('--lr', type=float, default=1e-3, metavar='N',
help='learning rate')
parser.add_argument('--nf', type=int, default=128, metavar='N',
help='learning rate')
parser.add_argument('--attention', type=int, default=1, metavar='N',
help='attention in the ae model')
parser.add_argument('--n_layers', type=int, default=7, metavar='N',
help='number of layers for the autoencoder')
parser.add_argument('--property', type=str, default='alpha', metavar='N',
help='label to predict: alpha | gap | homo | lumo | mu | Cv | G | H | r2 | U | U0 | zpve')
parser.add_argument('--num_workers', type=int, default=0, metavar='N',
help='number of workers for the dataloader')
parser.add_argument('--filter_n_atoms', type=int, default=None,
help='When set to an integer value, QM9 will only contain molecules of that amount of atoms')
parser.add_argument('--charge_power', type=int, default=2, metavar='N',
help='maximum power to take into one-hot features')
parser.add_argument('--dataset', type=str, default="qm9_first_half", metavar='N',
help='qm9_first_half')
parser.add_argument('--datadir', type=str, default="../../qm9/temp", metavar='N',
help='qm9_first_half')
parser.add_argument('--remove_h', action='store_true')
parser.add_argument('--include_charges', type=eval, default=True, help='include atom charge or not')
parser.add_argument('--node_attr', type=int, default=0, metavar='N',
help='node_attr or not')
parser.add_argument('--weight_decay', type=float, default=1e-16, metavar='N',
help='weight decay')
parser.add_argument('--save_path', type=float, default=1e-16, metavar='N',
help='weight decay')
parser.add_argument('--model_name', type=str, default='numnodes', metavar='N',
help='egnn | naive | numnodes')
parser.add_argument('--save_model', type=eval, default=True)
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if args.cuda else "cpu")
dtype = torch.float32
args.device = device
print(args)
res = {'epochs': [], 'losess': [], 'best_val': 1e10, 'best_test': 1e10, 'best_epoch': 0}
prop_utils.makedir(args.outf)
prop_utils.makedir(args.outf + "/" + args.exp_name)
dataloaders, charge_scale = dataset.retrieve_dataloaders(args)
args.dataset = "qm9_second_half"
dataloaders_aux, _ = dataset.retrieve_dataloaders(args)
dataloaders["test"] = dataloaders_aux["train"]
# compute mean and mean absolute deviation
property_norms = utils.compute_mean_mad_from_dataloader(dataloaders['valid'], [args.property])
mean, mad = property_norms[args.property]['mean'], property_norms[args.property]['mad']
model = get_model(args)
print(model)
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs)
for epoch in range(0, args.epochs):
train(model, epoch, dataloaders['train'], mean, mad, args.property, device, partition='train', optimizer=optimizer, lr_scheduler=lr_scheduler, log_interval=args.log_interval)
if epoch % args.test_interval == 0:
val_loss = train(model, epoch, dataloaders['valid'], mean, mad, args.property, device, partition='valid', optimizer=optimizer, lr_scheduler=lr_scheduler, log_interval=args.log_interval)
test_loss = test(model, epoch, dataloaders['test'], mean, mad, args.property, device, log_interval=args.log_interval)
res['epochs'].append(epoch)
res['losess'].append(test_loss)
if val_loss < res['best_val']:
res['best_val'] = val_loss
res['best_test'] = test_loss
res['best_epoch'] = epoch
if args.save_model:
torch.save(model.state_dict(), args.outf + "/" + args.exp_name + "/best_checkpoint.npy")
with open(args.outf + "/" + args.exp_name + "/args.pickle", 'wb') as f:
pickle.dump(args, f)
print("Val loss: %.4f \t test loss: %.4f \t epoch %d" % (val_loss, test_loss, epoch))
print("Best: val loss: %.4f \t test loss: %.4f \t epoch %d" % (res['best_val'], res['best_test'], res['best_epoch']))
json_object = json.dumps(res, indent=4)
with open(args.outf + "/" + args.exp_name + "/losess.json", "w") as outfile:
outfile.write(json_object)
| 10,043 | 44.654545 | 197 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/property_prediction/__init__.py | 0 | 0 | 0 | py |
|
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/property_prediction/models_property.py | from .models.gcl import E_GCL, unsorted_segment_sum
import torch
from torch import nn
class E_GCL_mask(E_GCL):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self, input_nf, output_nf, hidden_nf, edges_in_d=0, nodes_attr_dim=0, act_fn=nn.ReLU(), recurrent=True, coords_weight=1.0, attention=False):
E_GCL.__init__(self, input_nf, output_nf, hidden_nf, edges_in_d=edges_in_d, nodes_att_dim=nodes_attr_dim, act_fn=act_fn, recurrent=recurrent, coords_weight=coords_weight, attention=attention)
del self.coord_mlp
self.act_fn = act_fn
def coord_model(self, coord, edge_index, coord_diff, edge_feat, edge_mask):
row, col = edge_index
trans = coord_diff * self.coord_mlp(edge_feat) * edge_mask
agg = unsorted_segment_sum(trans, row, num_segments=coord.size(0))
coord += agg*self.coords_weight
return coord
def forward(self, h, edge_index, coord, node_mask, edge_mask, edge_attr=None, node_attr=None, n_nodes=None):
row, col = edge_index
radial, coord_diff = self.coord2radial(edge_index, coord)
edge_feat = self.edge_model(h[row], h[col], radial, edge_attr)
edge_feat = edge_feat * edge_mask
# TO DO: edge_feat = edge_feat * edge_mask
#coord = self.coord_model(coord, edge_index, coord_diff, edge_feat, edge_mask)
h, agg = self.node_model(h, edge_index, edge_feat, node_attr)
return h, coord, edge_attr
class EGNN(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, device='cpu', act_fn=nn.SiLU(), n_layers=4, coords_weight=1.0, attention=False, node_attr=1):
super(EGNN, self).__init__()
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
### Encoder
self.embedding = nn.Linear(in_node_nf, hidden_nf)
self.node_attr = node_attr
if node_attr:
n_node_attr = in_node_nf
else:
n_node_attr = 0
for i in range(0, n_layers):
self.add_module("gcl_%d" % i, E_GCL_mask(self.hidden_nf, self.hidden_nf, self.hidden_nf, edges_in_d=in_edge_nf, nodes_attr_dim=n_node_attr, act_fn=act_fn, recurrent=True, coords_weight=coords_weight, attention=attention))
self.node_dec = nn.Sequential(nn.Linear(self.hidden_nf, self.hidden_nf),
act_fn,
nn.Linear(self.hidden_nf, self.hidden_nf))
self.graph_dec = nn.Sequential(nn.Linear(self.hidden_nf, self.hidden_nf),
act_fn,
nn.Linear(self.hidden_nf, 1))
self.to(self.device)
def forward(self, h0, x, edges, edge_attr, node_mask, edge_mask, n_nodes):
h = self.embedding(h0)
for i in range(0, self.n_layers):
if self.node_attr:
h, _, _ = self._modules["gcl_%d" % i](h, edges, x, node_mask, edge_mask, edge_attr=edge_attr, node_attr=h0, n_nodes=n_nodes)
else:
h, _, _ = self._modules["gcl_%d" % i](h, edges, x, node_mask, edge_mask, edge_attr=edge_attr,
node_attr=None, n_nodes=n_nodes)
h = self.node_dec(h)
h = h * node_mask
h = h.view(-1, n_nodes, self.hidden_nf)
h = torch.sum(h, dim=1)
pred = self.graph_dec(h)
return pred.squeeze(1)
class EGNN(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, device='cpu', act_fn=nn.SiLU(), n_layers=4, coords_weight=1.0, attention=False, node_attr=1):
super(EGNN, self).__init__()
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
### Encoder
self.embedding = nn.Linear(in_node_nf, hidden_nf)
self.node_attr = node_attr
if node_attr:
n_node_attr = in_node_nf
else:
n_node_attr = 0
for i in range(0, n_layers):
self.add_module("gcl_%d" % i, E_GCL_mask(self.hidden_nf, self.hidden_nf, self.hidden_nf, edges_in_d=in_edge_nf, nodes_attr_dim=n_node_attr, act_fn=act_fn, recurrent=True, coords_weight=coords_weight, attention=attention))
self.node_dec = nn.Sequential(nn.Linear(self.hidden_nf, self.hidden_nf),
act_fn,
nn.Linear(self.hidden_nf, self.hidden_nf))
self.graph_dec = nn.Sequential(nn.Linear(self.hidden_nf, self.hidden_nf),
act_fn,
nn.Linear(self.hidden_nf, 1))
self.to(self.device)
def forward(self, h0, x, edges, edge_attr, node_mask, edge_mask, n_nodes):
h = self.embedding(h0)
for i in range(0, self.n_layers):
if self.node_attr:
h, _, _ = self._modules["gcl_%d" % i](h, edges, x, node_mask, edge_mask, edge_attr=edge_attr, node_attr=h0, n_nodes=n_nodes)
else:
h, _, _ = self._modules["gcl_%d" % i](h, edges, x, node_mask, edge_mask, edge_attr=edge_attr,
node_attr=None, n_nodes=n_nodes)
h = self.node_dec(h)
h = h * node_mask
h = h.view(-1, n_nodes, self.hidden_nf)
h = torch.sum(h, dim=1)
pred = self.graph_dec(h)
return pred.squeeze(1)
class Naive(nn.Module):
def __init__(self, device):
super(Naive, self).__init__()
self.device = device
self.linear = nn.Linear(1, 1)
self.to(self.device)
def forward(self, h0, x, edges, edge_attr, node_mask, edge_mask, n_nodes):
node_mask = node_mask.view(-1, n_nodes)
bs, n_nodes = node_mask.size()
x = torch.zeros(bs, 1).to(self.device)
return self.linear(x).squeeze(1)
class NumNodes(nn.Module):
def __init__(self, device, nf=128):
super(NumNodes, self).__init__()
self.device = device
self.linear1 = nn.Linear(1, nf)
self.linear2 = nn.Linear(nf, 1)
self.act_fn = nn.SiLU()
self.to(self.device)
def forward(self, h0, x, edges, edge_attr, node_mask, edge_mask, n_nodes):
reshaped_mask = node_mask.view(-1, n_nodes)
nodesxmol = torch.sum(reshaped_mask, dim=1).unsqueeze(1)/29
x = self.act_fn(self.linear1(nodesxmol))
return self.linear2(x).squeeze(1) | 6,706 | 40.91875 | 233 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/property_prediction/prop_utils.py | import os
import matplotlib
matplotlib.use('Agg')
import torch
import matplotlib.pyplot as plt
def create_folders(args):
try:
os.makedirs(args.outf)
except OSError:
pass
try:
os.makedirs(args.outf + '/' + args.exp_name)
except OSError:
pass
try:
os.makedirs(args.outf + '/' + args.exp_name + '/images_recon')
except OSError:
pass
try:
os.makedirs(args.outf + '/' + args.exp_name + '/images_gen')
except OSError:
pass
def makedir(path):
try:
os.makedirs(path)
except OSError:
pass
def normalize_res(res, keys=[]):
for key in keys:
if key != 'counter':
res[key] = res[key] / res['counter']
del res['counter']
return res
def plot_coords(coords_mu, path, coords_logvar=None):
if coords_mu is None:
return 0
if coords_logvar is not None:
coords_std = torch.sqrt(torch.exp(coords_logvar))
else:
coords_std = torch.zeros(coords_mu.size())
coords_size = (coords_std ** 2) * 1
plt.scatter(coords_mu[:, 0], coords_mu[:, 1], alpha=0.6, s=100)
#plt.errorbar(coords_mu[:, 0], coords_mu[:, 1], xerr=coords_size[:, 0], yerr=coords_size[:, 1], linestyle="None", alpha=0.5)
plt.savefig(path)
plt.clf()
def filter_nodes(dataset, n_nodes):
new_graphs = []
for i in range(len(dataset.graphs)):
if len(dataset.graphs[i].nodes) == n_nodes:
new_graphs.append(dataset.graphs[i])
dataset.graphs = new_graphs
dataset.n_nodes = n_nodes
return dataset
def adjust_learning_rate(optimizer, epoch, lr_0, factor=0.5, epochs_decay=100):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = lr_0 * (factor ** (epoch // epochs_decay))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
edges_dic = {}
def get_adj_matrix(n_nodes, batch_size, device):
if n_nodes in edges_dic:
edges_dic_b = edges_dic[n_nodes]
if batch_size in edges_dic_b:
return edges_dic_b[batch_size]
else:
# get edges for a single sample
rows, cols = [], []
for batch_idx in range(batch_size):
for i in range(n_nodes):
for j in range(n_nodes):
rows.append(i + batch_idx*n_nodes)
cols.append(j + batch_idx*n_nodes)
else:
edges_dic[n_nodes] = {}
return get_adj_matrix(n_nodes, batch_size, device)
edges = [torch.LongTensor(rows).to(device), torch.LongTensor(cols).to(device)]
return edges
def preprocess_input(one_hot, charges, charge_power, charge_scale, device):
charge_tensor = (charges.unsqueeze(-1) / charge_scale).pow(
torch.arange(charge_power + 1., device=device, dtype=torch.float32))
charge_tensor = charge_tensor.view(charges.shape + (1, charge_power + 1))
atom_scalars = (one_hot.unsqueeze(-1) * charge_tensor).view(charges.shape[:2] + (-1,))
return atom_scalars | 3,051 | 28.346154 | 128 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/property_prediction/models/gcl.py | from torch import nn
import torch
class MLP(nn.Module):
""" a simple 4-layer MLP """
def __init__(self, nin, nout, nh):
super().__init__()
self.net = nn.Sequential(
nn.Linear(nin, nh),
nn.LeakyReLU(0.2),
nn.Linear(nh, nh),
nn.LeakyReLU(0.2),
nn.Linear(nh, nh),
nn.LeakyReLU(0.2),
nn.Linear(nh, nout),
)
def forward(self, x):
return self.net(x)
class GCL_basic(nn.Module):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self):
super(GCL_basic, self).__init__()
def edge_model(self, source, target, edge_attr):
pass
def node_model(self, h, edge_index, edge_attr):
pass
def forward(self, x, edge_index, edge_attr=None):
row, col = edge_index
edge_feat = self.edge_model(x[row], x[col], edge_attr)
x = self.node_model(x, edge_index, edge_feat)
return x, edge_feat
class GCL(GCL_basic):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self, input_nf, output_nf, hidden_nf, edges_in_nf=0, act_fn=nn.ReLU(), bias=True, attention=False, t_eq=False, recurrent=True):
super(GCL, self).__init__()
self.attention = attention
self.t_eq=t_eq
self.recurrent = recurrent
input_edge_nf = input_nf * 2
self.edge_mlp = nn.Sequential(
nn.Linear(input_edge_nf + edges_in_nf, hidden_nf, bias=bias),
act_fn,
nn.Linear(hidden_nf, hidden_nf, bias=bias),
act_fn)
if self.attention:
self.att_mlp = nn.Sequential(
nn.Linear(input_nf, hidden_nf, bias=bias),
act_fn,
nn.Linear(hidden_nf, 1, bias=bias),
nn.Sigmoid())
self.node_mlp = nn.Sequential(
nn.Linear(hidden_nf + input_nf, hidden_nf, bias=bias),
act_fn,
nn.Linear(hidden_nf, output_nf, bias=bias))
#if recurrent:
#self.gru = nn.GRUCell(hidden_nf, hidden_nf)
def edge_model(self, source, target, edge_attr):
edge_in = torch.cat([source, target], dim=1)
if edge_attr is not None:
edge_in = torch.cat([edge_in, edge_attr], dim=1)
out = self.edge_mlp(edge_in)
if self.attention:
att = self.att_mlp(torch.abs(source - target))
out = out * att
return out
def node_model(self, h, edge_index, edge_attr):
row, col = edge_index
agg = unsorted_segment_sum(edge_attr, row, num_segments=h.size(0))
out = torch.cat([h, agg], dim=1)
out = self.node_mlp(out)
if self.recurrent:
out = out + h
#out = self.gru(out, h)
return out
class GCL_rf(GCL_basic):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self, nf=64, edge_attr_nf=0, reg=0, act_fn=nn.LeakyReLU(0.2), clamp=False):
super(GCL_rf, self).__init__()
self.clamp = clamp
layer = nn.Linear(nf, 1, bias=False)
torch.nn.init.xavier_uniform_(layer.weight, gain=0.001)
self.phi = nn.Sequential(nn.Linear(edge_attr_nf + 1, nf),
act_fn,
layer)
self.reg = reg
def edge_model(self, source, target, edge_attr):
x_diff = source - target
radial = torch.sqrt(torch.sum(x_diff ** 2, dim=1)).unsqueeze(1)
e_input = torch.cat([radial, edge_attr], dim=1)
e_out = self.phi(e_input)
m_ij = x_diff * e_out
if self.clamp:
m_ij = torch.clamp(m_ij, min=-100, max=100)
return m_ij
def node_model(self, x, edge_index, edge_attr):
row, col = edge_index
agg = unsorted_segment_mean(edge_attr, row, num_segments=x.size(0))
x_out = x + agg - x*self.reg
return x_out
class E_GCL(nn.Module):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self, input_nf, output_nf, hidden_nf, edges_in_d=0, nodes_att_dim=0, act_fn=nn.ReLU(), recurrent=True, coords_weight=1.0, attention=False, clamp=False, norm_diff=False, tanh=False):
super(E_GCL, self).__init__()
input_edge = input_nf * 2
self.coords_weight = coords_weight
self.recurrent = recurrent
self.attention = attention
self.norm_diff = norm_diff
self.tanh = tanh
edge_coords_nf = 1
self.edge_mlp = nn.Sequential(
nn.Linear(input_edge + edge_coords_nf + edges_in_d, hidden_nf),
act_fn,
nn.Linear(hidden_nf, hidden_nf),
act_fn)
self.node_mlp = nn.Sequential(
nn.Linear(hidden_nf + input_nf + nodes_att_dim, hidden_nf),
act_fn,
nn.Linear(hidden_nf, output_nf))
layer = nn.Linear(hidden_nf, 1, bias=False)
torch.nn.init.xavier_uniform_(layer.weight, gain=0.001)
self.clamp = clamp
coord_mlp = []
coord_mlp.append(nn.Linear(hidden_nf, hidden_nf))
coord_mlp.append(act_fn)
coord_mlp.append(layer)
if self.tanh:
coord_mlp.append(nn.Tanh())
self.coords_range = nn.Parameter(torch.ones(1))*3
self.coord_mlp = nn.Sequential(*coord_mlp)
if self.attention:
self.att_mlp = nn.Sequential(
nn.Linear(hidden_nf, 1),
nn.Sigmoid())
#if recurrent:
# self.gru = nn.GRUCell(hidden_nf, hidden_nf)
def edge_model(self, source, target, radial, edge_attr):
if edge_attr is None: # Unused.
out = torch.cat([source, target, radial], dim=1)
else:
out = torch.cat([source, target, radial, edge_attr], dim=1)
out = self.edge_mlp(out)
if self.attention:
att_val = self.att_mlp(out)
out = out * att_val
return out
def node_model(self, x, edge_index, edge_attr, node_attr):
row, col = edge_index
agg = unsorted_segment_sum(edge_attr, row, num_segments=x.size(0))
if node_attr is not None:
agg = torch.cat([x, agg, node_attr], dim=1)
else:
agg = torch.cat([x, agg], dim=1)
out = self.node_mlp(agg)
if self.recurrent:
out = x + out
return out, agg
def coord_model(self, coord, edge_index, coord_diff, edge_feat):
row, col = edge_index
trans = coord_diff * self.coord_mlp(edge_feat)
trans = torch.clamp(trans, min=-100, max=100) #This is never activated but just in case it case it explosed it may save the train
agg = unsorted_segment_mean(trans, row, num_segments=coord.size(0))
coord += agg*self.coords_weight
return coord
def coord2radial(self, edge_index, coord):
row, col = edge_index
coord_diff = coord[row] - coord[col]
radial = torch.sum((coord_diff)**2, 1).unsqueeze(1)
if self.norm_diff:
norm = torch.sqrt(radial) + 1
coord_diff = coord_diff/(norm)
return radial, coord_diff
def forward(self, h, edge_index, coord, edge_attr=None, node_attr=None):
row, col = edge_index
radial, coord_diff = self.coord2radial(edge_index, coord)
edge_feat = self.edge_model(h[row], h[col], radial, edge_attr)
coord = self.coord_model(coord, edge_index, coord_diff, edge_feat)
h, agg = self.node_model(h, edge_index, edge_feat, node_attr)
# coord = self.node_coord_model(h, coord)
# x = self.node_model(x, edge_index, x[col], u, batch) # GCN
return h, coord, edge_attr
class E_GCL_vel(E_GCL):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self, input_nf, output_nf, hidden_nf, edges_in_d=0, nodes_att_dim=0, act_fn=nn.ReLU(), recurrent=True, coords_weight=1.0, attention=False, norm_diff=False, tanh=False):
E_GCL.__init__(self, input_nf, output_nf, hidden_nf, edges_in_d=edges_in_d, nodes_att_dim=nodes_att_dim, act_fn=act_fn, recurrent=recurrent, coords_weight=coords_weight, attention=attention, norm_diff=norm_diff, tanh=tanh)
self.norm_diff = norm_diff
self.coord_mlp_vel = nn.Sequential(
nn.Linear(input_nf, hidden_nf),
act_fn,
nn.Linear(hidden_nf, 1))
def forward(self, h, edge_index, coord, vel, edge_attr=None, node_attr=None):
row, col = edge_index
radial, coord_diff = self.coord2radial(edge_index, coord)
edge_feat = self.edge_model(h[row], h[col], radial, edge_attr)
coord = self.coord_model(coord, edge_index, coord_diff, edge_feat)
coord += self.coord_mlp_vel(h) * vel
h, agg = self.node_model(h, edge_index, edge_feat, node_attr)
# coord = self.node_coord_model(h, coord)
# x = self.node_model(x, edge_index, x[col], u, batch) # GCN
return h, coord, edge_attr
class GCL_rf_vel(nn.Module):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self, nf=64, edge_attr_nf=0, act_fn=nn.LeakyReLU(0.2), coords_weight=1.0):
super(GCL_rf_vel, self).__init__()
self.coords_weight = coords_weight
self.coord_mlp_vel = nn.Sequential(
nn.Linear(1, nf),
act_fn,
nn.Linear(nf, 1))
layer = nn.Linear(nf, 1, bias=False)
torch.nn.init.xavier_uniform_(layer.weight, gain=0.001)
#layer.weight.uniform_(-0.1, 0.1)
self.phi = nn.Sequential(nn.Linear(1 + edge_attr_nf, nf),
act_fn,
layer,
nn.Tanh()) #we had to add the tanh to keep this method stable
def forward(self, x, vel_norm, vel, edge_index, edge_attr=None):
row, col = edge_index
edge_m = self.edge_model(x[row], x[col], edge_attr)
x = self.node_model(x, edge_index, edge_m)
x += vel * self.coord_mlp_vel(vel_norm)
return x, edge_attr
def edge_model(self, source, target, edge_attr):
x_diff = source - target
radial = torch.sqrt(torch.sum(x_diff ** 2, dim=1)).unsqueeze(1)
e_input = torch.cat([radial, edge_attr], dim=1)
e_out = self.phi(e_input)
m_ij = x_diff * e_out
return m_ij
def node_model(self, x, edge_index, edge_m):
row, col = edge_index
agg = unsorted_segment_mean(edge_m, row, num_segments=x.size(0))
x_out = x + agg * self.coords_weight
return x_out
def unsorted_segment_sum(data, segment_ids, num_segments):
"""Custom PyTorch op to replicate TensorFlow's `unsorted_segment_sum`."""
result_shape = (num_segments, data.size(1))
result = data.new_full(result_shape, 0) # Init empty result tensor.
segment_ids = segment_ids.unsqueeze(-1).expand(-1, data.size(1))
result.scatter_add_(0, segment_ids, data)
return result
def unsorted_segment_mean(data, segment_ids, num_segments):
result_shape = (num_segments, data.size(1))
segment_ids = segment_ids.unsqueeze(-1).expand(-1, data.size(1))
result = data.new_full(result_shape, 0) # Init empty result tensor.
count = data.new_full(result_shape, 0)
result.scatter_add_(0, segment_ids, data)
count.scatter_add_(0, segment_ids, torch.ones_like(data))
return result / count.clamp(min=1) | 12,996 | 36.02849 | 230 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/property_prediction/models/__init__.py | from .gcl import GCL
| 21 | 10 | 20 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/args.py | import argparse
from math import inf
#### Argument parser ####
def setup_shared_args(parser):
"""
Sets up the argparse object for the qm9 dataset
Parameters
----------
parser : :class:`argparse.ArgumentParser`
Argument Parser with arguments.
Parameters
----------
parser : :class:`argparse.ArgumentParser`
The same Argument Parser, now with more arguments.
"""
# Optimizer options
parser.add_argument('--num-epoch', type=int, default=255, metavar='N',
help='number of epochs to train (default: 511)')
parser.add_argument('--batch-size', '-bs', type=int, default=25, metavar='N',
help='Mini-batch size (default: 25)')
parser.add_argument('--alpha', type=float, default=0.9, metavar='N',
help='Value of alpha to use for exponential moving average of training loss. (default: 0.9)')
parser.add_argument('--weight-decay', type=float, default=0, metavar='N',
help='Set the weight decay used in optimizer (default: 0)')
parser.add_argument('--cutoff-decay', type=float, default=0, metavar='N',
help='Set the weight decay used in optimizer for learnable radial cutoffs (default: 0)')
parser.add_argument('--lr-init', type=float, default=1e-3, metavar='N',
help='Initial learning rate (default: 1e-3)')
parser.add_argument('--lr-final', type=float, default=1e-5, metavar='N',
help='Final (held) learning rate (default: 1e-5)')
parser.add_argument('--lr-decay', type=int, default=inf, metavar='N',
help='Timescale over which to decay the learning rate (default: inf)')
parser.add_argument('--lr-decay-type', type=str, default='cos', metavar='str',
help='Type of learning rate decay. (cos | linear | exponential | pow | restart) (default: cos)')
parser.add_argument('--lr-minibatch', '--lr-mb', action=BoolArg, default=True,
help='Decay learning rate every minibatch instead of epoch.')
parser.add_argument('--sgd-restart', type=int, default=-1, metavar='int',
help='Restart SGD optimizer every (lr_decay)^p epochs, where p=sgd_restart. (-1 to disable) (default: -1)')
parser.add_argument('--optim', type=str, default='amsgrad', metavar='str',
help='Set optimizer. (SGD, AMSgrad, Adam, RMSprop)')
# Dataloader and randomness options
parser.add_argument('--shuffle', action=BoolArg, default=True,
help='Shuffle minibatches.')
parser.add_argument('--seed', type=int, default=1, metavar='N',
help='Set random number seed. Set to -1 to set based upon clock.')
# Saving and logging options
parser.add_argument('--save', action=BoolArg, default=True,
help='Save checkpoint after each epoch. (default: True)')
parser.add_argument('--load', action=BoolArg, default=False,
help='Load from previous checkpoint. (default: False)')
parser.add_argument('--test', action=BoolArg, default=True,
help='Perform automated network testing. (Default: True)')
parser.add_argument('--log-level', type=str, default='info',
help='Logging level to output')
parser.add_argument('--textlog', action=BoolArg, default=True,
help='Log a summary of each mini-batch to a text file.')
parser.add_argument('--predict', action=BoolArg, default=True,
help='Save predictions. (default)')
### Arguments for files to save things to
# Job prefix is used to name checkpoint/best file
parser.add_argument('--prefix', '--jobname', type=str, default='nosave',
help='Prefix to set load, save, and logfile. (default: nosave)')
# Allow to manually specify file to load
parser.add_argument('--loadfile', type=str, default='',
help='Set checkpoint file to load. Leave empty to auto-generate from prefix. (default: (empty))')
# Filename to save model checkpoint to
parser.add_argument('--checkfile', type=str, default='',
help='Set checkpoint file to save checkpoints to. Leave empty to auto-generate from prefix. (default: (empty))')
# Filename to best model checkpoint to
parser.add_argument('--bestfile', type=str, default='',
help='Set checkpoint file to best model to. Leave empty to auto-generate from prefix. (default: (empty))')
# Filename to save logging information to
parser.add_argument('--logfile', type=str, default='',
help='Duplicate logging.info output to logfile. Set to empty string to generate from prefix. (default: (empty))')
# Filename to save predictions to
parser.add_argument('--predictfile', type=str, default='',
help='Save predictions to file. Set to empty string to generate from prefix. (default: (empty))')
# Working directory to place all files
parser.add_argument('--workdir', type=str, default='./',
help='Working directory as a default location for all files. (default: ./)')
# Directory to place logging information
parser.add_argument('--logdir', type=str, default='log/',
help='Directory to place log and savefiles. (default: log/)')
# Directory to place saved models
parser.add_argument('--modeldir', type=str, default='model/',
help='Directory to place log and savefiles. (default: model/)')
# Directory to place model predictions
parser.add_argument('--predictdir', type=str, default='predict/',
help='Directory to place log and savefiles. (default: predict/)')
# Directory to read and save data from
parser.add_argument('--datadir', type=str, default='qm9/temp',
help='Directory to look up data from. (default: data/)')
# Dataset options
parser.add_argument('--num-train', type=int, default=-1, metavar='N',
help='Number of samples to train on. Set to -1 to use entire dataset. (default: -1)')
parser.add_argument('--num-valid', type=int, default=-1, metavar='N',
help='Number of validation samples to use. Set to -1 to use entire dataset. (default: -1)')
parser.add_argument('--num-test', type=int, default=-1, metavar='N',
help='Number of test samples to use. Set to -1 to use entire dataset. (default: -1)')
parser.add_argument('--force-download', action=BoolArg, default=False,
help='Force download and processing of dataset.')
# Computation options
parser.add_argument('--cuda', dest='cuda', action='store_true',
help='Use CUDA (default)')
parser.add_argument('--no-cuda', '--cpu', dest='cuda', action='store_false',
help='Use CPU')
parser.set_defaults(cuda=True)
parser.add_argument('--float', dest='dtype', action='store_const', const='float',
help='Use floats.')
parser.add_argument('--double', dest='dtype', action='store_const', const='double',
help='Use doubles.')
parser.set_defaults(dtype='float')
parser.add_argument('--num-workers', type=int, default=8,
help='Set number of workers in dataloader. (Default: 1)')
# Model options
parser.add_argument('--num-cg-levels', type=int, default=4, metavar='N',
help='Number of CG levels (default: 4)')
parser.add_argument('--maxl', nargs='*', type=int, default=[3], metavar='N',
help='Cutoff in CG operations (default: [3])')
parser.add_argument('--max-sh', nargs='*', type=int, default=[3], metavar='N',
help='Number of spherical harmonic powers to use (default: [3])')
parser.add_argument('--num-channels', nargs='*', type=int, default=[10], metavar='N',
help='Number of channels to allow after mixing (default: [10])')
parser.add_argument('--level-gain', nargs='*', type=float, default=[10.], metavar='N',
help='Gain at each level (default: [10.])')
parser.add_argument('--charge-power', type=int, default=2, metavar='N',
help='Maximum power to take in one-hot (default: 2)')
parser.add_argument('--hard-cutoff', dest='hard_cut_rad',
type=float, default=1.73, nargs='*', metavar='N',
help='Radius of HARD cutoff in Angstroms (default: 1.73)')
parser.add_argument('--soft-cutoff', dest='soft_cut_rad', type=float,
default=1.73, nargs='*', metavar='N',
help='Radius of SOFT cutoff in Angstroms (default: 1.73)')
parser.add_argument('--soft-width', dest='soft_cut_width',
type=float, default=0.2, nargs='*', metavar='N',
help='Width of SOFT cutoff in Angstroms (default: 0.2)')
parser.add_argument('--cutoff-type', '--cutoff', type=str, default=['learn'], nargs='*', metavar='str',
help='Types of cutoffs to include')
parser.add_argument('--basis-set', '--krange', type=int, default=[3, 3], nargs=2, metavar='N',
help='Radial function basis set (m, n) size (default: [3, 3])')
# TODO: Update(?)
parser.add_argument('--weight-init', type=str, default='rand', metavar='str',
help='Weight initialization function to use (default: rand)')
parser.add_argument('--input', type=str, default='linear',
help='Function to apply to process l0 input (linear | MPNN) default: linear')
parser.add_argument('--num-mpnn-levels', type=int, default=1,
help='Number levels to use in input featurization MPNN. (default: 1)')
parser.add_argument('--top', '--output', type=str, default='linear',
help='Top function to use (linear | PMLP) default: linear')
parser.add_argument('--gaussian-mask', action='store_true',
help='Use gaussian mask instead of sigmoid mask.')
parser.add_argument('--edge-cat', action='store_true',
help='Concatenate the scalars from different \ell in the dot-product-matrix part of the edge network.')
parser.add_argument('--target', type=str, default='',
help='Learning target for a dataset (such as qm9) with multiple options.')
return parser
def setup_argparse(dataset):
"""
Sets up the argparse object for a specific dataset.
Parameters
----------
dataset : :class:`str`
Dataset being used. Currently MD17 and QM9 are supported.
Returns
-------
parser : :class:`argparse.ArgumentParser`
Argument Parser with arguments.
"""
parser = argparse.ArgumentParser(description='Cormorant network options for the md17 dataset.')
parser = setup_shared_args(parser)
if dataset == "md17":
parser.add_argument('--subset', '--molecule', type=str, default='',
help='Subset/molecule on data with subsets (such as md17).')
elif dataset == "qm9":
parser.add_argument('--subtract-thermo', action=BoolArg, default=True,
help='Subtract thermochemical energy from relvant learning targets in QM9 dataset.')
else:
raise ValueError("Dataset is not recognized")
return parser
###
class BoolArg(argparse.Action):
"""
Take an argparse argument that is either a boolean or a string and return a boolean.
"""
def __init__(self, default=None, nargs=None, *args, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
# Set default
if default is None:
raise ValueError("Default must be set!")
default = _arg_to_bool(default)
super().__init__(*args, default=default, nargs='?', **kwargs)
def __call__(self, parser, namespace, argstring, option_string):
if argstring is not None:
# If called with an argument, convert to bool
argval = _arg_to_bool(argstring)
else:
# BoolArg will invert default option
argval = True
setattr(namespace, self.dest, argval)
def _arg_to_bool(arg):
# Convert argument to boolean
if type(arg) is bool:
# If argument is bool, just return it
return arg
elif type(arg) is str:
# If string, convert to true/false
arg = arg.lower()
if arg in ['true', 't', '1']:
return True
elif arg in ['false', 'f', '0']:
return False
else:
return ValueError('Could not parse a True/False boolean')
else:
raise ValueError('Input must be boolean or string! {}'.format(type(arg)))
# From https://stackoverflow.com/questions/12116685/how-can-i-require-my-python-scripts-argument-to-be-a-float-between-0-0-1-0-usin
class Range(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __eq__(self, other):
return self.start <= other <= self.end
def init_argparse(dataset):
"""
Reads in the arguments for the script for a given dataset.
Parameters
----------
dataset : :class:`str`
Dataset being used. Currently 'md17' and 'qm9' are supported.
Returns
-------
args : :class:`Namespace`
Namespace with a dictionary of arguments where the key is the name of
the argument and the item is the input value.
"""
parser = setup_argparse(dataset)
args = parser.parse_args([])
d = vars(args)
d['dataset'] = dataset
return args | 14,008 | 46.488136 | 137 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/utils.py | import torch
import numpy as np
import logging
import os
from torch.utils.data import DataLoader
from qm9.data.dataset_class import ProcessedDataset
from qm9.data.prepare import prepare_dataset
def initialize_datasets(args, datadir, dataset, subset=None, splits=None,
force_download=False, subtract_thermo=False,
remove_h=False):
"""
Initialize datasets.
Parameters
----------
args : dict
Dictionary of input arguments detailing the cormorant calculation.
datadir : str
Path to the directory where the data and calculations and is, or will be, stored.
dataset : str
String specification of the dataset. If it is not already downloaded, must currently by "qm9" or "md17".
subset : str, optional
Which subset of a dataset to use. Action is dependent on the dataset given.
Must be specified if the dataset has subsets (i.e. MD17). Otherwise ignored (i.e. GDB9).
splits : str, optional
TODO: DELETE THIS ENTRY
force_download : bool, optional
If true, forces a fresh download of the dataset.
subtract_thermo : bool, optional
If True, subtracts the thermochemical energy of the atoms from each molecule in GDB9.
Does nothing for other datasets.
remove_h: bool, optional
If True, remove hydrogens from the dataset
Returns
-------
args : dict
Dictionary of input arguments detailing the cormorant calculation.
datasets : dict
Dictionary of processed dataset objects (see ????? for more information).
Valid keys are "train", "test", and "valid"[ate]. Each associated value
num_species : int
Number of unique atomic species in the dataset.
max_charge : pytorch.Tensor
Largest atomic number for the dataset.
Notes
-----
TODO: Delete the splits argument.
"""
# Set the number of points based upon the arguments
num_pts = {'train': args.num_train,
'test': args.num_test, 'valid': args.num_valid}
# Download and process dataset. Returns datafiles.
datafiles = prepare_dataset(
datadir, 'qm9', subset, splits, force_download=force_download)
# Load downloaded/processed datasets
datasets = {}
for split, datafile in datafiles.items():
with np.load(datafile) as f:
datasets[split] = {key: torch.from_numpy(
val) for key, val in f.items()}
if dataset != 'qm9':
np.random.seed(42)
fixed_perm = np.random.permutation(len(datasets['train']['num_atoms']))
if dataset == 'qm9_second_half':
sliced_perm = fixed_perm[len(datasets['train']['num_atoms'])//2:]
elif dataset == 'qm9_first_half':
sliced_perm = fixed_perm[0:len(datasets['train']['num_atoms']) // 2]
else:
raise Exception('Wrong dataset name')
for key in datasets['train']:
datasets['train'][key] = datasets['train'][key][sliced_perm]
# Basic error checking: Check the training/test/validation splits have the same set of keys.
keys = [list(data.keys()) for data in datasets.values()]
assert all([key == keys[0] for key in keys]
), 'Datasets must have same set of keys!'
# TODO: remove hydrogens here if needed
if remove_h:
for key, dataset in datasets.items():
pos = dataset['positions']
charges = dataset['charges']
num_atoms = dataset['num_atoms']
# Check that charges corresponds to real atoms
assert torch.sum(num_atoms != torch.sum(charges > 0, dim=1)) == 0
mask = dataset['charges'] > 1
new_positions = torch.zeros_like(pos)
new_charges = torch.zeros_like(charges)
for i in range(new_positions.shape[0]):
m = mask[i]
p = pos[i][m] # positions to keep
p = p - torch.mean(p, dim=0) # Center the new positions
c = charges[i][m] # Charges to keep
n = torch.sum(m)
new_positions[i, :n, :] = p
new_charges[i, :n] = c
dataset['positions'] = new_positions
dataset['charges'] = new_charges
dataset['num_atoms'] = torch.sum(dataset['charges'] > 0, dim=1)
# Get a list of all species across the entire dataset
all_species = _get_species(datasets, ignore_check=False)
# Now initialize MolecularDataset based upon loaded data
datasets = {split: ProcessedDataset(data, num_pts=num_pts.get(
split, -1), included_species=all_species, subtract_thermo=subtract_thermo) for split, data in datasets.items()}
# Now initialize MolecularDataset based upon loaded data
# Check that all datasets have the same included species:
assert(len(set(tuple(data.included_species.tolist()) for data in datasets.values())) ==
1), 'All datasets must have same included_species! {}'.format({key: data.included_species for key, data in datasets.items()})
# These parameters are necessary to initialize the network
num_species = datasets['train'].num_species
max_charge = datasets['train'].max_charge
# Now, update the number of training/test/validation sets in args
args.num_train = datasets['train'].num_pts
args.num_valid = datasets['valid'].num_pts
args.num_test = datasets['test'].num_pts
return args, datasets, num_species, max_charge
def _get_species(datasets, ignore_check=False):
"""
Generate a list of all species.
Includes a check that each split contains examples of every species in the
entire dataset.
Parameters
----------
datasets : dict
Dictionary of datasets. Each dataset is a dict of arrays containing molecular properties.
ignore_check : bool
Ignores/overrides checks to make sure every split includes every species included in the entire dataset
Returns
-------
all_species : Pytorch tensor
List of all species present in the data. Species labels shoguld be integers.
"""
# Get a list of all species in the dataset across all splits
all_species = torch.cat([dataset['charges'].unique()
for dataset in datasets.values()]).unique(sorted=True)
# Find the unique list of species in each dataset.
split_species = {split: species['charges'].unique(
sorted=True) for split, species in datasets.items()}
# If zero charges (padded, non-existent atoms) are included, remove them
if all_species[0] == 0:
all_species = all_species[1:]
# Remove zeros if zero-padded charges exst for each split
split_species = {split: species[1:] if species[0] ==
0 else species for split, species in split_species.items()}
# Now check that each split has at least one example of every atomic spcies from the entire dataset.
if not all([split.tolist() == all_species.tolist() for split in split_species.values()]):
# Allows one to override this check if they really want to. Not recommended as the answers become non-sensical.
if ignore_check:
logging.error(
'The number of species is not the same in all datasets!')
else:
raise ValueError(
'Not all datasets have the same number of species!')
# Finally, return a list of all species
return all_species
| 7,481 | 39.443243 | 136 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/collate.py | import torch
def batch_stack(props):
"""
Stack a list of torch.tensors so they are padded to the size of the
largest tensor along each axis.
Parameters
----------
props : list of Pytorch Tensors
Pytorch tensors to stack
Returns
-------
props : Pytorch tensor
Stacked pytorch tensor.
Notes
-----
TODO : Review whether the behavior when elements are not tensors is safe.
"""
if not torch.is_tensor(props[0]):
return torch.tensor(props)
elif props[0].dim() == 0:
return torch.stack(props)
else:
return torch.nn.utils.rnn.pad_sequence(props, batch_first=True, padding_value=0)
def drop_zeros(props, to_keep):
"""
Function to drop zeros from batches when the entire dataset is padded to the largest molecule size.
Parameters
----------
props : Pytorch tensor
Full Dataset
Returns
-------
props : Pytorch tensor
The dataset with only the retained information.
Notes
-----
TODO : Review whether the behavior when elements are not tensors is safe.
"""
if not torch.is_tensor(props[0]):
return props
elif props[0].dim() == 0:
return props
else:
return props[:, to_keep, ...]
class PreprocessQM9:
def __init__(self, load_charges=True):
self.load_charges = load_charges
def add_trick(self, trick):
self.tricks.append(trick)
def collate_fn(self, batch):
"""
Collation function that collates datapoints into the batch format for cormorant
Parameters
----------
batch : list of datapoints
The data to be collated.
Returns
-------
batch : dict of Pytorch tensors
The collated data.
"""
batch = {prop: batch_stack([mol[prop] for mol in batch]) for prop in batch[0].keys()}
to_keep = (batch['charges'].sum(0) > 0)
batch = {key: drop_zeros(prop, to_keep) for key, prop in batch.items()}
atom_mask = batch['charges'] > 0
batch['atom_mask'] = atom_mask
#Obtain edges
batch_size, n_nodes = atom_mask.size()
edge_mask = atom_mask.unsqueeze(1) * atom_mask.unsqueeze(2)
#mask diagonal
diag_mask = ~torch.eye(edge_mask.size(1), dtype=torch.bool).unsqueeze(0)
edge_mask *= diag_mask
#edge_mask = atom_mask.unsqueeze(1) * atom_mask.unsqueeze(2)
batch['edge_mask'] = edge_mask.view(batch_size * n_nodes * n_nodes, 1)
if self.load_charges:
batch['charges'] = batch['charges'].unsqueeze(2)
else:
batch['charges'] = torch.zeros(0)
return batch
| 2,718 | 25.144231 | 103 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/__init__.py | from qm9.data.utils import initialize_datasets
from qm9.data.collate import PreprocessQM9
from qm9.data.dataset_class import ProcessedDataset | 141 | 46.333333 | 51 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/dataset_class.py | import torch
from torch.utils.data import Dataset
import os
from itertools import islice
from math import inf
import logging
class ProcessedDataset(Dataset):
"""
Data structure for a pre-processed cormorant dataset. Extends PyTorch Dataset.
Parameters
----------
data : dict
Dictionary of arrays containing molecular properties.
included_species : tensor of scalars, optional
Atomic species to include in ?????. If None, uses all species.
num_pts : int, optional
Desired number of points to include in the dataset.
Default value, -1, uses all of the datapoints.
normalize : bool, optional
????? IS THIS USED?
shuffle : bool, optional
If true, shuffle the points in the dataset.
subtract_thermo : bool, optional
If True, subtracts the thermochemical energy of the atoms from each molecule in GDB9.
Does nothing for other datasets.
"""
def __init__(self, data, included_species=None, num_pts=-1, normalize=True, shuffle=True, subtract_thermo=True):
self.data = data
if num_pts < 0:
self.num_pts = len(data['charges'])
else:
if num_pts > len(data['charges']):
logging.warning('Desired number of points ({}) is greater than the number of data points ({}) available in the dataset!'.format(num_pts, len(data['charges'])))
self.num_pts = len(data['charges'])
else:
self.num_pts = num_pts
# If included species is not specified
if included_species is None:
included_species = torch.unique(self.data['charges'], sorted=True)
if included_species[0] == 0:
included_species = included_species[1:]
if subtract_thermo:
thermo_targets = [key.split('_')[0] for key in data.keys() if key.endswith('_thermo')]
if len(thermo_targets) == 0:
logging.warning('No thermochemical targets included! Try reprocessing dataset with --force-download!')
else:
logging.info('Removing thermochemical energy from targets {}'.format(' '.join(thermo_targets)))
for key in thermo_targets:
data[key] -= data[key + '_thermo'].to(data[key].dtype)
self.included_species = included_species
self.data['one_hot'] = self.data['charges'].unsqueeze(-1) == included_species.unsqueeze(0).unsqueeze(0)
self.num_species = len(included_species)
self.max_charge = max(included_species)
self.parameters = {'num_species': self.num_species, 'max_charge': self.max_charge}
# Get a dictionary of statistics for all properties that are one-dimensional tensors.
self.calc_stats()
if shuffle:
self.perm = torch.randperm(len(data['charges']))[:self.num_pts]
else:
self.perm = None
def calc_stats(self):
self.stats = {key: (val.mean(), val.std()) for key, val in self.data.items() if type(val) is torch.Tensor and val.dim() == 1 and val.is_floating_point()}
def convert_units(self, units_dict):
for key in self.data.keys():
if key in units_dict:
self.data[key] *= units_dict[key]
self.calc_stats()
def __len__(self):
return self.num_pts
def __getitem__(self, idx):
if self.perm is not None:
idx = self.perm[idx]
return {key: val[idx] for key, val in self.data.items()}
| 3,510 | 36.351064 | 175 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/prepare/md17.py | from os.path import join as join
import urllib.request
import numpy as np
import torch
import logging, os, urllib
from qm9.data.prepare.utils import download_data, is_int, cleanup_file
md17_base_url = 'http://quantum-machine.org/gdml/data/npz/'
md17_subsets = {'benzene': 'benzene_old_dft',
'uracil': 'uracil_dft',
'naphthalene': 'naphthalene_dft',
'aspirin': 'aspirin_dft',
'salicylic_acid': 'salicylic_dft',
'malonaldehyde': 'malonaldehyde_dft',
'ethanol': 'ethanol_dft',
'toluene': 'toluene_dft',
'paracetamol': 'paracetamol_dft',
'azobenzene': 'azobenzene_dft'
}
def download_dataset_md17(datadir, dataname, subset, splits=None, cleanup=True):
"""
Downloads the MD17 dataset.
"""
if subset not in md17_subsets:
logging.info('Molecule {} not included in list of downloadable MD17 datasets! Attempting to download based directly upon input key.'.format(subset))
md17_molecule = subset
else:
md17_molecule = md17_subsets[subset]
# Define directory for which data will be output.
md17dir = join(*[datadir, dataname, subset])
# Important to avoid a race condition
os.makedirs(md17dir, exist_ok=True)
logging.info('Downloading and processing molecule {} from MD17 dataset. Output will be in directory: {}.'.format(subset, md17dir))
md17_data_url = md17_base_url + md17_molecule + '.npz'
md17_data_npz = join(md17dir, md17_molecule + '.npz')
download_data(md17_data_url, outfile=md17_data_npz, binary=True)
# Convert raw MD17 data to torch tensors.
md17_raw_data = np.load(md17_data_npz)
# Number of molecules in dataset:
num_tot_mols = len(md17_raw_data['E'])
# Dictionary to convert keys in MD17 database to those used in this code.
md17_keys = {'E': 'energies', 'R': 'positions', 'F': 'forces'}
# Convert numpy arrays to torch.Tensors
md17_data = {new_key: md17_raw_data[old_key] for old_key, new_key in md17_keys.items()}
# Reshape energies to remove final singleton dimension
md17_data['energies'] = md17_data['energies'].squeeze(1)
# Add charges to md17_data
md17_data['charges'] = np.tile(md17_raw_data['z'], (num_tot_mols, 1))
# If splits are not specified, automatically generate them.
if splits is None:
splits = gen_splits_md17(num_tot_mols)
# Process GDB9 dataset, and return dictionary of splits
md17_data_split = {}
for split, split_idx in splits.items():
md17_data_split[split] = {key: val[split_idx] if type(val) is np.ndarray else val for key, val in md17_data.items()}
# Save processed GDB9 data into train/validation/test splits
logging.info('Saving processed data:')
for split, data_split in md17_data_split.items():
savefile = join(md17dir, split + '.npz')
np.savez_compressed(savefile, **data_split)
cleanup_file(md17_data_npz, cleanup)
def gen_splits_md17(num_pts):
"""
Generate the splits used to train/evaluate the network in the original Cormorant paper.
"""
# deterministically generate random split based upon random permutation
np.random.seed(0)
data_perm = np.random.permutation(num_pts)
# Create masks for which splits to invoke
mask_train = np.zeros(num_pts, dtype=np.bool)
mask_valid = np.zeros(num_pts, dtype=np.bool)
mask_test = np.zeros(num_pts, dtype=np.bool)
# For historical reasons, this is the indexing on the
# 50k/10k/10k train/valid/test splits used in the paper.
mask_train[:10000] = True
mask_valid[10000:20000] = True
mask_test[20000:30000] = True
mask_train[30000:70000] = True
# COnvert masks to splits
splits = {}
splits['train'] = torch.tensor(data_perm[mask_train])
splits['valid'] = torch.tensor(data_perm[mask_valid])
splits['test'] = torch.tensor(data_perm[mask_test])
return splits
| 3,992 | 34.972973 | 156 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/prepare/qm9.py | import numpy as np
import torch
import logging
import os
import urllib
from os.path import join as join
import urllib.request
from qm9.data.prepare.process import process_xyz_files, process_xyz_gdb9
from qm9.data.prepare.utils import download_data, is_int, cleanup_file
def download_dataset_qm9(datadir, dataname, splits=None, calculate_thermo=True, exclude=True, cleanup=True):
"""
Download and prepare the QM9 (GDB9) dataset.
"""
# Define directory for which data will be output.
gdb9dir = join(*[datadir, dataname])
# Important to avoid a race condition
os.makedirs(gdb9dir, exist_ok=True)
logging.info(
'Downloading and processing GDB9 dataset. Output will be in directory: {}.'.format(gdb9dir))
logging.info('Beginning download of GDB9 dataset!')
gdb9_url_data = 'https://springernature.figshare.com/ndownloader/files/3195389'
gdb9_tar_data = join(gdb9dir, 'dsgdb9nsd.xyz.tar.bz2')
# gdb9_tar_file = join(gdb9dir, 'dsgdb9nsd.xyz.tar.bz2')
# gdb9_tar_data =
# tardata = tarfile.open(gdb9_tar_file, 'r')
# files = tardata.getmembers()
urllib.request.urlretrieve(gdb9_url_data, filename=gdb9_tar_data)
logging.info('GDB9 dataset downloaded successfully!')
# If splits are not specified, automatically generate them.
if splits is None:
splits = gen_splits_gdb9(gdb9dir, cleanup)
# Process GDB9 dataset, and return dictionary of splits
gdb9_data = {}
for split, split_idx in splits.items():
gdb9_data[split] = process_xyz_files(
gdb9_tar_data, process_xyz_gdb9, file_idx_list=split_idx, stack=True)
# Subtract thermochemical energy if desired.
if calculate_thermo:
# Download thermochemical energy from GDB9 dataset, and then process it into a dictionary
therm_energy = get_thermo_dict(gdb9dir, cleanup)
# For each of train/validation/test split, add the thermochemical energy
for split_idx, split_data in gdb9_data.items():
gdb9_data[split_idx] = add_thermo_targets(split_data, therm_energy)
# Save processed GDB9 data into train/validation/test splits
logging.info('Saving processed data:')
for split, data in gdb9_data.items():
savedir = join(gdb9dir, split+'.npz')
np.savez_compressed(savedir, **data)
logging.info('Processing/saving complete!')
def gen_splits_gdb9(gdb9dir, cleanup=True):
"""
Generate GDB9 training/validation/test splits used.
First, use the file 'uncharacterized.txt' in the GDB9 figshare to find a
list of excluded molecules.
Second, create a list of molecule ids, and remove the excluded molecule
indices.
Third, assign 100k molecules to the training set, 10% to the test set,
and the remaining to the validation set.
Finally, generate torch.tensors which give the molecule ids for each
set.
"""
logging.info('Splits were not specified! Automatically generating.')
gdb9_url_excluded = 'https://springernature.figshare.com/ndownloader/files/3195404'
gdb9_txt_excluded = join(gdb9dir, 'uncharacterized.txt')
urllib.request.urlretrieve(gdb9_url_excluded, filename=gdb9_txt_excluded)
# First get list of excluded indices
excluded_strings = []
with open(gdb9_txt_excluded) as f:
lines = f.readlines()
excluded_strings = [line.split()[0]
for line in lines if len(line.split()) > 0]
excluded_idxs = [int(idx) - 1 for idx in excluded_strings if is_int(idx)]
assert len(excluded_idxs) == 3054, 'There should be exactly 3054 excluded atoms. Found {}'.format(
len(excluded_idxs))
# Now, create a list of indices
Ngdb9 = 133885
Nexcluded = 3054
included_idxs = np.array(
sorted(list(set(range(Ngdb9)) - set(excluded_idxs))))
# Now generate random permutations to assign molecules to training/validation/test sets.
Nmols = Ngdb9 - Nexcluded
Ntrain = 100000
Ntest = int(0.1*Nmols)
Nvalid = Nmols - (Ntrain + Ntest)
# Generate random permutation
np.random.seed(0)
data_perm = np.random.permutation(Nmols)
# Now use the permutations to generate the indices of the dataset splits.
# train, valid, test, extra = np.split(included_idxs[data_perm], [Ntrain, Ntrain+Nvalid, Ntrain+Nvalid+Ntest])
train, valid, test, extra = np.split(
data_perm, [Ntrain, Ntrain+Nvalid, Ntrain+Nvalid+Ntest])
assert(len(extra) == 0), 'Split was inexact {} {} {} {}'.format(
len(train), len(valid), len(test), len(extra))
train = included_idxs[train]
valid = included_idxs[valid]
test = included_idxs[test]
splits = {'train': train, 'valid': valid, 'test': test}
# Cleanup
cleanup_file(gdb9_txt_excluded, cleanup)
return splits
def get_thermo_dict(gdb9dir, cleanup=True):
"""
Get dictionary of thermochemical energy to subtract off from
properties of molecules.
Probably would be easier just to just precompute this and enter it explicitly.
"""
# Download thermochemical energy
logging.info('Downloading thermochemical energy.')
gdb9_url_thermo = 'https://springernature.figshare.com/ndownloader/files/3195395'
gdb9_txt_thermo = join(gdb9dir, 'atomref.txt')
urllib.request.urlretrieve(gdb9_url_thermo, filename=gdb9_txt_thermo)
# Loop over file of thermochemical energies
therm_targets = ['zpve', 'U0', 'U', 'H', 'G', 'Cv']
# Dictionary that
id2charge = {'H': 1, 'C': 6, 'N': 7, 'O': 8, 'F': 9}
# Loop over file of thermochemical energies
therm_energy = {target: {} for target in therm_targets}
with open(gdb9_txt_thermo) as f:
for line in f:
# If line starts with an element, convert the rest to a list of energies.
split = line.split()
# Check charge corresponds to an atom
if len(split) == 0 or split[0] not in id2charge.keys():
continue
# Loop over learning targets with defined thermochemical energy
for therm_target, split_therm in zip(therm_targets, split[1:]):
therm_energy[therm_target][id2charge[split[0]]
] = float(split_therm)
# Cleanup file when finished.
cleanup_file(gdb9_txt_thermo, cleanup)
return therm_energy
def add_thermo_targets(data, therm_energy_dict):
"""
Adds a new molecular property, which is the thermochemical energy.
Parameters
----------
data : ?????
QM9 dataset split.
therm_energy : dict
Dictionary of thermochemical energies for relevant properties found using :get_thermo_dict:
"""
# Get the charge and number of charges
charge_counts = get_unique_charges(data['charges'])
# Now, loop over the targets with defined thermochemical energy
for target, target_therm in therm_energy_dict.items():
thermo = np.zeros(len(data[target]))
# Loop over each charge, and multiplicity of the charge
for z, num_z in charge_counts.items():
if z == 0:
continue
# Now add the thermochemical energy per atomic charge * the number of atoms of that type
thermo += target_therm[z] * num_z
# Now add the thermochemical energy as a property
data[target + '_thermo'] = thermo
return data
def get_unique_charges(charges):
"""
Get count of each charge for each molecule.
"""
# Create a dictionary of charges
charge_counts = {z: np.zeros(len(charges), dtype=np.int)
for z in np.unique(charges)}
print(charge_counts.keys())
# Loop over molecules, for each molecule get the unique charges
for idx, mol_charges in enumerate(charges):
# For each molecule, get the unique charge and multiplicity
for z, num_z in zip(*np.unique(mol_charges, return_counts=True)):
# Store the multiplicity of each charge in charge_counts
charge_counts[z][idx] = num_z
return charge_counts
| 8,060 | 34.355263 | 114 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/prepare/download.py | import logging
import os
from qm9.data.prepare.md17 import download_dataset_md17
from qm9.data.prepare.qm9 import download_dataset_qm9
def prepare_dataset(datadir, dataset, subset=None, splits=None, cleanup=True, force_download=False):
"""
Download and process dataset.
Parameters
----------
datadir : str
Path to the directory where the data and calculations and is, or will be, stored.
dataset : str
String specification of the dataset. If it is not already downloaded, must currently by "qm9" or "md17".
subset : str, optional
Which subset of a dataset to use. Action is dependent on the dataset given.
Must be specified if the dataset has subsets (i.e. MD17). Otherwise ignored (i.e. GDB9).
splits : dict, optional
Dataset splits to use.
cleanup : bool, optional
Clean up files created while preparing the data.
force_download : bool, optional
If true, forces a fresh download of the dataset.
Returns
-------
datafiles : dict of strings
Dictionary of strings pointing to the files containing the data.
Notes
-----
TODO: Delete the splits argument?
"""
# If datasets have subsets,
if subset:
dataset_dir = [datadir, dataset, subset]
else:
dataset_dir = [datadir, dataset]
# Names of splits, based upon keys if split dictionary exists, elsewise default to train/valid/test.
split_names = splits.keys() if splits is not None else [
'train', 'valid', 'test']
# Assume one data file for each split
datafiles = {split: os.path.join(
*(dataset_dir + [split + '.npz'])) for split in split_names}
# Check datafiles exist
datafiles_checks = [os.path.exists(datafile)
for datafile in datafiles.values()]
# Check if prepared dataset exists, and if not set flag to download below.
# Probably should add more consistency checks, such as number of datapoints, etc...
new_download = False
if all(datafiles_checks):
logging.info('Dataset exists and is processed.')
elif all([not x for x in datafiles_checks]):
# If checks are failed.
new_download = True
else:
raise ValueError(
'Dataset only partially processed. Try deleting {} and running again to download/process.'.format(os.path.join(dataset_dir)))
# If need to download dataset, pass to appropriate downloader
if new_download or force_download:
logging.info('Dataset does not exist. Downloading!')
if dataset.lower().startswith('qm9'):
download_dataset_qm9(datadir, dataset, splits, cleanup=cleanup)
elif dataset.lower().startswith('md17'):
download_dataset_md17(datadir, dataset, subset,
splits, cleanup=cleanup)
else:
raise ValueError(
'Incorrect choice of dataset! Must chose qm9/md17!')
return datafiles
| 2,990 | 35.925926 | 137 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/prepare/utils.py | import os, logging
from urllib.request import urlopen
def download_data(url, outfile='', binary=False):
"""
Downloads data from a URL and returns raw data.
Parameters
----------
url : str
URL to get the data from
outfile : str, optional
Where to save the data.
binary : bool, optional
If true, writes data in binary.
"""
# Try statement to catch downloads.
try:
# Download url using urlopen
with urlopen(url) as f:
data = f.read()
logging.info('Data download success!')
success = True
except:
logging.info('Data download failed!')
success = False
if binary:
# If data is binary, use 'wb' if outputting to file
writeflag = 'wb'
else:
# If data is string, convert to string and use 'w' if outputting to file
writeflag = 'w'
data = data.decode('utf-8')
if outfile:
logging.info('Saving downloaded data to file: {}'.format(outfile))
with open(outfile, writeflag) as f:
f.write(data)
return data, success
# Check if a string can be converted to an int, without throwing an error.
def is_int(str):
try:
int(str)
return True
except:
return False
# Cleanup. Use try-except to avoid race condition.
def cleanup_file(file, cleanup=True):
if cleanup:
try:
os.remove(file)
except OSError:
pass
| 1,480 | 23.278689 | 80 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/prepare/__init__.py | from qm9.data.prepare.download import *
from qm9.data.prepare.process import *
from qm9.data.prepare.qm9 import *
from qm9.data.prepare.md17 import *
| 150 | 29.2 | 39 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/qm9/data/prepare/process.py | import logging
import os
import torch
import tarfile
from torch.nn.utils.rnn import pad_sequence
charge_dict = {'H': 1, 'C': 6, 'N': 7, 'O': 8, 'F': 9}
def split_dataset(data, split_idxs):
"""
Splits a dataset according to the indices given.
Parameters
----------
data : dict
Dictionary to split.
split_idxs : dict
Dictionary defining the split. Keys are the name of the split, and
values are the keys for the items in data that go into the split.
Returns
-------
split_dataset : dict
The split dataset.
"""
split_data = {}
for set, split in split_idxs.items():
split_data[set] = {key: val[split] for key, val in data.items()}
return split_data
# def save_database()
def process_xyz_files(data, process_file_fn, file_ext=None, file_idx_list=None, stack=True):
"""
Take a set of datafiles and apply a predefined data processing script to each
one. Data can be stored in a directory, tarfile, or zipfile. An optional
file extension can be added.
Parameters
----------
data : str
Complete path to datafiles. Files must be in a directory, tarball, or zip archive.
process_file_fn : callable
Function to process files. Can be defined externally.
Must input a file, and output a dictionary of properties, each of which
is a torch.tensor. Dictionary must contain at least three properties:
{'num_elements', 'charges', 'positions'}
file_ext : str, optional
Optionally add a file extension if multiple types of files exist.
file_idx_list : ?????, optional
Optionally add a file filter to check a file index is in a
predefined list, for example, when constructing a train/valid/test split.
stack : bool, optional
?????
"""
logging.info('Processing data file: {}'.format(data))
if tarfile.is_tarfile(data):
tardata = tarfile.open(data, 'r')
files = tardata.getmembers()
readfile = lambda data_pt: tardata.extractfile(data_pt)
elif os.is_dir(data):
files = os.listdir(data)
files = [os.path.join(data, file) for file in files]
readfile = lambda data_pt: open(data_pt, 'r')
else:
raise ValueError('Can only read from directory or tarball archive!')
# Use only files that end with specified extension.
if file_ext is not None:
files = [file for file in files if file.endswith(file_ext)]
# Use only files that match desired filter.
if file_idx_list is not None:
files = [file for idx, file in enumerate(files) if idx in file_idx_list]
# Now loop over files using readfile function defined above
# Process each file accordingly using process_file_fn
molecules = []
for file in files:
with readfile(file) as openfile:
molecules.append(process_file_fn(openfile))
# Check that all molecules have the same set of items in their dictionary:
props = molecules[0].keys()
assert all(props == mol.keys() for mol in molecules), 'All molecules must have same set of properties/keys!'
# Convert list-of-dicts to dict-of-lists
molecules = {prop: [mol[prop] for mol in molecules] for prop in props}
# If stacking is desireable, pad and then stack.
if stack:
molecules = {key: pad_sequence(val, batch_first=True) if val[0].dim() > 0 else torch.stack(val) for key, val in molecules.items()}
return molecules
def process_xyz_md17(datafile):
"""
Read xyz file and return a molecular dict with number of atoms, energy, forces, coordinates and atom-type for the MD-17 dataset.
Parameters
----------
datafile : python file object
File object containing the molecular data in the MD17 dataset.
Returns
-------
molecule : dict
Dictionary containing the molecular properties of the associated file object.
"""
xyz_lines = [line.decode('UTF-8') for line in datafile.readlines()]
line_counter = 0
atom_positions = []
atom_types = []
for line in xyz_lines:
if line[0] is '#':
continue
if line_counter is 0:
num_atoms = int(line)
elif line_counter is 1:
split = line.split(';')
assert (len(split) == 1 or len(split) == 2), 'Improperly formatted energy/force line.'
if (len(split) == 1):
e = split[0]
f = None
elif (len(split) == 2):
e, f = split
f = f.split('],[')
atom_energy = float(e)
atom_forces = [[float(x.strip('[]\n')) for x in force.split(',')] for force in f]
else:
split = line.split()
if len(split) is 4:
type, x, y, z = split
atom_types.append(split[0])
atom_positions.append([float(x) for x in split[1:]])
else:
logging.debug(line)
line_counter += 1
atom_charges = [charge_dict[type] for type in atom_types]
molecule = {'num_atoms': num_atoms, 'energy': atom_energy, 'charges': atom_charges,
'forces': atom_forces, 'positions': atom_positions}
molecule = {key: torch.tensor(val) for key, val in molecule.items()}
return molecule
def process_xyz_gdb9(datafile):
"""
Read xyz file and return a molecular dict with number of atoms, energy, forces, coordinates and atom-type for the gdb9 dataset.
Parameters
----------
datafile : python file object
File object containing the molecular data in the MD17 dataset.
Returns
-------
molecule : dict
Dictionary containing the molecular properties of the associated file object.
Notes
-----
TODO : Replace breakpoint with a more informative failure?
"""
xyz_lines = [line.decode('UTF-8') for line in datafile.readlines()]
num_atoms = int(xyz_lines[0])
mol_props = xyz_lines[1].split()
mol_xyz = xyz_lines[2:num_atoms+2]
mol_freq = xyz_lines[num_atoms+2]
atom_charges, atom_positions = [], []
for line in mol_xyz:
atom, posx, posy, posz, _ = line.replace('*^', 'e').split()
atom_charges.append(charge_dict[atom])
atom_positions.append([float(posx), float(posy), float(posz)])
prop_strings = ['tag', 'index', 'A', 'B', 'C', 'mu', 'alpha', 'homo', 'lumo', 'gap', 'r2', 'zpve', 'U0', 'U', 'H', 'G', 'Cv']
prop_strings = prop_strings[1:]
mol_props = [int(mol_props[1])] + [float(x) for x in mol_props[2:]]
mol_props = dict(zip(prop_strings, mol_props))
mol_props['omega1'] = max(float(omega) for omega in mol_freq.split())
molecule = {'num_atoms': num_atoms, 'charges': atom_charges, 'positions': atom_positions}
molecule.update(mol_props)
molecule = {key: torch.tensor(val) for key, val in molecule.items()}
return molecule
| 6,929 | 33.137931 | 138 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/generated_samples/gschnet/__init__.py | 0 | 0 | 0 | py |
|
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/generated_samples/gschnet/analyze_gschnet.py | # Rdkit import should be first, do not move it
try:
from rdkit import Chem
except ModuleNotFoundError:
pass
import pickle
import torch.nn.functional as F
from qm9.analyze import analyze_stability_for_molecules
import numpy as np
import torch
def flatten_sample_dictionary(samples):
results = {'one_hot': [], 'x': [], 'node_mask': []}
for number_of_atoms in samples:
positions = samples[number_of_atoms]['_positions']
atom_types = samples[number_of_atoms]['_atomic_numbers']
for positions_single_molecule, atom_types_single_molecule in zip(positions, atom_types):
mask = np.ones(positions.shape[1])
one_hot = F.one_hot(
torch.from_numpy(atom_types_single_molecule),
num_classes=10).numpy()
results['x'].append(torch.from_numpy(positions_single_molecule))
results['one_hot'].append(torch.from_numpy(one_hot))
results['node_mask'].append(torch.from_numpy(mask))
return results
def main():
with open('generated_samples/gschnet/gschnet_samples.pickle', 'rb') as f:
samples = pickle.load(f)
from configs import datasets_config
dataset_info = {'atom_decoder': [None, 'H', None, None, None,
None, 'C', 'N', 'O', 'F'],
'name': 'qm9'}
results = flatten_sample_dictionary(samples)
print(f'Analyzing {len(results["x"])} molecules...')
validity_dict, rdkit_metrics = analyze_stability_for_molecules(results, dataset_info)
print(validity_dict, rdkit_metrics[0])
if __name__ == '__main__':
main()
| 1,647 | 29.518519 | 96 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/egnn/egnn_new.py | from torch import nn
import torch
import math
class GCL(nn.Module):
def __init__(self, input_nf, output_nf, hidden_nf, normalization_factor, aggregation_method,
edges_in_d=0, nodes_att_dim=0, act_fn=nn.SiLU(), attention=False):
super(GCL, self).__init__()
input_edge = input_nf * 2
self.normalization_factor = normalization_factor
self.aggregation_method = aggregation_method
self.attention = attention
self.edge_mlp = nn.Sequential(
nn.Linear(input_edge + edges_in_d, hidden_nf),
act_fn,
nn.Linear(hidden_nf, hidden_nf),
act_fn)
self.node_mlp = nn.Sequential(
nn.Linear(hidden_nf + input_nf + nodes_att_dim, hidden_nf),
act_fn,
nn.Linear(hidden_nf, output_nf))
if self.attention:
self.att_mlp = nn.Sequential(
nn.Linear(hidden_nf, 1),
nn.Sigmoid())
def edge_model(self, source, target, edge_attr, edge_mask):
if edge_attr is None: # Unused.
out = torch.cat([source, target], dim=1)
else:
out = torch.cat([source, target, edge_attr], dim=1)
mij = self.edge_mlp(out)
if self.attention:
att_val = self.att_mlp(mij)
out = mij * att_val
else:
out = mij
if edge_mask is not None:
out = out * edge_mask
return out, mij
def node_model(self, x, edge_index, edge_attr, node_attr):
row, col = edge_index
agg = unsorted_segment_sum(edge_attr, row, num_segments=x.size(0),
normalization_factor=self.normalization_factor,
aggregation_method=self.aggregation_method)
if node_attr is not None:
agg = torch.cat([x, agg, node_attr], dim=1)
else:
agg = torch.cat([x, agg], dim=1)
out = x + self.node_mlp(agg)
return out, agg
def forward(self, h, edge_index, edge_attr=None, node_attr=None, node_mask=None, edge_mask=None):
row, col = edge_index
edge_feat, mij = self.edge_model(h[row], h[col], edge_attr, edge_mask)
h, agg = self.node_model(h, edge_index, edge_feat, node_attr)
if node_mask is not None:
h = h * node_mask
return h, mij
class EquivariantUpdate(nn.Module):
def __init__(self, hidden_nf, normalization_factor, aggregation_method,
edges_in_d=1, act_fn=nn.SiLU(), tanh=False, coords_range=10.0):
super(EquivariantUpdate, self).__init__()
self.tanh = tanh
self.coords_range = coords_range
input_edge = hidden_nf * 2 + edges_in_d
layer = nn.Linear(hidden_nf, 1, bias=False)
torch.nn.init.xavier_uniform_(layer.weight, gain=0.001)
self.coord_mlp = nn.Sequential(
nn.Linear(input_edge, hidden_nf),
act_fn,
nn.Linear(hidden_nf, hidden_nf),
act_fn,
layer)
self.normalization_factor = normalization_factor
self.aggregation_method = aggregation_method
def coord_model(self, h, coord, edge_index, coord_diff, edge_attr, edge_mask):
row, col = edge_index
input_tensor = torch.cat([h[row], h[col], edge_attr], dim=1)
if self.tanh:
trans = coord_diff * torch.tanh(self.coord_mlp(input_tensor)) * self.coords_range
else:
trans = coord_diff * self.coord_mlp(input_tensor)
if edge_mask is not None:
trans = trans * edge_mask
agg = unsorted_segment_sum(trans, row, num_segments=coord.size(0),
normalization_factor=self.normalization_factor,
aggregation_method=self.aggregation_method)
coord = coord + agg
return coord
def forward(self, h, coord, edge_index, coord_diff, edge_attr=None, node_mask=None, edge_mask=None):
coord = self.coord_model(h, coord, edge_index, coord_diff, edge_attr, edge_mask)
if node_mask is not None:
coord = coord * node_mask
return coord
class EquivariantBlock(nn.Module):
def __init__(self, hidden_nf, edge_feat_nf=2, device='cpu', act_fn=nn.SiLU(), n_layers=2, attention=True,
norm_diff=True, tanh=False, coords_range=15, norm_constant=1, sin_embedding=None,
normalization_factor=100, aggregation_method='sum'):
super(EquivariantBlock, self).__init__()
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
self.coords_range_layer = float(coords_range)
self.norm_diff = norm_diff
self.norm_constant = norm_constant
self.sin_embedding = sin_embedding
self.normalization_factor = normalization_factor
self.aggregation_method = aggregation_method
for i in range(0, n_layers):
self.add_module("gcl_%d" % i, GCL(self.hidden_nf, self.hidden_nf, self.hidden_nf, edges_in_d=edge_feat_nf,
act_fn=act_fn, attention=attention,
normalization_factor=self.normalization_factor,
aggregation_method=self.aggregation_method))
self.add_module("gcl_equiv", EquivariantUpdate(hidden_nf, edges_in_d=edge_feat_nf, act_fn=nn.SiLU(), tanh=tanh,
coords_range=self.coords_range_layer,
normalization_factor=self.normalization_factor,
aggregation_method=self.aggregation_method))
self.to(self.device)
def forward(self, h, x, edge_index, node_mask=None, edge_mask=None, edge_attr=None):
# Edit Emiel: Remove velocity as input
distances, coord_diff = coord2diff(x, edge_index, self.norm_constant)
if self.sin_embedding is not None:
distances = self.sin_embedding(distances)
edge_attr = torch.cat([distances, edge_attr], dim=1)
for i in range(0, self.n_layers):
h, _ = self._modules["gcl_%d" % i](h, edge_index, edge_attr=edge_attr, node_mask=node_mask, edge_mask=edge_mask)
x = self._modules["gcl_equiv"](h, x, edge_index, coord_diff, edge_attr, node_mask, edge_mask)
# Important, the bias of the last linear might be non-zero
if node_mask is not None:
h = h * node_mask
return h, x
class EGNN(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, device='cpu', act_fn=nn.SiLU(), n_layers=3, attention=False,
norm_diff=True, out_node_nf=None, tanh=False, coords_range=15, norm_constant=1, inv_sublayers=2,
sin_embedding=False, normalization_factor=100, aggregation_method='sum'):
super(EGNN, self).__init__()
if out_node_nf is None:
out_node_nf = in_node_nf
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
self.coords_range_layer = float(coords_range/n_layers)
self.norm_diff = norm_diff
self.normalization_factor = normalization_factor
self.aggregation_method = aggregation_method
if sin_embedding:
self.sin_embedding = SinusoidsEmbeddingNew()
edge_feat_nf = self.sin_embedding.dim * 2
else:
self.sin_embedding = None
edge_feat_nf = 2
self.embedding = nn.Linear(in_node_nf, self.hidden_nf)
self.embedding_out = nn.Linear(self.hidden_nf, out_node_nf)
for i in range(0, n_layers):
self.add_module("e_block_%d" % i, EquivariantBlock(hidden_nf, edge_feat_nf=edge_feat_nf, device=device,
act_fn=act_fn, n_layers=inv_sublayers,
attention=attention, norm_diff=norm_diff, tanh=tanh,
coords_range=coords_range, norm_constant=norm_constant,
sin_embedding=self.sin_embedding,
normalization_factor=self.normalization_factor,
aggregation_method=self.aggregation_method))
self.to(self.device)
def forward(self, h, x, edge_index, node_mask=None, edge_mask=None):
# Edit Emiel: Remove velocity as input
distances, _ = coord2diff(x, edge_index)
if self.sin_embedding is not None:
distances = self.sin_embedding(distances)
h = self.embedding(h)
for i in range(0, self.n_layers):
h, x = self._modules["e_block_%d" % i](h, x, edge_index, node_mask=node_mask, edge_mask=edge_mask, edge_attr=distances)
# Important, the bias of the last linear might be non-zero
h = self.embedding_out(h)
if node_mask is not None:
h = h * node_mask
return h, x
class GNN(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, aggregation_method='sum', device='cpu',
act_fn=nn.SiLU(), n_layers=4, attention=False,
normalization_factor=1, out_node_nf=None):
super(GNN, self).__init__()
if out_node_nf is None:
out_node_nf = in_node_nf
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
### Encoder
self.embedding = nn.Linear(in_node_nf, self.hidden_nf)
self.embedding_out = nn.Linear(self.hidden_nf, out_node_nf)
for i in range(0, n_layers):
self.add_module("gcl_%d" % i, GCL(
self.hidden_nf, self.hidden_nf, self.hidden_nf,
normalization_factor=normalization_factor,
aggregation_method=aggregation_method,
edges_in_d=in_edge_nf, act_fn=act_fn,
attention=attention))
self.to(self.device)
def forward(self, h, edges, edge_attr=None, node_mask=None, edge_mask=None):
# Edit Emiel: Remove velocity as input
h = self.embedding(h)
for i in range(0, self.n_layers):
h, _ = self._modules["gcl_%d" % i](h, edges, edge_attr=edge_attr, node_mask=node_mask, edge_mask=edge_mask)
h = self.embedding_out(h)
# Important, the bias of the last linear might be non-zero
if node_mask is not None:
h = h * node_mask
return h
class SinusoidsEmbeddingNew(nn.Module):
def __init__(self, max_res=15., min_res=15. / 2000., div_factor=4):
super().__init__()
self.n_frequencies = int(math.log(max_res / min_res, div_factor)) + 1
self.frequencies = 2 * math.pi * div_factor ** torch.arange(self.n_frequencies)/max_res
self.dim = len(self.frequencies) * 2
def forward(self, x):
x = torch.sqrt(x + 1e-8)
emb = x * self.frequencies[None, :].to(x.device)
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
return emb.detach()
def coord2diff(x, edge_index, norm_constant=1):
row, col = edge_index
coord_diff = x[row] - x[col]
radial = torch.sum((coord_diff) ** 2, 1).unsqueeze(1)
norm = torch.sqrt(radial + 1e-8)
coord_diff = coord_diff/(norm + norm_constant)
return radial, coord_diff
def unsorted_segment_sum(data, segment_ids, num_segments, normalization_factor, aggregation_method: str):
"""Custom PyTorch op to replicate TensorFlow's `unsorted_segment_sum`.
Normalization: 'sum' or 'mean'.
"""
result_shape = (num_segments, data.size(1))
result = data.new_full(result_shape, 0) # Init empty result tensor.
segment_ids = segment_ids.unsqueeze(-1).expand(-1, data.size(1))
result.scatter_add_(0, segment_ids, data)
if aggregation_method == 'sum':
result = result / normalization_factor
if aggregation_method == 'mean':
norm = data.new_zeros(result.shape)
norm.scatter_add_(0, segment_ids, data.new_ones(data.shape))
norm[norm == 0] = 1
result = result / norm
return result
| 12,294 | 43.709091 | 131 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/egnn/egnn.py | import torch
from torch import Tensor
from torch import nn
import torch.nn.functional as F
class E_GCL(nn.Module):
"""Graph Neural Net with global state and fixed number of nodes per graph.
Args:
hidden_dim: Number of hidden units.
num_nodes: Maximum number of nodes (for self-attentive pooling).
global_agg: Global aggregation function ('attn' or 'sum').
temp: Softmax temperature.
"""
def __init__(self, input_nf, output_nf, hidden_nf, edges_in_d=0, nodes_att_dim=0, act_fn=nn.SiLU(), attention=False, norm_diff=True, tanh=False, coords_range=1, norm_constant=0):
super(E_GCL, self).__init__()
input_edge = input_nf * 2
self.attention = attention
self.norm_diff = norm_diff
self.tanh = tanh
self.norm_constant = norm_constant
edge_coords_nf = 1
self.edge_mlp = nn.Sequential(
nn.Linear(input_edge + edge_coords_nf + edges_in_d, hidden_nf),
act_fn,
nn.Linear(hidden_nf, hidden_nf),
act_fn)
self.node_mlp = nn.Sequential(
nn.Linear(hidden_nf + input_nf + nodes_att_dim, hidden_nf),
act_fn,
nn.Linear(hidden_nf, output_nf))
layer = nn.Linear(hidden_nf, 1, bias=False)
torch.nn.init.xavier_uniform_(layer.weight, gain=0.001)
coord_mlp = []
coord_mlp.append(nn.Linear(hidden_nf, hidden_nf))
coord_mlp.append(act_fn)
coord_mlp.append(layer)
if self.tanh:
coord_mlp.append(nn.Tanh())
self.coords_range = coords_range
self.coord_mlp = nn.Sequential(*coord_mlp)
if self.attention:
self.att_mlp = nn.Sequential(
nn.Linear(hidden_nf, 1),
nn.Sigmoid())
def edge_model(self, source, target, radial, edge_attr, edge_mask):
if edge_attr is None: # Unused.
out = torch.cat([source, target, radial], dim=1)
else:
out = torch.cat([source, target, radial, edge_attr], dim=1)
out = self.edge_mlp(out)
if self.attention:
att_val = self.att_mlp(out)
out = out * att_val
if edge_mask is not None:
out = out * edge_mask
return out
def node_model(self, x, edge_index, edge_attr, node_attr):
row, col = edge_index
agg = unsorted_segment_sum(edge_attr, row, num_segments=x.size(0))
if node_attr is not None:
agg = torch.cat([x, agg, node_attr], dim=1)
else:
agg = torch.cat([x, agg], dim=1)
out = x + self.node_mlp(agg)
return out, agg
def coord_model(self, coord, edge_index, coord_diff, radial, edge_feat, node_mask, edge_mask):
row, col = edge_index
if self.tanh:
trans = coord_diff * self.coord_mlp(edge_feat) * self.coords_range
else:
trans = coord_diff * self.coord_mlp(edge_feat)
if edge_mask is not None:
trans = trans * edge_mask
agg = unsorted_segment_sum(trans, row, num_segments=coord.size(0))
coord = coord + agg
return coord
def forward(self, h, edge_index, coord, edge_attr=None, node_attr=None, node_mask=None, edge_mask=None):
row, col = edge_index
radial, coord_diff = self.coord2radial(edge_index, coord)
edge_feat = self.edge_model(h[row], h[col], radial, edge_attr, edge_mask)
coord = self.coord_model(coord, edge_index, coord_diff, radial, edge_feat, node_mask, edge_mask)
h, agg = self.node_model(h, edge_index, edge_feat, node_attr)
# coord = self.node_coord_model(h, coord)
# x = self.node_model(x, edge_index, x[col], u, batch) # GCN
if node_mask is not None:
h = h * node_mask
coord = coord * node_mask
return h, coord, edge_attr
def coord2radial(self, edge_index, coord):
row, col = edge_index
coord_diff = coord[row] - coord[col]
radial = torch.sum((coord_diff)**2, 1).unsqueeze(1)
norm = torch.sqrt(radial + 1e-8)
coord_diff = coord_diff/(norm + self.norm_constant)
return radial, coord_diff
class EGNN(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, device='cpu', act_fn=nn.SiLU(), n_layers=4, recurrent=True, attention=False, norm_diff=True, out_node_nf=None, tanh=False, coords_range=15, agg='sum', norm_constant=0, inv_sublayers=1, sin_embedding=False):
super(EGNN, self).__init__()
if out_node_nf is None:
out_node_nf = in_node_nf
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
self.coords_range_layer = float(coords_range)/self.n_layers
if agg == 'mean':
self.coords_range_layer = self.coords_range_layer * 19
#self.reg = reg
### Encoder
#self.add_module("gcl_0", E_GCL(in_node_nf, self.hidden_nf, self.hidden_nf, edges_in_d=in_edge_nf, act_fn=act_fn, recurrent=False, coords_weight=coords_weight))
self.embedding = nn.Linear(in_node_nf, self.hidden_nf)
self.embedding_out = nn.Linear(self.hidden_nf, out_node_nf)
for i in range(0, n_layers):
self.add_module("gcl_%d" % i, E_GCL(self.hidden_nf, self.hidden_nf, self.hidden_nf, edges_in_d=in_edge_nf, act_fn=act_fn, attention=attention, norm_diff=norm_diff, tanh=tanh, coords_range=self.coords_range_layer, norm_constant=norm_constant))
self.to(self.device)
def forward(self, h, x, edges, edge_attr=None, node_mask=None, edge_mask=None):
# Edit Emiel: Remove velocity as input
edge_attr = torch.sum((x[edges[0]] - x[edges[1]]) ** 2, dim=1, keepdim=True)
h = self.embedding(h)
for i in range(0, self.n_layers):
h, x, _ = self._modules["gcl_%d" % i](h, edges, x, edge_attr=edge_attr, node_mask=node_mask, edge_mask=edge_mask)
h = self.embedding_out(h)
# Important, the bias of the last linear might be non-zero
if node_mask is not None:
h = h * node_mask
return h, x
def unsorted_segment_sum(data, segment_ids, num_segments):
"""Custom PyTorch op to replicate TensorFlow's `unsorted_segment_sum`."""
result_shape = (num_segments, data.size(1))
result = data.new_full(result_shape, 0) # Init empty result tensor.
segment_ids = segment_ids.unsqueeze(-1).expand(-1, data.size(1))
result.scatter_add_(0, segment_ids, data)
return result
class EGNN_old(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, device='cpu', act_fn=nn.SiLU(), n_layers=4, recurrent=True, attention=False, norm_diff=True, out_node_nf=None, tanh=False, coords_range=15, agg='sum'):
super(EGNN_old, self).__init__()
if out_node_nf is None:
out_node_nf = in_node_nf
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
self.coords_range_layer = float(coords_range)/self.n_layers
if agg == 'mean':
self.coords_range_layer = self.coords_range_layer * 19
#self.reg = reg
### Encoder
#self.add_module("gcl_0", E_GCL(in_node_nf, self.hidden_nf, self.hidden_nf, edges_in_d=in_edge_nf, act_fn=act_fn, recurrent=False, coords_weight=coords_weight))
self.embedding = nn.Linear(in_node_nf, self.hidden_nf)
self.embedding_out = nn.Linear(self.hidden_nf, out_node_nf)
for i in range(0, n_layers):
self.add_module("gcl_%d" % i, E_GCL(self.hidden_nf, self.hidden_nf, self.hidden_nf, edges_in_d=in_edge_nf, act_fn=act_fn, attention=attention, norm_diff=norm_diff, tanh=tanh, coords_range=self.coords_range_layer))
self.to(self.device)
def forward(self, h, x, edges, edge_attr=None, node_mask=None, edge_mask=None):
# Edit Emiel: Remove velocity as input
edge_attr = torch.sum((x[edges[0]] - x[edges[1]]) ** 2, dim=1, keepdim=True)
h = self.embedding(h)
for i in range(0, self.n_layers):
h, x, _ = self._modules["gcl_%d" % i](h, edges, x, edge_attr=edge_attr, node_mask=node_mask, edge_mask=edge_mask)
h = self.embedding_out(h)
# Important, the bias of the last linear might be non-zero
if node_mask is not None:
h = h * node_mask
return h, x
class GNN(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, device='cpu', act_fn=nn.SiLU(), n_layers=4,
attention=False, out_node_nf=None):
super(GNN, self).__init__()
if out_node_nf is None:
out_node_nf = in_node_nf
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
### Encoder
self.embedding = nn.Linear(in_node_nf, self.hidden_nf)
self.embedding_out = nn.Linear(self.hidden_nf, out_node_nf)
for i in range(0, n_layers):
self.add_module("gcl_%d" % i, GCL(self.hidden_nf, self.hidden_nf, self.hidden_nf, edges_in_d=in_edge_nf,
act_fn=act_fn, attention=attention))
self.to(self.device)
def forward(self, h, edges, edge_attr=None, node_mask=None, edge_mask=None):
# Edit Emiel: Remove velocity as input
h = self.embedding(h)
for i in range(0, self.n_layers):
h, _ = self._modules["gcl_%d" % i](h, edges, edge_attr=edge_attr, node_mask=node_mask,
edge_mask=edge_mask)
h = self.embedding_out(h)
# Important, the bias of the last linear might be non-zero
if node_mask is not None:
h = h * node_mask
return h
class TransformerNN(nn.Module):
def __init__(self, in_node_nf, in_edge_nf, hidden_nf, device='cpu', act_fn=nn.SiLU(), n_layers=4, recurrent=True, attention=False, norm_diff=True, out_node_nf=None, tanh=False, coords_range=15, agg='sum', norm_constant=0):
super(EGNN, self).__init__()
hidden_initial = 128
initial_mlp_layers = 1
hidden_final = 128
final_mlp_layers = 2
n_heads = 8
dim_feedforward = 512
if out_node_nf is None:
out_node_nf = in_node_nf
self.hidden_nf = hidden_nf
self.device = device
self.n_layers = n_layers
self.initial_mlp = MLP(in_node_nf, hidden_nf, hidden_initial, initial_mlp_layers, skip=1, bias=True)
self.decoder_layers = nn.ModuleList()
if self.use_bn:
self.bn_layers = nn.ModuleList()
for _ in n_layers:
self.decoder_layers.append(nn.TransformerEncoderLayer(hidden_nf, n_heads, dim_feedforward, dropout=0))
self.final_mlp = MLP(hidden_nf, out_node_nf, hidden_final, final_mlp_layers, skip=1, bias=True)
self.to(self.device)
def forward(self, h, x, edges, edge_attr=None, node_mask=None, edge_mask=None):
""" x: batch_size, n, channels
latent: batch_size, channels2. """
x = F.relu(self.initial_mlp(x))
for i in range(len(self.decoder_layers)):
out = F.relu(self.decoder_layers[i](x)) # [bs, n, d]
if self.use_bn and type(x).__name__ != 'TransformerEncoderLayer':
out = self.bn_layers[i](out.transpose(1, 2)).transpose(1, 2) # bs, n, hidden
x = out + x if self.res and type(x).__name__ != 'TransformerEncoderLayer' else out
return x
# Edit Emiel: Remove velocity as input
edge_attr = torch.sum((x[edges[0]] - x[edges[1]]) ** 2, dim=1, keepdim=True)
h = self.embedding(h)
for i in range(0, self.n_layers):
h, x, _ = self._modules["gcl_%d" % i](h, edges, x, edge_attr=edge_attr, node_mask=node_mask, edge_mask=edge_mask)
h = self.embedding_out(h)
# Important, the bias of the last linear might be non-zero
if node_mask is not None:
h = h * node_mask
return h, x
class SetDecoder(nn.Module):
def __init__(self, cfg):
super().__init__()
hidden, hidden_final = cfg.hidden_decoder, cfg.hidden_last_decoder
self.use_bn = cfg.use_batch_norm
self.res = cfg.use_residual
self.cosine_channels = cfg.cosine_channels
self.initial_mlp = MLP(cfg.set_channels,
cfg.hidden_decoder,
cfg.hidden_initial_decoder,
cfg.initial_mlp_layers_decoder,
skip=1, bias=True)
self.decoder_layers = nn.ModuleList()
if self.use_bn:
self.bn_layers = nn.ModuleList()
for layer in cfg.decoder_layers:
self.decoder_layers.append(create_layer(layer, hidden, hidden, cfg))
if self.use_bn:
self.bn_layers.append(nn.BatchNorm1d(hidden))
def forward(self, x, latent):
""" x: batch_size, n, channels
latent: batch_size, channels2. """
x = F.relu(self.initial_mlp(x, latent[:, self.cosine_channels:].unsqueeze(1)))
for i in range(len(self.decoder_layers)):
out = F.relu(self.decoder_layers[i](x)) # [bs, n, d]
if self.use_bn and type(x).__name__ != 'TransformerEncoderLayer':
out = self.bn_layers[i](out.transpose(1, 2)).transpose(1, 2) # bs, n, hidden
x = out + x if self.res and type(x).__name__ != 'TransformerEncoderLayer' else out
return x
class MLP(nn.Module):
def __init__(self, dim_in: int, dim_out: int, width: int, nb_layers: int, skip=1, bias=True):
"""
Args:
dim_in: input dimension
dim_out: output dimension
width: hidden width
nb_layers: number of layers
skip: jump from residual connections
bias: indicates presence of bias
"""
super(MLP, self).__init__()
self.dim_in = dim_in
self.dim_out = dim_out
self.width = width
self.nb_layers = nb_layers
self.hidden = nn.ModuleList()
self.lin1 = nn.Linear(self.dim_in, width, bias)
self.skip = skip
self.residual_start = dim_in == width
self.residual_end = dim_out == width
for i in range(nb_layers-2):
self.hidden.append(nn.Linear(width, width, bias))
self.lin_final = nn.Linear(width, dim_out, bias)
def forward(self, x: Tensor):
out = self.lin1(x)
out = F.relu(out) + (x if self.residual_start else 0)
for layer in self.hidden:
out = out + layer(F.relu(out))
out = self.lin_final(F.relu(out)) + (out if self.residual_end else 0)
return out | 14,826 | 41.976812 | 264 | py |
e3_diffusion_for_molecules | e3_diffusion_for_molecules-main/egnn/models.py | import torch
import torch.nn as nn
from egnn.egnn_new import EGNN, GNN
from equivariant_diffusion.utils import remove_mean, remove_mean_with_mask
import numpy as np
class EGNN_dynamics_QM9(nn.Module):
def __init__(self, in_node_nf, context_node_nf,
n_dims, hidden_nf=64, device='cpu',
act_fn=torch.nn.SiLU(), n_layers=4, attention=False,
condition_time=True, tanh=False, mode='egnn_dynamics', norm_constant=0,
inv_sublayers=2, sin_embedding=False, normalization_factor=100, aggregation_method='sum'):
super().__init__()
self.mode = mode
if mode == 'egnn_dynamics':
self.egnn = EGNN(
in_node_nf=in_node_nf + context_node_nf, in_edge_nf=1,
hidden_nf=hidden_nf, device=device, act_fn=act_fn,
n_layers=n_layers, attention=attention, tanh=tanh, norm_constant=norm_constant,
inv_sublayers=inv_sublayers, sin_embedding=sin_embedding,
normalization_factor=normalization_factor,
aggregation_method=aggregation_method)
self.in_node_nf = in_node_nf
elif mode == 'gnn_dynamics':
self.gnn = GNN(
in_node_nf=in_node_nf + context_node_nf + 3, in_edge_nf=0,
hidden_nf=hidden_nf, out_node_nf=3 + in_node_nf, device=device,
act_fn=act_fn, n_layers=n_layers, attention=attention,
normalization_factor=normalization_factor, aggregation_method=aggregation_method)
self.context_node_nf = context_node_nf
self.device = device
self.n_dims = n_dims
self._edges_dict = {}
self.condition_time = condition_time
def forward(self, t, xh, node_mask, edge_mask, context=None):
raise NotImplementedError
def wrap_forward(self, node_mask, edge_mask, context):
def fwd(time, state):
return self._forward(time, state, node_mask, edge_mask, context)
return fwd
def unwrap_forward(self):
return self._forward
def _forward(self, t, xh, node_mask, edge_mask, context):
bs, n_nodes, dims = xh.shape
h_dims = dims - self.n_dims
edges = self.get_adj_matrix(n_nodes, bs, self.device)
edges = [x.to(self.device) for x in edges]
node_mask = node_mask.view(bs*n_nodes, 1)
edge_mask = edge_mask.view(bs*n_nodes*n_nodes, 1)
xh = xh.view(bs*n_nodes, -1).clone() * node_mask
x = xh[:, 0:self.n_dims].clone()
if h_dims == 0:
h = torch.ones(bs*n_nodes, 1).to(self.device)
else:
h = xh[:, self.n_dims:].clone()
if self.condition_time:
if np.prod(t.size()) == 1:
# t is the same for all elements in batch.
h_time = torch.empty_like(h[:, 0:1]).fill_(t.item())
else:
# t is different over the batch dimension.
h_time = t.view(bs, 1).repeat(1, n_nodes)
h_time = h_time.view(bs * n_nodes, 1)
h = torch.cat([h, h_time], dim=1)
if context is not None:
# We're conditioning, awesome!
context = context.view(bs*n_nodes, self.context_node_nf)
h = torch.cat([h, context], dim=1)
if self.mode == 'egnn_dynamics':
h_final, x_final = self.egnn(h, x, edges, node_mask=node_mask, edge_mask=edge_mask)
vel = (x_final - x) * node_mask # This masking operation is redundant but just in case
elif self.mode == 'gnn_dynamics':
xh = torch.cat([x, h], dim=1)
output = self.gnn(xh, edges, node_mask=node_mask)
vel = output[:, 0:3] * node_mask
h_final = output[:, 3:]
else:
raise Exception("Wrong mode %s" % self.mode)
if context is not None:
# Slice off context size:
h_final = h_final[:, :-self.context_node_nf]
if self.condition_time:
# Slice off last dimension which represented time.
h_final = h_final[:, :-1]
vel = vel.view(bs, n_nodes, -1)
if torch.any(torch.isnan(vel)):
print('Warning: detected nan, resetting EGNN output to zero.')
vel = torch.zeros_like(vel)
if node_mask is None:
vel = remove_mean(vel)
else:
vel = remove_mean_with_mask(vel, node_mask.view(bs, n_nodes, 1))
if h_dims == 0:
return vel
else:
h_final = h_final.view(bs, n_nodes, -1)
return torch.cat([vel, h_final], dim=2)
def get_adj_matrix(self, n_nodes, batch_size, device):
if n_nodes in self._edges_dict:
edges_dic_b = self._edges_dict[n_nodes]
if batch_size in edges_dic_b:
return edges_dic_b[batch_size]
else:
# get edges for a single sample
rows, cols = [], []
for batch_idx in range(batch_size):
for i in range(n_nodes):
for j in range(n_nodes):
rows.append(i + batch_idx * n_nodes)
cols.append(j + batch_idx * n_nodes)
edges = [torch.LongTensor(rows).to(device),
torch.LongTensor(cols).to(device)]
edges_dic_b[batch_size] = edges
return edges
else:
self._edges_dict[n_nodes] = {}
return self.get_adj_matrix(n_nodes, batch_size, device)
| 5,555 | 40.155556 | 107 | py |
cpuinfo | cpuinfo-main/configure.py | #!/usr/bin/env python
import confu
parser = confu.standard_parser("cpuinfo configuration script")
parser.add_argument("--log", dest="log_level",
choices=("none", "fatal", "error", "warning", "info", "debug"), default="error")
parser.add_argument("--mock", dest="mock", action="store_true")
def main(args):
options = parser.parse_args(args)
build = confu.Build.from_options(options)
macros = {
"CPUINFO_LOG_LEVEL": {"none": 0, "fatal": 1, "error": 2, "warning": 3, "info": 4, "debug": 5}[options.log_level],
"CLOG_LOG_TO_STDIO": int(not options.mock),
"CPUINFO_MOCK": int(options.mock),
}
if build.target.is_linux or build.target.is_android:
macros["_GNU_SOURCE"] = 1
build.export_cpath("include", ["cpuinfo.h"])
with build.options(source_dir="src", macros=macros, extra_include_dirs="src", deps=build.deps.clog):
sources = ["api.c", "init.c", "cache.c"]
if build.target.is_x86 or build.target.is_x86_64:
sources += [
"x86/init.c", "x86/info.c", "x86/isa.c", "x86/vendor.c",
"x86/uarch.c", "x86/name.c", "x86/topology.c",
"x86/cache/init.c", "x86/cache/descriptor.c", "x86/cache/deterministic.c",
]
if build.target.is_macos:
sources += ["x86/mach/init.c"]
elif build.target.is_linux or build.target.is_android:
sources += [
"x86/linux/init.c",
"x86/linux/cpuinfo.c",
]
if build.target.is_arm or build.target.is_arm64:
sources += ["arm/uarch.c", "arm/cache.c"]
if build.target.is_linux or build.target.is_android:
sources += [
"arm/linux/init.c",
"arm/linux/cpuinfo.c",
"arm/linux/clusters.c",
"arm/linux/midr.c",
"arm/linux/chipset.c",
"arm/linux/hwcap.c",
]
if build.target.is_arm:
sources.append("arm/linux/aarch32-isa.c")
elif build.target.is_arm64:
sources.append("arm/linux/aarch64-isa.c")
if build.target.is_android:
sources += [
"arm/android/properties.c",
]
if build.target.is_macos:
sources += ["mach/topology.c"]
if build.target.is_linux or build.target.is_android:
sources += [
"linux/cpulist.c",
"linux/smallfile.c",
"linux/multiline.c",
"linux/processors.c",
]
if options.mock:
sources += ["linux/mockfile.c"]
build.static_library("cpuinfo", map(build.cc, sources))
with build.options(source_dir="tools", deps=[build, build.deps.clog]):
build.executable("cpu-info", build.cc("cpu-info.c"))
build.executable("isa-info", build.cc("isa-info.c"))
build.executable("cache-info", build.cc("cache-info.c"))
if build.target.is_x86_64:
with build.options(source_dir="tools", include_dirs=["src", "include"]):
build.executable("cpuid-dump", build.cc("cpuid-dump.c"))
with build.options(source_dir="test", deps=[build, build.deps.clog, build.deps.googletest]):
build.smoketest("init-test", build.cxx("init.cc"))
if build.target.is_linux:
build.smoketest("get-current-test", build.cxx("get-current.cc"))
if build.target.is_x86_64:
build.smoketest("brand-string-test", build.cxx("name/brand-string.cc"))
if options.mock:
with build.options(source_dir="test", include_dirs="test", macros="CPUINFO_MOCK", deps=[build, build.deps.googletest]):
if build.target.is_arm64 and build.target.is_linux:
build.unittest("scaleway-test", build.cxx("scaleway.cc"))
if not options.mock:
with build.options(source_dir="bench", deps=[build, build.deps.clog, build.deps.googlebenchmark]):
build.benchmark("init-bench", build.cxx("init.cc"))
if not build.target.is_macos:
build.benchmark("get-current-bench", build.cxx("get-current.cc"))
return build
if __name__ == "__main__":
import sys
main(sys.argv[1:]).generate()
| 4,374 | 40.666667 | 127 | py |
cpuinfo | cpuinfo-main/deps/clog/configure.py | #!/usr/bin/env python
import confu
parser = confu.standard_parser("clog configuration script")
def main(args):
options = parser.parse_args(args)
build = confu.Build.from_options(options)
build.export_cpath("include", ["clog.h"])
with build.options(source_dir="src", extra_include_dirs="src"):
build.static_library("clog", build.cc("clog.c"))
with build.options(source_dir="test", deps={
(build, build.deps.googletest): all,
"log": build.target.is_android}):
build.unittest("clog-test", build.cxx("clog.cc"))
return build
if __name__ == "__main__":
import sys
main(sys.argv[1:]).generate()
| 670 | 23.851852 | 67 | py |
cpuinfo | cpuinfo-main/scripts/arm-linux-filesystem-dump.py | #!/usr/bin/env python
import os
import sys
import argparse
import shutil
parser = argparse.ArgumentParser(description='Android system files extractor')
parser.add_argument("-p", "--prefix", metavar="NAME", required=True,
help="Prefix for stored files, e.g. galaxy-s7-us")
SYSTEM_FILES = [
"/proc/cpuinfo",
"/sys/devices/system/cpu/kernel_max",
"/sys/devices/system/cpu/possible",
"/sys/devices/system/cpu/present",
]
CPU_FILES = [
"cpufreq/cpuinfo_max_freq",
"cpufreq/cpuinfo_min_freq",
"topology/physical_package_id",
"topology/core_siblings_list",
"topology/core_id",
"topology/thread_siblings_list",
]
CACHE_FILES = [
"allocation_policy",
"coherency_line_size",
"level",
"number_of_sets",
"shared_cpu_list",
"size",
"type",
"ways_of_associativity",
"write_policy",
]
def c_escape(string):
c_string = ""
for c in string:
if c == "\\":
c_string += "\\\\"
elif c == "\"":
c_string += "\\\""
elif c == "\t":
c_string += "\\t"
elif c == "\n":
c_string += "\\n"
elif c == "\r":
c_string += "\\r"
elif ord(c) == 0:
c_string += "\\0"
elif 32 <= ord(c) < 127:
c_string += c
else:
c_string += "x%02X" % ord(c)
return c_string
def dump_system_file(stream, path):
try:
with open(path, "rb") as device_file:
content = device_file.read()
stream.write("\t{\n")
stream.write("\t\t.path = \"%s\",\n" % path)
stream.write("\t\t.size = %d,\n" % len(content))
if len(content.splitlines()) > 1:
stream.write("\t\t.content =")
for line in content.splitlines(True):
stream.write("\n\t\t\t\"%s\"" % c_escape(line))
stream.write(",\n")
else:
stream.write("\t\t.content = \"%s\",\n" % c_escape(content))
stream.write("\t},\n")
return True
except IOError:
pass
def main(args):
options = parser.parse_args(args)
# with open(os.path.join("test", "dmesg", options.prefix + ".log"), "w") as dmesg_log:
# dmesg_log.write(device.Shell("dmesg"))
with open(os.path.join("test", options.prefix + ".h"), "w") as file_header:
file_header.write("struct cpuinfo_mock_file filesystem[] = {\n")
for path in SYSTEM_FILES:
dump_system_file(file_header, path)
for cpu in range(16):
for filename in CPU_FILES:
path = "/sys/devices/system/cpu/cpu%d/%s" % (cpu, filename)
dump_system_file(file_header, path)
for index in range(10):
for filename in CACHE_FILES:
path = "/sys/devices/system/cpu/cpu%d/cache/index%d/%s" % (cpu, index, filename)
dump_system_file(file_header, path)
file_header.write("\t{ NULL },\n")
file_header.write("};\n")
shutil.copy("/proc/cpuinfo",
os.path.join("test", "cpuinfo", options.prefix + ".log"))
if __name__ == "__main__":
main(sys.argv[1:])
| 3,213 | 28.759259 | 100 | py |
cpuinfo | cpuinfo-main/scripts/parse-x86-cpuid-dump.py | #!/usr/bin/env python
from __future__ import print_function
import argparse
import sys
import re
parser = argparse.ArgumentParser(description='x86 CPUID dump parser')
parser.add_argument("input", metavar="INPUT", nargs=1,
help="Path to CPUID dump log")
def main(args):
options = parser.parse_args(args)
cpuid_dump = list()
for line in open(options.input[0]).read().splitlines():
match = re.match(r"CPUID ([\dA-F]{8}): ([\dA-F]{8})-([\dA-F]{8})-([\dA-F]{8})-([\dA-F]{8})", line)
if match is not None:
input_eax, eax, ebx, ecx, edx = tuple(int(match.group(i), 16) for i in [1, 2, 3, 4, 5])
line = line[match.end(0):].strip()
input_ecx = None
match = re.match(r"\[SL (\d{2})\]", line)
if match is not None:
input_ecx = int(match.group(1), 16)
cpuid_dump.append((input_eax, input_ecx, eax, ebx, ecx, edx))
print("struct cpuinfo_mock_cpuid cpuid_dump[] = {")
for input_eax, input_ecx, eax, ebx, ecx, edx in cpuid_dump:
print("\t{")
print("\t\t.input_eax = 0x%08X," % input_eax)
if input_ecx is not None:
print("\t\t.input_ecx = 0x%08X," % input_ecx)
print("\t\t.eax = 0x%08X," % eax)
print("\t\t.ebx = 0x%08X," % ebx)
print("\t\t.ecx = 0x%08X," % ecx)
print("\t\t.edx = 0x%08X," % edx)
print("\t},")
print("};")
print()
if __name__ == "__main__":
main(sys.argv[1:])
| 1,504 | 30.354167 | 106 | py |
cpuinfo | cpuinfo-main/scripts/android-device-dump.py | #!/usr/bin/env python
import os
import sys
import string
import argparse
import subprocess
import tempfile
root_dir = os.path.abspath(os.path.dirname(__file__))
parser = argparse.ArgumentParser(description='Android system files extractor')
parser.add_argument("-p", "--prefix", metavar="NAME", required=True,
help="Prefix for stored files, e.g. galaxy-s7-us")
# System files which need to be read with `adb shell cat filename`
# instead of `adb pull filename`
SHELL_PREFIX = [
"/sys/class/kgsl/kgsl-3d0/",
]
SYSTEM_FILES = [
"/proc/cpuinfo",
"/system/build.prop",
"/sys/class/kgsl/kgsl-3d0/bus_split",
"/sys/class/kgsl/kgsl-3d0/clock_mhz",
"/sys/class/kgsl/kgsl-3d0/deep_nap_timer",
"/sys/class/kgsl/kgsl-3d0/default_pwrlevel",
"/sys/class/kgsl/kgsl-3d0/dev",
"/sys/class/kgsl/kgsl-3d0/devfreq/available_frequencies",
"/sys/class/kgsl/kgsl-3d0/devfreq/available_governors",
"/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq",
"/sys/class/kgsl/kgsl-3d0/devfreq/governor",
"/sys/class/kgsl/kgsl-3d0/devfreq/gpu_load",
"/sys/class/kgsl/kgsl-3d0/devfreq/max_freq",
"/sys/class/kgsl/kgsl-3d0/devfreq/min_freq",
"/sys/class/kgsl/kgsl-3d0/devfreq/polling_interval",
"/sys/class/kgsl/kgsl-3d0/devfreq/suspend_time",
"/sys/class/kgsl/kgsl-3d0/devfreq/target_freq",
"/sys/class/kgsl/kgsl-3d0/devfreq/trans_stat",
"/sys/class/kgsl/kgsl-3d0/device/op_cpu_table",
"/sys/class/kgsl/kgsl-3d0/freq_table_mhz",
"/sys/class/kgsl/kgsl-3d0/ft_fast_hang_detect",
"/sys/class/kgsl/kgsl-3d0/ft_hang_intr_status",
"/sys/class/kgsl/kgsl-3d0/ft_long_ib_detect",
"/sys/class/kgsl/kgsl-3d0/ft_pagefault_policy",
"/sys/class/kgsl/kgsl-3d0/ft_policy",
"/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies",
"/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage",
"/sys/class/kgsl/kgsl-3d0/gpu_clock_stats",
"/sys/class/kgsl/kgsl-3d0/gpu_llc_slice_enable",
"/sys/class/kgsl/kgsl-3d0/gpu_model",
"/sys/class/kgsl/kgsl-3d0/gpubusy",
"/sys/class/kgsl/kgsl-3d0/gpuclk",
"/sys/class/kgsl/kgsl-3d0/gpuhtw_llc_slice_enable",
"/sys/class/kgsl/kgsl-3d0/hwcg",
"/sys/class/kgsl/kgsl-3d0/idle_timer",
"/sys/class/kgsl/kgsl-3d0/lm",
"/sys/class/kgsl/kgsl-3d0/max_gpuclk",
"/sys/class/kgsl/kgsl-3d0/max_pwrlevel",
"/sys/class/kgsl/kgsl-3d0/min_clock_mhz",
"/sys/class/kgsl/kgsl-3d0/min_pwrlevel",
"/sys/class/kgsl/kgsl-3d0/num_pwrlevels",
"/sys/class/kgsl/kgsl-3d0/pmqos_active_latency",
"/sys/class/kgsl/kgsl-3d0/popp",
"/sys/class/kgsl/kgsl-3d0/preempt_count",
"/sys/class/kgsl/kgsl-3d0/preempt_level",
"/sys/class/kgsl/kgsl-3d0/preemption",
"/sys/class/kgsl/kgsl-3d0/pwrscale",
"/sys/class/kgsl/kgsl-3d0/reset_count",
"/sys/class/kgsl/kgsl-3d0/skipsaverestore",
"/sys/class/kgsl/kgsl-3d0/sptp_pc",
"/sys/class/kgsl/kgsl-3d0/thermal_pwrlevel",
"/sys/class/kgsl/kgsl-3d0/throttling",
"/sys/class/kgsl/kgsl-3d0/usesgmem",
"/sys/class/kgsl/kgsl-3d0/wake_nice",
"/sys/class/kgsl/kgsl-3d0/wake_timeout",
"/sys/devices/soc0/accessory_chip",
"/sys/devices/soc0/build_id",
"/sys/devices/soc0/chip_family",
"/sys/devices/soc0/chip_name",
"/sys/devices/soc0/family",
"/sys/devices/soc0/foundry_id",
"/sys/devices/soc0/hw_platform",
"/sys/devices/soc0/image_crm_version",
"/sys/devices/soc0/image_variant",
"/sys/devices/soc0/image_version",
"/sys/devices/soc0/images",
"/sys/devices/soc0/machine",
"/sys/devices/soc0/ncluster_array_offset",
"/sys/devices/soc0/ndefective_parts_array_offset",
"/sys/devices/soc0/nmodem_supported",
"/sys/devices/soc0/nproduct_id",
"/sys/devices/soc0/num_clusters",
"/sys/devices/soc0/num_defective_parts",
"/sys/devices/soc0/platform_subtype",
"/sys/devices/soc0/platform_subtype_id",
"/sys/devices/soc0/platform_version",
"/sys/devices/soc0/pmic_die_revision",
"/sys/devices/soc0/pmic_model",
"/sys/devices/soc0/raw_device_family",
"/sys/devices/soc0/raw_device_number",
"/sys/devices/soc0/raw_id",
"/sys/devices/soc0/raw_version",
"/sys/devices/soc0/revision",
"/sys/devices/soc0/select_image",
"/sys/devices/soc0/serial_number",
"/sys/devices/soc0/soc_id",
"/sys/devices/soc0/vendor",
"/sys/devices/system/b.L/big_threads",
"/sys/devices/system/b.L/boot_cluster",
"/sys/devices/system/b.L/core_status",
"/sys/devices/system/b.L/little_threads",
"/sys/devices/system/b.L/down_migrations",
"/sys/devices/system/b.L/up_migrations",
"/sys/devices/system/cpu/isolated",
"/sys/devices/system/cpu/kernel_max",
"/sys/devices/system/cpu/modalias",
"/sys/devices/system/cpu/offline",
"/sys/devices/system/cpu/online",
"/sys/devices/system/cpu/possible",
"/sys/devices/system/cpu/present",
"/sys/devices/system/cpu/sched_isolated",
"/sys/devices/system/cpu/clusterhotplug/cur_hstate",
"/sys/devices/system/cpu/clusterhotplug/down_freq",
"/sys/devices/system/cpu/clusterhotplug/down_tasks",
"/sys/devices/system/cpu/clusterhotplug/down_threshold",
"/sys/devices/system/cpu/clusterhotplug/sampling_rate",
"/sys/devices/system/cpu/clusterhotplug/time_in_state",
"/sys/devices/system/cpu/clusterhotplug/up_freq",
"/sys/devices/system/cpu/clusterhotplug/up_tasks",
"/sys/devices/system/cpu/clusterhotplug/up_threshold",
"/sys/devices/system/cpu/cpufreq/all_time_in_state",
"/sys/devices/system/cpu/cpufreq/current_in_state",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/big_cpu_num",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/big_max_freq",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/big_min_freq",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/hmp_boost_type",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/hmp_prev_boost_type",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/ltl_cpu_num",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/ltl_divider",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/ltl_max_freq",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/ltl_min_freq",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/ltl_min_lock",
"/sys/devices/system/cpu/cpufreq/cpufreq_limit/requests",
"/sys/devices/system/cpu/cpuidle/current_driver",
"/sys/devices/system/cpu/cpuidle/current_governor_ro",
"/sys/devices/system/cpu/cputopo/cpus_per_cluster",
"/sys/devices/system/cpu/cputopo/big_cpumask",
"/sys/devices/system/cpu/cputopo/glbinfo",
"/sys/devices/system/cpu/cputopo/is_big_little",
"/sys/devices/system/cpu/cputopo/is_multi_cluster",
"/sys/devices/system/cpu/cputopo/little_cpumask",
"/sys/devices/system/cpu/cputopo/nr_clusters",
"/sys/devices/system/sched/idle_prefer",
"/sys/devices/system/sched/sched_boost",
]
CPU_FILES = [
"core_ctl/active_cpus",
"core_ctl/busy_up_thres",
"core_ctl/busy_down_thres",
"core_ctl/enable",
"core_ctl/global_state",
"core_ctl/is_big_cluster",
"core_ctl/max_cpus",
"core_ctl/min_cpus",
"core_ctl/need_cpus",
"core_ctl/not_preferred",
"core_ctl/offline_delay_ms",
"core_ctl/task_thres",
"current_driver",
"current_governor_ro",
"cpuidle/driver/name",
"cpufreq/affected_cpus",
"cpufreq/cpuinfo_max_freq",
"cpufreq/cpuinfo_min_freq",
"cpufreq/cpuinfo_transition_latency",
"cpufreq/related_cpus",
"cpufreq/scaling_available_frequencies",
"cpufreq/scaling_available_governors",
"cpufreq/scaling_cur_freq",
"cpufreq/scaling_driver",
"cpufreq/scaling_governor",
"cpufreq/scaling_max_freq",
"cpufreq/scaling_min_freq",
"cpufreq/sched/down_throttle_nsec",
"cpufreq/sched/up_throttle_nsec",
"cpufreq/stats/time_in_state",
"cpufreq/stats/total_trans",
"cpufreq/stats/trans_table",
"isolate",
"regs/identification/midr_el1",
"regs/identification/revidr_el1",
"sched_load_boost",
"topology/core_id",
"topology/core_siblings",
"topology/core_siblings_list",
"topology/cpu_capacity",
"topology/max_cpu_capacity",
"topology/physical_package_id",
"topology/thread_siblings",
"topology/thread_siblings_list",
]
CACHE_FILES = [
"allocation_policy",
"coherency_line_size",
"level",
"number_of_sets",
"shared_cpu_list",
"shared_cpu_map",
"size",
"type",
"ways_of_associativity",
"write_policy",
]
def c_escape(string):
c_string = ""
for c in string:
if c == "\\":
c_string += "\\\\"
elif c == "\"":
c_string += "\\\""
elif c == "\t":
c_string += "\\t"
elif c == "\n":
c_string += "\\n"
elif c == "\r":
c_string += "\\r"
elif ord(c) == 0:
c_string += "\\0"
elif 32 <= ord(c) < 127:
c_string += c
else:
c_string += "x%02X" % ord(c)
return c_string
def adb_shell(commands):
env = os.environ.copy()
env["LC_ALL"] = "C"
adb = subprocess.Popen(["adb", "shell"] + commands, env=env, stdout=subprocess.PIPE)
stdout, _ = adb.communicate()
if adb.returncode == 0:
return stdout
def adb_push(local_path, device_path):
env = os.environ.copy()
env["LC_ALL"] = "C"
adb = subprocess.Popen(["adb", "push", local_path, device_path], env=env)
adb.communicate()
return adb.returncode == 0
def adb_pull(device_path, local_path):
if any(device_path.startswith(prefix) for prefix in SHELL_PREFIX):
content = adb_shell(["cat", device_path])
if content is not None:
if not content.rstrip().endswith("No such file or directory"):
with open(local_path, "wb") as local_file:
local_file.write(content)
return True
else:
env = os.environ.copy()
env["LC_ALL"] = "C"
adb = subprocess.Popen(["adb", "pull", device_path, local_path], env=env)
adb.communicate()
return adb.returncode == 0
def adb_getprop():
properties = adb_shell(["getprop"])
properties_list = list()
while properties:
assert properties.startswith("[")
properties = properties[1:]
key, properties = properties.split("]", 1)
properties = properties.strip()
assert properties.startswith(":")
properties = properties[1:].strip()
assert properties.startswith("[")
properties = properties[1:]
value, properties = properties.split("]", 1)
properties = properties.strip()
properties_list.append((key, value))
return properties_list
def add_mock_file(stream, path, content):
assert content is not None
stream.write("\t{\n")
stream.write("\t\t.path = \"%s\",\n" % path)
stream.write("\t\t.size = %d,\n" % len(content))
if len(content.splitlines()) > 1:
stream.write("\t\t.content =")
for line in content.splitlines(True):
stream.write("\n\t\t\t\"%s\"" % c_escape(line))
stream.write(",\n")
else:
stream.write("\t\t.content = \"%s\",\n" % c_escape(content))
stream.write("\t},\n")
def dump_device_file(stream, path, prefix_line=None):
temp_fd, temp_path = tempfile.mkstemp()
os.close(temp_fd)
try:
if adb_pull(path, temp_path):
with open(temp_path, "rb") as temp_file:
content = temp_file.read()
if prefix_line is not None:
stream.write(prefix_line)
add_mock_file(stream, path, content)
return content
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
def main(args):
options = parser.parse_args(args)
dmesg_content = adb_shell(["dmesg"])
if dmesg_content is not None and dmesg_content.strip() == "klogctl: Operation not permitted":
dmesg_content = None
if dmesg_content is not None:
with open(os.path.join("test", "dmesg", options.prefix + ".log"), "w") as dmesg_dump:
dmesg_dump.write(dmesg_content)
build_prop_content = None
proc_cpuinfo_content = None
proc_cpuinfo_content32 = None
kernel_max = 0
with open(os.path.join("test", "mock", options.prefix + ".h"), "w") as file_header:
file_header.write("struct cpuinfo_mock_file filesystem[] = {\n")
android_props = adb_getprop()
abi = None
for key, value in android_props:
if key == "ro.product.cpu.abi":
abi = value
for path in SYSTEM_FILES:
arm64_prefix = None
if path == "/proc/cpuinfo" and abi == "arm64-v8a":
arm64_prefix = "#if CPUINFO_ARCH_ARM64\n"
content = dump_device_file(file_header, path, prefix_line=arm64_prefix)
if content is not None:
if path == "/proc/cpuinfo":
proc_cpuinfo_content = content
elif path == "/system/build.prop":
build_prop_content = content
elif path == "/sys/devices/system/cpu/kernel_max":
kernel_max = int(content.strip())
if arm64_prefix:
cpuinfo_dump_binary = os.path.join(root_dir, "..", "build", "android", "armeabi-v7a", "cpuinfo-dump")
assert os.path.isfile(cpuinfo_dump_binary)
adb_push(cpuinfo_dump_binary, "/data/local/tmp/cpuinfo-dump")
proc_cpuinfo_content32 = adb_shell(["/data/local/tmp/cpuinfo-dump"])
if proc_cpuinfo_content32:
proc_cpuinfo_content32 = "\n".join(proc_cpuinfo_content32.splitlines())
file_header.write("#elif CPUINFO_ARCH_ARM\n")
add_mock_file(file_header, "/proc/cpuinfo", proc_cpuinfo_content32)
file_header.write("#endif\n")
for cpu in range(kernel_max + 1):
for filename in CPU_FILES:
path = "/sys/devices/system/cpu/cpu%d/%s" % (cpu, filename)
dump_device_file(file_header, path)
for index in range(5):
for filename in CACHE_FILES:
path = "/sys/devices/system/cpu/cpu%d/cache/index%d/%s" % (cpu, index, filename)
dump_device_file(file_header, path)
file_header.write("\t{ NULL },\n")
file_header.write("};\n")
file_header.write("#ifdef __ANDROID__\n")
file_header.write("struct cpuinfo_mock_property properties[] = {\n")
for key, value in android_props:
file_header.write("\t{\n")
file_header.write("\t\t.key = \"%s\",\n" % c_escape(key))
file_header.write("\t\t.value = \"%s\",\n" % c_escape(value))
file_header.write("\t},\n")
file_header.write("\t{ NULL },\n")
file_header.write("};\n")
file_header.write("#endif /* __ANDROID__ */\n")
if proc_cpuinfo_content is not None:
with open(os.path.join("test", "cpuinfo", options.prefix + ".log"), "w") as proc_cpuinfo_dump:
proc_cpuinfo_dump.write(proc_cpuinfo_content)
if proc_cpuinfo_content32 is not None:
with open(os.path.join("test", "cpuinfo", options.prefix + ".armeabi.log"), "w") as proc_cpuinfo_dump32:
proc_cpuinfo_dump32.write(proc_cpuinfo_content32)
if build_prop_content is not None:
with open(os.path.join("test", "build.prop", options.prefix + ".log"), "w") as build_prop_dump:
build_prop_dump.write(build_prop_content)
if __name__ == "__main__":
main(sys.argv[1:])
| 15,626 | 37.970075 | 117 | py |
infinispan | infinispan-main/documentation/src/main/asciidoc/topics/python/monitor_site_status.py | #!/usr/bin/python3
import time
import requests
from requests.auth import HTTPDigestAuth
class InfinispanConnection:
def __init__(self, server: str = 'http://localhost:11222', cache_manager: str = 'default',
auth: tuple = ('admin', 'change_me')) -> None:
super().__init__()
self.__url = f'{server}/rest/v2/cache-managers/{cache_manager}/x-site/backups/'
self.__auth = auth
self.__headers = {
'accept': 'application/json'
}
def get_sites_status(self):
try:
rsp = requests.get(self.__url, headers=self.__headers, auth=HTTPDigestAuth(self.__auth[0], self.__auth[1]))
if rsp.status_code != 200:
return None
return rsp.json()
except:
return None
# Specify credentials for {brandname} user with permission to access the REST endpoint
USERNAME = 'admin'
PASSWORD = 'change_me'
# Set an interval between cross-site status checks
POLL_INTERVAL_SEC = 5
# Provide a list of servers
SERVERS = [
InfinispanConnection('http://127.0.0.1:11222', auth=(USERNAME, PASSWORD)),
InfinispanConnection('http://127.0.0.1:12222', auth=(USERNAME, PASSWORD))
]
#Specify the names of remote sites
REMOTE_SITES = [
'nyc'
]
#Provide a list of caches to monitor
CACHES = [
'work',
'sessions'
]
def on_event(site: str, cache: str, old_status: str, new_status: str):
# TODO implement your handling code here
print(f'site={site} cache={cache} Status changed {old_status} -> {new_status}')
def __handle_mixed_state(state: dict, site: str, site_status: dict):
if site not in state:
state[site] = {c: 'online' if c in site_status['online'] else 'offline' for c in CACHES}
return
for cache in CACHES:
__update_cache_state(state, site, cache, 'online' if cache in site_status['online'] else 'offline')
def __handle_online_or_offline_state(state: dict, site: str, new_status: str):
if site not in state:
state[site] = {c: new_status for c in CACHES}
return
for cache in CACHES:
__update_cache_state(state, site, cache, new_status)
def __update_cache_state(state: dict, site: str, cache: str, new_status: str):
old_status = state[site].get(cache)
if old_status != new_status:
on_event(site, cache, old_status, new_status)
state[site][cache] = new_status
def update_state(state: dict):
rsp = None
for conn in SERVERS:
rsp = conn.get_sites_status()
if rsp:
break
if rsp is None:
print('Unable to fetch site status from any server')
return
for site in REMOTE_SITES:
site_status = rsp.get(site, {})
new_status = site_status.get('status')
if new_status == 'mixed':
__handle_mixed_state(state, site, site_status)
else:
__handle_online_or_offline_state(state, site, new_status)
if __name__ == '__main__':
_state = {}
while True:
update_state(_state)
time.sleep(POLL_INTERVAL_SEC)
| 3,065 | 28.76699 | 119 | py |
infinispan | infinispan-main/documentation/src/main/asciidoc/topics/code_examples/rest_client.py | import urllib.request
# Setup basic auth
base_uri = 'http://localhost:11222/rest/v2/caches/default'
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(user='user', passwd='pass', realm='ApplicationRealm', uri=base_uri)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
# putting data in
data = "SOME DATA HERE \!"
req = urllib.request.Request(url=base_uri + '/Key', data=data.encode("UTF-8"), method='PUT',
headers={"Content-Type": "text/plain"})
with urllib.request.urlopen(req) as f:
pass
print(f.status)
print(f.reason)
# getting data out
resp = urllib.request.urlopen(base_uri + '/Key')
print(resp.read().decode('utf-8'))
| 731 | 29.5 | 93 | py |
infinispan | infinispan-main/bin/diff_test_lists.py | #!/usr/bin/python
"""
Merge the results of the find_unstable_tests.py, find_unstable_tests_jira.py, and find_unstable_tests_teamcity.py
"""
import argparse
import csv
import os
from pprint import pprint
def parse_tsv(annotations_file, testNameReplacement, verbose):
tests = dict()
with open(annotations_file, 'rb') as csvfile:
reader = csv.reader(csvfile, dialect='excel-tab')
for row in reader:
# AsyncDistExtendedStatisticTest extended-statistics/src/test/java/org/infinispan/stats/simple/AsyncDistExtendedStatisticTest.java
# AsyncDistExtendedStatisticTest ISPN-3995 AsyncDistExtendedStatisticTest.testReplaceWithOldVal fails randomly
# AsyncDistExtendedStatisticTest org.infinispan.stats.simple.AsyncDistExtendedStatisticTest.testReplaceWithOldVal 2
if verbose: pprint(row)
class_name = row[0]
row[0] = testNameReplacement
rows = tests.setdefault(class_name, [])
rows.append(row)
if verbose: pprint(tests)
return tests
def print_diffs(target_dict, source1_dict, source2_dict, verbose):
diffs = []
for test, rows in sorted(source1_dict.iteritems()):
if test not in target_dict:
diffs.append((test, rows))
rows = sorted(diffs)
if verbose: pprint(rows)
for test, rows in diffs:
print(test)
for row in rows:
print("\t%s" % ("\t".join(row)))
source2_rows = source2_dict.get(test)
if source2_rows:
for row in source2_rows:
print("\t%s" % ("\t".join(row)))
print('')
def main(args):
verbose = args.verbose
annotations_file = args.annotations_file
jiras_file = args.jira_file
teamcity_file = args.teamcity_file
location = args.find_missing
if verbose: print csv.list_dialects(); print os.getcwd()
annotations = parse_tsv(annotations_file, "annotation", verbose)
jiras = parse_tsv(jiras_file, "jira", verbose)
teamcity_failures = parse_tsv(teamcity_file, "failure", verbose)
if location == 'jira' or location == 'all':
print("Tests annotated as unstable or failing in TeamCity missing an issue in JIRA:")
print_diffs(jiras, annotations, teamcity_failures, verbose)
if location == 'annotation' or location == 'all':
print("Tests with a random failure issue in JIRA or failing in TeamCity missing the unstable annotation:")
print_diffs(annotations, jiras, teamcity_failures, verbose)
if location == 'teamcity' or location == 'all':
print("Tests annotated as unstable or with a random failure issue in JIRA but not failing in TeamCity:")
print_diffs(teamcity_failures, annotations, jiras, verbose)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--annotations-file", help="Unstable test annotations file",
required=True)
parser.add_argument("-j", "--jira-file", help="Unstable test JIRAs file", required=True)
parser.add_argument("-t", "--teamcity-file", help="TeamCity test failures file",
required=True)
parser.add_argument("-v", "--verbose", help="print debugging information",
action="store_true")
parser.add_argument("find_missing",
choices=['jira', 'teamcity', 'annotation', 'all'], default='all')
args = parser.parse_args()
if args.verbose: pprint(args)
main(args) | 3,301 | 36.101124 | 136 | py |
infinispan | infinispan-main/bin/greplog.py | #!/usr/bin/python
from __future__ import print_function
import argparse
import fileinput
import re
import sys
def handleMessage(message, filter):
if filter.search(message):
print(message, end='')
def main():
parser = argparse.ArgumentParser("Filter logs")
parser.add_argument('pattern', nargs=1,
help='Filter pattern')
parser.add_argument('files', metavar='file', nargs='*', default='-',
help='Input file')
args = parser.parse_args()
#print(args)
#pattern = sys.argv[1]
#files = sys.argv[2:]
pattern = args.pattern[0]
files = args.files
messageStartFilter = re.compile('.* (FATAL|ERROR|WARN|INFO|DEBUG|TRACE)')
messageFilter = re.compile(pattern, re.MULTILINE | re.DOTALL)
f = fileinput.input(files)
message = ""
for line in f:
if messageStartFilter.match(line):
handleMessage(message, messageFilter)
message = line
else:
message = message + line
handleMessage(message, messageFilter)
main()
| 1,040 | 22.133333 | 76 | py |
infinispan | infinispan-main/bin/find_disabled_tests.py | #!/usr/bin/python
import re
import time
import sys
from utils import *
def main():
start_time = time.clock()
disabled_test_files = []
test_annotation_matcher = re.compile('^\s*@Test')
disabled_matcher = re.compile('enabled\s*=\s*false')
for test_file in GlobDirectoryWalker(get_search_path(sys.argv[0]), '*Test.java'):
tf = open(test_file)
try:
for line in tf:
if test_annotation_matcher.search(line) and disabled_matcher.search(line):
disabled_test_files.append(test_file)
break
finally:
tf.close()
print "Files containing disabled tests: \n"
unique_tests=to_set(disabled_test_files)
i = 1
for f in unique_tests:
zeropad=""
if i < 10 and len(unique_tests) > 9:
zeropad = " "
print "%s%s. %s" % (zeropad, str(i), strip_leading_dots(f))
i += 1
print "\n (finished in " + str(time.clock() - start_time) + " seconds)"
if __name__ == '__main__':
main()
| 972 | 23.948718 | 83 | py |
infinispan | infinispan-main/bin/clean_logs.py | #!/usr/bin/python
from __future__ import with_statement
import re
import subprocess
import os
import sys
VIEW_TO_USE = '3'
INPUT_FILE = "infinispan.log"
OUTPUT_FILE = "infinispan0.log"
addresses = {}
new_addresses = {}
def find(filename, expr):
with open(filename) as f:
for l in f:
if expr.match(l):
handle(l, expr)
break
def handle(l, expr):
"""Handles a given line of log file, to be parsed and substituted"""
m = expr.match(l)
print "Using JGROUPS VIEW line:"
print " %s" % l
members = m.group(1).strip()
i = 1
for m in members.split(','):
addresses[m.strip()] = "CACHE%s" % i
new_addresses["CACHE%s" % i] = m.strip()
i += 1
def help():
print '''
INFINISPAN log file fixer. Makes log files more readable by replacing JGroups addresses with friendly names.
'''
def usage():
print '''
Usage:
$ bin/cleanlogs.py <N> <input_file> <output_file>
OR:
$ bin/cleanlogs.py <input_file> <output_file> to allow the script to guess which view is most appropriate.
N: (number) the JGroups VIEW ID to use as the definite list of caches. Choose a view which has the most complete cache list.
input_file: path to log file to transform
output_file: path to result file
'''
def guess_view(fn):
"""Guesses which view is the most complete, by looking for the view with the largest number of members. Inaccurate for log files that involve members leaving and others joining at the same time."""
all_views_re = re.compile('.*Received new cluster view.*\|([0-9]+). \[(.*)\].*')
views = {}
with open(fn) as f:
for l in f:
m = all_views_re.match(l)
if m:
view_num = m.group(1)
members = m.group(2)
views[view_num] = as_list(members)
return views
def most_likely_view(views):
"""Picks the most likely view from a dictionary of views, keyed on view ID. Returns the view ID."""
largest_view = -1
lvid = -1
for i in views.items():
if largest_view < len(i[1]):
largest_view = len(i[1])
lvid = i[0]
return lvid
def as_list(string_members):
"""Returns a string of comma-separated member addresses as a list"""
ml = []
for m in string_members.split(","):
ml.append(m.strip())
return ml
def main():
help()
### Get args
if len(sys.argv) != 4 and len(sys.argv) != 3:
usage()
sys.exit(1)
if len(sys.argv) == 4:
VIEW_TO_USE = int(sys.argv[1])
INPUT_FILE = sys.argv[2]
OUTPUT_FILE = sys.argv[3]
else:
INPUT_FILE = sys.argv[1]
OUTPUT_FILE = sys.argv[2]
views = guess_view(INPUT_FILE)
VIEW_TO_USE = most_likely_view(views)
print "Guessing you want view id %s" % VIEW_TO_USE
expr = re.compile('.*Received new cluster view.*\|%s. \[(.*)\].*' % VIEW_TO_USE)
find(INPUT_FILE, expr)
with open(INPUT_FILE) as f_in:
with open(OUTPUT_FILE, 'w+') as f_out:
for l in f_in:
for c in addresses.keys():
l = l.replace(c, addresses[c])
f_out.write(l)
print "Processed %s and generated %s. The following replacements were made: " % (INPUT_FILE, OUTPUT_FILE)
sorted_keys = new_addresses.keys()
sorted_keys.sort()
for a in sorted_keys:
print " %s --> %s" % (new_addresses[a], a)
if __name__ == "__main__":
main()
| 3,285 | 27.08547 | 200 | py |
infinispan | infinispan-main/bin/find_unstable_tests_jira.py | #!/usr/bin/python
"""
Search JIRA using the restkit library (yum install python-restkit).
JIRA REST API documentation: https://docs.atlassian.com/jira/REST/5.0-m5
"""
import json
import re
from restkit import Resource, BasicAuth, request
from pprint import pprint
import argparse
from getpass import getpass
import csv
import sys
default_base_url = 'https://issues.jboss.org'
jql_search = 'project = ISPN AND (component in ("Test Suite - Core", "Test Suite - Server", "Test Suite - Query") OR labels = testsuite_stability) AND status in (Open, "Coding In Progress", Reopened, "Pull Request Sent") ORDER BY priority DESC'
def main(args):
verbose = args.verbose
server_base_url = args.url
user = args.user
password = args.password
# This sends the user and password with the request.
filters = []
if user:
auth = BasicAuth(user, password)
filters = [auth]
url = "%s/rest/api/latest" % (server_base_url)
resource = Resource(url, filters=filters)
issueList = get_json(resource, "search", jql=jql_search, fields="key,issuetype,created,status,summary", expand="renderedFields", maxResults=500)
if verbose: pprint(issueList)
tests = []
for issue in issueList['issues']:
id = issue['key']
summary = issue['fields']['summary']
match = re.search(r'\w+Test', summary)
if match:
test = match.group(0)
tests.append((test, id, summary))
tests = sorted(tests)
csvwriter = csv.writer(sys.stdout, dialect='excel-tab')
for row in tests:
csvwriter.writerow(row)
def get_json(resource, path, **params):
response = resource.get(path, headers={'Content-Type': 'application/json'},
params_dict = params)
# Most successful responses have an HTTP 200 status
if response.status_int != 200:
raise Exception("ERROR: status %s" % response.status_int)
# Convert the text in the reply into a Python dictionary
return json.loads(response.body_string())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--url", help="site URL", default=default_base_url)
parser.add_argument("-u", "--user", help="user name", required = True)
parser.add_argument("-p", "--password", help="password")
parser.add_argument("-v", "--verbose", help="print debugging information", action="store_true")
args = parser.parse_args()
if args.user and not args.password:
args.password = getpass()
main(args)
| 2,435 | 29.45 | 244 | py |
infinispan | infinispan-main/bin/utils.py | import os
import fnmatch
import re
import subprocess
import sys
import readline
import shutil
import random
settings_file = '%s/.infinispan_dev_settings' % os.getenv('HOME')
upstream_url = '[email protected]:infinispan/infinispan.git'
### Known config keys
local_mvn_repo_dir_key = "local_mvn_repo_dir"
maven_pom_xml_namespace = "http://maven.apache.org/POM/4.0.0"
default_settings = {'dry_run': False, 'multi_threaded': False, 'verbose': False, 'use_colors': True}
boolean_keys = ['dry_run', 'multi_threaded', 'verbose']
class Colors(object):
MAGENTA = '\033[95m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
CYAN = '\033[96m'
END = '\033[0m'
UNDERLINE = '\033[4m'
@staticmethod
def magenta():
if use_colors():
return Colors.MAGENTA
else:
return ""
@staticmethod
def green():
if use_colors():
return Colors.GREEN
else:
return ""
@staticmethod
def yellow():
if use_colors():
return Colors.YELLOW
else:
return ""
@staticmethod
def red():
if use_colors():
return Colors.RED
else:
return ""
@staticmethod
def cyan():
if use_colors():
return Colors.CYAN
else:
return ""
@staticmethod
def end_color():
if use_colors():
return Colors.END
else:
return ""
class Levels(Colors):
C_DEBUG = Colors.CYAN
C_INFO = Colors.GREEN
C_WARNING = Colors.YELLOW
C_FATAL = Colors.RED
C_ENDC = Colors.END
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
FATAL = "FATAL"
@staticmethod
def get_color(level):
if use_colors():
return getattr(Levels, "C_" + level)
else:
return ""
def use_colors():
return ('use_colors' in settings and settings['use_colors']) or ('use_colors' not in settings)
def prettyprint(message, level):
start_color = Levels.get_color(level)
end_color = Levels.end_color()
print("[%s%s%s] %s" % (start_color, level, end_color, message))
def apply_defaults(s):
for e in default_settings.items():
if e[0] not in s:
s[e[0]] = e[1]
return s
def to_bool(x):
if type(x) == bool:
return x
if type(x) == str:
return {'true': True, 'false': False}.get(x.strip().lower())
def get_settings():
"""Retrieves user-specific settings for all Infinispan tools. Returns a dict of key/value pairs, or an empty dict if the settings file doesn't exist."""
f = None
try:
settings = {}
f = open(settings_file)
for l in f:
if not l.strip().startswith("#"):
kvp = l.split("=")
if kvp and len(kvp) > 0 and kvp[0] and len(kvp) > 1:
settings[kvp[0].strip()] = kvp[1].strip()
settings = apply_defaults(settings)
for k in boolean_keys:
settings[k] = to_bool(settings[k])
return settings
except IOError as ioe:
return {}
finally:
if f:
f.close()
settings = get_settings()
def input_with_default(msg, default):
i = raw_input("%s %s[%s]%s: " % (msg, Colors.magenta(), default, Colors.end_color()))
if i.strip() == "":
i = default
return i
def handle_release_virgin():
"""This sounds dirty!"""
prettyprint("""
It appears that this is the first time you are using this script. I need to ask you a few questions before
we can proceed. Default values are in brackets, just hitting ENTER will accept the default value.
Lets get started!
""", Levels.WARNING)
s = {}
s["verbose"] = input_with_default("Be verbose?", False)
s["multi_threaded"] = input_with_default("Run multi-threaded? (Disable to debug)", True)
s["use_colors"] = input_with_default("Use colors?", True)
s = apply_defaults(s)
f = open(settings_file, "w")
try:
for e in s.keys():
f.write(" %s = %s \n" % (e, s[e]))
finally:
f.close()
def require_settings_file(recursive = False):
"""Tests whether the settings file exists, and if not prompts the user to create one."""
f = None
try:
f = open(settings_file)
except IOError as ioe:
if not recursive:
handle_release_virgin()
require_settings_file(True)
prettyprint("User-specific environment settings file %s created! Please start this script again!" % settings_file, Levels.INFO)
sys.exit(4)
else:
prettyprint("User-specific environment settings file %s is missing! Cannot proceed!" % settings_file, Levels.FATAL)
prettyprint("Please create a file called %s with the following lines:" % settings_file, Levels.FATAL)
prettyprint( '''
verbose = False
use_colors = True
multi_threaded = True
''', Levels.INFO)
sys.exit(3)
finally:
if f:
f.close()
def get_search_path(executable):
"""Retrieves a search path based on where the current executable is located. Returns a string to be prepended to add"""
in_bin_dir = re.compile('^.*/?bin/.*.py')
if in_bin_dir.search(executable):
return "./"
else:
return "../"
def strip_leading_dots(filename):
return filename.strip('/. ')
def to_set(list):
"""Crappy implementation of creating a Set from a List. To cope with older Python versions"""
temp_dict = {}
for entry in list:
temp_dict[entry] = "dummy"
return temp_dict.keys()
class GlobDirectoryWalker:
"""A forward iterator that traverses a directory tree"""
def __init__(self, directory, pattern="*"):
self.stack = [directory]
self.pattern = pattern
self.files = []
self.index = 0
def __getitem__(self, index):
while True:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
if fnmatch.fnmatch(file, self.pattern):
return fullname
class Git(object):
'''Encapsulates git functionality necessary for releasing Infinispan'''
cmd = 'git'
# Helper functions to clean up branch lists
@staticmethod
def clean(e): return e.strip().replace(' ', '').replace('*', '')
@staticmethod
def non_empty(e): return e != None and e.strip() != ''
@staticmethod
def current(e): return e != None and e.strip().replace(' ', '').startswith('*')
def __init__(self, branch, tag_name):
if not self.is_git_directory():
raise Exception('Attempting to run git outside of a repository. Current directory is %s' % os.path.abspath(os.path.curdir))
self.branch = branch
self.tag = tag_name
self.verbose = False
if settings['verbose']:
self.verbose = True
rand = '%x'.upper() % (random.random() * 100000)
self.working_branch = '__temp_%s' % rand
self.original_branch = self.current_branch()
def run_git(self, opts):
call = [self.cmd]
if type(opts) == list:
for o in opts:
call.append(o)
elif type(opts) == str:
for o in opts.split(' '):
if o != '':
call.append(o)
else:
raise Error("Cannot handle argument of type %s" % type(opts))
if settings['verbose']:
prettyprint( 'Executing %s' % call, Levels.DEBUG )
return subprocess.Popen(call, stdout=subprocess.PIPE).communicate()[0].split('\n')
def is_git_directory(self):
return self.run_git('branch')[0] != ''
def is_upstream_clone(self):
r = self.run_git('remote show -n origin')
cleaned = map(self.clean, r)
def push(e): return e.startswith('PushURL:')
def remove_noise(e): return e.replace('PushURL:', '')
push_urls = map(remove_noise, filter(push, cleaned))
return len(push_urls) == 1 and push_urls[0] == upstream_url
def clean_branches(self, raw_branch_list):
return map(self.clean, filter(self.non_empty, raw_branch_list))
def remote_branch_exists(self):
'''Tests whether the branch exists on the remote origin'''
branches = self.clean_branches(self.run_git("branch -r"))
def replace_origin(b): return b.replace('origin/', '')
return self.branch in map(replace_origin, branches)
def switch_to_branch(self):
'''Switches the local repository to the specified branch. Creates it if it doesn't already exist.'''
local_branches = self.clean_branches(self.run_git("branch"))
if self.branch not in local_branches:
self.run_git("branch %s origin/%s" % (self.branch, self.branch))
self.run_git("checkout %s" % self.branch)
def create_tag_branch(self):
'''Creates and switches to a temp tagging branch, based off the release branch.'''
self.run_git("checkout -b %s %s" % (self.working_branch, self.branch))
def commit(self, files, message):
'''Commits the set of files to the current branch with a generated commit message.'''
for f in files:
self.run_git("add %s" % f)
self.run_git(["commit", "-m", message])
def commit_modified(self, message):
'''Commits all the files that were modified in working copy to the current branch with a generated commit message.'''
self.run_git(["commit", "-a", "-m", message])
def tag_for_release(self):
'''Tags the current branch for release using the tag name.'''
self.run_git(["tag", "-a", "-m", "'Release Script: tag %s'" % self.tag, self.tag])
def push_tag_to_origin(self):
'''Pushes the updated tags to origin'''
self.run_git("push origin --tags")
def push_branch_to_origin(self):
'''Pushes the updated branch to origin'''
self.run_git("push origin %s" % (self.branch))
def current_branch(self):
'''Returns the current branch you are on'''
return map(self.clean, filter(self.current, self.run_git('branch')))[0]
def cleanup(self):
'''Cleans up any temporary branches created'''
self.run_git("checkout %s" % self.original_branch)
self.run_git("branch -D %s" % self.working_branch)
def clean_release_directory(self):
'''Makes sure that no files exist in the working directory that might affect the content of the distribution'''
self.run_git("clean -d -x -f")
self.run_git("reset --hard HEAD")
class DryRun(object):
location_root = "%s/%s" % (os.getenv("HOME"), "infinispan_release_dry_run")
def find_version(self, url):
return os.path.split(url)[1]
def copy(self, src, dst):
prettyprint( " DryRun: Executing %s" % ['rsync', '-rv', '--protocol=28', src, dst], Levels.DEBUG)
try:
os.makedirs(dst)
except:
pass
subprocess.check_call(['rsync', '-rv', '--protocol=28', src, dst])
class Uploader(object):
def __init__(self):
if settings['verbose']:
self.scp_cmd = ['scp', '-rv']
self.rsync_cmd = ['rsync', '-rv', '--protocol=28']
else:
self.scp_cmd = ['scp', '-r']
self.rsync_cmd = ['rsync', '-r', '--protocol=28']
def upload_scp(self, fr, to, flags = []):
self.upload(fr, to, flags, list(self.scp_cmd))
def upload_rsync(self, fr, to, flags = []):
self.upload(fr, to, flags, list(self.rsync_cmd))
def upload(self, fr, to, flags, cmd):
for e in flags:
cmd.append(e)
cmd.append(fr)
cmd.append(to)
subprocess.check_call(cmd)
class DryRunUploader(DryRun):
def upload_scp(self, fr, to, flags = []):
self.upload(fr, to, "scp")
def upload_rsync(self, fr, to, flags = []):
self.upload(fr, to.replace(':', '____').replace('@', "__"), "rsync")
def upload(self, fr, to, type):
self.copy(fr, "%s/%s/%s" % (self.location_root, type, to))
def maven_build_distribution(version):
"""Builds the distribution in the current working dir"""
mvn_commands = [["clean"], ["install"], ["deploy", "-Pdistribution,extras"]]
for c in mvn_commands:
c.append("-Dmaven.test.skip.exec=true")
c.append("-DskipTests")
if settings['dry_run']:
c.append("-Dmaven.deploy.skip=true")
if not settings['verbose']:
c.insert(0, '-q')
c.insert(0, 'mvn')
subprocess.check_call(c)
def get_version_pattern():
return re.compile("^([1-9]?[0-9]+\.[1-9]?[0-9]+)\.[1-9]?[0-9]+\.(Final|(Alpha|Beta|CR)[1-9][0-9]?)$")
def get_version_major_minor(full_version):
pattern = get_version_pattern()
matcher = pattern.match(full_version)
return matcher.group(1)
def assert_python_minimum_version(major, minor):
e = re.compile('([0-9])\.([0-9])\.([0-9]).*')
m = e.match(sys.version)
major_ok = int(m.group(1)) == major
minor_ok = int(m.group(2)) >= minor
if not (minor_ok and major_ok):
prettyprint( "This script requires Python >= %s.%s.0. You have %s" % (major, minor, sys.version), Levels.FATAL)
sys.exit(3)
| 12,812 | 29.65311 | 155 | py |
infinispan | infinispan-main/bin/find_unstable_tests_teamcity.py | #!/usr/bin/python
"""
Search JIRA using the restkit library (yum install python-restkit).
Teamcity REST API documentation: http://confluence.jetbrains.com/display/TCD8/REST+API
"""
import json
import re
from restkit import Resource, BasicAuth, request
from pprint import pprint
import argparse
import datetime
from getpass import getpass
import csv
import sys
default_base_url = 'http://ci.infinispan.org'
default_build_types = ['Master Hotspot JDK6', 'Master Hotspot JDK7', 'Master Unstable Tests JDK6']
default_days = 15
def main(args):
verbose = args.verbose
server_base_url = args.base_url
user = args.user
password = args.password
days = args.days
build_type_names = args.build
# This sends the user and password with the request.
url = "%s/guestAuth/app/rest/" % (server_base_url)
filters = []
if user:
auth = BasicAuth(user, password)
filters = [auth]
url = "%s/httpAuth/app/rest/" % (server_base_url)
resource = Resource(url, filters=filters)
buildTypes = get_json(resource, "buildTypes")
watched_build_type_ids = [bt['id'] for bt in buildTypes['buildType']
if bt['name'] in default_build_types]
if verbose: print("Found build ids: %s" %watched_build_type_ids)
unstable_tests = []
for btid in watched_build_type_ids:
days_delta = datetime.timedelta(days=default_days)
days_ago = datetime.datetime.utcnow() - days_delta
date = days_ago.strftime('%Y%m%dT%H%M%S') + '+0000'
builds_path = 'buildTypes/id:%s/builds' % btid
builds = get_json(resource, builds_path, locator = build_locator(sinceDate = date, status = 'FAILURE'))
build_ids = [build['id'] for build in builds['build']]
if verbose: print("Found build ids for build type %s: %s" % (btid, build_ids))
for bid in build_ids:
build_path = "builds/id:%s" % bid
build = get_json(resource, build_path)
#pprint(build)
bname = "%s#%s" % (build['buildType']['name'], build['number'])
bdate = build['startDate']
test_occurrences_path = "testOccurrences"
failed_tests = get_json(resource, test_occurrences_path, locator = build_locator(build = "(id:%s)" % bid, status = 'FAILURE'))
#pprint(failed_tests)
if 'testOccurrence' in failed_tests:
failed_test_names = [test['name'] for test in failed_tests['testOccurrence']]
if verbose: print("Found failed tests for build %s: %s" % (bid, failed_test_names))
for test_name in failed_test_names:
clean_test_name = test_name.replace("TestSuite: ", "")
unstable_tests.append((extract_class_name(clean_test_name), clean_test_name, bname, bdate))
unstable_tests = sorted(unstable_tests)
csvwriter = csv.writer(sys.stdout, dialect='excel-tab')
for row in unstable_tests:
csvwriter.writerow(row)
def extract_class_name(test_name):
match = re.search(r'\w+Test', test_name)
if match:
class_name = match.group(0)
else:
components = test_name.split('.')
class_name = components[-2]
return class_name
def build_locator(**locators):
return ",".join("%s:%s" %(k, v) for (k, v )in locators.items())
def get_json(resource, path, **params):
response = resource.get(path, headers={'Accept': 'application/json'},
params_dict = params)
# Most successful responses have an HTTP 200 status
if response.status_int != 200:
raise Exception("ERROR: status %s" % response.status_int)
# Convert the text in the reply into a Python dictionary
return json.loads(response.body_string())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--base-url", help="base URL", default=default_base_url)
parser.add_argument("-u", "--user", help="user name")
parser.add_argument("-p", "--password", help="password")
parser.add_argument("-d", "--days", help="days to search back", default=default_days)
parser.add_argument("--build", help="one or more builds to search", nargs='*', action='append', default=default_build_types)
parser.add_argument("-v", "--verbose", help="print debugging information", action="store_true")
args = parser.parse_args()
if args.user and not args.password:
args.password = getpass()
main(args) | 4,221 | 33.892562 | 132 | py |
infinispan | infinispan-main/bin/find_broken_links.py | #!/usr/bin/python3
import re
import os
from urllib.request import Request, urlopen
"""
Finds broken links in documentation. Takes ~13 minutes. Run from root infinispan directory.
"""
rootDir = 'documentation/target/generated-docs/'
def isBad(url):
req = Request(url, headers={'User-Agent': 'Mozilla/5.0 Chrome/41.0.2228.0 Safari/537.36'})
try:
if urlopen(req).status != 200:
return True
except Exception as e:
return True
return False
def findUrls(str):
return re.findall('<a href="(https?://[^"]*)"', str)
badUrls = 0
urls = dict() # url -> files containing that url
for dirName, subdirList, fileList in os.walk(rootDir):
for file in fileList:
if file.endswith('.html'):
for url in findUrls(''.join(open(dirName + file).readlines())):
if url.rfind('http://localhost') != -1:
continue
if not urls.__contains__(url):
urls.update({url: set()})
urls.get(url).add(dirName + file)
for url in urls.keys():
if isBad(url):
print(url, urls.get(url))
badUrls += 1
print('Number of unique URLS checked: ', len(urls))
print('Number of bad URLs: ', badUrls)
| 1,237 | 27.136364 | 95 | py |
infinispan | infinispan-main/bin/report_thread_leaks.py | #!/usr/bin/python3
import fileinput
import re
import sys
# Usage:
# * Add a breakpoint in Thread.start()
# * Action: new RuntimeException(String.format("Thread %s started thread %s", Thread.currentThread().getName(), name)).printStackTrace()
# * Condition: name.startsWith("<thread name prefix reported as thread leak>")
# * Run tests with the debugger attached and tee the output to build.log
# * Run report_thread_leaks.py build.log
# TODO Replace the conditional breakpoint with a Byteman script
re_leaked_threads_header = re.compile(r'.*java.lang.RuntimeException: Leaked threads:')
# {HotRod-client-async-pool-88-15: reported, possible sources [UNKNOWN]},
re_leaked_thread_line = re.compile(r'.* \{(.*):.* possible sources \[(.*)\]\}.*')
# java.lang.RuntimeException: Thread main started thread HotRod-client-async-pool-92-1
re_started_thread_header = re.compile(r'.*java.lang.RuntimeException: Thread (.*) started thread (.*)')
# \tat java.base/java.lang.Thread.start(Thread.java:793)
re_stacktrace = re.compile('.*(\tat .*)')
# at org.infinispan.server.test.client.hotrod.HotRodRemoteStreamingIT.RCMStopTest(HotRodRemoteStreamingIT.java:279)
re_interesting_stacktrace = re.compile('\tat .*(Test|IT).java')
lines = iter(fileinput.input(sys.argv[1:]))
leaks = []
threads = dict()
def advance():
global line, lines
line = next(lines, None)
advance()
while line:
m = re_started_thread_header.match(line)
if m:
thread_name = m.group(2)
thread_parent = m.group(1)
parent_stacktrace = []
advance()
while line:
m = re_stacktrace.match(line)
if m:
if re_interesting_stacktrace.match(m.group(1)):
parent_stacktrace.append(m.group(1))
advance()
else:
break
threads[thread_name] = (thread_parent, parent_stacktrace)
m = re_leaked_threads_header.match(line)
if m:
advance()
while line:
m = re_leaked_thread_line.match(line)
if m:
leaks.append(m.group(1))
advance()
else:
break
for leak in leaks:
print("- Leaked thread: %s" % leak)
thread = leak
parent = threads.get(leak, None)
if not parent:
print(" - INFORMATION MISSING")
continue
while parent:
if parent[1]:
parentStack = "\n" + "\n".join(parent[1])
else:
parentStack = ""
print(" - %s started by: %s%s" % (thread, parent[0], parentStack))
thread = parent[0]
parent = threads.get(thread, None)
print("")
leaks.clear()
threads.clear()
advance()
| 2,713 | 28.5 | 136 | py |
infinispan | infinispan-main/bin/list_command_ids.py | #!/usr/bin/python
import re
import sys
from utils import *
command_file_name = re.compile('([a-zA-Z0-9/]*Command.java)')
def trim_name(nm):
res = command_file_name.search(nm)
if res:
return res.group(1)
else:
return nm
def get_next(ids_used):
# Cannot assume a command ID greater than the size of 1 byte!
for i in range(1, 128):
if i not in ids_used:
return i
return -1
command_line_regexp = re.compile('COMMAND_ID\s*=\s*([0-9]+)\s*;')
command_ids = {}
warnings = []
for test_file in GlobDirectoryWalker(get_search_path(sys.argv[0]) + 'core/src/main/java/', '*Command.java'):
tf = open(test_file)
try:
for line in tf:
mo = command_line_regexp.search(line)
if mo:
id = int(mo.group(1))
trimmed_name = trim_name(test_file)
if id in command_ids:
warnings.append("Saw duplicate COMMAND_IDs in files [%s] and [%s]" % (trimmed_name, command_ids[id]))
command_ids[id] = trimmed_name
finally:
tf.close()
print('Scanned %s Command source files. IDs are (in order):' % len(command_ids))
sorted_keys = sorted(command_ids.keys())
i=1
prev_id = 0
for k in sorted_keys:
prev_id += 1
while k > prev_id:
print(' ---')
prev_id += 1
zeropad = ""
if (i < 10 and len(sorted_keys) > 9):
zeropad = " "
if i < 100 and len(sorted_keys) > 90:
zeropad += " "
print(' %s%s) Class [%s%s%s] has COMMAND_ID [%s%s%s]' % (zeropad, i, Colors.green(), command_ids[k], Colors.end_color(), Colors.yellow(), k, Colors.end_color()))
i += 1
print("\n")
if len(warnings) > 0:
print("WARNINGS:")
for w in warnings:
print(" *** %s" % w)
print("\n")
print("Next available ID is %s%s%s" % (Colors.cyan(), get_next(sorted_keys), Colors.end_color()))
| 1,762 | 23.830986 | 164 | py |
infinispan | infinispan-main/bin/find_unstable_tests.py | #!/usr/bin/python
import re
import time
import sys
import csv
import argparse
import os.path
import fnmatch
def main(args):
base_dir = args.dir
annotated_test_files = []
disabled_test_matcher = re.compile('\s*@Test.*groups\s*=\s*("unstable|Array\("unstable"\))|@Category\(UnstableTest\.class\).*')
filename_matcher = re.compile('.*Test.(java|scala)')
for dirpath, dirnames, filenames in os.walk(base_dir):
for filename in filenames:
if filename_matcher.match(filename):
test_file = os.path.join(dirpath, filename)
with open(test_file) as tf:
for line in tf:
if disabled_test_matcher.search(line):
class_name = os.path.splitext(filename)[0]
rel_test_file = os.path.relpath(test_file, base_dir)
annotated_test_files.append((class_name, rel_test_file))
break
annotated_test_files=sorted(annotated_test_files)
csvwriter = csv.writer(sys.stdout, dialect='excel-tab')
for row in annotated_test_files:
csvwriter.writerow(row)
def extract_class_name(f):
return splitext(basename(f))[0]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("dir", help="base directory", nargs='?', default='.')
args = parser.parse_args()
main(args)
| 1,302 | 26.145833 | 129 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.