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 |
---|---|---|---|---|---|---|
pytorch-playground | pytorch-playground-master/svhn/dataset.py | import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import os
def get(batch_size, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):
data_root = os.path.expanduser(os.path.join(data_root, 'svhn-data'))
num_workers = kwargs.setdefault('num_workers', 1)
kwargs.pop('input_size', None)
print("Building SVHN data loader with {} workers".format(num_workers))
def target_transform(target):
return int(target) - 1
ds = []
if train:
train_loader = torch.utils.data.DataLoader(
datasets.SVHN(
root=data_root, split='train', download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]),
target_transform=target_transform,
),
batch_size=batch_size, shuffle=True, **kwargs)
ds.append(train_loader)
if val:
test_loader = torch.utils.data.DataLoader(
datasets.SVHN(
root=data_root, split='test', download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]),
target_transform=target_transform
),
batch_size=batch_size, shuffle=False, **kwargs)
ds.append(test_loader)
ds = ds[0] if len(ds) == 1 else ds
return ds
| 1,565 | 34.590909 | 93 | py |
pytorch-playground | pytorch-playground-master/svhn/__init__.py | 0 | 0 | 0 | py |
|
pytorch-playground | pytorch-playground-master/svhn/train.py | import argparse
import os
import time
from utee import misc
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import dataset
import model
from IPython import embed
parser = argparse.ArgumentParser(description='PyTorch SVHN Example')
parser.add_argument('--channel', type=int, default=32, help='first conv channel (default: 32)')
parser.add_argument('--wd', type=float, default=0.001, help='weight decay')
parser.add_argument('--batch_size', type=int, default=200, help='input batch size for training (default: 64)')
parser.add_argument('--epochs', type=int, default=150, help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.001, help='learning rate (default: 1e-3)')
parser.add_argument('--gpu', default=None, help='index of gpus to use')
parser.add_argument('--ngpu', type=int, default=2, help='number of gpus to use')
parser.add_argument('--seed', type=int, default=117, help='random seed (default: 1)')
parser.add_argument('--log_interval', type=int, default=100, help='how many batches to wait before logging training status')
parser.add_argument('--test_interval', type=int, default=5, help='how many epochs to wait before another test')
parser.add_argument('--logdir', default='log/default', help='folder to save to the log')
parser.add_argument('--data_root', default='/tmp/public_dataset/pytorch/', help='folder to save the model')
parser.add_argument('--decreasing_lr', default='80,120', help='decreasing strategy')
args = parser.parse_args()
args.logdir = os.path.join(os.path.dirname(__file__), args.logdir)
misc.logger.init(args.logdir, 'train_log')
print = misc.logger.info
# select gpu
args.gpu = misc.auto_select_gpu(utility_bound=0, num_gpu=args.ngpu, selected_gpus=args.gpu)
args.ngpu = len(args.gpu)
# logger
misc.ensure_dir(args.logdir)
print("=================FLAGS==================")
for k, v in args.__dict__.items():
print('{}: {}'.format(k, v))
print("========================================")
# seed
args.cuda = torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
# data loader and model
train_loader, test_loader = dataset.get(batch_size=args.batch_size, data_root=args.data_root, num_workers=1)
model = model.svhn(n_channel=args.channel)
model = torch.nn.DataParallel(model, device_ids= range(args.ngpu))
if args.cuda:
model.cuda()
# optimizer
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)
decreasing_lr = list(map(int, args.decreasing_lr.split(',')))
print('decreasing_lr: ' + str(decreasing_lr))
best_acc, old_file = 0, None
t_begin = time.time()
try:
for epoch in range(args.epochs):
model.train()
if epoch in decreasing_lr:
optimizer.param_groups[0]['lr'] *= 0.1
for batch_idx, (data, target) in enumerate(train_loader):
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0 and batch_idx > 0:
pred = output.data.max(1)[1] # get the index of the max log-probability
correct = pred.cpu().eq(indx_target).sum()
acc = correct * 1.0 / len(data)
print('Train Epoch: {} [{}/{}] Loss: {:.6f} Acc: {:.4f} lr: {:.2e}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
loss.data[0], acc, optimizer.param_groups[0]['lr']))
elapse_time = time.time() - t_begin
speed_epoch = elapse_time / (epoch + 1)
speed_batch = speed_epoch / len(train_loader)
eta = speed_epoch * args.epochs - elapse_time
print("Elapsed {:.2f}s, {:.2f} s/epoch, {:.2f} s/batch, ets {:.2f}s".format(
elapse_time, speed_epoch, speed_batch, eta))
misc.model_snapshot(model, os.path.join(args.logdir, 'latest.pth'))
if epoch % args.test_interval == 0:
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda().long().squeeze()
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += F.cross_entropy(output, target).data[0]
pred = output.data.max(1)[1] # get the index of the max log-probability
correct += pred.cpu().eq(indx_target).sum()
test_loss = test_loss / len(test_loader) # average over number of mini-batch
acc = 100. * correct / len(test_loader.dataset)
print('\tTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(
test_loss, correct, len(test_loader.dataset), acc))
if acc > best_acc:
new_file = os.path.join(args.logdir, 'best-{}.pth'.format(epoch))
misc.model_snapshot(model, new_file, old_file=old_file, verbose=True)
best_acc = acc
old_file = new_file
except Exception as e:
import traceback
traceback.print_exc()
finally:
print("Total Elapse: {:.2f}, Best Result: {:.3f}%".format(time.time()-t_begin, best_acc))
| 5,590 | 43.023622 | 125 | py |
pytorch-playground | pytorch-playground-master/stl10/model.py | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import os
from utee import misc
from collections import OrderedDict
print = misc.logger.info
model_urls = {
'stl10': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/stl10-866321e9.pth',
}
class SVHN(nn.Module):
def __init__(self, features, n_channel, num_classes):
super(SVHN, self).__init__()
assert isinstance(features, nn.Sequential), type(features)
self.features = features
self.classifier = nn.Sequential(
nn.Linear(n_channel, num_classes)
)
print(self.features)
print(self.classifier)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for i, v in enumerate(cfg):
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
padding = v[1] if isinstance(v, tuple) else 1
out_channels = v[0] if isinstance(v, tuple) else v
conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=padding)
if batch_norm:
layers += [conv2d, nn.BatchNorm2d(out_channels, affine=False), nn.ReLU()]
else:
layers += [conv2d, nn.ReLU()]
in_channels = out_channels
return nn.Sequential(*layers)
def stl10(n_channel, pretrained=None):
cfg = [
n_channel, 'M',
2*n_channel, 'M',
4*n_channel, 'M',
4*n_channel, 'M',
(8*n_channel, 0), (8*n_channel, 0), 'M'
]
layers = make_layers(cfg, batch_norm=True)
model = SVHN(layers, n_channel=8*n_channel, num_classes=10)
if pretrained is not None:
m = model_zoo.load_url(model_urls['stl10'])
state_dict = m.state_dict() if isinstance(m, nn.Module) else m
assert isinstance(state_dict, (dict, OrderedDict)), type(state_dict)
model.load_state_dict(state_dict)
return model
| 2,071 | 30.876923 | 89 | py |
pytorch-playground | pytorch-playground-master/stl10/dataset.py | import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from IPython import embed
import os
def get(batch_size, data_root='/mnt/local0/public_dataset/pytorch/', train=True, val=True, **kwargs):
data_root = os.path.expanduser(os.path.join(data_root, 'stl10-data'))
num_workers = kwargs.setdefault('num_workers', 1)
kwargs.pop('input_size', None)
print("Building STL10 data loader with {} workers".format(num_workers))
ds = []
if train:
train_loader = torch.utils.data.DataLoader(
datasets.STL10(
root=data_root, split='train', download=True,
transform=transforms.Compose([
transforms.Pad(4),
transforms.RandomCrop(96),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])),
batch_size=batch_size, shuffle=True, **kwargs)
ds.append(train_loader)
if val:
test_loader = torch.utils.data.DataLoader(
datasets.STL10(
root=data_root, split='test', download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])),
batch_size=batch_size, shuffle=False, **kwargs)
ds.append(test_loader)
ds = ds[0] if len(ds) == 1 else ds
return ds
if __name__ == '__main__':
train_ds, test_ds = get(200, num_workers=1)
for data, target in train_ds:
print("~~")
| 1,678 | 36.311111 | 101 | py |
pytorch-playground | pytorch-playground-master/stl10/__init__.py | 0 | 0 | 0 | py |
|
pytorch-playground | pytorch-playground-master/stl10/train.py | import argparse
import os
import time
from utee import misc
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import dataset
import model
from IPython import embed
parser = argparse.ArgumentParser(description='PyTorch SVHN Example')
parser.add_argument('--channel', type=int, default=32, help='first conv channel (default: 32)')
parser.add_argument('--wd', type=float, default=0.00, help='weight decay')
parser.add_argument('--batch_size', type=int, default=200, help='input batch size for training (default: 64)')
parser.add_argument('--epochs', type=int, default=150, help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.001, help='learning rate (default: 1e-3)')
parser.add_argument('--gpu', default=None, help='index of gpus to use')
parser.add_argument('--ngpu', type=int, default=2, help='number of gpus to use')
parser.add_argument('--seed', type=int, default=117, help='random seed (default: 1)')
parser.add_argument('--log_interval', type=int, default=20, help='how many batches to wait before logging training status')
parser.add_argument('--test_interval', type=int, default=5, help='how many epochs to wait before another test')
parser.add_argument('--logdir', default='log/default', help='folder to save to the log')
parser.add_argument('--decreasing_lr', default='80,120', help='decreasing strategy')
args = parser.parse_args()
args.logdir = os.path.join(os.path.dirname(__file__), args.logdir)
misc.logger.init(args.logdir, 'train_log')
print = misc.logger.info
# select gpu
args.gpu = misc.auto_select_gpu(utility_bound=0, num_gpu=args.ngpu, selected_gpus=args.gpu)
args.ngpu = len(args.gpu)
# logger
misc.ensure_dir(args.logdir)
print("=================FLAGS==================")
for k, v in args.__dict__.items():
print('{}: {}'.format(k, v))
print("========================================")
# seed
args.cuda = torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
# data loader and model
train_loader, test_loader = dataset.get(batch_size=args.batch_size, num_workers=1)
model = model.stl10(n_channel=args.channel)
model = torch.nn.DataParallel(model, device_ids= range(args.ngpu))
if args.cuda:
model.cuda()
# optimizer
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)
decreasing_lr = list(map(int, args.decreasing_lr.split(',')))
print('decreasing_lr: ' + str(decreasing_lr))
best_acc, old_file = 0, None
t_begin = time.time()
try:
# ready to go
for epoch in range(args.epochs):
model.train()
if epoch in decreasing_lr:
optimizer.param_groups[0]['lr'] *= 0.1
for batch_idx, (data, target) in enumerate(train_loader):
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0 and batch_idx > 0:
pred = output.data.max(1)[1] # get the index of the max log-probability
correct = pred.cpu().eq(indx_target).sum()
acc = correct * 1.0 / len(data)
print('Train Epoch: {} [{}/{}] Loss: {:.6f} Acc: {:.4f} lr: {:.2e}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
loss.data[0], acc, optimizer.param_groups[0]['lr']))
elapse_time = time.time() - t_begin
speed_epoch = elapse_time / (epoch + 1)
speed_batch = speed_epoch / len(train_loader)
eta = speed_epoch * args.epochs - elapse_time
print("Elapsed {:.2f}s, {:.2f} s/epoch, {:.2f} s/batch, ets {:.2f}s".format(
elapse_time, speed_epoch, speed_batch, eta))
misc.model_snapshot(model, os.path.join(args.logdir, 'latest.pth'))
if epoch % args.test_interval == 0:
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda().long().squeeze()
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += F.cross_entropy(output, target).data[0]
pred = output.data.max(1)[1] # get the index of the max log-probability
correct += pred.cpu().eq(indx_target).sum()
test_loss = test_loss / len(test_loader) # average over number of mini-batch
acc = 100. * correct / len(test_loader.dataset)
print('\tTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(
test_loss, correct, len(test_loader.dataset), acc))
if acc > best_acc:
new_file = os.path.join(args.logdir, 'best-{}.pth'.format(epoch))
misc.model_snapshot(model, new_file, old_file=old_file, verbose=True)
best_acc = acc
old_file = new_file
except Exception as e:
import traceback
traceback.print_exc()
finally:
print("Total Elapse: {:.2f}, Best Result: {:.3f}%".format(time.time()-t_begin, best_acc))
| 5,473 | 42.102362 | 124 | py |
pytorch-playground | pytorch-playground-master/imagenet/inception.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from utee import misc
from collections import OrderedDict
__all__ = ['Inception3', 'inception_v3']
model_urls = {
'inception_v3_google': 'https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth',
}
def inception_v3(pretrained=False, model_root=None, **kwargs):
if pretrained:
if 'transform_input' not in kwargs:
kwargs['transform_input'] = True
model = Inception3(**kwargs)
misc.load_state_dict(model, model_urls['inception_v3_google'], model_root)
return model
return Inception3(**kwargs)
class Inception3(nn.Module):
def __init__(self, num_classes=1000, aux_logits=True, transform_input=False):
super(Inception3, self).__init__()
self.aux_logits = aux_logits
self.transform_input = transform_input
self.Conv2d_1a_3x3 = BasicConv2d(3, 32, kernel_size=3, stride=2)
self.Conv2d_2a_3x3 = BasicConv2d(32, 32, kernel_size=3)
self.Conv2d_2b_3x3 = BasicConv2d(32, 64, kernel_size=3, padding=1)
self.Conv2d_3b_1x1 = BasicConv2d(64, 80, kernel_size=1)
self.Conv2d_4a_3x3 = BasicConv2d(80, 192, kernel_size=3)
self.Mixed_5b = InceptionA(192, pool_features=32)
self.Mixed_5c = InceptionA(256, pool_features=64)
self.Mixed_5d = InceptionA(288, pool_features=64)
self.Mixed_6a = InceptionB(288)
self.Mixed_6b = InceptionC(768, channels_7x7=128)
self.Mixed_6c = InceptionC(768, channels_7x7=160)
self.Mixed_6d = InceptionC(768, channels_7x7=160)
self.Mixed_6e = InceptionC(768, channels_7x7=192)
if aux_logits:
self.AuxLogits = InceptionAux(768, num_classes)
self.Mixed_7a = InceptionD(768)
self.Mixed_7b = InceptionE(1280)
self.Mixed_7c = InceptionE(2048)
self.group1 = nn.Sequential(
OrderedDict([
('fc', nn.Linear(2048, num_classes))
])
)
for m in self.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
import scipy.stats as stats
stddev = m.stddev if hasattr(m, 'stddev') else 0.1
X = stats.truncnorm(-2, 2, scale=stddev)
values = torch.Tensor(X.rvs(m.weight.data.numel()))
m.weight.data.copy_(values.reshape(m.weight.shape))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def forward(self, x):
if self.transform_input:
x = x.clone()
x[0] = x[0] * (0.229 / 0.5) + (0.485 - 0.5) / 0.5
x[1] = x[1] * (0.224 / 0.5) + (0.456 - 0.5) / 0.5
x[2] = x[2] * (0.225 / 0.5) + (0.406 - 0.5) / 0.5
# 299 x 299 x 3
x = self.Conv2d_1a_3x3(x)
# 149 x 149 x 32
x = self.Conv2d_2a_3x3(x)
# 147 x 147 x 32
x = self.Conv2d_2b_3x3(x)
# 147 x 147 x 64
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 73 x 73 x 64
x = self.Conv2d_3b_1x1(x)
# 73 x 73 x 80
x = self.Conv2d_4a_3x3(x)
# 71 x 71 x 192
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 35 x 35 x 192
x = self.Mixed_5b(x)
# 35 x 35 x 256
x = self.Mixed_5c(x)
# 35 x 35 x 288
x = self.Mixed_5d(x)
# 35 x 35 x 288
x = self.Mixed_6a(x)
# 17 x 17 x 768
x = self.Mixed_6b(x)
# 17 x 17 x 768
x = self.Mixed_6c(x)
# 17 x 17 x 768
x = self.Mixed_6d(x)
# 17 x 17 x 768
x = self.Mixed_6e(x)
# 17 x 17 x 768
if self.training and self.aux_logits:
aux = self.AuxLogits(x)
# 17 x 17 x 768
x = self.Mixed_7a(x)
# 8 x 8 x 1280
x = self.Mixed_7b(x)
# 8 x 8 x 2048
x = self.Mixed_7c(x)
# 8 x 8 x 2048
x = F.avg_pool2d(x, kernel_size=8)
# 1 x 1 x 2048
x = F.dropout(x, training=self.training)
# 1 x 1 x 2048
x = x.view(x.size(0), -1)
# 2048
x = self.group1(x)
# 1000 (num_classes)
if self.training and self.aux_logits:
return x, aux
return x
class InceptionA(nn.Module):
def __init__(self, in_channels, pool_features):
super(InceptionA, self).__init__()
self.branch1x1 = BasicConv2d(in_channels, 64, kernel_size=1)
self.branch5x5_1 = BasicConv2d(in_channels, 48, kernel_size=1)
self.branch5x5_2 = BasicConv2d(48, 64, kernel_size=5, padding=2)
self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1)
self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1)
self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, padding=1)
self.branch_pool = BasicConv2d(in_channels, pool_features, kernel_size=1)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch5x5 = self.branch5x5_1(x)
branch5x5 = self.branch5x5_2(branch5x5)
branch3x3dbl = self.branch3x3dbl_1(x)
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
branch_pool = self.branch_pool(branch_pool)
outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
return torch.cat(outputs, 1)
class InceptionB(nn.Module):
def __init__(self, in_channels):
super(InceptionB, self).__init__()
self.branch3x3 = BasicConv2d(in_channels, 384, kernel_size=3, stride=2)
self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1)
self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1)
self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, stride=2)
def forward(self, x):
branch3x3 = self.branch3x3(x)
branch3x3dbl = self.branch3x3dbl_1(x)
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)
outputs = [branch3x3, branch3x3dbl, branch_pool]
return torch.cat(outputs, 1)
class InceptionC(nn.Module):
def __init__(self, in_channels, channels_7x7):
super(InceptionC, self).__init__()
self.branch1x1 = BasicConv2d(in_channels, 192, kernel_size=1)
c7 = channels_7x7
self.branch7x7_1 = BasicConv2d(in_channels, c7, kernel_size=1)
self.branch7x7_2 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3))
self.branch7x7_3 = BasicConv2d(c7, 192, kernel_size=(7, 1), padding=(3, 0))
self.branch7x7dbl_1 = BasicConv2d(in_channels, c7, kernel_size=1)
self.branch7x7dbl_2 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0))
self.branch7x7dbl_3 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3))
self.branch7x7dbl_4 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0))
self.branch7x7dbl_5 = BasicConv2d(c7, 192, kernel_size=(1, 7), padding=(0, 3))
self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch7x7 = self.branch7x7_1(x)
branch7x7 = self.branch7x7_2(branch7x7)
branch7x7 = self.branch7x7_3(branch7x7)
branch7x7dbl = self.branch7x7dbl_1(x)
branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
branch_pool = self.branch_pool(branch_pool)
outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
return torch.cat(outputs, 1)
class InceptionD(nn.Module):
def __init__(self, in_channels):
super(InceptionD, self).__init__()
self.branch3x3_1 = BasicConv2d(in_channels, 192, kernel_size=1)
self.branch3x3_2 = BasicConv2d(192, 320, kernel_size=3, stride=2)
self.branch7x7x3_1 = BasicConv2d(in_channels, 192, kernel_size=1)
self.branch7x7x3_2 = BasicConv2d(192, 192, kernel_size=(1, 7), padding=(0, 3))
self.branch7x7x3_3 = BasicConv2d(192, 192, kernel_size=(7, 1), padding=(3, 0))
self.branch7x7x3_4 = BasicConv2d(192, 192, kernel_size=3, stride=2)
def forward(self, x):
branch3x3 = self.branch3x3_1(x)
branch3x3 = self.branch3x3_2(branch3x3)
branch7x7x3 = self.branch7x7x3_1(x)
branch7x7x3 = self.branch7x7x3_2(branch7x7x3)
branch7x7x3 = self.branch7x7x3_3(branch7x7x3)
branch7x7x3 = self.branch7x7x3_4(branch7x7x3)
branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)
outputs = [branch3x3, branch7x7x3, branch_pool]
return torch.cat(outputs, 1)
class InceptionE(nn.Module):
def __init__(self, in_channels):
super(InceptionE, self).__init__()
self.branch1x1 = BasicConv2d(in_channels, 320, kernel_size=1)
self.branch3x3_1 = BasicConv2d(in_channels, 384, kernel_size=1)
self.branch3x3_2a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1))
self.branch3x3_2b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0))
self.branch3x3dbl_1 = BasicConv2d(in_channels, 448, kernel_size=1)
self.branch3x3dbl_2 = BasicConv2d(448, 384, kernel_size=3, padding=1)
self.branch3x3dbl_3a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1))
self.branch3x3dbl_3b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0))
self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch3x3 = self.branch3x3_1(x)
branch3x3 = [
self.branch3x3_2a(branch3x3),
self.branch3x3_2b(branch3x3),
]
branch3x3 = torch.cat(branch3x3, 1)
branch3x3dbl = self.branch3x3dbl_1(x)
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
branch3x3dbl = [
self.branch3x3dbl_3a(branch3x3dbl),
self.branch3x3dbl_3b(branch3x3dbl),
]
branch3x3dbl = torch.cat(branch3x3dbl, 1)
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
branch_pool = self.branch_pool(branch_pool)
outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
return torch.cat(outputs, 1)
class InceptionAux(nn.Module):
def __init__(self, in_channels, num_classes):
super(InceptionAux, self).__init__()
self.conv0 = BasicConv2d(in_channels, 128, kernel_size=1)
self.conv1 = BasicConv2d(128, 768, kernel_size=5)
self.conv1.stddev = 0.01
fc = nn.Linear(768, num_classes)
fc.stddev = 0.001
self.group1 = nn.Sequential(
OrderedDict([
('fc', fc)
])
)
def forward(self, x):
# 17 x 17 x 768
x = F.avg_pool2d(x, kernel_size=5, stride=3)
# 5 x 5 x 768
x = self.conv0(x)
# 5 x 5 x 128
x = self.conv1(x)
# 1 x 1 x 768
x = x.view(x.size(0), -1)
# 768
x = self.group1(x)
# 1000
return x
class BasicConv2d(nn.Module):
def __init__(self, in_channels, out_channels, **kwargs):
super(BasicConv2d, self).__init__()
self.group1 = nn.Sequential(
OrderedDict([
('conv', nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)),
('bn', nn.BatchNorm2d(out_channels, eps=0.001))
])
)
def forward(self, x):
x = self.group1(x)
return F.relu(x, inplace=True)
| 11,908 | 34.549254 | 98 | py |
pytorch-playground | pytorch-playground-master/imagenet/resnet.py | import torch.nn as nn
import math
from utee import misc
from collections import OrderedDict
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
def conv3x3(in_planes, out_planes, stride=1):
# "3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
m = OrderedDict()
m['conv1'] = conv3x3(inplanes, planes, stride)
m['bn1'] = nn.BatchNorm2d(planes)
m['relu1'] = nn.ReLU(inplace=True)
m['conv2'] = conv3x3(planes, planes)
m['bn2'] = nn.BatchNorm2d(planes)
self.group1 = nn.Sequential(m)
self.relu= nn.Sequential(nn.ReLU(inplace=True))
self.downsample = downsample
def forward(self, x):
if self.downsample is not None:
residual = self.downsample(x)
else:
residual = x
out = self.group1(x) + residual
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
m = OrderedDict()
m['conv1'] = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
m['bn1'] = nn.BatchNorm2d(planes)
m['relu1'] = nn.ReLU(inplace=True)
m['conv2'] = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
m['bn2'] = nn.BatchNorm2d(planes)
m['relu2'] = nn.ReLU(inplace=True)
m['conv3'] = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
m['bn3'] = nn.BatchNorm2d(planes * 4)
self.group1 = nn.Sequential(m)
self.relu= nn.Sequential(nn.ReLU(inplace=True))
self.downsample = downsample
def forward(self, x):
if self.downsample is not None:
residual = self.downsample(x)
else:
residual = x
out = self.group1(x) + residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
m = OrderedDict()
m['conv1'] = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
m['bn1'] = nn.BatchNorm2d(64)
m['relu1'] = nn.ReLU(inplace=True)
m['maxpool'] = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.group1= nn.Sequential(m)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.Sequential(nn.AvgPool2d(7))
self.group2 = nn.Sequential(
OrderedDict([
('fc', nn.Linear(512 * block.expansion, num_classes))
])
)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.group1(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.group2(x)
return x
def resnet18(pretrained=False, model_root=None, **kwargs):
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
misc.load_state_dict(model, model_urls['resnet18'], model_root)
return model
def resnet34(pretrained=False, model_root=None, **kwargs):
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
if pretrained:
misc.load_state_dict(model, model_urls['resnet34'], model_root)
return model
def resnet50(pretrained=False, model_root=None, **kwargs):
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
misc.load_state_dict(model, model_urls['resnet50'], model_root)
return model
def resnet101(pretrained=False, model_root=None, **kwargs):
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
misc.load_state_dict(model, model_urls['resnet101'], model_root)
return model
def resnet152(pretrained=False, model_root=None, **kwargs):
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
misc.load_state_dict(model, model_urls['resnet152'], model_root)
return model
| 5,916 | 32.055866 | 109 | py |
pytorch-playground | pytorch-playground-master/imagenet/squeezenet.py | import math
import torch
import torch.nn as nn
from utee import misc
from collections import OrderedDict
__all__ = ['SqueezeNet', 'squeezenet1_0', 'squeezenet1_1']
model_urls = {
'squeezenet1_0': 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth',
'squeezenet1_1': 'https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth',
}
class Fire(nn.Module):
def __init__(self, inplanes, squeeze_planes,
expand1x1_planes, expand3x3_planes):
super(Fire, self).__init__()
self.inplanes = inplanes
self.group1 = nn.Sequential(
OrderedDict([
('squeeze', nn.Conv2d(inplanes, squeeze_planes, kernel_size=1)),
('squeeze_activation', nn.ReLU(inplace=True))
])
)
self.group2 = nn.Sequential(
OrderedDict([
('expand1x1', nn.Conv2d(squeeze_planes, expand1x1_planes, kernel_size=1)),
('expand1x1_activation', nn.ReLU(inplace=True))
])
)
self.group3 = nn.Sequential(
OrderedDict([
('expand3x3', nn.Conv2d(squeeze_planes, expand3x3_planes, kernel_size=3, padding=1)),
('expand3x3_activation', nn.ReLU(inplace=True))
])
)
def forward(self, x):
x = self.group1(x)
return torch.cat([self.group2(x),self.group3(x)], 1)
class SqueezeNet(nn.Module):
def __init__(self, version=1.0, num_classes=1000):
super(SqueezeNet, self).__init__()
if version not in [1.0, 1.1]:
raise ValueError("Unsupported SqueezeNet version {version}:"
"1.0 or 1.1 expected".format(version=version))
self.num_classes = num_classes
if version == 1.0:
self.features = nn.Sequential(
nn.Conv2d(3, 96, kernel_size=7, stride=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(96, 16, 64, 64),
Fire(128, 16, 64, 64),
Fire(128, 32, 128, 128),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(256, 32, 128, 128),
Fire(256, 48, 192, 192),
Fire(384, 48, 192, 192),
Fire(384, 64, 256, 256),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(512, 64, 256, 256),
)
else:
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(64, 16, 64, 64),
Fire(128, 16, 64, 64),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(128, 32, 128, 128),
Fire(256, 32, 128, 128),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(256, 48, 192, 192),
Fire(384, 48, 192, 192),
Fire(384, 64, 256, 256),
Fire(512, 64, 256, 256),
)
# Final convolution is initialized differently form the rest
final_conv = nn.Conv2d(512, num_classes, kernel_size=1)
self.classifier = nn.Sequential(
nn.Dropout(p=0.5),
final_conv,
nn.ReLU(inplace=True),
nn.AvgPool2d(13)
)
for m in self.modules():
if isinstance(m, nn.Conv2d):
gain = 2.0
if m is final_conv:
m.weight.data.normal_(0, 0.01)
else:
fan_in = m.kernel_size[0] * m.kernel_size[1] * m.in_channels
u = math.sqrt(3.0 * gain / fan_in)
m.weight.data.uniform_(-u, u)
if m.bias is not None:
m.bias.data.zero_()
def forward(self, x):
x = self.features(x)
x = self.classifier(x)
return x.view(x.size(0), self.num_classes)
def squeezenet1_0(pretrained=False, model_root=None, **kwargs):
r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level
accuracy with 50x fewer parameters and <0.5MB model size"
<https://arxiv.org/abs/1602.07360>`_ paper.
"""
model = SqueezeNet(version=1.0, **kwargs)
if pretrained:
misc.load_state_dict(model, model_urls['squeezenet1_0'], model_root)
return model
def squeezenet1_1(pretrained=False, model_root=None, **kwargs):
r"""SqueezeNet 1.1 model from the `official SqueezeNet repo
<https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_.
SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters
than SqueezeNet 1.0, without sacrificing accuracy.
"""
model = SqueezeNet(version=1.1, **kwargs)
if pretrained:
misc.load_state_dict(model, model_urls['squeezenet1_1'], model_root)
return model
| 5,022 | 35.398551 | 101 | py |
pytorch-playground | pytorch-playground-master/imagenet/vgg.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import math
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
}
class VGG(nn.Module):
def __init__(self, features, num_classes=1000):
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, num_classes),
)
self._initialize_weights()
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
n = m.weight.size(1)
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for v in cfg:
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
if batch_norm:
layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
else:
layers += [conv2d, nn.ReLU(inplace=True)]
in_channels = v
return nn.Sequential(*layers)
cfg = {
'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}
def vgg11(pretrained=False, model_root=None, **kwargs):
"""VGG 11-layer model (configuration "A")"""
model = VGG(make_layers(cfg['A']), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg11'], model_root))
return model
def vgg11_bn(**kwargs):
"""VGG 11-layer model (configuration "A") with batch normalization"""
kwargs.pop('model_root', None)
return VGG(make_layers(cfg['A'], batch_norm=True), **kwargs)
def vgg13(pretrained=False, model_root=None, **kwargs):
"""VGG 13-layer model (configuration "B")"""
model = VGG(make_layers(cfg['B']), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg13'], model_root))
return model
def vgg13_bn(**kwargs):
"""VGG 13-layer model (configuration "B") with batch normalization"""
kwargs.pop('model_root', None)
return VGG(make_layers(cfg['B'], batch_norm=True), **kwargs)
def vgg16(pretrained=False, model_root=None, **kwargs):
"""VGG 16-layer model (configuration "D")"""
model = VGG(make_layers(cfg['D']), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg16'], model_root))
return model
def vgg16_bn(**kwargs):
"""VGG 16-layer model (configuration "D") with batch normalization"""
kwargs.pop('model_root', None)
return VGG(make_layers(cfg['D'], batch_norm=True), **kwargs)
def vgg19(pretrained=False, model_root=None, **kwargs):
"""VGG 19-layer model (configuration "E")"""
model = VGG(make_layers(cfg['E']), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg19'], model_root))
return model
def vgg19_bn(**kwargs):
"""VGG 19-layer model (configuration 'E') with batch normalization"""
kwargs.pop('model_root', None)
return VGG(make_layers(cfg['E'], batch_norm=True), **kwargs)
| 4,505 | 32.132353 | 113 | py |
pytorch-playground | pytorch-playground-master/imagenet/dataset.py | from utee import misc
import os
import os.path
import numpy as np
import joblib
def get(batch_size, data_root='/tmp/public_dataset/pytorch', train=False, val=True, **kwargs):
data_root = os.path.expanduser(os.path.join(data_root, 'imagenet-data'))
print("Building IMAGENET data loader, 50000 for train, 50000 for test")
ds = []
assert train is not True, 'train not supported yet'
if train:
ds.append(IMAGENET(data_root, batch_size, True, **kwargs))
if val:
ds.append(IMAGENET(data_root, batch_size, False, **kwargs))
ds = ds[0] if len(ds) == 1 else ds
return ds
class IMAGENET(object):
def __init__(self, root, batch_size, train=False, input_size=224, **kwargs):
self.mean = np.array([0.485, 0.456, 0.406]).reshape(1, 1, 1, 3)
self.std = np.array([0.229, 0.224, 0.225]).reshape(1, 1, 1, 3)
self.train = train
if train:
pkl_file = os.path.join(root, 'train{}.pkl'.format(input_size))
else:
pkl_file = os.path.join(root, 'val{}.pkl'.format(input_size))
self.data_dict = joblib.load(pkl_file)
self.batch_size = batch_size
self.idx = 0
@property
def n_batch(self):
return int(np.ceil(self.n_sample* 1.0 / self.batch_size))
@property
def n_sample(self):
return len(self.data_dict['data'])
def __len__(self):
return self.n_batch
def __iter__(self):
return self
def __next__(self):
if self.idx >= self.n_batch:
self.idx = 0
raise StopIteration
else:
img = self.data_dict['data'][self.idx*self.batch_size:(self.idx+1)*self.batch_size].astype('float32')
target = self.data_dict['target'][self.idx*self.batch_size:(self.idx+1)*self.batch_size]
self.idx += 1
return img, target
if __name__ == '__main__':
train_ds, val_ds = get(200)
| 1,927 | 29.603175 | 113 | py |
pytorch-playground | pytorch-playground-master/imagenet/__init__.py | 0 | 0 | 0 | py |
|
pytorch-playground | pytorch-playground-master/imagenet/alexnet.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['AlexNet', 'alexnet']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
class AlexNet(nn.Module):
def __init__(self, num_classes=1000):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), 256 * 6 * 6)
x = self.classifier(x)
return x
def alexnet(pretrained=False, model_root=None, **kwargs):
model = AlexNet(**kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['alexnet'], model_root))
return model
| 1,637 | 29.333333 | 84 | py |
pytorch-playground | pytorch-playground-master/mnist/model.py | import torch.nn as nn
from collections import OrderedDict
import torch.utils.model_zoo as model_zoo
from utee import misc
print = misc.logger.info
model_urls = {
'mnist': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/mnist-b07bb66b.pth'
}
class MLP(nn.Module):
def __init__(self, input_dims, n_hiddens, n_class):
super(MLP, self).__init__()
assert isinstance(input_dims, int), 'Please provide int for input_dims'
self.input_dims = input_dims
current_dims = input_dims
layers = OrderedDict()
if isinstance(n_hiddens, int):
n_hiddens = [n_hiddens]
else:
n_hiddens = list(n_hiddens)
for i, n_hidden in enumerate(n_hiddens):
layers['fc{}'.format(i+1)] = nn.Linear(current_dims, n_hidden)
layers['relu{}'.format(i+1)] = nn.ReLU()
layers['drop{}'.format(i+1)] = nn.Dropout(0.2)
current_dims = n_hidden
layers['out'] = nn.Linear(current_dims, n_class)
self.model= nn.Sequential(layers)
print(self.model)
def forward(self, input):
input = input.view(input.size(0), -1)
assert input.size(1) == self.input_dims
return self.model.forward(input)
def mnist(input_dims=784, n_hiddens=[256, 256], n_class=10, pretrained=None):
model = MLP(input_dims, n_hiddens, n_class)
if pretrained is not None:
m = model_zoo.load_url(model_urls['mnist'])
state_dict = m.state_dict() if isinstance(m, nn.Module) else m
assert isinstance(state_dict, (dict, OrderedDict)), type(state_dict)
model.load_state_dict(state_dict)
return model
| 1,660 | 34.340426 | 85 | py |
pytorch-playground | pytorch-playground-master/mnist/dataset.py | from torch.utils.data import DataLoader
import torch
from torchvision import datasets, transforms
import os
def get(batch_size, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):
data_root = os.path.expanduser(os.path.join(data_root, 'mnist-data'))
kwargs.pop('input_size', None)
num_workers = kwargs.setdefault('num_workers', 1)
print("Building MNIST data loader with {} workers".format(num_workers))
ds = []
if train:
train_loader = torch.utils.data.DataLoader(
datasets.MNIST(root=data_root, train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True, **kwargs)
ds.append(train_loader)
if val:
test_loader = torch.utils.data.DataLoader(
datasets.MNIST(root=data_root, train=False, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True, **kwargs)
ds.append(test_loader)
ds = ds[0] if len(ds) == 1 else ds
return ds
| 1,398 | 41.393939 | 93 | py |
pytorch-playground | pytorch-playground-master/mnist/__init__.py | 0 | 0 | 0 | py |
|
pytorch-playground | pytorch-playground-master/mnist/train.py | import argparse
import os
import time
from utee import misc
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import dataset
import model
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--wd', type=float, default=0.0001, help='weight decay')
parser.add_argument('--batch_size', type=int, default=200, help='input batch size for training (default: 64)')
parser.add_argument('--epochs', type=int, default=40, help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, help='learning rate (default: 1e-3)')
parser.add_argument('--gpu', default=None, help='index of gpus to use')
parser.add_argument('--ngpu', type=int, default=1, help='number of gpus to use')
parser.add_argument('--seed', type=int, default=117, help='random seed (default: 1)')
parser.add_argument('--log_interval', type=int, default=100, help='how many batches to wait before logging training status')
parser.add_argument('--test_interval', type=int, default=5, help='how many epochs to wait before another test')
parser.add_argument('--logdir', default='log/default', help='folder to save to the log')
parser.add_argument('--data_root', default='/tmp/public_dataset/pytorch/', help='folder to save the model')
parser.add_argument('--decreasing_lr', default='80,120', help='decreasing strategy')
args = parser.parse_args()
args.logdir = os.path.join(os.path.dirname(__file__), args.logdir)
misc.logger.init(args.logdir, 'train_log')
print = misc.logger.info
# select gpu
args.gpu = misc.auto_select_gpu(utility_bound=0, num_gpu=args.ngpu, selected_gpus=args.gpu)
args.ngpu = len(args.gpu)
# logger
misc.ensure_dir(args.logdir)
print("=================FLAGS==================")
for k, v in args.__dict__.items():
print('{}: {}'.format(k, v))
print("========================================")
# seed
args.cuda = torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
# data loader
train_loader, test_loader = dataset.get(batch_size=args.batch_size, data_root=args.data_root, num_workers=1)
# model
model = model.mnist(input_dims=784, n_hiddens=[256, 256], n_class=10)
model = torch.nn.DataParallel(model, device_ids= range(args.ngpu))
if args.cuda:
model.cuda()
# optimizer
optimizer = optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.wd, momentum=0.9)
decreasing_lr = list(map(int, args.decreasing_lr.split(',')))
print('decreasing_lr: ' + str(decreasing_lr))
best_acc, old_file = 0, None
t_begin = time.time()
try:
# ready to go
for epoch in range(args.epochs):
model.train()
if epoch in decreasing_lr:
optimizer.param_groups[0]['lr'] *= 0.1
for batch_idx, (data, target) in enumerate(train_loader):
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0 and batch_idx > 0:
pred = output.data.max(1)[1] # get the index of the max log-probability
correct = pred.cpu().eq(indx_target).sum()
acc = correct * 1.0 / len(data)
print('Train Epoch: {} [{}/{}] Loss: {:.6f} Acc: {:.4f} lr: {:.2e}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
loss.data, acc, optimizer.param_groups[0]['lr']))
elapse_time = time.time() - t_begin
speed_epoch = elapse_time / (epoch + 1)
speed_batch = speed_epoch / len(train_loader)
eta = speed_epoch * args.epochs - elapse_time
print("Elapsed {:.2f}s, {:.2f} s/epoch, {:.2f} s/batch, ets {:.2f}s".format(
elapse_time, speed_epoch, speed_batch, eta))
misc.model_snapshot(model, os.path.join(args.logdir, 'latest.pth'))
if epoch % args.test_interval == 0:
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += F.cross_entropy(output, target).data
pred = output.data.max(1)[1] # get the index of the max log-probability
correct += pred.cpu().eq(indx_target).sum()
test_loss = test_loss / len(test_loader) # average over number of mini-batch
acc = 100. * correct / len(test_loader.dataset)
print('\tTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(
test_loss, correct, len(test_loader.dataset), acc))
if acc > best_acc:
new_file = os.path.join(args.logdir, 'best-{}.pth'.format(epoch))
misc.model_snapshot(model, new_file, old_file=old_file, verbose=True)
best_acc = acc
old_file = new_file
except Exception as e:
import traceback
traceback.print_exc()
finally:
print("Total Elapse: {:.2f}, Best Result: {:.3f}%".format(time.time()-t_begin, best_acc))
| 5,502 | 41.992188 | 125 | py |
pytorch-playground | pytorch-playground-master/cifar/model.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from IPython import embed
from collections import OrderedDict
from utee import misc
print = misc.logger.info
model_urls = {
'cifar10': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar10-d875770b.pth',
'cifar100': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar100-3a55a987.pth',
}
class CIFAR(nn.Module):
def __init__(self, features, n_channel, num_classes):
super(CIFAR, self).__init__()
assert isinstance(features, nn.Sequential), type(features)
self.features = features
self.classifier = nn.Sequential(
nn.Linear(n_channel, num_classes)
)
print(self.features)
print(self.classifier)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for i, v in enumerate(cfg):
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
padding = v[1] if isinstance(v, tuple) else 1
out_channels = v[0] if isinstance(v, tuple) else v
conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=padding)
if batch_norm:
layers += [conv2d, nn.BatchNorm2d(out_channels, affine=False), nn.ReLU()]
else:
layers += [conv2d, nn.ReLU()]
in_channels = out_channels
return nn.Sequential(*layers)
def cifar10(n_channel, pretrained=None):
cfg = [n_channel, n_channel, 'M', 2*n_channel, 2*n_channel, 'M', 4*n_channel, 4*n_channel, 'M', (8*n_channel, 0), 'M']
layers = make_layers(cfg, batch_norm=True)
model = CIFAR(layers, n_channel=8*n_channel, num_classes=10)
if pretrained is not None:
m = model_zoo.load_url(model_urls['cifar10'])
state_dict = m.state_dict() if isinstance(m, nn.Module) else m
assert isinstance(state_dict, (dict, OrderedDict)), type(state_dict)
model.load_state_dict(state_dict)
return model
def cifar100(n_channel, pretrained=None):
cfg = [n_channel, n_channel, 'M', 2*n_channel, 2*n_channel, 'M', 4*n_channel, 4*n_channel, 'M', (8*n_channel, 0), 'M']
layers = make_layers(cfg, batch_norm=True)
model = CIFAR(layers, n_channel=8*n_channel, num_classes=100)
if pretrained is not None:
m = model_zoo.load_url(model_urls['cifar100'])
state_dict = m.state_dict() if isinstance(m, nn.Module) else m
assert isinstance(state_dict, (dict, OrderedDict)), type(state_dict)
model.load_state_dict(state_dict)
return model
if __name__ == '__main__':
model = cifar10(128, pretrained='log/cifar10/best-135.pth')
embed()
| 2,809 | 36.972973 | 122 | py |
pytorch-playground | pytorch-playground-master/cifar/dataset.py | import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import os
def get10(batch_size, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):
data_root = os.path.expanduser(os.path.join(data_root, 'cifar10-data'))
num_workers = kwargs.setdefault('num_workers', 1)
kwargs.pop('input_size', None)
print("Building CIFAR-10 data loader with {} workers".format(num_workers))
ds = []
if train:
train_loader = torch.utils.data.DataLoader(
datasets.CIFAR10(
root=data_root, train=True, download=True,
transform=transforms.Compose([
transforms.Pad(4),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])),
batch_size=batch_size, shuffle=True, **kwargs)
ds.append(train_loader)
if val:
test_loader = torch.utils.data.DataLoader(
datasets.CIFAR10(
root=data_root, train=False, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])),
batch_size=batch_size, shuffle=False, **kwargs)
ds.append(test_loader)
ds = ds[0] if len(ds) == 1 else ds
return ds
def get100(batch_size, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):
data_root = os.path.expanduser(os.path.join(data_root, 'cifar100-data'))
num_workers = kwargs.setdefault('num_workers', 1)
kwargs.pop('input_size', None)
print("Building CIFAR-100 data loader with {} workers".format(num_workers))
ds = []
if train:
train_loader = torch.utils.data.DataLoader(
datasets.CIFAR100(
root=data_root, train=True, download=True,
transform=transforms.Compose([
transforms.Pad(4),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])),
batch_size=batch_size, shuffle=True, **kwargs)
ds.append(train_loader)
if val:
test_loader = torch.utils.data.DataLoader(
datasets.CIFAR100(
root=data_root, train=False, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])),
batch_size=batch_size, shuffle=False, **kwargs)
ds.append(test_loader)
ds = ds[0] if len(ds) == 1 else ds
return ds
| 2,937 | 40.380282 | 96 | py |
pytorch-playground | pytorch-playground-master/cifar/__init__.py | 0 | 0 | 0 | py |
|
pytorch-playground | pytorch-playground-master/cifar/train.py | import argparse
import os
import time
from utee import misc
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import dataset
import model
from IPython import embed
parser = argparse.ArgumentParser(description='PyTorch CIFAR-X Example')
parser.add_argument('--type', default='cifar10', help='cifar10|cifar100')
parser.add_argument('--channel', type=int, default=128, help='first conv channel (default: 32)')
parser.add_argument('--wd', type=float, default=0.00, help='weight decay')
parser.add_argument('--batch_size', type=int, default=200, help='input batch size for training (default: 64)')
parser.add_argument('--epochs', type=int, default=150, help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.001, help='learning rate (default: 1e-3)')
parser.add_argument('--gpu', default=None, help='index of gpus to use')
parser.add_argument('--ngpu', type=int, default=2, help='number of gpus to use')
parser.add_argument('--seed', type=int, default=117, help='random seed (default: 1)')
parser.add_argument('--log_interval', type=int, default=100, help='how many batches to wait before logging training status')
parser.add_argument('--test_interval', type=int, default=5, help='how many epochs to wait before another test')
parser.add_argument('--logdir', default='log/default', help='folder to save to the log')
parser.add_argument('--decreasing_lr', default='80,120', help='decreasing strategy')
args = parser.parse_args()
args.logdir = os.path.join(os.path.dirname(__file__), args.logdir)
misc.logger.init(args.logdir, 'train_log')
print = misc.logger.info
# select gpu
args.gpu = misc.auto_select_gpu(utility_bound=0, num_gpu=args.ngpu, selected_gpus=args.gpu)
args.ngpu = len(args.gpu)
# logger
misc.ensure_dir(args.logdir)
print("=================FLAGS==================")
for k, v in args.__dict__.items():
print('{}: {}'.format(k, v))
print("========================================")
# seed
args.cuda = torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
# data loader and model
assert args.type in ['cifar10', 'cifar100'], args.type
if args.type == 'cifar10':
train_loader, test_loader = dataset.get10(batch_size=args.batch_size, num_workers=1)
model = model.cifar10(n_channel=args.channel)
else:
train_loader, test_loader = dataset.get100(batch_size=args.batch_size, num_workers=1)
model = model.cifar100(n_channel=args.channel)
model = torch.nn.DataParallel(model, device_ids= range(args.ngpu))
if args.cuda:
model.cuda()
# optimizer
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)
decreasing_lr = list(map(int, args.decreasing_lr.split(',')))
print('decreasing_lr: ' + str(decreasing_lr))
best_acc, old_file = 0, None
t_begin = time.time()
try:
# ready to go
for epoch in range(args.epochs):
model.train()
if epoch in decreasing_lr:
optimizer.param_groups[0]['lr'] *= 0.1
for batch_idx, (data, target) in enumerate(train_loader):
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0 and batch_idx > 0:
pred = output.data.max(1)[1] # get the index of the max log-probability
correct = pred.cpu().eq(indx_target).sum()
acc = correct * 1.0 / len(data)
print('Train Epoch: {} [{}/{}] Loss: {:.6f} Acc: {:.4f} lr: {:.2e}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
loss.data[0], acc, optimizer.param_groups[0]['lr']))
elapse_time = time.time() - t_begin
speed_epoch = elapse_time / (epoch + 1)
speed_batch = speed_epoch / len(train_loader)
eta = speed_epoch * args.epochs - elapse_time
print("Elapsed {:.2f}s, {:.2f} s/epoch, {:.2f} s/batch, ets {:.2f}s".format(
elapse_time, speed_epoch, speed_batch, eta))
misc.model_snapshot(model, os.path.join(args.logdir, 'latest.pth'))
if epoch % args.test_interval == 0:
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
indx_target = target.clone()
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += F.cross_entropy(output, target).data[0]
pred = output.data.max(1)[1] # get the index of the max log-probability
correct += pred.cpu().eq(indx_target).sum()
test_loss = test_loss / len(test_loader) # average over number of mini-batch
acc = 100. * correct / len(test_loader.dataset)
print('\tTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(
test_loss, correct, len(test_loader.dataset), acc))
if acc > best_acc:
new_file = os.path.join(args.logdir, 'best-{}.pth'.format(epoch))
misc.model_snapshot(model, new_file, old_file=old_file, verbose=True)
best_acc = acc
old_file = new_file
except Exception as e:
import traceback
traceback.print_exc()
finally:
print("Total Elapse: {:.2f}, Best Result: {:.3f}%".format(time.time()-t_begin, best_acc))
| 5,777 | 42.119403 | 125 | py |
pytorch-playground | pytorch-playground-master/utee/quant.py | from torch.autograd import Variable
import torch
from torch import nn
from collections import OrderedDict
import math
from IPython import embed
def compute_integral_part(input, overflow_rate):
abs_value = input.abs().view(-1)
sorted_value = abs_value.sort(dim=0, descending=True)[0]
split_idx = int(overflow_rate * len(sorted_value))
v = sorted_value[split_idx]
if isinstance(v, Variable):
v = float(v.data.cpu())
sf = math.ceil(math.log2(v+1e-12))
return sf
def linear_quantize(input, sf, bits):
assert bits >= 1, bits
if bits == 1:
return torch.sign(input) - 1
delta = math.pow(2.0, -sf)
bound = math.pow(2.0, bits-1)
min_val = - bound
max_val = bound - 1
rounded = torch.floor(input / delta + 0.5)
clipped_value = torch.clamp(rounded, min_val, max_val) * delta
return clipped_value
def log_minmax_quantize(input, bits):
assert bits >= 1, bits
if bits == 1:
return torch.sign(input), 0.0, 0.0
s = torch.sign(input)
input0 = torch.log(torch.abs(input) + 1e-20)
v = min_max_quantize(input0, bits-1)
v = torch.exp(v) * s
return v
def log_linear_quantize(input, sf, bits):
assert bits >= 1, bits
if bits == 1:
return torch.sign(input), 0.0, 0.0
s = torch.sign(input)
input0 = torch.log(torch.abs(input) + 1e-20)
v = linear_quantize(input0, sf, bits-1)
v = torch.exp(v) * s
return v
def min_max_quantize(input, bits):
assert bits >= 1, bits
if bits == 1:
return torch.sign(input) - 1
min_val, max_val = input.min(), input.max()
if isinstance(min_val, Variable):
max_val = float(max_val.data.cpu().numpy()[0])
min_val = float(min_val.data.cpu().numpy()[0])
input_rescale = (input - min_val) / (max_val - min_val)
n = math.pow(2.0, bits) - 1
v = torch.floor(input_rescale * n + 0.5) / n
v = v * (max_val - min_val) + min_val
return v
def tanh_quantize(input, bits):
assert bits >= 1, bits
if bits == 1:
return torch.sign(input)
input = torch.tanh(input) # [-1, 1]
input_rescale = (input + 1.0) / 2 #[0, 1]
n = math.pow(2.0, bits) - 1
v = torch.floor(input_rescale * n + 0.5) / n
v = 2 * v - 1 # [-1, 1]
v = 0.5 * torch.log((1 + v) / (1 - v)) # arctanh
return v
class LinearQuant(nn.Module):
def __init__(self, name, bits, sf=None, overflow_rate=0.0, counter=10):
super(LinearQuant, self).__init__()
self.name = name
self._counter = counter
self.bits = bits
self.sf = sf
self.overflow_rate = overflow_rate
@property
def counter(self):
return self._counter
def forward(self, input):
if self._counter > 0:
self._counter -= 1
sf_new = self.bits - 1 - compute_integral_part(input, self.overflow_rate)
self.sf = min(self.sf, sf_new) if self.sf is not None else sf_new
return input
else:
output = linear_quantize(input, self.sf, self.bits)
return output
def __repr__(self):
return '{}(sf={}, bits={}, overflow_rate={:.3f}, counter={})'.format(
self.__class__.__name__, self.sf, self.bits, self.overflow_rate, self.counter)
class LogQuant(nn.Module):
def __init__(self, name, bits, sf=None, overflow_rate=0.0, counter=10):
super(LogQuant, self).__init__()
self.name = name
self._counter = counter
self.bits = bits
self.sf = sf
self.overflow_rate = overflow_rate
@property
def counter(self):
return self._counter
def forward(self, input):
if self._counter > 0:
self._counter -= 1
log_abs_input = torch.log(torch.abs(input))
sf_new = self.bits - 1 - compute_integral_part(log_abs_input, self.overflow_rate)
self.sf = min(self.sf, sf_new) if self.sf is not None else sf_new
return input
else:
output = log_linear_quantize(input, self.sf, self.bits)
return output
def __repr__(self):
return '{}(sf={}, bits={}, overflow_rate={:.3f}, counter={})'.format(
self.__class__.__name__, self.sf, self.bits, self.overflow_rate, self.counter)
class NormalQuant(nn.Module):
def __init__(self, name, bits, quant_func):
super(NormalQuant, self).__init__()
self.name = name
self.bits = bits
self.quant_func = quant_func
@property
def counter(self):
return self._counter
def forward(self, input):
output = self.quant_func(input, self.bits)
return output
def __repr__(self):
return '{}(bits={})'.format(self.__class__.__name__, self.bits)
def duplicate_model_with_quant(model, bits, overflow_rate=0.0, counter=10, type='linear'):
"""assume that original model has at least a nn.Sequential"""
assert type in ['linear', 'minmax', 'log', 'tanh']
if isinstance(model, nn.Sequential):
l = OrderedDict()
for k, v in model._modules.items():
if isinstance(v, (nn.Conv2d, nn.Linear, nn.BatchNorm1d, nn.BatchNorm2d, nn.AvgPool2d)):
l[k] = v
if type == 'linear':
quant_layer = LinearQuant('{}_quant'.format(k), bits=bits, overflow_rate=overflow_rate, counter=counter)
elif type == 'log':
# quant_layer = LogQuant('{}_quant'.format(k), bits=bits, overflow_rate=overflow_rate, counter=counter)
quant_layer = NormalQuant('{}_quant'.format(k), bits=bits, quant_func=log_minmax_quantize)
elif type == 'minmax':
quant_layer = NormalQuant('{}_quant'.format(k), bits=bits, quant_func=min_max_quantize)
else:
quant_layer = NormalQuant('{}_quant'.format(k), bits=bits, quant_func=tanh_quantize)
l['{}_{}_quant'.format(k, type)] = quant_layer
else:
l[k] = duplicate_model_with_quant(v, bits, overflow_rate, counter, type)
m = nn.Sequential(l)
return m
else:
for k, v in model._modules.items():
model._modules[k] = duplicate_model_with_quant(v, bits, overflow_rate, counter, type)
return model
| 6,302 | 32.705882 | 124 | py |
pytorch-playground | pytorch-playground-master/utee/misc.py | import cv2
import os
import shutil
import pickle as pkl
import time
import numpy as np
import hashlib
from IPython import embed
class Logger(object):
def __init__(self):
self._logger = None
def init(self, logdir, name='log'):
if self._logger is None:
import logging
if not os.path.exists(logdir):
os.makedirs(logdir)
log_file = os.path.join(logdir, name)
if os.path.exists(log_file):
os.remove(log_file)
self._logger = logging.getLogger()
self._logger.setLevel('INFO')
fh = logging.FileHandler(log_file)
ch = logging.StreamHandler()
self._logger.addHandler(fh)
self._logger.addHandler(ch)
def info(self, str_info):
self.init('/tmp', 'tmp.log')
self._logger.info(str_info)
logger = Logger()
print = logger.info
def ensure_dir(path, erase=False):
if os.path.exists(path) and erase:
print("Removing old folder {}".format(path))
shutil.rmtree(path)
if not os.path.exists(path):
print("Creating folder {}".format(path))
os.makedirs(path)
def load_pickle(path):
begin_st = time.time()
with open(path, 'rb') as f:
print("Loading pickle object from {}".format(path))
v = pkl.load(f)
print("=> Done ({:.4f} s)".format(time.time() - begin_st))
return v
def dump_pickle(obj, path):
with open(path, 'wb') as f:
print("Dumping pickle object to {}".format(path))
pkl.dump(obj, f, protocol=pkl.HIGHEST_PROTOCOL)
def auto_select_gpu(mem_bound=500, utility_bound=0, gpus=(0, 1, 2, 3, 4, 5, 6, 7), num_gpu=1, selected_gpus=None):
import sys
import os
import subprocess
import re
import time
import numpy as np
if 'CUDA_VISIBLE_DEVCIES' in os.environ:
sys.exit(0)
if selected_gpus is None:
mem_trace = []
utility_trace = []
for i in range(5): # sample 5 times
info = subprocess.check_output('nvidia-smi', shell=True).decode('utf-8')
mem = [int(s[:-5]) for s in re.compile('\d+MiB\s/').findall(info)]
utility = [int(re.compile('\d+').findall(s)[0]) for s in re.compile('\d+%\s+Default').findall(info)]
mem_trace.append(mem)
utility_trace.append(utility)
time.sleep(0.1)
mem = np.mean(mem_trace, axis=0)
utility = np.mean(utility_trace, axis=0)
assert(len(mem) == len(utility))
nGPU = len(utility)
ideal_gpus = [i for i in range(nGPU) if mem[i] <= mem_bound and utility[i] <= utility_bound and i in gpus]
if len(ideal_gpus) < num_gpu:
print("No sufficient resource, available: {}, require {} gpu".format(ideal_gpus, num_gpu))
sys.exit(0)
else:
selected_gpus = list(map(str, ideal_gpus[:num_gpu]))
else:
selected_gpus = selected_gpus.split(',')
print("Setting GPU: {}".format(selected_gpus))
os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(selected_gpus)
return selected_gpus
def expand_user(path):
return os.path.abspath(os.path.expanduser(path))
def model_snapshot(model, new_file, old_file=None, verbose=False):
from collections import OrderedDict
import torch
if isinstance(model, torch.nn.DataParallel):
model = model.module
if old_file and os.path.exists(expand_user(old_file)):
if verbose:
print("Removing old model {}".format(expand_user(old_file)))
os.remove(expand_user(old_file))
if verbose:
print("Saving model to {}".format(expand_user(new_file)))
state_dict = OrderedDict()
for k, v in model.state_dict().items():
if v.is_cuda:
v = v.cpu()
state_dict[k] = v
torch.save(state_dict, expand_user(new_file))
def load_lmdb(lmdb_file, n_records=None):
import lmdb
import numpy as np
lmdb_file = expand_user(lmdb_file)
if os.path.exists(lmdb_file):
data = []
env = lmdb.open(lmdb_file, readonly=True, max_readers=512)
with env.begin() as txn:
cursor = txn.cursor()
begin_st = time.time()
print("Loading lmdb file {} into memory".format(lmdb_file))
for key, value in cursor:
_, target, _ = key.decode('ascii').split(':')
target = int(target)
img = cv2.imdecode(np.fromstring(value, np.uint8), cv2.IMREAD_COLOR)
data.append((img, target))
if n_records is not None and len(data) >= n_records:
break
env.close()
print("=> Done ({:.4f} s)".format(time.time() - begin_st))
return data
else:
print("Not found lmdb file".format(lmdb_file))
def str2img(str_b):
return cv2.imdecode(np.fromstring(str_b, np.uint8), cv2.IMREAD_COLOR)
def img2str(img):
return cv2.imencode('.jpg', img)[1].tostring()
def md5(s):
m = hashlib.md5()
m.update(s)
return m.hexdigest()
def eval_model(model, ds, n_sample=None, ngpu=1, is_imagenet=False):
import tqdm
import torch
from torch import nn
from torch.autograd import Variable
class ModelWrapper(nn.Module):
def __init__(self, model):
super(ModelWrapper, self).__init__()
self.model = model
self.mean = [0.485, 0.456, 0.406]
self.std = [0.229, 0.224, 0.225]
def forward(self, input):
input.data.div_(255.)
input.data[:, 0, :, :].sub_(self.mean[0]).div_(self.std[0])
input.data[:, 1, :, :].sub_(self.mean[1]).div_(self.std[1])
input.data[:, 2, :, :].sub_(self.mean[2]).div_(self.std[2])
return self.model(input)
correct1, correct5 = 0, 0
n_passed = 0
if is_imagenet:
model = ModelWrapper(model)
model = model.eval()
model = torch.nn.DataParallel(model, device_ids=range(ngpu)).cuda()
n_sample = len(ds) if n_sample is None else n_sample
for idx, (data, target) in enumerate(tqdm.tqdm(ds, total=n_sample)):
n_passed += len(data)
data = Variable(torch.FloatTensor(data)).cuda()
indx_target = torch.LongTensor(target)
output = model(data)
bs = output.size(0)
idx_pred = output.data.sort(1, descending=True)[1]
idx_gt1 = indx_target.expand(1, bs).transpose_(0, 1)
idx_gt5 = idx_gt1.expand(bs, 5)
correct1 += idx_pred[:, :1].cpu().eq(idx_gt1).sum()
correct5 += idx_pred[:, :5].cpu().eq(idx_gt5).sum()
if idx >= n_sample - 1:
break
acc1 = correct1 * 1.0 / n_passed
acc5 = correct5 * 1.0 / n_passed
return acc1, acc5
def load_state_dict(model, model_urls, model_root):
from torch.utils import model_zoo
from torch import nn
import re
from collections import OrderedDict
own_state_old = model.state_dict()
own_state = OrderedDict() # remove all 'group' string
for k, v in own_state_old.items():
k = re.sub('group\d+\.', '', k)
own_state[k] = v
state_dict = model_zoo.load_url(model_urls, model_root)
for name, param in state_dict.items():
if name not in own_state:
print(own_state.keys())
raise KeyError('unexpected key "{}" in state_dict'
.format(name))
if isinstance(param, nn.Parameter):
# backwards compatibility for serialized parameters
param = param.data
own_state[name].copy_(param)
missing = set(own_state.keys()) - set(state_dict.keys())
no_use = set(state_dict.keys()) - set(own_state.keys())
if len(no_use) > 0:
raise KeyError('some keys are not used: "{}"'.format(no_use))
| 7,772 | 32.943231 | 114 | py |
pytorch-playground | pytorch-playground-master/utee/__init__.py | 0 | 0 | 0 | py |
|
pytorch-playground | pytorch-playground-master/utee/selector.py | from utee import misc
import os
from imagenet import dataset
print = misc.logger.info
from IPython import embed
known_models = [
'mnist', 'svhn', # 28x28
'cifar10', 'cifar100', # 32x32
'stl10', # 96x96
'alexnet', # 224x224
'vgg16', 'vgg16_bn', 'vgg19', 'vgg19_bn', # 224x224
'resnet18', 'resnet34', 'resnet50', 'resnet101','resnet152', # 224x224
'squeezenet_v0', 'squeezenet_v1', #224x224
'inception_v3', # 299x299
]
def mnist(cuda=True, model_root=None):
print("Building and initializing mnist parameters")
from mnist import model, dataset
m = model.mnist(pretrained=os.path.join(model_root, 'mnist.pth'))
if cuda:
m = m.cuda()
return m, dataset.get, False
def svhn(cuda=True, model_root=None):
print("Building and initializing svhn parameters")
from svhn import model, dataset
m = model.svhn(32, pretrained=os.path.join(model_root, 'svhn.pth'))
if cuda:
m = m.cuda()
return m, dataset.get, False
def cifar10(cuda=True, model_root=None):
print("Building and initializing cifar10 parameters")
from cifar import model, dataset
m = model.cifar10(128, pretrained=os.path.join(model_root, 'cifar10.pth'))
if cuda:
m = m.cuda()
return m, dataset.get10, False
def cifar100(cuda=True, model_root=None):
print("Building and initializing cifar100 parameters")
from cifar import model, dataset
m = model.cifar100(128, pretrained=os.path.join(model_root, 'cifar100.pth'))
if cuda:
m = m.cuda()
return m, dataset.get100, False
def stl10(cuda=True, model_root=None):
print("Building and initializing stl10 parameters")
from stl10 import model, dataset
m = model.stl10(32, pretrained=os.path.join(model_root, 'stl10.pth'))
if cuda:
m = m.cuda()
return m, dataset.get, False
def alexnet(cuda=True, model_root=None):
print("Building and initializing alexnet parameters")
from imagenet import alexnet as alx
m = alx.alexnet(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def vgg16(cuda=True, model_root=None):
print("Building and initializing vgg16 parameters")
from imagenet import vgg
m = vgg.vgg16(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def vgg16_bn(cuda=True, model_root=None):
print("Building vgg16_bn parameters")
from imagenet import vgg
m = vgg.vgg16_bn(model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def vgg19(cuda=True, model_root=None):
print("Building and initializing vgg19 parameters")
from imagenet import vgg
m = vgg.vgg19(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def vgg19_bn(cuda=True, model_root=None):
print("Building vgg19_bn parameters")
from imagenet import vgg
m = vgg.vgg19_bn(model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def inception_v3(cuda=True, model_root=None):
print("Building and initializing inception_v3 parameters")
from imagenet import inception
m = inception.inception_v3(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def resnet18(cuda=True, model_root=None):
print("Building and initializing resnet-18 parameters")
from imagenet import resnet
m = resnet.resnet18(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def resnet34(cuda=True, model_root=None):
print("Building and initializing resnet-34 parameters")
from imagenet import resnet
m = resnet.resnet34(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def resnet50(cuda=True, model_root=None):
print("Building and initializing resnet-50 parameters")
from imagenet import resnet
m = resnet.resnet50(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def resnet101(cuda=True, model_root=None):
print("Building and initializing resnet-101 parameters")
from imagenet import resnet
m = resnet.resnet101(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def resnet152(cuda=True, model_root=None):
print("Building and initializing resnet-152 parameters")
from imagenet import resnet
m = resnet.resnet152(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def squeezenet_v0(cuda=True, model_root=None):
print("Building and initializing squeezenet_v0 parameters")
from imagenet import squeezenet
m = squeezenet.squeezenet1_0(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def squeezenet_v1(cuda=True, model_root=None):
print("Building and initializing squeezenet_v1 parameters")
from imagenet import squeezenet
m = squeezenet.squeezenet1_1(True, model_root)
if cuda:
m = m.cuda()
return m, dataset.get, True
def select(model_name, **kwargs):
assert model_name in known_models, model_name
kwargs.setdefault('model_root', os.path.expanduser('~/.torch/models'))
return eval('{}'.format(model_name))(**kwargs)
if __name__ == '__main__':
m1 = alexnet()
embed()
| 5,245 | 29.5 | 80 | py |
pytorch-playground | pytorch-playground-master/script/convert.py | import os
import numpy as np
import tqdm
from utee import misc
import argparse
import cv2
import joblib
parser = argparse.ArgumentParser(description='Extract the ILSVRC2012 val dataset')
parser.add_argument('--in_file', default='val224_compressed.pkl', help='input file path')
parser.add_argument('--out_root', default='/data/public_dataset/pytorch/imagenet-data/', help='output file path')
args = parser.parse_args()
d = misc.load_pickle(args.in_file)
assert len(d['data']) == 50000, len(d['data'])
assert len(d['target']) == 50000, len(d['target'])
data299 = []
for img, target in tqdm.tqdm(zip(d['data'], d['target']), total=50000):
img224 = misc.str2img(img)
img299 = cv2.resize(img224, (299, 299))
data299.append(img299)
data_dict299 = dict(
data = np.array(data299).transpose(0, 3, 1, 2),
target = d['target']
)
if not os.path.exists(args.out_root):
os.makedirs(args.out_root)
joblib.dump(data_dict299, os.path.join(args.out_root, 'val299.pkl'))
data299.clear()
data_dict299.clear()
data224 = []
for img, target in tqdm.tqdm(zip(d['data'], d['target']), total=50000):
img224 = misc.str2img(img)
data224.append(img224)
data_dict224 = dict(
data = np.array(data224).transpose(0, 3, 1, 2),
target = d['target']
)
joblib.dump(data_dict224, os.path.join(args.out_root, 'val224.pkl'))
| 1,337 | 25.76 | 113 | py |
coling2018-xling_argument_mining | coling2018-xling_argument_mining-master/code/annotationProjection/readDocs.py | import sys
def readDoc(fn,index0=1):
hh=[]
hd = {}
h=[]
for line in open(fn):
line = line.strip()
if line=="":
if h!=[]:
hh.append(h)
str=" ".join([x[0] for x in h])
hd[str] = h
h=[]
else:
x = line.split("\t")
word,label = x[index0],x[-1]
h.append((word,label))
if h!=[]:
hh.append(h)
str=" ".join([x[0] for x in h])
hd[str] = h
return hh,hd
| 434 | 17.125 | 39 | py |
coling2018-xling_argument_mining | coling2018-xling_argument_mining-master/code/annotationProjection/projectArguments.py | import sys
from readDocs import readDoc as rd
# project argument spans from source to target document
# Steffen Eger
# 03/2018
# SAMPLE USAGE:
# python2 projectArguments.py train_full.dat test_full.dat dev_full.dat essays.aligned essays.aligned.bidirectional
#
# Inputs:
# $x_full.dat: train, test, dev annotated data in source language
# essays.aligned: aligned sentences in source and target language (source sentences must all be in train/dev/test.dat)
# essays.aligned.bidirectional: word alignments (e.g., produced by fast_align)
# Outputs:
# my${x}_gen1.dat: train, test, dev projected annotation spans in the target language
K=1
def isConsecutive(lst,descending=False):
last = None
for x in lst:
if last is not None:
next = last-1 if descending else last+1
if x!=next: return False
last = x
return True
def findExtremeConsecutive(lst,reverse=True,k=1):
s = sorted(lst,reverse=reverse)
for ix,x in enumerate(s):
mylst = s[ix:ix+k]
if isConsecutive(mylst,descending=reverse): return x
return s[0]
def detect_bios(labels):
indices = []
startComponent=False
startindex = None
type = None
for index,tok in enumerate(labels):
word,token = tok
if startComponent==True and token.startswith("B-"):
endindex = index-1
indices.append((startindex,endindex,type))
startindex = index
type = token.split(":")[0][2:]
startComponent = True
elif startComponent==True and token.startswith("O"):
endindex = index-1
indices.append((startindex,endindex,type))
startComponent = False
elif token.startswith("B-"):
type = token.split(":")[0][2:]
startComponent = True
startindex = index
if token.startswith("I-"):
endindex = index
indices.append((startindex,endindex,type))
return indices
def getTranslationIndices(indices,align):
h = {}
for y in align.split():
a,b = list(map(int,y.split("-")))
if a in h:
h[a] = h[a]+[b]
else:
h[a] = [b]
#print(h,align,indices)
#sys.exit(1)
aligns=[]
for x in indices:
start,end,type = x
q = []
for z in range(start,end+1):
#print("-->",z,h)
#print(h[z])
q.append( h.get(z,None) )
qq = list(filter(lambda x: x!=None,q))
flat_list = [item for sublist in qq for item in sublist]
#print("##->",flat_list,x)
#print(flat_list); sys.exit(1)
# YOU MAY WANT TO CHANGE THIS
indexStart,indexEnd = min(flat_list),max(flat_list)
for myK in range(K,0,-1):
indexStart,indexEnd = findExtremeConsecutive(flat_list,reverse=False,k=K),findExtremeConsecutive(flat_list,reverse=True,k=myK)
if len(aligns)>0:
indexEndPrev = aligns[-1][1]
indexStartPrev = aligns[-1][0]
if indexStart<=indexEndPrev:
sys.stderr.write("DOESN'T WORK OUT %d %d\n"%(indexStart,indexEndPrev))
if indexEnd<indexStartPrev:
sys.stderr.write("Li'l non-monotonity\n")
break
indexStart = indexEndPrev+1
if indexStart<=indexEnd: break
if indexStart>indexEnd:
sys.stderr.write(str(aligns))
sys.stderr.write("ERROR SOMEWHERE: %d %d\n"%(indexStart,indexEnd));
#sys.exit(1)
print(indices)
aligns.append((indexStart,indexEnd,type))
#print(aligns)
return aligns
def printout(sequence,fout,type="O"):
for itoken,token in enumerate(sequence):
if type!="O":
if itoken==0:
pre="B-"
else:
pre="I-"
else:
pre=""
fout.write(token+"\t"+pre+type+"\n")
def process(sentences,sentences_alignments,labels,fout,verbose=False):
n = len(sentences)
last = 0
for i in range(len(sentences)):
en,de = sentences[i]
en_tokens = en.split()
de_tokens = de.split()
m = len(en_tokens)
align = sentences_alignments[i].strip()
curLabels = labels[last:last+m]
indices = detect_bios(curLabels)
last = last+m
#print(en_tokens,"\t",curLabels,"\t",de_tokens,"\t",indices)
#print(align)
aligns = sorted( getTranslationIndices(indices,align) )
if verbose:
print("ALIGNS",aligns,de)
#if aligns!=[]:
prev = 0
for start,end,type in aligns:
if start>end: continue
before = de_tokens[prev:start]
middle = de_tokens[start:end+1]
if before!=[]: printout(before,fout)
printout(middle,fout,type)
prev = end+1
after = de_tokens[prev:]
if after!=[]:
printout(after,fout)
#sys.exit(1)
train,train_hash = rd(sys.argv[1])
test,test_hash = rd(sys.argv[2])
dev,dev_hash = rd(sys.argv[3])
#print(train_hash)
alignedText = sys.argv[4]
alignments = sys.argv[5]
fp_lines=open(alignments).readlines()
acc=[]
sentences=[]
sentences_alignments=[]
i=0
ftrain=open("mytrain_gen%d.dat"%K,"w")
ftest=open("mytest_gen%d.dat"%K,"w")
fdev=open("mydev_gen%d.dat"%K,"w")
for line in open(alignedText):
line = line.strip()
en,de = line.split(" ||| ")
sentences.append((en,de))
sentences_alignments.append(fp_lines[i])
acc+=en.split()
acc_text = " ".join(acc)
#print(acc_text+"<--")
for hash in [train_hash,test_hash,dev_hash]:
if acc_text in hash:
if hash==train_hash: fout = ftrain
elif hash==test_hash: fout = ftest
elif hash==dev_hash: fout = fdev
else: fout=None
labels = hash[acc_text]
process(sentences,sentences_alignments,labels,fout)
fout.write("\n")
acc = []
sentences=[]
sentences_alignments=[]
i+=1
| 5,486 | 27.878947 | 132 | py |
checklist | checklist-master/setup.py | from setuptools import setup, find_packages
from setuptools.command.develop import develop
from setuptools.command.install import install
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.egg_info import egg_info
from setuptools.command.build_py import build_py
from subprocess import check_call
import sys
import os
def enable_visual_interface():
check_call(f'"{sys.executable}"'+" -m pip install jupyter", shell=True)
import notebook
notebook.nbextensions.install_nbextension_python(
"checklist.viewer", user=True, overwrite=True)
notebook.nbextensions.enable_nbextension_python(
"checklist.viewer")
def enable_visual_interface_shell_cmd(direction):
sys.path.append(direction)
enable_visual_interface()
#"""
class PostDevelopCommand(develop):
"""Pre-installation for development mode."""
def run(self):
develop.run(self)
#enable_visual_interface()
self.execute(enable_visual_interface_shell_cmd, (self.install_lib,), msg="Running post install task")
class BdistEggCommand(bdist_egg):
def run(self):
bdist_egg.run(self)
enable_visual_interface()
#self.execute(enable_visual_interface_shell_cmd, (self.install_lib,), msg=f"Running post install task on {sys.executable}")
class BuildPyCommand(build_py):
def run(self):
build_py.run(self)
enable_visual_interface()
#self.execute(enable_visual_interface_shell_cmd, (self.install_lib,), msg="Running post install task")
class PostInstallCommand(install):
def run(self):
#super().do_egg_install()
install.run(self)
self.execute(enable_visual_interface_shell_cmd, (self.install_lib,), msg="Running post install task")
#enable_visual_interface()
class EggInfoCommand(egg_info):
def run(self):
egg_info.run(self)
enable_visual_interface()
#self.execute(enable_visual_interface_shell_cmd, (self.install_lib,), msg="Running post install task")
setup(name='checklist',
version='0.0.11',
description='Beyond Accuracy: Behavioral Testing of NLP Models with CheckList',
url='http://github.com/marcotcr/checklist',
author='Marco Tulio Ribeiro',
author_email='[email protected]',
license='MIT',
packages= find_packages(exclude=['js', 'node_modules', 'tests']),
install_requires=[
'numpy>=1.18',
'spacy>=2.2',
'munch>=2.5',
'dill>=0.3.1',
'jupyter>=1.0',
'ipywidgets>=7.5',
'transformers>=2.8',
'patternfork-nosql',
'iso-639'
],
cmdclass={
'develop': PostDevelopCommand,
'install': PostInstallCommand,
'bdist_egg': BdistEggCommand,
'egg_info': EggInfoCommand,
'build_py': BuildPyCommand,
},
package_data={'viewer':['static/*'], "data": ["*"], 'checklist': ['data/*', 'data/lexicons/*', 'viewer/static/*']},
#include_package_data=True,
zip_safe=False
)
| 3,011 | 33.62069 | 131 | py |
checklist | checklist-master/checklist/perturb.py | import numpy as np
import collections
import re
import os
import json
import pattern
from pattern.en import tenses
from .editor import recursive_apply, MunchWithAdd
def load_data():
cur_folder = os.path.dirname(__file__)
basic = json.load(open(os.path.join(cur_folder, 'data', 'lexicons', 'basic.json')))
names = json.load(open(os.path.join(cur_folder, 'data', 'names.json')))
name_set = { x:set(names[x]) for x in names }
data = {
'name': names,
'name_set': name_set,
'city': basic['city'],
'country': basic['country'],
}
return data
def process_ret(ret, ret_m=None, meta=False, n=10):
if ret:
if len(ret) > n:
idxs = np.random.choice(len(ret), n, replace=False)
ret = [ret[i] for i in idxs]
if ret_m:
ret_m = [ret_m[i] for i in idxs]
if meta:
ret = (ret, ret_m)
return ret
return None
class Perturb:
data = load_data()
@staticmethod
def perturb(data, perturb_fn, keep_original=True, nsamples=None, *args, **kwargs):
"""Perturbs data according to some function
Parameters
----------
data : list
List of examples, could be strings, tuples, dicts, spacy docs, whatever
perturb_fn : function
Arguments: (example, *args, **kwargs)
Returns: list of examples, or (examples, meta) if meta=True in **kwargs.
Can also return None if perturbation does not apply, and it will be ignored.
keep_original : bool
if True, include original example (from data) in output
nsamples : int
number of examples in data to perturb
meta : bool
if True, perturb_fn returns (examples, meta), and meta is added to ret.meta
Returns
-------
MunchWithAdd
will have .data and .meta (if meta=True in **kwargs)
"""
ret = MunchWithAdd()
use_meta = kwargs.get('meta', False)
ret_data = []
meta = []
order = list(range(len(data)))
samples = 0
if nsamples:
np.random.shuffle(order)
for i in order:
d = data[i]
t = []
add = []
if keep_original:
org = recursive_apply(d, str)
t.append(org)
add.append(None)
p = perturb_fn(d, *args, **kwargs)
a = []
x = []
if not p or all([not x for x in p]):
continue
if use_meta:
p, a = p
if type(p) in [np.array, list]:
t.extend(p)
add.extend(a)
else:
t.append(p)
add.append(a)
ret_data.append(t)
meta.append(add)
samples += 1
if nsamples and samples == nsamples:
break
ret.data = ret_data
if use_meta:
ret.meta = meta
return ret
@staticmethod
def strip_punctuation(doc):
"""Removes punctuation
Parameters
----------
doc : spacy.tokens.Doc
spacy doc
Returns
-------
string
With punctuation stripped
"""
# doc is a spacy doc
while len(doc) and doc[-1].pos_ == 'PUNCT':
doc = doc[:-1]
return doc.text
@staticmethod
def punctuation(doc):
"""Perturbation function which adds / removes punctuations
Parameters
----------
doc : spacy.tokens.Doc
spacy doc
Returns
-------
list(string)
With punctuation removed and / or final stop added.
"""
# doc is a spacy doc
s = Perturb.strip_punctuation(doc)
ret = []
if s != doc.text:
ret.append(s)
if s + '.' != doc.text:
ret.append(s + '.')
return ret
@staticmethod
def add_typos(string, typos=1):
"""Perturbation functions, swaps random characters with their neighbors
Parameters
----------
string : str
input string
typos : int
number of typos to add
Returns
-------
list(string)
perturbed strings
"""
string = list(string)
swaps = np.random.choice(len(string) - 1, typos)
for swap in swaps:
tmp = string[swap]
string[swap] = string[swap + 1]
string[swap + 1] = tmp
return ''.join(string)
@staticmethod
def remove_negation(doc):
"""Removes negation from doc.
This is experimental, may or may not work.
Parameters
----------
doc : spacy.token.Doc
input
Returns
-------
string
With all negations removed
"""
# This removes all negations in the doc. I should maybe add an option to remove just some.
notzs = [i for i, z in enumerate(doc) if z.lemma_ == 'not' or z.dep_ == 'neg']
new = []
for notz in notzs:
before = doc[notz - 1] if notz != 0 else None
after = doc[notz + 1] if len(doc) > notz + 1 else None
if (after and after.pos_ == 'PUNCT') or (before and before.text in ['or']):
continue
new.append(notz)
notzs = new
if not notzs:
return None
ret = ''
start = 0
for i, notz in enumerate(notzs):
id_start = notz
to_add = ' '
id_end = notz + 1
before = doc[notz - 1] if notz != 0 else None
after = doc[notz + 1] if len(doc) > notz + 1 else None
if before and before.lemma_ in ['will', 'can', 'do']:
id_start = notz - 1
tenses = collections.Counter([x[0] for x in pattern.en.tenses(before.text)]).most_common(1)
tense = tenses[0][0] if len(tenses) else 'present'
p = pattern.en.tenses(before.text)
params = [tense, 3]
if p:
tmp = [x for x in p if x[0] == tense]
if tmp:
params = list(tmp[0])
else:
params = list(p[0])
to_add = ' '+ pattern.en.conjugate(before.lemma_, *params) + ' '
if before and after and before.lemma_ == 'do' and after.pos_ == 'VERB':
id_start = notz - 1
tenses = collections.Counter([x[0] for x in pattern.en.tenses(before.text)]).most_common(1)
tense = tenses[0][0] if len(tenses) else 'present'
p = pattern.en.tenses(before.text)
params = [tense, 3]
if p:
tmp = [x for x in p if x[0] == tense]
if tmp:
params = list(tmp[0])
else:
params = list(p[0])
to_add = ' '+ pattern.en.conjugate(after.text, *params) + ' '
id_end = notz + 2
ret += doc[start:id_start].text + to_add
start = id_end
ret += doc[id_end:].text
return ret
@staticmethod
def add_negation(doc):
"""Adds negation to doc
This is experimental, may or may not work. It also only works for specific parses.
Parameters
----------
doc : spacy.token.Doc
input
Returns
-------
string
With negations added
"""
for sentence in doc.sents:
if len(sentence) < 3:
continue
root_id = [x.i for x in sentence if x.dep_ == 'ROOT'][0]
root = doc[root_id]
if '?' in sentence.text and sentence[0].text.lower() == 'how':
continue
if root.lemma_.lower() in ['thank', 'use']:
continue
if root.pos_ not in ['VERB', 'AUX']:
continue
neg = [True for x in sentence if x.dep_ == 'neg' and x.head.i == root_id]
if neg:
continue
if root.lemma_ == 'be':
if '?' in sentence.text:
continue
if root.text.lower() in ['is', 'was', 'were', 'am', 'are', '\'s', '\'re', '\'m']:
return doc[:root_id + 1].text + ' not ' + doc[root_id + 1:].text
else:
return doc[:root_id].text + ' not ' + doc[root_id:].text
else:
aux = [x for x in sentence if x.dep_ in ['aux', 'auxpass'] and x.head.i == root_id]
if aux:
aux = aux[0]
if aux.lemma_.lower() in ['can', 'do', 'could', 'would', 'will', 'have', 'should']:
lemma = doc[aux.i].lemma_.lower()
if lemma == 'will':
fixed = 'won\'t'
elif lemma == 'have' and doc[aux.i].text in ['\'ve', '\'d']:
fixed = 'haven\'t' if doc[aux.i].text == '\'ve' else 'hadn\'t'
elif lemma == 'would' and doc[aux.i].text in ['\'d']:
fixed = 'wouldn\'t'
else:
fixed = doc[aux.i].text.rstrip('n') + 'n\'t' if lemma != 'will' else 'won\'t'
fixed = ' %s ' % fixed
return doc[:aux.i].text + fixed + doc[aux.i + 1:].text
return doc[:root_id].text + ' not ' + doc[root_id:].text
else:
# TODO: does, do, etc. Remover return None de cima
subj = [x for x in sentence if x.dep_ in ['csubj', 'nsubj']]
p = pattern.en.tenses(root.text)
tenses = collections.Counter([x[0] for x in pattern.en.tenses(root.text)]).most_common(1)
tense = tenses[0][0] if len(tenses) else 'present'
params = [tense, 3]
if p:
tmp = [x for x in p if x[0] == tense]
if tmp:
params = list(tmp[0])
else:
params = list(p[0])
if root.tag_ not in ['VBG']:
do = pattern.en.conjugate('do', *params) + 'n\'t'
new_root = pattern.en.conjugate(root.text, tense='infinitive')
else:
do = 'not'
new_root = root.text
return '%s %s %s %s' % (doc[:root_id].text, do, new_root, doc[root_id + 1:].text)
@staticmethod
def contractions(sentence, **kwargs):
"""Perturbation functions, contracts and expands contractions if present
Parameters
----------
sentence : str
input
Returns
-------
list
List of strings with contractions expanded or contracted, or []
"""
expanded = [Perturb.expand_contractions(sentence), Perturb.contract(sentence)]
return [t for t in expanded if t != sentence]
@staticmethod
def expand_contractions(sentence, **kwargs):
"""Expands contractions in a sentence (if any)
Parameters
----------
sentence : str
input string
Returns
-------
string
String with contractions expanded (if any)
"""
contraction_map = {
"ain't": "is not", "aren't": "are not", "can't": "cannot",
"can't've": "cannot have", "could've": "could have", "couldn't":
"could not", "didn't": "did not", "doesn't": "does not", "don't":
"do not", "hadn't": "had not", "hasn't": "has not", "haven't":
"have not", "he'd": "he would", "he'd've": "he would have",
"he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y":
"how do you", "how'll": "how will", "how's": "how is",
"I'd": "I would", "I'll": "I will", "I'm": "I am",
"I've": "I have", "i'd": "i would", "i'll": "i will",
"i'm": "i am", "i've": "i have", "isn't": "is not",
"it'd": "it would", "it'll": "it will", "it's": "it is", "ma'am":
"madam", "might've": "might have", "mightn't": "might not",
"must've": "must have", "mustn't": "must not", "needn't":
"need not", "oughtn't": "ought not", "shan't": "shall not",
"she'd": "she would", "she'll": "she will", "she's": "she is",
"should've": "should have", "shouldn't": "should not", "that'd":
"that would", "that's": "that is", "there'd": "there would",
"there's": "there is", "they'd": "they would",
"they'll": "they will", "they're": "they are",
"they've": "they have", "wasn't": "was not", "we'd": "we would",
"we'll": "we will", "we're": "we are", "we've": "we have",
"weren't": "were not", "what're": "what are", "what's": "what is",
"when's": "when is", "where'd": "where did", "where's": "where is",
"where've": "where have", "who'll": "who will", "who's": "who is",
"who've": "who have", "why's": "why is", "won't": "will not",
"would've": "would have", "wouldn't": "would not",
"you'd": "you would", "you'd've": "you would have",
"you'll": "you will", "you're": "you are", "you've": "you have"
}
# self.reverse_contraction_map = dict([(y, x) for x, y in self.contraction_map.items()])
contraction_pattern = re.compile(r'\b({})\b'.format('|'.join(contraction_map.keys())),
flags=re.IGNORECASE|re.DOTALL)
def expand_match(contraction):
match = contraction.group(0)
first_char = match[0]
expanded_contraction = contraction_map.get(match, contraction_map.get(match.lower()))
expanded_contraction = first_char + expanded_contraction[1:]
return expanded_contraction
return contraction_pattern.sub(expand_match, sentence)
@staticmethod
def contract(sentence, **kwargs):
"""Contract expanded contractions in a sentence (if any)
Parameters
----------
sentence : str
input string
Returns
-------
string
String with contractions contracted (if any)
"""
reverse_contraction_map = {
'is not': "isn't", 'are not': "aren't", 'cannot': "can't",
'could not': "couldn't", 'did not': "didn't", 'does not':
"doesn't", 'do not': "don't", 'had not': "hadn't", 'has not':
"hasn't", 'have not': "haven't", 'he is': "he's", 'how did':
"how'd", 'how is': "how's", 'I would': "I'd", 'I will': "I'll",
'I am': "I'm", 'i would': "i'd", 'i will': "i'll", 'i am': "i'm",
'it would': "it'd", 'it will': "it'll", 'it is': "it's",
'might not': "mightn't", 'must not': "mustn't", 'need not': "needn't",
'ought not': "oughtn't", 'shall not': "shan't", 'she would': "she'd",
'she will': "she'll", 'she is': "she's", 'should not': "shouldn't",
'that would': "that'd", 'that is': "that's", 'there would':
"there'd", 'there is': "there's", 'they would': "they'd",
'they will': "they'll", 'they are': "they're", 'was not': "wasn't",
'we would': "we'd", 'we will': "we'll", 'we are': "we're", 'were not':
"weren't", 'what are': "what're", 'what is': "what's", 'when is':
"when's", 'where did': "where'd", 'where is': "where's",
'who will': "who'll", 'who is': "who's", 'who have': "who've", 'why is':
"why's", 'will not': "won't", 'would not': "wouldn't", 'you would':
"you'd", 'you will': "you'll", 'you are': "you're",
}
reverse_contraction_pattern = re.compile(r'\b({})\b '.format('|'.join(reverse_contraction_map.keys())),
flags=re.IGNORECASE|re.DOTALL)
def cont(possible):
match = possible.group(1)
first_char = match[0]
expanded_contraction = reverse_contraction_map.get(match, reverse_contraction_map.get(match.lower()))
expanded_contraction = first_char + expanded_contraction[1:] + ' '
return expanded_contraction
return reverse_contraction_pattern.sub(cont, sentence)
@staticmethod
def change_names(doc, meta=False, n=10, first_only=False, last_only=False, seed=None):
"""Replace names with other names
Parameters
----------
doc : spacy.token.Doc
input
meta : bool
if True, will return list of (orig_name, new_name) as meta
n : int
number of names to replace original names with
first_only : bool
if True, will only replace first names
last_only : bool
if True, will only replace last names
seed : int
random seed
Returns
-------
list(str)
if meta=True, returns (list(str), list(tuple))
Strings with names replaced.
"""
if seed is not None:
np.random.seed(seed)
ents = [x.text for x in doc.ents if np.all([a.ent_type_ == 'PERSON' for a in x])]
ret = []
ret_m = []
for x in ents:
f = x.split()[0]
sex = None
if f.capitalize() in Perturb.data['name_set']['women']:
sex = 'women'
if f.capitalize() in Perturb.data['name_set']['men']:
sex = 'men'
if not sex:
continue
if len(x.split()) > 1:
l = x.split()[1]
if len(l) > 2 and l.capitalize() not in Perturb.data['name_set']['last']:
continue
else:
if last_only:
return None
names = Perturb.data['name'][sex][:90+n]
to_use = np.random.choice(names, n)
if not first_only:
f = x
if len(x.split()) > 1:
last = Perturb.data['name']['last'][:90+n]
last = np.random.choice(last, n)
to_use = ['%s %s' % (x, y) for x, y in zip(names, last)]
if last_only:
to_use = last
f = x.split()[1]
for y in to_use:
ret.append(re.sub(r'\b%s\b' % re.escape(f), y, doc.text))
ret_m.append((f, y))
return process_ret(ret, ret_m=ret_m, n=n, meta=meta)
@staticmethod
def change_location(doc, meta=False, seed=None, n=10):
"""Change city and country names
Parameters
----------
doc : spacy.token.Doc
input
meta : bool
if True, will return list of (orig_loc, new_loc) as meta
seed : int
random seed
n : int
number of locations to replace original locations with
Returns
-------
list(str)
if meta=True, returns (list(str), list(tuple))
Strings with locations replaced.
"""
if seed is not None:
np.random.seed(seed)
ents = [x.text for x in doc.ents if np.all([a.ent_type_ == 'GPE' for a in x])]
ret = []
ret_m = []
for x in ents:
if x in Perturb.data['city']:
names = Perturb.data['city'][:100]
elif x in Perturb.data['country']:
names = Perturb.data['country'][:50]
else:
continue
sub_re = re.compile(r'\b%s\b' % re.escape(x))
to_use = np.random.choice(names, n)
ret.extend([sub_re.sub(n, doc.text) for n in to_use])
ret_m.extend([(x, n) for n in to_use])
return process_ret(ret, ret_m=ret_m, n=n, meta=meta)
@staticmethod
def change_number(doc, meta=False, seed=None, n=10):
"""Change integers to other integers within 20% of the original integer
Does not change '2' or '4' to avoid abbreviations (this is 4 you, etc)
Parameters
----------
doc : spacy.token.Doc
input
meta : bool
if True, will return list of (orig_number, new_number) as meta
seed : int
random seed
n : int
number of numbers to replace original locations with
Returns
-------
list(str)
if meta=True, returns (list(str), list(tuple))
Strings with numbers replaced.
"""
if seed is not None:
np.random.seed(seed)
nums = [x.text for x in doc if x.text.isdigit()]
ret = []
ret_m = []
for x in nums:
# e.g. this is 4 you
if x == '2' or x == '4':
continue
sub_re = re.compile(r'\b%s\b' % x)
try:
change = int(int(x) * .2) + 1
except:
continue
to_sub = np.random.randint(-min(change, int(x) - 1), change + 1, n * 3)
to_sub = ['%s' % str(int(x) + t) for t in to_sub if str(int(x) + t) != x][:n]
ret.extend([sub_re.sub(n, doc.text) for n in to_sub])
ret_m.extend([(x, n) for n in to_sub])
return process_ret(ret, ret_m=ret_m, n=n, meta=meta)
| 21,734 | 36.217466 | 113 | py |
checklist | checklist-master/checklist/test_suite.py | import collections
from collections import defaultdict, OrderedDict
import dill
import json
from .abstract_test import load_test, read_pred_file
from .test_types import MFT, INV, DIR
from .viewer.suite_summarizer import SuiteSummarizer
class TestSuite:
def __init__(self, format_example_fn=None, print_fn=None):
self.tests = OrderedDict()
self.info = defaultdict(lambda: defaultdict(lambda: ''))
self.format_example_fn = format_example_fn
self.print_fn = print_fn
self.test_ranges = {}
@staticmethod
def from_file(path):
"""Loads suite from file
Parameters
----------
path : string
pickled (dill) file
Returns
-------
TestSuite
the suite
"""
return load_test(path)
def add(self, test, name=None, capability=None, description=None, format_example_fn=None, print_fn=None, overwrite=False):
"""Adds a test to suite
Parameters
----------
test : AbstractTest
test
name : string
test name. If test has test.name, this is optional.
capability : string
test capability. If test has test.capability, this is optional.
description : string
test description. If test has test.capability, this is optional.
format_example_fn : function
If not None, use this to print a failed example within a test case
Arguments: (x, pred, conf, label=None, meta=None)
print_fn : function
If not None, use this to print a failed test case.
Arguments: (xs, preds, confs, expect_results, labels=None, meta=None)
overwrite : bool
If False, will raise exception if test with same name is already in suite.
"""
if name is None and test.name is None:
raise(Exception('If test does not have test.name, you must specify a name'))
if capability is None and test.capability is None:
raise(Exception('If test does not have test.capabiliy, you must specify a capability'))
if name is None:
name = test.name
if capability is None:
capability = test.capability
if description is None:
description = test.description
if name in self.tests and not overwrite:
raise(Exception('There is already a test named %s suite. Run with overwrite=True to overwrite' % name))
if name in self.info:
del self.info[name]
type_map = {
MFT: 'MFT',
INV: 'INV',
DIR: 'DIR',
}
typez = type_map[type(test)]
self.tests[name] = test
self.info[name]['capability'] = capability
self.info[name]['type'] = typez
if description:
self.info[name]['description'] = description
if format_example_fn:
self.info[name]['format_example_fn'] = format_example_fn
if print_fn:
self.info[name]['print_fn'] = format_example_fn
def remove(self, name):
"""Removes test from suite
Parameters
----------
name : string
test name
"""
if name not in self.tests:
raise(Exception('%s not in suite.' % name))
del self.tests[name]
del self.info[name]
def to_dict(self, example_to_dict_fn=None, n=None, seed=None, new_sample=False):
if example_to_dict_fn is None:
try:
example_to_dict_fn = self.example_to_dict_fn
except AttributeError:
raise(Exception('suite does not have example_to_dict_fn, must pass function as argument.'))
examples = self.get_raw_examples(format_fn=lambda x:x, n=n, seed=seed, new_sample=new_sample)
data_keys = list(example_to_dict_fn(examples[0]).keys())
keys = data_keys + ['test_name', 'test_case', 'example_idx']
hf_dict = { k:[] for k in keys }
for e in examples:
m = example_to_dict_fn(e)
for k,v in m.items():
hf_dict[k].append(v)
for test_name, r in sorted(self.test_ranges.items(), key=lambda x:x[1][0]):
test = self.tests[test_name]
size = r[1] - r[0]
hf_dict['test_name'].extend([test_name for _ in range(size)])
hf_dict['test_case'].extend(test.result_indexes)
cnt = collections.defaultdict(lambda: 0)
example_idx = []
for i in test.result_indexes:
example_idx.append(cnt[i])
cnt[i] += 1
hf_dict['example_idx'].extend(example_idx)
return hf_dict
def get_raw_examples(self, file_format=None, format_fn=None, n=None, seed=None, new_sample=True):
if new_sample or len(self.test_ranges) == 0:
self.test_ranges = {}
all_examples = self.create_raw_example_list(file_format=file_format, format_fn=format_fn, n=n, seed=seed)
else:
all_examples = self.get_raw_example_list(file_format=file_format, format_fn=format_fn)
return all_examples
def get_raw_example_list(self, file_format=None, format_fn=None):
if not self.test_ranges:
raise(Exception('example list not created. please call create_raw_example_list, or to_raw_file first'))
examples = []
for test_name, r in sorted(self.test_ranges.items(), key=lambda x:x[1][0]):
test = self.tests[test_name]
test_examples = test.to_raw_examples(file_format=file_format, format_fn=format_fn,
n=None, seed=None, new_sample=False)
assert len(test_examples) == r[1] - r[0]
examples.extend(test_examples)
return examples
def create_raw_example_list(self, file_format, format_fn, n, seed):
self.test_ranges = {}
current_idx = 0
all_examples = []
for name, t in self.tests.items():
examples = t.to_raw_examples(file_format=file_format, format_fn=format_fn, n=n, seed=seed, new_sample=True)
self.test_ranges[name] = (current_idx, current_idx + len(examples))
current_idx += len(examples)
all_examples.extend(examples)
return all_examples
def to_raw_file(self, path, file_format=None, format_fn=None, header=None, n=None, seed=None, new_sample=True):
"""Flatten all tests into individual examples and print them to file.
Indices of example to test case will be stored in each test.
If n is not None, test.run_idxs will store the test case indexes.
The line ranges for each test will be saved in self.test_ranges.
Parameters
----------
path : string
File path
file_format : string, must be one of 'jsonl', 'squad', 'qqp_test', or None
None just calls str(x) for each example in self.data
squad assumes x has x['question'] and x['passage'], or that format_fn does this
format_fn : function or None
If not None, call this function to format each example in self.data
header : string
If not None, first line of file
n : int
If not None, number of samples to draw
seed : int
Seed to use if n is not None
new_sample: bool
If False, will rely on a previous sample and ignore the 'n' and 'seed' parameters
"""
ret = ''
all_examples = []
add_id = False
if file_format == 'qqp_test':
add_id = True
file_format = 'tsv'
header = 'id\tquestion1\tquestion2'
if header is not None:
ret += header.strip('\n') + '\n'
all_examples = self.get_raw_examples(file_format=file_format, format_fn=format_fn, n=n, seed=seed, new_sample=new_sample)
if add_id and file_format == 'tsv':
all_examples = ['%d\t%s' % (i, x) for i, x in enumerate(all_examples)]
if file_format == 'squad':
ret_map = {'version': 'fake',
'data': []}
for i, x in enumerate(all_examples):
r = {'title': '',
'paragraphs': [{
'context': x['passage'],
'qas': [{'question' : x['question'],
'id': str(i)
}]
}]
}
ret_map['data'].append(r)
ret = json.dumps(ret_map)
else:
ret += '\n'.join(all_examples)
f = open(path, 'w')
f.write(ret)
f.close()
def run_from_preds_confs(self, preds, confs, overwrite):
for n, t in self.tests.items():
p = preds[slice(*self.test_ranges[n])]
c = confs[slice(*self.test_ranges[n])]
t.run_from_preds_confs(p, c, overwrite=overwrite)
def run_from_file(self, path, file_format=None, format_fn=None, ignore_header=False, overwrite=False):
"""Update test.results (run tests) for every test, from a prediction file
Parameters
----------
path : string
prediction file path
file_format : string
None, or one of 'pred_only', 'softmax', binary_conf', 'pred_and_conf', 'pred_and_softmax', 'squad',
pred_only: each line has a prediction
softmax: each line has prediction probabilities separated by spaces
binary_conf: each line has the prediction probability of class 1 (binary)
pred_and_conf: each line has a prediction and a confidence value, separated by a space
pred_and_softmax: each line has a prediction and all softmax probabilities, separated by a space
squad: TODO
format_fn : function
If not None, function that reads a line in the input file and outputs a tuple of (prediction, confidence)
ignore_header : bool
If True, skip first line in the file
overwrite : bool
If False, raise exception if results already exist
"""
preds, confs = read_pred_file(path, file_format=file_format,
format_fn=format_fn,
ignore_header=ignore_header)
self.run_from_preds_confs(preds, confs, overwrite=overwrite)
def run(self, predict_and_confidence_fn, verbose=True, **kwargs):
"""Runs all tests in the suite
See run in abstract_test.py .
Parameters
----------
predict_and_confidence_fn : function
Takes as input a list of examples
Outputs a tuple (predictions, confidences)
overwrite : bool
If False, raise exception if results already exist
verbose : bool
If True, print extra information
n : int
If not None, number of samples to draw
seed : int
Seed to use if n is not None
"""
for n, t in self.tests.items():
if verbose:
print('Running', n)
t.run(predict_and_confidence_fn, verbose=verbose, **kwargs)
def summary(self, types=None, capabilities=None, **kwargs):
"""Print stats and example failures for each test.
See summary in abstract_test.py
Parameters
----------
types : list(string)
If not None, will only show tests of these test types.
Options are MFT, INV, and DIR
capabilities : list(string)
If not None, will only show tests with these capabilities.
**kwargs : type
Will be passed as arguments to each test.summary()
"""
vals = collections.defaultdict(lambda: 100, {'MFT': 0, 'INV': 1, 'DIR': 2})
tests = self.tests.keys()
capability_order = ['Vocabulary', 'Taxonomy', 'Robustness', 'NER', 'Fairness', 'Temporal', 'Negation', 'Coref', 'SRL', 'Logic']
cap_order = lambda x:capability_order.index(x) if x in capability_order else 100
caps = sorted(set([x['capability'] for x in self.info.values()]), key=cap_order)
for capability in caps:
if capabilities is not None and capability not in capabilities:
continue
print(capability)
print()
tests = [x for x in self.tests if self.info[x]['capability'] == capability]
for n in tests:
if types is not None and self.info[n]['type'] not in types:
continue
print(n)
if 'format_example_fn' not in kwargs:
kwargs['format_example_fn'] = self.info[n].get('format_example_fn', self.format_example_fn)
if 'print_fn' not in kwargs:
kwargs['print_fn'] = self.info[n].get('print_fn', self.print_fn)
self.tests[n].summary(**kwargs)
print()
print()
print()
print()
def visual_summary_by_test(self, testname):
"""Displays visual summary for a single test.
Parameters
----------
testname : string
name of the test
Returns
-------
test.visual_summary
summary
"""
if not testname in self.tests:
raise(Exception(f"There's no test named {testname} in the suite!"))
test, info = self.tests[testname], self.info[testname]
return test.visual_summary(
name=testname,
capability=info["capability"] if "capability" in info else None,
description=info["description"] if "description" in info else None
)
def _on_select_test(self, testname: str):
if not testname:
test_info, testcases = {}, []
else:
if not testname in self.tests:
raise(Exception(f"There's no test named {testname} in the suite!"))
test, info = self.tests[testname], self.info[testname]
test_info = test.form_test_info(
name=testname,
capability=info["capability"] if "capability" in info else None,
description=info["description"] if "description" in info else None
)
n = 1 if self.info[testname]['type'] == 'MFT' else 2
testcases = test.form_testcases(n_per_testcase=n)
return test_info, testcases
def visual_summary_table(self, types=None, capabilities=None):
"""Displays a matrix visualization of the test suite
Parameters
----------
types : list(string)
If not None, will only show tests of these test types.
Options are MFT, INV, and DIR
capabilities : list(string)
If not None, will only show tests with these capabilities.
Returns
-------
SuiteSummarizer
jupyter visualization
"""
print("Please wait as we prepare the table data...")
test_infos = []
for testname in self.tests.keys():
test, info = self.tests[testname], self.info[testname]
local_info = test.form_test_info(
name=testname,
capability=info["capability"] if "capability" in info else None,
description=info["description"] if "description" in info else None
)
if (not capabilities or local_info["capability"] in capabilities) and \
(not types or local_info["type"] in types):
test_infos.append(local_info)
capability_order = ['Vocabulary', 'Taxonomy', 'Robustness', 'NER', 'Fairness', 'Temporal', 'Negation', 'Coref', 'SRL', 'Logic']
cap_order = lambda x: capability_order.index(x["capability"]) if x in capability_order else 100
test_infos = sorted(test_infos, key=cap_order)
return SuiteSummarizer(
test_infos=test_infos,
select_test_fn=self._on_select_test
)
def save(self, path):
"""Serializes the suite and saves it to a file
Parameters
----------
path : string
output file path
"""
dill.dump(self, open(path, 'wb'), recurse=True)
| 16,352 | 39.477723 | 136 | py |
checklist | checklist-master/checklist/test_types.py | from .abstract_test import AbstractTest
from .expect import Expect
class MFT(AbstractTest):
def __init__(self, data, expect=None, labels=None, meta=None, agg_fn='all',
templates=None, name=None, capability=None, description=None):
"""Minimum Functionality Test
Parameters
----------
data : list
List or list(lists) of whatever the model takes as input. Strings, tuples, etc.
expect : function
Expectation function, takes an AbstractTest (self) as parameter
see expect.py for details
labels : single value (int, str, etc) or list
If list, must be the same length as data
meta : list
metadata for examples, must be the same length as data
agg_fn : function, or string in ['all', 'all_except_first']
Aggregation function for expect function, if each element in data is a list.
Takes as input a numpy array, outputs a boolean.
templates : list(tuple)
Parameters used to generate the data. Use ret.templates from editor.template
name : str
test name
capability : str
test capability
description : str
test description
"""
if labels is None and expect is None:
raise(Exception('Must specify either \'expect\' or \'labels\''))
if labels is not None and expect is None:
expect = Expect.eq()
super().__init__(data, expect, labels=labels, meta=meta, agg_fn=agg_fn,
templates=templates, print_first=False, name=name,
capability=capability, description=description)
class INV(AbstractTest):
def __init__(self, data, expect=None, threshold=0.1, meta=None,
agg_fn='all_except_first', templates=None, name=None,
capability=None, description=None, labels=None):
"""Invariance Test
Parameters
----------
data : list
List or list(lists) of whatever the model takes as input. Strings, tuples, etc.
expect : function
Expectation function, takes an AbstractTest (self) as parameter
see expect.py for details. If None, will be Invariance with threshold
threshold : float
Prediction probability threshold for invariance. Will consider
pairs invariant even if prediction is the same when difference in
probability is smaller than threshold.
meta : list
metadata for examples, must be the same length as data
agg_fn : function, or string in ['all', 'all_except_first']
Aggregation function for expect function, if each element in data is a list.
Takes as input a numpy array, outputs a boolean.
templates : list(tuple)
Parameters used to generate the data. Use ret.templates from editor.template
name : str
test name
capability : str
test capability
description : str
test description
labels : single value (int, str, etc) or list
If list, must be the same length as data
"""
if expect is None:
expect = Expect.inv(threshold)
super().__init__(data, expect, labels=labels, meta=meta, agg_fn=agg_fn,
templates=templates, print_first=True, name=name,
capability=capability, description=description)
class DIR(AbstractTest):
def __init__(self, data, expect, meta=None, agg_fn='all_except_first',
templates=None, name=None, labels=None, capability=None, description=None):
"""Directional Expectation Test
Parameters
----------
data : list
List or list(lists) of whatever the model takes as input. Strings, tuples, etc.
expect : function
Expectation function, takes an AbstractTest (self) as parameter
see expect.py for details.
meta : list
metadata for examples, must be the same length as data
agg_fn : function, or string in ['all', 'all_except_first']
Aggregation function for expect function, if each element in data is a list.
Takes as input a numpy array, outputs a boolean.
templates : list(tuple)
Parameters used to generate the data. Use ret.templates from editor.template
name : str
test name
labels : single value (int, str, etc) or list
If list, must be the same length as data
capability : str
test capability
description : str
test description
"""
super().__init__(data, expect, labels=labels, meta=meta, agg_fn=agg_fn,
templates=templates, print_first=True, name=name,
capability=capability, description=description)
| 4,974 | 44.227273 | 92 | py |
checklist | checklist-master/checklist/editor.py | import collections
import itertools
import string
import numpy as np
import re
import copy
import os
import json
import munch
import pickle
import csv
from .viewer.template_editor import TemplateEditor
from .multilingual import multilingual_params, get_language_code
class MunchWithAdd(munch.Munch):
def __add__(self, other):
temp = copy.deepcopy(self)
for k in self:
try:
temp[k] = temp[k] + other[k]
except KeyError:
raise Exception('Both Munches must have the same keys')
return temp
def __iadd__(self, other):
for k in self:
self[k] = self[k] + other[k]
return self
def __hash__(self):
return hash(self.toJSON())
class SafeFormatter(string.Formatter):
def vformat(self, format_string, args, kwargs):
args_len = len(args) # for checking IndexError
tokens = []
for (lit, name, spec, conv) in self.parse(format_string):
# re-escape braces that parse() unescaped
lit = lit.replace('{', '{{').replace('}', '}}')
# only lit is non-None at the end of the string
if name is None:
tokens.append(lit)
else:
# but conv and spec are None if unused
conv = '!' + conv if conv else ''
spec = ':' + spec if spec else ''
# name includes indexing ([blah]) and attributes (.blah)
# so get just the first part
fp = name.split('[')[0].split('.')[0]
# treat as normal if fp is empty (an implicit
# positional arg), a digit (an explicit positional
# arg) or if it is in kwargs
if not fp or fp.isdigit() or fp in kwargs:
tokens.extend([lit, '{', name, conv, spec, '}'])
# otherwise escape the braces
else:
tokens.extend([lit, '{{', name, conv, spec, '}}'])
format_string = ''.join(tokens) # put the string back together
# finally call the default formatter
return string.Formatter.vformat(self, format_string, args, kwargs)
def recursive_format(obj, mapping, ignore_missing=False):
"""Formats all strings within an object, using mapping
Parameters
----------
obj : string, tuple, list, or dict
Object (leaves must be strings, regardless of type)
mapping : dict
format dictionary, maps keys to values
ignore_missing : bool
If True, will not throw exception if a string contains a tag not
present in mapping, and will keep the tag instead.
Returns
-------
string, tuple, list, or dict
Object of the same type as obj, with strings formatted (tags replaced
by their value)
"""
def formatfn(x, mapping):
fmt = SafeFormatter()
formatz = lambda x, m: x.format(**m) if not ignore_missing else fmt.format(x, **m)
options = re.compile(r'{([^}]+):([^}]+)}')
def mysub(match):
options, thing = match.group(1, 2)
ret = ''
if 'a' in options:
if ignore_missing and thing not in mapping:
return match.group()
else:
word = formatz('{%s}' % thing, mapping)
ret += '%s ' % add_article(word).split()[0]
ret += '{%s}' % thing
return ret
x = options.sub(mysub, x)
return formatz(x, mapping)
return recursive_apply(obj, formatfn, mapping)
def recursive_apply(obj, fn, *args, **kwargs):
"""Recursively applies a function to an obj
Parameters
----------
obj : string, tuple, list, or dict
Object (leaves must be strings, regardless of type)
fn : function
function to be applied to the leaves (strings)
Returns
-------
string, tuple, list, or dict
Object of the same type as obj, with fn applied to leaves
"""
if type(obj) in [str, bytes]:
return fn(obj, *args, **kwargs)#obj.format(**(mapping))
elif type(obj) == tuple:
return tuple(recursive_apply(list(obj), fn, *args, **kwargs))
elif type(obj) == list:
return [recursive_apply(o, fn, *args, **kwargs) for o in obj]
elif type(obj) == dict:
return {k: recursive_apply(v, fn, *args, **kwargs) for k, v in obj.items()}
else:
return fn(obj, *args, **kwargs)
# return obj
def replace_mask(text):
"""Replaces multiple instances of mask with indexed versions.
Parameters
----------
text : string
masked input, e.g. "This is a {mask} {mask} and {mask}"
Returns
-------
string
multiple instances of the same mask are replaced with indexed versions
e.g. "This is a {mask[0]} {mask[1]} and {mask[2]}
"""
mask_finder = re.compile(r'\{((?:[^\}]*:)?mask\d*)\}')
i = 0
while mask_finder.search(text):
text = mask_finder.sub(r'{\1[%d]}' % i, text, 1)
i += 1
return text
def add_article(noun):
return 'an %s' % noun if noun[0].lower() in ['a', 'e', 'i', 'o', 'u'] else 'a %s' % noun
def find_all_keys(obj):
"""Finds all tag keys in object
Parameters
----------
obj : string, tuple, list, or dict
Object (leaves must be strings, regardless of type)
Returns
-------
set
Set of all keys (with options)
"""
strings = get_all_strings(obj)
ret = set()
for s in strings:
f = string.Formatter()
for x in f.parse(s):
r = x[1] if not x[2] else '%s:%s' % (x[1], x[2])
ret.add(r)
return set([x for x in ret if x])
def get_mask_index(obj):
"""Find all masked strings in obj and index them by mask id
Parameters
----------
obj : string, tuple, list, or dict
Object (leaves must be strings, regardless of type)
Returns
-------
tuple(dict, dict)
First dict is a map from mask id to list of strings
Second dict is a map from mask id to options
"""
strings = get_all_strings(obj)
# ?: after parenthesis makes group non-capturing
mask_finder = re.compile(r'\{(?:[^\}]*:)?mask\d*\}')
mask_rep = re.compile(r'[\{\}]')
find_options = re.compile(r'.*:')
ret = collections.defaultdict(lambda: [])
options = collections.defaultdict(lambda: '')
for s in strings:
masks = mask_finder.findall(s)
nooptions = [mask_rep.sub('', find_options.sub('', x)) for x in masks]
ops = [find_options.search(mask_rep.sub('', x)) for x in masks]
ops = [x.group().strip(':') for x in ops if x]
if len(set(nooptions)) > 1:
raise Exception('Can only have one mask index per template string')
if nooptions:
ret[nooptions[0]].append(s)
options[nooptions[0]] += ''.join(ops)
return ret, options
def get_all_strings(obj):
"""Returns all strings in obj
Parameters
----------
obj : string, tuple, list, or dict
Object (leaves must be strings, regardless of type)
Returns
-------
set
All strings in obj leaves.
"""
ret = set()
if type(obj) in [str, bytes]:
ret.add(obj)
elif type(obj) in [tuple, list, dict]:
if type(obj) == dict:
obj = obj.values()
k = [get_all_strings(x) for x in obj]
k = [x for x in k if x]
for x in k:
ret = ret.union(x)
return set([x for x in ret if x])
def get_all_strings_ordered(obj):
ret = list()
if type(obj) in [str, bytes]:
ret.append(obj)
elif type(obj) in [tuple, list, dict]:
if type(obj) == dict:
obj = obj.values()
k = [get_all_strings(x) for x in obj]
for x in k:
ret += x
return [x for x in ret if x]
def wrapped_random_choice(x, *args, **kwargs):
try:
return np.random.choice(x, *args, **kwargs)
except:
idxs = np.random.choice(len(x), *args, **kwargs)
return type(x)([x[i] for i in idxs])
class Editor(object):
def __init__(self, language='english', model_name=None):
self.lexicons = {}
self.data = {}
self.tg_params = {
'language': language,
}
if model_name is not None:
self.tg_params['model_name'] = model_name
self._load_lexicons(language)
self.selected_suggestions = []
def _load_lexicons(self, language):
cur_folder = os.path.dirname(__file__)
folder = os.path.abspath(os.path.join(cur_folder, "data", 'lexicons'))
for f in os.listdir(folder):
self.lexicons.update(json.load(open(os.path.join(folder, f))))
self.data['names'] = json.load(open(os.path.join(cur_folder, 'data', 'names.json')))
self.data['names'] = {x:set(self.data['names'][x]) for x in self.data['names']}
make_munch = lambda x: munch.Munch(x) if type(x) == dict else x
for x in self.lexicons:
self.lexicons[x] = [make_munch(x) for x in self.lexicons[x]]
language = get_language_code(language)
wikidata = pickle.load(open(os.path.join(cur_folder, 'data', 'wikidata.pkl'), 'rb'))
get_ln = lambda d: d.get(language, d.get('en'))
self.lexicons['male'] = get_ln(wikidata.mnames)
self.lexicons['female'] = get_ln(wikidata.fnames)
self.lexicons['first_name'] = [y for x in zip(self.lexicons['male'], self.lexicons['female']) for y in x]
self.lexicons['last_name'] = get_ln(wikidata.lnames)
self.lexicons['country'] = [get_ln(x.label) for x in wikidata.countries]
# united states by default
self.lexicons['city'] = [get_ln(x.label) for x in wikidata.countries[2].cities]
# Most populous country that has language as official language
for country in wikidata.countries:
if country.primary_lang == language:
self.lexicons['city'] = [get_ln(x.label) for x in country.cities]
break
self.lexicons['country_city'] = munch.Munch()
for country in wikidata.countries:
l = country.label.en.replace(' ', '_')
self.lexicons['country_city'][l] = [get_ln(x.label) for x in country.cities]
self.lexicons['male_from'] = wikidata.male_by_country
self.lexicons['female_from'] = wikidata.female_by_country
self.lexicons['last_from'] = wikidata.last_by_country
self.lexicons = munch.Munch(self.lexicons)
def __getattr__(self, attr):
if attr == 'tg':
from .text_generation import TextGenerator
params = multilingual_params(**self.tg_params)
self.tg = TextGenerator(**params)
return self.tg
else:
raise AttributeError
def suggest_replace(self, text, word, full_sentences=False, words_and_sentences=False, **kwargs):
"""Masked language model suggestion for replacing word in sentence
Parameters
----------
text : str
context
word : str
word to be replaced
full_sentences : bool
If True, returns full sentences with replaced suggestions
words_and_sentences : bool
If True, returns tuples of (replacement word, full_sentence)
Returns
-------
list
Default: list of strings, suggestions for replacements
If full_sentences or words_and_sentences: see documentation above.
"""
ret = self.tg.replace_word(text, word, **kwargs)
if kwargs.get('verbose', False):
print('\n'.join(['%6s %s' % ('%.2f' % x[2], x[1]) for x in ret[:5]]))
if words_and_sentences:
return [(tuple(x[0]), x[1]) if len(x[0]) > 1 else (x[0][0], x[1]) for x in ret]
if full_sentences:
return [x[1] for x in ret]
else:
return [tuple(x[0]) if len(x[0]) > 1 else x[0][0] for x in ret]
def _wordnet_stuff(self, templates, word, type, threshold=5, depth=3, pos=None, **kwargs):
texts = self.template(templates, unroll=True, **kwargs).data
idxs = np.random.choice(len(texts), min(10, len(texts)), replace=False)
texts = [texts[i] for i in idxs]
if type != 'related' and any([word not in x for x in texts]):
raise Exception('word %s must be in all templates' % word)
fn = {'antonyms': self.tg.antonyms,
'synonyms': self.tg.synonyms,
'related': self.tg.related_words,
'hypernyms': self.tg.more_general,
'hyponyms': self.tg.more_specific,
}[type]
return [x[0][0] for x in fn(texts, word, threshold=threshold, pos=pos, depth=depth)]
def antonyms(self, templates, word, threshold=5, **kwargs):
"""Find antonyms of word that fit in templates
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
word : str
Word for which we want antonyms
threshold : float
Maximum allowed log likelihood difference between word and antonym in context
Returns
-------
list
List of antonyms that fit the given templates
"""
return self._wordnet_stuff(templates, word, 'antonyms', threshold=threshold, **kwargs)
def synonyms(self, templates, word, threshold=5, **kwargs):
"""Find synonyms of word that fit in templates
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
word : str
Word for which we want synonyms
threshold : float
Maximum allowed log likelihood difference between word and antonym in context
Returns
-------
list
List of synonyms that fit the given templates
"""
return self._wordnet_stuff(templates, word, 'synonyms', threshold=threshold, **kwargs)
def related_words(self, templates, word, threshold=5, **kwargs):
"""Find words that are related to word that fit in templates
By related words, we mean hyponyms of the word's hypernyms
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
word : str
Word for which we want related words
threshold : float
Maximum allowed log likelihood difference between word and antonym in context
Returns
-------
list
List of related words that fit the given templates
"""
return self._wordnet_stuff(templates, word, 'related', threshold=threshold, **kwargs)
def hypernyms(self, templates, word, threshold=5, **kwargs):
"""Find hypernyms of word that fit in templates
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
word : str
Word for which we want hypernyms
threshold : float
Maximum allowed log likelihood difference between word and antonym in context
Returns
-------
list
List of hypernyms that fit the given templates
"""
return self._wordnet_stuff(templates, word, 'hypernyms', threshold=threshold, **kwargs)
def hyponyms(self, templates, word, threshold=5, **kwargs):
"""Find hyponyms of word that fit in templates
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
word : str
Word for which we want hyponyms
threshold : float
Maximum allowed log likelihood difference between word and antonym in context
Returns
-------
list
List of hyponyms that fit the given templates
"""
return self._wordnet_stuff(templates, word, 'hyponyms', threshold=threshold, **kwargs)
def suggest(self, templates, return_score=False, **kwargs):
"""Suggests fill-ins based on a masked language model
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
Must have at least one {mask}. Cannot have {mask} and {mask1}, but can have multiple {mask}s
return_score : bool
If True, returns tuples of (word, score)
**kwargs : type
See documentation for function 'template'
Returns
-------
list(str or tuple)
list of fill-in suggestions, sorted by likelihood
(with likelihood if return_score=True)
"""
mask_index, ops = get_mask_index(templates)
if not mask_index:
return []
if len(mask_index) != 1:
raise Exception('Only one mask index is allowed')
ret = self.template(templates, **kwargs, mask_only=True)
xs = [tuple(x[0]) if len(x[0]) > 1 else x[0][0] for x in ret]
if return_score:
scores = [x[2] for x in ret]
xs = list(zip(xs, scores))
if kwargs.get('verbose', False):
print('\n'.join(['%6s %s' % ('%.2f' % x[2], x[1]) for x in ret[:5]]))
return xs
def _set_selected_suggestions(self, mask_suggests):
self.selected_suggestions = mask_suggests
return self.selected_suggestions
def visual_suggest(self, templates, **kwargs):
"""Spawns a jupyter visualization for masked language model suggestions
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
Must have at least one {mask}. Cannot have {mask} and {mask1}, but can have multiple {mask}s
**kwargs : type
See documentation for function 'template'
Returns
-------
TemplateEditor
visualization. Selected suggestions will be in self.selected_suggestions
"""
tagged_keys = find_all_keys(templates)
template_strs = get_all_strings_ordered(templates)
items = self._get_fillin_items(tagged_keys, max_count=5, **kwargs)
kwargs["verbose"] = False
mask_suggests = self.suggest(templates, **kwargs)
if not mask_suggests:
raise Exception('No valid suggestions for the given template!')
self.selected_suggestions = []
return TemplateEditor(
template_strs=template_strs,
tagged_keys=tagged_keys,
tag_dict=items,
mask_suggests=mask_suggests[:50],
format_fn=recursive_format,
select_suggests_fn=self._set_selected_suggestions,
tokenizer=self.tg.tokenizer
)
def add_lexicon(self, name, values, overwrite=False, append=False, remove_duplicates=False):
"""Add tag to lexicon
Parameters
----------
name : str
Tag name.
values : list(str)
Tag values.
overwrite : bool
If True, replaces tag with the same name if it already exists
append : bool
If True, adds values to current lexicon with name
remove_duplicates: bool
If append=True and remove_duplicates=True, remove duplicate values
from lexicon after appending
"""
# words can be strings, dictionarys, and other objects
if overwrite == True and append == True:
raise Exception('Either overwrite or append must be False')
if append == True:
if name not in self.lexicons:
self.lexicons[name] = values
else:
self.lexicons[name].extend(values)
if remove_duplicates == True:
self.lexicons[name] = list(set(self.lexicons[name]))
return
if name in self.lexicons and not overwrite:
raise Exception('%s already in lexicons. Call with overwrite=True to overwrite' % name)
self.lexicons[name] = values
def add_lexicon_from_csv(self, name, path, overwrite=False, append=False, remove_duplicates=False):
"""Add tag to lexicon from csv file
Parameters
----------
name : str
Tag name.
path : str
Path to csv file
overwrite : bool
If True, replaces tag with the same name if it already exists
append : bool
If True, adds values to current lexicon with name
remove_duplicates: bool
If append=True and remove_duplicates=True, remove duplicate values
from lexicon after appending
"""
values = []
col_names = []
with open(path, newline='') as f:
reader = csv.reader(f)
for (i, row) in enumerate(reader):
if i == 0:
for col_name in row:
col_names.append(col_name)
else:
d = {}
if len(row) != len(col_names):
raise Exception(f'Length of row {i} does not match header length ({len(row)} != {len(col_names)})')
for (j, val) in enumerate(row):
d[col_names[j]] = val
values.append(MunchWithAdd(d))
self.add_lexicon(name, values, overwrite=overwrite, append=append, remove_duplicates=remove_duplicates)
def _get_fillin_items(self, all_keys, max_count=None, **kwargs):
items = {}
mask_match = re.compile(r'mask\d*')
for k in kwargs:
if re.search(r'\d+$', k):
raise(Exception('Error: keys cannot end in integers, we use that to index multiple copies of the same key (offending key: "%s")' % k))
for k in all_keys:
# TODO: process if ends in number
# TODO: process if is a:key to add article
k = re.sub(r'\..*', '', k)
k = re.sub(r'\[.*\]', '', k)
k = re.sub(r'.*?:', '', k)
newk = re.sub(r'\d+$', '', k)
if mask_match.match(k):
continue
if newk in kwargs:
items[k] = kwargs[newk]
elif newk in self.lexicons:
items[k] = self.lexicons[newk]
else:
raise(Exception('Error: key "%s" not in items or lexicons' % newk))
if max_count:
items[k] = items[k][:max_count]
return items
def template(self, templates, nsamples=None,
product=True, remove_duplicates=False, mask_only=False,
unroll=False, labels=None, meta=False, save=False, **kwargs):
"""Fills in templates
Parameters
----------
templates : str, list, tuple, or dict
On leaves: templates with {tags}, which will be substituted for mapping in **kwargs
Can have {mask} tags, which will be replaced by a masked language model.
Other tags can be numbered for distinction, e.g. {person} and {person1} will be considered
separate tags, but both will use fill-ins for 'person'
nsamples : int
Number of samples
product : bool
If true, take cartesian product
remove_duplicates : bool
If True, will not generate any strings where two or more fill-in values are duplicates.
mask_only : bool
If True, return only fill-in values for {mask} tokens
unroll : bool
If True, returns list of strings regardless of template type (i.e. unrolls)
labels : int or object with strings on leaves
If int, all generated strings will have the same label. Otherwise, can refer
to tags, or be strings, etc. Output will be in ret.meta
meta : bool
If True, ret.meta will contain a dict of fill in values for each item in ret.data
save : bool
If True, ret.templates will contain all parameters and fill-in lists
**kwargs : type
Must include fill-in lists for every tag not in editor.lexicons
Returns
-------
MunchWithAdd
Returns ret, a glorified dict, which will have the filled in templates in ret.data.
It may contain ret.labels, ret.templates and ret.meta (depending on parameters as noted above)
You can add or += two MunchWithAdd, which will concatenate values
"""
# 1. go through object, find every attribute inside brackets
# 2. check if they are in kwargs and self.attributes
# 3. generate keys and vals
# 4. go through object, generate
params = locals()
ret = MunchWithAdd()
del params['kwargs']
del params['self']
templates = copy.deepcopy(templates)
added_labels = False
if labels is not None and type(labels) != int:
added_labels = True
templates = (templates, labels)
all_keys = find_all_keys(templates)
items = self._get_fillin_items(all_keys, **kwargs)
mask_index, mask_options = get_mask_index(templates)
for mask, strings in mask_index.items():
# ks = {re.sub(r'.*?:', '', a): '{%s}' % a for a in all_keys}
ks = {}
tok = 'VERYLONGTOKENTHATWILLNOTEXISTEVER'
ks[mask] = tok
a_tok = 'thisisaratherlongtokenthatwillnotexist'
# print(mask)
# print('options:', mask_options[mask])
top = 100
find_top = re.search(r't(\d+)', mask_options[mask])
if find_top:
top = int(find_top.group(1))
sub_a = lambda x: re.sub(r'{[^:}]*a[^:}]*:(%s)}' % mask, r'{%s} {\1}' % a_tok, x)
# print(strings)
strings = recursive_apply(strings, sub_a)
ks[a_tok] = '{%s}' % a_tok
# print(strings)
ts = recursive_format(strings, ks, ignore_missing=True)
samp = self.template(ts, nsamples=5, remove_duplicates=remove_duplicates,
thisisaratherlongtokenthatwillnotexist=['a'], **kwargs).data
samp += self.template(ts, nsamples=5, remove_duplicates=remove_duplicates,
thisisaratherlongtokenthatwillnotexist=['an'], **kwargs).data
# print(samp)
# print(len([x for x in samp if ' an ' in x[0]]))
samp = [x.replace(tok, self.tg.tokenizer.mask_token) for y in samp for x in y][:20]
samp = list(set(samp))
# print(samp)
if 'beam_size' not in kwargs:
kwargs['beam_size'] = 100
# beam_size = kwargs.get('beam_size', 100)
# kwargs.
options = self.tg.unmask_multiple(samp, **kwargs)
# print(options)
# print(top)
v = [x[0] for x in options][:top]
items[mask] = v
if mask_only:
return options[:nsamples]
if save:
ret.templates = [(params, items)]
templates = recursive_apply(templates, replace_mask)
# print(templates)
keys = [x[0] for x in items.items()]
vals = [[x[1]] if type(x[1]) not in [list, tuple] else x[1] for x in items.items()]
if nsamples is not None:
# v = [np.random.choice(x, nsamples) for x in vals]
v = [wrapped_random_choice(x, nsamples) for x in vals]
if not v:
vals = [[]]
else:
vals = zip(*v)
# print(list(vals))
else:
if not product:
vals = zip(*vals)
else:
vals = itertools.product(*vals)
data = []
use_meta = meta
meta = []
for v in vals:
# print(v)
if remove_duplicates and len(v) != len(set([str(x) for x in v])):
continue
mapping = dict(zip(keys, v))
# print(templates)
# print(mapping)
data.append(recursive_format(templates, mapping))
meta.append(mapping)
if unroll and data and type(data[0]) in [list, np.array, np.ndarray, tuple]:
meta = [z for y, z in zip(data, meta) for x in y]
data = [x for y in data for x in y]
if use_meta:
ret.meta = meta
if added_labels:
data, labels = map(list, zip(*data))
ret.labels = labels
if labels is not None and type(labels) == int:
ret.labels = [labels for _ in range(len(data))]
ret.data = data
return ret
| 29,139 | 37.041775 | 150 | py |
checklist | checklist-master/checklist/expect.py | import numpy as np
import itertools
def iter_with_optional(data, preds, confs, labels, meta, idxs=None):
# If this is a single example
if type(data) not in [list, np.array, np.ndarray]:
return [(data, preds, confs, labels, meta)]
if type(meta) not in [list, np.array, np.ndarray]:
meta = itertools.repeat(meta)
else:
if len(meta) != len(data):
raise(Exception('If meta is list, length must match data'))
if type(labels) not in [list, np.array, np.ndarray]:
labels = itertools.repeat(labels)
else:
if len(labels) != len(data):
raise(Exception('If labels is list, length must match data'))
ret = zip(data, preds, confs, labels, meta)
if idxs is not None:
ret = list(ret)
ret = [ret[i] for i in idxs]
return ret
class Expect:
"""Helpers for writing expectation functions over tests.
Each test has a list of testcases, and each testcase has a list of examples.
Expectation function will act on whole tests, testcases, individual examples, or pairs of examples.
In any of these, the output of an expectation function for a single example
is an integer, float, bool, or None, where:
> 0 (or True) means passed,
<= 0 or False means fail, and (optionally) the magnitude of the
failure, indicated by distance from 0, e.g. -10 is worse than -1
None means the test does not apply, and this should not be counted
"""
@staticmethod
def test(fn):
"""Expectation over a whole test
Parameters
----------
fn : function
Arguments: (data, preds, confs, labels=None, meta=None), all of
which are potentially lists of lists
Returns: list of np.arrays, representing results for
examples inside a testcase. See docstring for the Expect class
for what different values in the output mean.
Returns
-------
function
Arguments: AbstractTest
Returns: List of np.arrays
"""
def expect(self):
return fn(self.data, self.results.preds, self.results.confs, self.labels, self.meta, self.run_idxs)
return expect
@staticmethod
def testcase(fn):
"""Expectation over a single testcase (may have multiple examples)
Parameters
----------
fn : function
Arguments: (xs, preds, confs, labels=None, meta=None)
Returns: np.array, representing results for the examples inside the
testcase. See docstring for the Expect class for what different
values in the output mean.
Returns
-------
function
Arguments: AbstractTest
Returns: List of np.arrays
"""
def expect(self):
zipped = iter_with_optional(self.data, self.results.preds, self.results.confs, self.labels, self.meta, self.run_idxs)
return [fn(x, pred, confs, labels, meta) for x, pred, confs, labels, meta in zipped]
return expect
@staticmethod
def single(fn):
"""Expectation over a single example
Parameters
----------
fn : function
Arguments: (x, pred, conf, label=None, meta=None)
Returns: bool, float, or int. See docstring for the Expect class
for what different values in the output mean.
Returns
-------
function
Arguments: AbstractTest
Returns: List of np.arrays
"""
def expect_fn(xs, preds, confs, label=None, meta=None):
return np.array([fn(x, p, c, l, m) for x, p, c, l, m in iter_with_optional(xs, preds, confs, label, meta)])
return Expect.testcase(expect_fn)#, agg_fn)
@staticmethod
def pairwise(fn):
"""Expectation over pairs of examples, suitable for perturbation tests
Parameters
----------
fn : function
Arguments: (orig_pred, pred, orig_conf, conf, labels=None, meta=None)
Orig_pred and orig_conf are the prediction and the confidence
of the first example in the test case
Returns: bool, float, or int. See docstring for the Expect class
for what different values in the output mean.
Returns
-------
function
Arguments: AbstractTest
Returns: List of np.arrays
"""
def expect_fn(xs, preds, confs, labels=None, meta=None):
orig_pred = preds[0]
orig_conf = confs[0]
return np.array([fn(orig_pred, p, orig_conf, c, l, m) for _, p, c, l, m in iter_with_optional(xs, preds, confs, labels, meta)] )
return Expect.testcase(expect_fn)
@staticmethod
def aggregate(data, agg_fn='all'):
"""aggregates expectation results for all examples in each test case
Parameters
----------
data : type
list of np.arrays
agg_fn : function or string in 'all', 'all_except_first'
Arguments: np.array
Returns: bool, float, or int. See docstring for the Expect class
for what different values in the output mean.
Returns
-------
np.array
Of bool, float, or int. See docstring for the Expect class
for what different values in the output mean.
"""
# data is a list of lists or list of np.arrays
return np.array([Expect.aggregate_testcase(x, agg_fn) for x in data])
@staticmethod
def aggregate_testcase(expect_results, agg_fn='all'):
"""See docstring for aggregate"""
if agg_fn == 'all':
agg_fn = Expect.all()
if agg_fn == 'all_except_first':
agg_fn = Expect.all(ignore_first=True)
if expect_results is None:
return None
r = [x for x in expect_results if x is not None]
if not r:
return None
else:
return agg_fn(np.array(r))
@staticmethod
def all(ignore_first=False):
"""Aggregate such that all have to be True
See docstring for "aggregate", this is an aggregation function
Parameters
----------
ignore_first : bool
If True, do not require first example to be True (useful for perturbation tests)
Returns
-------
function
aggregation function
"""
def tmp_fn(results):
if ignore_first:
results = results[1:]
return np.all(results > 0)
return tmp_fn
@staticmethod
def wrap_slice(expect_fn, slice_fn, agg_fn='all'):
"""Wraps an expectation function with a slice function to discard certain testcases.
Parameters
----------
expect_fn : function
an expectation function
slice_fn : function
A slice function, slices testcases.
Arguments: the same as the expectation function
Returns: np.array where True means 'keep' and False means 'discard'
agg_fn : function
Aggregates examples within a test case. See aggregate_testcase
Returns
-------
function
The expect function, but now returning None for discarded examples
"""
def wrapped(*args, **kwargs):
ret = expect_fn(*args, **kwargs)
sliced = Expect.aggregate(slice_fn(*args, **kwargs), agg_fn)
for i in np.where(sliced != True)[0]:
if type(ret[i]) in [list, np.array, np.ndarray]:
ret[i] = [None for _ in ret[i]]
else:
ret[i] = None
return ret
return wrapped
@staticmethod
def slice_testcase(expect_fn, slice_fn, agg_fn='all'):
"""Wraps an expectation function with a slice function to discard certain testcases.
Slice function acts on testcase.
Parameters
----------
expect_fn : function
an expectation function, where argument is a Test
slice_fn : function
A slice function, slices testcases.
Arguments: (xs, preds, confs, labels=None, meta=None)
Returns: np.array where True means 'keep' and False means 'discard'
agg_fn : function
Aggregates examples within a test case. See aggregate_testcase
Returns
-------
function
The expect function, but now returning None for discarded examples
"""
wrapped_slice = Expect.testcase(slice_fn)
return Expect.wrap_slice(expect_fn, wrapped_slice, agg_fn)
@staticmethod
def slice_single(expect_fn, slice_fn, agg_fn='all'):
"""Wraps an expectation function with a slice function to discard certain testcases.
Slice function acts on single examples.
Parameters
----------
expect_fn : function
an expectation function, where argument is a Test
slice_fn : function
A slice function, slices testcases.
Arguments: (x, pred, conf, label=None, meta=None)
Returns: True ('keep') or False ('discard')
agg_fn : function
Aggregates examples within a test case. See aggregate_testcase
Returns
-------
function
The expect function, but now returning None for discarded examples
"""
wrapped_slice = Expect.single(slice_fn)
return Expect.wrap_slice(expect_fn, wrapped_slice, agg_fn)
@staticmethod
def slice_orig(expect_fn, slice_fn, agg_fn='all'):
"""Wraps an expectation function with a slice function to discard certain testcases.
Slice function acts on the original example in a perturbation test.
Parameters
----------
expect_fn : function
an expectation function, where argument is a Test
slice_fn : function
A slice function, slices original examples for perturbation tests.
Arguments: (orig_pred, orig_conf)
Returns: True ('keep') or False ('discard')
agg_fn : function
Aggregates examples within a test case. See aggregate_testcase
Returns
-------
function
The expect function, but now returning None for discarded examples
"""
new_fn = lambda orig, pred, *args, **kwargs: slice_fn(orig, pred)
return Expect.slice_pairwise(expect_fn, new_fn, agg_fn)
@staticmethod
def slice_pairwise(expect_fn, slice_fn, agg_fn='all_except_first'):
"""Wraps an expectation function with a slice function to discard certain testcases.
Slice function acts on pairs.
Parameters
----------
expect_fn : function
an expectation function, where argument is a Test
slice_fn : function
A slice function, slices testcases.
Arguments: (orig_pred, pred, orig_conf, conf, labels=None, meta=None)
Returns: np.array where True means 'keep' and False means 'discard'
agg_fn : function
Aggregates examples within a test case. See aggregate_testcase
Returns
-------
function
The expect function, but now returning None for discarded examples
"""
wrapped_slice = Expect.pairwise(slice_fn)
return Expect.wrap_slice(expect_fn, wrapped_slice, agg_fn)
@staticmethod
def combine(expect_fn1, expect_fn2, combine_fn, ignore_none=True):
"""Creates a wrapper that combines two expectation functions
Parameters
----------
expect_fn1 : function
an expectation function, where argument is a Test
expect_fn2 : function
an expectation function, where argument is a Test
combine_fn : function
Arguments: (x1, x2), the output of (expect_fn1, expect_fn2)
Returns: bool, float, or int. See docstring for the Expect class
for what different values in the output mean.
ignore_none : bool
If True, will take x1 if x2 is None and vice versa. If both are Nones,
will return None without calling combine_fn.
Returns
-------
function
wrapped expectation function
"""
# each expect_fn takes 'self' as input (i.e. wrapped by Expect.test or Expect.testcase)
# combine_fn takes (x1, x2), where each is an output from expect_fn1 or
# 2 (a single example within a testcase, which is a float, a bool, or
# None) and combines them into a float, a bool, or None if
# ignore_none=True, will take one of the inputs if the other is None
# without passing them to the combine_fn (and return None if both are
# Nones. otherwise, combine_fn must handle Nones)
def tmp_fn(self):
e1 = expect_fn1(self)
e2 = expect_fn2(self)
ret = []
for list1, list2 in zip(e1, e2):
r = []
for z1, z2 in zip(list1, list2):
if ignore_none:
if z1 == None:
r.append(z2)
continue
elif z2 == None:
r.append(z1)
continue
r.append(combine_fn(z1, z2))
ret.append(np.array(r))
return ret
return tmp_fn
@staticmethod
def combine_and(expect_fn1, expect_fn2):
"""Combines two expectation functions with the 'and' function
See 'combine' for more details.
"""
def combine_fn(x1, x2):
return min(x1, x2)
return Expect.combine(expect_fn1, expect_fn2, combine_fn)
@staticmethod
def combine_or(expect_fn1, expect_fn2):
"""Combines two expectation functions with the 'or' function
See 'combine' for more details.
"""
def combine_fn(x1, x2):
return max(x1, x2)
return Expect.combine(expect_fn1, expect_fn2, combine_fn)
# SAMPLE EXPECTATION FUNCTION
@staticmethod
def eq(val=None):
"""Expect predictions to be equal to a value.
See documentation for Expect.single
Parameters
----------
val : whatever or None
If None, expect prediction to be equal to label. Otherwise, to be equal to val
Returns
-------
function
an expectation function
"""
def ret_fn(x, pred, conf, label=None, meta=None):
gt = val if val is not None else label
softmax = type(conf) in [np.array, np.ndarray]
conf = conf[gt] if softmax else -conf
conf_viol = -(1 - conf)
if pred == gt:
return True
else:
return conf_viol
return Expect.single(ret_fn)
@staticmethod
def inv(tolerance=0):
"""Expect predictions not to change, with a tolerance threshold
See documentation for Expect.pairwise.
Parameters
----------
tolerance : float
If prediction changes but prediction probability is within the tolerance,
will not consider it a failure.
Returns
-------
function
an expectation function
"""
def expect(orig_pred, pred, orig_conf, conf, labels=None, meta=None):
softmax = type(orig_conf) in [np.array, np.ndarray]
try:
if pred == orig_pred:
return True
except ValueError: # np.array output
if (pred == orig_pred).all():
return True
if softmax:
orig_conf = orig_conf[orig_pred]
conf = conf[orig_pred]
if np.abs(conf - orig_conf) <= tolerance:
return True
else:
return -np.abs(conf - orig_conf)
else:
# This is being generous I think
if conf + orig_conf <= tolerance:
return True
else:
return -(conf + orig_conf)
return Expect.pairwise(expect)
@staticmethod
def monotonic(label=None, increasing=True, tolerance=0.):
"""Expect predictions to be monotonic
See documentation for Expect.pairwise.
Parameters
----------
label : None or integer (only allowed if conf is softmax)
If None, the original prediction label
increasing : bool
Whether we want monotonically increasing or decreasing
tolerance : float
If confidence goes down (up) for monotonically increasing
(decreasing) by less than tolerance, will not be considered a failure.
Returns
-------
function
an expectation function
"""
keep_label = label
def expect(orig_pred, pred, orig_conf, conf, labels=None, meta=None):
label = keep_label
softmax = type(orig_conf) in [np.array, np.ndarray]
if not softmax and label is not None:
raise(Exception('Need prediction function to be softmax for monotonic if you specify label'))
if label is None:
label = orig_pred
if softmax:
orig_conf = orig_conf[label]
conf = conf[label]
conf_diff = conf - orig_conf
else:
if pred == orig_pred:
conf_diff = conf - orig_conf
else:
conf_diff = -(orig_conf + conf)
# can't fail
if increasing and orig_conf <= tolerance:
return None
if not increasing and orig_conf >= 1 - tolerance:
return None
if increasing:
if conf_diff + tolerance >= 0:
return True
else:
return conf_diff + tolerance
# return conf + tolerance >= orig_conf
else:
if conf_diff - tolerance <= 0:
return True
else:
return -(conf_diff - tolerance)
# return conf - tolerance <= orig_conf
return Expect.pairwise(expect)
| 18,549 | 35.089494 | 140 | py |
checklist | checklist-master/checklist/abstract_test.py | from abc import ABC, abstractmethod
import dill
from munch import Munch
import numpy as np
import inspect
from .expect import iter_with_optional, Expect
from .viewer.test_summarizer import TestSummarizer
def load_test(file):
dill._dill._reverse_typemap['ClassType'] = type
with open(file, 'rb') as infile:
return dill.load(infile)
def read_pred_file(path, file_format=None, format_fn=None, ignore_header=False):
f = open(path, 'r', encoding='utf-8')
if ignore_header:
f.readline()
preds = []
confs = []
if file_format is None and format_fn is None:
file_format = 'pred_and_softmax'
if file_format == 'pred_only':
format_fn = lambda x: (x, 1)
elif file_format == 'binary_conf':
def formatz(x):
conf = float(x)
confs = np.array([1 - conf, conf])
pred = int(np.argmax(confs))
return pred, confs
format_fn = formatz
elif file_format == 'softmax':
def formatz(x):
confs = np.array([float(y) for y in x.split()])
pred = int(np.argmax(confs))
return pred, confs
format_fn = formatz
elif file_format == 'pred_and_conf':
def formatz(x):
pred, conf = x.split()
if pred.isdigit():
pred = int(pred)
return pred, float(conf)
format_fn = formatz
elif file_format == 'pred_and_softmax':
def formatz(x):
allz = x.split()
pred = allz[0]
confs = np.array([float(x) for x in allz[1:]])
if pred.isdigit():
pred = int(pred)
return pred, confs
format_fn = formatz
elif file_format is None:
pass
else:
raise(Exception('file_format %s not suported. Accepted values are pred_only, softmax, binary_conf, pred_and_conf, pred_and_softmax' % file_format))
for l in f:
l = l.strip('\n')
p, c = format_fn(l)
preds.append(p)
confs.append(c)
if file_format == 'pred_only' and all([x.isdigit() for x in preds]):
preds = [int(x) for x in preds]
return preds, confs
class AbstractTest(ABC):
def __init__(self, data, expect, labels=None, meta=None, agg_fn='all',
templates=None, print_first=None, name=None, capability=None,
description=None):
self.data = data
self.expect = expect
self.labels = labels
self.meta = meta
self.agg_fn = agg_fn
self.templates = templates
self.print_first = print_first
self.run_idxs = None
self.result_indexes = None
self.name = name
self.capability = capability
self.description = description
def save(self, file):
dill.dump(self, open(file, 'wb'), recurse=True)
@staticmethod
def from_file(file):
return load_test(file)
def _extract_examples_per_testcase(
self, xs, preds, confs, expect_results, labels, meta, nsamples, only_include_fail=True):
iters = list(iter_with_optional(xs, preds, confs, labels, meta))
idxs = [0] if self.print_first else []
idxs = [i for i in np.argsort(expect_results) if not only_include_fail or expect_results[i] <= 0]
if preds is None or (type(preds) == list and len(preds) == 0) or len(idxs) > len(iters):
return None
if self.print_first:
if 0 in idxs:
idxs.remove(0)
idxs.insert(0, 0)
idxs = idxs[:nsamples]
iters = [iters[i] for i in idxs]
return idxs, iters, [expect_results[i] for i in idxs]
def print(self, xs, preds, confs, expect_results, labels=None, meta=None, format_example_fn=None, nsamples=3):
result = self._extract_examples_per_testcase(
xs, preds, confs, expect_results, labels, meta, nsamples, only_include_fail=True)
if not result:
return
idxs, iters, _ = result
for x, pred, conf, label, meta in iters:
print(format_example_fn(x, pred, conf, label, meta))
if type(preds) in [np.array, np.ndarray, list] and len(preds) > 1:
print()
print('----')
def set_expect(self, expect):
"""Sets and updates expectation function
Parameters
----------
expect : function
Expectation function, takes an AbstractTest (self) as parameter
see expect.py for details
"""
self.expect = expect
self.update_expect()
def update_expect(self):
self._check_results()
self.results.expect_results = self.expect(self)
self.results.passed = Expect.aggregate(self.results.expect_results, self.agg_fn)
def example_list_and_indices(self, n=None, seed=None):
"""Subsamples test cases
Parameters
----------
n : int
Number of testcases to sample
seed : int
Seed to use
Returns
-------
tuple(list, list)
First list is a list of examples
Second list maps examples to testcases.
For example, let's say we have two testcases: [a, b, c] and [d, e].
The first list will be [a, b, c, d, e]
the second list will be [0, 0, 0, 1, 1]
Also updates self.run_idxs if n is not None to indicate which testcases
were run. Also updates self.result_indexes with the second list.
"""
if seed is not None:
np.random.seed(seed)
self.run_idxs = None
idxs = list(range(len(self.data)))
if n is not None:
idxs = np.random.choice(idxs, min(n, len(idxs)), replace=False)
self.run_idxs = idxs
if type(self.data[0]) in [list, np.array, np.ndarray]:
all = [(i, y) for i in idxs for y in self.data[i]]
result_indexes, examples = map(list, list(zip(*all)))
else:
examples = [self.data[i] for i in idxs]
result_indexes = idxs# list(range(len(self.data)))
self.result_indexes = result_indexes
return examples, result_indexes
def update_results_from_preds(self, preds, confs):
"""Updates results from preds and confs
Assumes that example_lists_and_indices or to_raw_examples or to_raw_file
was called before, so that self.result_indexes exists
Parameters
----------
preds : list
Predictions
confs : list
Confidences
Updates self.results.preds and self.results.confs
"""
result_indexes = self.result_indexes
if type(self.data[0]) == list:
self.results.preds = [[] for _ in self.data]
self.results.confs = [[] for _ in self.data]
for i, p, c in zip(result_indexes, preds, confs):
self.results.preds[i].append(p)
self.results.confs[i].append(c)
for i in range(len(self.results.preds)):
self.results.preds[i] = np.array(self.results.preds[i])
self.results.confs[i] = np.array(self.results.confs[i])
else:
self.results.preds = [None for _ in self.data]
self.results.confs = [None for _ in self.data]
for i, p, c in zip(result_indexes, preds, confs):
self.results.preds[i] = p
self.results.confs[i] = c
def recover_example_list_and_indices(self):
"""Recovers a previously computed example_list_and_indices"""
idxs = list(range(len(self.data)))
if self.run_idxs is not None:
idxs = self.run_idxs
if type(self.data[0]) in [list, np.array, np.ndarray]:
examples = [y for i in idxs for y in self.data[i]]
else:
examples = [self.data[i] for i in idxs]
result_indexes = self.result_indexes
return examples, result_indexes
def to_raw_examples(self, file_format=None, format_fn=None, n=None, seed=None, new_sample=True):
"""Flattens all test examples into a single list
Parameters
----------
file_format : string, must be one of 'jsonl', 'tsv', or None
None just calls str(x) for each example in self.data
format_fn : function or None
If not None, call this function to format each example in self.data
n : int
If not None, number of samples to draw
seed : int
Seed to use if n is not None
new_sample: bool
If False, will rely on a previous sample and ignore the 'n' and 'seed' parameters
Returns
-------
list(string)
List of all examples. Indices of example to test case will be
stored in self.result_indexes. If n is not None, self.run_idxs will
store the test case indexes.
"""
if file_format == 'jsonl':
import json
format_fn = lambda x: json.dumps(x)
elif file_format == 'tsv':
format_fn = lambda x: '\t'.join(x).replace('\n', ' ')
else:
if format_fn is None:
format_fn = lambda x: str(x).replace('\n', ' ')
if new_sample:
examples, indices = self.example_list_and_indices(n, seed=seed)
else:
examples, indices = self.recover_example_list_and_indices()
examples = [format_fn(x) for x in examples]
return examples
def to_raw_file(self, path, file_format=None, format_fn=str, header=None, n=None, seed=None):
"""Flatten test cases into individual examples and print them to file.
Indices of example to test case will be stored in self.result_indexes.
If n is not None, self.run_idxs will store the test case indexes.
Parameters
----------
path : string
File path
file_format : string, must be one of 'jsonl', 'tsv', or None
None just calls str(x) for each example in self.data
format_fn : function or None
If not None, call this function to format each example in self.data
header : string
If not None, first line of file
n : int
If not None, number of samples to draw
seed : int
Seed to use if n is not None
"""
# file_format can be jsonl, TODO
# format_fn takes an example and outputs a line in the file
ret = ''
if header is not None:
ret += header.strip('\n') + '\n'
examples = self.to_raw_examples(file_format=file_format, format_fn=format_fn, n=n, seed=seed)
ret += '\n'.join(examples)
f = open(path, 'w')
f.write(ret)
f.close()
def _results_exist(self):
return hasattr(self, 'results') and self.results
def _check_results(self):
if not self._results_exist():
raise(Exception('No results. Run run() first'))
def _check_create_results(self, overwrite, check_only=False):
if self._results_exist() and not overwrite:
raise(Exception('Results exist. To overwrite, set overwrite=True'))
if not check_only:
self.results = Munch()
def run_from_preds_confs(self, preds, confs, overwrite=False):
"""Update self.results (run tests) from list of predictions and confidences
Parameters
----------
preds : list
predictions
confs : list
confidences
overwrite : bool
If False, raise exception if results already exist
"""
self._check_create_results(overwrite)
self.update_results_from_preds(preds, confs)
self.update_expect()
def run_from_file(self, path, file_format=None, format_fn=None, ignore_header=False, overwrite=False):
"""Update self.results (run tests) from a prediction file
Parameters
----------
path : string
prediction file path
file_format : string
None, or one of 'pred_only', 'softmax', binary_conf', 'pred_and_conf', 'pred_and_softmax', 'squad',
pred_only: each line has a prediction
softmax: each line has prediction probabilities separated by spaces
binary_conf: each line has the prediction probability of class 1 (binary)
pred_and_conf: each line has a prediction and a confidence value, separated by a space
pred_and_softmax: each line has a prediction and all softmax probabilities, separated by a space
squad: TODO
format_fn : function
If not None, function that reads a line in the input file and outputs a tuple of (prediction, confidence)
ignore_header : bool
If True, skip first line in the file
overwrite : bool
If False, raise exception if results already exist
"""
# file_format can be 'pred_only' (only preds, conf=1), TODO
# Format_fn takes a line in the file and outputs (pred, conf)
# Checking just to avoid reading the file in vain
self._check_create_results(overwrite, check_only=True)
preds, confs = read_pred_file(path, file_format=file_format,
format_fn=format_fn,
ignore_header=ignore_header)
self.run_from_preds_confs(preds, confs, overwrite=overwrite)
def run(self, predict_and_confidence_fn, overwrite=False, verbose=True, n=None, seed=None):
"""Runs test
Parameters
----------
predict_and_confidence_fn : function
Takes as input a list of examples
Outputs a tuple (predictions, confidences)
overwrite : bool
If False, raise exception if results already exist
verbose : bool
If True, print extra information
n : int
If not None, number of samples to draw
seed : int
Seed to use if n is not None
"""
# Checking just to avoid predicting in vain, will be created in run_from_preds_confs
self._check_create_results(overwrite, check_only=True)
examples, result_indexes = self.example_list_and_indices(n, seed=seed)
if verbose:
print('Predicting %d examples' % len(examples))
preds, confs = predict_and_confidence_fn(examples)
self.run_from_preds_confs(preds, confs, overwrite=overwrite)
def fail_idxs(self):
self._check_results()
return np.where(self.results.passed == False)[0]
def filtered_idxs(self):
self._check_results()
return np.where(self.results.passed == None)[0]
def get_stats(self):
stats = Munch()
self._check_results()
n_run = n = len(self.data)
if self.run_idxs is not None:
n_run = len(self.run_idxs)
fails = self.fail_idxs().shape[0]
filtered = self.filtered_idxs().shape[0]
nonfiltered = n_run - filtered
stats.testcases = n
if n_run != n:
stats.testcases_run = n_run
if filtered:
stats.after_filtering = nonfiltered
stats.after_filtering_rate = 100 * nonfiltered / n_run
if nonfiltered != 0:
stats.fails = fails
stats.fail_rate = 100 * fails / nonfiltered
return stats
def print_stats(self):
stats = self.get_stats()
print('Test cases: %d' % stats.testcases)
if 'testcases_run' in stats:
print('Test cases run: %d' % stats.testcases_run)
if 'after_filtering' in stats:
print('After filtering: %d (%.1f%%)' % (stats.after_filtering, stats.after_filtering_rate))
if 'fails' in stats:
print('Fails (rate): %d (%.1f%%)' % (stats.fails, stats.fail_rate))
def _label_meta(self, i):
if self.labels is None:
label = None
else:
label = self.labels if type(self.labels) not in [list, np.array, np.ndarray] else self.labels[i]
if self.meta is None:
meta = None
else:
meta = self.meta if type(self.meta) not in [list, np.array, np.ndarray] else self.meta[i]
return label, meta
def summary(self, n=3, print_fn=None, format_example_fn=None, n_per_testcase=3):
"""Print stats and example failures
Parameters
----------
n : int
number of example failures to show
print_fn : function
If not None, use this to print a failed test case.
Arguments: (xs, preds, confs, expect_results, labels=None, meta=None)
format_example_fn : function
If not None, use this to print a failed example within a test case
Arguments: (x, pred, conf, label=None, meta=None)
n_per_testcase : int
Maximum number of examples to show for each test case
"""
self.print_stats()
if not n:
return
if print_fn is None:
print_fn = self.print
def default_format_example(x, pred, conf, *args, **kwargs):
softmax = type(conf) in [np.array, np.ndarray]
binary = False
if softmax:
if conf.shape[0] == 2:
conf = conf[1]
return '%.1f %s' % (conf, str(x))
elif conf.shape[0] <= 4:
confs = ' '.join(['%.1f' % c for c in conf])
return '%s %s' % (confs, str(x))
else:
conf = conf[pred]
return '%s (%.1f) %s' % (pred, conf, str(x))
else:
return '%s %s' % (pred, str(x))
if format_example_fn is None:
format_example_fn = default_format_example
fails = self.fail_idxs()
if fails.shape[0] == 0:
return
print()
print('Example fails:')
fails = np.random.choice(fails, min(fails.shape[0], n), replace=False)
for f in fails:
d_idx = f if self.run_idxs is None else self.run_idxs[f]
# should be format_fn
label, meta = self._label_meta(d_idx)
# print(label, meta)
print_fn(self.data[d_idx], self.results.preds[d_idx],
self.results.confs[d_idx], self.results.expect_results[f],
label, meta, format_example_fn, nsamples=n_per_testcase)
def _form_examples_per_testcase_for_viz(
self, xs, preds, confs, expect_results, labels=None, meta=None, nsamples=3):
result = self._extract_examples_per_testcase(
xs, preds, confs, expect_results, labels, meta, nsamples, only_include_fail=False)
if not result:
return []
idxs, iters, expect_results_sample = result
if not iters:
return []
start_idx = 1 if self.print_first else 0
if self.print_first:
base = iters[0]
try:
conf = base[2][base[1]]
except:
conf = None
old_example = {"text": base[0], "pred": str(base[1]), "conf": conf}
else:
old_example = None
examples = []
for idx, e in enumerate(iters[start_idx:]):
try:
conf = e[2][e[1]]
except:
conf = None
example = {
"new": {"text": e[0], "pred": str(e[1]), "conf": conf},
"old": old_example,
"label": e[3],
"succeed": int(expect_results_sample[start_idx:][idx] > 0)
}
examples.append(example)
return examples
def form_test_info(self, name=None, description=None, capability=None):
n_run = n = len(self.data)
if self.run_idxs is not None:
n_run = len(self.run_idxs)
fails = self.fail_idxs().shape[0]
filtered = self.filtered_idxs().shape[0]
return {
"name": name if name else self.name,
"description": description if description else self.description,
"capability": capability if capability else self.capability,
"type": self.__class__.__name__.lower(),
"tags": [],
"stats": {
"nfailed": fails,
"npassed": n_run - filtered - fails,
"nfiltered": filtered
}
}
def form_testcases(self, n_per_testcase=3):
self._check_results()
testcases = []
nonfiltered_idxs = np.where(self.results.passed != None)[0]
for f in nonfiltered_idxs:
d_idx = f if self.run_idxs is None else self.run_idxs[f]
# should be format_fn
label, meta = self._label_meta(d_idx)
# print(label, meta)
succeed = self.results.passed[f]
if succeed is not None:
examples = self._form_examples_per_testcase_for_viz(
self.data[d_idx], self.results.preds[d_idx],
self.results.confs[d_idx], self.results.expect_results[f],
label, meta, nsamples=n_per_testcase)
else:
examples = []
if examples:
testcases.append({
"examples": examples,
"succeed": int(succeed),
"tags": []
})
return testcases
def visual_summary(self, name=None, description=None, capability=None, n_per_testcase=3):
self._check_results()
# get the test meta
test_info = self.form_test_info(name, description, capability)
testcases = self.form_testcases(n_per_testcase)
return TestSummarizer(test_info, testcases)
| 21,832 | 37.848754 | 155 | py |
checklist | checklist-master/checklist/multilingual.py | import collections
from iso639 import languages
def get_language_code(language):
to_try = [languages.name, languages.inverted, languages.part1]
l_to_try = [language.capitalize(), language.lower()]
for l in l_to_try:
for t in to_try:
if l in t:
if not t[l].part1:
continue
return t[l].part1
raise Exception('Language %s not recognized. Try the iso-639 code.' % language)
def multilingual_params(language, **kwargs):
language_code = get_language_code(language)
lang_model = collections.defaultdict(lambda: 'xlm-roberta-large')
lang_model['fr'] = 'flaubert/flaubert_base_cased'
lang_model['en'] = 'roberta-base'
lang_model['de'] = 'bert-base-german-cased'
prefixes = {
'af': 'Hierdie teks is in Afrikaans geskryf. ',
'sq': 'Ky tekst është shkruar në shqip. ',
'am': 'ይህ ጽሑፍ በአማርኛ ተጽ writtenል ፡፡ ',
'ar': 'هذا النص مكتوب بالعربية. ',
'hy': 'Այս տեքստը գրված է հայերեն: ',
'az': 'Bu mətn Azərbaycan dilində yazılmışdır. ',
'eu': 'Testu hau euskaraz idatzita dago. ',
'be': 'Гэты тэкст напісаны па-беларуску. ',
'bn': 'এই লেখাটি বাংলা ভাষায় রচিত;। ',
'bs': 'Ovaj tekst je napisan na bosanskom jeziku. ',
'br': 'Ce texte est écrit en breton. ',
'bg': 'Този текст е написан на български език. ',
'my': 'ဒီစာသားကိုဗမာလိုရေးထားတယ်။ ',
'ca': 'Aquest text està escrit en català ;. ',
'zh': '这段文字是用中文写的。',
'hr': 'Ovaj tekst je napisan na hrvatskom jeziku. ',
'cs': 'Tento text je psán česky. ',
'da': 'Denne tekst er skrevet på dansk. ',
'nl': 'Deze tekst is geschreven in het Nederlands ;. ',
'eo': 'This text is written in Esperanto. ',
'et': 'See tekst on kirjutatud eesti keeles. ',
'fi': 'Tämä teksti on kirjoitettu suomeksi. ',
'gl': 'Este texto está escrito en galego. ',
'ka': 'ეს ტექსტი ქართულად არის დაწერილი. ',
'el': 'Αυτό το κείμενο είναι γραμμένο στα Ελληνικά. ',
'gu': 'આ લખાણ ગુજરાતીમાં લખાયેલ છે. ',
'ha': 'An rubuta wannan rubutun cikin harshen Hausa. ',
'he': 'טקסט זה כתוב בעברית. ',
'hi': 'यह पाठ हिंदी में लिखा गया है। ',
'hu': 'Ez a szöveg magyarul készült. ',
'is': 'Þessi texti er skrifaður á íslensku. ',
'id': 'Teks ini ditulis dalam bahasa Indonesia. ',
'ga': 'Tá an téacs seo scríofa i nGaeilge. ',
'it': 'Questo testo è scritto in italiano. ',
'ja': 'このテキストは日本語で書かれています。 ',
'jv': 'Naskah iki ditulis nganggo basa jawa. ',
'kn': 'ಈ ಪಠ್ಯವನ್ನು ಕನ್ನಡದಲ್ಲಿ ಬರೆಯಲಾಗಿದೆ. ',
'kk': 'Бұл мәтін қазақ тілінде жазылған. ',
'km': 'អត្ថបទនេះត្រូវបានសរសេរនៅកណ្តាល។ ',
'ko': '이 텍스트는 한국어로 작성되었습니다. ',
'ku': 'Bu metin Kürtçe yazılmıştır. ',
'ky': 'Бул текст кыргыз тилинде жазылган;. ',
'lo': 'ບົດຂຽນນີ້ຂຽນເປັນພາສາລາວ. ',
'la': 'Questo testo è scritto in latino. ',
'lv': 'Šis teksts ir uzrakstīts latviešu valodā. ',
'lt': 'Šis tekstas parašytas lietuvių kalba. ',
'mk': 'Овој текст е напишан на македонски јазик. ',
'mg': 'Ity soratra ity dia voasoratra amin\'ny teny malagasy. ',
'ms': 'Teks ini ditulis dalam bahasa Melayu. ',
'ml': 'ഈ വാചകം മലയാളത്തിലാണ് എഴുതിയിരിക്കുന്നത്. ',
'mr': 'हा मजकूर मराठीत लिहिला आहे;. ',
'mn': 'Энэ текстийг монгол хэлээр бичсэн болно. ',
'ne': 'यो लेख नेपालीमा लेखिएको छ। ',
'no': 'Denne teksten er skrevet på norsk. ',
'ps': 'دا متن په پښتو ژبه لیکل شوی.. ',
'fa': 'این متن به زبان فارسی نوشته شده است ؛. ',
'pl': 'Ten tekst jest napisany w języku polskim. ',
'pt': 'Este texto está escrito em português. ',
'pa': 'ਇਹ ਪਾਠ ਪੰਜਾਬ ਵਿਚ ਲਿਖਿਆ ਗਿਆ ਹੈ;. ',
'ro': 'Acest text este scris în limba română ;. ',
'ru': 'Этот текст написан на русском языке. ',
'gd': 'Tha an teacsa seo sgrìobhte ann an Gàidhlig ;. ',
'sr': 'Овај текст је написан на српском. ',
'sd': 'اهو متن سنڌي ۾ لکيو وڃي ٿو. ',
'si': 'මෙම පා text ය සිංහල භාෂාවෙන් ලියා ඇත. ',
'sk': 'Tento text je v slovenskom jazyku. ',
'sl': 'To besedilo je napisano v slovenščini;. ',
'so': 'Qoraalkan wuxuu ku qoran yahay Afsoomaali. ',
'es': 'Este texto está escrito en español. ',
'su': 'Téks ieu ditulis dina basa Sunda. ',
'sw': 'Maandishi haya yameandikwa kwa kiswahili. ',
'sv': 'Denna text är skriven på svenska. ',
'ta': 'இந்த உரை தமிழில் எழுதப்பட்டுள்ளது. ',
'te': 'ఈ వచనం తెలుగులో వ్రాయబడింది. ',
'th': 'ข้อความนี้เขียนเป็นภาษาไทย ',
'tr': 'Bu metin Türkçe yazılmıştır. ',
'uk': 'Цей текст написаний українською мовою. ',
'ur': 'یہ عبارت اردو میں لکھی گئی ہے۔ ',
'ug': 'This text is written in Uighur;. ',
'uz': 'Ushbu matn o\'zbek tilida yozilgan. ',
'vi': 'Văn bản này được viết bằng tiếng Việt. ',
'cy': 'Mae\'r testun hwn wedi\'i ysgrifennu yn Gymraeg. ',
'xh': 'Lo mbhalo ubhalwe ngesiXhosa. ',
'yi': 'דער טעקסט איז געשריבן אויף ייִדיש. ',
}
params = {
'model_name': lang_model[language_code],
'prefix_sentence': prefixes.get(language_code, ''),
'allow_word_pieces': True if language_code in ['zh', 'ja', 'ko'] else False
}
if language_code not in prefixes and language_code not in ['fr', 'en', 'de']:
raise Exception('Language %s not supported yet. Sorry!' % language)
params.update(**kwargs)
return params
| 5,646 | 48.104348 | 83 | py |
checklist | checklist-master/checklist/pred_wrapper.py | import numpy as np
class PredictorWrapper:
@staticmethod
def wrap_softmax(softmax_fn):
"""Wraps softmax such that it outputs predictions and confidences
Parameters
----------
softmax_fn : fn
Takes lists of inputs, outputs softmax probabilities (2d np.array)
Returns
-------
function
wrapped prediction function, returns (preds, confs) instead of softmax
"""
def pred_and_conf(inputs):
confs = softmax_fn(inputs)
preds = np.argmax(confs, axis=1)
return preds, confs
pred_and_conf.conf = 'softmax'
return pred_and_conf
@staticmethod
def wrap_predict(predict_fn):
"""Wraps prediction functions to output predictions and a confidence score of 1
Parameters
----------
predict_fn : function
Outputs a list of predictions given inputs (strings, integers, whatever)
Returns
-------
function
wrapped prediction function, returns (preds, confs) such that confs is list of float(1)
"""
def pred_and_conf(inputs):
preds = predict_fn(inputs)
confs = np.ones(len(preds))
return preds, confs
return pred_and_conf
| 1,310 | 27.5 | 99 | py |
checklist | checklist-master/checklist/__init__.py | 0 | 0 | 0 | py |
|
checklist | checklist-master/checklist/text_generation.py | from transformers import AutoTokenizer, AutoModelForMaskedLM
import collections
import itertools
import numpy as np
import re
from transformers import GPT2Config
from transformers import GPT2LMHeadModel, GPT2Tokenizer
from tqdm.auto import tqdm
import torch
import torch.nn.functional as F
from pattern.en import wordnet, pluralize
import requests
import json
def all_synsets(word, pos=None):
map = {
'NOUN': wordnet.NOUN,
'VERB': wordnet.VERB,
'ADJ': wordnet.ADJECTIVE,
'ADV': wordnet.ADVERB
}
if pos is None:
pos_list = [wordnet.VERB, wordnet.ADJECTIVE, wordnet.NOUN, wordnet.ADVERB]
else:
pos_list = [map[pos]]
ret = []
for pos in pos_list:
ret.extend(wordnet.synsets(word, pos=pos))
return ret
def clean_senses(synsets):
return [x for x in set(synsets) if '_' not in x]
def all_possible_synonyms(word, pos=None):
ret = []
for syn in all_synsets(word, pos=pos):
# if syn.synonyms[0] != word:
# continue
ret.extend(syn.senses)
return clean_senses(ret)
def all_possible_antonyms(word, pos=None):
ret = []
for syn in all_synsets(word, pos=pos):
if not syn.antonym:
continue
for s in syn.antonym:
ret.extend(s.senses)
return clean_senses(ret)
def all_possible_hypernyms(word, pos=None, depth=None):
ret = []
for syn in all_synsets(word, pos=pos):
ret.extend([y for x in syn.hypernyms(recursive=True, depth=depth) for y in x.senses])
return clean_senses(ret)
def all_possible_hyponyms(word, pos=None, depth=None):
ret = []
for syn in all_synsets(word, pos=pos):
ret.extend([y for x in syn.hyponyms(recursive=True, depth=depth) for y in x.senses])
return clean_senses(ret)
def all_possible_related(words, pos=None, depth=1):
all_syns = [y for word in words for y in all_synsets(word, pos=pos)]
# all_syns = [all_synsets(x, pos=pos) for x in words]
# all_syns = [x[0] for x in all_syns if x]
# return all_syns
# print(all_syns)
all_ancestors = [wordnet.ancestor(s1, s2) for s1, s2 in itertools.combinations(all_syns, 2)]
all_ancestors = [x for x in all_ancestors if x]
# print(all_ancestors)
mapz = {x.lexname: x for x in all_ancestors}
all_ancestors = list(mapz.values())
all_descendents = [y for x in all_ancestors for y in x.hyponyms(recursive=True, depth=depth)]
ret = [y for x in all_descendents for y in x.senses]
return clean_senses(ret)
class TextGenerator(object):
def __init__(self, url=None, model_name='roberta-base', prefix_sentence='', allow_word_pieces=False, **kwargs):
self.url = url
if url is None:
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# self.tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
# self.model = BertForMaskedLM.from_pretrained('bert-base-cased')
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForMaskedLM.from_pretrained(model_name)
self.model.to(self.device)
self.model.eval()
self.prefix_sentence = prefix_sentence
self.prefix_len = len(self.tokenizer.encode(prefix_sentence, add_special_tokens=False))
self.allow_word_pieces = allow_word_pieces
tmp = self.tokenizer.tokenize(' a')[0].split('a')
assert len(tmp) == 2
assert tmp[1] == ''
self.space_prefix = tmp[0]
if not self.allow_word_pieces:
self.with_space = torch.tensor(np.array(list(set([i for x, i in self.tokenizer.get_vocab().items() if x.startswith(self.space_prefix)]))), device=self.device);
self.with_space_set = set(self.with_space.cpu().numpy())
self.special_chars = set([i for x, i in self.tokenizer.get_vocab().items() if not x.strip(self.space_prefix).isalnum()])
def unmask_multiple(self, texts, beam_size=500, candidates=None, metric='avg', **kwargs):
rets = []
for text in texts:
rets.append(self.unmask(text, beam_size, candidates))
scores = collections.defaultdict(lambda: 0.) if metric == 'avg' else collections.defaultdict(lambda: 999999999)
count = collections.defaultdict(lambda: 0.)
examples = {}
longest = max([len(x[0][0]) for x in rets])
rets = sorted(rets, key=lambda x:len(x[0][0]), reverse=True)
for r in rets:
for x in r:
tup = tuple(x[0])
if len(tup) != longest:
tups = [k for k in scores if tuple(k[:len(tup)]) == tup]
else:
tups = [tup]
for tup in tups:
count[tup] += 1
examples[tup] = x[1]
if metric == 'avg':
scores[tup] += x[-1]
elif metric == 'min':
scores[tup] = min(scores[tup], x[-1])
if metric == 'min':
for x in count:
# print(x, count[x])
if count[x] != len(texts):
scores[x] = -999999
else:
for x in scores:
scores[x] = scores[x] / len(texts)
scores = sorted(scores.items(), key=lambda x:x[1], reverse=True)
return [(list(x[0]), examples[x[0]], x[1]) for x in scores]
def unmask(self, text_with_mask, beam_size=10, candidates=None):
if self.url is not None:
params = {'text': text_with_mask, 'beam_size': beam_size, 'candidates': candidates}
r = requests.post(url='%s/unmask' % self.url, data={'params': json.dumps(params)})
r = [tuple(x) for x in json.loads(r.text)]
return r
tokenizer = self.tokenizer
model = self.model
encoded = np.array(tokenizer.encode(self.prefix_sentence + text_with_mask, add_special_tokens=True))
cands = []
if candidates is not None:
candidates = candidates + [self.space_prefix + x for x in candidates]
cands = tokenizer.convert_tokens_to_ids(candidates)
if self.allow_word_pieces:
cands_with_space = list(set(cands))
else:
cands_with_space = list(set(cands).intersection(self.with_space_set))
if not len(cands_with_space):
return []
input_ids = torch.tensor(encoded)
# toks = tokenizer.tokenize('[CLS] %s [SEP]' % string)
current_beam= [([], 0)]
masked = (input_ids == self.tokenizer.mask_token_id).numpy().nonzero()[0]
# print(masked)
while len(current_beam[0][0]) != masked.shape[0]:
current_beam = current_beam[:beam_size]
size = len(current_beam[0][0])
to_pred = []
new_beam = []
for i, current in enumerate(current_beam):
idxs = current[0]
c = encoded.copy()
c[masked[:len(idxs)]] = idxs
to_pred.append(c)
# print('ae')
# print('\n'.join([tokenizer.decode(x) for x in to_pred]))
# print()
to_pred = torch.tensor(to_pred, device=self.device).to(torch.int64)
with torch.no_grad():
outputs = model(to_pred)[0]
for i, current in enumerate(current_beam):
prev = int(to_pred[i][masked[size] - 1])
forbid = False
# allow tokens that don't start with space if previous is not alphanumeric
if not self.allow_word_pieces and prev not in self.special_chars:
forbid = True
# print('Forbid Prev, current', prev, tokenizer.decode(to_pred[i][masked[size] - 1:masked[size]+1]))
if candidates is not None:
cands_to_use = cands_with_space if forbid else cands
scores = [outputs[i, masked[size], j] for j in cands_to_use]
new = [(current[0] + [int(x[0])], float(x[1]) + current[1]) for x in zip(cands_to_use, scores)]
else:
if forbid:
v, top_preds = torch.topk(outputs[i, masked[size], self.with_space.to(torch.int64)], beam_size + 10)
top_preds = self.with_space[top_preds]
else:
v, top_preds = torch.topk(outputs[i, masked[size]], beam_size + 10)
new = [(current[0] + [int(x[0])], float(x[1]) + current[1]) for x in zip(top_preds, v)]
new_beam.extend(new)
current_beam = sorted(new_beam, key=lambda x:x[1], reverse=True)
ret = []
ret_text = []
cop = encoded.copy()
for idxs, score in current_beam:
# words = tokenizer.convert_ids_to_tokens(idxs)
words = [str(tokenizer.decode([i])).strip() for i in idxs]
cop[masked] = idxs
text = tokenizer.decode(cop[1 + self.prefix_len:-1])
ret.append((words, text, score / masked.shape[0]))
ret = sorted(ret, key=lambda x:x[2], reverse=True)
return ret
def fill_in_between(self, pieces, beam_size=10, candidates=None):
text = ''
for p in pieces[:-1]:
text += p
text += ' ' + self.tokenizer.mask_token
if p != '':
text += ' '
text += pieces[-1]
if pieces[-1] == '':
text = text.rstrip()
return self.unmask(text, beam_size=beam_size, candidates=candidates)
def replace_word(self, text, word, threshold=5, beam_size=100, candidates=None):
masked = re.sub(r'\b%s\b' % re.escape(word), self.tokenizer.mask_token, text)
if masked == text:
return []
if candidates is not None:
candidates = [word] + candidates
ret = self.unmask(masked, beam_size=beam_size, candidates=candidates)
non_word = [x for x in ret if np.all([y not in [self.tokenizer.unk_token, word] for y in x[0]])]
score = [x for x in ret if np.all([y in [word, self.tokenizer.unk_token] for y in x[0]])]
if not score:
score = 0
else:
score = score[0][-1]
escaped = re.escape(word)
# new_ret = [(x[0], x[1], score - x[2]) for x in non_word if score - x[2] < threshold]
try:
new_ret = [(x[0], re.sub(r'\b%s\b' % escaped, x[0][0], text), score - x[2]) for x in non_word if score - x[2] < threshold]
except:
new_ret = [(x[0], x[1], score - x[2]) for x in non_word if score - x[2] < threshold]
return new_ret
def more_general(self, texts, word, threshold=5, pos=None, **kwargs):
options = all_possible_hypernyms(word, pos=pos)
# print(options)
return self.filter_options(texts, word, options, threshold)
def more_specific(self, texts, word, threshold=5, depth=3, pos=None, **kwargs):
options = all_possible_hyponyms(word, depth=depth, pos=pos)
return self.filter_options(texts, word, options, threshold)
def related_words(self, texts, words, threshold=5, depth=3, pos=None, **kwargs):
if type(words) != list:
words = [words]
if len(words) == 1:
options = all_possible_hypernyms(words[0], pos=pos)
ancestors = [x[0][0] for x in self.filter_options(texts, words[0], options, threshold)]
# print(ancestors)
options = list(set([y for x in ancestors for y in all_possible_hyponyms(x, depth=depth)]))
else:
options = all_possible_related(words, depth=depth)
return self.filter_options(texts, words[0], options, threshold)
def antonyms(self, texts, word, threshold=5, pos=None, **kwargs):
options = all_possible_antonyms(word, pos=pos)
return self.filter_options(texts, word, options, threshold)
def synonyms(self, texts, word, threshold=5, pos=None, **kwargs):
options = all_possible_synonyms(word, pos=pos)
# print(options)
return self.filter_options(texts, word, options, threshold)
def filter_options(self, texts, word, options, threshold=5):
if type(texts) != list:
texts = [texts]
options = options + [word]
in_all = set(options)
orig_ret = []
for text in texts:
masked = re.sub(r'\b%s\b' % re.escape(word), self.tokenizer.mask_token, text)
if masked == text:
continue
ret = self.unmask(masked, beam_size=100, candidates=options)
if not ret:
in_all = in_all.intersection(set())
continue
non_word = [x for x in ret if np.all([y not in [self.tokenizer.unk_token, word] for y in x[0]])]
score = [x for x in ret if np.all([y in [word, self.tokenizer.unk_token] for y in x[0]])]
if score:
score = score[0][-1]
# this will happen when the word is not in the vocabulary, in which case we don't look at the score
else:
score = 0
new_ret = [(x[0], x[1], score - x[2]) for x in non_word if score - x[2] < threshold]
# print(text)
# print(new_ret)
# print()
if text == texts[0]:
orig_ret = new_ret
in_all = in_all.intersection(set([x[0][0] for x in new_ret]))
return [x for x in orig_ret if x[0][0] in in_all]
def antonym(self, text, word, threshold=5, synonym=False):
options = all_possible_antonyms(word)
if synonym:
options = all_possible_synonyms(word)
if not options:
return []
options = options + [word]
masked = re.sub(r'\b%s\b' % re.escape(word), '[MASK]', text)
if masked == text:
return []
ret = self.unmask(masked, beam_size=100000000, candidates=options)
non_word = [x for x in ret if np.all([y not in [self.tokenizer.unk_token, word] for y in x[0]])]
score = [x for x in ret if np.all([y in [word, self.tokenizer.unk_token] for y in x[0]])][0][-1]
new_ret = [(x[0], x[1], score - x[2]) for x in non_word if score - x[2] < threshold]
return new_ret
def try_all_antonyms(self, text, threshold=5, synonym=False):
if self.url is not None:
params = {'text': text }
r = requests.post(url='%s/tokenize' % self.url, data={'params': json.dumps(params)})
words = json.loads(r.text)
else:
words = self.tokenizer.tokenize(text)
new_ret = []
for word in words:
word = word.strip(self.space_prefix)
try:
if synonym:
ret = self.synonyms(text, word, threshold)
else:
ret = self.antonyms(text, word, threshold)
except:
print('Error', word)
print()
continue
new_ret.extend(ret)
return sorted(new_ret, key=lambda x:x[2])
| 15,163 | 44.951515 | 175 | py |
checklist | checklist-master/checklist/viewer/viewer.py | from .template_editor import TemplateEditor
from .test_summarizer import TestSummarizer
from .suite_summarizer import SuiteSummarizer | 133 | 43.666667 | 45 | py |
checklist | checklist-master/checklist/viewer/template_editor.py | import ipywidgets as widgets
from traitlets import Unicode, List, Dict
import os
import typing
import itertools
try:
from IPython.core.display import display, Javascript
except:
raise Exception("This module must be run in IPython.")
DIRECTORY = os.path.abspath(os.path.dirname(__file__))
# import logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__) # pylint: disable=invalid-name
@widgets.register
class TemplateEditor(widgets.DOMWidget):
"""An example widget."""
_view_name = Unicode('TemplateEditorView').tag(sync=True)
_model_name = Unicode('TemplateEditorModel').tag(sync=True)
_view_module = Unicode('viewer').tag(sync=True)
_model_module = Unicode('viewer').tag(sync=True)
_view_module_version = Unicode('^0.1.0').tag(sync=True)
_model_module_version = Unicode('^0.1.0').tag(sync=True)
templates = List([], help="The template list, with tags and masks.").tag(sync=True)
bert_suggests = List([], help="The BERT suggestion list").tag(sync=True)
def __init__(self, \
template_strs: typing.List[str], \
tagged_keys: typing.List[str], \
tag_dict: typing.Dict[str, str], \
mask_suggests: typing.List[typing.Union[str, tuple]], \
format_fn: typing.Callable, \
select_suggests_fn: typing.Callable, \
tokenizer, \
**kwargs):
widgets.DOMWidget.__init__(self, **kwargs)
self.format_fn = format_fn
self.select_suggests_fn = select_suggests_fn
# ONLY do tokenization here
self.tokenizer = tokenizer
self.bert_suggests = mask_suggests
self.templates = [
self.tokenize_template_str(s, tagged_keys, tag_dict) for \
s in template_strs]
self.on_msg(self.handle_events)
def tokenize_template_str(self, template_str, tagged_keys, tag_dict, max_count=5):
tagged_keys = list(tagged_keys)
trans_keys = ["{" + key + "}" for key in tagged_keys]
item_keys = [x[0] for x in tag_dict.items()]
item_vals = [[x[1][:max_count]] if type(x[1]) not in [list, tuple] else x[1][:max_count] for x in tag_dict.items()]
local_items = []
for idx, key in enumerate(tagged_keys):
self.tokenizer.add_tokens(trans_keys[idx])
for item_val in itertools.product(*item_vals):
if len(item_val) != len(set([str(x) for x in item_val])):
continue
local_item = {item_keys[i]: item_val[i] for i, _ in enumerate(item_val)}
local_items.append(local_item)
def _tokenize(text):
tokens = [self.tokenizer.decode(x) for x in self.tokenizer.encode(text, add_special_tokens=False)]
return [t for t in tokens if t]
def get_meta(text):
if text in trans_keys:
idx = trans_keys.index(text)
norm = tagged_keys[idx]
lemma = norm.split(":")[-1]
normalized_key = lemma.split('[')[0].split('.')[0]
texts = list()
for local_item in local_items:
try:
texts.append(self.format_fn(["{" + lemma +"}"], local_item)[0])
except:
pass
return (texts, norm, normalized_key)
else:
return text
template_tokens = [get_meta(t) for t in _tokenize(template_str)]
return template_tokens
def handle_events(self, _, content, buffers):
"""
Event handler. Users trigger python functions through the frontend interaction.
"""
if content.get('event', '') == 'select_suggests':
idxes = content.get("idxes", [])
selected_suggests = [self.bert_suggests[i] for i in idxes]
if self.select_suggests_fn:
self.select_suggests_fn(selected_suggests)
def render(self):
"""
Customized renderer. Directly load the bundled index.
"""
display(Javascript(open(os.path.join(DIRECTORY, 'static', 'index.js')).read()))
| 4,125 | 39.058252 | 123 | py |
checklist | checklist-master/checklist/viewer/fake_data.py | tag_dict = {'pos_adj': 'good', 'air_noun': 'flight', 'intens': 'very'}
raw_templates = [
['It', 'is', ['good', 'a:pos_adj'], ['flight', 'air_noun'], '.'],
['It', ['', 'a:mask'], ['very', 'a:intens'], ['good', 'pos_adj'], ['', 'mask'],'.']
]
suggests = [
['was', 'day'],
['been', 'day'],
['been', 'week'],
['was', 'time'],
['been', 'year'],
['was', 'experience'],
['been', 'weekend'],
['was', 'moment'],
['s', 'day'],
['was', 'game']
]
raw_testcases = [
{
"examples": [{
"new": {
"tokens": [
["Who", "is", "taller", ",", "Mary", "or", "Heather", "?"],
["Who", "is", "taller", ",", "Heather", "or", "Mary", "?"]
],
"pred": "1",
"conf": 0.7
},
"old": None,
"label": "1",
"succeed": 0,
}],
"tags": ["person1=Mary", "person2=Heather", "comparative=taller"],
"succeed": 0,
}, {
"examples": [{
"new": {
"tokens": [
["Who", "is", "taller", ",", "Mary", "or", "Heather", "?"],
["Who", "is", "taller", ",", "Heather", "or", "Mary", "?"]
],
"pred": "1",
"conf": 0.7
},
"old": None,
"label": "1",
"succeed": 1,
}, {
"new": {
"tokens": [
["Who", "is", "cooler", ",", "Mary", "or", "Heather", "?"],
["Who", "is", "cooler", ",", "Heather", "or", "Mary", "?"]
],
"pred": "1",
"conf": 0.7
},
"old": None,
"label": "1",
"succeed": 1,
}],
"tags": ["person1=Mary", "person2=Heather", "comparative=taller", "comparative=cooler"],
"succeed": 1,
}, {
"examples": [{
"new": {
"tokens": [
["Who", "is", "taller", ",", "Mary", "or", "Heather", "?"],
["Who", "is", "taller", ",", "Heather", "or", "Mary", "?"]
],
"pred": "0",
"conf": 0.9
},
"old": {
"tokens": [
["Who", "is", "taller", ",", "Mary", "or", "Heather", "?"],
["Who", "is", "taller", ",", "Mary", "or", "Heather", "?"]
],
"pred": "1",
"conf": 0.7
},
"succeed": 0,
"label": None,
}, {
"new": {
"tokens": [
["Who", "is", "cooler", ",", "Mary", "or", "Heather", "?"],
["Who", "is", "cooler", ",", "Heather", "or", "Mary", "?"]
],
"pred": "1",
"conf": 0.7
},
"old": {
"tokens": [
["Who", "is", "cooler", ",", "Mary", "or", "Heather", "?"],
["Who", "is", "cooler", ",", "Mary", "or", "Heather", "?"]
],
"pred": "0",
"conf": 0.8
},
"label": None,
"succeed": 0,
}],
"succeed": 0,
"tags": ["person1=Mary", "person2=Heather", "comparative=cooler", "comparative=taller"]
}
]
raw_testresult = {
"name": "Change the PERSON order",
"type": "inv",
"expect_meta": {"expected": "equal"},
"tags": [
"person1=Mary",
"person2=Heather",
"person2=Marco",
"comparative=cooler",
"comparative=taller"
],
"stats": {"nfailed": 10, "npassed": 20, "nfiltered": 20}
}
| 3,770 | 29.658537 | 96 | py |
checklist | checklist-master/checklist/viewer/suite_summarizer.py | import ipywidgets as widgets
from traitlets import Unicode, List, Dict
import os
import typing
from spacy.lang.en import English
from copy import deepcopy
try:
from IPython.core.display import display, Javascript
except:
raise Exception("This module must be run in IPython.")
DIRECTORY = os.path.abspath(os.path.dirname(__file__))
from .test_summarizer import TestSummarizer
@widgets.register
class SuiteSummarizer(TestSummarizer):
"""An testcase widget."""
_view_name = Unicode('SuiteSummarizerView').tag(sync=True)
_model_name = Unicode('SuiteSummarizerModel').tag(sync=True)
_view_module = Unicode('viewer').tag(sync=True)
_model_module = Unicode('viewer').tag(sync=True)
_view_module_version = Unicode('^0.1.0').tag(sync=True)
_model_module_version = Unicode('^0.1.0').tag(sync=True)
test_infos = List([]).tag(sync=True)
def __init__(self,
test_infos: typing.Dict,
select_test_fn: typing.Callable, \
**kwargs):
TestSummarizer.__init__(self, test_summary=None, testcases=[], **kwargs)
self.test_infos = test_infos
self.select_test_fn = select_test_fn
self.on_msg(self.handle_events)
def handle_events(self, _, content, buffers):
"""
Event handler. Users trigger python functions through the frontend interaction.
"""
if content.get('event', '') == 'apply_filter':
filter_tags = content.get("filter_tags", [])
is_fail_case = content.get("filter_fail_case", [])
self.search(filter_tags, is_fail_case)
elif content.get('event', '') == 'fetch_example':
self.fetch_example()
elif content.get('event', '') == 'switch_test':
testname = content.get("testname", "")
self.on_select_test(testname)
def on_select_test(self, testname: str) -> None:
if not self.select_test_fn:
summary, testcases = None, []
else:
summary, testcases = self.select_test_fn(testname)
self.reset_summary(summary)
self.reset_testcases(testcases) | 2,105 | 36.607143 | 87 | py |
checklist | checklist-master/checklist/viewer/__init__.py | def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'static',
'dest': 'viewer',
'require': 'viewer/extension'
}]
| 175 | 21 | 37 | py |
checklist | checklist-master/checklist/viewer/test_summarizer.py | import ipywidgets as widgets
from traitlets import Unicode, List, Dict
import os
import typing
from spacy.lang.en import English
from copy import deepcopy
try:
from IPython.core.display import display, Javascript
except:
raise Exception("This module must be run in IPython.")
DIRECTORY = os.path.abspath(os.path.dirname(__file__))
@widgets.register
class TestSummarizer(widgets.DOMWidget):
"""An testcase widget."""
_view_name = Unicode('TestSummarizerView').tag(sync=True)
_model_name = Unicode('TestSummarizerModel').tag(sync=True)
_view_module = Unicode('viewer').tag(sync=True)
_model_module = Unicode('viewer').tag(sync=True)
_view_module_version = Unicode('^0.1.0').tag(sync=True)
_model_module_version = Unicode('^0.1.0').tag(sync=True)
stats = Dict({}).tag(sync=True)
testcases = List([]).tag(sync=True)
summarizer = Dict({}).tag(sync=True)
def __init__(self,
test_summary: typing.Dict,
testcases: typing.List,
**kwargs):
widgets.DOMWidget.__init__(self, **kwargs)
nlp = English()
# ONLY do tokenization here (compatible with spaCy 2.3.x and 3.x.x)
self.tokenizer = nlp.tokenizer
self.max_return = 10
self.reset_summary(test_summary)
self.reset_testcases(testcases)
self.on_msg(self.handle_events)
def reset_summary(self, test_summary=None):
self.summarizer = test_summary if test_summary else {}
def reset_testcases(self, testcases=None):
self.filtered_testcases = testcases if testcases else []
self.tokenize_testcases()
self.search(filter_tags=[], is_fail_case=True)
def handle_events(self, _, content, buffers):
"""
Event handler. Users trigger python functions through the frontend interaction.
"""
if content.get('event', '') == 'apply_filter':
filter_tags = content.get("filter_tags", [])
is_fail_case = content.get("filter_fail_case", [])
self.search(filter_tags, is_fail_case)
elif content.get('event', '') == 'fetch_example':
self.fetch_example()
def tokenize_testcases(self):
for testcase in self.filtered_testcases:
for e in testcase["examples"]:
for tag in ["old", "new"]:
if not e[tag]:
continue
tokens = []
if type(e[tag]["text"]) != list:
e[tag]["tokens"] = [str(e[tag]["text"])]
else:
e[tag]["tokens"] = [str(s) for s in e[tag]["text"]]
for sentence in e[tag]["tokens"]:
tokens.append([t.text for t in self.tokenizer(sentence)])
e[tag]["tokens"] = tokens
def render(self):
"""
Customized renderer. Directly load the bundled index.
"""
display(Javascript(open(os.path.join(DIRECTORY, 'static', 'index.js')).read()))
def compute_stats_result(self, candidate_testcases):
nfailed = len([ e for e in candidate_testcases if e["succeed"] == 0 ])
self.stats = {
"npassed": len(candidate_testcases) - nfailed,
"nfailed": nfailed,
"nfiltered": 0
}
def is_satisfy_filter(self, testcase,
filter_tags: typing.List[str],
is_fail_case: bool) -> bool:
testcase_tags = testcase["tags"]
texts = []
for e in testcase["examples"]:
for tag in ["old", "new"]:
if not e[tag]:
continue
for tokens in e[tag]["tokens"]:
texts += tokens
def raw_text_search(tag, testcase_tags, text):
text_searched = tag in text.lower()
return tag in testcase_tags or text_searched
is_tag_filtered = all([raw_text_search(t, testcase_tags, " ".join(texts)) for t in filter_tags])
is_failured_filtered = not (is_fail_case and testcase["succeed"] == 1)
return is_tag_filtered and is_failured_filtered
def search(self, filter_tags: typing.List[str], is_fail_case: bool):
self.testcases = []
candidate_testcases_not_fail = [
e for e in self.filtered_testcases if \
self.is_satisfy_filter(e, filter_tags, False)
]
self.candidate_testcases = [
e for e in candidate_testcases_not_fail if \
not (is_fail_case and e["succeed"] == 1)
]
self.compute_stats_result(candidate_testcases_not_fail)
self.to_slice_idx = 0
self.fetch_example()
def fetch_example(self):
if self.to_slice_idx >= len(self.candidate_testcases):
self.testcases = []
else:
new_examples = self.candidate_testcases[self.to_slice_idx : self.to_slice_idx+self.max_return]
self.to_slice_idx += len(new_examples)
self.testcases = [e for e in new_examples] | 5,039 | 38.375 | 106 | py |
checklist | checklist-master/checklist/viewer/static/__init__.py | 0 | 0 | 0 | py |
|
checklist | checklist-master/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../..'))
sys.path.insert(0, os.path.abspath('../../checklist'))
autodoc_mock_imports = [
'spacy', 'spacy.cli', 'nltk', 'nltk.corpus', 'nltk.tree', 'pattern',
'numpy', 'np', 'spacy.syntax.nn_parser.array', '__reduce_cython__',
'numpy.dtype', 'spacy.syntax.nn_parser.array.__reduce_cython__', '_ARRAY_API',
'BertForMaskedLM', 'dill', 'munch', 'pattern.en', 'transformers', 'ipywidgets', 'tqdm',
'traitlets', 'torch', 'typing', 'spacy.attrs', 'spacy.lang.en', 'IPython', 'IPython.core.display',
'iso639'
]
# -- Project information -----------------------------------------------------
project = 'checklist'
copyright = '2020, Marco Tulio Ribeiro'
author = 'Marco Tulio Ribeiro'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.coverage',
'sphinx.ext.doctest',
'sphinx.ext.linkcode',
'sphinx.ext.mathjax',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
]
# The master toctree document.
master_doc = 'index'
autodoc_member_order = 'groupwise'
autoclass_content = 'both'
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = False
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = False
napoleon_use_rtype = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', "static"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# make github links resolve
def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
This code is from
https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290
and https://github.com/Lasagne/Lasagne/pull/262
"""
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.split('.'):
try:
obj = getattr(obj, part)
except:
return None
try:
fn = inspect.getsourcefile(obj)
except:
fn = None
if not fn:
return None
try:
source, lineno = inspect.getsourcelines(obj)
except:
lineno = None
if lineno:
linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1)
else:
linespec = ""
filename = info['module'].replace('.', '/')
return "https://github.com/marcotcr/checklist/blob/master/%s.py%s" % (filename, linespec)
| 4,326 | 30.355072 | 102 | py |
CQMaxwell | CQMaxwell-main/RKRefErrorDatadelta10.py | import bempp.api
import numpy as np
import math
from RKconv_op import *
print("Bempp version used : " + bempp.api.__version__)
def create_timepoints(c,N,T):
m=len(c)
time_points=np.zeros((1,m*N))
for j in range(m):
time_points[0,j:m*N:m]=c[j]*1.0/N*np.ones((1,N))+np.linspace(0,1-1.0/N,N)
return T*time_points
def create_rhs(grid,dx,N,T,m):
# grid=bempp.api.shapes.cube(h=1)
#
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
if (m==2):
c_RK=np.array([1.0/3,1])
if (m==3):
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
from bempp.api.operators.boundary import maxwell
from bempp.api.operators.boundary import sparse
# multitrace = maxwell.multitrace_operator(grid, 1)
NC_space = bempp.api.function_space(grid,"NC",0)
RT_space = bempp.api.function_space(grid,"RT",0)
#curl_space = bempp.api.function_space(grid, "RBC", 0)
BC_space=bempp.api.function_space(grid, "BC",0)
SNC_space=bempp.api.function_space(grid, "SNC",0)
BRWG_space=bempp.api.function_space(grid, "B-RWG",0)
# div_space=bempp.api.function_space(grid, "B-RWG",0)
RBC_space=bempp.api.function_space(grid,"RBC",0)
# curl_space=bempp.api.function_space(grid,"RBC",0)
#from bempp.api.operators.boundary.sparse import identity as ident
# id1 = ident(div_space,div_space,curl_space).weak_form()
# print("CONDITION NUMBER : ", np.linalg.cond(bempp.api.as_matrix(id1).todense()))
dof=RT_space.global_dof_count
dof1=NC_space.global_dof_count
print(" DOF: ", dof)
rhs=np.zeros((dof+dof,N*m))
curls=np.zeros((dof,N*m))
time_points=create_timepoints(c_RK,N,T)
for j in range(m*N):
t=time_points[0,j]
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
#return np.array([np.exp(-200*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
def tangential_trace(x, n, domain_index, result):
result[:] = np.cross(n,np.cross(incident_field(x), n))
def curl_trace(x,n,domain_index,result):
curlU=np.array([ 0. * x[2],-100*(x[2]-t+2)*np.exp(-50*(x[2]-t+2)**2), 0. * x[2]])
result[:] = np.cross(curlU , n)
curl_fun = bempp.api.GridFunction(RT_space, fun=curl_trace,dual_space=RT_space)
trace_fun= bempp.api.GridFunction(RT_space, fun=tangential_trace,dual_space=RT_space)
rhs[0:dof,j]=trace_fun.coefficients
curlCoeffs=curl_fun.coefficients
if np.linalg.norm(curlCoeffs)>10**-9:
curls[0:dof,j]=curlCoeffs
#print("RHS NORM :", np.linalg.norm(trace_fun.coefficients))
def sinv(s,b):
return s**(-1)*b
IntegralOperator=Conv_Operator(sinv)
def HarmonicImpedance(s,b):
return 10*s**(0.5)*b
TimeImpedance=Conv_Operator(HarmonicImpedance)
if (m==2):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
if (m==3):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
rhs[0:dof,:]=np.real(ZptNeuTrace)-rhs[0:dof,:]
return rhs
def harmonic_calderon(s,b,grid):
points=np.array([[0],[0],[2]])
#normb=np.linalg.norm(b[0])+np.linalg.norm(b[1])+np.linalg.norm(b[2])
normb=np.max(np.abs(b))
bound=np.abs(s)**4*np.exp(-s.real)*normb
print("s: ",s, " maxb: ", normb, " bound : ", bound)
if bound <10**(-9):
print("JUMPED")
return np.zeros(3)
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
### Define Spaces
NC_space=bempp.api.function_space(grid, "NC",0)
RT_space=bempp.api.function_space(grid, "RT",0)
elec = -bempp.api.operators.boundary.maxwell.electric_field(RT_space, RT_space, NC_space,1j*s)
magn = -bempp.api.operators.boundary.maxwell.magnetic_field(RT_space, RT_space, NC_space, 1j*s)
identity2=bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, RT_space)
identity= -bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, NC_space)
dof=NC_space.global_dof_count
trace_fun= bempp.api.GridFunction(RT_space, coefficients=b[0:dof],dual_space=RT_space)
######## End condition, by theoretical bound:
normb=trace_fun.l2_norm()
bound=np.abs(s)**3*np.exp(-s.real)*normb
if bound <10**(-8):
print("JUMPED")
return np.zeros(3)
zero_fun= bempp.api.GridFunction(RT_space,coefficients = b[dof:],dual_space=RT_space)
#rhs=[trace_fun,zero_fun]
id_discrete=identity2.weak_form()
b[0:dof]=id_discrete*b[0:dof]
blocks=np.array([[None,None], [None,None]])
#blocks[0,0] = -elec.weak_form()+10*s**0.5*identity2.weak_form()
blocks[0,0] = -elec.weak_form()+10*s**0.5*identity2.weak_form()
blocks[0,1] = magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,0] = -magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,1] = -elec.weak_form()
blocks=bempp.api.BlockedDiscreteOperator(blocks)
# A_mat=bempp.api.as_matrix(blocks)
# print("A_mat : ",A_mat)
# e,D=np.linalg.eig(A_mat)
# print("Eigs : ", e)
# print("Cond : ", np.linalg.cond(A_mat))
##
## trace_fun= bempp.api.GridFunction(multitrace.range_spaces[0], coefficients=b[0:dof],dual_space=multitrace.dual_to_range_spaces[0])
##
## zero_fun= bempp.api.GridFunction(multitrace.range_spaces[1],coefficients = b[dof:],dual_space=multitrace.dual_to_range_spaces[1])
##
## rhs=[trace_fun,zero_fun]
##
## #print("Still living")
##
#from bempp.api.linalg import gmres
from scipy.sparse.linalg import gmres
print("Start GMRES : ")
# def print_res(rk):
# print("Norm of residual: "+ str(np.linalg.norm(rk)))
#print(np.linalg.norm(lambda_data))
#lambda_data,info = gmres(blocks, b,tol=10**-4,restart=50,maxiter=100,callback=print_res)
lambda_data,info = gmres(blocks, b,tol=10**-5,maxiter=300)
print("INFO :", info)
#lambda_data,info = gmres(blocks, b,tol=10**-4,callback=print_res)
#print("I survived!")
#from bempp.api.linalg import lu
#lambda_data = lu(elec, trace_fun)
#lambda_data.plot()
#print("Norm lambda_data : ",np.linalg.norm(lambda_data))
#if (np.linalg.norm(lambda_data)<10**-10):
phigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[0:dof],dual_space=RT_space)
psigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[dof:2*dof],dual_space=RT_space)
slp_pot = bempp.api.operators.potential.maxwell.electric_field(RT_space, points, s*1j)
dlp_pot = bempp.api.operators.potential.maxwell.magnetic_field(RT_space, points, s*1j)
print("Evaluate field : ")
scattered_field_data = -slp_pot * phigrid+dlp_pot*psigrid
# scattered_field_H = -slp_pot * psigrid-dlp_pot*phigrid
# H = scattered_field_H.reshape(3,1)[:,0]
# print(" E : ", E, " H : ", H)
# print("Angle: ", np.dot(E,H), " Scalar product with conjugation : ", np.dot(np.conj(E),H))
# print("NORM COMBINED OPERATOR :" , np.linalg.norm(scattered_field_data)/np.linalg.norm(b))
# print(scattered_field_data)
# print("NORM ScatteredField :", np.linalg.norm(scattered_field_data))
#
# print("s : ", s)
# print("NORM B :" ,np.linalg.norm(b))
if np.isnan(scattered_field_data).any():
print("NAN Warning, s = ", s)
scattered_field_data=np.zeros(np.shape(scattered_field_data))
return scattered_field_data.reshape(3,1)[:,0]
def scattering_solution(dx,N,T,m):
grid=bempp.api.shapes.sphere(h=dx)
rhs=create_rhs(grid,dx,N,T,m)
def ellipticSystem(s,b):
return harmonic_calderon(s,b,grid)
ScatOperator=Conv_Operator(ellipticSystem)
#num_sol=ScatOperator.apply_convol(rhs,T)
if (m==2):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-5),method="RadauIIA-2")
if (m==3):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-5),method="RadauIIA-3")
num_sol=np.zeros((len(num_solStages[:,0]),N+1))
num_sol[:,1:N+1]=np.real(num_solStages[:,m-1:N*m:m])
return num_sol
import time
T=6
#N_ref=2**4
N_ref=2**11
tt_ref=np.linspace(0,T,N_ref+1)
#dx_ref=np.sqrt(2)**(-4)
dx_ref=np.sqrt(2)**(-9)
m=3
import matplotlib.pyplot as plt
start=time.time()
#sol_ref=scattering_solution(dx_ref,N_ref,T)
#sol_ref2=scattering_solution(dx_ref,N_ref,T)
#
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,np.abs(sol_ref[0,:]))
#plt.plot(tt,np.abs(sol_ref[0,:]-sol_ref2[0,:]))
##plt.plot(tt,resc_ref[0,:],linestyle='dashed')
##plt.plot(tt,num_sol[0,:])
#plt.show()
sol_ref=scattering_solution(dx_ref,N_ref,T,m)
#
np.save("data/sol_ref_absorbing_delta10_N2h11_dxsqrt2m9RK5.npy",sol_ref)
#sol_ref=np.load("data/sol_ref_absorbing_delta0p1_N2h11_dxsqrt2m10RK5.npy")
#Current Reference solutions:
#np.save("data/sol_ref_absorbing_delta0p1_N212_dxsqrt2m9RK5.npy",sol_ref)
#np.save("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy",sol_ref)
#sol_ref=np.load("data/sol_ref_absorbing_delta1_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_N212_dxsqrt2m7RK5.npy")
#import scipy.io
#scipy.io.loadmat('data/Err_data_delta1.mat')
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,sol_ref[0,:])
#plt.show()
#plt.plot(sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2)
#plt.show()
Am_space=8
Am_time=7
#Am_space=1
#Am_time=8
tau_s=np.zeros(Am_time)
h_s=np.zeros(Am_space)
errors=np.zeros((Am_space,Am_time))
m=2
for ixSpace in range(Am_space):
for ixTime in range(Am_time):
N=8*2**(ixTime)
tau_s[ixTime]=T*1.0/N
tt=np.linspace(0,T,N+1)
dx=np.sqrt(2)**(-ixSpace)
h_s[ixSpace]=dx
########## Rescaling reference solution:
speed=N_ref/N
resc_ref=np.zeros((3,N+1))
# resc_ref=sol_ref
for j in range(N+1):
resc_ref[:,j] = sol_ref[:,j*speed]
#num_sol = calc_ref_sol(N,dx,F_transfer)
num_sol = scattering_solution(dx,N,T,m)
# plt.plot(tt,num_sol[0,:]**2+num_sol[1,:]**2+num_sol[2,:]**2)
# plt.plot(tt_ref,sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2,linestyle='dashed')
# plt.show()
errors[ixSpace,ixTime]=np.max(np.abs(resc_ref-num_sol))
print(errors)
import scipy.io
scipy.io.savemat('data/Err_data_delta10.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
#scipy.io.savemat('data/Err_data_delta0p1_long.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
end=time.time()
print("Script Runtime: "+str((end-start)/60) +" Min")
#
| 11,402 | 34.194444 | 133 | py |
CQMaxwell | CQMaxwell-main/libVersions.py | import bempp.api
import scipy
import numpy
import matplotlib
print("Bempp version :", bempp.api.__version__)
print("Scipy version :", scipy.__version__)
print("Numpy version :", numpy.__version__)
print("Matplotlib version :", matplotlib.__version__)
| 251 | 27 | 53 | py |
CQMaxwell | CQMaxwell-main/RKconv_op.py |
class Conv_Operator:
import numpy as np
tol=10**-16
def __init__(self,apply_elliptic_operator,order=2):
self.order=order
self.delta=lambda zeta : self.char_functions(zeta,order)
self.apply_elliptic_operator=apply_elliptic_operator
def get_integration_parameters(self,N,T):
tol=self.tol
dt=(T*1.0)/N
L=N*2
rho=tol**(1.0/(2*L))
return L,dt,tol,rho
def char_functions(self,zeta,order):
if order==1:
return 1-zeta
else:
if order==2:
return 1.5-2.0*zeta+0.5*zeta**2
else:
if order ==3:
#return 1-zeta**3
return (1-zeta)+0.5*(1-zeta)**2+1.0/3.0*(1-zeta)**3
else:
print("Multistep order not availible")
def get_zeta_vect(self,N,T):
L,dt,tol,rho=self.get_integration_parameters(N,T)
import numpy as np
Unit_Roots=np.exp(-1j*2*np.pi*(np.linspace(0,L,L+1)/(L+1)))
Zeta_vect=self.delta( rho* Unit_Roots)/dt
return Zeta_vect
def get_frequencies(self,N,T):
import numpy as np
L,dt,tol,rho=self.get_integration_parameters(N,T)
Unit_Roots=np.exp(-1j*2*np.pi*(np.linspace(0,L-1,L)/(L)))
return rho*Unit_Roots
def get_method_characteristics(self,method):
import numpy as np
import math
if (method == "RadauIIA-2"):
c_RK=np.array([1.0/3,1])
A_RK=np.array([[5.0/12,-1.0/12],[3.0/4,1.0/4]])
b_RK=np.array([[3.0/4,1.0/4]])
elif (method == "RadauIIA-3"):
A_RK=np.array([[11.0/45-7*math.sqrt(6)/360, 37.0/225-169.0*math.sqrt(6)/1800 , -2.0/225+math.sqrt(6)/75],[37.0/225+169.0*math.sqrt(6)/1800,11.0/45+7*math.sqrt(6)/360,-2.0/225-math.sqrt(6)/75],[4.0/9-math.sqrt(6)/36,4.0/9+math.sqrt(6)/36,1.0/9]])
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
b_RK=np.array([4.0/9-math.sqrt(6)/36,4.0/9+math.sqrt(6)/36,1.0/9])
m=len(A_RK[0,:])
return A_RK,b_RK,c_RK,m
def format_rhs(self,rhs,m):
try:
N=(len(rhs[0,:]))/m
except:
N=(len(rhs))/m
rhs_mat=np.zeros((1,N+1))
rhs_mat[0,:]=rhs
rhs=rhs_mat
return rhs,N
def apply_RKconvol(self,rhs,T,show_progress=True,method="RadauIIA-2",cutoff=10**(-8)):
import numpy as np
import bempp.api
## Step 1
[A_RK,b_RK,c_RK,m]=self.get_method_characteristics(method)
self.m=m
[rhs,N]=self.format_rhs(rhs,m)
L,dt,tol,rho=self.get_integration_parameters(N,T)
rhs_fft=1j*np.zeros((len(rhs[:,0]),m*L))
for stageInd in range(m):
rhs_fft[:,stageInd:m*L:m]=self.scale_fft(rhs[:,stageInd:m*N:m],N,T)
#Initialising important parameters for the later stage
s_vect=self.get_frequencies(N,T)
dof=len(rhs[:,0])
L,dt,tol,rho=self.get_integration_parameters(N,T)
Half=int(np.ceil(float(L)/2.0))
## Step 2
#phi_hat=1j*np.zeros((dof,L+1))
normsRHS=np.ones(m*L)
counter=0
for j in range(0,m*L):
normsRHS[j]=np.max(np.abs(rhs_fft[:,j]))
if normsRHS[j]>cutoff:
counter=counter+1
#import matplotlib.pyplot as plt
#plt.semilogy(normsRHS)
#plt.show()
print("CUTOFF :", cutoff)
HalfL= int(np.ceil(float(L)/2.0))
print("Amount of Systems needed: "+ str(counter))
#Timing the elliptic systems
import time
start=0
end=0
rhsStages=1j*np.zeros((len(rhs_fft[:,0]),m))
for j in range(0,HalfL+1):
s=s_vect[j]
deltaMatrix=np.linalg.inv(A_RK+s*1.0/(1-s)*np.ones((m,1))*b_RK)
deltaEigs,T =np.linalg.eig(deltaMatrix)
# print("CONDITION T: ", np.linalg.cond(T))
deltaEigs=deltaEigs/dt
Tinv=np.linalg.inv(T)
# print("NormT: ",np.linalg.norm(T))
if show_progress:
print("j:",j,"L:",L, "Time of previous iteration: " +str((end-start)/60), " MIN" )
start=time.time()
if j>0:
relevantChange=False
rhsStages=1j*rhsStages*0
lhsStages=1j*lhsStages*0
for stageInd in range(m):
for sumInd in range(m):
rhsStages[:,stageInd]=rhsStages[:,stageInd]+Tinv[stageInd,sumInd]*rhs_fft[:,m*j+sumInd]
maxRHS=np.max(np.abs(rhsStages[:,stageInd]))
#print("RHS MAX : ",maxRHS )
if maxRHS>cutoff:
relevantChange=True
lhsStages[:,stageInd]=self.apply_elliptic_operator(deltaEigs[stageInd],rhsStages[:,stageInd])
else:
relevantChange=True
for sumInd in range(m):
rhsStages[:,0]=rhsStages[:,0]+Tinv[0,sumInd]*rhs_fft[:,m*j+sumInd]
first_eval=self.apply_elliptic_operator(deltaEigs[0],rhsStages[:,0])
phi_hat=1j*np.zeros((len(first_eval),m*L))
lhsStages=1j*np.zeros((len(phi_hat[:,0]),m))
lhsStages[:,0]=first_eval
for stageInd in range(1,m):
for sumInd in range(m):
rhsStages[:,stageInd]=rhsStages[:,stageInd]+Tinv[stageInd,sumInd]*rhs_fft[:,m*j+sumInd]
lhsStages[:,stageInd]=self.apply_elliptic_operator(deltaEigs[stageInd],rhsStages[:,stageInd])
if relevantChange:
for stageInd in range(m):
for sumInd in range(m):
phi_hat[:,m*j+stageInd]=phi_hat[:,m*j+stageInd]+T[stageInd,sumInd]*lhsStages[:,sumInd]
end=time.time()
# for j in range(Half+1,L+1):
# phi_hat[:,j]=np.conj(phi_hat[:,L+1-j])
## Step 3
for freqInd in range(HalfL,L):
for stageInd in range(m):
phi_hat[:,freqInd*m+stageInd]=np.conj(phi_hat[:,m*(L-freqInd)+stageInd])
#print(phi_hat)
#print(phi_hat2)
#print("ERR: ",np.abs(phi_hat-phi_hat2))
#print("phi_hat ",phi_hat)
#
#print("phi_hat2 ",phi_hat2)
#phi_sol=1j*phi_hat*0
for stageInd in range(m):
phi_hat[:,stageInd:m*L:m]=self.rescale_ifft(phi_hat[:,stageInd:m*L:m],N,T)
#phi_sol[:,1:2*N+2:2]=self.rescale_ifft(phi_hat[:,1:2*N+2:2])
phi_sol=phi_hat[:,:m*N]
if len(phi_sol[:,0])==1:
phi_sol=phi_sol[0,:]
return phi_sol
def apply_convol(self,rhs,T,show_progress=True,method="BDF2",cutoff=10**(-8)):
import numpy as np
import bempp.api
if (method == "RadauIIA-2"):
print(show_progress)
return self.apply_RKconvol(rhs,T,show_progress=show_progress,method=method,cutoff=cutoff)
## Step 1
print("In apply_convol")
try:
N=len(rhs[0,:])-1
except:
N=len(rhs)-1
rhs_mat=np.zeros((1,N+1))
rhs_mat[0,:]=rhs
rhs=rhs_mat
normsRHS=np.ones(N+1)
for j in range(0,N+1):
normsRHS[j]=np.max(np.abs(rhs[:,j]))
#import matplotlib.pyplot as plt
#plt.semilogy(normsRHS)
#plt.show()
rhs_fft=self.scale_fft(rhs)
# import matplotlib.pyplot as plt
# for j in range(0,len(rhs[:,0])):
# print("rhs_fft : " , np.abs(rhs[j,:]))
# plt.loglog(list(map(max,np.abs(rhs_fft[j,:]),10**-15*np.ones(len(rhs_fft[j,:])))))
# plt.show()
#
#Initialising important parameters for the later stage
Zeta_vect=self.get_zeta_vect(N,T)
print("ZETA0 :", Zeta_vect[0])
dof=len(rhs[:,0])
L,dt,tol,rho=self.get_integration_parameters(N,T)
Half=int(np.ceil(float(L)/2.0))
## Step 2
#phi_hat=1j*np.zeros((dof,L+1))
normsRHS=np.ones(L+1)
counter=0
for j in range(0,Half+1):
normsRHS[j]=np.max(np.abs(rhs_fft[:,j]))
if normsRHS[j]>cutoff:
counter=counter+1
#import matplotlib.pyplot as plt
#plt.semilogy(normsRHS)
#plt.show()
print("CUTOFF :", cutoff)
print("Amount of Systems needed: "+ str(counter))
#Timing the elliptic systems
import time
start=0
end=0
for j in range(0,Half+1):
normsRHS[j]=np.max(np.abs(rhs_fft[:,j]))
#print("normRHS:",normsRHS[j])
if normsRHS[j]>cutoff:
if show_progress:
print("j:",j,"L:",str(Half), "Time of previous iteration: " +str((end-start)/60), " MIN" )
start=time.time()
if j>0:
phi_hat[:,j]=self.apply_elliptic_operator(Zeta_vect[j],rhs_fft[:,j])
else:
first_eval=self.apply_elliptic_operator(Zeta_vect[j],rhs_fft[:,j])
phi_hat=1j*np.zeros((len(first_eval),L+1))
phi_hat[:,0]=first_eval
end=time.time()
for j in range(Half+1,L+1):
phi_hat[:,j]=np.conj(phi_hat[:,L+1-j])
## Step 3
import matplotlib.pyplot as plt
phi_sol=self.rescale_ifft(phi_hat)
phi_sol=phi_sol[:,:m*N]
if len(phi_sol[:,0])==1:
phi_sol=phi_sol[0,:]
return phi_sol
def scale_fft(self,A,N,T):
import numpy as np
L,dt,tol,rho=self.get_integration_parameters(N,T)
n_rows=len(A[:,0])
n_columns=len(A[0,:])
A=rho**(np.linspace(0,n_columns-1,n_columns))*A
A_fft=np.fft.fft(np.concatenate((A,np.zeros((n_rows,L-n_columns))),axis=1))
return A_fft
def rescale_ifft(self,A,N,T):
import numpy as np
L,dt,tol,rho=self.get_integration_parameters(N,T)
n_rows=len(A[:,0])
n_columns=len(A[0,:])
A_ift=np.real(np.fft.ifft(A))
A_sol=np.real(rho**(-np.linspace(0,n_columns-1,n_columns))*A_ift[:,0:n_columns])
return(A_sol)
| 8,340 | 27.467577 | 248 | py |
CQMaxwell | CQMaxwell-main/FramesAndConditions.py | import numpy as np
import bempp.api
import math
from RKconv_op import *
def create_timepoints(c,N,T):
m=len(c)
time_points=np.zeros((1,m*N))
for j in range(m):
time_points[0,j:m*N:m]=c[j]*1.0/N*np.ones((1,N))+np.linspace(0,1-1.0/N,N)
return T*time_points
def create_rhs(grid,N,T,m):
#grid=bempp.api.shapes.sphere(h=dx)
if (m==2):
c_RK=np.array([1.0/3,1])
if (m==3):
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
from bempp.api.operators.boundary import maxwell
RT_space = bempp.api.function_space(grid,"RT",0)
# curl_space=bempp.api.function_space(grid,"RBC",0)
#from bempp.api.operators.boundary.sparse import identity as ident
# id1 = ident(div_space,div_space,curl_space).weak_form()
# print("CONDITION NUMBER : ", np.linalg.cond(bempp.api.as_matrix(id1).todense()))
dof=RT_space.global_dof_count
print(" DOF: ", dof)
rhs=np.zeros((dof+dof,N*m))
curls=np.zeros((dof,N*m))
time_points=create_timepoints(c_RK,N,T)
for j in range(m*N):
t=time_points[0,j]
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+1)**2), 0. * x[2], 0. * x[2]])
#return np.array([np.exp(-200*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
def tangential_trace(x, n, domain_index, result):
result[:] = np.cross(n,np.cross(incident_field(x), n))
def curl_trace(x,n,domain_index,result):
curlU=np.array([ 0. * x[2],-100*(x[2]-t+1)*np.exp(-50*(x[2]-t+1)**2), 0. * x[2]])
result[:] = np.cross(curlU , n)
curl_fun = bempp.api.GridFunction(RT_space, fun=curl_trace,dual_space=RT_space)
trace_fun= bempp.api.GridFunction(RT_space, fun=tangential_trace,dual_space=RT_space)
rhs[0:dof,j]=trace_fun.coefficients
curlCoeffs=curl_fun.coefficients
if np.linalg.norm(curlCoeffs)>10**-9:
curls[0:dof,j]=curlCoeffs
#print("RHS NORM :", np.linalg.norm(trace_fun.coefficients))
def sinv(s,b):
return s**(-1)*b
IntegralOperator=Conv_Operator(sinv)
def HarmonicImpedance(s,b):
return 0.1*s**(0.5)*b
TimeImpedance=Conv_Operator(HarmonicImpedance)
if (m==2):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
if (m==3):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
rhs[0:dof,:]=np.real(ZptNeuTrace)-rhs[0:dof,:]
return rhs
def harmonic_calderon(s,b,grid,points):
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
### Define Spaces
NC_space=bempp.api.function_space(grid, "NC",0)
RT_space=bempp.api.function_space(grid, "RT",0)
elec = -bempp.api.operators.boundary.maxwell.electric_field(RT_space, RT_space, NC_space,1j*s)
magn = -bempp.api.operators.boundary.maxwell.magnetic_field(RT_space, RT_space, NC_space, 1j*s)
identity2=bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, RT_space)
identity= -bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, NC_space)
dof=NC_space.global_dof_count
trace_fun= bempp.api.GridFunction(RT_space, coefficients=b[0:dof],dual_space=RT_space)
zero_fun= bempp.api.GridFunction(RT_space,coefficients = b[dof:],dual_space=RT_space)
#rhs=[trace_fun,zero_fun]
id_discrete=identity2.weak_form()
b[0:dof]=id_discrete*b[0:dof]
blocks=np.array([[None,None], [None,None]])
blocks[0,0] = -elec.weak_form()+0.1*s**0.5*identity2.weak_form()
blocks[0,1] = magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,0] = -magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,1] = -elec.weak_form()
blocks_discrete=bempp.api.BlockedDiscreteOperator(blocks)
######## Saving the condition number and frequency :
from scipy.sparse.linalg import gmres
lambda_data,info= gmres(blocks_discrete, b)
#cond=np.linalg.cond(bempp.api.as_matrix(blocks_discrete))
print("System solved !")
import scipy.io,time
mat_contents =scipy.io.loadmat('data/cond.mat')
freqCond_old = mat_contents['freqCond']
if s in freqCond_old[0]:
print("Frequency already calculated")
else:
tp0=time.time()
blocks_mat=bempp.api.as_matrix(blocks_discrete)
# tp4=time.time()
sigmas = scipy.linalg.svdvals(blocks_mat)
norminv = min(sigmas)**(-1)
normA = max(sigmas)
cond=normA*norminv
print("Freq: ",s ," Cond: ",cond)
# print(freqCond_old)
freqCond=np.concatenate((freqCond_old,np.array([[s],[cond],[normA],[norminv]])),axis=1)
scipy.io.savemat('data/cond.mat',dict(freqCond=freqCond))
#####################################################
#print(np.linalg.norm(lambda_data))
#print("I survived!")
#from bempp.api.linalg import lu
#lambda_data = lu(elec, trace_fun)
#lambda_data.plot()
#print("Norm lambda_data : ",np.linalg.norm(lambda_data))
#if (np.linalg.norm(lambda_data)<10**-10):
phigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[0:dof],dual_space=RT_space)
psigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[dof:2*dof],dual_space=RT_space)
######## Create Points
#
# x_a=-0.75
# x_b=0.75
# y_a=-0.25
# y_b=1.25
##
# x_a=-2
# x_b=2
# y_a=-2
# y_b=2
# n_grid_points=150
################################################
# plot_grid = np.mgrid[y_a:y_b:1j*n_grid_points, x_a:x_b:1j*n_grid_points]
## plot_grid = np.mgrid[-0.5:1:1j*n_grid_points, -1.5:1.5:1j*n_grid_points]
# #print(plot_grid)
## points = np.vstack( ( plot_grid[0].ravel() , plot_grid[1].ravel() , 0.25*np.ones(plot_grid[0].size) ) )
#
# points = np.vstack( ( plot_grid[0].ravel() , 0*np.ones(plot_grid[0].size) , plot_grid[1].ravel()) )
#point=np.array([[0],[0],[2]])
slp_pot = bempp.api.operators.potential.maxwell.electric_field(RT_space, points, s*1j)
dlp_pot = bempp.api.operators.potential.maxwell.magnetic_field(RT_space, points, s*1j)
scattered_field_data = -slp_pot * phigrid+dlp_pot*psigrid
# print("NORM COMBINED OPERATOR :" , np.linalg.norm(scattered_field_data)/np.linalg.norm(b))
# print(scattered_field_data)
# print("NORM ScatteredField :", np.linalg.norm(scattered_field_data))
#
# print("s : ", s)
# print("NORM B :" ,np.linalg.norm(b))
if np.isnan(scattered_field_data).any():
print("NAN Warning",s)
print("NORM B :" ,np.linalg.norm(b))
return np.zeros(n_grid_points**2*3)
#print(scattered_field_data.reshape(3,1)[:,0])
return scattered_field_data.reshape(n_grid_points**2*3,1)[:,0]
def scattering_solution(dx,N,T,m,points):
import scipy.io
import numpy as np
mat_contents=scipy.io.loadmat('grids/TorusDOF896.mat')
Nodes=np.array(mat_contents['Nodes']).T
rawElements=mat_contents['Elements']
for j in range(len(rawElements)):
betw=rawElements[j][0]
rawElements[j][0]=rawElements[j][1]
rawElements[j][1]=betw
Elements=np.array(rawElements).T
Elements=Elements-1
grid=bempp.api.grid_from_element_data(Nodes,Elements)
# def tangential_trace(x, n, domain_index, result):
# result[:] = n[1]
#
# P1_space = bempp.api.function_space(grid,"P",1)
# normal_fun = bempp.api.GridFunction(P1_space, fun=tangential_trace,dual_space=P1_space)
#normal_fun.plot()
#grid.plot()
#grid=bempp.api.shapes.sphere(h=dx)
rhs=create_rhs(grid,N,T,m)
def ellipticSystem(s,b):
return harmonic_calderon(s,b,grid,points)
ScatOperator=Conv_Operator(ellipticSystem)
#num_sol=ScatOperator.apply_convol(rhs,T)
if (m==2):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-16),method="RadauIIA-2")
if (m==3):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-16),method="RadauIIA-3")
num_sol=np.zeros((len(num_solStages[:,0]),N+1))
num_sol[:,1:N+1]=np.real(num_solStages[:,m-1:N*m:m])
return num_sol
import time
N=100
T=4
#Generate points
x_a=-1.5
x_b=1.5
y_a=-1.5
y_b=1.5
n_grid_points=300
nx=n_grid_points
nz=n_grid_points
#######################################
#Initialize empty file, which will be overwritten continously with condition numbers#and the frequencies
freqCond=1j*np.array([[0],[0],[0],[0]])
import scipy.io
scipy.io.savemat('data/cond.mat',dict(freqCond=freqCond))
###############
plot_grid = np.mgrid[y_a:y_b:1j*n_grid_points, x_a:x_b:1j*n_grid_points]
#plot_grid = np.mgrid[-0.5:1:1j*n_grid_points, -1.5:1.5:1j*n_grid_points]
#print(plot_grid)
points = np.vstack( ( plot_grid[0].ravel() , 0*np.ones(plot_grid[0].size) , plot_grid[1].ravel()) )
evals=scattering_solution(1,N,T,3,points)
u_ges=np.zeros((n_grid_points**2,N+1))
for j in range(N+1):
#matplotlib inline
import matplotlib
from matplotlib import pylab as plt
# Adjust the figure size in IPython
matplotlib.rcParams['figure.figsize'] = (10.0, 8.0)
t=j*T*1.0/N
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+1)**2), 0. * x[2], 0. * x[2]])
incident_field_data = incident_field(points)
#scat_eval=np.zeros(nx*nz*3)
#incident_field_data[radius<1]=np.nan
scat_eval=evals[:,j].reshape(3,nx*nz)
# print(scat_eval)
field_data = scat_eval + incident_field_data
# field_data = scat_eval
# field_data = incident_field_data
# print("Points: ")
# print(points)
# print("Data: ")
#print(field_data)
squared_field_density = np.sum(field_data * field_data,axis = 0)
u_ges[:,j]=squared_field_density.T
#squared_field_density=field_data[2,:]
#squared_field_density[radius<1]=np.nan
#print("MAX FIELD DATA: " , max(squared_field_density))
print(max(np.abs(squared_field_density)))
plt.imshow(squared_field_density.reshape((nx, nz)).T,
cmap='coolwarm', origin='lower',
extent=[x_a, x_b, y_a, y_b])
if j==10:
plt.colorbar()
plt.clim((-1,1))
#plt.title("Squared Electric Field Density")
#plt.savefig("data/wave_images/Screen_n{}.png".format(j))
import scipy.io
scipy.io.savemat('data/delta01_dof896.mat',dict(u_ges=u_ges,N=N,T=T,plot_grid=plot_grid,points=points))
#
# tp1=time.time()
# print("Dense Matrix assembled, time : ", tp1-tp0)
#
# normA=np.linalg.norm(blocks_mat,ord=2)
# tp2=time.time()
# print("Norm A calculated, value ",normA, " time : ",tp2-tp1)
# cond=np.linalg.cond(blocks_mat)
# tp3=time.time()
# print("Cond A calculated, value ", cond," time : ",tp3-tp2)
# norminv=np.linalg.norm(np.linalg.inv(blocks_mat),ord=2)
# print("Inv A calculated, direct : ", norminv, " Previous estimate : ", cond/normA)
| 10,911 | 33.1 | 113 | py |
CQMaxwell | CQMaxwell-main/RKRefErrorDatadelta01.py | import bempp.api
import numpy as np
import math
from RKconv_op import *
print("Bempp version used : " + bempp.api.__version__)
def create_timepoints(c,N,T):
m=len(c)
time_points=np.zeros((1,m*N))
for j in range(m):
time_points[0,j:m*N:m]=c[j]*1.0/N*np.ones((1,N))+np.linspace(0,1-1.0/N,N)
return T*time_points
def create_rhs(grid,dx,N,T,m):
# grid=bempp.api.shapes.cube(h=1)
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
if (m==2):
c_RK=np.array([1.0/3,1])
if (m==3):
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
from bempp.api.operators.boundary import maxwell
from bempp.api.operators.boundary import sparse
# multitrace = maxwell.multitrace_operator(grid, 1)
NC_space = bempp.api.function_space(grid,"NC",0)
RT_space = bempp.api.function_space(grid,"RT",0)
#curl_space = bempp.api.function_space(grid, "RBC", 0)
#BC_space=bempp.api.function_space(grid, "BC",0)
#SNC_space=bempp.api.function_space(grid, "SNC",0)
#BRWG_space=bempp.api.function_space(grid, "B-RWG",0)
# #div_space=bempp.api.function_space(grid, "B-RWG",0)
#RBC_space=bempp.api.function_space(grid,"RBC",0)
# curl_space=bempp.api.function_space(grid,"RBC",0)
#from bempp.api.operators.boundary.sparse import identity as ident
# id1 = ident(div_space,div_space,curl_space).weak_form()
# print("CONDITION NUMBER : ", np.linalg.cond(bempp.api.as_matrix(id1).todense()))
dof=RT_space.global_dof_count
dof1=NC_space.global_dof_count
print(" DOF: ", dof)
rhs=np.zeros((dof+dof,N*m))
curls=np.zeros((dof,N*m))
time_points=create_timepoints(c_RK,N,T)
for j in range(m*N):
t=time_points[0,j]
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
#return np.array([np.exp(-200*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
@bempp.api.real_callable
def tangential_trace(x, n, domain_index, result):
result[:] = np.cross(n,np.cross(incident_field(x), n))
@bempp.api.real_callable
def curl_trace(x,n,domain_index,result):
curlU=np.array([ 0. * x[2],-100*(x[2]-t+2)*np.exp(-50*(x[2]-t+2)**2), 0. * x[2]])
result[:] = np.cross(curlU , n)
curl_fun = bempp.api.GridFunction(RT_space, fun=curl_trace,dual_space=RT_space)
trace_fun= bempp.api.GridFunction(RT_space, fun=tangential_trace,dual_space=RT_space)
rhs[0:dof,j]=trace_fun.coefficients
curlCoeffs=curl_fun.coefficients
if np.linalg.norm(curlCoeffs)>10**-9:
curls[0:dof,j]=curlCoeffs
#print("RHS NORM :", np.linalg.norm(trace_fun.coefficients))
def sinv(s,b):
return s**(-1)*b
IntegralOperator=Conv_Operator(sinv)
def HarmonicImpedance(s,b):
return 0.1*s**(0.5)*b
TimeImpedance=Conv_Operator(HarmonicImpedance)
if (m==2):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
if (m==3):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
rhs[0:dof,:]=np.real(ZptNeuTrace)-rhs[0:dof,:]
return rhs
def harmonic_calderon(s,b,grid):
points=np.array([[0],[0],[2]])
#normb=np.linalg.norm(b[0])+np.linalg.norm(b[1])+np.linalg.norm(b[2])
normb=np.max(np.abs(b))
bound=np.abs(s)**4*np.exp(-s.real)*normb
print("s: ",s, " maxb: ", normb, " bound : ", bound)
if bound <10**(-9):
print("JUMPED")
return np.zeros(3)
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
### Define Spaces
NC_space=bempp.api.function_space(grid, "NC",0)
RT_space=bempp.api.function_space(grid, "RT",0)
elec = -bempp.api.operators.boundary.maxwell.electric_field(RT_space, RT_space, NC_space,1j*s)
magn = -bempp.api.operators.boundary.maxwell.magnetic_field(RT_space, RT_space, NC_space, 1j*s)
identity2=bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, RT_space)
identity= -bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, NC_space)
dof=NC_space.global_dof_count
trace_fun= bempp.api.GridFunction(RT_space, coefficients=b[0:dof],dual_space=RT_space)
######## End condition, by theoretical bound:
normb=trace_fun.l2_norm()
bound=np.abs(s)**3*np.exp(-s.real)*normb
if bound <10**(-8):
print("JUMPED")
return np.zeros(3)
zero_fun= bempp.api.GridFunction(RT_space,coefficients = b[dof:],dual_space=RT_space)
#rhs=[trace_fun,zero_fun]
id_discrete=identity2.weak_form()
b[0:dof]=id_discrete*b[0:dof]
blocks=np.array([[None,None], [None,None]])
#blocks[0,0] = -elec.weak_form()+10*s**0.5*identity2.weak_form()
blocks[0,0] = -elec.weak_form()+0.1*s**0.5*identity2.weak_form()
blocks[0,1] = magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,0] = -magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,1] = -elec.weak_form()
blocks=bempp.api.BlockedDiscreteOperator(blocks)
# A_mat=bempp.api.as_matrix(blocks)
# print("A_mat : ",A_mat)
# e,D=np.linalg.eig(A_mat)
# print("Eigs : ", e)
# print("Cond : ", np.linalg.cond(A_mat))
##
## trace_fun= bempp.api.GridFunction(multitrace.range_spaces[0], coefficients=b[0:dof],dual_space=multitrace.dual_to_range_spaces[0])
##
## zero_fun= bempp.api.GridFunction(multitrace.range_spaces[1],coefficients = b[dof:],dual_space=multitrace.dual_to_range_spaces[1])
##
## rhs=[trace_fun,zero_fun]
##
## #print("Still living")
##
#from bempp.api.linalg import gmres
from scipy.sparse.linalg import gmres
print("Start GMRES : ")
# def print_res(rk):
# print("Norm of residual: "+ str(np.linalg.norm(rk)))
#print(np.linalg.norm(lambda_data))
#lambda_data,info = gmres(blocks, b,tol=10**-4,restart=50,maxiter=100,callback=print_res)
lambda_data,info = gmres(blocks, b,tol=10**-5,maxiter=300)
print("INFO :", info)
#lambda_data,info = gmres(blocks, b,tol=10**-4,callback=print_res)
#print("I survived!")
#from bempp.api.linalg import lu
#lambda_data = lu(elec, trace_fun)
#lambda_data.plot()
#print("Norm lambda_data : ",np.linalg.norm(lambda_data))
#if (np.linalg.norm(lambda_data)<10**-10):
phigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[0:dof],dual_space=RT_space)
psigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[dof:2*dof],dual_space=RT_space)
slp_pot = bempp.api.operators.potential.maxwell.electric_field(RT_space, points, s*1j)
dlp_pot = bempp.api.operators.potential.maxwell.magnetic_field(RT_space, points, s*1j)
print("Evaluate field : ")
scattered_field_data = -slp_pot * phigrid+dlp_pot*psigrid
# scattered_field_H = -slp_pot * psigrid-dlp_pot*phigrid
# H = scattered_field_H.reshape(3,1)[:,0]
# print(" E : ", E, " H : ", H)
# print("Angle: ", np.dot(E,H), " Scalar product with conjugation : ", np.dot(np.conj(E),H))
# print("NORM COMBINED OPERATOR :" , np.linalg.norm(scattered_field_data)/np.linalg.norm(b))
# print(scattered_field_data)
# print("NORM ScatteredField :", np.linalg.norm(scattered_field_data))
#
# print("s : ", s)
# print("NORM B :" ,np.linalg.norm(b))
if np.isnan(scattered_field_data).any():
print("NAN Warning, s = ", s)
scattered_field_data=np.zeros(np.shape(scattered_field_data))
return scattered_field_data.reshape(3,1)[:,0]
def scattering_solution(dx,N,T,m):
grid=bempp.api.shapes.sphere(h=dx)
rhs=create_rhs(grid,dx,N,T,m)
def ellipticSystem(s,b):
return harmonic_calderon(s,b,grid)
ScatOperator=Conv_Operator(ellipticSystem)
#num_sol=ScatOperator.apply_convol(rhs,T)
if (m==2):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-5),method="RadauIIA-2")
if (m==3):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-5),method="RadauIIA-3")
num_sol=np.zeros((len(num_solStages[:,0]),N+1))
num_sol[:,1:N+1]=np.real(num_solStages[:,m-1:N*m:m])
return num_sol
import time
T=6
#N_ref=2**4
N_ref=2**11
tt_ref=np.linspace(0,T,N_ref+1)
#dx_ref=np.sqrt(2)**(0)
dx_ref=np.sqrt(2)**(-9)
m=3
import matplotlib.pyplot as plt
start=time.time()
#sol_ref=scattering_solution(dx_ref,N_ref,T)
#sol_ref2=scattering_solution(dx_ref,N_ref,T)
#
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,np.abs(sol_ref[0,:]))
#plt.plot(tt,np.abs(sol_ref[0,:]-sol_ref2[0,:]))
##plt.plot(tt,resc_ref[0,:],linestyle='dashed')
##plt.plot(tt,num_sol[0,:])
#plt.show()
sol_ref=scattering_solution(dx_ref,N_ref,T,m)
#
np.save("data/sol_ref_absorbing_delta0p1_N2h11_dxsqrt2m9RK5.npy",sol_ref)
#sol_ref=np.load("data/sol_ref_absorbing_delta0p1_N2h11_dxsqrt2m10RK5.npy")
#Current Reference solutions:
#np.save("data/sol_ref_absorbing_delta0p1_N212_dxsqrt2m9RK5.npy",sol_ref)
#np.save("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy",sol_ref)
#sol_ref=np.load("data/sol_ref_absorbing_delta1_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_N212_dxsqrt2m7RK5.npy")
#import scipy.io
#scipy.io.loadmat('data/Err_data_delta1.mat')
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,sol_ref[0,:])
#plt.show()
#plt.plot(sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2)
#plt.show()
Am_space=8
Am_time=7
#Am_space=1
#Am_time=8
tau_s=np.zeros(Am_time)
h_s=np.zeros(Am_space)
errors=np.zeros((Am_space,Am_time))
m=2
for ixSpace in range(Am_space):
for ixTime in range(Am_time):
N=8*2**(ixTime)
tau_s[ixTime]=T*1.0/N
tt=np.linspace(0,T,N+1)
dx=np.sqrt(2)**(-ixSpace)
h_s[ixSpace]=dx
########## Rescaling reference solution:
speed=N_ref/N
resc_ref=np.zeros((3,N+1))
# resc_ref=sol_ref
for j in range(N+1):
resc_ref[:,j] = sol_ref[:,j*speed]
#num_sol = calc_ref_sol(N,dx,F_transfer)
num_sol = scattering_solution(dx,N,T,m)
# plt.plot(tt,num_sol[0,:]**2+num_sol[1,:]**2+num_sol[2,:]**2)
# plt.plot(tt_ref,sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2,linestyle='dashed')
# plt.show()
errors[ixSpace,ixTime]=np.max(np.abs(resc_ref-num_sol))
print(errors)
import scipy.io
scipy.io.savemat('data/Err_data_delta01.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
#scipy.io.savemat('data/Err_data_delta0p1_long.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
end=time.time()
print("Script Runtime: "+str((end-start)/60) +" Min")
#
| 11,463 | 34.058104 | 133 | py |
CQMaxwell | CQMaxwell-main/d10RKRefErrorData.py | import bempp.api
import numpy as np
import math
from RKconv_op import *
def create_timepoints(c,N,T):
m=len(c)
time_points=np.zeros((1,m*N))
for j in range(m):
time_points[0,j:m*N:m]=c[j]*1.0/N*np.ones((1,N))+np.linspace(0,1-1.0/N,N)
return T*time_points
def create_rhs(grid,dx,N,T,m):
# grid=bempp.api.shapes.cube(h=1)
#
OrderQF = 7
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
if (m==2):
c_RK=np.array([1.0/3,1])
if (m==3):
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
from bempp.api.operators.boundary import maxwell
from bempp.api.operators.boundary import sparse
multitrace = maxwell.multitrace_operator(grid, 1)
RWG_space = bempp.api.function_space(grid,"RWG",0)
NC_space = bempp.api.function_space(grid,"NC",0)
RT_space = bempp.api.function_space(grid,"RT",0)
#curl_space = bempp.api.function_space(grid, "RBC", 0)
BC_space=bempp.api.function_space(grid, "BC",0)
SNC_space=bempp.api.function_space(grid, "SNC",0)
BRWG_space=bempp.api.function_space(grid, "B-RWG",0)
# div_space=bempp.api.function_space(grid, "B-RWG",0)
RBC_space=bempp.api.function_space(grid,"RBC",0)
# curl_space=bempp.api.function_space(grid,"RBC",0)
#from bempp.api.operators.boundary.sparse import identity as ident
# id1 = ident(div_space,div_space,curl_space).weak_form()
# print("CONDITION NUMBER : ", np.linalg.cond(bempp.api.as_matrix(id1).todense()))
dof=multitrace.range_spaces[0].global_dof_count
dof1=RBC_space.global_dof_count
print(" RWG: ", dof)
print(" RBC: ", dof1)
rhs=np.zeros((dof+dof,N*m))
curls=np.zeros((dof,N*m))
time_points=create_timepoints(c_RK,N,T)
for j in range(m*N):
t=time_points[0,j]
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
#return np.array([np.exp(-200*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
def tangential_trace(x, n, domain_index, result):
result[:] = np.cross(n,np.cross(incident_field(x), n))
def curl_trace(x,n,domain_index,result):
curlU=np.array([ 0. * x[2],-100*(x[2]-t+2)*np.exp(-50*(x[2]-t+2)**2), 0. * x[2]])
result[:] = np.cross(curlU , n)
curl_fun = bempp.api.GridFunction(RT_space, fun=curl_trace,dual_space=RT_space)
trace_fun= bempp.api.GridFunction(RT_space, fun=tangential_trace,dual_space=RT_space)
rhs[0:dof,j]=trace_fun.coefficients
curlCoeffs=curl_fun.coefficients
if np.linalg.norm(curlCoeffs)>10**-9:
curls[0:dof,j]=curlCoeffs
#print("RHS NORM :", np.linalg.norm(trace_fun.coefficients))
def sinv(s,b):
return s**(-1)*b
IntegralOperator=Conv_Operator(sinv)
def HarmonicImpedance(s,b):
return 10*s**(0.5)*b
TimeImpedance=Conv_Operator(HarmonicImpedance)
if (m==2):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
if (m==3):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
rhs[0:dof,:]=np.real(ZptNeuTrace)-rhs[0:dof,:]
return rhs
def harmonic_calderon(s,b,grid):
points=np.array([[0],[0],[2]])
#normb=np.linalg.norm(b[0])+np.linalg.norm(b[1])+np.linalg.norm(b[2])
normb=np.max(np.abs(b))
bound=np.abs(s)**3*np.exp(-s.real*2)*normb
print("s: ",s, " maxb: ", normb, " bound : ", bound)
if bound <10**(-5):
print("JUMPED")
return np.zeros(3)
if normb <10**(-6):
print("JUMPED")
return np.zeros(3)
OrderQF = 7
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-3
bempp.api.global_parameters.hmat.admissibility='strong'
### Define Spaces
NC_space=bempp.api.function_space(grid, "NC",0)
RT_space=bempp.api.function_space(grid, "RT",0)
elec = -bempp.api.operators.boundary.maxwell.electric_field(RT_space, RT_space, NC_space,1j*s)
magn = -bempp.api.operators.boundary.maxwell.magnetic_field(RT_space, RT_space, NC_space, 1j*s)
identity2=bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, RT_space)
identity= -bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, NC_space)
dof=NC_space.global_dof_count
trace_fun= bempp.api.GridFunction(RT_space, coefficients=b[0:dof],dual_space=RT_space)
######## End condition, by theoretical bound:
normb=trace_fun.l2_norm()
bound=np.abs(s)**3*np.exp(-2*s.real)*normb
if bound <10**(-3):
print("JUMPED")
return np.zeros(3)
zero_fun= bempp.api.GridFunction(RT_space,coefficients = b[dof:],dual_space=RT_space)
#rhs=[trace_fun,zero_fun]
id_discrete=identity2.weak_form()
b[0:dof]=id_discrete*b[0:dof]
blocks=np.array([[None,None], [None,None]])
#blocks[0,0] = -elec.weak_form()+10*s**0.5*identity2.weak_form()
blocks[0,0] = -elec.weak_form()+10*s**0.5*identity2.weak_form()
blocks[0,1] = magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,0] = -magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,1] = -elec.weak_form()
blocks=bempp.api.BlockedDiscreteOperator(blocks)
# A_mat=bempp.api.as_matrix(blocks)
# print("A_mat : ",A_mat)
# e,D=np.linalg.eig(A_mat)
# print("Eigs : ", e)
# print("Cond : ", np.linalg.cond(A_mat))
##
## trace_fun= bempp.api.GridFunction(multitrace.range_spaces[0], coefficients=b[0:dof],dual_space=multitrace.dual_to_range_spaces[0])
##
## zero_fun= bempp.api.GridFunction(multitrace.range_spaces[1],coefficients = b[dof:],dual_space=multitrace.dual_to_range_spaces[1])
##
## rhs=[trace_fun,zero_fun]
##
## #print("Still living")
##
#from bempp.api.linalg import gmres
from scipy.sparse.linalg import gmres
print("Start GMRES : ")
# def print_res(rk):
# print("Norm of residual: "+ str(np.linalg.norm(rk)))
#print(np.linalg.norm(lambda_data))
#lambda_data,info = gmres(blocks, b,tol=10**-4,restart=50,maxiter=100,callback=print_res)
lambda_data,info = gmres(blocks, b,tol=10**-4,maxiter=100)
print("INFO :", info)
#lambda_data,info = gmres(blocks, b,tol=10**-4,callback=print_res)
#print("I survived!")
#from bempp.api.linalg import lu
#lambda_data = lu(elec, trace_fun)
#lambda_data.plot()
#print("Norm lambda_data : ",np.linalg.norm(lambda_data))
#if (np.linalg.norm(lambda_data)<10**-10):
phigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[0:dof],dual_space=RT_space)
psigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[dof:2*dof],dual_space=RT_space)
slp_pot = bempp.api.operators.potential.maxwell.electric_field(RT_space, points, s*1j)
dlp_pot = bempp.api.operators.potential.maxwell.magnetic_field(RT_space, points, s*1j)
print("Evaluate field : ")
scattered_field_data = -slp_pot * phigrid+dlp_pot*psigrid
# scattered_field_H = -slp_pot * psigrid-dlp_pot*phigrid
# H = scattered_field_H.reshape(3,1)[:,0]
# print(" E : ", E, " H : ", H)
# print("Angle: ", np.dot(E,H), " Scalar product with conjugation : ", np.dot(np.conj(E),H))
# print("NORM COMBINED OPERATOR :" , np.linalg.norm(scattered_field_data)/np.linalg.norm(b))
# print(scattered_field_data)
# print("NORM ScatteredField :", np.linalg.norm(scattered_field_data))
#
# print("s : ", s)
# print("NORM B :" ,np.linalg.norm(b))
if np.isnan(scattered_field_data).any():
print("NAN Warning, s = ", s)
scattered_field_data=np.zeros(np.shape(scattered_field_data))
return scattered_field_data.reshape(3,1)[:,0]
def scattering_solution(dx,N,T,m):
grid=bempp.api.shapes.sphere(h=dx)
rhs=create_rhs(grid,dx,N,T,m)
def ellipticSystem(s,b):
return harmonic_calderon(s,b,grid)
ScatOperator=Conv_Operator(ellipticSystem)
#num_sol=ScatOperator.apply_convol(rhs,T)
if (m==2):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-4),method="RadauIIA-2")
if (m==3):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-4),method="RadauIIA-3")
num_sol=np.zeros((len(num_solStages[:,0]),N+1))
num_sol[:,1:N+1]=np.real(num_solStages[:,m-1:N*m:m])
return num_sol
import time
T=6
N_ref=2**10
tt_ref=np.linspace(0,T,N_ref+1)
dx_ref=np.sqrt(2)**(-10)
m=3
import matplotlib.pyplot as plt
start=time.time()
#sol_ref=scattering_solution(dx_ref,N_ref,T)
#sol_ref2=scattering_solution(dx_ref,N_ref,T)
#
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,np.abs(sol_ref[0,:]))
#plt.plot(tt,np.abs(sol_ref[0,:]-sol_ref2[0,:]))
##plt.plot(tt,resc_ref[0,:],linestyle='dashed')
##plt.plot(tt,num_sol[0,:])
#plt.show()
sol_ref=scattering_solution(dx_ref,N_ref,T,m)
np.save("data/sol_ref_absorbing_delta10_N2h10_dxsqrt2m10RK5.npy",sol_ref)
#Current Reference solutions:
#np.save("data/sol_ref_absorbing_delta0p1_N212_dxsqrt2m9RK5.npy",sol_ref)
#np.save("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy",sol_ref)
#sol_ref=np.load("data/sol_ref_absorbing_delta1_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_N212_dxsqrt2m7RK5.npy")
#import scipy.io
#scipy.io.loadmat('data/Err_data_delta1.mat')
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,sol_ref[0,:])
#plt.show()
#plt.plot(sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2)
#plt.show()
Am_space=9
Am_time=7
#Am_space=1
#Am_time=8
tau_s=np.zeros(Am_time)
h_s=np.zeros(Am_space)
errors=np.zeros((Am_space,Am_time))
m=2
for ixSpace in range(Am_space):
for ixTime in range(Am_time):
N=8*2**(ixTime)
tau_s[ixTime]=T*1.0/N
tt=np.linspace(0,T,N+1)
dx=np.sqrt(2)**(-ixSpace)
h_s[ixSpace]=dx
########## Rescaling reference solution:
speed=N_ref/N
resc_ref=np.zeros((3,N+1))
# resc_ref=sol_ref
for j in range(N+1):
resc_ref[:,j] = sol_ref[:,j*speed]
#num_sol = calc_ref_sol(N,dx,F_transfer)
num_sol = scattering_solution(dx,N,T,m)
# plt.plot(tt,num_sol[0,:]**2+num_sol[1,:]**2+num_sol[2,:]**2)
# plt.plot(tt_ref,sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2,linestyle='dashed')
# plt.show()
errors[ixSpace,ixTime]=np.max(np.abs(resc_ref-num_sol))
print(errors)
import scipy.io
# scipy.io.savemat('data/Err_data_delta0p1.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
#scipy.io.savemat('data/Err_data_delta0p1_long.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
end=time.time()
print("Script Runtime: "+str((end-start)/60) +" Min")
#
| 11,396 | 33.853211 | 133 | py |
CQMaxwell | CQMaxwell-main/Old Scripts/RKtemp.py | import bempp.api
import math
from RKconv_op import *
print("Bempp version used : " + bempp.api.__version__)
def create_timepoints(c,N,T):
m=len(c)
time_points=np.zeros((1,m*N))
for j in range(m):
time_points[0,j:m*N:m]=c[j]*1.0/N*np.ones((1,N))+np.linspace(0,1-1.0/N,N)
return T*time_points
def create_rhs(grid,dx,N,T,m):
# grid=bempp.api.shapes.cube(h=1)
#
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
if (m==2):
c_RK=np.array([1.0/3,1])
if (m==3):
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
from bempp.api.operators.boundary import maxwell
from bempp.api.operators.boundary import sparse
# multitrace = maxwell.multitrace_operator(grid, 1)
NC_space = bempp.api.function_space(grid,"NC",0)
RT_space = bempp.api.function_space(grid,"RT",0)
#curl_space = bempp.api.function_space(grid, "RBC", 0)
BC_space=bempp.api.function_space(grid, "BC",0)
SNC_space=bempp.api.function_space(grid, "SNC",0)
BRWG_space=bempp.api.function_space(grid, "B-RWG",0)
# div_space=bempp.api.function_space(grid, "B-RWG",0)
RBC_space=bempp.api.function_space(grid,"RBC",0)
# curl_space=bempp.api.function_space(grid,"RBC",0)
#from bempp.api.operators.boundary.sparse import identity as ident
# id1 = ident(div_space,div_space,curl_space).weak_form()
# print("CONDITION NUMBER : ", np.linalg.cond(bempp.api.as_matrix(id1).todense()))
dof=RT_space.global_dof_count
dof1=NC_space.global_dof_count
print(" DOF: ", dof)
rhs=np.zeros((dof+dof,N*m))
curls=np.zeros((dof,N*m))
time_points=create_timepoints(c_RK,N,T)
for j in range(m*N):
t=time_points[0,j]
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
#return np.array([np.exp(-200*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
def tangential_trace(x, n, domain_index, result):
result[:] = np.cross(n,np.cross(incident_field(x), n))
def curl_trace(x,n,domain_index,result):
curlU=np.array([ 0. * x[2],-100*(x[2]-t+2)*np.exp(-50*(x[2]-t+2)**2), 0. * x[2]])
result[:] = np.cross(curlU , n)
curl_fun = bempp.api.GridFunction(RT_space, fun=curl_trace,dual_space=RT_space)
trace_fun= bempp.api.GridFunction(RT_space, fun=tangential_trace,dual_space=RT_space)
rhs[0:dof,j]=trace_fun.coefficients
curlCoeffs=curl_fun.coefficients
if np.linalg.norm(curlCoeffs)>10**-9:
curls[0:dof,j]=curlCoeffs
#print("RHS NORM :", np.linalg.norm(trace_fun.coefficients))
def sinv(s,b):
return s**(-1)*b
IntegralOperator=Conv_Operator(sinv)
def HarmonicImpedance(s,b):
return 10*s**(0.5)*b
TimeImpedance=Conv_Operator(HarmonicImpedance)
if (m==2):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
if (m==3):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
rhs[0:dof,:]=np.real(ZptNeuTrace)-rhs[0:dof,:]
return rhs
def harmonic_calderon(s,b,grid):
points=np.array([[0],[0],[2]])
#normb=np.linalg.norm(b[0])+np.linalg.norm(b[1])+np.linalg.norm(b[2])
normb=np.max(np.abs(b))
bound=np.abs(s)**4*np.exp(-s.real)*normb
print("s: ",s, " maxb: ", normb, " bound : ", bound)
if bound <10**(-9):
print("JUMPED")
return np.zeros(3)
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
### Define Spaces
NC_space=bempp.api.function_space(grid, "NC",0)
RT_space=bempp.api.function_space(grid, "RT",0)
elec = -bempp.api.operators.boundary.maxwell.electric_field(RT_space, RT_space, NC_space,1j*s)
magn = -bempp.api.operators.boundary.maxwell.magnetic_field(RT_space, RT_space, NC_space, 1j*s)
identity2=bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, RT_space)
identity= -bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, NC_space)
dof=NC_space.global_dof_count
trace_fun= bempp.api.GridFunction(RT_space, coefficients=b[0:dof],dual_space=RT_space)
######## End condition, by theoretical bound:
normb=trace_fun.l2_norm()
bound=np.abs(s)**3*np.exp(-s.real)*normb
if bound <10**(-8):
print("JUMPED")
return np.zeros(3)
zero_fun= bempp.api.GridFunction(RT_space,coefficients = b[dof:],dual_space=RT_space)
#rhs=[trace_fun,zero_fun]
id_discrete=identity2.weak_form()
b[0:dof]=id_discrete*b[0:dof]
blocks=np.array([[None,None], [None,None]])
#blocks[0,0] = -elec.weak_form()+10*s**0.5*identity2.weak_form()
blocks[0,0] = -elec.weak_form()+10*s**0.5*identity2.weak_form()
blocks[0,1] = magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,0] = -magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,1] = -elec.weak_form()
blocks=bempp.api.BlockedDiscreteOperator(blocks)
# A_mat=bempp.api.as_matrix(blocks)
# print("A_mat : ",A_mat)
# e,D=np.linalg.eig(A_mat)
# print("Eigs : ", e)
# print("Cond : ", np.linalg.cond(A_mat))
##
## trace_fun= bempp.api.GridFunction(multitrace.range_spaces[0], coefficients=b[0:dof],dual_space=multitrace.dual_to_range_spaces[0])
##
## zero_fun= bempp.api.GridFunction(multitrace.range_spaces[1],coefficients = b[dof:],dual_space=multitrace.dual_to_range_spaces[1])
##
## rhs=[trace_fun,zero_fun]
##
## #print("Still living")
##
#from bempp.api.linalg import gmres
from scipy.sparse.linalg import gmres
print("Start GMRES : ")
# def print_res(rk):
# print("Norm of residual: "+ str(np.linalg.norm(rk)))
#print(np.linalg.norm(lambda_data))
#lambda_data,info = gmres(blocks, b,tol=10**-4,restart=50,maxiter=100,callback=print_res)
lambda_data,info = gmres(blocks, b,tol=10**-5,maxiter=300)
print("INFO :", info)
#lambda_data,info = gmres(blocks, b,tol=10**-4,callback=print_res)
#print("I survived!")
#from bempp.api.linalg import lu
#lambda_data = lu(elec, trace_fun)
#lambda_data.plot()
#print("Norm lambda_data : ",np.linalg.norm(lambda_data))
#if (np.linalg.norm(lambda_data)<10**-10):
phigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[0:dof],dual_space=RT_space)
psigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[dof:2*dof],dual_space=RT_space)
slp_pot = bempp.api.operators.potential.maxwell.electric_field(RT_space, points, s*1j)
dlp_pot = bempp.api.operators.potential.maxwell.magnetic_field(RT_space, points, s*1j)
print("Evaluate field : ")
scattered_field_data = -slp_pot * phigrid+dlp_pot*psigrid
# scattered_field_H = -slp_pot * psigrid-dlp_pot*phigrid
# H = scattered_field_H.reshape(3,1)[:,0]
# print(" E : ", E, " H : ", H)
# print("Angle: ", np.dot(E,H), " Scalar product with conjugation : ", np.dot(np.conj(E),H))
# print("NORM COMBINED OPERATOR :" , np.linalg.norm(scattered_field_data)/np.linalg.norm(b))
# print(scattered_field_data)
# print("NORM ScatteredField :", np.linalg.norm(scattered_field_data))
#
# print("s : ", s)
# print("NORM B :" ,np.linalg.norm(b))
if np.isnan(scattered_field_data).any():
print("NAN Warning, s = ", s)
scattered_field_data=np.zeros(np.shape(scattered_field_data))
return scattered_field_data.reshape(3,1)[:,0]
def scattering_solution(dx,N,T,m):
grid=bempp.api.shapes.sphere(h=dx)
rhs=create_rhs(grid,dx,N,T,m)
def ellipticSystem(s,b):
return harmonic_calderon(s,b,grid)
ScatOperator=Conv_Operator(ellipticSystem)
#num_sol=ScatOperator.apply_convol(rhs,T)
if (m==2):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-7),method="RadauIIA-2")
if (m==3):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-7),method="RadauIIA-3")
num_sol=np.zeros((len(num_solStages[:,0]),N+1))
num_sol[:,1:N+1]=np.real(num_solStages[:,m-1:N*m:m])
return num_sol
import time
T=6
#N_ref=2**4
N_ref=2**8
tt_ref=np.linspace(0,T,N_ref+1)
#dx_ref=np.sqrt(2)**(-4)
dx_ref=np.sqrt(2)**(-0)
m=3
import matplotlib.pyplot as plt
start=time.time()
#sol_ref=scattering_solution(dx_ref,N_ref,T)
#sol_ref2=scattering_solution(dx_ref,N_ref,T)
#
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,np.abs(sol_ref[0,:]))
#plt.plot(tt,np.abs(sol_ref[0,:]-sol_ref2[0,:]))
##plt.plot(tt,resc_ref[0,:],linestyle='dashed')
##plt.plot(tt,num_sol[0,:])
#plt.show()
sol_ref=scattering_solution(dx_ref,N_ref,T,m)
#
#np.save("data/sol_ref_absorbing_delta10_N2h11_dxsqrt2m9RK5.npy",sol_ref)
#sol_ref=np.load("data/sol_ref_absorbing_delta0p1_N2h11_dxsqrt2m10RK5.npy")
#Current Reference solutions:
#np.save("data/sol_ref_absorbing_delta0p1_N212_dxsqrt2m9RK5.npy",sol_ref)
#np.save("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy",sol_ref)
#sol_ref=np.load("data/sol_ref_absorbing_delta1_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_delta001_N212_dxsqrt2m9RK3.npy")
#sol_ref=np.load("data/sol_ref_absorbing_N212_dxsqrt2m7RK5.npy")
#import scipy.io
#scipy.io.loadmat('data/Err_data_delta1.mat')
#tt=np.linspace(0,T,N_ref+1)
#plt.plot(tt,sol_ref[0,:])
#plt.show()
#plt.plot(sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2)
#plt.show()
Am_space=8
Am_time=7
#Am_space=1
#Am_time=8
tau_s=np.zeros(Am_time)
h_s=np.zeros(Am_space)
errors=np.zeros((Am_space,Am_time))
m=2
for ixSpace in range(Am_space):
for ixTime in range(Am_time):
N=8*2**(ixTime)
tau_s[ixTime]=T*1.0/N
tt=np.linspace(0,T,N+1)
dx=np.sqrt(2)**(-ixSpace)
h_s[ixSpace]=dx
########## Rescaling reference solution:
speed=N_ref/N
resc_ref=np.zeros((3,N+1))
# resc_ref=sol_ref
for j in range(N+1):
resc_ref[:,j] = sol_ref[:,j*speed]
#num_sol = calc_ref_sol(N,dx,F_transfer)
num_sol = scattering_solution(dx,N,T,m)
# plt.plot(tt,num_sol[0,:]**2+num_sol[1,:]**2+num_sol[2,:]**2)
# plt.plot(tt_ref,sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2,linestyle='dashed')
# plt.show()
errors[ixSpace,ixTime]=np.max(np.abs(resc_ref-num_sol))
print(errors)
import scipy.io
# scipy.io.savemat('data/Err_data_delta10.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
#scipy.io.savemat('data/Err_data_delta0p1_long.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
end=time.time()
print("Script Runtime: "+str((end-start)/60) +" Min")
#
| 11,384 | 34.247678 | 133 | py |
CQMaxwell | CQMaxwell-main/Old Scripts/load-test.py | import scipy.io
import numpy as np
#v=1j*np.zeros((2,1))
#scipy.io.savemat('data/test.mat',dict(v=v))
mat_contents=scipy.io.loadmat('data/cond.mat')
freqCond=mat_contents['freqCond']
freqs = np.concatenate((freqCond[0,1:],np.conj(freqCond[0,1:])))
conds = np.concatenate((freqCond[1,1:],freqCond[1,1:]))
norms = np.concatenate((freqCond[2,1:],freqCond[2,1:]))
norminvs = np.concatenate((freqCond[3,1:],freqCond[3,1:]))
n=len(freqs)
posImagpart=[]
negImagpart=[]
for j in range(n):
if np.imag(freqs[j])>=0:
posImagpart.append(j)
else:
negImagpart.append(j)
freqsPos=freqs[posImagpart]
condsPos=conds[posImagpart]
normsPos=norms[posImagpart]
norminvsPos=normsinvs[posImagpart]
indicesPos=np.argsort(np.real(freqsPos))
freqsPosOrdered=freqsPos[indicesPos]
condsPosOrdered=condsPos[indicesPos]
normsPosOrdered=normsPos[indicesPos]
norminvsPosOrdered=norminvsPos[indicesPos]
import matplotlib.pyplot as plt
#plt.scatter(np.real(freqsPos),np.imag(freqsPos))
#plt.show()
plt.semilogy(condsPosOrdered,linestyle='-')
#plt.semilogy(np.real(freqsPos))
plt.show()
#v_old=mat_contents['v']
#n=len(v_old[0,:])
#x=1j
#y=1+1j
#v_old=[[],[]]
#v_new=np.concatenate((v_old,np.array([[x],[y]])),axis=1)
##v_new=np.zeros((2,n+1))
##v_new[:,:n]=v_old
##v_new[:,n]=np.array([x,y])
| 1,273 | 23.5 | 64 | py |
CQMaxwell | CQMaxwell-main/Old Scripts/test_RK.py |
import numpy as np
def freq_der(s,b):
return s**1*np.exp(-1*s)*b
import math
from RKconv_op import *
def create_timepoints(c,N,T):
m=len(c)
time_points=np.zeros((1,m*N))
for j in range(m):
time_points[0,j:m*N:m]=c[j]*1.0/N*np.ones((1,N))+np.linspace(0,1-1.0/N,N)
return T*time_points
def create_rhs(N,T,m):
if (m==2):
c_RK=np.array([1.0/3,1])
if (m==3):
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
rhs=np.zeros((1,N*m))
time_points=create_timepoints(c_RK,N,T)
for j in range(m*N):
t=time_points[0,j]
rhs[0,j]=np.sin(t)**6
return rhs
def deriv_solution(N,T,m):
rhs=create_rhs(N,T,m)
def ellipticSystem(s,b):
return harmonic_calderon(s,b,grid)
ScatOperator=Conv_Operator(freq_der)
#num_sol=ScatOperator.apply_convol(rhs,T)
if (m==2):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-8),show_progress=False,method="RadauIIA-2")
if (m==3):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-8),show_progress=False,method="RadauIIA-3")
num_sol=np.zeros((1,N+1))
num_sol[:,1:N+1]=np.real(num_solStages[m-1:N*m:m])
return num_sol
import time
T=2
N_ref=2**12
tt_ref=np.linspace(0,T,N_ref+1)
m=3
sol_ref=deriv_solution(N_ref,T,m)
Am_time=8
#Am_space=1
#Am_time=8
tau_s=np.zeros(Am_time)
errors=np.zeros(Am_time)
m=2
for ixTime in range(Am_time):
N=8*2**(ixTime)
tau_s[ixTime]=T*1.0/N
tt=np.linspace(0,T,N+1)
## Rescaling reference solution:
speed=N_ref/N
resc_ref=np.zeros((3,N+1))
# resc_ref=sol_ref
for j in range(N+1):
resc_ref[:,j] = sol_ref[:,j*speed]
#num_sol = calc_ref_sol(N,dx,F_transfer)
num_sol = deriv_solution(N,T,m)
# plt.plot(tt,num_sol[0,:]**2+num_sol[1,:]**2+num_sol[2,:]**2)
# plt.plot(tt_ref,sol_ref[0,:]**2+sol_ref[1,:]**2+sol_ref[2,:]**2,linestyle='dashed')
#plt.show()
errors[ixTime]=np.max(np.abs(resc_ref-num_sol))
print(errors)
import scipy.io
# scipy.io.savemat('data/Err_data_delta01.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
#scipy.io.savemat('data/Err_data_delta0p1_long.mat', dict( ERR=errors,h_s=h_s,tau_s=tau_s))
#end=time.time()
#print("Script Runtime: "+str((end-start)/60) +" Min")
import matplotlib.pyplot as plt
plt.loglog(tau_s,errors)
plt.loglog(tau_s,tau_s**3,linestyle='dashed')
plt.loglog(tau_s,tau_s**2,linestyle='dashed')
plt.loglog(tau_s,tau_s**1,linestyle='dashed')
plt.show()
| 2,333 | 24.933333 | 106 | py |
CQMaxwell | CQMaxwell-main/Old Scripts/MaxwellFrames.py | import bempp.api
import numpy as np
import math
from RKconv_op import *
def create_timepoints(c,N,T):
m=len(c)
time_points=np.zeros((1,m*N))
for j in range(m):
time_points[0,j:m*N:m]=c[j]*1.0/N*np.ones((1,N))+np.linspace(0,1-1.0/N,N)
return T*time_points
def create_rhs(grid,N,T,m):
#grid=bempp.api.shapes.sphere(h=dx)
if (m==2):
c_RK=np.array([1.0/3,1])
if (m==3):
c_RK=np.array([2.0/5-math.sqrt(6)/10,2.0/5+math.sqrt(6)/10,1])
from bempp.api.operators.boundary import maxwell
RT_space = bempp.api.function_space(grid,"RT",0)
# curl_space=bempp.api.function_space(grid,"RBC",0)
#from bempp.api.operators.boundary.sparse import identity as ident
# id1 = ident(div_space,div_space,curl_space).weak_form()
# print("CONDITION NUMBER : ", np.linalg.cond(bempp.api.as_matrix(id1).todense()))
dof=RT_space.global_dof_count
print(" DOF: ", dof)
rhs=np.zeros((dof+dof,N*m))
curls=np.zeros((dof,N*m))
time_points=create_timepoints(c_RK,N,T)
for j in range(m*N):
t=time_points[0,j]
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+1)**2), 0. * x[2], 0. * x[2]])
#return np.array([np.exp(-200*(x[2]-t+2)**2), 0. * x[2], 0. * x[2]])
def tangential_trace(x, n, domain_index, result):
result[:] = np.cross(n,np.cross(incident_field(x), n))
def curl_trace(x,n,domain_index,result):
curlU=np.array([ 0. * x[2],-100*(x[2]-t+1)*np.exp(-50*(x[2]-t+1)**2), 0. * x[2]])
result[:] = np.cross(curlU , n)
curl_fun = bempp.api.GridFunction(RT_space, fun=curl_trace,dual_space=RT_space)
trace_fun= bempp.api.GridFunction(RT_space, fun=tangential_trace,dual_space=RT_space)
rhs[0:dof,j]=trace_fun.coefficients
curlCoeffs=curl_fun.coefficients
if np.linalg.norm(curlCoeffs)>10**-9:
curls[0:dof,j]=curlCoeffs
#print("RHS NORM :", np.linalg.norm(trace_fun.coefficients))
def sinv(s,b):
return s**(-1)*b
IntegralOperator=Conv_Operator(sinv)
def HarmonicImpedance(s,b):
return 0.1*s**(0.5)*b
TimeImpedance=Conv_Operator(HarmonicImpedance)
if (m==2):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-2",show_progress=False)
if (m==3):
curls=IntegralOperator.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
ZptNeuTrace=TimeImpedance.apply_RKconvol(curls,T,method="RadauIIA-3",show_progress=False)
rhs[0:dof,:]=np.real(ZptNeuTrace)-rhs[0:dof,:]
return rhs
def harmonic_calderon(s,b,grid,points):
OrderQF = 8
#tol= np.finfo(float).eps
bempp.api.global_parameters.quadrature.near.max_rel_dist = 2
bempp.api.global_parameters.quadrature.near.single_order =OrderQF-1
bempp.api.global_parameters.quadrature.near.double_order = OrderQF-1
bempp.api.global_parameters.quadrature.medium.max_rel_dist =4
bempp.api.global_parameters.quadrature.medium.single_order =OrderQF-2
bempp.api.global_parameters.quadrature.medium.double_order =OrderQF-2
bempp.api.global_parameters.quadrature.far.single_order =OrderQF-3
bempp.api.global_parameters.quadrature.far.double_order =OrderQF-3
bempp.api.global_parameters.quadrature.double_singular = OrderQF
bempp.api.global_parameters.hmat.eps=10**-4
bempp.api.global_parameters.hmat.admissibility='strong'
### Define Spaces
NC_space=bempp.api.function_space(grid, "NC",0)
RT_space=bempp.api.function_space(grid, "RT",0)
elec = -bempp.api.operators.boundary.maxwell.electric_field(RT_space, RT_space, NC_space,1j*s)
magn = -bempp.api.operators.boundary.maxwell.magnetic_field(RT_space, RT_space, NC_space, 1j*s)
identity2=bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, RT_space)
identity= -bempp.api.operators.boundary.sparse.identity(RT_space, RT_space, NC_space)
dof=NC_space.global_dof_count
trace_fun= bempp.api.GridFunction(RT_space, coefficients=b[0:dof],dual_space=RT_space)
zero_fun= bempp.api.GridFunction(RT_space,coefficients = b[dof:],dual_space=RT_space)
#rhs=[trace_fun,zero_fun]
id_discrete=identity2.weak_form()
b[0:dof]=id_discrete*b[0:dof]
blocks=np.array([[None,None], [None,None]])
blocks[0,0] = -elec.weak_form()+0.1*s**0.5*identity2.weak_form()
blocks[0,1] = magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,0] = -magn.weak_form()-1.0/2*identity.weak_form()
blocks[1,1] = -elec.weak_form()
blocks=bempp.api.BlockedDiscreteOperator(blocks)
#from bempp.api.linalg import gmres
from scipy.sparse.linalg import gmres
lambda_data,info = gmres(blocks, b,tol=10**-5)
#print(np.linalg.norm(lambda_data))
#print("I survived!")
#from bempp.api.linalg import lu
#lambda_data = lu(elec, trace_fun)
#lambda_data.plot()
#print("Norm lambda_data : ",np.linalg.norm(lambda_data))
#if (np.linalg.norm(lambda_data)<10**-10):
phigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[0:dof],dual_space=RT_space)
psigrid=bempp.api.GridFunction(RT_space,coefficients=lambda_data[dof:2*dof],dual_space=RT_space)
######## Create Points
#
# x_a=-0.75
# x_b=0.75
# y_a=-0.25
# y_b=1.25
##
# x_a=-2
# x_b=2
# y_a=-2
# y_b=2
# n_grid_points=150
################################################
# plot_grid = np.mgrid[y_a:y_b:1j*n_grid_points, x_a:x_b:1j*n_grid_points]
## plot_grid = np.mgrid[-0.5:1:1j*n_grid_points, -1.5:1.5:1j*n_grid_points]
# #print(plot_grid)
## points = np.vstack( ( plot_grid[0].ravel() , plot_grid[1].ravel() , 0.25*np.ones(plot_grid[0].size) ) )
#
# points = np.vstack( ( plot_grid[0].ravel() , 0*np.ones(plot_grid[0].size) , plot_grid[1].ravel()) )
#point=np.array([[0],[0],[2]])
slp_pot = bempp.api.operators.potential.maxwell.electric_field(RT_space, points, s*1j)
dlp_pot = bempp.api.operators.potential.maxwell.magnetic_field(RT_space, points, s*1j)
scattered_field_data = -slp_pot * phigrid+dlp_pot*psigrid
# print("NORM COMBINED OPERATOR :" , np.linalg.norm(scattered_field_data)/np.linalg.norm(b))
# print(scattered_field_data)
# print("NORM ScatteredField :", np.linalg.norm(scattered_field_data))
#
# print("s : ", s)
# print("NORM B :" ,np.linalg.norm(b))
if np.isnan(scattered_field_data).any():
print("NAN Warning",s)
print("NORM B :" ,np.linalg.norm(b))
return np.zeros(n_grid_points**2*3)
#print(scattered_field_data.reshape(3,1)[:,0])
return scattered_field_data.reshape(n_grid_points**2*3,1)[:,0]
def scattering_solution(dx,N,T,m,points):
import scipy.io
import numpy as np
mat_contents=scipy.io.loadmat('grids/TorusDOF896.mat')
Nodes=np.array(mat_contents['Nodes']).T
rawElements=mat_contents['Elements']
for j in range(len(rawElements)):
betw=rawElements[j][0]
rawElements[j][0]=rawElements[j][1]
rawElements[j][1]=betw
Elements=np.array(rawElements).T
Elements=Elements-1
grid=bempp.api.grid_from_element_data(Nodes,Elements)
# def tangential_trace(x, n, domain_index, result):
# result[:] = n[1]
#
# P1_space = bempp.api.function_space(grid,"P",1)
# normal_fun = bempp.api.GridFunction(P1_space, fun=tangential_trace,dual_space=P1_space)
#normal_fun.plot()
#grid.plot()
#grid=bempp.api.shapes.sphere(h=dx)
rhs=create_rhs(grid,N,T,m)
def ellipticSystem(s,b):
return harmonic_calderon(s,b,grid,points)
ScatOperator=Conv_Operator(ellipticSystem)
#num_sol=ScatOperator.apply_convol(rhs,T)
if (m==2):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-8),method="RadauIIA-2")
if (m==3):
num_solStages=ScatOperator.apply_RKconvol(rhs,T,cutoff=10**(-8),method="RadauIIA-3")
num_sol=np.zeros((len(num_solStages[:,0]),N+1))
num_sol[:,1:N+1]=np.real(num_solStages[:,m-1:N*m:m])
return num_sol
import time
N=200
T=4
#Generate points
x_a=-1.5
x_b=1.5
y_a=-1.5
y_b=1.5
n_grid_points=300
nx=n_grid_points
nz=n_grid_points
#######################################
plot_grid = np.mgrid[y_a:y_b:1j*n_grid_points, x_a:x_b:1j*n_grid_points]
#plot_grid = np.mgrid[-0.5:1:1j*n_grid_points, -1.5:1.5:1j*n_grid_points]
#print(plot_grid)
points = np.vstack( ( plot_grid[0].ravel() , 0*np.ones(plot_grid[0].size) , plot_grid[1].ravel()) )
evals=scattering_solution(1,N,T,3,points)
u_ges=np.zeros((n_grid_points**2,N+1))
for j in range(N+1):
#matplotlib inline
import matplotlib
from matplotlib import pylab as plt
# Adjust the figure size in IPython
matplotlib.rcParams['figure.figsize'] = (10.0, 8.0)
# A=points[0]
# B=points[2]
# max_grid=np.zeros((nx,nz))
## for k in range(nz):
## A[k]=A[k]-0.5
## B[k]=B[k]-0.5
## for i in range(nx):
## max_grid[i,k]=max(np.abs(A[i]-0.5),np.abs(B[k]-0.5))
t=j*T*1.0/N
def incident_field(x):
return np.array([np.exp(-50*(x[2]-t+1)**2), 0. * x[2], 0. * x[2]])
incident_field_data = incident_field(points)
#scat_eval=np.zeros(nx*nz*3)
#incident_field_data[radius<1]=np.nan
scat_eval=evals[:,j].reshape(3,nx*nz)
# print(scat_eval)
field_data = scat_eval + incident_field_data
# field_data = scat_eval
# field_data = incident_field_data
# print("Points: ")
# print(points)
# print("Data: ")
#print(field_data)
squared_field_density = np.sum(field_data * field_data,axis = 0)
u_ges[:,j]=squared_field_density.T
#squared_field_density=field_data[2,:]
#squared_field_density[radius<1]=np.nan
#print("MAX FIELD DATA: " , max(squared_field_density))
print(max(np.abs(squared_field_density)))
#plt.imshow(squared_field_density.reshape((nx, nz)).T,
# cmap='coolwarm', origin='lower',
# extent=[x_a, x_b, y_a, y_b])
#if j==10:
# plt.colorbar()
#plt.clim((-1,1))
#plt.title("Squared Electric Field Density")
#plt.savefig("data/wave_images/Screen_n{}.png".format(j))
import scipy.io
scipy.io.savemat('data/delta01_dof896.mat',dict(u_ges=u_ges,N=N,T=T,plot_grid=plot_grid,points=points))
#
| 9,655 | 33 | 113 | py |
Semi-Online-KD | Semi-Online-KD-master/main.py | import argparse
import yaml
import os
import torch
from trainer import build_trainer
from utils.utils import save_code, save_opts
def main():
parser = argparse.ArgumentParser(description='KnowledgeDistillation')
parser.add_argument('--configs', '-c', dest='params', default='./configs/sokd.yaml')
parser.add_argument('--name', '-n', dest='name', default='debug')
parser.add_argument('--seed', '-s', type=int, default=8888)
parser.add_argument('--gpus', '-g', type=str, default='0')
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
with open(args.params) as f:
params = yaml.load(f, Loader=yaml.FullLoader)
params['name'] = args.name
params['seed'] = args.seed
params['device'] = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
trainer = build_trainer(**params)
save_opts(params, trainer.save_folder)
save_code(trainer.repo_path, f"{trainer.save_folder}/code", ['results', 'datasets'])
trainer.run()
trainer.logger.info(f"{trainer.experimental_name} done!")
if __name__ == '__main__':
main()
| 1,116 | 31.852941 | 88 | py |
Semi-Online-KD | Semi-Online-KD-master/trainer/base_trainer.py | from datetime import datetime
from tensorboardX import SummaryWriter
import os
import logging
from utils.utils import create_logger, output_process, fix_random
class BaseTrainer(object):
def __init__(self, experimental_name='debug', seed=None):
# BASE
self.current_time = datetime.now().strftime('%b.%d_%H.%M.%S')
self.writer = None
self.logger = None
self.experimental_name = experimental_name
self.seed = seed
# SAVE PATH
self.repo_path = os.getcwd()
self.save_folder = f'{self.repo_path}/results/{experimental_name}'
output_process(self.save_folder) # create folder or not
self._init_log() # get log and writer
if seed is not None:
fix_random(seed)
def _init_log(self):
self.writer = SummaryWriter(log_dir=self.save_folder)
self.logger = create_logger()
fh = logging.FileHandler(filename=f'{self.save_folder}/log.txt')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
self.logger.addHandler(fh)
| 1,135 | 31.457143 | 93 | py |
Semi-Online-KD | Semi-Online-KD-master/trainer/vanilla.py | import torch.nn as nn
import torch
from tqdm import tqdm
from trainer.base_trainer import BaseTrainer
from models import model_dict
from utils.utils import count_parameters_in_MB, AverageMeter, accuracy, save_checkpoint
from dataset import get_dataloader
class Vanilla(BaseTrainer):
def __init__(self, params, experimental_name=''):
# Data
self.data_name = params.get('data_name')
self.data_path = params.get('data_path')
self.num_classes = params.get('num_classes', 100)
self.train_loader = None
self.test_loader = None
# Model
self.model_name = params.get('model_name')
self.model_depth = params.get('model_depth', '')
self.model_widen = params.get('model_widen', '')
self.model_checkpoint = params.get('model_checkpoint')
self.model = None
self.testing = params.get('evaluation', False)
# Base training settings
self.start_epoch = params.get('start_epoch', 1)
self.epochs = params.get('epochs', 200)
self.batch_size = params.get('batch_size', 128)
self.lr = params.get('lr', 0.1)
self.device = params.get('device', 'cuda')
self.milestones = params.get('milestones', [200])
self.optimizer = None
self.scheduler = None
self.criterion_ce = nn.CrossEntropyLoss()
# Log
self.best_top1 = 0
self.best_top5 = 0
self.best_epoch = 0
seed = params.get('seed', None)
experimental_name = f"{self.__class__.__name__}_{self.model_name}{self.model_depth}-{self.model_widen}_{self.data_name}_" \
f"{experimental_name}/{params.get('name', 'debug')}"
super().__init__(experimental_name, seed)
def run(self):
self.set_data()
self.set_model()
self.set_optimizer_scheduler()
self.train_model()
def train_model(self):
if self.model_checkpoint:
state_dict = torch.load(self.model_checkpoint)
self.model.load_state_dict(state_dict['model'])
self.optimizer.load_state_dict(state_dict['optimizer'])
self.scheduler.load_state_dict(state_dict['scheduler'])
self.best_top1 = state_dict['best_top1']
self.best_top5 = state_dict['best_top5']
self.best_epoch = state_dict['best_epoch']
self.start_epoch = state_dict['start_epoch']
self.logger.info("Load model's checkpoint done!")
if self.testing:
self.logger.info("Start testing model...")
top1, top5 = self.evaluation_vanilla(self.model)
self.logger.info(f"top1:{top1.avg:.2f}, top5:{top5.avg:.2f}")
else:
self.logger.info("Start training model...")
for epoch in tqdm(range(self.start_epoch, self.epochs + 1)):
self.logger.info(f'Epoch[{epoch}/{self.epochs}]')
self.train()
top1, top5 = self.evaluation(self.model)
self.writer.add_scalar('test/top1', top1.avg, epoch)
is_best = False
if top1.avg > self.best_top1:
self.best_top1 = top1.avg
self.best_top5 = top5.avg
self.best_epoch = epoch
is_best = True
state_dict = {'model': self.model.state_dict(),
'optimizer': self.optimizer.state_dict(),
'scheduler': self.scheduler.state_dict(),
'best_top1': self.best_top1,
'best_top5': self.best_top5,
'best_epoch': self.best_epoch,
'start_epoch': epoch
}
save_checkpoint(state_dict, is_best, f"{self.save_folder}/model")
self.logger.info(
f"Test=> lr:{self.optimizer.param_groups[0]['lr']}, "
f"top1:{top1.avg:.2f}, top5:{top5.avg:.2f} "
f"@Best:({self.best_top1}, {self.best_top5}, {self.best_epoch})")
self.scheduler.step()
def train(self):
self.model.train()
total_loss = AverageMeter()
total_top1 = AverageMeter()
total_top5 = AverageMeter()
for batch_id, (data, targets) in enumerate(self.train_loader):
data = data.to(self.device)
targets = targets.to(self.device)
output = self.model(data)
loss = self.criterion_ce(output, targets)
top1, top5 = accuracy(output, targets, topk=(1, 5))
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
total_loss.update(loss.item(), data.size(0))
total_top1.update(top1.item(), data.size(0))
total_top5.update(top5.item(), data.size(0))
info_str = f"Train=> total_loss: {total_loss.avg}, " \
f"prec@1: {total_top1.avg}, prec@5: {total_top5.avg}"
self.logger.info(info_str)
@torch.no_grad()
def evaluation_vanilla(self, model):
model.eval()
total_top1 = AverageMeter()
total_top5 = AverageMeter()
for batch_id, (data, targets) in enumerate(self.test_loader):
data = data.to(self.device)
targets = targets.to(self.device)
output_S = model(data)
top1, top5 = accuracy(output_S, targets, topk=(1, 5))
total_top1.update(top1.item(), data.size(0))
total_top5.update(top5.item(), data.size(0))
return total_top1, total_top5
@torch.no_grad()
def evaluation(self, model):
model.eval()
total_top1 = AverageMeter()
total_top5 = AverageMeter()
for batch_id, (data, targets) in enumerate(self.test_loader):
data = data.to(self.device)
targets = targets.to(self.device)
output_S = model(data)
top1, top5 = accuracy(output_S, targets, topk=(1, 5))
total_top1.update(top1.item(), data.size(0))
total_top5.update(top5.item(), data.size(0))
return total_top1, total_top5
def set_data(self):
self.train_loader, self.test_loader = get_dataloader(self.data_name, self.data_path, self.batch_size)
def set_model(self):
if self.data_name.startswith('CIFAR'):
if self.model_name == 'wideresnet':
self.model = model_dict[f"wrn_{self.model_depth}_{self.model_widen}"](num_classes=self.num_classes)
else:
assert False, f'Not considering {self.model_name}'
if torch.cuda.device_count() > 1:
self.model = torch.nn.DataParallel(self.model)
self.model = self.model.to(self.device)
else:
assert False, f"Not considering {self.data_name}"
def set_optimizer_scheduler(self):
self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.lr, momentum=0.9, weight_decay=5e-4)
self.scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, self.milestones)
| 7,150 | 41.820359 | 131 | py |
Semi-Online-KD | Semi-Online-KD-master/trainer/__init__.py | from trainer.sokd import SemiOnlineKnowledgeDistillation
from trainer.vanilla import Vanilla
def build_trainer(**kwargs):
maps = dict(
sokd=SemiOnlineKnowledgeDistillation,
vanilla=Vanilla,
)
return maps[kwargs['distillation_type']](kwargs)
| 273 | 20.076923 | 56 | py |
Semi-Online-KD | Semi-Online-KD-master/trainer/sokd.py | import torch
from trainer.vanilla import Vanilla
from utils.utils import accuracy, AverageMeter, save_checkpoint
from kd_losses import SoftTarget
from models import model_dict
class SemiOnlineKnowledgeDistillation(Vanilla):
def __init__(self, params):
# Model
self.teacher_name = params.get('teacher_name')
self.teacher_depth = params.get('teacher_depth', '')
self.teacher_widen = params.get('teacher_widen', '')
self.teacher_checkpoint = params.get('teacher_checkpoint')
self.teacher = None
# Coefficient
self.lambda_kd = params.get('lambda_kd', 1)
self.lambda_ce = params.get('lambda_ce', 1)
self.auxiliary_lambda_kd_t = params.get('auxiliary_lambda_kd_t', 1)
self.auxiliary_lambda_kd_s = params.get('auxiliary_lambda_kd_s', 1)
self.auxiliary_lambda_ce = params.get('auxiliary_lambda_ce', 1)
self.lr_auxiliary = params.get('lr_auxiliary', 0.05)
self.distillation_name = params.get('distillation_name', 'soft_target')
self.criterion_kd = SoftTarget(T=4)
self.auxiliary_index = -3
self.best_top1_A = 0
experimental_name = f"Teacher-{self.teacher_name}{self.teacher_depth}-{self.teacher_widen}"
super().__init__(params, experimental_name)
def run(self):
self.set_data()
self.set_model()
self.load_teacher()
self.set_optimizer_scheduler()
self.train_model()
def load_teacher(self):
if self.teacher_name == 'wideresnet':
self.teacher = model_dict[f"wrn_{self.teacher_depth}_{self.teacher_widen}"](
num_classes=self.num_classes)
else:
assert False, f'Not considering {self.teacher_name}'
if torch.cuda.device_count() > 1:
self.teacher = torch.nn.DataParallel(self.teacher)
self.teacher = self.teacher.to(self.device)
if self.teacher_checkpoint:
state = torch.load(self.teacher_checkpoint)['model']
teacher_state_dict = self.teacher.state_dict()
loaded_state = {k: v for k, v in state.items() if k in teacher_state_dict}
teacher_state_dict.update(loaded_state)
self.teacher.load_state_dict(teacher_state_dict)
self.logger.info("Load teacher's checkpoint done!")
else:
self.logger.info("No teacher's checkpoint!")
top1, _ = self.evaluation_vanilla(self.teacher)
self.logger.info(f'Teacher ACC: {top1.avg}')
for k, v in self.teacher.named_parameters():
if 'auxiliary' not in k:
v.requires_grad = False
def train(self):
self.model.train()
self.teacher.train()
# log of student
total_loss = AverageMeter()
total_loss_ce = AverageMeter()
total_loss_kd = AverageMeter()
total_top1 = AverageMeter()
total_top5 = AverageMeter()
# log of auxiliary
total_loss_A = AverageMeter()
total_loss_ce_A = AverageMeter()
total_loss_kd_T_A = AverageMeter()
total_loss_kd_S_A = AverageMeter()
total_top1_A = AverageMeter()
total_top5_A = AverageMeter()
for batch_id, (data, targets) in enumerate(self.train_loader):
data = data.to(self.device)
targets = targets.to(self.device)
feature_S, output_S = self.model(data, is_feat=True)
feature_T, output_T = self.teacher(data, is_feat=True)
feature_A, output_A = self.teacher.auxiliary_forward(feature_T[self.auxiliary_index].detach())
# loss of auxiliary
loss_kd_T_A, loss_kd_S_A, loss_kd = self.calculate_kd(self.distillation_name, feature_S, feature_A,
feature_T, output_S, output_A, output_T)
loss_ce_A = self.criterion_ce(output_A, targets) * self.auxiliary_lambda_ce
loss_A = loss_ce_A + loss_kd_T_A + loss_kd_S_A
# loss of student
loss_ce = self.criterion_ce(output_S, targets) * self.lambda_ce
loss = loss_ce + loss_kd
loss_total = loss_A + loss
# accuracy
top1, top5 = accuracy(output_S, targets, topk=(1, 5))
top1_A, top5_A = accuracy(output_A, targets, topk=(1, 5))
# update parameter of student
self.optimizer.zero_grad()
loss_total.backward()
self.optimizer.step()
# update log of student
total_loss.update(loss.item(), data.size(0))
total_loss_ce.update(loss_ce.item(), data.size(0))
total_loss_kd.update(loss_kd.item(), data.size(0))
total_top1.update(top1.item(), data.size(0))
total_top5.update(top5.item(), data.size(0))
# update log of auxiliary
total_loss_A.update(loss_A.item(), data.size(0))
total_loss_ce_A.update(loss_ce_A.item(), data.size(0))
total_loss_kd_T_A.update(loss_kd_T_A.item(), data.size(0))
total_loss_kd_S_A.update(loss_kd_S_A.item(), data.size(0))
total_top1_A.update(top1_A.item(), data.size(0))
total_top5_A.update(top5_A.item(), data.size(0))
info_str = f"Train (Branch)=> loss_ce: {total_loss_ce_A.avg:.4f}, loss_kd_T_A: {total_loss_kd_T_A.avg:.4f}," \
f"loss_kd_S_A: {total_loss_kd_S_A.avg:.4f}, prec@1: {total_top1_A.avg:.2f}, prec@5: {total_top5_A.avg:.2f}"
self.logger.info(info_str)
info_str = f"Train (Student)=> loss_ce: {total_loss_ce.avg:.4f}, loss_kd: {total_loss_kd.avg:.4f}, " \
f"prec@1: {total_top1.avg:.2f}, prec@5: {total_top5.avg:.2f}"
self.logger.info(info_str)
return total_top1, total_top5
@torch.no_grad()
def evaluation(self, model):
model.eval()
self.teacher.eval()
total_top1 = AverageMeter()
total_top5 = AverageMeter()
total_top1_t = AverageMeter()
total_top5_t = AverageMeter()
for batch_id, (data, targets) in enumerate(self.test_loader):
data = data.to(self.device)
targets = targets.to(self.device)
output_S = model(data)
feature_T, output_T = self.teacher(data, is_feat=True)
_, output_A = self.teacher.auxiliary_forward(feature_T[self.auxiliary_index].detach())
top1, top5 = accuracy(output_S, targets, topk=(1, 5))
total_top1.update(top1.item(), data.size(0))
total_top5.update(top5.item(), data.size(0))
top1_t, top5_t = accuracy(output_A, targets, topk=(1, 5))
total_top1_t.update(top1_t.item(), data.size(0))
total_top5_t.update(top5_t.item(), data.size(0))
if total_top1_t.avg > self.best_top1_A:
self.best_top1_A = total_top1_t.avg
state_dict = {'model': self.teacher.state_dict()}
save_checkpoint(state_dict, True, f"{self.save_folder}/teacher")
self.logger.info(
f"Test (branch)=> lr:{self.optimizer.param_groups[1]['lr']}, "
f"top1_A:{total_top1_t.avg:.2f}, top5_A:{total_top5_t.avg:.2f}, @Best: {self.best_top1_A}")
return total_top1, total_top5
def set_optimizer_scheduler(self):
self.optimizer = torch.optim.SGD([{'params': self.model.parameters()},
{'params': self.teacher.parameters(), 'lr': self.lr_auxiliary}],
lr=self.lr, momentum=0.9, weight_decay=5e-4)
self.scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, self.milestones)
def calculate_kd(self, name, feature_S, feature_A, feature_T, output_S, output_A, output_T):
if name == 'soft_target':
loss_kd_T_A = self.criterion_kd(output_A, output_T.detach()) * self.auxiliary_lambda_kd_t
loss_kd_S_A = self.criterion_kd(output_A, output_S.detach()) * self.auxiliary_lambda_kd_s
loss_S = self.criterion_kd(output_S, output_A.detach()) * self.lambda_kd
else:
assert NotImplementedError, f"No considering {name}"
return loss_kd_T_A, loss_kd_S_A, loss_S
| 8,214 | 46.212644 | 126 | py |
Semi-Online-KD | Semi-Online-KD-master/dataset/__init__.py | from torchvision import transforms
from torchvision import datasets
import torch
def get_dataset(data_name, data_path):
"""
Get dataset according to data name and data path.
"""
transform_train, transform_test = data_transform(data_name)
if data_name.lower() == 'cifar100':
train_dataset = datasets.CIFAR100(data_path, train=True, download=True, transform=transform_train)
test_dataset = datasets.CIFAR100(data_path, train=False, download=True, transform=transform_test)
else:
raise NotImplementedError(f'No considering {data_name}')
return train_dataset, test_dataset
def get_dataloader(data_name, data_path, batch_size):
train_dataset, test_dataset = get_dataset(data_name, data_path)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=2)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=2)
return train_loader, test_loader
def data_transform(data_name):
transform_train, transform_test = None, None
if data_name.lower().startswith('cifar'):
transform_train = transforms.Compose([
transforms.Pad(4, padding_mode='reflect'),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)),
])
transform_test = transforms.Compose([
transforms.CenterCrop(32),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)),
])
else:
assert False
return transform_train, transform_test
| 1,750 | 38.795455 | 113 | py |
Semi-Online-KD | Semi-Online-KD-master/models/__init__.py | from .wrn import wrn_40_1, wrn_40_2
model_dict = {
'wrn_40_1': wrn_40_1,
'wrn_40_2': wrn_40_2
}
| 106 | 12.375 | 35 | py |
Semi-Online-KD | Semi-Online-KD-master/models/wrn.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from copy import deepcopy
__all__ = ['wrn']
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_planes)
self.relu2 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1,
padding=1, bias=False)
self.droprate = dropRate
self.equalInOut = (in_planes == out_planes)
self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,
padding=0, bias=False) or None
def forward(self, x):
if not self.equalInOut:
x = self.relu1(self.bn1(x))
else:
out = self.relu1(self.bn1(x))
out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x)))
if self.droprate > 0:
out = F.dropout(out, p=self.droprate, training=self.training)
out = self.conv2(out)
return torch.add(x if self.equalInOut else self.convShortcut(x), out)
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super(NetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate):
layers = []
for i in range(nb_layers):
layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate))
return nn.Sequential(*layers)
def forward(self, x):
return self.layer(x)
class WideResNet(nn.Module):
def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0):
super(WideResNet, self).__init__()
nChannels = [16, 16 * widen_factor, 32 * widen_factor, 64 * widen_factor]
assert (depth - 4) % 6 == 0, 'depth should be 6n+4'
n = (depth - 4) // 6
block = BasicBlock
# 1st conv before any network block
self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1,
padding=1, bias=False)
# 1st block
self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate)
# 2nd block
self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate)
# 3rd block
self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate)
# global average pooling and classifier
self.bn1 = nn.BatchNorm2d(nChannels[3])
self.relu = nn.ReLU(inplace=True)
self.fc = nn.Linear(nChannels[3], num_classes)
self.nChannels = nChannels[3]
self.auxiliary_block = nn.Sequential(
deepcopy(self.block3)
)
self.auxiliary_bn1 = deepcopy(self.bn1)
self.auxiliary_fc = deepcopy(self.fc)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_()
def get_feat_modules(self):
feat_m = nn.ModuleList([])
feat_m.append(self.conv1)
feat_m.append(self.block1)
feat_m.append(self.block2)
feat_m.append(self.block3)
return feat_m
def get_bn_before_relu(self):
bn1 = self.block2.layer[0].bn1
bn2 = self.block3.layer[0].bn1
bn3 = self.bn1
return [bn1, bn2, bn3]
def forward(self, x, is_feat=False, preact=False):
out = self.conv1(x)
f0 = out
out = self.block1(out)
f1 = out
out = self.block2(out)
f2 = out
out = self.block3(out)
f3 = out
out = self.relu(self.bn1(out))
out = F.avg_pool2d(out, 8)
out = out.view(-1, self.nChannels)
f4 = out
out = self.fc(out)
if is_feat:
if preact:
f1 = self.block2.layer[0].bn1(f1)
f2 = self.block3.layer[0].bn1(f2)
f3 = self.bn1(f3)
return [f0, f1, f2, f3, f4], out
else:
return out
def auxiliary_forward(self, feat):
out = self.auxiliary_block(feat)
f0 = out
out = self.relu(self.auxiliary_bn1(out))
out = F.avg_pool2d(out, 8)
out = out.view(-1, self.nChannels)
f1 = out
out = self.auxiliary_fc(out)
return [f0, f1], out
def wrn(**kwargs):
"""
Constructs a Wide Residual Networks.
"""
model = WideResNet(**kwargs)
return model
def wrn_40_2(**kwargs):
model = WideResNet(depth=40, widen_factor=2, **kwargs)
return model
def wrn_40_1(**kwargs):
model = WideResNet(depth=40, widen_factor=1, **kwargs)
return model
| 5,436 | 33.411392 | 116 | py |
Semi-Online-KD | Semi-Online-KD-master/kd_losses/st.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
class SoftTarget(nn.Module):
'''
Distilling the Knowledge in a Neural Network
https://arxiv.org/pdf/1503.02531.pdf
'''
def __init__(self, T):
super(SoftTarget, self).__init__()
self.T = T
def forward(self, out_s, out_t):
loss = F.kl_div(F.log_softmax(out_s/self.T, dim=1),
F.softmax(out_t/self.T, dim=1),
reduction='batchmean') * self.T * self.T
return loss | 563 | 23.521739 | 53 | py |
Semi-Online-KD | Semi-Online-KD-master/kd_losses/__init__.py | from .st import SoftTarget
| 27 | 13 | 26 | py |
Semi-Online-KD | Semi-Online-KD-master/utils/utils.py | import logging
import colorlog
import os
import time
import shutil
import torch
import random
import numpy as np
from shutil import copyfile
def create_logger():
"""
Setup the logging environment
"""
log = logging.getLogger() # root logger
log.setLevel(logging.DEBUG)
format_str = '%(asctime)s - %(levelname)-8s - %(message)s'
date_format = '%Y-%m-%d %H:%M:%S'
if os.isatty(2):
cformat = '%(log_color)s' + format_str
colors = {'DEBUG': 'reset',
'INFO': 'reset',
'WARNING': 'bold_yellow',
'ERROR': 'bold_red',
'CRITICAL': 'bold_red'}
formatter = colorlog.ColoredFormatter(cformat, date_format,
log_colors=colors)
else:
formatter = logging.Formatter(format_str, date_format)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
return logging.getLogger(__name__)
class TimeRecorder(object):
"""
Recode training time.
"""
def __init__(self, start_epoch, epochs, logger):
self.total_time = 0.
self.remaining_time = 0.
self.epochs = epochs
self.start_epoch = start_epoch
self.logger = logger
self.start_time = time.time()
def update(self):
now_time = time.time()
elapsed_time = now_time - self.start_time
self.start_time = now_time
self.total_time += elapsed_time
self.remaining_time = elapsed_time * (self.epochs - self.start_epoch)
self.start_epoch += 1
self.logger.info(f'Cost time=>{self.format_time(self.total_time)}')
self.logger.info(f'Remaining time=>{self.format_time(self.remaining_time)}')
@staticmethod
def format_time(time):
h = time // 3600
m = (time % 3600) // 60
s = (time % 3600) % 60
return f'{h}h{m}m{s:.2f}s'
def output_process(output_path):
if os.path.exists(output_path):
print("{} file exist!".format(output_path))
action = input("Select Action: d (delete) / q (quit):").lower().strip()
act = action
if act == 'd':
shutil.rmtree(output_path)
else:
raise OSError("Directory {} exits!".format(output_path))
if not os.path.exists(output_path):
os.makedirs(output_path)
def save_code(src, dst, exclude=[]):
"""
Save experimental codes.
"""
for f in os.listdir(src):
# Do not save experimental results
if f in exclude:
continue
src_file = os.path.join(src, f)
file_split = f.split(".")
if len(file_split) >= 2:
if not os.path.isdir(dst):
os.makedirs(dst)
dst_file = os.path.join(dst, f)
try:
shutil.copyfile(src=src_file, dst=dst_file)
except:
print("Copy file error! src: {}, dst: {}".format(src_file, dst_file))
elif os.path.isdir(src_file):
deeper_dst = os.path.join(dst, f)
save_code(src_file, deeper_dst)
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
# res.append(correct_k)
return res
class AverageMeter(object):
"""
Keeps track of most recent, average, sum, and count of a metric.
"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def save_opts(opts, save_path='.'):
with open(f"{save_path}/opts.txt", 'w') as f:
for k, v in opts.items():
f.write(str(k) + ": " + str(v) + '\n')
def save_checkpoint(state_dict, is_best, folder_name='.'):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
checkpoint_name = f"{folder_name}/checkpoint.pth.tar"
torch.save(state_dict, checkpoint_name)
if is_best:
model_name = f"{folder_name}/best_model.pth.tar"
copyfile(checkpoint_name, model_name)
def fix_random(seed=0):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
return True
def count_parameters_in_MB(model):
return sum(np.prod(v.size()) for name, v in model.named_parameters()) / 1e6
| 4,987 | 27.340909 | 85 | py |
Semi-Online-KD | Semi-Online-KD-master/utils/__init__.py | 0 | 0 | 0 | py |
|
Simplified_DMC | Simplified_DMC-master/location_dmc.py | import argparse
import os
import torch
from torch.utils.data import DataLoader
from torch import optim
import numpy as np
from data.MUSIC_dataset import MUSIC_Dataset, MUSIC_AV_Classify
from model.base_model import resnet18
from model.dmc_model import DMC_NET
from sklearn import cluster, metrics
import numpy as np
from sklearn.preprocessing import normalize
from torch import nn
import torch.nn.functional as F
import pickle
def batch_organize(audio_data, posi_img_data, nega_img_data, posi_label, nega_label):
batch_audio_data = torch.zeros(audio_data.shape[0] * 2, audio_data.shape[1], audio_data.shape[2],
audio_data.shape[3])
batch_image_data = torch.zeros(posi_img_data.shape[0] * 2, posi_img_data.shape[1], posi_img_data.shape[2],
posi_img_data.shape[3])
batch_labels = torch.zeros(audio_data.shape[0] * 2)
class_labels = torch.zeros(audio_data.shape[0] * 2)
for i in range(audio_data.shape[0]):
batch_audio_data[i * 2, :] = audio_data[i, :]
batch_audio_data[i * 2 + 1, :] = audio_data[i, :]
batch_image_data[i * 2, :] = posi_img_data[i, :]
batch_image_data[i * 2 + 1, :] = nega_img_data[i, :]
batch_labels[i * 2] = 1
batch_labels[i * 2 + 1] = 0
class_labels[i * 2] = posi_label[i]
class_labels[i * 2 + 1] = nega_label[i]
return batch_audio_data, batch_image_data, batch_labels, class_labels
def eva_metric2(predict, gt, pair_num=2):
num = int(predict.shape[0]/pair_num)
correct = 0
for i in range(num):
pos = predict[pair_num*i]
flag = True
for j in range(pair_num-1):
neg = predict[pair_num*i+j+1]
if pos >= neg:
flag = False
if flag == True:
correct += 1
return correct / num
class ContrastiveLoss(nn.Module):
"""
Contrastive loss
Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise
"""
def __init__(self, margin=5.):
super(ContrastiveLoss, self).__init__()
self.margin = margin
self.eps = 1e-9
def forward(self, output, target, size_average=True):
distances = output.pow(2).sum(1) # squared distances
losses = 0.5 * (target.float() * distances +
(1 + -1 * target).float() * F.relu(self.margin - (distances + self.eps).sqrt()).pow(2))
return losses.mean() if size_average else losses.sum()
def location_model_train(model, data_loader, optimizer, criterion):
model.train()
accs = 0
count = 0
losses = 0
for i, data in enumerate(data_loader, 0):
if i % 200 == 0:
print('location batch:%d' % i)
audio_data, posi_img_data, nega_img_data, posi_label, nega_label, _, _ = data
audio_data, image_data, av_labels, class_labels = batch_organize(audio_data, posi_img_data, nega_img_data, posi_label, nega_label)
audio_data, image_data, av_labels = audio_data.type(torch.FloatTensor).cuda(), \
image_data.type(torch.FloatTensor).cuda(), \
av_labels.type(torch.FloatTensor).cuda()
optimizer.zero_grad()
av_outputs, _, _ = model(image_data, audio_data)
loss = criterion(av_outputs, av_labels)
loss.backward()
optimizer.step()
losses += loss.detach().cpu().numpy()
# acc = eva_metric2(av_outputs.detach().cpu().numpy(), av_labels.cpu().numpy())
# accs += acc
count += 1
print('location loss is %.3f ' % (losses / count))
return accs / count
def location_model_eva(model, data_loader):
model.eval()
accs = 0
num = len(data_loader.dataset)
count = 0
results = {}
with torch.no_grad():
for i, data in enumerate(data_loader, 0):
audio_data, posi_img_data, nega_img_data, posi_label, nega_label, img_path, _ = data
audio_data, image_data, av_labels, class_labels = batch_organize(audio_data, posi_img_data, nega_img_data,
posi_label, nega_label)
audio_data, image_data = audio_data.type(torch.FloatTensor).cuda(), image_data.type(torch.FloatTensor).cuda()
av_outputs, av_maps, av_dists = model(image_data, audio_data)
obj_localization = av_maps.detach().cpu().numpy()
obj_localization = obj_localization[::2]
av_dists = av_dists[::2]
# accs += eva_metric2(av_outputs.detach().cpu().numpy(), av_labels.numpy())
count += 1
_, idx = torch.sort(av_dists, dim=1)
idx = idx[:, 1].detach().cpu().numpy()
for k in range(len(img_path)):
results[img_path[k][:-4]] = obj_localization[k]
pickle.dump(results, open('dmc.pkl', 'wb'))
return accs / count
def main():
parser = argparse.ArgumentParser(description='AID_PRETRAIN')
parser.add_argument('--data_list_dir', type=str,
default='./data/data_indicator/music/solo')
parser.add_argument('--data_dir', type=str, default='/home/ruiq/Music/solo')
parser.add_argument('--mode', type=str, default='train', help='train/val/test')
parser.add_argument('--json_file', type=str,default='./data/MUSIC_label/MUSIC_solo_videos.json')
parser.add_argument('--use_pretrain', type=int, default=0, help='whether to init from ckpt')
parser.add_argument('--ckpt_file', type=str, default='location_net_009_0.665.pth', help='pretrained model name')
parser.add_argument('--enable_img_augmentation', type=int, default=1, help='whether to augment input image')
parser.add_argument('--enable_audio_augmentation', type=int, default=1, help='whether to augment input audio')
parser.add_argument('--batch_size', type=int, default=32, help='training batch size')
parser.add_argument('--learning_rate', type=float, default=1e-4, help='training batch size')
parser.add_argument('--epoch', type=int, default=100, help='training epoch')
parser.add_argument('--gpu_ids', type=str, default='[0,1,2,3]', help='USING GPU IDS e.g.\'[0,4]\'')
parser.add_argument('--num_threads', type=int, default=4, help='number of threads')
parser.add_argument('--seed', type=int, default=10)
parser.add_argument('--evaluate', type=int, default=0, help='only evaluate or not')
parser.add_argument('--v_cluster', type=int, default=2, help='number of visual cluster')
parser.add_argument('--a_cluster', type=int, default=1, help='number of audio cluster')
args = parser.parse_args()
train_list_file = os.path.join(args.data_list_dir, 'solo_training_1.txt')
val_list_file = os.path.join(args.data_list_dir, 'solo_validation.txt')
test_list_file = os.path.join(args.data_list_dir, 'solo_testing.txt')
train_dataset = MUSIC_Dataset(args.data_dir, train_list_file, args)
val_dataset = MUSIC_Dataset(args.data_dir, val_list_file, args)
test_dataset = MUSIC_Dataset(args.data_dir, test_list_file, args)
train_dataloader = DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=True,
num_workers=args.num_threads)
val_dataloader = DataLoader(dataset=val_dataset, batch_size=args.batch_size, shuffle=False,
num_workers=args.num_threads)
test_dataloader = DataLoader(dataset=test_dataset, batch_size=args.batch_size, shuffle=False,
num_workers=args.num_threads)
# net setup
visual_backbone = resnet18(modal='vision',pretrained=False)
audio_backbone = resnet18(modal='audio')
av_model = DMC_NET(visual_net=visual_backbone, audio_net=audio_backbone, v_cluster_num=args.v_cluster, a_cluster_num=args.a_cluster)
if args.use_pretrain:
PATH = args.ckpt_file
state = torch.load(PATH)
av_model.load_state_dict(state, strict=False)
av_model_cuda = av_model.cuda()
loss_func = ContrastiveLoss()
optimizer = optim.Adam(params=av_model_cuda.parameters(), lr=args.learning_rate, betas=(0.9, 0.999),
weight_decay=0.0001)
if args.evaluate:
eva_location_acc = location_model_eva(av_model_cuda, test_dataloader)
return
for e in range(0, args.epoch):
print('Epoch is %03d' % e)
train_location_acc = location_model_train(av_model_cuda, train_dataloader, optimizer, loss_func)
eva_location_acc = location_model_eva(av_model_cuda, test_dataloader)
print('train acc is %.3f, val acc is %.3f' % (train_location_acc, eva_location_acc))
if e % 3 == 0:
PATH = 'ckpt/dmc/dmc_stage_one_%03d_%.3f.pth' % (e, eva_location_acc)
torch.save(av_model_cuda.state_dict(), PATH)
if __name__ == '__main__':
main()
| 8,957 | 41.254717 | 138 | py |
Simplified_DMC | Simplified_DMC-master/data/pair_video_audio.py | import os
import pdb
audio_dir = './MUSIC/solo/audio'
video_dir = './MUSIC/solo/video'
all_audios = os.listdir(audio_dir)
audios = [ audio for audio in all_audios if audio.endswith('.flac')]
all_videos = os.listdir(video_dir)
videos = [video for video in all_videos if video.endswith('.mp4')]
fid = open('solo_pairs.txt','w')
for each in audios:
video = each.replace('.flac', '.mp4')
if video in videos:
fid.write(each+' '+video+'\n')
fid.close()
| 469 | 22.5 | 69 | py |
Simplified_DMC | Simplified_DMC-master/data/MUSIC_dataset.py | import numpy as np
import librosa
from PIL import Image, ImageEnhance
import pickle
import random
import os
import torchvision.transforms as transforms
import json
import torch
def augment_image(image):
if(random.random() < 0.5):
image = image.transpose(Image.FLIP_LEFT_RIGHT)
enhancer = ImageEnhance.Brightness(image)
image = enhancer.enhance(random.random()*0.6 + 0.7)
enhancer = ImageEnhance.Color(image)
image = enhancer.enhance(random.random()*0.6 + 0.7)
return image
class MUSIC_Dataset(object):
def __init__(self, data_root, data_list_file, opt):
# self.root = root
# root = '/mnt/scratch/hudi/MUSIC/solo'
self.opt = opt
self.audio_root = os.path.join(data_root, 'audio_frames')
self.video_root = os.path.join(data_root, 'video_frames')
with open(data_list_file,'r') as fid:
pairs = [line.strip().split(' ') for line in fid.readlines()]
self.sample_label= self._parse_csv(self.opt.json_file)
self.audio_list = []
self.video_list = []
self.label_list = []
for each in pairs:
audio = each[0]
video = each[1]
assert audio[:-5] == video[:-4]
audio_path = os.path.join(self.audio_root, audio[:-5])
video_path = os.path.join(self.video_root, video[:-4])
audio_samples= os.listdir(audio_path)
for item in range(len(audio_samples)):
audio_segment = audio_samples[item]
video_segment = os.path.join(video_path, 'frame_'+audio_segment[:3])
if os.path.exists(video_segment):
self.audio_list.append(os.path.join(audio_path, audio_segment))
self.video_list.append(os.path.join(video_path, video_segment))
if self.opt.mode == 'val' or self.opt.mode == 'test':
img_transform_list = [transforms.Resize((224,224)), transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))]
else:
img_transform_list = [transforms.Resize((256, 256)), transforms.RandomCrop(224), transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))]
self.img_transform = transforms.Compose(img_transform_list)
#self.audio_transform = audio_transform
def __len__(self):
return len(self.audio_list)
def _parse_csv(self, json_file):
f = open(json_file, encoding='utf-8')
content = f.read()
ins_indicator = json.loads(content)
ins_indicator = ins_indicator['videos']
ins_list = [*ins_indicator]
sample_label = {}
pickle.dump(ins_list, open('keylist.pkl', 'wb'))
for i in range(len(ins_list)):
current_list = ins_indicator[ins_list[i]]
for j in range(len(current_list)):
sample_label[current_list[j]] = i
return sample_label
def __getitem__(self, index):
# positive
cur_audio_segment = self.audio_list[index]
posi_video_segment = self.video_list[index]
if self.opt.mode == 'train':
posi_video_segment_img = random.choice(os.listdir(posi_video_segment))
else:
posi_video_segment_img = os.listdir(posi_video_segment)[0]
# load data
with open(cur_audio_segment, 'rb') as fid:
cur_audio_data = pickle.load(fid)
cur_audio_data = np.expand_dims(cur_audio_data, 0)
posi_img_path = os.path.join(posi_video_segment, posi_video_segment_img)
posi_img = Image.open(posi_img_path)
if(self.opt.enable_img_augmentation and self.opt.mode == 'train'):
posi_img = augment_image(posi_img)
posi_img = self.img_transform(posi_img)
posi_label = self.sample_label[posi_video_segment[-28:-17]]
# TODO: here may need normalization
# negative
while(1):
nega_video_segment = random.choice(self.video_list)
if nega_video_segment[-28:-17] != posi_video_segment[-28:-17]:
break
nega_video_segment_img = random.choice(os.listdir(nega_video_segment))
nega_img_path = os.path.join(nega_video_segment, nega_video_segment_img)
nega_img = Image.open(nega_img_path)
if(self.opt.enable_img_augmentation and self.opt.mode == 'train'):
nega_img = augment_image(nega_img)
nega_img = self.img_transform(nega_img)
nega_label = self.sample_label[nega_video_segment[-28:-17]]
if self.opt.mode == 'train':
return cur_audio_data, posi_img, nega_img, posi_label, nega_label, posi_video_segment, cur_audio_segment
return cur_audio_data, posi_img, nega_img, posi_label, nega_label, posi_img_path, cur_audio_segment
class MUSIC_Dataset_(object):
def __init__(self, data_root, data_list_file, opt):
# self.root = root
# root = '/mnt/scratch/hudi/MUSIC/solo'
self.opt = opt
if self.opt.mode == 'train':
self.audio_root = '/home/yuxi/ruiq/AudioVisual/multiple-sound-source-localization/synthesize/train/audio'
self.video_root = '/home/yuxi/ruiq/AudioVisual/multiple-sound-source-localization/synthesize/train/video'
else:
self.audio_root = '/home/yuxi/ruiq/AudioVisual/multiple-sound-source-localization/synthesize/test/audio'
self.video_root = '/home/yuxi/ruiq/AudioVisual/multiple-sound-source-localization/synthesize/test/video'
self.box_root = '/home/yuxi/ruiq/AudioVisual/multiple-sound-source-localization/synthesize/test/box'
self.audio_list = os.listdir(self.audio_root)
self.video_list = os.listdir(self.video_root)
self.box_list = os.listdir(self.box_root)
self.audio_list.sort()
self.video_list.sort()
self.box_list.sort()
assert len(self.audio_list) == len(self.video_list)
if self.opt.mode == 'val' or self.opt.mode == 'test':
img_transform_list = [transforms.Resize((224,224)), transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))]
else:
img_transform_list = [transforms.Resize((256, 256)), transforms.RandomCrop(224), transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))]
self.img_transform = transforms.Compose(img_transform_list)
def __len__(self):
return len(self.audio_list)
def __getitem__(self, index):
# positive
cur_audio_segment = self.audio_list[index]
posi_video_segment = self.video_list[index]
if self.opt.mode == 'val':
box_segment = self.box_list[index]
# load data
with open(os.path.join(self.audio_root, cur_audio_segment), 'rb') as fid:
cur_audio_data = pickle.load(fid)
cur_audio_data = np.expand_dims(cur_audio_data, 0)
posi_img_path = os.path.join(self.video_root, posi_video_segment)
posi_img = Image.open(posi_img_path)
if(self.opt.enable_img_augmentation and self.opt.mode == 'train'):
posi_img = augment_image(posi_img)
posi_img = self.img_transform(posi_img)
while(1):
nega_video_segment = random.choice(self.video_list)
if nega_video_segment != posi_video_segment:
break
nega_img_path = os.path.join(self.video_root, nega_video_segment)
nega_img = Image.open(nega_img_path)
if(self.opt.enable_img_augmentation and self.opt.mode == 'train'):
nega_img = augment_image(nega_img)
nega_img = self.img_transform(nega_img)
if self.opt.mode == 'val':
box = np.load(os.path.join(self.box_root, box_segment))
return cur_audio_data, posi_img, nega_img, torch.tensor(0), torch.tensor(0), torch.tensor(0), box
return cur_audio_data, posi_img, nega_img, torch.tensor(0), torch.tensor(0), torch.tensor(0), torch.tensor(0)
class MUSIC_AV_Classify(object):
def __init__(self, video_dirs, aud_dirs, label, opt):
self.opt = opt
self.video_dirs = video_dirs
self.aud_dirs = aud_dirs
self.label = label
if self.opt.mode == 'val' or self.opt.mode == 'test':
img_transform_list = [transforms.Resize((224,224)), transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))]
else:
img_transform_list = [transforms.Resize((256, 256)), transforms.RandomCrop(224), transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))]
self.img_transform = transforms.Compose(img_transform_list)
def __len__(self):
return len(self.video_dirs)
def __getitem__(self, index):
video_segment_img = random.choice(os.listdir(self.video_dirs[index]))
img_path = os.path.join(self.video_dirs[index], video_segment_img)
img = Image.open(img_path)
if(self.opt.enable_img_augmentation and self.opt.mode == 'train'):
img = augment_image(img)
img_data = self.img_transform(img)
with open(self.aud_dirs[index], 'rb') as fid:
cur_audio_data = pickle.load(fid)
audio_data = np.expand_dims(cur_audio_data, 0)
if self.opt.mode == 'val' or self.opt.mode == 'test':
return audio_data, img_data
else:
return audio_data, img_data, self.label[index] | 9,784 | 42.29646 | 117 | py |
Simplified_DMC | Simplified_DMC-master/data/base_sampler.py | import torch
from torch.utils.data.sampler import Sampler
Class BaseSampler(Sampler):
def __init__(self):
super(BaseSampler,self).__init__()
def __len__(self):
def __iter__(self):
| 203 | 17.545455 | 44 | py |
Simplified_DMC | Simplified_DMC-master/data/cut_audios.py | import numpy as np
import librosa
import pickle
import os
import pdb
with open('data_indicator/music/solo/solo_pairs.txt','r') as fid:
audios = [line.strip().split(' ')[0] for line in fid.readlines()]
audio_dir = './MUSIC/solo/audio'
save_dir = './MUSIC/solo/audio_frames'
#def audio_extract(wav_name, sr=22000):
def audio_extract(wav_name, sr=16000):
#pdb.set_trace()
wav_file = os.path.join(audio_dir, wav_name)
save_path = os.path.join(save_dir, wav_name[:-5])
if not os.path.exists(save_path):
os.mkdir(save_path)
wav, cur_sr = librosa.load(wav_file, sr=sr)
if cur_sr !=sr:
pdb.set_trace()
secs = int(len(wav)/sr)
print(secs)
for i in range(secs):
start = sr * i
end = sr * (i+1)
cur_wav = wav[start:end]
#spec = librosa.core.stft(cur_wav, n_fft=0.01*sr, hop_length=0.005*sr,
# window='hann', center=True, pad_mode='constant')
spec = librosa.core.stft(cur_wav, n_fft=160, hop_length=80,
window='hann', center=True, pad_mode='constant')
#mel = librosa.feature.melspectrogram(S = np.abs(spec), sr=sr, n_mels=256, fmax=sr/2)
mel = librosa.feature.melspectrogram(S = np.abs(spec), sr=sr, n_mels=64, fmax=sr/2)
log_mel = librosa.core.power_to_db(mel)
log_mel_T = log_mel.T.astype('float32')
assert log_mel_T.shape == (201,64)
#pdb.set_trace()
save_name = os.path.join(save_path, '{:03d}.pkl'.format(i))
#print(save_name)
with open(save_name, 'wb') as fid:
pickle.dump(log_mel_T, fid)
for audio in audios:
print(audio)
audio_extract(audio)
#pdb.set_trace()
| 1,685 | 33.408163 | 93 | py |
Simplified_DMC | Simplified_DMC-master/data/data_split.py | import os
import json
solo_videos = './MUSIC_label/MUSIC_solo_videos.json'
solo_videos = json.load(open(solo_videos, 'r'))
solo_videos = solo_videos['videos']
trains = []
vals = []
for _, item in solo_videos.items():
for i, vid in enumerate(item):
if i < 5:
vals.append(vid)
else:
trains.append(vid)
videos = open('./data_indicator/music/solo/solo_pairs.txt', 'r')
train_file = open('./data_indicator/music/solo/solo_training.txt', 'w')
val_file = open('./data_indicator/music/solo/solo_validation.txt', 'w')
while True:
pair = videos.readline()
if len(pair) == 0:
break
vid = pair.split(' ')[0][:-12]
if vid in trains:
train_file.write(pair)
elif vid in vals:
val_file.write(pair)
videos.close()
train_file.close()
val_file.close() | 825 | 24.030303 | 71 | py |
Simplified_DMC | Simplified_DMC-master/data/__init__.py | 2 | 0 | 0 | py |
|
Simplified_DMC | Simplified_DMC-master/data/cut_videos.py | import os
import cv2
import pdb
def video2frame(video_path, frame_save_path, frame_interval=1):
vid = cv2.VideoCapture(video_path)
fps = vid.get(cv2.CAP_PROP_FPS)
#pdb.set_trace()
success, image = vid.read()
count = 0
while success:
count +=1
if count % frame_interval == 0:
#cv2.imencode('.png', image)[1].tofile(frame_save_path+'/fame_%d.png'%count)
save_name = '{}/frame_{}_{}.jpg'.format(frame_save_path, int(count/fps),count)
cv2.imencode('.jpg', image)[1].tofile(save_name)
success, image = vid.read()
print(count)
def video2frame_update(video_path, frame_save_path, frame_kept_per_second=4):
vid = cv2.VideoCapture(video_path)
fps = vid.get(cv2.CAP_PROP_FPS)
video_frames = vid.get(cv2.CAP_PROP_FRAME_COUNT)
video_len = int(video_frames/fps)
print(video_len)
count = 0
frame_interval = int(fps/frame_kept_per_second)
while(count < fps*video_len):
ret, image = vid.read()
if not ret:
break
if count % fps == 0:
frame_id = 0
if frame_id<frame_interval*frame_kept_per_second and frame_id%frame_interval == 0:
#cv2.imencode('.png', image)[1].tofile(frame_save_path+'/fame_%d.png'%count)
save_dir = '{}/frame_{:03d}'.format(frame_save_path, int(count/fps))
if not os.path.exists(save_dir):
os.mkdir(save_dir)
save_name = '{}/frame_{:03d}/{:05d}.jpg'.format(frame_save_path, int(count/fps), count)
cv2.imencode('.jpg', image)[1].tofile(save_name)
frame_id += 1
count += 1
video_dir = './MUSIC/solo/video'
#videos = os.listdir(video_dir)
with open('data_indicator/music/solo/solo_pairs.txt','r') as fid:
videos = [line.strip().split(' ')[1] for line in fid.readlines()]
save_dir = './MUSIC/solo/video_frames'
if not os.path.exists(save_dir):
os.mkdir(save_dir)
vid_count = 0
for each_video in videos:
if not each_video.endswith('.mp4'):
continue
print(each_video)
video_path = os.path.join(video_dir, each_video)
save_path = os.path.join(save_dir, each_video[:-4])
if not os.path.exists(save_path):
os.mkdir(save_path)
video2frame_update(video_path, save_path, frame_kept_per_second=4)
#pdb.set_trace()
print('cut %d videos' % vid_count)
| 2,377 | 32.492958 | 99 | py |
Simplified_DMC | Simplified_DMC-master/model/base_model.py | import torch
import torch.nn as nn
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
if dilation > 1:
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = norm_layer(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = norm_layer(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv1x1(inplanes, width)
self.bn1 = norm_layer(width)
self.conv2 = conv3x3(width, width, stride, groups, dilation)
self.bn2 = norm_layer(width)
self.conv3 = conv1x1(width, planes * self.expansion)
self.bn3 = norm_layer(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, modal, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 64
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
self.modal = modal
self.groups = groups
self.base_width = width_per_group
self.conv1_a = nn.Conv2d(1, self.inplanes, kernel_size=7, stride=2, padding=3,
bias=False)
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0], stride=1)
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
dilate=replace_stride_with_dilation[0])
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
dilate=replace_stride_with_dilation[1])
self.layer4 = self._make_layer(block, 512, layers[3], stride=1,
dilate=replace_stride_with_dilation[2])
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
def _forward_impl(self, x):
# See note [TorchScript super()]
if self.modal == 'audio':
x = self.conv1_a(x)
else:
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
return x
def forward(self, x):
return self._forward_impl(x)
def _resnet(arch, block, layers, pretrained, progress, modal, **kwargs):
model = ResNet(block, layers, modal, **kwargs)
if pretrained:
print('load pretrained res-18')
model.load_state_dict(torch.load('../resnet18-5c106cde.pth'), strict=False)
return model
def resnet18(pretrained=False, progress=True, modal='vision',**kwargs):
r"""ResNet-18 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, modal, **kwargs)
| 9,147 | 38.261803 | 106 | py |
Simplified_DMC | Simplified_DMC-master/model/audio_net.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Unet(nn.Module):
def __init__(self, fc_dim=64, num_downs=5, ngf=64, use_dropout=False):
super(Unet, self).__init__()
# construct unet structure
unet_block = UnetBlock(
ngf * 8, ngf * 8, input_nc=None,
submodule=None, innermost=True)
for i in range(num_downs - 5):
unet_block = UnetBlock(
ngf * 8, ngf * 8, input_nc=None,
submodule=unet_block, use_dropout=use_dropout)
unet_block = UnetBlock(
ngf * 4, ngf * 8, input_nc=None,
submodule=unet_block)
unet_block = UnetBlock(
ngf * 2, ngf * 4, input_nc=None,
submodule=unet_block)
unet_block = UnetBlock(
ngf, ngf * 2, input_nc=None,
submodule=unet_block)
unet_block = UnetBlock(
fc_dim, ngf, input_nc=1,
submodule=unet_block, outermost=True)
self.bn0 = nn.BatchNorm2d(1)
self.unet_block = unet_block
def forward(self, x):
x = self.bn0(x)
x = self.unet_block(x)
return x
# Defines the submodule with skip connection.
# X -------------------identity---------------------- X
# |-- downsampling -- |submodule| -- upsampling --|
class UnetBlock(nn.Module):
def __init__(self, outer_nc, inner_input_nc, input_nc=None,
submodule=None, outermost=False, innermost=False,
use_dropout=False, inner_output_nc=None, noskip=False):
super(UnetBlock, self).__init__()
self.outermost = outermost
self.noskip = noskip
use_bias = False
if input_nc is None:
input_nc = outer_nc
if innermost:
inner_output_nc = inner_input_nc
elif inner_output_nc is None:
inner_output_nc = 2 * inner_input_nc
downrelu = nn.LeakyReLU(0.2, True)
downnorm = nn.BatchNorm2d(inner_input_nc)
uprelu = nn.ReLU(True)
upnorm = nn.BatchNorm2d(outer_nc)
upsample = nn.Upsample(
scale_factor=2, mode='bilinear', align_corners=True)
if outermost:
downconv = nn.Conv2d(
input_nc, inner_input_nc, kernel_size=4,
stride=2, padding=1, bias=use_bias)
upconv = nn.Conv2d(
inner_output_nc, outer_nc, kernel_size=3, padding=1)
down = [downconv]
up = [uprelu, upsample, upconv]
model = down + [submodule] + up
elif innermost:
downconv = nn.Conv2d(
input_nc, inner_input_nc, kernel_size=4,
stride=2, padding=1, bias=use_bias)
upconv = nn.Conv2d(
inner_output_nc, outer_nc, kernel_size=3,
padding=1, bias=use_bias)
down = [downrelu, downconv]
up = [uprelu, upsample, upconv, upnorm]
model = down + up
else:
downconv = nn.Conv2d(
input_nc, inner_input_nc, kernel_size=4,
stride=2, padding=1, bias=use_bias)
upconv = nn.Conv2d(
inner_output_nc, outer_nc, kernel_size=3,
padding=1, bias=use_bias)
down = [downrelu, downconv, downnorm]
up = [uprelu, upsample, upconv, upnorm]
if use_dropout:
model = down + [submodule] + up + [nn.Dropout(0.5)]
else:
model = down + [submodule] + up
self.model = nn.Sequential(*model)
def forward(self, x):
if self.outermost or self.noskip:
return self.model(x)
else:
return torch.cat([x, self.model(x)], 1)
| 3,744 | 33.675926 | 74 | py |
Simplified_DMC | Simplified_DMC-master/model/vision_net.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Resnet(nn.Module):
def __init__(self, original_resnet):
super(Resnet, self).__init__()
self.features = nn.Sequential(
*list(original_resnet.children())[:-1])
# for param in self.features.parameters():
# param.requires_grad = False
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), x.size(1))
return x
class ResnetFC(nn.Module):
def __init__(self, original_resnet, fc_dim=64,
pool_type='maxpool', conv_size=3):
super(ResnetFC, self).__init__()
self.pool_type = pool_type
self.features = nn.Sequential(
*list(original_resnet.children())[:-2])
self.fc = nn.Conv2d(
512, fc_dim, kernel_size=conv_size, padding=conv_size//2)
def forward(self, x, pool=True):
x = self.features(x)
x = self.fc(x)
if not pool:
return x
if self.pool_type == 'avgpool':
x = F.adaptive_avg_pool2d(x, 1)
elif self.pool_type == 'maxpool':
x = F.adaptive_max_pool2d(x, 1)
x = x.view(x.size(0), x.size(1))
return x
def forward_multiframe(self, x, pool=True):
(B, C, T, H, W) = x.size()
x = x.permute(0, 2, 1, 3, 4).contiguous()
x = x.view(B*T, C, H, W)
x = self.features(x)
x = self.fc(x)
(_, C, H, W) = x.size()
x = x.view(B, T, C, H, W)
x = x.permute(0, 2, 1, 3, 4)
if not pool:
return x
if self.pool_type == 'avgpool':
x = F.adaptive_avg_pool3d(x, 1)
elif self.pool_type == 'maxpool':
x = F.adaptive_max_pool3d(x, 1)
x = x.view(B, C)
return x
class ResnetDilated(nn.Module):
def __init__(self, orig_resnet, fc_dim=64, pool_type='maxpool',
dilate_scale=16, conv_size=3):
super(ResnetDilated, self).__init__()
from functools import partial
self.pool_type = pool_type
if dilate_scale == 8:
orig_resnet.layer3.apply(
partial(self._nostride_dilate, dilate=2))
orig_resnet.layer4.apply(
partial(self._nostride_dilate, dilate=4))
elif dilate_scale == 16:
orig_resnet.layer4.apply(
partial(self._nostride_dilate, dilate=2))
self.features = nn.Sequential(
*list(orig_resnet.children())[:-2])
self.fc = nn.Conv2d(
512, fc_dim, kernel_size=conv_size, padding=conv_size//2)
def _nostride_dilate(self, m, dilate):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
# the convolution with stride
if m.stride == (2, 2):
m.stride = (1, 1)
if m.kernel_size == (3, 3):
m.dilation = (dilate//2, dilate//2)
m.padding = (dilate//2, dilate//2)
# other convoluions
else:
if m.kernel_size == (3, 3):
m.dilation = (dilate, dilate)
m.padding = (dilate, dilate)
def forward(self, x, pool=True):
x = self.features(x)
x = self.fc(x)
if not pool:
return x
if self.pool_type == 'avgpool':
x = F.adaptive_avg_pool2d(x, 1)
elif self.pool_type == 'maxpool':
x = F.adaptive_max_pool2d(x, 1)
x = x.view(x.size(0), x.size(1))
return x
def forward_multiframe(self, x, pool=True):
(B, C, T, H, W) = x.size()
x = x.permute(0, 2, 1, 3, 4).contiguous()
x = x.view(B*T, C, H, W)
x = self.features(x)
x = self.fc(x)
(_, C, H, W) = x.size()
x = x.view(B, T, C, H, W)
x = x.permute(0, 2, 1, 3, 4)
if not pool:
return x
if self.pool_type == 'avgpool':
x = F.adaptive_avg_pool3d(x, 1)
elif self.pool_type == 'maxpool':
x = F.adaptive_max_pool3d(x, 1)
x = x.view(B, C)
return x
| 4,152 | 27.445205 | 69 | py |
Simplified_DMC | Simplified_DMC-master/model/base_model_v1.py | import torch
import torch.nn as nn
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
if dilation > 1:
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = norm_layer(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = norm_layer(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv1x1(inplanes, width)
self.bn1 = norm_layer(width)
self.conv2 = conv3x3(width, width, stride, groups, dilation)
self.bn2 = norm_layer(width)
self.conv3 = conv1x1(width, planes * self.expansion)
self.bn3 = norm_layer(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, modal, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 64
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
self.modal = modal
self.groups = groups
self.base_width = width_per_group
self.conv1_a = nn.Conv2d(1, self.inplanes, kernel_size=3, stride=2, padding=3,
bias=False)
self.conv1_v = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0], stride=2)
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
dilate=replace_stride_with_dilation[0])
self.layer3 = self._make_layer(block, 256, layers[2], stride=1,
dilate=replace_stride_with_dilation[1])
self.layer4 = self._make_layer(block, 512, layers[3], stride=1,
dilate=replace_stride_with_dilation[2])
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
def _forward_impl(self, x):
# See note [TorchScript super()]
if self.modal == 'audio':
x = self.conv1_a(x)
else:
x = self.conv1_v(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
return x
def forward(self, x):
return self._forward_impl(x)
def _resnet(arch, block, layers, pretrained, progress, modal, **kwargs):
model = ResNet(block, layers, modal, **kwargs)
return model
def resnet18(pretrained=False, progress=True, modal='vision',**kwargs):
r"""ResNet-18 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, modal, **kwargs)
| 9,008 | 38.169565 | 106 | py |
Simplified_DMC | Simplified_DMC-master/model/dmc_model.py | import torch
import torch.nn as nn
import random
class Cluster_layer(nn.Module):
def __init__(self, input_dim = 512, num_cluster=2, iters=4, beta=-30, **kwargs):
super(Cluster_layer, self).__init__()
self.input_dim = input_dim
self.num_cluster = num_cluster
self.iters = iters
self.beta = beta
self.epsilon = torch.tensor(1e-10).type(torch.FloatTensor)#.cuda()
def forward(self, u_vecs):
(batch_size, input_num, feature_dim) = u_vecs.size()
ini_interval = int(input_num/self.num_cluster) #
o = torch.unsqueeze(u_vecs[:, 0, :], dim=1)
count = 1
while(self.num_cluster-count > 0):
current_o = torch.unsqueeze(u_vecs[:, ini_interval*count, :], dim=1) #ini_interval*count
o = torch.cat([o, current_o], dim=1)
count += 1
for i in range(self.iters):
nx = torch.sum(o**2, dim=2, keepdim=True)
ny = torch.sum(u_vecs**2, dim=2, keepdim=True)
qq = nx - 2 * torch.bmm(o, u_vecs.permute(0,2,1)) + ny.permute(0,2,1)
b = torch.sqrt(torch.max(qq, self.epsilon))
c = nn.functional.softmax(self.beta*b, dim=1) # assignments [None, output_num_capsule, input_num_capsule]
o = torch.bmm(c, u_vecs) # cluster centers [None, num_cluster, dim_cluster]
weights = torch.sum(c, dim=2, keepdim=True)
o = o / weights
return o, c
class DMC_NET(nn.Module):
def __init__(self, visual_net, audio_net, v_cluster_num = 4, a_cluster_num = 2):
super(DMC_NET, self).__init__()
# backbone net
self.visual_net = visual_net
self.audio_net = audio_net
self.pooling = nn.AdaptiveAvgPool2d((1, 1))
# visual ops
self.fc_v_1 = nn.Linear(512, 512)
self.fc_v_2 = nn.Linear(128, 128)
# audio ops
self.pooling_a = nn.AdaptiveMaxPool2d((1, 1))
self.fc_a_1 = nn.Linear(512, 512)
self.fc_a_2 = nn.Linear(128, 128)
self.relu = nn.ReLU(inplace=True)
# fusion ops
self.fc_av = nn.Linear(1, 2)
self.v_clustering = Cluster_layer(num_cluster=v_cluster_num)
self.a_clustering = Cluster_layer(num_cluster=a_cluster_num)
self.epsilon = torch.tensor(1e-10).type(torch.FloatTensor)#.cuda()
def forward(self, v_input, a_input):
# visual pathway
v_fea = self.visual_net(v_input)
(B, C, H, W) = v_fea.size()
v_fea = v_fea.view(B, C, H*W)
v_fea = v_fea.permute(0,2,1)
v_fea = self.fc_v_1(v_fea)
v_centers, v_assign = self.v_clustering(v_fea)
# audio pathway
a_fea = self.audio_net(a_input)
(B, C, H, W) = a_fea.size()
a_fea = a_fea.view(B, C, H*W)
a_fea = a_fea.permute(0,2,1)
a_fea = self.fc_a_1(a_fea)
a_centers, a_assign = self.a_clustering(a_fea)
v_centers_ = torch.sum(v_centers ** 2, dim=2, keepdim=True)
a_centers_ = torch.sum(a_centers ** 2, dim=2, keepdim=True)
distance_ = torch.sqrt(torch.max(v_centers_ - 2 * torch.bmm(v_centers, a_centers.permute(0, 2, 1)) + a_centers_.permute(0, 2, 1), self.epsilon))
distance = torch.min(distance_, dim=1)
distance = distance.values
return distance, v_assign, distance_ | 3,338 | 35.293478 | 152 | py |
Simplified_DMC | Simplified_DMC-master/model/__init__.py | 1 | 0 | 0 | py |
|
synfeal | synfeal-main/utils.py | import numpy as np
import os
import cv2
import torch
import torch
import math
import yaml
from sklearn.metrics import mean_squared_error
from torchsummary import summary
from yaml.loader import SafeLoader
from colorama import Fore
from scipy.spatial.transform import Rotation as R
from models.loss_functions import BetaLoss, DynamicLoss
from models.posenet import PoseNetGoogleNet, PoseNetResNet
from models.poselstm import PoseLSTM
from models.hourglass import HourglassBatch
from synfeal_collection.src.pypcd_no_ros import PointCloud
def write_pcd(filename, msg, mode='binary'):
pc = PointCloud.from_msg(msg)
pc.save_pcd(filename, compression=mode)
def read_pcd(filename):
if not os.path.isfile(filename):
raise Exception("[read_pcd] File does not exist.")
pc = PointCloud.from_path(filename)
return pc
def write_transformation(filename, transformation):
np.savetxt(filename, transformation, delimiter=',',fmt='%.5f')
def write_img(filename, img):
cv2.imwrite(filename, img)
def matrixToRodrigues(matrix):
rods, _ = cv2.Rodrigues(matrix[0:3, 0:3])
rods = rods.transpose()
rodrigues = rods[0]
return rodrigues
def matrixToQuaternion(matrix):
rot_matrix = matrix[0:3, 0:3]
r = R.from_matrix(rot_matrix)
return r.as_quat()
def matrixToXYZ(matrix):
return matrix[0:3,3]
def rodriguesToMatrix(r):
rod = np.array(r, dtype=np.float)
matrix = cv2.Rodrigues(rod)
return matrix[0]
def quaternionToMatrix(quat):
return R.from_quat(quat).as_matrix()
def poseToMatrix(pose):
matrix = np.zeros((4,4))
rot_mat = quaternionToMatrix(pose[3:])
trans = pose[:3]
matrix[0:3,0:3] = rot_mat
matrix[0:3,3] = trans
matrix[3,3] = 1
return matrix
def write_intrinsic(filename, data):
matrix = np.zeros((3,3))
matrix[0,0] = data[0]
matrix[0,1] = data[1]
matrix[0,2] = data[2]
matrix[1,0] = data[3]
matrix[1,1] = data[4]
matrix[1,2] = data[5]
matrix[2,0] = data[6]
matrix[2,1] = data[7]
matrix[2,2] = data[8]
np.savetxt(filename, matrix, delimiter=',',fmt='%.5f')
def rotationAndpositionToMatrix44(rotation, position):
matrix44 = np.empty(shape=(4,4))
matrix44[:3,:3] = rotation
matrix44[:3,3] = position
matrix44[3,:3] = 0
matrix44[3,3] = 1
return matrix44
def matrix44_to_pose(matrix44):
quaternion = matrixToQuaternion(matrix44)
quaternion = normalize_quat(quaternion)
xyz = matrixToXYZ(matrix44)
pose = np.append(xyz, quaternion)
return pose
def compute_position_error(pred, targ):
pred = pred[:3]
targ = targ[:3]
return mean_squared_error(pred, targ, squared=False) # RMSE
def compute_rotation_error(pred, targ):
## second way: using rodrigues (like ATOM) --> better because angle ranges from 0 to pi (whereas with quaterions ranges from 0 to 2pi)
## https://github.com/lardemua/atom/blob/284b7943e467e53a3258de6f673cf852b07654cb/atom_evaluation/scripts/camera_to_camera_evalutation.py#L290
pred_matrix = poseToMatrix(pred)
targ_matrix = poseToMatrix(targ)
delta = np.dot(np.linalg.inv(pred_matrix), targ_matrix)
deltaR = matrixToRodrigues(delta[0:3, 0:3])
return np.linalg.norm(deltaR)
def normalize_quat(x, p=2, dim=1):
"""
Divides a tensor along a certain dim by the Lp norm
:param x:
:param p: Lp norm
:param dim: Dimension to normalize along
:return:
"""
if torch.is_tensor(x):
# x.shape = (N,4)
xn = x.norm(p=p, dim=dim) # computes the norm: 1xN
x = x / xn.unsqueeze(dim=dim)
else: # numpy
xn = np.linalg.norm(x)
x = x/xn
return x
def summarizeModel(model, input_example):
model.cuda()
summary(model, input_size=input_example.shape)
model.cpu()
def resumeTraining(folder_name):
model_name = [f for f in os.listdir(folder_name) if f.endswith('.pth')][0] # get first in the list of files that have extension .pth
file_name = f'{folder_name}/config.yaml'
with open(file_name) as f:
config = yaml.load(f, Loader=SafeLoader)
model = eval(config['init_model'])
model.load_state_dict(torch.load(f'{folder_name}/{model_name}'))
start_epoch = config['epoch']
train_losses = config['train_losses']
test_losses = config['test_losses']
print(f'{Fore.BLUE} Resuming training of model from epoch: {start_epoch} {Fore.RESET}')
return start_epoch, train_losses, test_losses, model
def process_pose(pose):
quat_unit = normalize_quat(pose[:,3:])
return torch.cat((pose[:,:3], quat_unit), dim=1)
def projectToCamera(intrinsic_matrix, distortion, width, height, pts):
"""
Projects a list of points to the camera defined transform, intrinsics and distortion
:param intrinsic_matrix: 3x3 intrinsic camera matrix
:param distortion: should be as follows: (k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])
:param width: the image width
:param height: the image height
:param pts: a list of point coordinates (in the camera frame) with the following format: np array 4xn or 3xn
:return: a list of pixel coordinates with the same length as pts
"""
_, n_pts = pts.shape
# Project the 3D points in the camera's frame to image pixels
# From https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
pixs = np.zeros((2, n_pts), dtype=np.float)
k1, k2, p1, p2, k3 = distortion
# fx, _, cx, _, fy, cy, _, _, _ = intrinsic_matrix
# print('intrinsic=\n' + str(intrinsic_matrix))
fx = intrinsic_matrix[0, 0]
fy = intrinsic_matrix[1, 1]
cx = intrinsic_matrix[0, 2]
cy = intrinsic_matrix[1, 2]
x = pts[0, :]
y = pts[1, :]
z = pts[2, :]
dists = np.linalg.norm(pts[0:3, :], axis=0) # compute distances from point to camera
xl = np.divide(x, z) # compute homogeneous coordinates
yl = np.divide(y, z) # compute homogeneous coordinates
r2 = xl ** 2 + yl ** 2 # r square (used multiple times bellow)
xll = xl * (1 + k1 * r2 + k2 * r2 ** 2 + k3 * r2 ** 3) + 2 * p1 * xl * yl + p2 * (r2 + 2 * xl ** 2)
yll = yl * (1 + k1 * r2 + k2 * r2 ** 2 + k3 * r2 ** 3) + p1 * (r2 + 2 * yl ** 2) + 2 * p2 * xl * yl
pixs[0, :] = fx * xll + cx
pixs[1, :] = fy * yll + cy
# Compute mask of valid projections
valid_z = z > 0
valid_xpix = np.logical_and(pixs[0, :] >= 0, pixs[0, :] < width)
valid_ypix = np.logical_and(pixs[1, :] >= 0, pixs[1, :] < height)
valid_pixs = np.logical_and(valid_z, np.logical_and(valid_xpix, valid_ypix))
return pixs, valid_pixs, dists
def synthesize_pose(pose1, pose2):
"""
synthesize pose between pose1 and pose2
pose1: 4x4
pose2: 4x4
"""
pos1 = pose1[:3,3]
rot1 = pose1[:3,:3]
pos2 = pose2[:3,3]
rot2 = pose2[:3,:3]
# rot3x3 to euler angles
rot1_euler = R.from_matrix(rot1).as_euler('xyz', degrees=False)
rot2_euler = R.from_matrix(rot2).as_euler('xyz', degrees=False)
pos3 = (pos1 + pos2) / 2
rot3_euler = (rot1_euler + rot2_euler) / 2
rot3 = R.from_euler('xyz', rot3_euler, degrees=False).as_matrix()
pose3 = np.zeros(shape=(4,4))
pose3[:3,:3] = rot3
pose3[:3,3] = pos3
pose3[-1,-1] = 1
return pose3
def applyNoise(matrix44, pos_error, rot_error):
xyz = matrixToXYZ(matrix44)
euler = R.from_quat(matrixToQuaternion(matrix44)).as_euler('xyz', 'degrees')
# adapted from ATOM
v = np.random.uniform(-1.0, 1.0, 3)
v = v / np.linalg.norm(v)
new_xyz = xyz + v * (pos_error*math.sqrt(3))
v = np.random.choice([-1.0, 1.0], 3) * (rot_error/math.sqrt(3))
new_euler = euler + v
rotation_angles = R.from_euler('xyz', new_euler, degrees=True).as_matrix()
new_matrix44 = rotationAndpositionToMatrix44(rotation=rotation_angles, position=new_xyz)
return new_matrix44 | 7,993 | 29.51145 | 146 | py |
synfeal | synfeal-main/dataset.py | import cv2
import torch.utils.data as data
import numpy as np
import torch
import os
import yaml
from PIL import Image
from yaml.loader import SafeLoader
from utils import read_pcd, matrixToXYZ, matrixToQuaternion, normalize_quat
# pytorch datasets: https://pytorch.org/tutorials/beginner/basics/data_tutorial.html
class Dataset(data.Dataset):
def __init__(self, path_seq, rgb_transform = None, depth_transform = None, inputs = None):
self.root = f'{os.environ.get("SYNFEAL_DATASET")}/datasets/localbot'
self.seq = path_seq
self.path_seq = f'{self.root}/{path_seq}'
self.rgb_transform = rgb_transform
self.depth_transform = depth_transform
if inputs == None:
self.inputs = ['point_cloud', 'depth_image', 'rgb_image']
else:
self.inputs = inputs
config = self.getConfig()
if 'statistics' in config:
self.depth_mean = config['statistics']['D']['mean']
self.depth_std = config['statistics']['D']['std']
def __getitem__(self, index):
output = []
if 'point_cloud' in self.inputs:
# load point cloud
pc_raw = read_pcd(f'{self.path_seq}/frame-{index:05d}.pcd')
point_set = np.vstack([pc_raw.pc_data['x'], pc_raw.pc_data['y'], pc_raw.pc_data['z']]).T # stays NX3
point_set = torch.from_numpy(point_set.astype(np.float32))
output.append(point_set)
if 'depth_image' in self.inputs:
# load depth image
depth_image = cv2.imread(f'{self.path_seq}/frame-{index:05d}.depth.png', cv2.IMREAD_UNCHANGED)
depth_image = depth_image.astype(np.float32) / 1000.0 # to meters
depth_image = Image.fromarray(depth_image)
if self.depth_transform!=None:
depth_image = self.depth_transform(depth_image)
output.append(depth_image)
if 'rgb_image' in self.inputs:
# TODO: change this to the correct dataset
rgb_image = Image.open(f'{self.path_seq}/frame-{index:05d}.rgb.png')
if self.rgb_transform != None:
rgb_image = self.rgb_transform(rgb_image)
output.append(rgb_image)
# load pose
matrix = np.loadtxt(f'{self.path_seq}/frame-{index:05d}.pose.txt', delimiter=',')
quaternion = matrixToQuaternion(matrix)
quaternion = normalize_quat(quaternion)
xyz = matrixToXYZ(matrix)
pose = np.append(xyz, quaternion)
pose = torch.from_numpy(pose.astype(np.float32))
output.append(pose)
return tuple(output)
def __len__(self):
return sum(f.endswith('pose.txt') for f in os.listdir(self.path_seq))
def getConfig(self):
with open(f'{self.path_seq}/config.yaml') as f:
config = yaml.load(f, Loader=SafeLoader)
return config
def setConfig(self, config):
with open(f'{self.path_seq}/config.yaml', 'w') as f:
yaml.dump(config, f)
# config_stats = Dataset('seq5',depth_transform=None ,rgb_transform=None, inputs=['depth_image']).getConfig()['statistics']
# rgb_mean = [config_stats['R']['mean'], config_stats['G']['mean'], config_stats['B']['mean']]
# rgb_std = [config_stats['R']['std'], config_stats['G']['std'], config_stats['B']['std']]
# depth_mean = config_stats['D']['mean']
# depth_std = config_stats['D']['std']
# print(depth_mean)
# depth_transform_train = transforms.Compose([
# transforms.Resize(300),
# transforms.CenterCrop(299),
# transforms.ToTensor(),
# transforms.Normalize(mean=(depth_mean,), std=(depth_std,))
# ])
# rgb_transform_train = transforms.Compose([
# transforms.Resize(300),
# transforms.RandomCrop(299),
# transforms.ToTensor(),
# transforms.Normalize(rgb_mean, rgb_std)
# ])
# rgb_transform_test = transforms.Compose([
# transforms.Resize(300),
# transforms.CenterCrop(299),
# transforms.ToTensor(),
# transforms.Normalize(rgb_mean, rgb_std)
# ])
# dataset = Dataset('seq6',depth_transform=depth_transform_train ,rgb_transform=rgb_transform_train, inputs=['depth_image', 'rgb_image'])
# for i in range(100,110):
# print(f'depth size: {dataset[i][0].shape}')
# print(f'rgb size: {dataset[i][1].shape}')
# print(f'depth mean: {np.mean(dataset[i][0].numpy())}')
# print(f'rgb mean: {np.mean(dataset[i][1].numpy())}')
| 4,547 | 34.53125 | 137 | py |
synfeal | synfeal-main/utils_ros.py | import copy
import math
import tf
import rospy
import os
from geometry_msgs.msg import Pose, Point
from visualization_msgs.msg import *
from std_msgs.msg import Header, ColorRGBA
from synfeal_collection.src.pypcd import PointCloud
def write_pcd(filename, msg, mode='binary'):
pc = PointCloud.from_msg(msg)
pc.save_pcd(filename, compression=mode)
def read_pcd(filename):
if not os.path.isfile(filename):
raise Exception("[read_pcd] File does not exist.")
pc = PointCloud.from_path(filename)
return pc
def data2pose(data):
if type(data) is str:
data = list(data)
lst_data = [i for i in data if i!=','] # remove ','
data = {'x' : lst_data[0],
'y' : lst_data[1],
'z' : lst_data[2],
'rx' : lst_data[3],
'ry' : lst_data[4],
'rz' : lst_data[5]}
quaternion = tf.transformations.quaternion_from_euler(data['rx'], data['ry'], data['rz'])
#quaternion = R.from_euler('xyz',[[data['rx'], data['ry'], data['rz']]], degrees=False).as_quat()
p = Pose()
p.position.x = data['x']
p.position.y = data['y']
p.position.z = data['z']
p.orientation.x = quaternion[0]
p.orientation.y = quaternion[1]
p.orientation.z = quaternion[2]
p.orientation.w = quaternion[3]
return p
def createArrowMarker(pose, color):
pose_marker = copy.deepcopy(pose)
matrix_quaternion_marker = pose_marker[3:]
#matrix_quaternion_marker = R.from_quat(pose_marker[3:]).as_matrix()
# rotate_y90 = R.from_euler('y', -90, degrees=True).as_matrix()
# matrix_quaternion_marker = np.dot(
# matrix_quaternion_marker, rotate_y90)
# quaternion_marker = R.from_matrix(
# matrix_quaternion_marker).as_quat()
marker = Marker(header=Header(
frame_id="world", stamp=rospy.Time.now()))
marker.type = marker.ARROW
marker.action = marker.ADD
marker.scale.x = 0.3
marker.scale.y = 0.05
marker.scale.z = 0.05
marker.color.a = color[-1]
marker.color.r = color[0]
marker.color.g = color[1]
marker.color.b = color[2]
marker.pose.orientation.x = matrix_quaternion_marker[0]
marker.pose.orientation.y = matrix_quaternion_marker[1]
marker.pose.orientation.z = matrix_quaternion_marker[2]
marker.pose.orientation.w = matrix_quaternion_marker[3]
marker.pose.position.x = pose[0]
marker.pose.position.y = pose[1]
marker.pose.position.z = pose[2]
marker.ns = 'final_pose'
marker.id = 1
return marker
def getFrustumMarkerArray(w, h, f_x, f_y, Z_near, Z_far, frame_id, ns, color, alpha=0.9, thickness=0.005, lifetime=False):
# big help from https: // github.com/ros-visualization/rviz/issues/925
marker_array = MarkerArray()
# ------------------------------------
# Define view frustum points
# ------------------------------------
fov_x = 2 * math.atan2(w, (2 * f_x))
fov_y = 2 * math.atan2(h, (2 * f_y))
x_n = math.tan(fov_x / 2) * Z_near
y_n = math.tan(fov_y / 2) * Z_near
x_f = math.tan(fov_x / 2) * Z_far
y_f = math.tan(fov_y / 2) * Z_far
points = [Point(-x_n, y_n, Z_near),
Point(x_n, y_n, Z_near),
Point(x_n, -y_n, Z_near),
Point(-x_n, -y_n, Z_near),
Point(-x_f, y_f, Z_far),
Point(x_f, y_f, Z_far),
Point(x_f, -y_f, Z_far),
Point(-x_f, -y_f, Z_far)]
# ------------------------------------
# Define wireframe
# ------------------------------------
color_rviz = ColorRGBA(r=color[0]/2, g=color[1]/2, b=color[2]/2, a=1.0)
marker = Marker(ns=ns+'_wireframe', type=Marker.LINE_LIST, action=Marker.ADD, header=Header(frame_id=frame_id),
color=color_rviz)
if lifetime:
marker.lifetime=rospy.Duration(0)
marker.scale.x = thickness # line width
marker.pose.orientation.w = 1.0
# marker line points
marker.points.append(points[0])
marker.points.append(points[1])
marker.points.append(points[1])
marker.points.append(points[2])
marker.points.append(points[2])
marker.points.append(points[3])
marker.points.append(points[3])
marker.points.append(points[0])
marker.points.append(points[0])
marker.points.append(points[4])
marker.points.append(points[1])
marker.points.append(points[5])
marker.points.append(points[2])
marker.points.append(points[6])
marker.points.append(points[3])
marker.points.append(points[7])
marker.points.append(points[4])
marker.points.append(points[5])
marker.points.append(points[5])
marker.points.append(points[6])
marker.points.append(points[6])
marker.points.append(points[7])
marker.points.append(points[7])
marker.points.append(points[4])
marker_array.markers.append(copy.deepcopy(marker))
# ------------------------------------
# Define filled
# ------------------------------------
color_rviz = ColorRGBA(r=color[0], g=color[1], b=color[2], a=alpha)
marker = Marker(ns=ns+'_filled', type=Marker.TRIANGLE_LIST, action=Marker.ADD, header=Header(frame_id=frame_id),
color=color_rviz)
if lifetime:
marker.lifetime=rospy.Duration(0)
marker.scale.x = 1 # line width
marker.scale.y = 1 # line width
marker.scale.z = 1 # line width
marker.pose.orientation.w = 1.0
# marker triangles of the lateral face of the frustum pyramid
marker.points.append(points[1])
marker.points.append(points[2])
marker.points.append(points[6])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.points.append(points[1])
marker.points.append(points[6])
marker.points.append(points[5])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.points.append(points[0])
marker.points.append(points[4])
marker.points.append(points[3])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.points.append(points[3])
marker.points.append(points[4])
marker.points.append(points[7])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.points.append(points[0])
marker.points.append(points[1])
marker.points.append(points[5])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.points.append(points[0])
marker.points.append(points[4])
marker.points.append(points[5])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.points.append(points[3])
marker.points.append(points[2])
marker.points.append(points[6])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.points.append(points[3])
marker.points.append(points[6])
marker.points.append(points[7])
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker.colors.append(color_rviz)
marker_array.markers.append(copy.deepcopy(marker))
return marker_array
| 7,402 | 30.105042 | 122 | py |
synfeal | synfeal-main/deprecated/raycast_example.py | #!/usr/bin/env python3
# stdlib
import sys
import argparse
# 3rd-party
import trimesh
import numpy as np
import time
def main():
# parser = argparse.ArgumentParser(description='Data Collector')
# parser.add_argument('-m', '--mode', type=str, default='interactive',
# help='interactive/automatic_random_path/automatic_path')
#mesh = trimesh.creation.icosphere()
#mesh = trimesh.exchange.dae.load_collada('/home/danc/models_3d/santuario_collision/Virtudes_Chapel.dae')
start_time = time.time()
mesh = trimesh.load('/home/danc/models_3d/santuario_collision/Virtudes_Chapel.dae', force='mesh')
p1 = np.array([0,0,0])
p2 = np.array([4,0,0])
dp1p2 = np.linalg.norm(p2-p1)
ori = p2 - p1
norm_ori = np.linalg.norm(ori)
ori = ori / norm_ori
# create some rays
#ray_origins = np.array([[0, 0, 0]])
#ray_directions = np.array([[0, 1, 0]])
ray_origins = np.array([p1])
ray_directions = np.array([ori])
# check out the docstring for intersects_location queries
print(mesh.ray.intersects_location.__doc__)
locations, index_ray, index_tri = mesh.ray.intersects_location(
ray_origins=ray_origins,
ray_directions=ray_directions)
print('The rays hit the mesh at coordinates:\n', locations)
print(time.time() - start_time)
# get the first intersection
dists_to_p1 = []
for dist in locations:
dists_to_p1.append(np.linalg.norm(dist - p1))
print(dists_to_p1)
closest_collision = min(dists_to_p1)
print(closest_collision)
print(dp1p2)
if closest_collision < dp1p2:
print('COLISSION')
else:
print('SAFE')
# compare the first intersection with p2 (in terms of distances)
if __name__ == "__main__":
main()
| 1,910 | 24.144737 | 109 | py |
synfeal | synfeal-main/deprecated/rotation_to_direction.py | #!/usr/bin/env python3
from scipy.spatial.transform import Rotation as R
#rotate_y90 = R.from_euler('y', 90, degrees=True).as_matrix()
rotate_y90 = R.from_euler('x', 40, degrees=True).as_quat()
matrix = R.from_quat(rotate_y90).as_matrix()
print(matrix)
print(matrix[:,0]) | 274 | 26.5 | 61 | py |
synfeal | synfeal-main/synfeal_collection/src/automatic_data_collection.py | #!/usr/bin/env python3
# stdlib
import random
import os
from xml.parsers.expat import model
# 3rd-party
import rospy
import tf
import numpy as np
import trimesh
from geometry_msgs.msg import Pose
#from interactive_markers.interactive_marker_server import *
#from interactive_markers.menu_handler import *
from visualization_msgs.msg import *
from gazebo_msgs.srv import SetModelState, GetModelState, SetModelStateRequest
from colorama import Fore
from scipy.spatial.transform import Rotation as R
from synfeal_collection.src.save_dataset import SaveDataset
from utils import *
from utils_ros import *
class AutomaticDataCollection():
def __init__(self, model_name, seq, dbf=None, uvl=None, model3d_config=None, fast=None, save_dataset=True, mode=None):
self.set_state_service = rospy.ServiceProxy(
'/gazebo/set_model_state', SetModelState)
self.model_name = model_name # model_name = 'localbot'
self.dbf = dbf
rospy.wait_for_service('/gazebo/get_model_state')
self.get_model_state_service = rospy.ServiceProxy(
'/gazebo/get_model_state', GetModelState)
# create instance to save dataset
if save_dataset:
self.save_dataset = SaveDataset(
f'{seq}', mode=mode, dbf=dbf, uvl=uvl, model3d_config=model3d_config, fast=fast)
name_model3d_config = model3d_config['name'].split('.')[0]
print(name_model3d_config)
# define minimum and maximum boundaries
self.x_min = model3d_config['volume']['position']['xmin']
self.x_max = model3d_config['volume']['position']['xmax']
self.y_min = model3d_config['volume']['position']['ymin']
self.y_max = model3d_config['volume']['position']['ymax']
self.z_min = model3d_config['volume']['position']['zmin']
self.z_max = model3d_config['volume']['position']['zmax']
self.rx_min = model3d_config['volume']['angles']['rxmin']
self.rx_max = model3d_config['volume']['angles']['rxmax']
self.ry_min = model3d_config['volume']['angles']['rymin']
self.ry_max = model3d_config['volume']['angles']['rymax']
self.rz_min = model3d_config['volume']['angles']['rzmin']
self.rz_max = model3d_config['volume']['angles']['rzmax']
# define minimum and maximum light
self.att_min = model3d_config['light']['att_min']
self.att_max = model3d_config['light']['att_max']
self.att_initial = model3d_config['light']['att_initial']
self.light_names = model3d_config['light']['light_names']
self.use_collision = model3d_config['collision']['use']
self.min_cam_dist = model3d_config['collision']['min_camera_distance']
if self.use_collision:
path=os.environ.get("SYNFEAL_DATASET")
self.mesh_collision = trimesh.load(
f'{path}/models_3d/localbot/{name_model3d_config}/{name_model3d_config}_collision.dae', force='mesh')
else:
self.mesh_collision = False
# set initial pose
print('setting initial pose...')
x = model3d_config['initial_pose']['x']
y = model3d_config['initial_pose']['y']
z = model3d_config['initial_pose']['z']
rx = model3d_config['initial_pose']['rx']
ry = model3d_config['initial_pose']['ry']
rz = model3d_config['initial_pose']['rz']
quaternion = tf.transformations.quaternion_from_euler(rx, ry, rz)
p = Pose()
p.position.x = x
p.position.y = y
p.position.z = z
p.orientation.x = quaternion[0]
p.orientation.y = quaternion[1]
p.orientation.z = quaternion[2]
p.orientation.w = quaternion[3]
self.setPose(p)
rospy.sleep(1)
def generateRandomPose(self):
x = random.uniform(self.x_min, self.x_max)
y = random.uniform(self.y_min, self.y_max)
z = random.uniform(self.z_min, self.z_max)
rx = random.uniform(self.rx_min, self.rx_max)
ry = random.uniform(self.ry_min, self.ry_max)
rz = random.uniform(self.rz_min, self.rz_max)
quaternion = tf.transformations.quaternion_from_euler(rx, ry, rz)
p = Pose()
p.position.x = x
p.position.y = y
p.position.z = z
p.orientation.x = quaternion[0]
p.orientation.y = quaternion[1]
p.orientation.z = quaternion[2]
p.orientation.w = quaternion[3]
return p
def generatePath(self, final_pose=None):
initial_pose = self.getPose().pose
if final_pose == None:
final_pose = self.generateRandomPose()
while True:
xyz_initial = np.array(
[initial_pose.position.x, initial_pose.position.y, initial_pose.position.z])
xyz_final = np.array(
[final_pose.position.x, final_pose.position.y, final_pose.position.z])
l2_dst = np.linalg.norm(xyz_final - xyz_initial)
# if final pose is close to the initial or there is collision, choose another final pose
if l2_dst < 1.5 or self.checkCollision(initial_pose=initial_pose, final_pose=final_pose):
final_pose = self.generateRandomPose()
else:
break
# compute n_steps based on l2_dist
n_steps = int(l2_dst / self.dbf)
print('using n_steps of: ', n_steps)
step_poses = [] # list of tuples
rx, ry, rz = tf.transformations.euler_from_quaternion(
[initial_pose.orientation.x, initial_pose.orientation.y, initial_pose.orientation.z, initial_pose.orientation.w])
pose_initial_dct = {'x': initial_pose.position.x,
'y': initial_pose.position.y,
'z': initial_pose.position.z,
'rx': rx,
'ry': ry,
'rz': rz}
rx, ry, rz = tf.transformations.euler_from_quaternion(
[final_pose.orientation.x, final_pose.orientation.y, final_pose.orientation.z, final_pose.orientation.w])
pose_final_dct = {'x': final_pose.position.x,
'y': final_pose.position.y,
'z': final_pose.position.z,
'rx': rx,
'ry': ry,
'rz': rz}
x_step_var = (pose_final_dct['x'] - pose_initial_dct['x']) / n_steps
y_step_var = (pose_final_dct['y'] - pose_initial_dct['y']) / n_steps
z_step_var = (pose_final_dct['z'] - pose_initial_dct['z']) / n_steps
rx_step_var = (pose_final_dct['rx'] - pose_initial_dct['rx']) / n_steps
ry_step_var = (pose_final_dct['ry'] - pose_initial_dct['ry']) / n_steps
rz_step_var = (pose_final_dct['rz'] - pose_initial_dct['rz']) / n_steps
for i in range(n_steps):
dct = {'x': pose_initial_dct['x'] + (i + 1) * x_step_var,
'y': pose_initial_dct['y'] + (i + 1) * y_step_var,
'z': pose_initial_dct['z'] + (i + 1) * z_step_var,
'rx': pose_initial_dct['rx'] + (i + 1) * rx_step_var,
'ry': pose_initial_dct['ry'] + (i + 1) * ry_step_var,
'rz': pose_initial_dct['rz'] + (i + 1) * rz_step_var}
pose = data2pose(dct)
step_poses.append(pose)
return step_poses
def getPose(self):
return self.get_model_state_service(self.model_name, 'world')
def setPose(self, pose):
req = SetModelStateRequest() # Create an object of type SetModelStateRequest
req.model_state.model_name = self.model_name
req.model_state.pose.position.x = pose.position.x
req.model_state.pose.position.y = pose.position.y
req.model_state.pose.position.z = pose.position.z
req.model_state.pose.orientation.x = pose.orientation.x
req.model_state.pose.orientation.y = pose.orientation.y
req.model_state.pose.orientation.z = pose.orientation.z
req.model_state.pose.orientation.w = pose.orientation.w
req.model_state.reference_frame = 'world'
self.set_state_service(req.model_state)
def generateLights(self, n_steps, random):
lights = []
if random:
lights = [np.random.uniform(
low=self.att_min, high=self.att_max) for _ in range(n_steps)]
else:
initial_light = self.att_initial
final_light = np.random.uniform(
low=self.att_min, high=self.att_max)
step_light = (final_light - initial_light) / n_steps
for i in range(n_steps):
lights.append(initial_light + (i + 1) * step_light)
self.att_initial = final_light
return lights
def setLight(self, light):
for name in self.light_names:
my_str = f'name: "{name}" \nattenuation_quadratic: {light}'
with open('/tmp/set_light.txt', 'w') as f:
f.write(my_str)
os.system(
f'gz topic -p /gazebo/mercado_negro/light/modify -f /tmp/set_light.txt')
def checkCollision(self, initial_pose, final_pose):
if self.use_collision is False:
print('not using COLLISIONS.')
return False
initial_pose.position.x
p1_xyz = np.array(
[initial_pose.position.x, initial_pose.position.y, initial_pose.position.z])
p1_quat = np.array([initial_pose.orientation.x, initial_pose.orientation.y,
initial_pose.orientation.z, initial_pose.orientation.w])
p2_xyz = np.array(
[final_pose.position.x, final_pose.position.y, final_pose.position.z])
p2_quat = np.array([final_pose.orientation.x, final_pose.orientation.y,
final_pose.orientation.z, final_pose.orientation.w])
dist_p1_to_p2 = np.linalg.norm(p2_xyz-p1_xyz)
print(
f' {Fore.BLUE} Checking collision... {Fore.RESET} between {p1_xyz} and {p2_xyz}')
orientation = p2_xyz - p1_xyz
norm_orientation = np.linalg.norm(orientation)
orientation = orientation / norm_orientation
ray_origins = np.array([p1_xyz])
ray_directions = np.array([orientation])
collisions, _, _ = self.mesh_collision.ray.intersects_location(
ray_origins=ray_origins,
ray_directions=ray_directions)
closest_collision_to_p1 = self.getClosestCollision(collisions, p1_xyz)
# compare the closest collision with the position of p2
if closest_collision_to_p1 < dist_p1_to_p2:
# collision
print(f'{Fore.RED} Collision Detected. {Fore.RESET}')
return True
else:
# no collision
# check if p2 camera viewpoint if close to a obstacle.
orientation = R.from_quat(p2_quat).as_matrix()[:, 0]
norm_orientation = np.linalg.norm(orientation)
orientation = orientation / norm_orientation
ray_origins = np.array([p2_xyz])
ray_directions = np.array([orientation])
collisions, _, _ = self.mesh_collision.ray.intersects_location(
ray_origins=ray_origins,
ray_directions=ray_directions)
closest_collision_to_p2 = self.getClosestCollision(
collisions, p2_xyz)
if closest_collision_to_p2 < self.min_cam_dist:
print(
f'{Fore.YELLOW} Final Pose is too close to a obstacle. {Fore.RESET}')
return True
else:
print(f'{Fore.GREEN} NO Collision Detected {Fore.RESET}')
return False
def checkCollisionVis(self, initial_pose, final_pose):
if self.use_collision is False:
print('not using COLLISIONS.')
return False
# load mesh
# TODO #83 this should not be hardcoded
mesh = trimesh.load(
'/home/danc/models_3d/santuario_collision/Virtudes_Chapel.dae', force='mesh')
initial_pose.position.x
p1_xyz = np.array(
[initial_pose.position.x, initial_pose.position.y, initial_pose.position.z])
p1_quat = np.array([initial_pose.orientation.x, initial_pose.orientation.y,
initial_pose.orientation.z, initial_pose.orientation.w])
p2_xyz = np.array(
[final_pose.position.x, final_pose.position.y, final_pose.position.z])
p2_quat = np.array([final_pose.orientation.x, final_pose.orientation.y,
final_pose.orientation.z, final_pose.orientation.w])
dist_p1_to_p2 = np.linalg.norm(p2_xyz-p1_xyz)
print(
f' {Fore.BLUE} Checking collision... {Fore.RESET} between {p1_xyz} and {p2_xyz}')
orientation = p2_xyz - p1_xyz
norm_orientation = np.linalg.norm(orientation)
orientation = orientation / norm_orientation
ray_origins = np.array([p1_xyz])
ray_directions = np.array([orientation])
collisions, _, _ = mesh.ray.intersects_location(
ray_origins=ray_origins,
ray_directions=ray_directions)
closest_collision_to_p1 = self.getClosestCollision(collisions, p1_xyz)
# compare the closest collision with the position of p2
if closest_collision_to_p1 < dist_p1_to_p2:
# collision
print(f'{Fore.RED} Collision Detected. {Fore.RESET}')
return 1
else:
# no collision
# check if p2 camera viewpoint if close to a obstacle.
orientation = R.from_quat(p2_quat).as_matrix()[:, 0]
norm_orientation = np.linalg.norm(orientation)
orientation = orientation / norm_orientation
ray_origins = np.array([p2_xyz])
ray_directions = np.array([orientation])
collisions, _, _ = mesh.ray.intersects_location(
ray_origins=ray_origins,
ray_directions=ray_directions)
closest_collision_to_p2 = self.getClosestCollision(
collisions, p2_xyz)
if closest_collision_to_p2 < self.min_cam_dist:
print(
f'{Fore.YELLOW} Final Pose is too close to a obstacle. {Fore.RESET}')
return 0.5
else:
print(f'{Fore.GREEN} NO Collision Detected {Fore.RESET}')
return 0
def generatePathViz(self, final_pose):
initial_pose = self.getPose().pose
xyz_initial = np.array(
[initial_pose.position.x, initial_pose.position.y, initial_pose.position.z])
xyz_final = np.array(
[final_pose.position.x, final_pose.position.y, final_pose.position.z])
l2_dst = np.linalg.norm(xyz_final - xyz_initial)
# compute n_steps based on l2_dist
n_steps = int(l2_dst / self.dbf)
print('using n_steps of: ', n_steps)
step_poses = [] # list of tuples
rx, ry, rz = tf.transformations.euler_from_quaternion(
[initial_pose.orientation.x, initial_pose.orientation.y, initial_pose.orientation.z, initial_pose.orientation.w])
pose_initial_dct = {'x': initial_pose.position.x,
'y': initial_pose.position.y,
'z': initial_pose.position.z,
'rx': rx,
'ry': ry,
'rz': rz}
rx, ry, rz = tf.transformations.euler_from_quaternion(
[final_pose.orientation.x, final_pose.orientation.y, final_pose.orientation.z, final_pose.orientation.w])
pose_final_dct = {'x': final_pose.position.x,
'y': final_pose.position.y,
'z': final_pose.position.z,
'rx': rx,
'ry': ry,
'rz': rz}
x_step_var = (pose_final_dct['x'] - pose_initial_dct['x']) / n_steps
y_step_var = (pose_final_dct['y'] - pose_initial_dct['y']) / n_steps
z_step_var = (pose_final_dct['z'] - pose_initial_dct['z']) / n_steps
rx_step_var = (pose_final_dct['rx'] - pose_initial_dct['rx']) / n_steps
ry_step_var = (pose_final_dct['ry'] - pose_initial_dct['ry']) / n_steps
rz_step_var = (pose_final_dct['rz'] - pose_initial_dct['rz']) / n_steps
for i in range(n_steps):
dct = {'x': pose_initial_dct['x'] + (i + 1) * x_step_var,
'y': pose_initial_dct['y'] + (i + 1) * y_step_var,
'z': pose_initial_dct['z'] + (i + 1) * z_step_var,
'rx': pose_initial_dct['rx'] + (i + 1) * rx_step_var,
'ry': pose_initial_dct['ry'] + (i + 1) * ry_step_var,
'rz': pose_initial_dct['rz'] + (i + 1) * rz_step_var}
pose = data2pose(dct)
step_poses.append(pose)
return step_poses
def getClosestCollision(self, collisions, p1_xyz):
closest_collision_to_p1 = np.inf
for position_collision in collisions:
dist_collision_p1 = np.linalg.norm(position_collision - p1_xyz)
if dist_collision_p1 < closest_collision_to_p1:
closest_collision_to_p1 = dist_collision_p1
return closest_collision_to_p1
def saveFrame(self):
self.save_dataset.saveFrame()
def getFrameIdx(self):
return self.save_dataset.frame_idx
| 17,567 | 39.018223 | 125 | py |
synfeal | synfeal-main/synfeal_collection/src/interactive_data_collection.py | #!/usr/bin/env python3
import copy
import rospy
from std_msgs.msg import Header, ColorRGBA
from geometry_msgs.msg import Point, Pose, Vector3, Quaternion
from interactive_markers.interactive_marker_server import *
from interactive_markers.menu_handler import *
from visualization_msgs.msg import *
from gazebo_msgs.srv import SetModelState, GetModelState, SetModelStateRequest
from synfeal_collection.src.save_dataset import SaveDataset
class InteractiveDataCollection():
def __init__(self, model_name, seq):
self.set_state_service = rospy.ServiceProxy('/gazebo/set_model_state', SetModelState)
self.menu_handler = MenuHandler()
self.model_name = model_name
self.server = InteractiveMarkerServer("interactive_camera")
rospy.wait_for_service('/gazebo/get_model_state')
self.get_model_state_service = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)
pose_gazebo = self.get_model_state_service(self.model_name, 'world')
self.pose = copy.deepcopy(pose_gazebo.pose)
self.make6DofMarker(True, InteractiveMarkerControl.MOVE_3D, pose_gazebo.pose, True)
# add interactive marker to save datasets
self.original_pose = Pose(position=Point(x=0, y=0, z=1), orientation=Quaternion(x=0, y=0, z=0, w=1))
self.makeClickMarker(self.original_pose)
self.server.applyChanges()
# create instance to save dataset
self.save_dataset = SaveDataset(seq, mode='interactive')
def makeBox(self, msg, pose, color):
marker = Marker(header=Header(frame_id="world", stamp=rospy.Time.now()),
ns=self.model_name, id=0, frame_locked=False,
type=Marker.SPHERE, action=Marker.ADD, lifetime=rospy.Duration(0),
pose=pose,
scale=Vector3(x=0.05, y=0.05, z=0.05),
color=ColorRGBA(r=color[0], g=color[1], b=color[2], a=1))
return marker
def makeBoxControl(self, msg, pose, color):
control = InteractiveMarkerControl()
control.interaction_mode = InteractiveMarkerControl.BUTTON
control.always_visible = True
control.markers.append(self.makeBox(msg, pose, color))
msg.controls.append(control)
return control
def makeClickMarker(self,pose):
int_marker = InteractiveMarker()
int_marker.header.frame_id = "world"
int_marker.pose = pose
int_marker.scale = 1
int_marker.name = "Save Frame"
int_marker.description = "Click to save frame"
control = self.makeBoxControl(int_marker, pose, color= [0.2,0.8,0.2])
int_marker.controls.append(copy.deepcopy(control))
self.server.insert(int_marker, self.processFeedbackMenu)
self.menu_handler.apply(self.server, int_marker.name)
def make6DofMarker(self, fixed, interaction_mode, pose, show_6dof=False):
int_marker = InteractiveMarker()
int_marker.header.frame_id = "world"
int_marker.pose = pose
int_marker.scale = 0.3
int_marker.name = "simple_6dof"
int_marker.description = "Simple 6-DOF Control"
self.makeBoxControl(int_marker, pose, color= [0.8,0.2,0.2])
int_marker.controls[0].interaction_mode = interaction_mode
if fixed:
int_marker.name += "_fixed"
int_marker.description += "\n(fixed orientation)"
if interaction_mode != InteractiveMarkerControl.NONE:
control_modes_dict = {
InteractiveMarkerControl.MOVE_3D: "MOVE_3D",
InteractiveMarkerControl.ROTATE_3D: "ROTATE_3D",
InteractiveMarkerControl.MOVE_ROTATE_3D: "MOVE_ROTATE_3D"}
int_marker.name += "_" + control_modes_dict[interaction_mode]
int_marker.description = "3D Control"
if show_6dof:
int_marker.description += " + 6-DOF controls"
int_marker.description += "\n" + control_modes_dict[interaction_mode]
if show_6dof:
control = InteractiveMarkerControl()
control.orientation.w = 1
control.orientation.x = 1
control.orientation.y = 0
control.orientation.z = 0
control.name = "rotate_x"
control.interaction_mode = InteractiveMarkerControl.ROTATE_AXIS
if fixed:
control.orientation_mode = InteractiveMarkerControl.FIXED
int_marker.controls.append(control)
control = InteractiveMarkerControl()
control.orientation.w = 1
control.orientation.x = 1
control.orientation.y = 0
control.orientation.z = 0
control.name = "move_x"
control.interaction_mode = InteractiveMarkerControl.MOVE_AXIS
if fixed:
control.orientation_mode = InteractiveMarkerControl.FIXED
int_marker.controls.append(control)
control = InteractiveMarkerControl()
control.orientation.w = 1
control.orientation.x = 0
control.orientation.y = 1
control.orientation.z = 0
control.name = "rotate_z"
control.interaction_mode = InteractiveMarkerControl.ROTATE_AXIS
if fixed:
control.orientation_mode = InteractiveMarkerControl.FIXED
int_marker.controls.append(control)
control = InteractiveMarkerControl()
control.orientation.w = 1
control.orientation.x = 0
control.orientation.y = 1
control.orientation.z = 0
control.name = "move_z"
control.interaction_mode = InteractiveMarkerControl.MOVE_AXIS
if fixed:
control.orientation_mode = InteractiveMarkerControl.FIXED
int_marker.controls.append(control)
control = InteractiveMarkerControl()
control.orientation.w = 1
control.orientation.x = 0
control.orientation.y = 0
control.orientation.z = 1
control.name = "rotate_y"
control.interaction_mode = InteractiveMarkerControl.ROTATE_AXIS
if fixed:
control.orientation_mode = InteractiveMarkerControl.FIXED
int_marker.controls.append(control)
control = InteractiveMarkerControl()
control.orientation.w = 1
control.orientation.x = 0
control.orientation.y = 0
control.orientation.z = 1
control.name = "move_y"
control.interaction_mode = InteractiveMarkerControl.MOVE_AXIS
if fixed:
control.orientation_mode = InteractiveMarkerControl.FIXED
int_marker.controls.append(control)
self.server.insert(int_marker, self.processFeedback)
self.menu_handler.apply(self.server, int_marker.name)
def processFeedback(self, feedback):
s = "feedback from marker '" + feedback.marker_name
s += "' / control '" + feedback.control_name + "'"
if feedback.event_type == InteractiveMarkerFeedback.POSE_UPDATE:
rospy.loginfo( s + ": pose changed")
print('feedback = \n' + str(feedback))
self.pose.position.x = feedback.pose.position.x
self.pose.position.y = feedback.pose.position.y
self.pose.position.z = feedback.pose.position.z
self.pose.orientation.x = feedback.pose.orientation.x
self.pose.orientation.y = feedback.pose.orientation.y
self.pose.orientation.z = feedback.pose.orientation.z
self.pose.orientation.w = feedback.pose.orientation.w
req = SetModelStateRequest() # Create an object of type SetModelStateRequest
req.model_state.model_name = self.model_name
req.model_state.pose.position.x = self.pose.position.x
req.model_state.pose.position.y = self.pose.position.y
req.model_state.pose.position.z = self.pose.position.z
req.model_state.pose.orientation.x = self.pose.orientation.x
req.model_state.pose.orientation.y = self.pose.orientation.y
req.model_state.pose.orientation.z = self.pose.orientation.z
req.model_state.pose.orientation.w = self.pose.orientation.w
req.model_state.reference_frame = 'world'
self.set_state_service(req.model_state)
self.server.applyChanges()
def processFeedbackMenu(self, feedback):
s = "feedback from marker '" + feedback.marker_name
s += "' / control '" + feedback.control_name + "'"
if feedback.event_type == InteractiveMarkerFeedback.BUTTON_CLICK:
self.save_dataset.saveFrame()
def callbackTimer(self,event):
print('Timer called at ' + str(event.current_real))
def getFrameIdx(self):
return self.save_dataset.frame_idx
| 9,016 | 42.350962 | 108 | py |
synfeal | synfeal-main/synfeal_collection/src/save_dataset.py | #!/usr/bin/env python3
import rospy
import os
from visualization_msgs.msg import *
from cv_bridge import CvBridge
from tf.listener import TransformListener
from utils import write_intrinsic, write_img, write_transformation
from utils_ros import read_pcd, write_pcd
from sensor_msgs.msg import PointCloud2, Image, PointField, CameraInfo
from colorama import Fore
from datetime import datetime
import yaml
import sensor_msgs.point_cloud2 as pc2
import numpy as np
class SaveDataset():
def __init__(self, output, mode, dbf = None, uvl = None, model3d_config = None, fast=False):
path=os.environ.get("SYNFEAL_DATASET")
self.output_folder = f'{path}/datasets/localbot/{output}'
if not os.path.exists(self.output_folder):
print(f'Creating folder {self.output_folder}')
os.makedirs(self.output_folder) # Create the new folder
else:
print(f'{Fore.RED} {self.output_folder} already exists... Aborting SaveDataset initialization! {Fore.RESET}')
exit(0)
name_model3d_config = model3d_config if model3d_config is not None else None
dt_now = datetime.now() # current date and time
config = {'user' : os.environ["USER"],
'date' : dt_now.strftime("%d/%m/%Y, %H:%M:%S"),
'mode' : mode,
'is_valid' : False,
'npoints' : None,
'scaled' : False,
'distance_between_frames' : dbf,
'raw' : output,
'variable_lights' : uvl,
'model3d_config' : name_model3d_config,
'fast' : fast}
self.fast = fast
self.frame_idx = 0
self.world_link = 'world'
self.depth_frame = 'kinect_depth_optical_frame'
self.rgb_frame = 'kinect_rgb_optical_frame'
self.listener = TransformListener()
self.bridge = CvBridge()
# get transformation from depth_frame to rgb_fram
now = rospy.Time()
print(f'Waiting for transformation from {self.depth_frame} to {self.rgb_frame}')
self.listener.waitForTransform(self.depth_frame, self.rgb_frame , now, rospy.Duration(5)) # admissible waiting time
print('... received!')
self.transform_depth_rgb = self.listener.lookupTransform(self.depth_frame, self.rgb_frame, now)
self.matrix_depth_rgb = self.listener.fromTranslationRotation(self.transform_depth_rgb[0], self.transform_depth_rgb[1])
# get intrinsic matrices from both cameras
rgb_camera_info = rospy.wait_for_message('/kinect/rgb/camera_info', CameraInfo)
depth_camera_info = rospy.wait_for_message('/kinect/depth/camera_info', CameraInfo)
# rgb information
rgb_intrinsic = rgb_camera_info.K
rgb_width = rgb_camera_info.width
rgb_height = rgb_camera_info.height
# depth information
depth_width = depth_camera_info.width
depth_height = depth_camera_info.height
depth_intrinsic = depth_camera_info.K
# save intrinsic to txt file
write_intrinsic(f'{self.output_folder}/rgb_intrinsic.txt', rgb_intrinsic)
write_intrinsic(f'{self.output_folder}/depth_intrinsic.txt', depth_intrinsic)
rgb_dict = {'intrinsic' : f'{self.output_folder}/rgb_intrinsic.txt',
'width' : rgb_width,
'height' : rgb_height}
depth_dict = {'intrinsic' : f'{self.output_folder}/depth_intrinsic.txt',
'width' : depth_width,
'height' : depth_height}
config['rgb'] = rgb_dict
config['depth'] = depth_dict
with open(f'{self.output_folder}/config.yaml', 'w') as file:
yaml.dump(config, file)
with open(f'{self.output_folder}/model3d_config.yaml', 'w') as file:
yaml.dump(model3d_config, file)
print('SaveDataset initialized properly')
def saveFrame(self):
transformation = self.getTransformation()
image = self.getImage()
filename = f'frame-{self.frame_idx:05d}'
write_transformation(f'{self.output_folder}/{filename}.pose.txt', transformation)
write_img(f'{self.output_folder}/{filename}.rgb.png', image)
if not self.fast:
pc_msg = self.getPointCloud()
write_pcd(f'{self.output_folder}/{filename}.pcd', pc_msg)
print(f'frame-{self.frame_idx:05d} saved successfully')
self.step()
def getTransformation(self):
now = rospy.Time()
print(f'Waiting for transformation from {self.world_link} to {self.rgb_frame}')
self.listener.waitForTransform(self.world_link, self.rgb_frame , now, rospy.Duration(5))
print('... received!')
(trans,rot) = self.listener.lookupTransform(self.world_link, self.rgb_frame, now)
return self.listener.fromTranslationRotation(trans, rot)
def getImage(self):
rgb_msg = rospy.wait_for_message('/kinect/rgb/image_raw', Image)
return self.bridge.imgmsg_to_cv2(rgb_msg, "bgr8") # convert to opencv image
def getPointCloud(self):
pc_msg = rospy.wait_for_message('/kinect/depth/points', PointCloud2)
pc2_points = pc2.read_points(pc_msg)
gen_selected_points = list(pc2_points)
lst_points = []
for point in gen_selected_points:
lst_points.append([point[0], point[1], point[2], 1])
np_points = np.array(lst_points)
# convert to rgb_frame
np_points = np.dot(self.matrix_depth_rgb, np_points.T).T
fields = [PointField('x', 0, PointField.FLOAT32, 1),
PointField('y', 4, PointField.FLOAT32, 1),
PointField('z', 8, PointField.FLOAT32, 1),
PointField('intensity', 12, PointField.FLOAT32, 1)]
pc_msg.header.frame_id = self.rgb_frame
return pc2.create_cloud(pc_msg.header, fields, np_points)
def step(self):
self.frame_idx+=1
| 6,373 | 37.630303 | 127 | py |
synfeal | synfeal-main/synfeal_collection/src/pypcd_no_ros.py | """
The MIT License (MIT)
Copyright (c) 2015 Daniel Maturana, Carnegie Mellon University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Read and write PCL .pcd files in python.
[email protected], 2013
"""
import re
import struct
import copy
import numpy as np
#from sensor_msgs.msg import PointField
#from sensor_msgs.msg import PointCloud2
# -----------------------------------------------------------------------------
# ----- Settings
# -----------------------------------------------------------------------------
DUMMY_FIELD_PREFIX = '__'
# sizes (in bytes) of PointField types
# pftype_sizes = {PointField.INT8: 1, PointField.UINT8: 1, PointField.INT16: 2, PointField.UINT16: 2,
# PointField.INT32: 4, PointField.UINT32: 4, PointField.FLOAT32: 4, PointField.FLOAT64: 8}
# # mappings between PointField types and numpy types
# type_mappings = [(PointField.INT8, np.dtype('int8')),
# (PointField.UINT8, np.dtype('uint8')),
# (PointField.INT16, np.dtype('int16')),
# (PointField.UINT16, np.dtype('uint16')),
# (PointField.INT32, np.dtype('int32')),
# (PointField.UINT32, np.dtype('uint32')),
# (PointField.FLOAT32, np.dtype('float32')),
# (PointField.FLOAT64, np.dtype('float64'))]
# pftype_to_nptype = dict(type_mappings)
# nptype_to_pftype = dict((nptype, pftype) for pftype, nptype in type_mappings)
# pc2_pcd_type_mappings = [(PointField.INT8, ('I', 1)),
# (PointField.UINT8, ('U', 1)),
# (PointField.INT16, ('I', 2)),
# (PointField.UINT16, ('U', 2)),
# (PointField.INT32, ('I', 4)),
# (PointField.UINT32, ('U', 4)),
# (PointField.FLOAT32, ('F', 4)),
# (PointField.FLOAT64, ('F', 8))]
# pc2_type_to_pcd_type = dict(pc2_pcd_type_mappings)
# pcd_type_to_pc2_type = dict((q, p) for (p, q) in pc2_pcd_type_mappings)
numpy_pcd_type_mappings = [(np.dtype('float32'), ('F', 4)),
(np.dtype('float64'), ('F', 8)),
(np.dtype('uint8'), ('U', 1)),
(np.dtype('uint16'), ('U', 2)),
(np.dtype('uint32'), ('U', 4)),
(np.dtype('uint64'), ('U', 8)),
(np.dtype('int16'), ('I', 2)),
(np.dtype('int32'), ('I', 4)),
(np.dtype('int64'), ('I', 8))]
numpy_type_to_pcd_type = dict(numpy_pcd_type_mappings)
pcd_type_to_numpy_type = dict((q, p) for (p, q) in numpy_pcd_type_mappings)
# -----------------------------------------------------------------------------
# ----- numpy <-> pc2 bridge
# -----------------------------------------------------------------------------
def split_rgb_field(cloud_arr):
'''Takes an array with a named 'rgb' float32 field, and returns an array in which
this has been split into 3 uint 8 fields: 'r', 'g', and 'b'.
(pcl stores rgb in packed 32 bit floats)
'''
rgb_arr = cloud_arr['rgb'].copy()
rgb_arr.dtype = np.uint32
r = np.asarray((rgb_arr >> 16) & 255, dtype=np.uint8)
g = np.asarray((rgb_arr >> 8) & 255, dtype=np.uint8)
b = np.asarray(rgb_arr & 255, dtype=np.uint8)
# create a new array, without rgb, but with r, g, and b fields
new_dtype = []
for field_name in cloud_arr.dtype.names:
field_type, field_offset = cloud_arr.dtype.fields[field_name]
if not field_name == 'rgb':
new_dtype.append((field_name, field_type))
new_dtype.append(('r', np.uint8))
new_dtype.append(('g', np.uint8))
new_dtype.append(('b', np.uint8))
new_cloud_arr = np.zeros(cloud_arr.shape, new_dtype)
# fill in the new array
for field_name in new_cloud_arr.dtype.names:
if field_name == 'r':
new_cloud_arr[field_name] = r
elif field_name == 'g':
new_cloud_arr[field_name] = g
elif field_name == 'b':
new_cloud_arr[field_name] = b
else:
new_cloud_arr[field_name] = cloud_arr[field_name]
return new_cloud_arr
def merge_rgb_fields(cloud_arr):
'''Takes an array with named np.uint8 fields 'r', 'g', and 'b', and returns an array in
which they have been merged into a single np.float32 'rgb' field. The first byte of this
field is the 'r' uint8, the second is the 'g', uint8, and the third is the 'b' uint8.
This is the way that pcl likes to handle RGB colors for some reason.
'''
r = np.asarray(cloud_arr['r'], dtype=np.uint32)
g = np.asarray(cloud_arr['g'], dtype=np.uint32)
b = np.asarray(cloud_arr['b'], dtype=np.uint32)
rgb_arr = np.array((r << 16) | (g << 8) | (b << 0), dtype=np.uint32)
# not sure if there is a better way to do this. i'm changing the type of the array
# from uint32 to float32, but i don't want any conversion to take place -jdb
rgb_arr.dtype = np.float32
# create a new array, without r, g, and b, but with rgb float32 field
new_dtype = []
for field_name in cloud_arr.dtype.names:
field_type, field_offset = cloud_arr.dtype.fields[field_name]
if field_name not in ('r', 'g', 'b'):
new_dtype.append((field_name, field_type))
new_dtype.append(('rgb', np.float32))
new_cloud_arr = np.zeros(cloud_arr.shape, new_dtype)
# fill in the new array
for field_name in new_cloud_arr.dtype.names:
if field_name == 'rgb':
new_cloud_arr[field_name] = rgb_arr
else:
new_cloud_arr[field_name] = cloud_arr[field_name]
return new_cloud_arr
def arr_to_fields(cloud_arr):
'''Convert a numpy record datatype into a list of PointFields.
'''
fields = []
for field_name in cloud_arr.dtype.names:
np_field_type, field_offset = cloud_arr.dtype.fields[field_name]
pf = PointField()
pf.name = field_name
pf.datatype = nptype_to_pftype[np_field_type]
pf.offset = field_offset
pf.count = 1 # is this ever more than one?
fields.append(pf)
return fields
def pointcloud2_to_dtype(cloud_msg):
'''Convert a list of PointFields to a numpy record datatype.
'''
offset = 0
np_dtype_list = []
for f in cloud_msg.fields:
while offset < f.offset:
# might be extra padding between fields
np_dtype_list.append(('%s%d' % (DUMMY_FIELD_PREFIX, offset), np.uint8))
offset += 1
np_dtype_list.append((f.name, pftype_to_nptype[f.datatype]))
offset += pftype_sizes[f.datatype]
# might be extra padding between points
while offset < cloud_msg.point_step:
np_dtype_list.append(('%s%d' % (DUMMY_FIELD_PREFIX, offset), np.uint8))
offset += 1
return np_dtype_list
def pointcloud2_to_array(cloud_msg, split_rgb=False, remove_padding=True):
''' Converts a rospy PointCloud2 message to a numpy recordarray
Reshapes the returned array to have shape (height, width), even if the height is 1.
The reason for using np.fromstring rather than struct.unpack is speed... especially
for large point clouds, this will be <much> faster.
'''
# construct a numpy record type equivalent to the point type of this cloud
dtype_list = pointcloud2_to_dtype(cloud_msg)
# parse the cloud into an array
cloud_arr = np.fromstring(cloud_msg.data, dtype_list)
# remove the dummy fields that were added
if remove_padding:
cloud_arr = cloud_arr[
[fname for fname, _type in dtype_list if not (fname[:len(DUMMY_FIELD_PREFIX)] == DUMMY_FIELD_PREFIX)]]
if split_rgb:
cloud_arr = split_rgb_field(cloud_arr)
return np.reshape(cloud_arr, (cloud_msg.height, cloud_msg.width))
def array_to_pointcloud2(cloud_arr, stamp=None, frame_id=None, merge_rgb=False):
'''Converts a numpy record array to a sensor_msgs.msg.PointCloud2.
'''
if merge_rgb:
cloud_arr = merge_rgb_fields(cloud_arr)
# make it 2d (even if height will be 1)
cloud_arr = np.atleast_2d(cloud_arr)
cloud_msg = PointCloud2()
if stamp is not None:
cloud_msg.header.stamp = stamp
if frame_id is not None:
cloud_msg.header.frame_id = frame_id
cloud_msg.height = cloud_arr.shape[0]
cloud_msg.width = cloud_arr.shape[1]
cloud_msg.fields = arr_to_fields(cloud_arr)
cloud_msg.is_bigendian = False # assumption
cloud_msg.point_step = cloud_arr.dtype.itemsize
cloud_msg.row_step = cloud_msg.point_step * cloud_arr.shape[1]
cloud_msg.is_dense = all([np.isfinite(cloud_arr[fname]).all() for fname in cloud_arr.dtype.names])
cloud_msg.data = cloud_arr.tostring()
return cloud_msg
# -----------------------------------------------------------------------------
# ----- Read/Write routines
# -----------------------------------------------------------------------------
def parse_header(lines):
metadata = {}
for ln in lines:
if ln.startswith('#') or len(ln) < 2:
continue
match = re.match('(\w+)\s+([\w\s\.]+)', ln)
if not match:
print("\033[93m" + "warning: can't understand line: %s" % ln + "\033[1m")
continue
key, value = match.group(1).lower(), match.group(2)
if key == 'version':
metadata[key] = value
elif key in ('fields', 'type'):
metadata[key] = value.split()
elif key in ('size', 'count'):
metadata[key] = list(map(int, value.split()))
elif key in ('width', 'height', 'points'):
metadata[key] = int(value)
elif key == 'viewpoint':
metadata[key] = list(map(float, value.split()))
elif key == 'data':
metadata[key] = value.strip().lower()
# TODO apparently count is not required?
# add some reasonable defaults
if 'count' not in metadata:
metadata['count'] = [1] * len(metadata['fields'])
if 'viewpoint' not in metadata:
metadata['viewpoint'] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
if 'version' not in metadata:
metadata['version'] = '.7'
return metadata
def write_header(metadata, rename_padding=False):
""" given metadata as dictionary return a string header.
"""
template = """\
VERSION {version}
FIELDS {fields}
SIZE {size}
TYPE {type}
COUNT {count}
WIDTH {width}
HEIGHT {height}
VIEWPOINT {viewpoint}
POINTS {points}
DATA {data}
"""
str_metadata = metadata.copy()
if not rename_padding:
str_metadata['fields'] = ' '.join(metadata['fields'])
else:
new_fields = []
for f in metadata['fields']:
if f == '_':
new_fields.append('padding')
else:
new_fields.append(f)
str_metadata['fields'] = ' '.join(new_fields)
str_metadata['size'] = ' '.join(map(str, metadata['size']))
str_metadata['type'] = ' '.join(metadata['type'])
str_metadata['count'] = ' '.join(map(str, metadata['count']))
str_metadata['width'] = str(metadata['width'])
str_metadata['height'] = str(metadata['height'])
str_metadata['viewpoint'] = ' '.join(map(str, metadata['viewpoint']))
str_metadata['points'] = str(metadata['points'])
tmpl = template.format(**str_metadata)
return tmpl
def _metadata_is_consistent(metadata):
""" sanity check for metadata. just some basic checks.
"""
checks = []
required = ('version', 'fields', 'size', 'width', 'height', 'points',
'viewpoint', 'data')
for f in required:
if f not in metadata:
print('%s required' % f)
checks.append((lambda m: all([k in m for k in required]),
'missing field'))
checks.append((lambda m: len(m['type']) == len(m['count']) ==
len(m['fields']),
'length of type, count and fields must be equal'))
checks.append((lambda m: m['height'] > 0,
'height must be greater than 0'))
checks.append((lambda m: m['width'] > 0,
'width must be greater than 0'))
checks.append((lambda m: m['points'] > 0,
'points must be greater than 0'))
checks.append((lambda m: m['data'].lower() in ('ascii', 'binary',
'binary_compressed'),
'unknown data type:'
'should be ascii/binary/binary_compressed'))
ok = True
for check, msg in checks:
if not check(metadata):
print('error:', msg)
ok = False
return ok
def _build_dtype(metadata):
""" build numpy structured array dtype from pcl metadata.
note that fields with count > 1 are 'flattened' by creating multiple
single-count fields.
TODO: allow 'proper' multi-count fields.
"""
fieldnames = []
typenames = []
for f, c, t, s in zip(metadata['fields'],
metadata['count'],
metadata['type'],
metadata['size']):
np_type = pcd_type_to_numpy_type[(t, s)]
if c == 1:
fieldnames.append(f)
typenames.append(np_type)
else:
fieldnames.extend(['%s_%04d' % (f, i) for i in range(c)])
typenames.extend([np_type] * c)
dtype = np.dtype(list(zip(fieldnames, typenames)))
return dtype
def parse_binary_pc_data(f, dtype, metadata):
rowstep = metadata['points'] * dtype.itemsize
# for some reason pcl adds empty space at the end of files
buf = f.read(rowstep)
return np.fromstring(buf, dtype=dtype)
def point_cloud_from_fileobj(f):
""" parse pointcloud coming from file object f
"""
header = []
while True:
ln = f.readline().strip()
if not isinstance(ln, str):
ln = ln.decode('utf-8')
header.append(ln)
if ln.startswith('DATA'):
metadata = parse_header(header)
dtype = _build_dtype(metadata)
break
pc_data = parse_binary_pc_data(f, dtype, metadata)
return PointCloud(metadata, pc_data)
def point_cloud_from_path(fname):
""" load point cloud in binary format
"""
with open(fname, 'rb') as f:
pc = point_cloud_from_fileobj(f)
return pc
def point_cloud_to_fileobj(pc, fileobj, data_compression=None):
""" write pointcloud as .pcd to fileobj.
if data_compression is not None it overrides pc.data.
"""
metadata = pc.get_metadata()
if data_compression is not None:
data_compression = data_compression.lower()
assert (data_compression in ('ascii', 'binary', 'binary_compressed'))
metadata['data'] = data_compression
header = write_header(metadata).encode('utf-8')
fileobj.write(header)
fileobj.write(pc.pc_data.tostring())
class PointCloud(object):
def __init__(self, metadata, pc_data):
self.metadata_keys = metadata.keys()
self.__dict__.update(metadata)
self.pc_data = pc_data
self.check_sanity()
def get_metadata(self):
""" returns copy of metadata """
metadata = {}
for k in self.metadata_keys:
metadata[k] = copy.copy(getattr(self, k))
return metadata
def check_sanity(self):
# pdb.set_trace()
md = self.get_metadata()
assert (_metadata_is_consistent(md))
assert (len(self.pc_data) == self.points)
assert (self.width * self.height == self.points)
assert (len(self.fields) == len(self.count))
assert (len(self.fields) == len(self.type))
def save_pcd(self, fname, compression=None, **kwargs):
if 'data_compression' in kwargs:
print('\033[93m' + 'data_compression keyword is deprecated for'
' compression' + '\033[1m')
compression = kwargs['data_compression']
with open(fname, 'wb') as f:
point_cloud_to_fileobj(self, f, compression)
def save_pcd_to_fileobj(self, fileobj, compression=None, **kwargs):
if 'data_compression' in kwargs:
print('\033[93m' + 'data_compression keyword is deprecated for'
' compression' + '\033[1m')
compression = kwargs['data_compression']
point_cloud_to_fileobj(self, fileobj, compression)
def copy(self):
new_pc_data = np.copy(self.pc_data)
new_metadata = self.get_metadata()
return PointCloud(new_metadata, new_pc_data)
def to_msg(self):
# TODO is there some metadata we want to attach?
return array_to_pointcloud2(self.pc_data)
@staticmethod
def from_path(fname):
return point_cloud_from_path(fname)
@staticmethod
def from_msg(msg, squeeze=True):
""" from pointcloud2 msg
squeeze: fix when clouds get 1 as first dim
"""
md = {'version': .7,
'fields': [],
'size': [],
'count': [],
'width': 0,
'height': 1,
'viewpoint': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
'points': 0,
'type': [],
'data': 'binary_compressed'}
for field in msg.fields:
md['fields'].append(field.name)
t, s = pc2_type_to_pcd_type[field.datatype]
md['type'].append(t)
md['size'].append(s)
# TODO handle multicount correctly
if field.count > 1:
print('\033[93m' + 'fields with count > 1 are not well tested' + '\033[1m')
md['count'].append(field.count)
pc_data = np.squeeze(pointcloud2_to_array(msg))
md['width'] = len(pc_data)
md['points'] = len(pc_data)
pc = PointCloud(md, pc_data)
return pc
| 18,853 | 36.859438 | 114 | py |
synfeal | synfeal-main/synfeal_collection/src/__init__.py | 0 | 0 | 0 | py |
|
synfeal | synfeal-main/synfeal_collection/src/pypcd.py | """
The MIT License (MIT)
Copyright (c) 2015 Daniel Maturana, Carnegie Mellon University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Read and write PCL .pcd files in python.
[email protected], 2013
"""
import re
import struct
import copy
import numpy as np
from sensor_msgs.msg import PointField
from sensor_msgs.msg import PointCloud2
# -----------------------------------------------------------------------------
# ----- Settings
# -----------------------------------------------------------------------------
DUMMY_FIELD_PREFIX = '__'
# sizes (in bytes) of PointField types
pftype_sizes = {PointField.INT8: 1, PointField.UINT8: 1, PointField.INT16: 2, PointField.UINT16: 2,
PointField.INT32: 4, PointField.UINT32: 4, PointField.FLOAT32: 4, PointField.FLOAT64: 8}
# mappings between PointField types and numpy types
type_mappings = [(PointField.INT8, np.dtype('int8')),
(PointField.UINT8, np.dtype('uint8')),
(PointField.INT16, np.dtype('int16')),
(PointField.UINT16, np.dtype('uint16')),
(PointField.INT32, np.dtype('int32')),
(PointField.UINT32, np.dtype('uint32')),
(PointField.FLOAT32, np.dtype('float32')),
(PointField.FLOAT64, np.dtype('float64'))]
pftype_to_nptype = dict(type_mappings)
nptype_to_pftype = dict((nptype, pftype) for pftype, nptype in type_mappings)
pc2_pcd_type_mappings = [(PointField.INT8, ('I', 1)),
(PointField.UINT8, ('U', 1)),
(PointField.INT16, ('I', 2)),
(PointField.UINT16, ('U', 2)),
(PointField.INT32, ('I', 4)),
(PointField.UINT32, ('U', 4)),
(PointField.FLOAT32, ('F', 4)),
(PointField.FLOAT64, ('F', 8))]
pc2_type_to_pcd_type = dict(pc2_pcd_type_mappings)
pcd_type_to_pc2_type = dict((q, p) for (p, q) in pc2_pcd_type_mappings)
numpy_pcd_type_mappings = [(np.dtype('float32'), ('F', 4)),
(np.dtype('float64'), ('F', 8)),
(np.dtype('uint8'), ('U', 1)),
(np.dtype('uint16'), ('U', 2)),
(np.dtype('uint32'), ('U', 4)),
(np.dtype('uint64'), ('U', 8)),
(np.dtype('int16'), ('I', 2)),
(np.dtype('int32'), ('I', 4)),
(np.dtype('int64'), ('I', 8))]
numpy_type_to_pcd_type = dict(numpy_pcd_type_mappings)
pcd_type_to_numpy_type = dict((q, p) for (p, q) in numpy_pcd_type_mappings)
# -----------------------------------------------------------------------------
# ----- numpy <-> pc2 bridge
# -----------------------------------------------------------------------------
def split_rgb_field(cloud_arr):
'''Takes an array with a named 'rgb' float32 field, and returns an array in which
this has been split into 3 uint 8 fields: 'r', 'g', and 'b'.
(pcl stores rgb in packed 32 bit floats)
'''
rgb_arr = cloud_arr['rgb'].copy()
rgb_arr.dtype = np.uint32
r = np.asarray((rgb_arr >> 16) & 255, dtype=np.uint8)
g = np.asarray((rgb_arr >> 8) & 255, dtype=np.uint8)
b = np.asarray(rgb_arr & 255, dtype=np.uint8)
# create a new array, without rgb, but with r, g, and b fields
new_dtype = []
for field_name in cloud_arr.dtype.names:
field_type, field_offset = cloud_arr.dtype.fields[field_name]
if not field_name == 'rgb':
new_dtype.append((field_name, field_type))
new_dtype.append(('r', np.uint8))
new_dtype.append(('g', np.uint8))
new_dtype.append(('b', np.uint8))
new_cloud_arr = np.zeros(cloud_arr.shape, new_dtype)
# fill in the new array
for field_name in new_cloud_arr.dtype.names:
if field_name == 'r':
new_cloud_arr[field_name] = r
elif field_name == 'g':
new_cloud_arr[field_name] = g
elif field_name == 'b':
new_cloud_arr[field_name] = b
else:
new_cloud_arr[field_name] = cloud_arr[field_name]
return new_cloud_arr
def merge_rgb_fields(cloud_arr):
'''Takes an array with named np.uint8 fields 'r', 'g', and 'b', and returns an array in
which they have been merged into a single np.float32 'rgb' field. The first byte of this
field is the 'r' uint8, the second is the 'g', uint8, and the third is the 'b' uint8.
This is the way that pcl likes to handle RGB colors for some reason.
'''
r = np.asarray(cloud_arr['r'], dtype=np.uint32)
g = np.asarray(cloud_arr['g'], dtype=np.uint32)
b = np.asarray(cloud_arr['b'], dtype=np.uint32)
rgb_arr = np.array((r << 16) | (g << 8) | (b << 0), dtype=np.uint32)
# not sure if there is a better way to do this. i'm changing the type of the array
# from uint32 to float32, but i don't want any conversion to take place -jdb
rgb_arr.dtype = np.float32
# create a new array, without r, g, and b, but with rgb float32 field
new_dtype = []
for field_name in cloud_arr.dtype.names:
field_type, field_offset = cloud_arr.dtype.fields[field_name]
if field_name not in ('r', 'g', 'b'):
new_dtype.append((field_name, field_type))
new_dtype.append(('rgb', np.float32))
new_cloud_arr = np.zeros(cloud_arr.shape, new_dtype)
# fill in the new array
for field_name in new_cloud_arr.dtype.names:
if field_name == 'rgb':
new_cloud_arr[field_name] = rgb_arr
else:
new_cloud_arr[field_name] = cloud_arr[field_name]
return new_cloud_arr
def arr_to_fields(cloud_arr):
'''Convert a numpy record datatype into a list of PointFields.
'''
fields = []
for field_name in cloud_arr.dtype.names:
np_field_type, field_offset = cloud_arr.dtype.fields[field_name]
pf = PointField()
pf.name = field_name
pf.datatype = nptype_to_pftype[np_field_type]
pf.offset = field_offset
pf.count = 1 # is this ever more than one?
fields.append(pf)
return fields
def pointcloud2_to_dtype(cloud_msg):
'''Convert a list of PointFields to a numpy record datatype.
'''
offset = 0
np_dtype_list = []
for f in cloud_msg.fields:
while offset < f.offset:
# might be extra padding between fields
np_dtype_list.append(('%s%d' % (DUMMY_FIELD_PREFIX, offset), np.uint8))
offset += 1
np_dtype_list.append((f.name, pftype_to_nptype[f.datatype]))
offset += pftype_sizes[f.datatype]
# might be extra padding between points
while offset < cloud_msg.point_step:
np_dtype_list.append(('%s%d' % (DUMMY_FIELD_PREFIX, offset), np.uint8))
offset += 1
return np_dtype_list
def pointcloud2_to_array(cloud_msg, split_rgb=False, remove_padding=True):
''' Converts a rospy PointCloud2 message to a numpy recordarray
Reshapes the returned array to have shape (height, width), even if the height is 1.
The reason for using np.fromstring rather than struct.unpack is speed... especially
for large point clouds, this will be <much> faster.
'''
# construct a numpy record type equivalent to the point type of this cloud
dtype_list = pointcloud2_to_dtype(cloud_msg)
# parse the cloud into an array
cloud_arr = np.fromstring(cloud_msg.data, dtype_list)
# remove the dummy fields that were added
if remove_padding:
cloud_arr = cloud_arr[
[fname for fname, _type in dtype_list if not (fname[:len(DUMMY_FIELD_PREFIX)] == DUMMY_FIELD_PREFIX)]]
if split_rgb:
cloud_arr = split_rgb_field(cloud_arr)
return np.reshape(cloud_arr, (cloud_msg.height, cloud_msg.width))
def array_to_pointcloud2(cloud_arr, stamp=None, frame_id=None, merge_rgb=False):
'''Converts a numpy record array to a sensor_msgs.msg.PointCloud2.
'''
if merge_rgb:
cloud_arr = merge_rgb_fields(cloud_arr)
# make it 2d (even if height will be 1)
cloud_arr = np.atleast_2d(cloud_arr)
cloud_msg = PointCloud2()
if stamp is not None:
cloud_msg.header.stamp = stamp
if frame_id is not None:
cloud_msg.header.frame_id = frame_id
cloud_msg.height = cloud_arr.shape[0]
cloud_msg.width = cloud_arr.shape[1]
cloud_msg.fields = arr_to_fields(cloud_arr)
cloud_msg.is_bigendian = False # assumption
cloud_msg.point_step = cloud_arr.dtype.itemsize
cloud_msg.row_step = cloud_msg.point_step * cloud_arr.shape[1]
cloud_msg.is_dense = all([np.isfinite(cloud_arr[fname]).all() for fname in cloud_arr.dtype.names])
cloud_msg.data = cloud_arr.tostring()
return cloud_msg
# -----------------------------------------------------------------------------
# ----- Read/Write routines
# -----------------------------------------------------------------------------
def parse_header(lines):
metadata = {}
for ln in lines:
if ln.startswith('#') or len(ln) < 2:
continue
match = re.match('(\w+)\s+([\w\s\.]+)', ln)
if not match:
print("\033[93m" + "warning: can't understand line: %s" % ln + "\033[1m")
continue
key, value = match.group(1).lower(), match.group(2)
if key == 'version':
metadata[key] = value
elif key in ('fields', 'type'):
metadata[key] = value.split()
elif key in ('size', 'count'):
metadata[key] = list(map(int, value.split()))
elif key in ('width', 'height', 'points'):
metadata[key] = int(value)
elif key == 'viewpoint':
metadata[key] = list(map(float, value.split()))
elif key == 'data':
metadata[key] = value.strip().lower()
# TODO apparently count is not required?
# add some reasonable defaults
if 'count' not in metadata:
metadata['count'] = [1] * len(metadata['fields'])
if 'viewpoint' not in metadata:
metadata['viewpoint'] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
if 'version' not in metadata:
metadata['version'] = '.7'
return metadata
def write_header(metadata, rename_padding=False):
""" given metadata as dictionary return a string header.
"""
template = """\
VERSION {version}
FIELDS {fields}
SIZE {size}
TYPE {type}
COUNT {count}
WIDTH {width}
HEIGHT {height}
VIEWPOINT {viewpoint}
POINTS {points}
DATA {data}
"""
str_metadata = metadata.copy()
if not rename_padding:
str_metadata['fields'] = ' '.join(metadata['fields'])
else:
new_fields = []
for f in metadata['fields']:
if f == '_':
new_fields.append('padding')
else:
new_fields.append(f)
str_metadata['fields'] = ' '.join(new_fields)
str_metadata['size'] = ' '.join(map(str, metadata['size']))
str_metadata['type'] = ' '.join(metadata['type'])
str_metadata['count'] = ' '.join(map(str, metadata['count']))
str_metadata['width'] = str(metadata['width'])
str_metadata['height'] = str(metadata['height'])
str_metadata['viewpoint'] = ' '.join(map(str, metadata['viewpoint']))
str_metadata['points'] = str(metadata['points'])
tmpl = template.format(**str_metadata)
return tmpl
def _metadata_is_consistent(metadata):
""" sanity check for metadata. just some basic checks.
"""
checks = []
required = ('version', 'fields', 'size', 'width', 'height', 'points',
'viewpoint', 'data')
for f in required:
if f not in metadata:
print('%s required' % f)
checks.append((lambda m: all([k in m for k in required]),
'missing field'))
checks.append((lambda m: len(m['type']) == len(m['count']) ==
len(m['fields']),
'length of type, count and fields must be equal'))
checks.append((lambda m: m['height'] > 0,
'height must be greater than 0'))
checks.append((lambda m: m['width'] > 0,
'width must be greater than 0'))
checks.append((lambda m: m['points'] > 0,
'points must be greater than 0'))
checks.append((lambda m: m['data'].lower() in ('ascii', 'binary',
'binary_compressed'),
'unknown data type:'
'should be ascii/binary/binary_compressed'))
ok = True
for check, msg in checks:
if not check(metadata):
print('error:', msg)
ok = False
return ok
def _build_dtype(metadata):
""" build numpy structured array dtype from pcl metadata.
note that fields with count > 1 are 'flattened' by creating multiple
single-count fields.
TODO: allow 'proper' multi-count fields.
"""
fieldnames = []
typenames = []
for f, c, t, s in zip(metadata['fields'],
metadata['count'],
metadata['type'],
metadata['size']):
np_type = pcd_type_to_numpy_type[(t, s)]
if c == 1:
fieldnames.append(f)
typenames.append(np_type)
else:
fieldnames.extend(['%s_%04d' % (f, i) for i in range(c)])
typenames.extend([np_type] * c)
dtype = np.dtype(list(zip(fieldnames, typenames)))
return dtype
def parse_binary_pc_data(f, dtype, metadata):
rowstep = metadata['points'] * dtype.itemsize
# for some reason pcl adds empty space at the end of files
buf = f.read(rowstep)
return np.fromstring(buf, dtype=dtype)
def point_cloud_from_fileobj(f):
""" parse pointcloud coming from file object f
"""
header = []
while True:
ln = f.readline().strip()
if not isinstance(ln, str):
ln = ln.decode('utf-8')
header.append(ln)
if ln.startswith('DATA'):
metadata = parse_header(header)
dtype = _build_dtype(metadata)
break
pc_data = parse_binary_pc_data(f, dtype, metadata)
return PointCloud(metadata, pc_data)
def point_cloud_from_path(fname):
""" load point cloud in binary format
"""
with open(fname, 'rb') as f:
pc = point_cloud_from_fileobj(f)
return pc
def point_cloud_to_fileobj(pc, fileobj, data_compression=None):
""" write pointcloud as .pcd to fileobj.
if data_compression is not None it overrides pc.data.
"""
metadata = pc.get_metadata()
if data_compression is not None:
data_compression = data_compression.lower()
assert (data_compression in ('ascii', 'binary', 'binary_compressed'))
metadata['data'] = data_compression
header = write_header(metadata).encode('utf-8')
fileobj.write(header)
fileobj.write(pc.pc_data.tostring())
class PointCloud(object):
def __init__(self, metadata, pc_data):
self.metadata_keys = metadata.keys()
self.__dict__.update(metadata)
self.pc_data = pc_data
self.check_sanity()
def get_metadata(self):
""" returns copy of metadata """
metadata = {}
for k in self.metadata_keys:
metadata[k] = copy.copy(getattr(self, k))
return metadata
def check_sanity(self):
# pdb.set_trace()
md = self.get_metadata()
assert (_metadata_is_consistent(md))
assert (len(self.pc_data) == self.points)
assert (self.width * self.height == self.points)
assert (len(self.fields) == len(self.count))
assert (len(self.fields) == len(self.type))
def save_pcd(self, fname, compression=None, **kwargs):
if 'data_compression' in kwargs:
print('\033[93m' + 'data_compression keyword is deprecated for'
' compression' + '\033[1m')
compression = kwargs['data_compression']
with open(fname, 'wb') as f:
point_cloud_to_fileobj(self, f, compression)
def save_pcd_to_fileobj(self, fileobj, compression=None, **kwargs):
if 'data_compression' in kwargs:
print('\033[93m' + 'data_compression keyword is deprecated for'
' compression' + '\033[1m')
compression = kwargs['data_compression']
point_cloud_to_fileobj(self, fileobj, compression)
def copy(self):
new_pc_data = np.copy(self.pc_data)
new_metadata = self.get_metadata()
return PointCloud(new_metadata, new_pc_data)
def to_msg(self):
# TODO is there some metadata we want to attach?
return array_to_pointcloud2(self.pc_data)
@staticmethod
def from_path(fname):
return point_cloud_from_path(fname)
@staticmethod
def from_msg(msg, squeeze=True):
""" from pointcloud2 msg
squeeze: fix when clouds get 1 as first dim
"""
md = {'version': .7,
'fields': [],
'size': [],
'count': [],
'width': 0,
'height': 1,
'viewpoint': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
'points': 0,
'type': [],
'data': 'binary_compressed'}
for field in msg.fields:
md['fields'].append(field.name)
t, s = pc2_type_to_pcd_type[field.datatype]
md['type'].append(t)
md['size'].append(s)
# TODO handle multicount correctly
if field.count > 1:
print('\033[93m' + 'fields with count > 1 are not well tested' + '\033[1m')
md['count'].append(field.count)
pc_data = np.squeeze(pointcloud2_to_array(msg))
md['width'] = len(pc_data)
md['points'] = len(pc_data)
pc = PointCloud(md, pc_data)
return pc | 18,804 | 36.837022 | 114 | py |
synfeal | synfeal-main/models/pointnet.py | import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
# this is a regularization to avoid overfitting! It adds another term to the cost function to penalize the complexity of the models.
def feature_transform_regularizer(trans):
d = trans.size()[1]
batchsize = trans.size()[0]
I = torch.eye(d)[None, :, :]
if trans.is_cuda:
I = I.cuda()
loss = torch.mean(torch.norm(torch.bmm(trans, trans.transpose(2,1)) - I, dim=(1,2)))
return loss
class STN3d(nn.Module): # spatial transformer network 3d, paper: https://arxiv.org/pdf/1506.02025v3.pdf
def __init__(self):
super(STN3d, self).__init__()
self.conv1 = torch.nn.Conv1d(3, 64, 1) # conv1d because we are sliding the filter over 1 dimensional.
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 9)
self.relu = nn.ReLU()
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
def forward(self, x):
batchsize = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=True)[0]
x = x.view(-1, 1024)
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.array([1,0,0,0,1,0,0,0,1]).astype(np.float32))).view(1,9).repeat(batchsize,1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, 3, 3)
return x
class STNkd(nn.Module):
def __init__(self, k=64):
super(STNkd, self).__init__()
self.conv1 = torch.nn.Conv1d(k, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k*k)
self.relu = nn.ReLU()
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
self.k = k
def forward(self, x):
batchsize = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=True)[0]
x = x.view(-1, 1024)
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.eye(self.k).flatten().astype(np.float32))).view(1,self.k*self.k).repeat(batchsize,1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, self.k, self.k)
return x
class PointNetfeat(nn.Module):
def __init__(self, feature_transform = False):
super(PointNetfeat, self).__init__()
#self.stn = STN3d()
self.conv1 = torch.nn.Conv1d(3, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.feature_transform = feature_transform
if self.feature_transform:
self.fstn = STNkd(k=64)
def forward(self, x):
n_pts = x.size()[2] # input is (batch_size, number_of_features, number_of_points)
#trans = self.stn(x)
#x = x.transpose(2, 1) # this swaps number of feature with number of points --> (batch_size, number_of_points, number_of_features)
#x = torch.bmm(x, trans) # batch matrix-matrix product --> x.shape = (32, 2500, 3), trans.shape = (32, 3, 3) --> output = (32, 2500, 3)
#x = x.transpose(2, 1) # now x.shape = (32, 3, 2500)
x = F.relu(self.bn1(self.conv1(x))) # x.shape = (32, 64, 2500)
if self.feature_transform:
trans_feat = self.fstn(x)
x = x.transpose(2,1)
x = torch.bmm(x, trans_feat)
x = x.transpose(2,1)
else:
trans_feat = None
x = F.relu(self.bn2(self.conv2(x)))
x = self.bn3(self.conv3(x)) #x.shape (32, 1024, 2500)
x = torch.max(x, 2, keepdim=True)[0] # MAX POOLING
x = x.view(-1, 1024) # flattening
trans = 0
return x, trans, trans_feat
class PointNet(nn.Module):
def __init__(self, feature_transform=False):
super(PointNet, self).__init__()
self.feature_transform = feature_transform
self.feat = PointNetfeat(feature_transform=feature_transform)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3_trans = nn.Linear(256, 3)
self.fc3_rot = nn.Linear(256, 4)
self.dropout = nn.Dropout(p=0.3)
self.bn1 = nn.BatchNorm1d(512)
self.bn2 = nn.BatchNorm1d(256)
self.relu = nn.ReLU()
def forward(self, x):
x, trans, trans_feat = self.feat(x) # the output x is the global feature (1024x1)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.dropout(self.fc2(x))))
x_trans = self.fc3_trans(x) # Joint Learning!
x_rot = self.fc3_rot(x) # Joint Learning!
x_pose = torch.cat((x_trans, x_rot), dim=1)
return x_pose, trans, trans_feat # softmax removed!
| 5,796 | 34.564417 | 143 | py |
synfeal | synfeal-main/models/pointnet_classification.py | import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
class STN3d(nn.Module):
def __init__(self):
super(STN3d, self).__init__()
self.conv1 = torch.nn.Conv1d(3, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 9)
self.relu = nn.ReLU()
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
def forward(self, x):
batchsize = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=True)[0]
x = x.view(-1, 1024)
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.array([1,0,0,0,1,0,0,0,1]).astype(np.float32))).view(1,9).repeat(batchsize,1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, 3, 3)
return x
class STNkd(nn.Module):
def __init__(self, k=64):
super(STNkd, self).__init__()
self.conv1 = torch.nn.Conv1d(k, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k*k)
self.relu = nn.ReLU()
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
self.k = k
def forward(self, x):
batchsize = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=True)[0]
x = x.view(-1, 1024)
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.eye(self.k).flatten().astype(np.float32))).view(1,self.k*self.k).repeat(batchsize,1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, self.k, self.k)
return x
class PointNetfeat(nn.Module):
def __init__(self, global_feat = True, feature_transform = False):
super(PointNetfeat, self).__init__()
self.stn = STN3d()
self.conv1 = torch.nn.Conv1d(3, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.global_feat = global_feat
self.feature_transform = feature_transform
if self.feature_transform:
self.fstn = STNkd(k=64)
def forward(self, x):
n_pts = x.size()[2]
trans = self.stn(x)
x = x.transpose(2, 1)
x = torch.bmm(x, trans)
x = x.transpose(2, 1)
x = F.relu(self.bn1(self.conv1(x)))
if self.feature_transform:
trans_feat = self.fstn(x)
x = x.transpose(2,1)
x = torch.bmm(x, trans_feat)
x = x.transpose(2,1)
else:
trans_feat = None
pointfeat = x
x = F.relu(self.bn2(self.conv2(x)))
x = self.bn3(self.conv3(x))
x = torch.max(x, 2, keepdim=True)[0]
x = x.view(-1, 1024)
if self.global_feat:
return x, trans, trans_feat
else:
x = x.view(-1, 1024, 1).repeat(1, 1, n_pts)
return torch.cat([x, pointfeat], 1), trans, trans_feat
class PointNetCls(nn.Module):
def __init__(self, k=2, feature_transform=False):
super(PointNetCls, self).__init__()
self.feature_transform = feature_transform
self.feat = PointNetfeat(global_feat=True, feature_transform=feature_transform)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k)
self.dropout = nn.Dropout(p=0.3)
self.bn1 = nn.BatchNorm1d(512)
self.bn2 = nn.BatchNorm1d(256)
self.relu = nn.ReLU()
def forward(self, x):
x, trans, trans_feat = self.feat(x) # the output x is the global feature (1024x1)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.dropout(self.fc2(x))))
x = self.fc3(x)
return F.log_softmax(x, dim=1), trans, trans_feat # this must change
| 4,884 | 32.006757 | 128 | py |
synfeal | synfeal-main/models/loss_functions.py | import torch
from torch import nn
class BetaLoss(nn.Module):
def __init__(self, beta= 512):
super(BetaLoss, self).__init__()
self.beta = beta
#self.loss_fn = torch.nn.L1Loss() # PoseNet said that L1 was the best
self.loss_fn = torch.nn.MSELoss()
def forward(self, pred, targ):
"""
:param pred: N x 7
:param targ: N x 7
:return:
"""
# Translation loss
loss = self.loss_fn(pred[:, :3], targ[:, :3])
# Rotation loss
loss += self.beta * self.loss_fn(pred[:, 3:], targ[:, 3:]) ## see paper: https://arxiv.org/abs/1704.00390
return loss
class DynamicLoss(nn.Module):
def __init__(self, sx=0.0, sq=-3.0):
super(DynamicLoss, self).__init__()
#self.loss_fn = torch.nn.L1Loss() # PoseNet said that L1 was the best
self.loss_fn = torch.nn.MSELoss()
self.sx = torch.nn.Parameter(torch.Tensor([sx]), requires_grad=True) # Parameter: When a Parameter is associated with a module as a model attribute, it gets added to the parameter list automatically and can be accessed using the 'parameters' iterator.
self.sq = torch.nn.Parameter(torch.Tensor([sq]), requires_grad=True)
def forward(self, pred, targ):
"""
:param pred: N x 7
:param targ: N x 7
:return:
"""
# Translation loss
loss = torch.exp(-self.sx) * self.loss_fn(pred[:, :3], targ[:, :3]) + self.sx
# Rotation loss
loss += torch.exp(-self.sq) * self.loss_fn(pred[:, 3:], targ[:, 3:]) + self.sq ## see paper: https://arxiv.org/abs/1704.00390
return loss | 1,656 | 39.414634 | 261 | py |
synfeal | synfeal-main/models/poselstm.py |
from turtle import forward
from unicodedata import bidirectional
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
from torchvision import transforms, models
# based on: https://github.com/hazirbas/poselstm-pytorch
# paper: https://openaccess.thecvf.com/content_ICCV_2017/papers/Walch_Image-Based_Localization_Using_ICCV_2017_paper.pdf
class PoseLSTM(nn.Module):
def __init__(self, hidden_size = 128, pretrained = True, aux_logits=True):
super(PoseLSTM, self).__init__()
self.hidden_size = hidden_size
self.aux_logits = aux_logits
if pretrained:
base_model = models.inception_v3(weights='Inception_V3_Weights.DEFAULT')
else:
base_model = models.inception_v3()
base_model.aux_logits = True
self.Conv2d_1a_3x3 = base_model.Conv2d_1a_3x3
self.Conv2d_2a_3x3 = base_model.Conv2d_2a_3x3
self.Conv2d_2b_3x3 = base_model.Conv2d_2b_3x3
self.Conv2d_3b_1x1 = base_model.Conv2d_3b_1x1
self.Conv2d_4a_3x3 = base_model.Conv2d_4a_3x3
self.Mixed_5b = base_model.Mixed_5b
self.Mixed_5c = base_model.Mixed_5c
self.Mixed_5d = base_model.Mixed_5d
self.Mixed_6a = base_model.Mixed_6a
self.Mixed_6b = base_model.Mixed_6b
self.Mixed_6c = base_model.Mixed_6c
self.Mixed_6d = base_model.Mixed_6d
self.Mixed_6e = base_model.Mixed_6e
self.Mixed_7a = base_model.Mixed_7a
self.Mixed_7b = base_model.Mixed_7b
self.Mixed_7c = base_model.Mixed_7c
if aux_logits:
self.aux1 = InceptionAux(288, stride=7, hidden_size = self.hidden_size)
self.aux2 = InceptionAux(768, stride=3, hidden_size = self.hidden_size)
self.lstm_regression = LstmRegression(dropout_rate=0.5, hidden_size=self.hidden_size)
def forward(self, x, verbose=False): # this is where we pass the input into the module
# 299 x 299 x 3
x = self.Conv2d_1a_3x3(x)
# 149 x 149 x 32
x = self.Conv2d_2a_3x3(x)
# 147 x 147 x 32
x = self.Conv2d_2b_3x3(x)
# 147 x 147 x 64
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 73 x 73 x 64
x = self.Conv2d_3b_1x1(x)
# 73 x 73 x 80
x = self.Conv2d_4a_3x3(x)
# 71 x 71 x 192
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 35 x 35 x 192
x = self.Mixed_5b(x) # mixed is the inception module!!
# 35 x 35 x 256
x = self.Mixed_5c(x)
# 35 x 35 x 288
x = self.Mixed_5d(x)
# 35 x 35 x 288
if self.aux_logits and self.training:
pose_aux1 = self.aux1(x)
x = self.Mixed_6a(x)
# 17 x 17 x 768
x = self.Mixed_6b(x)
# 17 x 17 x 768
x = self.Mixed_6c(x)
# 17 x 17 x 768
x = self.Mixed_6d(x)
# 17 x 17 x 768
x = self.Mixed_6e(x)
# 17 x 17 x 768
if self.aux_logits and self.training:
pose_aux2 = self.aux2(x)
x = self.Mixed_7a(x)
# 8 x 8 x 1280
x = self.Mixed_7b(x)
# 8 x 8 x 2048
x = self.Mixed_7c(x)
# 8 x 8 x 2048
x = F.avg_pool2d(x, kernel_size=8)
# 1 x 1 x 2048
# 1 x 1 x 2048
x = x.view(x.size(0), -1)
# 2048
pose = self.lstm_regression(x)
if self.aux_logits and self.training:
return pose_aux1, pose_aux2, pose
else:
return pose
class InceptionAux(nn.Module):
def __init__(self, in_channels, stride, hidden_size):
super(InceptionAux, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=128, kernel_size=(1,1))
self.fc = nn.Linear(3200, 2048)
self.relu = nn.ReLU()
self.pool = nn.AvgPool2d(kernel_size=5, stride=stride)
self.lstm_regression = LstmRegression(dropout_rate=0.7, hidden_size=hidden_size)
def forward(self, x):
x = self.pool(x)
x = self.relu(self.conv(x))
x = x.reshape(x.shape[0], -1)
x = self.relu(self.fc(x))
pose = self.lstm_regression(x)
return pose
class LstmRegression(nn.Module):
def __init__(self, dropout_rate, hidden_size):
super(LstmRegression, self).__init__()
#TODO: try hidden_size = 32
self.hidden_size = hidden_size
self.lstm_lr = nn.LSTM(input_size=64, hidden_size = hidden_size, bidirectional = True, batch_first = True)
self.lstm_ud = nn.LSTM(input_size=32, hidden_size = hidden_size, bidirectional = True, batch_first = True)
self.pos = nn.Linear(hidden_size*4, 3, bias=True)
self.ori = nn.Linear(hidden_size*4, 4, bias=True)
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self,x):
# x is of shape (N,1,2048)
x = x.view(x.size(0),32, 64)
_, (hidden_state_lr, _) = self.lstm_lr(x.permute(0,1,2)) # to run row by row
_, (hidden_state_ud, _) = self.lstm_ud(x.permute(0,2,1)) # to run col by col
# hidden_state_lr.shape = [2, batch_size, hidden_size]
lstm_vector = torch.cat((hidden_state_lr[0,:,:],
hidden_state_lr[1,:,:],
hidden_state_ud[0,:,:],
hidden_state_ud[1,:,:]), 1)
lstm_vector = self.dropout(lstm_vector)
pos = self.pos(lstm_vector)
ori = self.ori(lstm_vector)
pose = torch.cat((pos, ori), dim=1)
return pose
# if __name__ == "__main__":
# model = PoseLSTM()
# print(model(torch.rand(10,3,299,299))[0].shape) | 6,396 | 33.766304 | 120 | py |
synfeal | synfeal-main/models/posenet.py |
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
from torchvision import transforms, models
#https://github.com/youngguncho/PoseNet-Pytorch/blob/6c583a345a20ba17f67b76e54a26cf78e2811604/posenet_simple.py#L119
#https://pytorch.org/hub/pytorch_vision_inception_v3/
class PoseNetGoogleNet(nn.Module):
def __init__(self, pretrained,dropout_rate=0.0, aux_logits=True):
super(PoseNetGoogleNet, self).__init__()
self.dropout_rate = dropout_rate
self.aux_logits = aux_logits
if pretrained:
base_model = models.inception_v3(weights='Inception_V3_Weights.DEFAULT')
else:
base_model = models.inception_v3()
base_model.aux_logits = True
self.Conv2d_1a_3x3 = base_model.Conv2d_1a_3x3
self.Conv2d_2a_3x3 = base_model.Conv2d_2a_3x3
self.Conv2d_2b_3x3 = base_model.Conv2d_2b_3x3
self.Conv2d_3b_1x1 = base_model.Conv2d_3b_1x1
self.Conv2d_4a_3x3 = base_model.Conv2d_4a_3x3
self.Mixed_5b = base_model.Mixed_5b
self.Mixed_5c = base_model.Mixed_5c
self.Mixed_5d = base_model.Mixed_5d
self.Mixed_6a = base_model.Mixed_6a
self.Mixed_6b = base_model.Mixed_6b
self.Mixed_6c = base_model.Mixed_6c
self.Mixed_6d = base_model.Mixed_6d
self.Mixed_6e = base_model.Mixed_6e
self.Mixed_7a = base_model.Mixed_7a
self.Mixed_7b = base_model.Mixed_7b
self.Mixed_7c = base_model.Mixed_7c
if aux_logits:
self.aux1 = InceptionAux1(288, dropout_rate)
self.aux2 = InceptionAux2(768, dropout_rate)
# Out 2
self.pos = nn.Linear(2048, 3, bias=True)
self.ori = nn.Linear(2048, 4, bias=True)
def forward(self, x, verbose=False): # this is where we pass the input into the module
# 299 x 299 x 3
x = self.Conv2d_1a_3x3(x)
# 149 x 149 x 32
x = self.Conv2d_2a_3x3(x)
# 147 x 147 x 32
x = self.Conv2d_2b_3x3(x)
# 147 x 147 x 64
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 73 x 73 x 64
x = self.Conv2d_3b_1x1(x)
# 73 x 73 x 80
x = self.Conv2d_4a_3x3(x)
# 71 x 71 x 192
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 35 x 35 x 192
x = self.Mixed_5b(x) # mixed is the inception module!!
# 35 x 35 x 256
x = self.Mixed_5c(x)
# 35 x 35 x 288
x = self.Mixed_5d(x)
# 35 x 35 x 288
if self.aux_logits and self.training:
pose_aux1 = self.aux1(x)
x = self.Mixed_6a(x)
# 17 x 17 x 768
x = self.Mixed_6b(x)
# 17 x 17 x 768
x = self.Mixed_6c(x)
# 17 x 17 x 768
x = self.Mixed_6d(x)
# 17 x 17 x 768
x = self.Mixed_6e(x)
# 17 x 17 x 768
if self.aux_logits and self.training:
pose_aux2 = self.aux2(x)
x = self.Mixed_7a(x)
# 8 x 8 x 1280
x = self.Mixed_7b(x)
# 8 x 8 x 2048
x = self.Mixed_7c(x)
# 8 x 8 x 2048
x = F.avg_pool2d(x, kernel_size=8)
# 1 x 1 x 2048
x = F.dropout(x, p=self.dropout_rate, training=self.training)
# 1 x 1 x 2048
x = x.view(x.size(0), -1)
# 2048
pos = self.pos(x)
ori = self.ori(x)
pose = torch.cat((pos, ori), dim=1)
if self.aux_logits and self.training:
return pose_aux1, pose_aux2, pose
else:
return pose
class InceptionAux1(nn.Module):
def __init__(self, in_channels, dropout_rate):
super(InceptionAux1, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=128, kernel_size=(1,1))
self.fc = nn.Linear(3200, 2048)
self.pos_aux1 = nn.Linear(in_features=2048, out_features=3)
self.ori_aux1 = nn.Linear(in_features=2048, out_features=4)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=dropout_rate)
self.pool = nn.AvgPool2d(kernel_size=5, stride=7)
def forward(self, x):
x = self.pool(x)
x = self.relu(self.conv(x))
x = x.reshape(x.shape[0], -1)
x = self.relu(self.fc(x))
x = self.dropout(x)
pos = self.pos_aux1(x)
ori = self.ori_aux1(x)
pose = torch.cat((pos, ori), dim=1)
return pose
class InceptionAux2(nn.Module):
def __init__(self, in_channels, dropout_rate):
super(InceptionAux2, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=128, kernel_size=(1,1))
self.fc = nn.Linear(3200, 2048)
self.pos_aux2 = nn.Linear(in_features=2048, out_features=3)
self.ori_aux2 = nn.Linear(in_features=2048, out_features=4)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=dropout_rate)
self.pool = nn.AvgPool2d(kernel_size=5, stride=3)
def forward(self, x):
x = self.pool(x)
x = self.relu(self.conv(x))
x = x.reshape(x.shape[0], -1)
x = self.relu(self.fc(x))
x = self.dropout(x)
pos = self.pos_aux2(x)
ori = self.ori_aux2(x)
pose = torch.cat((pos, ori), dim=1)
return pose
class PoseNetResNet(nn.Module): #https://github.com/youngguncho/PoseNet-Pytorch/blob/master/model.py
def __init__(self, pretrained, dropout_rate=0.0, aux_logits=False):
super(PoseNetResNet, self).__init__()
base_model = models.resnet34(pretrained=pretrained)
feat_in = base_model.fc.in_features
self.aux_logits = aux_logits
self.dropout_rate = dropout_rate
self.base_model = nn.Sequential(*list(base_model.children())[:-1])
self.fc_last = nn.Linear(feat_in, 2048, bias=True)
self.fc_position = nn.Linear(2048, 3, bias=True)
self.fc_rotation = nn.Linear(2048, 4, bias=True)
init_modules = [self.fc_last, self.fc_position, self.fc_rotation]
# init modules accoring to kaiming normal
# https://pytorch.org/docs/stable/nn.init.html
for module in init_modules:
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
def forward(self, x):
x = self.base_model(x)
x = x.view(x.size(0), -1)
x_fully = self.fc_last(x)
x = F.relu(x_fully)
if self.dropout_rate > 0:
x = F.dropout(x, p=self.dropout_rate, training=self.training)
position = self.fc_position(x)
rotation = self.fc_rotation(x)
x_pose = torch.cat((position, rotation), dim=1)
return x_pose
| 7,521 | 34.314554 | 116 | py |