code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
from __future__ import generators
import abc
import json
import os
import sys
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from wrn.utils import data_parallel
import torch.backends.cudnn as cudnn
from sklearn.metrics import accuracy_score
import torchvision.models as models
from datetime import datetime
#from wrn.wideResNet import resnet
from wrn.wideResNet_50_2 import WideResNet_50_2
from wrn.wideResNet import WideResNet
from customResnet50 import CustomResNet50
from mobilenetv2 import mobilenetv2
from peleeNet import peleeNet
from torch.optim.lr_scheduler import ReduceLROnPlateau
cudnn.benchmark = True
# Factory class
class ConvCNNFactory:
factories = {}
@staticmethod
def addFactory(id, convCNNFactory):
ConvCNNFactory.factories.put[id] = convCNNFactory
# A Template Method:
@staticmethod
def createCNN(id, opt):
if id not in ConvCNNFactory.factories:
ConvCNNFactory.factories[id] = \
eval(id + '.Factory()')
return ConvCNNFactory.factories[id].create(opt)
# Base class
class ConvCNN_Base(nn.Module):
__metaclass__ = abc.ABCMeta
def __init__(self, opt):
super(ConvCNN_Base, self).__init__()
self.opt = opt
######################################################################
######################################################################
######################################################################
# Specialized Class. Wide Residual Networks.
class WideResidualNetwork(ConvCNN_Base):
def __init__(self, opt):
super(WideResidualNetwork, self).__init__(opt)
# Initialize network
fully_convolutional = True
self.model = WideResNet(self.opt['wrn_depth'], self.opt['wrn_width'], ninputs=self.opt['nchannels'],
num_groups=self.opt['wrn_groups'],
num_classes=None if fully_convolutional else self.opt['wrn_num_classes'],
dropout=self.opt['dropout'])
#Overload parameters to not return the stats parameters which running_mean and running_std does not
#contain derivative calculation.
def parameters(self, recurse=True):
for name, param in self.named_parameters(recurse=recurse):
if not('stats' in name):
yield param
def forward(self, x):
return self.model.forward(x)
class Factory:
def create(self,opt): return WideResidualNetwork(opt)
######################################################################
######################################################################
######################################################################
# Specialized Class. ResNet
class ResNet50(ConvCNN_Base):
def __init__(self, opt):
super(ResNet50, self).__init__(opt)
# Initialize network
#self.model = CustomResNet50(out_size=(100,60))
self.model = CustomResNet50(out_size=None)
def forward(self, x):
return self.model(x)
class Factory:
def create(self,opt): return ResNet50(opt)
######################################################################
######################################################################
######################################################################
# Specialized Class. ResNet
class ResNet50Classificaton(ConvCNN_Base):
def __init__(self, opt, num_classes = 2):
super(ResNet50Classificaton, self).__init__(opt)
# two class problem (genuine-counterfeit)
num_classes = 2
# Initialize network
self.model = models.resnet50(pretrained=True)
#block_expansion = 1 # Resnet 18,34
block_expansion = 4 # Resnet 50,101,152
self.model.fc = nn.Linear(512 * block_expansion, num_classes)
def forward(self, x):
return self.model(x)
def forward_features(self,x):
x = self.model.conv1(x)
x = self.model.bn1(x)
x = self.model.relu(x)
x = self.model.maxpool(x)
x = self.model.layer1(x)
x = self.model.layer2(x)
x = self.model.layer3(x)
x = self.model.layer4(x)
x = self.model.avgpool(x)
x = x.view(x.size(0), -1)
return x
def forward_classifier(self,x):
return self.model.fc(x)
class Factory:
def create(self,opt): return ResNet50Classificaton(opt)
######################################################################
######################################################################
######################################################################
# Specialized Class. Wide Residual Networks.
class Mobilenetv2(ConvCNN_Base):
def __init__(self, opt):
super(Mobilenetv2, self).__init__(opt)
# Initialize network
self.model = mobilenetv2(pretrained=True)
def forward(self, x):
for i in range(14):
x = self.model.features[i](x) # torch.Size([40, 96, 14, 14])
return x
# return self.model.features(x) # returns B x 320 x 7 x 7
# 0 torch.Size([40, 32, 112, 112])
# 1 torch.Size([40, 16, 112, 112])
# 2 torch.Size([40, 24, 56, 56])
# 3 torch.Size([40, 24, 56, 56])
# 4 torch.Size([40, 32, 28, 28])
# 5 torch.Size([40, 32, 28, 28])
# 6 torch.Size([40, 32, 28, 28])
# 7 torch.Size([40, 64, 14, 14])
# 8 torch.Size([40, 64, 14, 14])
# 9 torch.Size([40, 64, 14, 14])
# 10 torch.Size([40, 64, 14, 14])
# 11 torch.Size([40, 96, 14, 14])
# 12 torch.Size([40, 96, 14, 14])
# 13 torch.Size([40, 96, 14, 14])
# 14 torch.Size([40, 160, 7, 7])
# 15 torch.Size([40, 160, 7, 7])
# 16 torch.Size([40, 160, 7, 7])
# 17 torch.Size([40, 320, 7, 7])
class Factory:
def create(self,opt): return Mobilenetv2(opt)
######################################################################
######################################################################
######################################################################
class Mobilenetv2Classification(ConvCNN_Base):
def __init__(self, opt):
super(Mobilenetv2Classification, self).__init__(opt)
# Initialize network
self.model = mobilenetv2(pretrained=True)
self.model.classifier = nn.Linear(in_features=1280, out_features=2)
def forward(self, x):
return self.model(x)
def forward_features(self,x):
x = self.model.features(x)
x = self.model.conv(x)
x = self.model.avgpool(x)
x = x.view(x.size(0), -1)
return x
def forward_classifier(self,x):
return self.model.classifier(x)
class Factory:
def create(self,opt): return Mobilenetv2Classification(opt)
######################################################################
######################################################################
######################################################################
# Specialized Class. Wide Residual Networks.
class InceptionNetwork(ConvCNN_Base):
def __init__(self, opt):
ConvCNN_Base.__init__(self, opt)
self.opt = opt
def __doepoch__(self, data_loader,
model,
optimizer, isTraining = False):
all_acc = []
all_losses = []
for batch_idx, (data, label) in enumerate(data_loader):
if self.opt['cuda']:
data = data.cuda()
label = label.cuda()
inputs = Variable(data)
targets = Variable(label)
train_preds = model(inputs)
train_preds = train_preds[0] #get only the last fc
training_loss = F.cross_entropy(train_preds, targets)
if isTraining:
optimizer.zero_grad()
training_loss.backward()
optimizer.step()
train_probs, train_classes = torch.max(train_preds, 1)
train_acc = accuracy_score(targets.data.cpu().numpy(),
train_classes.data.cpu().numpy())
all_acc.append(train_acc)
all_losses.append(training_loss.data.cpu().numpy()[0])
# Free memory
inputs = []
targets = []
return model, all_acc, all_losses
def train(self, train_loader, val_loader, resume = None):
best_validation_loss = sys.float_info.max
best_val_acc = 0
inception = models.inception_v3(pretrained=True)
# change the last fully convolutional layer
inception.fc = nn.Linear(2048, self.opt['wrn_num_classes'])
# Anulation of AuxLogits
#modules_filtered = [not i == inception.AuxLogits for i in inception.children()]
#inception = nn.Sequential(*list(np.array(list(inception.children()))[modules_filtered]))
inception.AuxLogits.fc = nn.Linear(768, self.opt['wrn_num_classes'])
# create optimizer
optimizer = self.create_optimizer(params=inception.parameters(),
method=self.opt['wrn_optim_method'],
lr = self.opt['wrn_lr'])
if resume is not None:
state_dict = torch.load(resume)
inception.load_state_dict(state_dict['state_dict'])
optimizer.load_state_dict(state_dict['optimizer'])
#inception = torch.nn.DataParallel(inception)
if self.opt['cuda']:
inception = inception.cuda()
inception.train()
try:
epoch = 0
while epoch < self.opt['wrn_epochs']:
epoch += 1
print ('epoch: %d' % epoch)
inception, train_all_acc, train_all_losses = \
self.__doepoch__(train_loader,
inception, optimizer, isTraining=True)
# update optimizer
if epoch % self.opt['wrn_epochs_update_optimizer'] == 0:
lr = optimizer.param_groups[0]['lr']
optimizer = self.create_optimizer(params=inception.parameters(),
method=self.opt['wrn_optim_method'],
lr=lr * self.opt['wrn_lr_decay_ratio'])
# do validation
if epoch % self.opt['wrn_val_freq'] == 0:
inception.eval()
inception, val_all_acc, val_all_losses = \
self.__doepoch__(val_loader,
inception, optimizer = None, isTraining=False)
val_acc_epoch = np.mean(val_all_acc)
val_losses_epoch = np.mean(val_all_losses)
if val_acc_epoch >= best_val_acc:
n_parameters = sum(p.numel() for p in inception.parameters())
self.log({
"train_loss": float(np.mean(train_all_losses)),
"train_acc": float(np.mean(train_all_acc)),
"test_acc": val_acc_epoch,
"epoch": epoch,
"num_classes": self.opt['wrn_num_classes'],
"n_parameters": n_parameters,
}, optimizer, inception.parameters())
best_val_acc = val_acc_epoch
inception.train()
except KeyboardInterrupt:
pass
return inception, best_val_acc
def load(self, modelPath, fully_convolutional = False):
inception = models.inception_v3(pretrained=False)
state_dict = torch.load(modelPath)
inception.load_state_dict(state_dict['state_dict'])
n_parameters = sum(p.numel() for p in inception.parameters())
print ('\nTotal number of parameters:'+ n_parameters)
return inception
def log(self,dictParams, optimizer, params, stats):
torch.save(dict(state_dict={k: v.data for k, v in params.items()},
optimizer=optimizer.state_dict(),
epoch=dictParams['epoch']),
open(os.path.join(self.opt['save'], 'model.pt7'), 'w'))
z = vars(self.opt).copy(); z.update(dictParams)
logname = os.path.join(self.opt['save'], 'log.txt')
with open(logname, 'a') as f:
f.write('json_stats: ' + json.dumps(z) + '\n')
print (z)
def forward(self, data_loader, inception):
model, data_all_acc, data_all_losses = \
self.__doepoch__(self, data_loader,
inception, optimizer = None, isTraining=False)
return model, data_all_acc, data_all_losses
def forward_fcnn(self, data_loader, f, params, stats):
feature_maps = []
targets = []
for batch_idx, (data, label) in enumerate(data_loader):
if self.opt['cuda']:
data = data.cuda()
label = label.cuda()
inputs = Variable(data)
target = Variable(label)
isTraining = False
featureMap = data_parallel(f, inputs, params, stats, isTraining,
np.arange(self.opt['wrn_ngpu']))
feature_maps.append(featureMap)
targets.append(target)
return feature_maps, targets
class Factory:
def create(self,opt): return InceptionNetwork(opt)
######################################################################
######################################################################
######################################################################
# Specialized Class. Wide Residual Networks.
class VGGNetwork(ConvCNN_Base):
def __init__(self, opt):
ConvCNN_Base.__init__(self, opt)
self.opt = opt
def __doepoch__(self, data_loader,
model,
optimizer, isTraining = False):
all_acc = []
all_losses = []
for batch_idx, (data, label) in enumerate(data_loader):
if self.opt['cuda']:
data = data.cuda()
label = label.cuda()
inputs = Variable(data)
targets = Variable(label)
train_preds = model(inputs)
training_loss = F.cross_entropy(train_preds, targets)
if isTraining:
optimizer.zero_grad()
training_loss.backward()
optimizer.step()
train_probs, train_classes = torch.max(train_preds, 1)
train_acc = accuracy_score(targets.data.cpu().numpy(),
train_classes.data.cpu().numpy())
all_acc.append(train_acc)
all_losses.append(training_loss.data.cpu().numpy()[0])
# Free memory
inputs = []
targets = []
return model, all_acc, all_losses
def train(self, train_loader, val_loader, resume = None):
best_validation_loss = sys.float_info.max
best_val_acc = 0
vgg16 = models.vgg16(pretrained=True)
# change the last fully convolutional layer
vgg16.classifier = nn.Sequential(*list(vgg16.classifier)[:-1] + [nn.Linear(4096, self.opt['wrn_num_classes'])])
# create optimizer
optimizer = self.create_optimizer(params=vgg16.parameters(),
method=self.opt['wrn_optim_method'],
lr = self.opt['wrn_lr'])
if resume is not None:
state_dict = torch.load(resume)
vgg16.load_state_dict(state_dict['state_dict'])
optimizer.load_state_dict(state_dict['optimizer'])
if self.opt['cuda']:
vgg16 = vgg16.cuda()
vgg16.train()
try:
epoch = 0
while epoch < self.opt['wrn_epochs']:
epoch += 1
print ('epoch: %d' % epoch)
vgg16, train_all_acc, train_all_losses = \
self.__doepoch__(train_loader,
vgg16, optimizer, isTraining=True)
# update optimizer
if epoch % self.opt['wrn_epochs_update_optimizer'] == 0:
lr = optimizer.param_groups[0]['lr']
optimizer = self.create_optimizer(params=vgg16.parameters(),
method=self.opt['wrn_optim_method'],
lr=lr * self.opt['wrn_lr_decay_ratio'])
# do validation
if epoch % self.opt['wrn_val_freq'] == 0:
vgg16.eval()
vgg16, val_all_acc, val_all_losses = \
self.__doepoch__(val_loader,
vgg16, optimizer = None, isTraining=False)
val_acc_epoch = np.mean(val_all_acc)
val_losses_epoch = np.mean(val_all_losses)
if val_acc_epoch >= best_val_acc:
n_parameters = sum(p.numel() for p in vgg16.parameters())
self.log({
"train_loss": float(np.mean(train_all_losses)),
"train_acc": float(np.mean(train_all_acc)),
"test_acc": val_acc_epoch,
"epoch": epoch,
"num_classes": self.opt['wrn_num_classes'],
"n_parameters": n_parameters,
}, optimizer, vgg16.parameters())
best_val_acc = val_acc_epoch
vgg16.train()
except KeyboardInterrupt:
pass
return vgg16, best_val_acc
def load(self, modelPath, fully_convolutional = False):
inception = models.vgg16(pretrained=False)
state_dict = torch.load(modelPath)
inception.load_state_dict(state_dict['state_dict'])
n_parameters = sum(p.numel() for p in inception.parameters())
print ('\nTotal number of parameters:'+ n_parameters)
return inception
def log(self,dictParams, optimizer, params, stats):
torch.save(dict(state_dict={k: v.data for k, v in params.items()},
optimizer=optimizer.state_dict(),
epoch=dictParams['epoch']),
open(os.path.join(self.opt['save'], 'model.pt7'), 'w'))
z = vars(self.opt).copy(); z.update(dictParams)
logname = os.path.join(self.opt['save'], 'log.txt')
with open(logname, 'a') as f:
f.write('json_stats: ' + json.dumps(z) + '\n')
print (z)
def forward(self, data_loader, inception):
model, data_all_acc, data_all_losses = \
self.__doepoch__(self, data_loader,
inception, optimizer = None, isTraining=False)
return model, data_all_acc, data_all_losses
def forward_fcnn(self, data_loader, f, params, stats):
feature_maps = []
targets = []
for batch_idx, (data, label) in enumerate(data_loader):
if self.opt['cuda']:
data = data.cuda()
label = label.cuda()
inputs = Variable(data)
target = Variable(label)
isTraining = False
featureMap = data_parallel(f, inputs, params, stats, isTraining,
np.arange(self.opt['wrn_ngpu']))
feature_maps.append(featureMap)
targets.append(target)
return feature_maps, targets
class Factory:
def create(self,opt): return VGGNetwork(opt)
######################################################################
######################################################################
######################################################################
# Specialized Class. Wide Residual Networks.
class SqueezeNetNetwork(ConvCNN_Base):
def __init__(self, opt):
ConvCNN_Base.__init__(self, opt)
self.opt = opt
def __doepoch__(self, data_loader,
model,
optimizer, isTraining = False):
all_acc = []
all_losses = []
for batch_idx, (data, label) in enumerate(data_loader):
if self.opt['cuda']:
data = data.cuda()
label = label.cuda()
inputs = Variable(data)
targets = Variable(label)
#train_preds = model(inputs) ==> Not working, why???
train_preds = model.classifier(model.features(inputs))
train_preds = train_preds.squeeze()
training_loss = F.cross_entropy(train_preds.squeeze(), targets)
if isTraining:
optimizer.zero_grad()
training_loss.backward()
optimizer.step()
train_probs, train_classes = torch.max(train_preds, 1)
train_acc = accuracy_score(targets.data.cpu().numpy(),
train_classes.data.cpu().numpy())
all_acc.append(train_acc)
all_losses.append(training_loss.data.cpu().numpy()[0])
# Free memory
inputs = []
targets = []
return model, all_acc, all_losses
def train(self, train_loader, val_loader, resume = None):
best_validation_loss = sys.float_info.max
best_val_acc = 0
squeezenet = models.squeezenet1_0(pretrained=True)
# change the last fully convolutional layer
temp = list(squeezenet.classifier)
temp[1] = torch.nn.Conv2d(512, self.opt['wrn_num_classes'], kernel_size=(1, 1),
stride=(1, 1))
squeezenet.classifier = nn.Sequential(*temp)
# create optimizer
optimizer = self.create_optimizer(params=squeezenet.parameters(),
method=self.opt['wrn_optim_method'],
lr = self.opt['wrn_lr'])
if resume is not None:
state_dict = torch.load(resume)
squeezenet.load_state_dict(state_dict['state_dict'])
optimizer.load_state_dict(state_dict['optimizer'])
if self.opt['cuda']:
squeezenet = squeezenet.cuda()
squeezenet.train()
try:
epoch = 0
while epoch < self.opt['wrn_epochs']:
epoch += 1
print ('epoch: %d' % epoch)
squeezenet, train_all_acc, train_all_losses = \
self.__doepoch__(train_loader,
squeezenet, optimizer, isTraining=True)
# update optimizer
if epoch % self.opt['wrn_epochs_update_optimizer'] == 0:
lr = optimizer.param_groups[0]['lr']
optimizer = self.create_optimizer(params=squeezenet.parameters(),
method=self.opt['wrn_optim_method'],
lr=lr * self.opt['wrn_lr_decay_ratio'])
# do validation
if epoch % self.opt['wrn_val_freq'] == 0:
squeezenet.eval()
squeezenet, val_all_acc, val_all_losses = \
self.__doepoch__(val_loader,
squeezenet, optimizer = None, isTraining=False)
val_acc_epoch = np.mean(val_all_acc)
val_losses_epoch = np.mean(val_all_losses)
if val_acc_epoch >= best_val_acc:
n_parameters = sum(p.numel() for p in squeezenet.parameters())
self.log({
"train_loss": float(np.mean(train_all_losses)),
"train_acc": float(np.mean(train_all_acc)),
"test_acc": val_acc_epoch,
"epoch": epoch,
"num_classes": self.opt['wrn_num_classes'],
"n_parameters": n_parameters,
}, optimizer, squeezenet.parameters())
best_val_acc = val_acc_epoch
squeezenet.train()
except KeyboardInterrupt:
pass
return squeezenet, best_val_acc
def load(self, modelPath, fully_convolutional = False ):
inception = models.squeezenet(pretrained=False)
state_dict = torch.load(modelPath)
inception.load_state_dict(state_dict['state_dict'])
n_parameters = sum(p.numel() for p in inception.parameters())
print ('\nTotal number of parameters:'+ n_parameters)
return inception
def log(self,dictParams, optimizer, params, stats):
torch.save(dict(state_dict={k: v.data for k, v in params.items()},
optimizer=optimizer.state_dict(),
epoch=dictParams['epoch']),
open(os.path.join(self.opt['save'], 'model.pt7'), 'w'))
z = vars(self.opt).copy(); z.update(dictParams)
logname = os.path.join(self.opt['save'], 'log.txt')
with open(logname, 'a') as f:
f.write('json_stats: ' + json.dumps(z) + '\n')
print (z)
def forward(self, data_loader, inception):
model, data_all_acc, data_all_losses = \
self.__doepoch__(self, data_loader,
inception, optimizer = None, isTraining=False)
return model, data_all_acc, data_all_losses
def forward_fcnn(self, data_loader, f, params, stats):
feature_maps = []
targets = []
for batch_idx, (data, label) in enumerate(data_loader):
if self.opt['cuda']:
data = data.cuda()
label = label.cuda()
inputs = Variable(data)
target = Variable(label)
isTraining = False
featureMap = data_parallel(f, inputs, params, stats, isTraining,
np.arange(self.opt['wrn_ngpu']))
feature_maps.append(featureMap)
targets.append(target)
return feature_maps, targets
class Factory:
def create(self,opt): return SqueezeNetNetwork(opt)
######################################################################
######################################################################
######################################################################
class WideResidualNetworkImagenet(ConvCNN_Base):
def __init__(self, opt):
super(WideResidualNetworkImagenet, self).__init__(opt)
self.model = WideResNet_50_2(useCuda= torch.cuda.is_available(), num_groups = self.opt['wrn_groups'], num_classes = None)
#Overload parameters to not return the stats parameters which running_mean and running_std does not
#contain derivative calculation.
def parameters(self, recurse=True):
for name, param in self.named_parameters(recurse=recurse):
if not('stats' in name):
yield param
def forward(self, x):
return self.model.forward(x)
class Factory:
def create(self,opt): return WideResidualNetworkImagenet(opt)
######################################################################
######################################################################
######################################################################
class WideResidualNetworkImagenetClassification(ConvCNN_Base):
def __init__(self, opt):
super(WideResidualNetworkImagenetClassification, self).__init__(opt)
self.model = WideResNet_50_2(useCuda= torch.cuda.is_available(), num_groups = self.opt['wrn_groups'], num_classes = 2)
#Overload parameters to not return the stats parameters which running_mean and running_std does not
#contain derivative calculation.
def parameters(self, recurse=True):
for name, param in self.named_parameters(recurse=recurse):
if not('stats' in name):
yield param
def forward(self, x):
return self.model.forward(x)
def forward_features(self, x):
old_state_num_classes = self.model.num_classes
# Set the num classes to None
self.model.num_classes = None
x = self.model.forward(x)
self.model.num_classes = old_state_num_classes
return x
def forward_classifier(self, x):
# Execute only the classifier
x = F.avg_pool2d(x, x.shape[2], 1, 0)
x = x.view(x.size(0), -1)
x = F.linear(x, self.model.params['fc_weight'], self.model.params['fc_bias'])
return x
class Factory:
def create(self,opt): return WideResidualNetworkImagenetClassification(opt)
######################################################################
######################################################################
######################################################################
# Specialized Class. Wide Residual Networks.
class PeleeNet(ConvCNN_Base):
def __init__(self, opt):
super(PeleeNet, self).__init__(opt)
# Initialize network
self.model = peleeNet(pretrained=True)
def forward(self, x):
for i in range(9):
x = self.model.features[i](x)
return x # returns B x 512 x 14 x 14
#def forward(self, x):
# return self.model.features(x) # returns # B x 704 x 7 x 7
class Factory:
def create(self,opt): return PeleeNet(opt)
######################################################################
######################################################################
######################################################################
class PeleeNetClassification(ConvCNN_Base):
def __init__(self, opt):
super(PeleeNetClassification, self).__init__(opt)
# Initialize network
self.model = peleeNet(pretrained=True)
self.model.classifier = nn.Linear(704,2, bias=True)
def forward(self, x):
return self.model(x)
def forward_features(self, x):
x = self.model.features(x)
x = F.avg_pool2d(x, kernel_size=(x.size(2), x.size(3))).view(x.size(0), -1)
if self.model.drop_rate > 0:
x = F.dropout(x, p=self.model.drop_rate, training=self.model.training)
return x
def forward_classifier(self, x):
# Execute only the classifier
x = self.model.classifier(x)
return x
class Factory:
def create(self,opt): return PeleeNetClassification(opt)
######################################################################
######################################################################
######################################################################
class PeleeNetClassificationReduced(ConvCNN_Base):
def __init__(self, opt):
super(PeleeNetClassificationReduced, self).__init__(opt)
# Initialize network
self.model = peleeNet(pretrained=True)
# reduce the last two blocks of the net to have a output feature size of Bx512x14x14
self.model.features = nn.Sequential(*list(self.model.features.children())[:-2])
self.model.classifier = nn.Linear(512,2, bias=True)
def forward(self, x):
return self.model(x)
def forward_features(self, x):
for i in range(9):
x = self.model.features[i](x) # returns B x 512 x 14 x 14
x = F.avg_pool2d(x, kernel_size=(x.size(2), x.size(3))).view(x.size(0), -1)
if self.model.drop_rate > 0:
x = F.dropout(x, p=self.model.drop_rate, training=self.model.training)
return x
def forward_classifier(self, x):
# Execute only the classifier
x = self.model.classifier(x)
return x
class Factory:
def create(self,opt): return PeleeNetClassificationReduced(opt)
######################################################################
######################################################################
######################################################################
# Generate all name of the factorization classes
def ConvCNN_NameGen():
types = ConvCNN_Base.__subclasses__()
for type in types:
yield type.__name__
| [
"wrn.wideResNet.WideResNet",
"peleeNet.peleeNet",
"torch.nn.functional.dropout",
"json.dumps",
"numpy.mean",
"numpy.arange",
"os.path.join",
"mobilenetv2.mobilenetv2",
"torch.nn.functional.avg_pool2d",
"torch.load",
"torch.nn.Linear",
"customResnet50.CustomResNet50",
"torchvision.models.vgg1... | [((1775, 2014), 'wrn.wideResNet.WideResNet', 'WideResNet', (["self.opt['wrn_depth']", "self.opt['wrn_width']"], {'ninputs': "self.opt['nchannels']", 'num_groups': "self.opt['wrn_groups']", 'num_classes': "(None if fully_convolutional else self.opt['wrn_num_classes'])", 'dropout': "self.opt['dropout']"}), "(self.opt['wrn_depth'], self.opt['wrn_width'], ninputs=self.opt[\n 'nchannels'], num_groups=self.opt['wrn_groups'], num_classes=None if\n fully_convolutional else self.opt['wrn_num_classes'], dropout=self.opt[\n 'dropout'])\n", (1785, 2014), False, 'from wrn.wideResNet import WideResNet\n'), ((2997, 3026), 'customResnet50.CustomResNet50', 'CustomResNet50', ([], {'out_size': 'None'}), '(out_size=None)\n', (3011, 3026), False, 'from customResnet50 import CustomResNet50\n'), ((3670, 3702), 'torchvision.models.resnet50', 'models.resnet50', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (3685, 3702), True, 'import torchvision.models as models\n'), ((3819, 3864), 'torch.nn.Linear', 'nn.Linear', (['(512 * block_expansion)', 'num_classes'], {}), '(512 * block_expansion, num_classes)\n', (3828, 3864), True, 'import torch.nn as nn\n'), ((4886, 4914), 'mobilenetv2.mobilenetv2', 'mobilenetv2', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (4897, 4914), False, 'from mobilenetv2 import mobilenetv2\n'), ((6357, 6385), 'mobilenetv2.mobilenetv2', 'mobilenetv2', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (6368, 6385), False, 'from mobilenetv2 import mobilenetv2\n'), ((6418, 6461), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(1280)', 'out_features': '(2)'}), '(in_features=1280, out_features=2)\n', (6427, 6461), True, 'import torch.nn as nn\n'), ((8576, 8612), 'torchvision.models.inception_v3', 'models.inception_v3', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (8595, 8612), True, 'import torchvision.models as models\n'), ((8688, 8732), 'torch.nn.Linear', 'nn.Linear', (['(2048)', "self.opt['wrn_num_classes']"], {}), "(2048, self.opt['wrn_num_classes'])\n", (8697, 8732), True, 'import torch.nn as nn\n'), ((8986, 9029), 'torch.nn.Linear', 'nn.Linear', (['(768)', "self.opt['wrn_num_classes']"], {}), "(768, self.opt['wrn_num_classes'])\n", (8995, 9029), True, 'import torch.nn as nn\n'), ((11769, 11806), 'torchvision.models.inception_v3', 'models.inception_v3', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (11788, 11806), True, 'import torchvision.models as models\n'), ((11828, 11849), 'torch.load', 'torch.load', (['modelPath'], {}), '(modelPath)\n', (11838, 11849), False, 'import torch\n'), ((12458, 12499), 'os.path.join', 'os.path.join', (["self.opt['save']", '"""log.txt"""'], {}), "(self.opt['save'], 'log.txt')\n", (12470, 12499), False, 'import os\n'), ((15240, 15269), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (15252, 15269), True, 'import torchvision.models as models\n'), ((18104, 18134), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (18116, 18134), True, 'import torchvision.models as models\n'), ((18156, 18177), 'torch.load', 'torch.load', (['modelPath'], {}), '(modelPath)\n', (18166, 18177), False, 'import torch\n'), ((18786, 18827), 'os.path.join', 'os.path.join', (["self.opt['save']", '"""log.txt"""'], {}), "(self.opt['save'], 'log.txt')\n", (18798, 18827), False, 'import os\n'), ((21724, 21761), 'torchvision.models.squeezenet1_0', 'models.squeezenet1_0', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (21744, 21761), True, 'import torchvision.models as models\n'), ((21875, 21963), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['(512)', "self.opt['wrn_num_classes']"], {'kernel_size': '(1, 1)', 'stride': '(1, 1)'}), "(512, self.opt['wrn_num_classes'], kernel_size=(1, 1),\n stride=(1, 1))\n", (21890, 21963), False, 'import torch\n'), ((22049, 22069), 'torch.nn.Sequential', 'nn.Sequential', (['*temp'], {}), '(*temp)\n', (22062, 22069), True, 'import torch.nn as nn\n'), ((24808, 24843), 'torchvision.models.squeezenet', 'models.squeezenet', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (24825, 24843), True, 'import torchvision.models as models\n'), ((24865, 24886), 'torch.load', 'torch.load', (['modelPath'], {}), '(modelPath)\n', (24875, 24886), False, 'import torch\n'), ((25495, 25536), 'os.path.join', 'os.path.join', (["self.opt['save']", '"""log.txt"""'], {}), "(self.opt['save'], 'log.txt')\n", (25507, 25536), False, 'import os\n'), ((28867, 28900), 'torch.nn.functional.avg_pool2d', 'F.avg_pool2d', (['x', 'x.shape[2]', '(1)', '(0)'], {}), '(x, x.shape[2], 1, 0)\n', (28879, 28900), True, 'import torch.nn.functional as F\n'), ((28947, 29020), 'torch.nn.functional.linear', 'F.linear', (['x', "self.model.params['fc_weight']", "self.model.params['fc_bias']"], {}), "(x, self.model.params['fc_weight'], self.model.params['fc_bias'])\n", (28955, 29020), True, 'import torch.nn.functional as F\n'), ((29560, 29585), 'peleeNet.peleeNet', 'peleeNet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (29568, 29585), False, 'from peleeNet import peleeNet\n'), ((30305, 30330), 'peleeNet.peleeNet', 'peleeNet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (30313, 30330), False, 'from peleeNet import peleeNet\n'), ((30363, 30391), 'torch.nn.Linear', 'nn.Linear', (['(704)', '(2)'], {'bias': '(True)'}), '(704, 2, bias=True)\n', (30372, 30391), True, 'import torch.nn as nn\n'), ((31369, 31394), 'peleeNet.peleeNet', 'peleeNet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (31377, 31394), False, 'from peleeNet import peleeNet\n'), ((31608, 31636), 'torch.nn.Linear', 'nn.Linear', (['(512)', '(2)'], {'bias': '(True)'}), '(512, 2, bias=True)\n', (31617, 31636), True, 'import torch.nn as nn\n'), ((7623, 7637), 'torch.autograd.Variable', 'Variable', (['data'], {}), '(data)\n', (7631, 7637), False, 'from torch.autograd import Variable\n'), ((7660, 7675), 'torch.autograd.Variable', 'Variable', (['label'], {}), '(label)\n', (7668, 7675), False, 'from torch.autograd import Variable\n'), ((7808, 7845), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['train_preds', 'targets'], {}), '(train_preds, targets)\n', (7823, 7845), True, 'import torch.nn.functional as F\n'), ((8027, 8052), 'torch.max', 'torch.max', (['train_preds', '(1)'], {}), '(train_preds, 1)\n', (8036, 8052), False, 'import torch\n'), ((9334, 9352), 'torch.load', 'torch.load', (['resume'], {}), '(resume)\n', (9344, 9352), False, 'import torch\n'), ((13185, 13199), 'torch.autograd.Variable', 'Variable', (['data'], {}), '(data)\n', (13193, 13199), False, 'from torch.autograd import Variable\n'), ((13221, 13236), 'torch.autograd.Variable', 'Variable', (['label'], {}), '(label)\n', (13229, 13236), False, 'from torch.autograd import Variable\n'), ((14354, 14368), 'torch.autograd.Variable', 'Variable', (['data'], {}), '(data)\n', (14362, 14368), False, 'from torch.autograd import Variable\n'), ((14391, 14406), 'torch.autograd.Variable', 'Variable', (['label'], {}), '(label)\n', (14399, 14406), False, 'from torch.autograd import Variable\n'), ((14476, 14513), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['train_preds', 'targets'], {}), '(train_preds, targets)\n', (14491, 14513), True, 'import torch.nn.functional as F\n'), ((14695, 14720), 'torch.max', 'torch.max', (['train_preds', '(1)'], {}), '(train_preds, 1)\n', (14704, 14720), False, 'import torch\n'), ((15742, 15760), 'torch.load', 'torch.load', (['resume'], {}), '(resume)\n', (15752, 15760), False, 'import torch\n'), ((19513, 19527), 'torch.autograd.Variable', 'Variable', (['data'], {}), '(data)\n', (19521, 19527), False, 'from torch.autograd import Variable\n'), ((19549, 19564), 'torch.autograd.Variable', 'Variable', (['label'], {}), '(label)\n', (19557, 19564), False, 'from torch.autograd import Variable\n'), ((20683, 20697), 'torch.autograd.Variable', 'Variable', (['data'], {}), '(data)\n', (20691, 20697), False, 'from torch.autograd import Variable\n'), ((20720, 20735), 'torch.autograd.Variable', 'Variable', (['label'], {}), '(label)\n', (20728, 20735), False, 'from torch.autograd import Variable\n'), ((21174, 21199), 'torch.max', 'torch.max', (['train_preds', '(1)'], {}), '(train_preds, 1)\n', (21183, 21199), False, 'import torch\n'), ((22375, 22393), 'torch.load', 'torch.load', (['resume'], {}), '(resume)\n', (22385, 22393), False, 'import torch\n'), ((26222, 26236), 'torch.autograd.Variable', 'Variable', (['data'], {}), '(data)\n', (26230, 26236), False, 'from torch.autograd import Variable\n'), ((26258, 26273), 'torch.autograd.Variable', 'Variable', (['label'], {}), '(label)\n', (26266, 26273), False, 'from torch.autograd import Variable\n'), ((30655, 30721), 'torch.nn.functional.dropout', 'F.dropout', (['x'], {'p': 'self.model.drop_rate', 'training': 'self.model.training'}), '(x, p=self.model.drop_rate, training=self.model.training)\n', (30664, 30721), True, 'import torch.nn.functional as F\n'), ((31962, 32028), 'torch.nn.functional.dropout', 'F.dropout', (['x'], {'p': 'self.model.drop_rate', 'training': 'self.model.training'}), '(x, p=self.model.drop_rate, training=self.model.training)\n', (31971, 32028), True, 'import torch.nn.functional as F\n'), ((12333, 12376), 'os.path.join', 'os.path.join', (["self.opt['save']", '"""model.pt7"""'], {}), "(self.opt['save'], 'model.pt7')\n", (12345, 12376), False, 'import os\n'), ((13385, 13416), 'numpy.arange', 'np.arange', (["self.opt['wrn_ngpu']"], {}), "(self.opt['wrn_ngpu'])\n", (13394, 13416), True, 'import numpy as np\n'), ((18661, 18704), 'os.path.join', 'os.path.join', (["self.opt['save']", '"""model.pt7"""'], {}), "(self.opt['save'], 'model.pt7')\n", (18673, 18704), False, 'import os\n'), ((19713, 19744), 'numpy.arange', 'np.arange', (["self.opt['wrn_ngpu']"], {}), "(self.opt['wrn_ngpu'])\n", (19722, 19744), True, 'import numpy as np\n'), ((25370, 25413), 'os.path.join', 'os.path.join', (["self.opt['save']", '"""model.pt7"""'], {}), "(self.opt['save'], 'model.pt7')\n", (25382, 25413), False, 'import os\n'), ((26422, 26453), 'numpy.arange', 'np.arange', (["self.opt['wrn_ngpu']"], {}), "(self.opt['wrn_ngpu'])\n", (26431, 26453), True, 'import numpy as np\n'), ((27055, 27080), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (27078, 27080), False, 'import torch\n'), ((28043, 28068), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (28066, 28068), False, 'import torch\n'), ((10805, 10825), 'numpy.mean', 'np.mean', (['val_all_acc'], {}), '(val_all_acc)\n', (10812, 10825), True, 'import numpy as np\n'), ((10865, 10888), 'numpy.mean', 'np.mean', (['val_all_losses'], {}), '(val_all_losses)\n', (10872, 10888), True, 'import numpy as np\n'), ((17152, 17172), 'numpy.mean', 'np.mean', (['val_all_acc'], {}), '(val_all_acc)\n', (17159, 17172), True, 'import numpy as np\n'), ((17212, 17235), 'numpy.mean', 'np.mean', (['val_all_losses'], {}), '(val_all_losses)\n', (17219, 17235), True, 'import numpy as np\n'), ((23835, 23855), 'numpy.mean', 'np.mean', (['val_all_acc'], {}), '(val_all_acc)\n', (23842, 23855), True, 'import numpy as np\n'), ((23895, 23918), 'numpy.mean', 'np.mean', (['val_all_losses'], {}), '(val_all_losses)\n', (23902, 23918), True, 'import numpy as np\n'), ((12575, 12588), 'json.dumps', 'json.dumps', (['z'], {}), '(z)\n', (12585, 12588), False, 'import json\n'), ((15395, 15439), 'torch.nn.Linear', 'nn.Linear', (['(4096)', "self.opt['wrn_num_classes']"], {}), "(4096, self.opt['wrn_num_classes'])\n", (15404, 15439), True, 'import torch.nn as nn\n'), ((18903, 18916), 'json.dumps', 'json.dumps', (['z'], {}), '(z)\n', (18913, 18916), False, 'import json\n'), ((25612, 25625), 'json.dumps', 'json.dumps', (['z'], {}), '(z)\n', (25622, 25625), False, 'import json\n'), ((11112, 11137), 'numpy.mean', 'np.mean', (['train_all_losses'], {}), '(train_all_losses)\n', (11119, 11137), True, 'import numpy as np\n'), ((11187, 11209), 'numpy.mean', 'np.mean', (['train_all_acc'], {}), '(train_all_acc)\n', (11194, 11209), True, 'import numpy as np\n'), ((17455, 17480), 'numpy.mean', 'np.mean', (['train_all_losses'], {}), '(train_all_losses)\n', (17462, 17480), True, 'import numpy as np\n'), ((17530, 17552), 'numpy.mean', 'np.mean', (['train_all_acc'], {}), '(train_all_acc)\n', (17537, 17552), True, 'import numpy as np\n'), ((24143, 24168), 'numpy.mean', 'np.mean', (['train_all_losses'], {}), '(train_all_losses)\n', (24150, 24168), True, 'import numpy as np\n'), ((24218, 24240), 'numpy.mean', 'np.mean', (['train_all_acc'], {}), '(train_all_acc)\n', (24225, 24240), True, 'import numpy as np\n')] |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from auto_scan_test import PassAutoScanTest, SkipReasons
from program_config import TensorConfig, ProgramConfig, OpConfig
import numpy as np
import paddle.inference as paddle_infer
from functools import partial
from typing import Optional, List, Callable, Dict, Any, Set
import unittest
import hypothesis
from hypothesis import given, settings, seed, example, assume
import hypothesis.strategies as st
from functools import reduce
class TestSeqconvEltaddReluFusePass(PassAutoScanTest):
def is_program_valid(self, program_config: ProgramConfig) -> bool:
return True
def sample_program_config(self, draw):
contextLength = draw(st.sampled_from([1, 2, 3, 4]))
contextStart = draw(st.sampled_from([1, 2, 3]))
contextStride = draw(st.sampled_from([1]))
paddingTrainable = False
axis = draw(st.sampled_from([1]))
batch_size = draw(st.integers(min_value=1, max_value=4))
def generate_input():
shape = [batch_size, 128, 6, 120]
return np.random.random(shape).astype(np.float32)
def generate_weight(shape):
return np.random.random(shape).astype(np.float32)
im2sequence_op = OpConfig(
type="im2sequence",
inputs={"X": ["input_data"]},
outputs={"Out": ["seq_out"]},
attrs={
"kernels": [6, 1],
"out_stride": [1, 1],
"paddings": [0, 0, 0, 0],
"strides": [1, 1]
})
sequence_conv_op = OpConfig(
type="sequence_conv",
inputs={"X": ["seq_out"],
"Filter": ["conv_weight"]},
outputs={"Out": ["conv_out"]},
attrs={
"contextLength": contextLength,
"contextStart": contextStart,
"contextStride": contextStride,
"paddingTrainable": paddingTrainable
})
elementwise_add_op = OpConfig(
type="elementwise_add",
inputs={"X": ["conv_out"],
"Y": ["elt_weight"]},
outputs={"Out": ["elt_output"]},
attrs={'axis': axis})
relu_op = OpConfig(
type="relu",
inputs={"X": ["elt_output"]},
outputs={"Out": ["relu_output"]},
attrs={})
model_net = [
im2sequence_op, sequence_conv_op, elementwise_add_op, relu_op
]
program_config = ProgramConfig(
ops=model_net,
weights={
"conv_weight": TensorConfig(data_gen=partial(
generate_weight, [768 * contextLength, 16])),
"elt_weight":
TensorConfig(data_gen=partial(generate_weight, [16]))
},
inputs={
"input_data": TensorConfig(data_gen=partial(generate_input))
},
outputs=["relu_output"])
return program_config
def sample_predictor_configs(self, program_config):
config = self.create_inference_config()
yield config, ["im2sequence", "fusion_seqconv_eltadd_relu"], (1e-5,
1e-5)
def test(self):
self.run_and_statis(
quant=False, passes=["seqconv_eltadd_relu_fuse_pass"])
if __name__ == "__main__":
unittest.main()
| [
"unittest.main",
"functools.partial",
"program_config.OpConfig",
"hypothesis.strategies.sampled_from",
"numpy.random.random",
"hypothesis.strategies.integers"
] | [((3975, 3990), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3988, 3990), False, 'import unittest\n'), ((1806, 1996), 'program_config.OpConfig', 'OpConfig', ([], {'type': '"""im2sequence"""', 'inputs': "{'X': ['input_data']}", 'outputs': "{'Out': ['seq_out']}", 'attrs': "{'kernels': [6, 1], 'out_stride': [1, 1], 'paddings': [0, 0, 0, 0],\n 'strides': [1, 1]}"}), "(type='im2sequence', inputs={'X': ['input_data']}, outputs={'Out':\n ['seq_out']}, attrs={'kernels': [6, 1], 'out_stride': [1, 1],\n 'paddings': [0, 0, 0, 0], 'strides': [1, 1]})\n", (1814, 1996), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((2144, 2412), 'program_config.OpConfig', 'OpConfig', ([], {'type': '"""sequence_conv"""', 'inputs': "{'X': ['seq_out'], 'Filter': ['conv_weight']}", 'outputs': "{'Out': ['conv_out']}", 'attrs': "{'contextLength': contextLength, 'contextStart': contextStart,\n 'contextStride': contextStride, 'paddingTrainable': paddingTrainable}"}), "(type='sequence_conv', inputs={'X': ['seq_out'], 'Filter': [\n 'conv_weight']}, outputs={'Out': ['conv_out']}, attrs={'contextLength':\n contextLength, 'contextStart': contextStart, 'contextStride':\n contextStride, 'paddingTrainable': paddingTrainable})\n", (2152, 2412), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((2577, 2718), 'program_config.OpConfig', 'OpConfig', ([], {'type': '"""elementwise_add"""', 'inputs': "{'X': ['conv_out'], 'Y': ['elt_weight']}", 'outputs': "{'Out': ['elt_output']}", 'attrs': "{'axis': axis}"}), "(type='elementwise_add', inputs={'X': ['conv_out'], 'Y': [\n 'elt_weight']}, outputs={'Out': ['elt_output']}, attrs={'axis': axis})\n", (2585, 2718), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((2802, 2902), 'program_config.OpConfig', 'OpConfig', ([], {'type': '"""relu"""', 'inputs': "{'X': ['elt_output']}", 'outputs': "{'Out': ['relu_output']}", 'attrs': '{}'}), "(type='relu', inputs={'X': ['elt_output']}, outputs={'Out': [\n 'relu_output']}, attrs={})\n", (2810, 2902), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((1264, 1293), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (1279, 1293), True, 'import hypothesis.strategies as st\n'), ((1323, 1349), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (1338, 1349), True, 'import hypothesis.strategies as st\n'), ((1380, 1400), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['[1]'], {}), '([1])\n', (1395, 1400), True, 'import hypothesis.strategies as st\n'), ((1455, 1475), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['[1]'], {}), '([1])\n', (1470, 1475), True, 'import hypothesis.strategies as st\n'), ((1503, 1540), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(4)'}), '(min_value=1, max_value=4)\n', (1514, 1540), True, 'import hypothesis.strategies as st\n'), ((1638, 1661), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (1654, 1661), True, 'import numpy as np\n'), ((1737, 1760), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (1753, 1760), True, 'import numpy as np\n'), ((3197, 3248), 'functools.partial', 'partial', (['generate_weight', '[768 * contextLength, 16]'], {}), '(generate_weight, [768 * contextLength, 16])\n', (3204, 3248), False, 'from functools import partial\n'), ((3340, 3370), 'functools.partial', 'partial', (['generate_weight', '[16]'], {}), '(generate_weight, [16])\n', (3347, 3370), False, 'from functools import partial\n'), ((3460, 3483), 'functools.partial', 'partial', (['generate_input'], {}), '(generate_input)\n', (3467, 3483), False, 'from functools import partial\n')] |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
Converters for Sklearn's GradientBoosting models.
"""
import numpy as np
from onnxconverter_common.registration import register_converter
from .. import constants
from .._gbdt_commons import convert_gbdt_common, convert_gbdt_classifier_common
from .._tree_commons import get_parameters_for_sklearn_common, get_parameters_for_tree_trav_sklearn, TreeParameters
def _get_parameters_hist_gbdt(trees):
"""
Extract the tree parameters from SklearnHistGradientBoostingClassifier trees
Args:
trees: The information representing a tree (ensemble)
Returns: The tree parameters wrapped into an instance of `operator_converters._tree_commons_TreeParameters`
"""
features = [n["feature_idx"] for n in trees.nodes]
thresholds = [n["threshold"] if n["threshold"] != 0 else -1 for n in trees.nodes]
lefts = [n["left"] if n["left"] != 0 else -1 for n in trees.nodes]
rights = [n["right"] if n["right"] != 0 else -1 for n in trees.nodes]
values = [[n["value"]] if n["value"] != 0 else [-1] for n in trees.nodes]
return TreeParameters(lefts, rights, features, thresholds, values)
def convert_sklearn_gbdt_classifier(operator, device, extra_config):
"""
Converter for `sklearn.ensemble.GradientBoostingClassifier`
Args:
operator: An operator wrapping a `sklearn.ensemble.GradientBoostingClassifier`
or `sklearn.ensemble.HistGradientBoostingClassifier` model
device: String defining the type of device the converted operator should be run on
extra_config: Extra configuration used to select the best conversion strategy
Returns:
A PyTorch model
"""
assert operator is not None, "Cannot convert None operator"
# Get tree information out of the operator.
tree_infos = operator.raw_operator.estimators_
# GBDT does not scale the value using the learning rate upfront, we have to do it.
extra_config[constants.LEARNING_RATE] = operator.raw_operator.learning_rate
# GBDT does not normalize values upfront, we have to do it.
extra_config[constants.GET_PARAMETERS_FOR_TREE_TRAVERSAL] = get_parameters_for_tree_trav_sklearn
n_features = operator.raw_operator.n_features_
classes = operator.raw_operator.classes_.tolist()
n_classes = len(classes)
# Analyze classes.
if not all(isinstance(c, int) for c in classes):
raise RuntimeError("GBDT Classifier translation only supports integer class labels.")
if n_classes == 2:
n_classes -= 1
# Reshape the tree_infos into hummingbird gbdt internal format.
tree_infos = [tree_infos[i][j] for j in range(n_classes) for i in range(len(tree_infos))]
# Get the value for Alpha.
if hasattr(operator.raw_operator, "init"):
if operator.raw_operator.init == "zero":
base_prediction = [[0.0]]
elif operator.raw_operator.init is None:
if n_classes == 1:
base_prediction = [
[np.log(operator.raw_operator.init_.class_prior_[1] / (1 - operator.raw_operator.init_.class_prior_[1]))]
]
else:
base_prediction = [[np.log(operator.raw_operator.init_.class_prior_[i]) for i in range(n_classes)]]
else:
raise RuntimeError("Custom initializers for GBDT are not yet supported in Hummingbird.")
elif hasattr(operator.raw_operator, "_baseline_prediction"):
if n_classes == 1:
base_prediction = [[operator.raw_operator._baseline_prediction]]
else:
base_prediction = np.array([operator.raw_operator._baseline_prediction.flatten().tolist()])
extra_config[constants.BASE_PREDICTION] = base_prediction
extra_config[constants.REORDER_TREES] = False
return convert_gbdt_classifier_common(
operator, tree_infos, get_parameters_for_sklearn_common, n_features, n_classes, classes, missing_val=None, extra_config=extra_config
)
def convert_sklearn_gbdt_regressor(operator, device, extra_config):
"""
Converter for `sklearn.ensemble.GradientBoostingRegressor`.
Args:
operator: An operator wrapping a `sklearn.ensemble.GradientBoostingRegressor` or
`sklearn.ensemble.HistGradientBoostingRegressor` model
device: String defining the type of device the converted operator should be run on
extra_config: Extra configuration used to select the best conversion strategy
Returns:
A PyTorch model
"""
assert operator is not None, "Cannot convert None operator"
# Get tree information out of the operator.
tree_infos = operator.raw_operator.estimators_.ravel().tolist()
n_features = operator.raw_operator.n_features_
extra_config[constants.LEARNING_RATE] = operator.raw_operator.learning_rate
# For sklearn models we need to massage the parameters a bit before generating the parameters for tree_trav.
extra_config[constants.GET_PARAMETERS_FOR_TREE_TRAVERSAL] = get_parameters_for_tree_trav_sklearn
# Get the value for Alpha.
if operator.raw_operator.init == "zero":
base_prediction = [[0.0]]
elif operator.raw_operator.init is None:
base_prediction = operator.raw_operator.init_.constant_.tolist()
else:
raise RuntimeError("Custom initializers for GBDT are not yet supported in Hummingbird.")
extra_config[constants.BASE_PREDICTION] = base_prediction
return convert_gbdt_common(operator, tree_infos, get_parameters_for_sklearn_common, n_features, missing_val=None, extra_config=extra_config)
def convert_sklearn_hist_gbdt_classifier(operator, device, extra_config):
"""
Converter for `sklearn.ensemble.HistGradientBoostingClassifier`
Args:
operator: An operator wrapping a `sklearn.ensemble.HistGradientBoostingClassifier` model
device: String defining the type of device the converted operator should be run on
extra_config: Extra configuration used to select the best conversion strategy
Returns:
A PyTorch model
"""
assert operator is not None, "Cannot convert None operator"
# Get tree information out of the operator.
tree_infos = operator.raw_operator._predictors
n_features = operator.raw_operator.n_features_
classes = operator.raw_operator.classes_.tolist()
n_classes = len(classes)
# Analyze classes.
if not all(isinstance(c, int) for c in classes):
raise RuntimeError("GBDT Classifier translation only supports integer class labels.")
if n_classes == 2:
n_classes -= 1
# Reshape the tree_infos to a more generic format.
tree_infos = [tree_infos[i][j] for j in range(n_classes) for i in range(len(tree_infos))]
# Get the value for Alpha.
if n_classes == 1:
base_prediction = [[operator.raw_operator._baseline_prediction]]
else:
base_prediction = np.array([operator.raw_operator._baseline_prediction.flatten().tolist()])
extra_config[constants.BASE_PREDICTION] = base_prediction
extra_config[constants.REORDER_TREES] = False
return convert_gbdt_classifier_common(operator, tree_infos, _get_parameters_hist_gbdt, n_features, n_classes, classes, missing_val=None, extra_config=extra_config)
def convert_sklearn_hist_gbdt_regressor(operator, device, extra_config):
"""
Converter for `sklearn.ensemble.HistGradientBoostingRegressor`
Args:
operator: An operator wrapping a `sklearn.ensemble.HistGradientBoostingRegressor` model
device: String defining the type of device the converted operator should be run on
extra_config: Extra configuration used to select the best conversion strategy
Returns:
A PyTorch model
"""
assert operator is not None, "Cannot convert None operator"
# Get tree information out of the operator.
tree_infos = operator.raw_operator._predictors
tree_infos = [tree_infos[i][0] for i in range(len(tree_infos))]
n_features = operator.raw_operator.n_features_
extra_config[constants.BASE_PREDICTION] = [[operator.raw_operator._baseline_prediction]]
return convert_gbdt_common(operator, tree_infos, _get_parameters_hist_gbdt, n_features, missing_val=None, extra_config=extra_config)
# Register the converters.
register_converter("SklearnGradientBoostingClassifier", convert_sklearn_gbdt_classifier)
register_converter("SklearnGradientBoostingRegressor", convert_sklearn_gbdt_regressor)
register_converter("SklearnHistGradientBoostingClassifier", convert_sklearn_hist_gbdt_classifier)
register_converter("SklearnHistGradientBoostingRegressor", convert_sklearn_hist_gbdt_regressor)
| [
"onnxconverter_common.registration.register_converter",
"numpy.log"
] | [((8545, 8637), 'onnxconverter_common.registration.register_converter', 'register_converter', (['"""SklearnGradientBoostingClassifier"""', 'convert_sklearn_gbdt_classifier'], {}), "('SklearnGradientBoostingClassifier',\n convert_sklearn_gbdt_classifier)\n", (8563, 8637), False, 'from onnxconverter_common.registration import register_converter\n'), ((8634, 8724), 'onnxconverter_common.registration.register_converter', 'register_converter', (['"""SklearnGradientBoostingRegressor"""', 'convert_sklearn_gbdt_regressor'], {}), "('SklearnGradientBoostingRegressor',\n convert_sklearn_gbdt_regressor)\n", (8652, 8724), False, 'from onnxconverter_common.registration import register_converter\n'), ((8721, 8822), 'onnxconverter_common.registration.register_converter', 'register_converter', (['"""SklearnHistGradientBoostingClassifier"""', 'convert_sklearn_hist_gbdt_classifier'], {}), "('SklearnHistGradientBoostingClassifier',\n convert_sklearn_hist_gbdt_classifier)\n", (8739, 8822), False, 'from onnxconverter_common.registration import register_converter\n'), ((8819, 8918), 'onnxconverter_common.registration.register_converter', 'register_converter', (['"""SklearnHistGradientBoostingRegressor"""', 'convert_sklearn_hist_gbdt_regressor'], {}), "('SklearnHistGradientBoostingRegressor',\n convert_sklearn_hist_gbdt_regressor)\n", (8837, 8918), False, 'from onnxconverter_common.registration import register_converter\n'), ((3292, 3400), 'numpy.log', 'np.log', (['(operator.raw_operator.init_.class_prior_[1] / (1 - operator.raw_operator.\n init_.class_prior_[1]))'], {}), '(operator.raw_operator.init_.class_prior_[1] / (1 - operator.\n raw_operator.init_.class_prior_[1]))\n', (3298, 3400), True, 'import numpy as np\n'), ((3469, 3520), 'numpy.log', 'np.log', (['operator.raw_operator.init_.class_prior_[i]'], {}), '(operator.raw_operator.init_.class_prior_[i])\n', (3475, 3520), True, 'import numpy as np\n')] |
#=======================================================================
# quadrature weight/location for numerical integration along one dimension
#=======================================================================
import numpy
def gaussian(NG):
xg = numpy.zeros(NG)
wg = numpy.zeros_like(xg)
#=======================================================================
# generate initial guess values
#=======================================================================
M = int((NG + 1)/2) #max # of gauss points to generate (symmetry)
for i in range(0,M):
Z = numpy.cos(numpy.pi*(i + 1.0 - 0.25)/(NG + 0.5))
eps = 1.0
while abs(eps) > 1e-10:
P1 = 1.0 # first Legendre polynomial
P2 = 0.0 # second Legendre polynomial
for j in range(0,NG):
P3 = P2
P2 = P1
#=======================================================================
# n P_n(z) = (2*n-1) z P_(n-1) (z) - (n-1) P_(n-2) (z)
#=======================================================================
P1 = ((2.0*j + 1.0)*Z*P2 - j*P3)/(j+1)
#=======================================================================
# d/dx[p_n(z)] = [z P_(n) (z) - P_(n-1) (z)] * n/( z^2-1)
#=======================================================================
PP = NG*(Z*P1 - P2)/(Z*Z - 1.0) #slope of Pn(z)
Z1 = Z
#=======================================================================
#Use Newton-Raphson method to find the "true" zero of Legendre polynomial
#=======================================================================
Z = Z1 - P1/PP
eps = abs(Z-Z1)
#=======================================================================
# Store converged results in array
#=======================================================================
xg[i] = -Z
xg[NG - 1 - i] = Z
wg[i] = 2.0/((1.0 - Z*Z)*PP*PP) #Gauss-Legendre weight value
wg[NG - 1 - i] = wg[i]
#=======================================================================
# change limits of integration to be [0,1]
#=======================================================================
xg = 0.5*(xg+1.0)
wg = 0.5*wg
return xg, wg | [
"numpy.zeros_like",
"numpy.zeros",
"numpy.cos"
] | [((274, 289), 'numpy.zeros', 'numpy.zeros', (['NG'], {}), '(NG)\n', (285, 289), False, 'import numpy\n'), ((310, 330), 'numpy.zeros_like', 'numpy.zeros_like', (['xg'], {}), '(xg)\n', (326, 330), False, 'import numpy\n'), ((625, 676), 'numpy.cos', 'numpy.cos', (['(numpy.pi * (i + 1.0 - 0.25) / (NG + 0.5))'], {}), '(numpy.pi * (i + 1.0 - 0.25) / (NG + 0.5))\n', (634, 676), False, 'import numpy\n')] |
# Copyright (c) 2015-2019 by the parties listed in the AUTHORS file.
# All rights reserved. Use of this source code is governed by
# a BSD-style license that can be found in the LICENSE file.
import os
import numpy as np
from ..utils import Logger, memreport
from ..timing import function_timer, Timer
from ..op import Operator
from .atm import available, available_utils, available_mpi
if available_utils:
from .atm import (
atm_absorption_coefficient,
atm_absorption_coefficient_vec,
atm_atmospheric_loading,
atm_atmospheric_loading_vec,
)
if available:
from .atm import AtmSim
if available_mpi:
from .atm import AtmSimMPI
from toast.mpi import MPI, comm_py2c
import toast.qarray as qa
class OpSimAtmosphere(Operator):
"""Operator which generates atmosphere timestreams.
All processes collectively generate the atmospheric realization.
Then each process passes through its local data and observes the
atmosphere.
This operator is only compatible with TOD objects that can return
AZ/EL pointing.
Args:
out (str): accumulate data to the cache with name
<out>_<detector>. If the named cache objects do not exist,
then they are created.
realization (int): if simulating multiple realizations, the
realization index.
component (int): the component index to use for this noise
simulation.
lmin_center (float): Kolmogorov turbulence dissipation scale
center.
lmin_sigma (float): Kolmogorov turbulence dissipation scale
sigma.
lmax_center (float): Kolmogorov turbulence injection scale
center.
lmax_sigma (float): Kolmogorov turbulence injection scale sigma.
gain (float): Scaling applied to the simulated TOD.
zatm (float): atmosphere extent for temperature profile.
zmax (float): atmosphere extent for water vapor integration.
xstep (float): size of volume elements in X direction.
ystep (float): size of volume elements in Y direction.
zstep (float): size of volume elements in Z direction.
nelem_sim_max (int): controls the size of the simulation slices.
verbosity (int): more information is printed for values > 0.
z0_center (float): central value of the water vapor
distribution.
z0_sigma (float): sigma of the water vapor distribution.
common_flag_name (str): Cache name of the output common flags.
If it already exists, it is used. Otherwise flags
are read from the tod object and stored in the cache under
common_flag_name.
common_flag_mask (byte): Bitmask to use when flagging data
based on the common flags.
flag_name (str): Cache name of the output detector flags will
be <flag_name>_<detector>. If the object exists, it is
used. Otherwise flags are read from the tod object.
flag_mask (byte): Bitmask to use when flagging data
based on the detector flags.
apply_flags (bool): When True, flagged samples are not
simulated.
report_timing (bool): Print out time taken to initialize,
simulate and observe
wind_dist (float): Maximum wind drift before discarding the
volume and creating a new one [meters].
cachedir (str): Directory to use for loading and saving
atmosphere realizations. Set to None to disable caching.
flush (bool): Flush all print statements
freq (float): Observing frequency in GHz.
"""
def __init__(
self,
out="atm",
realization=0,
component=123456,
lmin_center=0.01,
lmin_sigma=0.001,
lmax_center=10,
lmax_sigma=10,
zatm=40000.0,
zmax=2000.0,
xstep=100.0,
ystep=100.0,
zstep=100.0,
nelem_sim_max=10000,
verbosity=0,
gain=1,
z0_center=2000,
z0_sigma=0,
apply_flags=False,
common_flag_name=None,
common_flag_mask=255,
flag_name=None,
flag_mask=255,
report_timing=True,
wind_dist=10000,
cachedir=".",
flush=False,
freq=None,
):
if not available:
msg = (
"TOAST not compiled with atmosphere simulation support (requires "
"SuiteSparse)"
)
raise RuntimeError(msg)
# Call the parent class constructor
super().__init__()
self._out = out
self._realization = realization
self._component = component
self._lmin_center = lmin_center
self._lmin_sigma = lmin_sigma
self._lmax_center = lmax_center
self._lmax_sigma = lmax_sigma
self._gain = gain
self._zatm = zatm
self._zmax = zmax
self._xstep = xstep
self._ystep = ystep
self._zstep = zstep
self._nelem_sim_max = nelem_sim_max
self._verbosity = verbosity
self._cachedir = cachedir
self._flush = flush
self._freq = freq
self._z0_center = z0_center
self._z0_sigma = z0_sigma
self._apply_flags = apply_flags
self._common_flag_name = common_flag_name
self._common_flag_mask = common_flag_mask
self._flag_name = flag_name
self._flag_mask = flag_mask
self._report_timing = report_timing
self._wind_dist = wind_dist
self._wind_time = None
@function_timer
def exec(self, data):
"""Generate atmosphere timestreams.
This iterates over all observations and detectors and generates
the atmosphere timestreams.
Args:
data (toast.Data): The distributed data.
Returns:
None
"""
if data.comm.comm_world is not None:
if not available_mpi:
msg = (
"MPI is used by the data distribution, but TOAST was not built "
"with MPI-enabled atmosphere simulation support."
)
raise RuntimeError(msg)
log = Logger.get()
group = data.comm.group
for obs in data.obs:
try:
obsname = obs["name"]
except Exception:
obsname = "observation"
prefix = "{} : {} : ".format(group, obsname)
tod = self._get_from_obs("tod", obs)
comm = tod.mpicomm
rank = 0
if comm is not None:
rank = comm.rank
site = self._get_from_obs("site_id", obs)
weather = self._get_from_obs("weather", obs)
# Get the observation time span and initialize the weather
# object if one is provided.
times = tod.local_times()
tmin = times[0]
tmax = times[-1]
tmin_tot = tmin
tmax_tot = tmax
if comm is not None:
tmin_tot = comm.allreduce(tmin, op=MPI.MIN)
tmax_tot = comm.allreduce(tmax, op=MPI.MAX)
weather.set(site, self._realization, tmin_tot)
key1, key2, counter1, counter2 = self._get_rng_keys(obs)
absorption = self._get_absorption_and_loading(obs)
cachedir = self._get_cache_dir(obs, comm)
if comm is not None:
comm.Barrier()
if rank == 0:
log.info("{}Setting up atmosphere simulation".format(prefix))
# Cache the output common flags
common_ref = tod.local_common_flags(self._common_flag_name)
scan_range = self._get_scan_range(obs, comm, prefix)
# Loop over the time span in "wind_time"-sized chunks.
# wind_time is intended to reflect the correlation length
# in the atmospheric noise.
tmr = Timer()
if self._report_timing:
if comm is not None:
comm.Barrier()
tmr.start()
tmin = tmin_tot
istart = 0
counter1start = counter1
while tmin < tmax_tot:
if comm is not None:
comm.Barrier()
if rank == 0:
log.info(
"{}Instantiating atmosphere for t = {}".format(
prefix, tmin - tmin_tot
)
)
istart, istop, tmax = self._get_time_range(
tmin, istart, times, tmax_tot, common_ref, tod, weather
)
ind = slice(istart, istop)
nind = istop - istart
rmin = 0
rmax = 100
scale = 10
counter2start = counter2
counter1 = counter1start
xstart, ystart, zstart = self._xstep, self._ystep, self._zstep
while rmax < 100000:
sim, counter2 = self._simulate_atmosphere(
weather,
scan_range,
tmin,
tmax,
comm,
key1,
key2,
counter1,
counter2start,
cachedir,
prefix,
tmin_tot,
tmax_tot,
rmin,
rmax,
)
if self._verbosity > 15:
self._plot_snapshots(
sim,
prefix,
obsname,
scan_range,
tmin,
tmax,
comm,
rmin,
rmax,
)
self._observe_atmosphere(
sim,
tod,
comm,
prefix,
common_ref,
istart,
nind,
ind,
scan_range,
times,
absorption,
)
del sim
rmin = rmax
rmax *= scale
self._xstep *= np.sqrt(scale)
self._ystep *= np.sqrt(scale)
self._zstep *= np.sqrt(scale)
counter1 += 1
if self._verbosity > 5:
self._save_tod(
obsname, tod, times, istart, nind, ind, comm, common_ref
)
self._xstep, self._ystep, self._zstep = xstart, ystart, zstart
tmin = tmax
if self._report_timing:
if comm is not None:
comm.Barrier()
if rank == 0:
tmr.stop()
tmr.report("{}Simulated and observed atmosphere".format(prefix))
return
@function_timer
def _save_tod(self, obsname, tod, times, istart, nind, ind, comm, common_ref):
import pickle
rank = 0
if comm is not None:
rank = comm.rank
t = times[ind]
tmin, tmax = t[0], t[-1]
outdir = "snapshots"
if rank == 0:
try:
os.makedirs(outdir)
except FileExistsError:
pass
try:
good = common_ref[ind] & tod.UNSTABLE == 0
except:
good = slice(0, nind)
for det in tod.local_dets:
# Cache the output signal
cachename = "{}_{}".format(self._out, det)
ref = tod.cache.reference(cachename)[ind]
try:
# Some TOD classes provide a shortcut to Az/El
az, el = tod.read_azel(detector=det, local_start=istart, n=nind)
except Exception as e:
azelquat = tod.read_pntg(
detector=det, local_start=istart, n=nind, azel=True
)
# Convert Az/El quaternion of the detector back into
# angles for the simulation.
theta, phi = qa.to_position(azelquat)
# Azimuth is measured in the opposite direction
# than longitude
az = 2 * np.pi - phi
el = np.pi / 2 - theta
fn = os.path.join(
outdir,
"atm_tod_{}_{}_t_{}_{}.pck".format(obsname, det, int(tmin), int(tmax)),
)
with open(fn, "wb") as fout:
pickle.dump([det, t[good], az[good], el[good], ref[good]], fout)
return
@function_timer
def _plot_snapshots(
self, sim, prefix, obsname, scan_range, tmin, tmax, comm, rmin, rmax
):
""" Create snapshots of the atmosphere
"""
from ..vis import set_backend
set_backend()
import matplotlib.pyplot as plt
import pickle
azmin, azmax, elmin, elmax = scan_range
# elstep = np.radians(0.01)
elstep = (elmax - elmin) / 320
azstep = elstep * np.cos(0.5 * (elmin + elmax))
azgrid = np.linspace(azmin, azmax, (azmax - azmin) // azstep + 1)
elgrid = np.linspace(elmin, elmax, (elmax - elmin) // elstep + 1)
AZ, EL = np.meshgrid(azgrid, elgrid)
nn = AZ.size
az = AZ.ravel()
el = EL.ravel()
atmdata = np.zeros(nn, dtype=np.float64)
atmtimes = np.zeros(nn, dtype=np.float64)
rank = 0
ntask = 1
if comm is not None:
rank = comm.rank
ntask = comm.size
r = 0
t = 0
my_snapshots = []
vmin = 1e30
vmax = -1e30
tstep = 1
for i, t in enumerate(np.arange(tmin, tmax, tstep)):
if i % ntask != rank:
continue
err = sim.observe(atmtimes + t, az, el, atmdata, r)
if err != 0:
raise RuntimeError(prefix + "Observation failed")
if self._gain:
atmdata *= self._gain
vmin = min(vmin, np.amin(atmdata))
vmax = max(vmax, np.amax(atmdata))
atmdata2d = atmdata.reshape(AZ.shape)
my_snapshots.append((t, r, atmdata2d.copy()))
outdir = "snapshots"
if rank == 0:
try:
os.makedirs(outdir)
except FileExistsError:
pass
fn = os.path.join(
outdir,
"atm_{}_{}_t_{}_{}_r_{}_{}.pck".format(
obsname, rank, int(tmin), int(tmax), int(rmin), int(rmax)
),
)
with open(fn, "wb") as fout:
pickle.dump([azgrid, elgrid, my_snapshots], fout)
print("Snapshots saved in {}".format(fn), flush=True)
"""
vmin = comm.allreduce(vmin, op=MPI.MIN)
vmax = comm.allreduce(vmax, op=MPI.MAX)
for t, r, atmdata2d in my_snapshots:
plt.figure(figsize=[12, 4])
plt.imshow(
atmdata2d,
interpolation="nearest",
origin="lower",
extent=np.degrees(
[0, (azmax - azmin) * np.cos(0.5 * (elmin + elmax)), elmin, elmax]
),
cmap=plt.get_cmap("Blues"),
vmin=vmin,
vmax=vmax,
)
plt.colorbar()
ax = plt.gca()
ax.set_title("t = {:15.1f} s, r = {:15.1f} m".format(t, r))
ax.set_xlabel("az [deg]")
ax.set_ylabel("el [deg]")
ax.set_yticks(np.degrees([elmin, elmax]))
plt.savefig("atm_{}_t_{:04}_r_{:04}.png".format(obsname, int(t), int(r)))
plt.close()
"""
del my_snapshots
return
def _get_from_obs(self, name, obs):
""" Extract value for name from observation.
If name is not defined in observation, raise an exception.
"""
if name in obs:
return obs[name]
else:
raise RuntimeError(
"Error simulating atmosphere: observation "
'does not define "{}"'.format(name)
)
def _get_rng_keys(self, obs):
"""
The random number generator accepts a key and a counter,
each made of two 64bit integers.
Following tod_math.py we set
key1 = realization * 2^32 + telescope * 2^16 + component
key2 = obsindx * 2^32
counter1 = hierarchical cone counter
counter2 = sample in stream (incremented internally in the atm code)
"""
telescope = self._get_from_obs("telescope_id", obs)
site = self._get_from_obs("site_id", obs)
obsindx = self._get_from_obs("id", obs)
key1 = self._realization * 2 ** 32 + telescope * 2 ** 16 + self._component
key2 = site * 2 ** 16 + obsindx
counter1 = 0
counter2 = 0
return key1, key2, counter1, counter2
@function_timer
def _get_absorption_and_loading(self, obs):
altitude = self._get_from_obs("altitude", obs)
weather = self._get_from_obs("weather", obs)
tod = self._get_from_obs("tod", obs)
if self._freq is not None:
if not available_utils:
msg = (
"TOAST not compiled with libaatm support- absorption and "
"loading unavailable"
)
raise RuntimeError(msg)
absorption = atm_absorption_coefficient(
altitude,
weather.air_temperature,
weather.surface_pressure,
weather.pwv,
self._freq,
)
loading = atm_atmospheric_loading(
altitude,
weather.air_temperature,
weather.surface_pressure,
weather.pwv,
self._freq,
)
tod.meta["loading"] = loading
else:
absorption = None
return absorption
def _get_cache_dir(self, obs, comm):
obsindx = self._get_from_obs("id", obs)
if self._cachedir is None:
cachedir = None
else:
# The number of atmospheric realizations can be large. Use
# sub-directories under cachedir.
subdir = str(int((obsindx % 1000) // 100))
subsubdir = str(int((obsindx % 100) // 10))
subsubsubdir = str(obsindx % 10)
cachedir = os.path.join(self._cachedir, subdir, subsubdir, subsubsubdir)
if (comm is None) or (comm.rank == 0):
# Handle a rare race condition when two process groups
# are creating the cache directories at the same time
while True:
print("Creating {}".format(cachedir), flush=True)
try:
os.makedirs(cachedir, exist_ok=True)
except OSError:
continue
except FileNotFoundError:
continue
else:
break
return cachedir
@function_timer
def _get_scan_range(self, obs, comm, prefix):
tod = self._get_from_obs("tod", obs)
fp_radius = np.radians(self._get_from_obs("fpradius", obs))
# Read the extent of the AZ/EL boresight pointing, and use that
# to compute the range of angles needed for simulating the slab.
(min_az_bore, max_az_bore, min_el_bore, max_el_bore) = tod.scan_range
# print("boresight scan range = {}, {}, {}, {}".format(
# min_az_bore, max_az_bore, min_el_bore, max_el_bore))
# Use a fixed focal plane radius so that changing the actual
# set of detectors will not affect the simulated atmosphere.
elfac = 1 / np.cos(max_el_bore + fp_radius)
azmin = min_az_bore - fp_radius * elfac
azmax = max_az_bore + fp_radius * elfac
if azmin < -2 * np.pi:
azmin += 2 * np.pi
azmax += 2 * np.pi
elif azmax > 2 * np.pi:
azmin -= 2 * np.pi
azmax -= 2 * np.pi
elmin = min_el_bore - fp_radius
elmax = max_el_bore + fp_radius
if comm is not None:
azmin = comm.allreduce(azmin, op=MPI.MIN)
azmax = comm.allreduce(azmax, op=MPI.MAX)
elmin = comm.allreduce(elmin, op=MPI.MIN)
elmax = comm.allreduce(elmax, op=MPI.MAX)
if elmin < 0 or elmax > np.pi / 2:
raise RuntimeError(
"{}Error in CES elevation: elmin = {:.3f} deg, elmax = {:.3f} deg, "
"elmin_bore = {:.3f} deg, elmax_bore = {:.3f} deg, "
"fp_radius = {:.3f} deg".format(
prefix,
np.degrees(elmin),
np.degrees(elmax),
np.degrees(min_el_bore),
np.degrees(max_el_bore),
np.degrees(fp_radius),
)
)
return azmin, azmax, elmin, elmax
@function_timer
def _get_time_range(self, tmin, istart, times, tmax_tot, common_ref, tod, weather):
while times[istart] < tmin:
istart += 1
# Translate the wind speed to time span of a correlated interval
wx = weather.west_wind
wy = weather.south_wind
w = np.sqrt(wx ** 2 + wy ** 2)
self._wind_time = self._wind_dist / w
tmax = tmin + self._wind_time
if tmax < tmax_tot:
# Extend the scan to the next turnaround
istop = istart
while istop < times.size and times[istop] < tmax:
istop += 1
while istop < times.size and (common_ref[istop] | tod.TURNAROUND == 0):
istop += 1
if istop < times.size:
tmax = times[istop]
else:
tmax = tmax_tot
else:
tmax = tmax_tot
istop = times.size
return istart, istop, tmax
@function_timer
def _simulate_atmosphere(
self,
weather,
scan_range,
tmin,
tmax,
comm,
key1,
key2,
counter1,
counter2,
cachedir,
prefix,
tmin_tot,
tmax_tot,
rmin,
rmax,
):
log = Logger.get()
rank = 0
if comm is not None:
rank = comm.rank
tmr = Timer()
if self._report_timing:
if comm is not None:
comm.Barrier()
tmr.start()
T0_center = weather.air_temperature
wx = weather.west_wind
wy = weather.south_wind
w_center = np.sqrt(wx ** 2 + wy ** 2)
wdir_center = np.arctan2(wy, wx)
azmin, azmax, elmin, elmax = scan_range
if cachedir is None:
# The wrapper requires a string argument
use_cache = False
cachedir = ""
else:
use_cache = True
sim = None
if comm is None:
sim = AtmSim(
azmin,
azmax,
elmin,
elmax,
tmin,
tmax,
self._lmin_center,
self._lmin_sigma,
self._lmax_center,
self._lmax_sigma,
w_center,
0,
wdir_center,
0,
self._z0_center,
self._z0_sigma,
T0_center,
0,
self._zatm,
self._zmax,
self._xstep,
self._ystep,
self._zstep,
self._nelem_sim_max,
self._verbosity,
key1,
key2,
counter1,
counter2,
cachedir,
rmin,
rmax,
)
else:
sim = AtmSimMPI(
azmin,
azmax,
elmin,
elmax,
tmin,
tmax,
self._lmin_center,
self._lmin_sigma,
self._lmax_center,
self._lmax_sigma,
w_center,
0,
wdir_center,
0,
self._z0_center,
self._z0_sigma,
T0_center,
0,
self._zatm,
self._zmax,
self._xstep,
self._ystep,
self._zstep,
self._nelem_sim_max,
self._verbosity,
comm_py2c(comm).value,
key1,
key2,
counter1,
counter2,
cachedir,
rmin,
rmax,
)
if self._report_timing:
if comm is not None:
comm.Barrier()
if rank == 0:
tmr.report_clear(
"{}OpSimAtmosphere: Initialize atmosphere".format(prefix)
)
if rank == 0:
fname = os.path.join(
cachedir,
"{}_{}_{}_{}_metadata.txt".format(key1, key2, counter1, counter2),
)
if use_cache and os.path.isfile(fname):
log.info(
"{}Loading the atmosphere for t = {} from {}".format(
prefix, tmin - tmin_tot, fname
)
)
cached = True
else:
log.info(
"{}Simulating the atmosphere for t = {}".format(
prefix, tmin - tmin_tot, fname
)
)
cached = False
err = sim.simulate(use_cache)
if err != 0:
raise RuntimeError(prefix + "Simulation failed.")
# Advance the sample counter in case wind_time broke the
# observation in parts
counter2 += 100000000
if self._report_timing:
if comm is not None:
comm.Barrier()
if rank == 0:
op = None
if cached:
op = "Loaded"
else:
op = "Simulated"
tmr.report_clear("{}OpSimAtmosphere: {} atmosphere".format(prefix, op))
return sim, counter2
@function_timer
def _observe_atmosphere(
self,
sim,
tod,
comm,
prefix,
common_ref,
istart,
nind,
ind,
scan_range,
times,
absorption,
):
log = Logger.get()
rank = 0
if comm is not None:
rank = comm.rank
tmr = Timer()
if self._report_timing:
if comm is not None:
comm.Barrier()
tmr.start()
azmin, azmax, elmin, elmax = scan_range
nsamp = tod.local_samples[1]
if rank == 0:
log.info("{}Observing the atmosphere".format(prefix))
for det in tod.local_dets:
# Cache the output signal
cachename = "{}_{}".format(self._out, det)
if tod.cache.exists(cachename):
ref = tod.cache.reference(cachename)
else:
ref = tod.cache.create(cachename, np.float64, (nsamp,))
# Cache the output flags
flag_ref = tod.local_flags(det, self._flag_name)
if self._apply_flags:
good = np.logical_and(
common_ref[ind] & self._common_flag_mask == 0,
flag_ref[ind] & self._flag_mask == 0,
)
ngood = np.sum(good)
else:
try:
good = common_ref[ind] & tod.UNSTABLE == 0
ngood = np.sum(good)
except:
good = slice(0, nind)
ngood = nind
if ngood == 0:
continue
try:
# Some TOD classes provide a shortcut to Az/El
az, el = tod.read_azel(detector=det, local_start=istart, n=nind)
az = az[good]
el = el[good]
except Exception as e:
azelquat = tod.read_pntg(
detector=det, local_start=istart, n=nind, azel=True
)[good]
# Convert Az/El quaternion of the detector back into
# angles for the simulation.
theta, phi = qa.to_position(azelquat)
# Azimuth is measured in the opposite direction
# than longitude
az = 2 * np.pi - phi
el = np.pi / 2 - theta
atmdata = np.zeros(ngood, dtype=np.float64)
if np.ptp(az) < np.pi:
azmin_det = np.amin(az)
azmax_det = np.amax(az)
else:
# Scanning across the zero azimuth.
azmin_det = np.amin(az[az > np.pi]) - 2 * np.pi
azmax_det = np.amax(az[az < np.pi])
elmin_det = np.amin(el)
elmax_det = np.amax(el)
if (
not (azmin <= azmin_det and azmax_det <= azmax)
and not (
azmin <= azmin_det - 2 * np.pi and azmax_det - 2 * np.pi <= azmax
)
) or not (elmin <= elmin_det and elmin_det <= elmax):
# DEBUG begin
import pickle
with open("bad_quats_{}_{}.pck".format(rank, det), "wb") as fout:
pickle.dump(
[scan_range, az, el, azelquat, tod._boresight_azel], fout
)
# DEBUG end
raise RuntimeError(
prefix + "Detector Az/El: [{:.5f}, {:.5f}], "
"[{:.5f}, {:.5f}] is not contained in "
"[{:.5f}, {:.5f}], [{:.5f} {:.5f}]"
"".format(
azmin_det,
azmax_det,
elmin_det,
elmax_det,
azmin,
azmax,
elmin,
elmax,
)
)
# Integrate detector signal
err = sim.observe(times[ind][good], az, el, atmdata, -1.0)
if err != 0:
# Observing failed
log.error(
"{}OpSimAtmosphere: Observing FAILED. "
"det = {}, rank = {}".format(prefix, det, rank)
)
atmdata[:] = 0
flag_ref[ind] = 255
if self._gain:
atmdata *= self._gain
if absorption is not None:
# Apply the frequency-dependent absorption-coefficient
atmdata *= absorption
ref[ind][good] += atmdata
del ref
if self._report_timing:
if comm is not None:
comm.Barrier()
if rank == 0:
tmr.stop()
tmr.report("{}OpSimAtmosphere: Observe atmosphere".format(prefix))
return
| [
"pickle.dump",
"numpy.arctan2",
"numpy.amin",
"numpy.sum",
"os.path.isfile",
"numpy.arange",
"os.path.join",
"toast.qarray.to_position",
"numpy.meshgrid",
"numpy.degrees",
"numpy.linspace",
"numpy.cos",
"os.makedirs",
"numpy.logical_and",
"numpy.ptp",
"numpy.zeros",
"numpy.amax",
"... | [((13522, 13578), 'numpy.linspace', 'np.linspace', (['azmin', 'azmax', '((azmax - azmin) // azstep + 1)'], {}), '(azmin, azmax, (azmax - azmin) // azstep + 1)\n', (13533, 13578), True, 'import numpy as np\n'), ((13596, 13652), 'numpy.linspace', 'np.linspace', (['elmin', 'elmax', '((elmax - elmin) // elstep + 1)'], {}), '(elmin, elmax, (elmax - elmin) // elstep + 1)\n', (13607, 13652), True, 'import numpy as np\n'), ((13670, 13697), 'numpy.meshgrid', 'np.meshgrid', (['azgrid', 'elgrid'], {}), '(azgrid, elgrid)\n', (13681, 13697), True, 'import numpy as np\n'), ((13785, 13815), 'numpy.zeros', 'np.zeros', (['nn'], {'dtype': 'np.float64'}), '(nn, dtype=np.float64)\n', (13793, 13815), True, 'import numpy as np\n'), ((13835, 13865), 'numpy.zeros', 'np.zeros', (['nn'], {'dtype': 'np.float64'}), '(nn, dtype=np.float64)\n', (13843, 13865), True, 'import numpy as np\n'), ((21794, 21820), 'numpy.sqrt', 'np.sqrt', (['(wx ** 2 + wy ** 2)'], {}), '(wx ** 2 + wy ** 2)\n', (21801, 21820), True, 'import numpy as np\n'), ((23128, 23154), 'numpy.sqrt', 'np.sqrt', (['(wx ** 2 + wy ** 2)'], {}), '(wx ** 2 + wy ** 2)\n', (23135, 23154), True, 'import numpy as np\n'), ((23177, 23195), 'numpy.arctan2', 'np.arctan2', (['wy', 'wx'], {}), '(wy, wx)\n', (23187, 23195), True, 'import numpy as np\n'), ((13475, 13504), 'numpy.cos', 'np.cos', (['(0.5 * (elmin + elmax))'], {}), '(0.5 * (elmin + elmax))\n', (13481, 13504), True, 'import numpy as np\n'), ((14134, 14162), 'numpy.arange', 'np.arange', (['tmin', 'tmax', 'tstep'], {}), '(tmin, tmax, tstep)\n', (14143, 14162), True, 'import numpy as np\n'), ((15055, 15104), 'pickle.dump', 'pickle.dump', (['[azgrid, elgrid, my_snapshots]', 'fout'], {}), '([azgrid, elgrid, my_snapshots], fout)\n', (15066, 15104), False, 'import pickle\n'), ((18881, 18942), 'os.path.join', 'os.path.join', (['self._cachedir', 'subdir', 'subsubdir', 'subsubsubdir'], {}), '(self._cachedir, subdir, subsubdir, subsubsubdir)\n', (18893, 18942), False, 'import os\n'), ((20242, 20273), 'numpy.cos', 'np.cos', (['(max_el_bore + fp_radius)'], {}), '(max_el_bore + fp_radius)\n', (20248, 20273), True, 'import numpy as np\n'), ((29295, 29328), 'numpy.zeros', 'np.zeros', (['ngood'], {'dtype': 'np.float64'}), '(ngood, dtype=np.float64)\n', (29303, 29328), True, 'import numpy as np\n'), ((29655, 29666), 'numpy.amin', 'np.amin', (['el'], {}), '(el)\n', (29662, 29666), True, 'import numpy as np\n'), ((29691, 29702), 'numpy.amax', 'np.amax', (['el'], {}), '(el)\n', (29698, 29702), True, 'import numpy as np\n'), ((11667, 11686), 'os.makedirs', 'os.makedirs', (['outdir'], {}), '(outdir)\n', (11678, 11686), False, 'import os\n'), ((12930, 12994), 'pickle.dump', 'pickle.dump', (['[det, t[good], az[good], el[good], ref[good]]', 'fout'], {}), '([det, t[good], az[good], el[good], ref[good]], fout)\n', (12941, 12994), False, 'import pickle\n'), ((14473, 14489), 'numpy.amin', 'np.amin', (['atmdata'], {}), '(atmdata)\n', (14480, 14489), True, 'import numpy as np\n'), ((14520, 14536), 'numpy.amax', 'np.amax', (['atmdata'], {}), '(atmdata)\n', (14527, 14536), True, 'import numpy as np\n'), ((14731, 14750), 'os.makedirs', 'os.makedirs', (['outdir'], {}), '(outdir)\n', (14742, 14750), False, 'import os\n'), ((25784, 25805), 'os.path.isfile', 'os.path.isfile', (['fname'], {}), '(fname)\n', (25798, 25805), False, 'import os\n'), ((28046, 28149), 'numpy.logical_and', 'np.logical_and', (['(common_ref[ind] & self._common_flag_mask == 0)', '(flag_ref[ind] & self._flag_mask == 0)'], {}), '(common_ref[ind] & self._common_flag_mask == 0, flag_ref[ind] &\n self._flag_mask == 0)\n', (28060, 28149), True, 'import numpy as np\n'), ((28229, 28241), 'numpy.sum', 'np.sum', (['good'], {}), '(good)\n', (28235, 28241), True, 'import numpy as np\n'), ((29345, 29355), 'numpy.ptp', 'np.ptp', (['az'], {}), '(az)\n', (29351, 29355), True, 'import numpy as np\n'), ((29393, 29404), 'numpy.amin', 'np.amin', (['az'], {}), '(az)\n', (29400, 29404), True, 'import numpy as np\n'), ((29433, 29444), 'numpy.amax', 'np.amax', (['az'], {}), '(az)\n', (29440, 29444), True, 'import numpy as np\n'), ((29607, 29630), 'numpy.amax', 'np.amax', (['az[az < np.pi]'], {}), '(az[az < np.pi])\n', (29614, 29630), True, 'import numpy as np\n'), ((10641, 10655), 'numpy.sqrt', 'np.sqrt', (['scale'], {}), '(scale)\n', (10648, 10655), True, 'import numpy as np\n'), ((10691, 10705), 'numpy.sqrt', 'np.sqrt', (['scale'], {}), '(scale)\n', (10698, 10705), True, 'import numpy as np\n'), ((10741, 10755), 'numpy.sqrt', 'np.sqrt', (['scale'], {}), '(scale)\n', (10748, 10755), True, 'import numpy as np\n'), ((12517, 12541), 'toast.qarray.to_position', 'qa.to_position', (['azelquat'], {}), '(azelquat)\n', (12531, 12541), True, 'import toast.qarray as qa\n'), ((21210, 21227), 'numpy.degrees', 'np.degrees', (['elmin'], {}), '(elmin)\n', (21220, 21227), True, 'import numpy as np\n'), ((21249, 21266), 'numpy.degrees', 'np.degrees', (['elmax'], {}), '(elmax)\n', (21259, 21266), True, 'import numpy as np\n'), ((21288, 21311), 'numpy.degrees', 'np.degrees', (['min_el_bore'], {}), '(min_el_bore)\n', (21298, 21311), True, 'import numpy as np\n'), ((21333, 21356), 'numpy.degrees', 'np.degrees', (['max_el_bore'], {}), '(max_el_bore)\n', (21343, 21356), True, 'import numpy as np\n'), ((21378, 21399), 'numpy.degrees', 'np.degrees', (['fp_radius'], {}), '(fp_radius)\n', (21388, 21399), True, 'import numpy as np\n'), ((25119, 25134), 'toast.mpi.comm_py2c', 'comm_py2c', (['comm'], {}), '(comm)\n', (25128, 25134), False, 'from toast.mpi import MPI, comm_py2c\n'), ((28372, 28384), 'numpy.sum', 'np.sum', (['good'], {}), '(good)\n', (28378, 28384), True, 'import numpy as np\n'), ((29074, 29098), 'toast.qarray.to_position', 'qa.to_position', (['azelquat'], {}), '(azelquat)\n', (29088, 29098), True, 'import toast.qarray as qa\n'), ((29543, 29566), 'numpy.amin', 'np.amin', (['az[az > np.pi]'], {}), '(az[az > np.pi])\n', (29550, 29566), True, 'import numpy as np\n'), ((30143, 30213), 'pickle.dump', 'pickle.dump', (['[scan_range, az, el, azelquat, tod._boresight_azel]', 'fout'], {}), '([scan_range, az, el, azelquat, tod._boresight_azel], fout)\n', (30154, 30213), False, 'import pickle\n'), ((19282, 19318), 'os.makedirs', 'os.makedirs', (['cachedir'], {'exist_ok': '(True)'}), '(cachedir, exist_ok=True)\n', (19293, 19318), False, 'import os\n')] |
#! /usr/bin/env python
'''
The clean_photometry.py script uses recursive outlier rejection
to identify stars from noisy astronomical catalogs containing stars,
galaxies and noise from many different sources.
With all dependencies installed (python3, Pandas, NumPy,
SciPy, AstroPy, Matplotlib etc.) the simplest use case is:
./clean_photomtry.py $path/filename.phot
where filename.phot is the raw DOLPHOT photomtery output.
This tool is built as part of the WFIRST simulations, analysis and
recommendation pipeline for carrying out Nearby Galaxies projects.
The current implementation requires STIPS simulation input catalogs
and optionally uses STIPS simulated images.
- <NAME>
<EMAIL>
'''
import time, argparse, concurrent.futures, matplotlib
matplotlib.use('Agg')
from matplotlib import cm
from matplotlib import pyplot as plt
plt.ioff()
import numpy as np
import pandas as pd
from astropy.io import ascii, fits
from astropy import units as u
from astropy import wcs
from astropy.coordinates import SkyCoord, match_coordinates_sky
from scipy.spatial import cKDTree
from os import cpu_count
'''Create worker pools'''
cpu_pool = concurrent.futures.ProcessPoolExecutor(max_workers=cpu_count())
'''
Therese parameters are used throughout the code:
feature_names: DOLPHOT quality parameters to use for
training Machine Learning models.
filters: WFIRST filters used in the simulation.
AB_Vega: Offsets between AB and Vega magnitude systems
fits_files, ref_fits, use_radec: Simulated images may
be misaligned by design to emulate real observational
conditions.
'''
# filter names
filters = np.array(['Z087','Y106','J129','H158','F184'])
# AB magnitude Zero points
AB_Vega = np.array([0.487, 0.653, 0.958, 1.287, 1.552])
# Simulated images
fits_files = ["sim_1_0.fits","sim_2_0.fits","sim_3_0.fits",
"sim_4_0.fits","sim_5_0.fits"]
sky_coord = np.zeros(len(filters))
ref_fits = int(3)
use_radec = False
def cleanAll(filename,filters=filters,AB_Vega=AB_Vega,
fits_files=fits_files,ref_fits=ref_fits,
sky_coord=sky_coord,use_radec=use_radec,
tol=1,niter=10,nsig=10,sigres=0.05,
sigcut=3.2,FR=0.4,RR=0.9,valid_mag=30):
fileroot,filename = get_fileroot(filename)
if use_radec:
sky_coord = [wcs.WCS(fits.open(fileroot+imfile)[1].header) \
for imfile in fits_files]
sigcuts = np.arange(sigcut-sigres*nsig/2,sigcut+sigres*nsig/2,sigres)
input_data,output_data = read_data(filename=filename,
fileroot=fileroot,
filters=filters)
in_DF,out_DF = prep_data(input_data,output_data,
filters=filters,
valid_mag=valid_mag)
_in,_out,_i,_j,_tol,_sigs,_nit,_file,_root,_FR,_RR,_best,_plots,_radec=\
[],[],[],[],[],[],[],[],[],[],[],[],[],[]
paired_in = lambda a,b,c: input_pair(in_DF,a,b,c)
paired_out = lambda a,b: output_pair(out_DF,a,b)
for i in range(len(filters)-1):
for j in range(i,len(filters)-1):
radec1 = {'opt':use_radec,
'wcs1':sky_coord[i],'wcs2':sky_coord[j+1]}
radec2 = {'opt':use_radec,
'wcs1':sky_coord[i],'wcs2':sky_coord[ref_fits]}
inPair,outPair = paired_in(i,j,radec1),paired_out(i,j)
_t1,_t2 = paired_in(i,j,radec1),paired_out(i,j)
_in.append(_t1); _out.append(_t2); _i.append(i); _j.append(j)
_tol.append(tol);_sigs.append(sigcuts);_nit.append(niter)
_file.append(filename);_root.append(fileroot)
_radec.append(radec2)
_FR.append(FR);_RR.append(RR);_best.append(True);_plots.append(True)
_t = cpu_pool.map(clean_all,_in,_out,_i,_j,\
_tol,_sigs,_nit,_RR,_FR,_file,_root,_best,_plots,_radec,\
chunksize=int(np.ceil(len(_i)/cpu_count())))
'''
_t = clean_all(_in[0],_out[0],_i[0],_j[0],\
_tol[0],_sigs[0],_nit[0],
_RR[0],_FR[0],_file[0],_root[0],
_best[0],_plots[0],_radec[0])
'''
return 1
def read_data(filename='10_10_phot.txt',fileroot='',filters=filters):
'''
Read in the raw fata files:
- Input: sythetic photometry file for image generation, IPAC format
- Output: DOLPHOT measured raw photometry, ASCII format
Return arrays of AstroPy tables for input and numpy arrays for output
ordered by corresponding filternames.
'''
input_data = [ascii.read(fileroot+filt+'_stips.txt',format='ipac')
for filt in filters]
output_data = np.loadtxt(fileroot+filename)
return input_data,output_data
def prep_data(input_data,output_data,
filters=filters,
valid_mag=30):
'''
Prepare the data for classification. The output data is now cleaned
to exclude low information entries
Return 2 arrays ordered by corresponding filternames:
- First array for input data in pandas data frames
- Second array for cleaned output data in pandas data frames
'''
nfilt = filters.size
xy = output_data[:,2:4].T
Count = output_data[:,range(13,13+13*nfilt,13)].T
vega_mags = output_data[:,range(15,15+13*nfilt,13)].T
mag_errors = output_data[:,range(17,17+13*nfilt,13)].T
SNR = output_data[:,range(19,19+13*nfilt,13)].T
Sharp = output_data[:,range(20,20+13*nfilt,13)].T
Round = output_data[:,range(21,21+13*nfilt,13)].T
Crowd = output_data[:,range(22,22+13*nfilt,13)].T
in_df,out_df = [],[]
for i in range(nfilt):
in_df.append(pack_input(input_data[i],valid_mag=valid_mag))
t = validate_output(mag_errors[i],
Count[i],SNR[i],
Sharp[i],Round[i],
Crowd[i])
out_df.append(pack_output(xy,vega_mags[i],mag_errors[i],
Count[i],SNR[i],Sharp[i],Round[i],
Crowd[i],t))
return in_df,out_df
def validate_output(err,count,snr,shr,rnd,crd):
'''
Clean and validate output data
- Remove measurements with unphysical values, such as negative countrate
- Remove low information entries, such as magnitude errors >0.5 & SNR <1
- Remove missing value indicators such as +/- 9.99
'''
return (err<0.5)&(count>=0)&(snr>=1)&(crd!=9.999)&\
(shr!=9.999)&(shr!=-9.999)&(rnd!=9.999)&(rnd!=-9.999)
def pack_input(data,valid_mag=30):
'''
return Pandas Dataframes for input AstroPy tables containing
sources that are brighter than specified magnitude (valid_mag)
'''
t = data['vegamag'] < valid_mag
return pd.DataFrame({'x':data['x'][t],'y':data['y'][t],\
'm':data['vegamag'][t],'type':data['type'][t]})
def pack_output(xy,mags,errs,count,snr,shr,rnd,crd,t):
'''
return Pandas Dataframes for output numpy arrays including
all quality parameter
'''
return pd.DataFrame({'x':xy[0][t],'y':xy[1][t],'mag':mags[t],'err':errs[t],
'Count':count[t],'SNR':snr[t],'Sharpness':shr[t],
'Roundness':rnd[t],'Crowding':crd[t]})
def input_pair(df,i,j,radec={'opt':False,'wcs1':'','wcs2':''}):
'''
Pick sources added in both bands as same object types
return data dictionary containing the two input magnitudes
(m1_in, m2_in), coordinates (X, Y) and input source type
(typ_in)
'''
m1_in,m2_in,X1,Y1,X2,Y2 = df[i]['m'].values,df[j+1]['m'].values,\
df[i]['x'].values,df[i]['y'].values,\
df[j+1]['x'].values,df[j+1]['y'].values
typ1_in, typ2_in = df[i]['type'].values, df[j+1]['type'].values
if radec['opt']:
ra1,dec1 = xy_to_wcs(np.array([X1,Y1]).T,radec['wcs1'])
ra2,dec2 = xy_to_wcs(np.array([X2,Y2]).T,radec['wcs2'])
in12= matchCats(0.05,ra1,dec1,ra2,dec2)
else:
in12 = matchLists(0.1,X1,Y1,X2,Y2)
m1_in,X1,Y1,typ1_in = m1_in[in12!=-1],\
X1[in12!=-1],Y1[in12!=-1],typ1_in[in12!=-1]
in12 = in12[in12!=-1]
m2_in,typ2_in = m2_in[in12],typ2_in[in12]
tt = typ1_in==typ2_in
m1_in,m2_in,X,Y,typ_in = m1_in[tt],\
m2_in[tt],X1[tt],Y1[tt],typ1_in[tt]
return dict(zip(['m1_in','m2_in','X','Y','typ_in'],[m1_in,m2_in,X,Y,typ_in]))
'''Recovered source photometry and quality params'''
def output_pair(df,i,j):
'''
Pick sources detected in both bands as same object types
return data dictionary containing the two output magnitudes (mag)
coordinates (xy), all quality parameters (err,snr,crd,rnd,shr)
and labels (lbl). Each dictionary item is has two elements for
two filters (xy has x and y).
'''
X1,Y1,X2,Y2 = df[i]['x'].values,df[i]['y'].values,\
df[j+1]['x'].values,df[j+1]['y'].values
t2 = matchLists(0.1,X1,Y1,X2,Y2)
t1 = t2!=-1
t2 = t2[t2!=-1]
xy = X1[t1],Y1[t1]
mags = [df[i]['mag'][t1].values,df[j+1]['mag'][t2].values]
errs = [df[i]['err'][t1].values,df[j+1]['err'][t2].values]
snrs = [df[i]['SNR'][t1].values,df[j+1]['SNR'][t2].values]
crds = [df[i]['Crowding'][t1].values,df[j+1]['Crowding'][t2].values]
rnds = [df[i]['Roundness'][t1].values,df[j+1]['Roundness'][t2].values]
shrs = [df[i]['Sharpness'][t1].values,df[j+1]['Sharpness'][t2].values]
nms = ['xy','mag','err','snr','crd','rnd','shr']
K = [xy,mags,errs,snrs,crds,rnds,shrs]
return dict(zip(nms,K))
def clean_all(all_in,all_out,i=0,j=0,tol=1,sigcuts=[3.0,3.2,3.5],niter=10,
RR=0.9,FR=0.25,filename='',fileroot='',best=True,plots=False,
radec={'opt':False,'wcs1':'','wcs2':''},
show_plot=False):
X,Y,typ_in,x,y,m1,m2,K = unpack_inOut(all_in,all_out)
''' Order of quality param use '''
nms = ['rnd','shr','err','crd','snr']
#nms = ['err','shr','rnd']
myClean = lambda a: clean_up(X,Y,typ_in,x,y,m1,m2,K,nms,\
tol=tol,sigcut=a,niter=niter,RR=RR,FR=FR,
radec=radec)
_rr,_fr,_tt = [],[],[]
for sigcut in sigcuts:
_r,_f,_t = myClean(sigcut)
_rr.append(_r); _fr.append(_f); _tt.append(_t)
_rr,_fr,_tt,_sig = np.array(_rr), np.array(_fr), np.array(_tt), np.array(sigcuts)
if len(_fr[_fr<FR])>0:
t = _fr<FR
_rr,_fr,_tt,_sig = _rr[t],_fr[t],_tt[t],_sig[t]
if len(_rr)>1:
t = np.argmax(_rr)
_rr,_fr,_tt, _sig = _rr[t],_fr[t],_tt[t],_sig[t]
else:
t = np.argmin(_fr)
_rr,_fr,_tt, _sig = _rr[t],_fr[t],_tt[t],_sig[t]
t = _tt==True
if best:
show_cuts(K,nms,t,_sig,filters[i],filters[j+1])
if plots:
tmp, typ_out = match_in_out(tol,X,Y,x[t],y[t],typ_in,radec=radec)
clean_out = dict(zip(['m1','m2','x','y','typ_out'],[m1[t],m2[t],x[t],y[t],typ_out]))
make_plots(all_in,all_out,clean_out,\
filt1=filters[i],filt2=filters[j+1],\
AB_Vega1=AB_Vega[i],AB_Vega2=AB_Vega[j+1],\
fileroot=fileroot,tol=tol,\
opt=['input','output','clean','diff'],\
radec=radec,show_plot=show_plot)
return 1
def show_cuts(K,nms,t,wd=3.2,filt1='',filt2='',wt=2):
print('\nFilters: {:s} and {:s}\nCuts:'.format(filt1,filt2))
for s in range(len(nms)):
xt,yt = K[nms[s]][0][t], K[nms[s]][1][t]
xtm,xts,ytm,yts = xt.mean(), xt.std(), yt.mean(), yt.std()
xlo,xhi,ylo,yhi = xtm-wd*xts, xtm+wd*xts, ytm-wd*yts, ytm+wd*yts
if (nms[s]=='err')|(nms[s]=='crd'):
xlo,ylo = 0,0
elif nms[s]=='snr':
xhi,yhi = xhi*wt,yhi*wt
if xlo<1: xlo=1
if ylo<1: ylo=1
print('{:s}\t{:.2f}\t{:.2f}\t{:.2f}\t{:.2f}'.format(nms[s],xlo,xhi,ylo,yhi))
return 1
'''Iteratively reject outliers until desired false-rate is achieved'''
def clean_up(X,Y,typ_in,x,y,m1,m2,K,nms,tol=1,sigcut=3.5,niter=10,RR=0.9,FR=0.25,
radec={'opt':False,'wcs1':'','wcs2':''}):
rr,fr,t = 0, 1, np.repeat(True,len(x))
for z in range(niter):
if (fr>FR):
for s in range(len(nms)):
tmp, typ_out = match_in_out(tol,X,Y,x[t],y[t],typ_in,radec=radec)
k0,k1 = K[nms[s]][0][t], K[nms[s]][1][t]
p0,p1 = k0[typ_out=='point'], k1[typ_out=='point']
t1 = myCut(k0,k1,p0,p1,sigcut,nms[int(s)])
t[t] = t1
tmp, typ_out = match_in_out(tol,X,Y,x[t],y[t],typ_in,radec=radec)
rr,fr = get_stat(typ_in,typ_out)
else:
break
# Also return the cuts
return rr,fr,t
'''Sigma outlier culling'''
def myCut(x,y,xt,yt,wd=3.5,nms='',wt=2):
xtm,xts,ytm,yts = xt.mean(), xt.std(), yt.mean(), yt.std()
xlo,xhi,ylo,yhi = xtm-wd*xts, xtm+wd*xts, ytm-wd*yts, ytm+wd*yts
if (nms=='err')|(nms=='crd'):
return (x<xhi) & (y<yhi)
elif (nms=='rnd')|(nms=='shr'):
return (x<xhi)&(x>xlo)&(y<yhi)&(y>ylo)
elif nms=='snr':
if xlo<1: xlo=1
if ylo<1: ylo=1
return (x<xhi*wt)&(x>xlo)&(y<yhi*wt)&(y>ylo)
def matchLists(tol,x1,y1,x2,y2):
'''
Match X and Y coordinates using cKDTree
return index of 2nd list at coresponding position in the 1st
return -1 if no match is found within matching radius (tol)
'''
d1 = np.empty((x1.size, 2))
d2 = np.empty((x2.size, 2))
d1[:,0],d1[:,1] = x1,y1
d2[:,0],d2[:,1] = x2,y2
t = cKDTree(d2)
tmp, in1 = t.query(d1, distance_upper_bound=tol)
in1[in1==x2.size] = -1
return in1
def matchCats(tol,ra1,dec1,ra2,dec2):
'''
Match astronomical coordinates using SkyCoord
return index of 2nd list at coresponding position in the 1st
return -1 if no match is found within matching radius (tol)
'''
c1 = SkyCoord(ra=ra1*u.degree, dec=dec1*u.degree)
c2 = SkyCoord(ra=ra2*u.degree, dec=dec2*u.degree)
in1,sep,tmp = match_coordinates_sky(c1,c2,storekdtree=False)
sep = sep.to(u.arcsec)
in1[in1==ra2.size] = -1
in1[sep>tol*u.arcsec] = -1
return in1
def match_in_out(tol,X,Y,x,y,typ_in,
radec={'opt':False,'wcs1':'','wcs2':''}):
'''
Match input coordnates to recovered coordinates picking the
closest matched item.
return index of output entry at coresponding position in the
input list and source type of the matching input
return -1 as the index if no match is found and source type
as 'other' (not point source)
'''
if radec['opt']:
ra1,dec1 = xy_to_wcs(np.array([X,Y]).T,radec['wcs1'])
ra2,dec2 = xy_to_wcs(np.array([x,y]).T,radec['wcs2'])
in1 = matchCats(tol*0.11,ra1,dec1,ra2,dec2)
else:
in1 = matchLists(tol,X,Y,x,y)
in2 = in1!=-1
in3 = in1[in2]
in4 = np.arange(len(x))
in5 = np.setdiff1d(in4,in3)
typ_out = np.empty(len(x),dtype='<U10')
typ_out[in3] = typ_in[in2]
typ_out[in5] = 'other'
return in1, typ_out
def get_stat(typ_in,typ_out):
''' Return recovery rate and false rate for stars'''
all_in, all_recov = len(typ_in), len(typ_out)
stars_in = len(typ_in[typ_in=='point'])
stars_recov = len(typ_out[typ_out=='point'])
recovery_rate = (stars_recov / stars_in)
false_rate = 1 - (stars_recov / all_recov)
return recovery_rate,false_rate
'''Take quality cuts on recovered'''
def unpack_inOut(all_in,all_out,tol=1,n=5):
X,Y,typ_in = all_in['X'], all_in['Y'], all_in['typ_in']
x,y,m1,m2 = all_out['xy'][0], all_out['xy'][1],\
all_out['mag'][0], all_out['mag'][1]
err,rnd,shr,crd,snr = all_out['err'],all_out['rnd'],\
all_out['shr'],all_out['crd'],all_out['snr']
K = [[rnd[0],rnd[1]],[shr[0],shr[1]],[err[0],err[1]],\
[crd[0],crd[1]],[snr[0],snr[1]]]
nms = ['rnd','shr','err','crd','snr']
return X,Y,typ_in,x,y,m1,m2,dict(zip(nms,K))
def make_plots(all_in=[],all_out=[],clean_out=[],\
filt1='',filt2='',AB_Vega1=0,AB_Vega2=0,
fileroot='',tol=5,
opt=['input','output','clean','diff'],
radec={'opt':False,'wcs1':'','wcs2':''},
show_plot=False):
'''Produce color-magnitude diagrams and systematic offsets'''
print('\nFilters {:s} and {:s}:'.format(filt1,filt2))
plot_me = lambda a,b,st,ot,ttl,pre,post: \
plot_cmd(a,b,filt1=filt1,filt2=filt2,\
stars=st,other=ot,title=ttl,\
fileroot=fileroot,outfile=\
'_'.join((pre,'cmd',filt1,filt2,post)),\
show_plot=show_plot)
plot_it = lambda a,b,filt: \
plot_xy(x=a,y=a-b,\
ylim1=-1.5,ylim2=0.5,xlim1=24.5,xlim2=28,\
ylabel='magIn - magOut',xlabel='magOut',\
title='In-Out Mag Diff {:s}'.format(filt),\
fileroot=fileroot,\
outfile='_'.join(('mag','diff',filt)),\
show_plot=show_plot)
if (('input' in opt)&(len(all_in)>0)):
m1_in,m2_in,typ_in = all_in['m1_in'],all_in['m2_in'],all_in['typ_in']
stars,other = typ_in=='point',typ_in!='point'
print('Stars: {:d} Others: {:d}'.format(int(np.sum(stars)),int(np.sum(other))))
plot_me(m1_in,m2_in,stars,other,\
'Input CMD (Vega)','input','Vega')
#plot_me(m1_in+AB_Vega1,m2_in+AB_Vega2,stars,other,\
# 'Input CMD (AB)','input','AB')
if (('output' in opt)&(len(all_out)>0)):
m1,m2 = all_out['mag'][0], all_out['mag'][1]
if 'input' in opt:
X,Y,x,y = all_in['X'],all_in['Y'], all_out['xy'][0], all_out['xy'][1]
in1, typ_out = match_in_out(tol,X,Y,x,y,typ_in,radec=radec)
stars,other = typ_out=='point',typ_out!='point'
if (('diff' in opt)|('diff2' in opt)):
t1 = (in1!=-1)&(typ_in=='point')
m1in,m2in,m1t,m2t = m1_in[t1],m2_in[t1],m1[in1[t1]],m2[in1[t1]]
t2 = typ_out[in1[t1]]=='point'
m1in,m2in,m1t,m2t=m1in[t2],m2in[t2],m1t[t2],m2t[t2]
if 'diff' in opt:
plot_it(m1in,m1t,filt1)
if 'diff2' in opt:
plot_it(m2in,m2t,filt2)
else:
typ_out = np.repeat('other',len(m1))
stars,other = typ_out=='point',typ_out!='point'
print('Stars: {:d} Others: {:d}'.format(int(np.sum(stars)),int(np.sum(other))))
plot_me(m1,m2,stars,other,'Full CMD','output','full')
if (('clean' in opt)&(len(clean_out)>0)):
m1,m2,typ_out = clean_out['m1'],clean_out['m2'],clean_out['typ_out']
stars,other = typ_out=='point',typ_out!='point'
print('Stars: {:d} Others: {:d}'.format(int(np.sum(stars)),int(np.sum(other))))
plot_me(m1,m2,stars,other,'Cleaned CMD','clean','clean')
rr,fr = get_stat(all_in['typ_in'],clean_out['typ_out'])
print('Recovery Rate:\t {:.2f}\nFalse Rate: \t {:.2f}\n'.format(rr,fr))
return print('\n')
def plot_cmd(m1,m2,e1=[],e2=[],filt1='',filt2='',stars=[],other=[],\
fileroot='',outfile='test',fmt='png',\
xlim1=-1.5,xlim2=3.5,ylim1=29.5,ylim2=20.5,n=4,
title='',show_plot=False):
'''Produce color-magnitude diagrams'''
m1m2 = m1-m2
plt.rc("font", family='serif', weight='bold')
plt.rc("xtick", labelsize=15); plt.rc("ytick", labelsize=15)
fig = plt.figure(1, ((10,10)))
fig.suptitle(title,fontsize=5*n)
if len(stars[stars])==0:
m1m2t,m2t = plotHess(m1m2,m2)
plt.plot(m1m2t,m2t,'k.',markersize=2,alpha=0.75,zorder=3)
else:
plt.plot(m1m2[stars],m2[stars],'b.',markersize=2,\
alpha=0.75,zorder=2,label='Stars: %d' % len(m2[stars]))
plt.plot(m1m2[other],m2[other],'k.',markersize=1,\
alpha=0.5,zorder=1,label='Other: %d' % len(m2[other]))
plt.legend(loc=4,fontsize=20)
if (len(e1)&len(e2)):
m1m2err = np.sqrt(e1**2+e2**2)
plot_error_bars(m2,e2,m1m2err,xlim1,xlim2,ylim1,slope=[])
plt.xlim(xlim1,xlim2); plt.ylim(ylim1,ylim2)
plt.xlabel(str(filt1+'-'+filt2),fontsize=20)
plt.ylabel(filt2,fontsize=20)
print('\t\t\t Writing out: ',fileroot+outfile+'.'+str(fmt))
plt.savefig(fileroot+outfile+'.'+str(fmt))
if show_plot: plt.show()
return plt.close()
def plot_xy(x,y,xlabel='',ylabel='',title='',stars=[],other=[],\
xlim1=-1,xlim2=1,ylim1=-7.5,ylim2=7.5,\
fileroot='',outfile='test',fmt='png',n=4,
show_plot=False):
'''Custom scatterplot maker'''
plt.rc("font", family='serif', weight='bold')
plt.rc("xtick", labelsize=15); plt.rc("ytick", labelsize=15)
fig = plt.figure(1, ((10,10)))
fig.suptitle(title,fontsize=5*n)
if not len(x[other]):
plt.plot(x, y,'k.',markersize=1,alpha=0.5)
else:
plt.plot(x[stars],y[stars],'b.',markersize=2,\
alpha=0.5,zorder=2,label='Stars: %d' % len(x[stars]))
plt.plot(x[other],y[other],'k.',markersize=1,\
alpha=0.75,zorder=1,label='Other: %d' % len(x[other]))
plt.legend(loc=4,fontsize=20)
plt.xlim(xlim1,xlim2); plt.ylim(ylim1,ylim2)
plt.xlabel(xlabel,fontsize=20)
plt.ylabel(ylabel,fontsize=20)
plt.savefig(fileroot+outfile+'.'+str(fmt))
#print('\t\t\t Writing out: ',fileroot+outfile+'.'+str(fmt))
if show_plot: plt.show()
return plt.close()
def plotHess(color,mag,binsize=0.1,threshold=25):
'''Overplot hess diagram for densest regions
of a scatterplot'''
if not len(color)>threshold:
return color,mag
mmin,mmax = np.amin(mag),np.amax(mag)
cmin,cmax = np.amin(color),np.amax(color)
nmbins = np.ceil((cmax-cmin)/binsize)
ncbins = np.ceil((cmax-cmin)/binsize)
Z, xedges, yedges = np.histogram2d(color,mag,\
bins=(ncbins,nmbins))
X = 0.5*(xedges[:-1] + xedges[1:])
Y = 0.5*(yedges[:-1] + yedges[1:])
y, x = np.meshgrid(Y, X)
z = np.ma.array(Z, mask=(Z==0))
levels = np.logspace(np.log10(threshold),\
np.log10(np.amax(z)),(nmbins/ncbins)*20)
if (np.amax(z)>threshold)&(len(levels)>1):
cntr=plt.contourf(x,y,z,cmap=cm.jet,levels=levels,zorder=0)
cntr.cmap.set_under(alpha=0)
x,y,z = x.flatten(),y.flatten(),Z.flatten()
x = x[z>2.5*threshold]
y = y[z>2.5*threshold]
mask = np.zeros_like(mag)
for col,m in zip(x,y):
mask[(m-binsize<mag)&(m+binsize>mag)&\
(col-binsize<color)&(col+binsize>color)]=1
mag = np.ma.array(mag,mask=mask)
color = np.ma.array(color,mask=mask)
return color,mag
def xy_to_wcs(xy,_w):
'''Convert pixel coordinates (xy) to astronomical
coordinated (RA and DEC)'''
_radec = _w.wcs_pix2world(xy,1)
return _radec[:,0],_radec[:,1]
def get_fileroot(filename):
'''return path to a file and filename'''
if '/' in filename:
tmp = filename.split('/')[-1]
fileroot = filename[:-len(tmp)]
filename = tmp
else:
fileroot = ''
return fileroot, filename
'''Argument parser template'''
def parse_all():
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='+',help='Photomtery file names')
parser.add_argument('--NITER', '-niter', type=int, dest='niter', default=10, help='Maximum iterations')
parser.add_argument('--NSIG', '-nsig', type=int, dest='nsig', default=4, help='# of other sigma thresholds to try')
parser.add_argument('--SIGRES', '-sigres', type=float, dest='sigres', default=0.1, help='Sigma stepsize')
parser.add_argument('--SIGMA', '-sig', type=float, dest='sig', default=3.5, help='Sigma threshold removing outliers')
parser.add_argument('--RADIUS', '-tol', type=float, dest='tol', default=5, help='Matching radius in pixels')
parser.add_argument('--FALSE', '-fr', type=float, dest='fr', default=0.2, help='Desired False Rate')
parser.add_argument('--RECOV', '-rr', type=float, dest='rr', default=0.5, help='Desired Recovery Rate')
parser.add_argument('--VALIDMAG', '-mag', type=float, dest='mag', default=30, help='Expected depth in mag')
return parser.parse_args()
'''If executed from command line'''
if __name__ == '__main__':
tic = time.time()
assert 3/2 == 1.5, 'Not running Python3 may lead to wrong results'
args = parse_all()
_do = lambda x: cleanAll(x, tol=args.tol,\
niter=args.niter, nsig=args.nsig,\
sigres=args.sigres, sigcut=args.sig,\
FR=args.fr,RR=args.rr)
for filename in args.filenames:
_do(filename)
else:
cpu_pool.shutdown(wait=True)
print('\n\nCompleted in %.3f seconds \n' % (time.time()-tic))
| [
"astropy.io.ascii.read",
"argparse.ArgumentParser",
"numpy.amin",
"numpy.argmax",
"numpy.sum",
"numpy.empty",
"numpy.argmin",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.contourf",
"scipy.spatial.cKDTree",
"pandas.DataFrame",
"numpy.meshgrid",
"numpy.zeros_like",
"matp... | [((757, 778), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (771, 778), False, 'import time, argparse, concurrent.futures, matplotlib\n'), ((842, 852), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (850, 852), True, 'from matplotlib import pyplot as plt\n'), ((1613, 1663), 'numpy.array', 'np.array', (["['Z087', 'Y106', 'J129', 'H158', 'F184']"], {}), "(['Z087', 'Y106', 'J129', 'H158', 'F184'])\n", (1621, 1663), True, 'import numpy as np\n'), ((1701, 1746), 'numpy.array', 'np.array', (['[0.487, 0.653, 0.958, 1.287, 1.552]'], {}), '([0.487, 0.653, 0.958, 1.287, 1.552])\n', (1709, 1746), True, 'import numpy as np\n'), ((2413, 2486), 'numpy.arange', 'np.arange', (['(sigcut - sigres * nsig / 2)', '(sigcut + sigres * nsig / 2)', 'sigres'], {}), '(sigcut - sigres * nsig / 2, sigcut + sigres * nsig / 2, sigres)\n', (2422, 2486), True, 'import numpy as np\n'), ((4757, 4788), 'numpy.loadtxt', 'np.loadtxt', (['(fileroot + filename)'], {}), '(fileroot + filename)\n', (4767, 4788), True, 'import numpy as np\n'), ((6903, 7009), 'pandas.DataFrame', 'pd.DataFrame', (["{'x': data['x'][t], 'y': data['y'][t], 'm': data['vegamag'][t], 'type':\n data['type'][t]}"], {}), "({'x': data['x'][t], 'y': data['y'][t], 'm': data['vegamag'][t],\n 'type': data['type'][t]})\n", (6915, 7009), True, 'import pandas as pd\n'), ((7199, 7380), 'pandas.DataFrame', 'pd.DataFrame', (["{'x': xy[0][t], 'y': xy[1][t], 'mag': mags[t], 'err': errs[t], 'Count':\n count[t], 'SNR': snr[t], 'Sharpness': shr[t], 'Roundness': rnd[t],\n 'Crowding': crd[t]}"], {}), "({'x': xy[0][t], 'y': xy[1][t], 'mag': mags[t], 'err': errs[t],\n 'Count': count[t], 'SNR': snr[t], 'Sharpness': shr[t], 'Roundness': rnd\n [t], 'Crowding': crd[t]})\n", (7211, 7380), True, 'import pandas as pd\n'), ((13621, 13643), 'numpy.empty', 'np.empty', (['(x1.size, 2)'], {}), '((x1.size, 2))\n', (13629, 13643), True, 'import numpy as np\n'), ((13653, 13675), 'numpy.empty', 'np.empty', (['(x2.size, 2)'], {}), '((x2.size, 2))\n', (13661, 13675), True, 'import numpy as np\n'), ((13740, 13751), 'scipy.spatial.cKDTree', 'cKDTree', (['d2'], {}), '(d2)\n', (13747, 13751), False, 'from scipy.spatial import cKDTree\n'), ((14092, 14140), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'ra': '(ra1 * u.degree)', 'dec': '(dec1 * u.degree)'}), '(ra=ra1 * u.degree, dec=dec1 * u.degree)\n', (14100, 14140), False, 'from astropy.coordinates import SkyCoord, match_coordinates_sky\n'), ((14146, 14194), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'ra': '(ra2 * u.degree)', 'dec': '(dec2 * u.degree)'}), '(ra=ra2 * u.degree, dec=dec2 * u.degree)\n', (14154, 14194), False, 'from astropy.coordinates import SkyCoord, match_coordinates_sky\n'), ((14209, 14257), 'astropy.coordinates.match_coordinates_sky', 'match_coordinates_sky', (['c1', 'c2'], {'storekdtree': '(False)'}), '(c1, c2, storekdtree=False)\n', (14230, 14257), False, 'from astropy.coordinates import SkyCoord, match_coordinates_sky\n'), ((15111, 15133), 'numpy.setdiff1d', 'np.setdiff1d', (['in4', 'in3'], {}), '(in4, in3)\n', (15123, 15133), True, 'import numpy as np\n'), ((19625, 19670), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""', 'weight': '"""bold"""'}), "('font', family='serif', weight='bold')\n", (19631, 19670), True, 'from matplotlib import pyplot as plt\n'), ((19675, 19704), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(15)'}), "('xtick', labelsize=15)\n", (19681, 19704), True, 'from matplotlib import pyplot as plt\n'), ((19706, 19735), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(15)'}), "('ytick', labelsize=15)\n", (19712, 19735), True, 'from matplotlib import pyplot as plt\n'), ((19746, 19769), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)', '(10, 10)'], {}), '(1, (10, 10))\n', (19756, 19769), True, 'from matplotlib import pyplot as plt\n'), ((20377, 20399), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xlim1', 'xlim2'], {}), '(xlim1, xlim2)\n', (20385, 20399), True, 'from matplotlib import pyplot as plt\n'), ((20400, 20422), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ylim1', 'ylim2'], {}), '(ylim1, ylim2)\n', (20408, 20422), True, 'from matplotlib import pyplot as plt\n'), ((20475, 20505), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['filt2'], {'fontsize': '(20)'}), '(filt2, fontsize=20)\n', (20485, 20505), True, 'from matplotlib import pyplot as plt\n'), ((20656, 20667), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (20665, 20667), True, 'from matplotlib import pyplot as plt\n'), ((20910, 20955), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""', 'weight': '"""bold"""'}), "('font', family='serif', weight='bold')\n", (20916, 20955), True, 'from matplotlib import pyplot as plt\n'), ((20960, 20989), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(15)'}), "('xtick', labelsize=15)\n", (20966, 20989), True, 'from matplotlib import pyplot as plt\n'), ((20991, 21020), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(15)'}), "('ytick', labelsize=15)\n", (20997, 21020), True, 'from matplotlib import pyplot as plt\n'), ((21031, 21054), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)', '(10, 10)'], {}), '(1, (10, 10))\n', (21041, 21054), True, 'from matplotlib import pyplot as plt\n'), ((21465, 21487), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xlim1', 'xlim2'], {}), '(xlim1, xlim2)\n', (21473, 21487), True, 'from matplotlib import pyplot as plt\n'), ((21488, 21510), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ylim1', 'ylim2'], {}), '(ylim1, ylim2)\n', (21496, 21510), True, 'from matplotlib import pyplot as plt\n'), ((21514, 21545), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {'fontsize': '(20)'}), '(xlabel, fontsize=20)\n', (21524, 21545), True, 'from matplotlib import pyplot as plt\n'), ((21549, 21580), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {'fontsize': '(20)'}), '(ylabel, fontsize=20)\n', (21559, 21580), True, 'from matplotlib import pyplot as plt\n'), ((21732, 21743), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (21741, 21743), True, 'from matplotlib import pyplot as plt\n'), ((22029, 22061), 'numpy.ceil', 'np.ceil', (['((cmax - cmin) / binsize)'], {}), '((cmax - cmin) / binsize)\n', (22036, 22061), True, 'import numpy as np\n'), ((22071, 22103), 'numpy.ceil', 'np.ceil', (['((cmax - cmin) / binsize)'], {}), '((cmax - cmin) / binsize)\n', (22078, 22103), True, 'import numpy as np\n'), ((22124, 22173), 'numpy.histogram2d', 'np.histogram2d', (['color', 'mag'], {'bins': '(ncbins, nmbins)'}), '(color, mag, bins=(ncbins, nmbins))\n', (22138, 22173), True, 'import numpy as np\n'), ((22290, 22307), 'numpy.meshgrid', 'np.meshgrid', (['Y', 'X'], {}), '(Y, X)\n', (22301, 22307), True, 'import numpy as np\n'), ((22316, 22343), 'numpy.ma.array', 'np.ma.array', (['Z'], {'mask': '(Z == 0)'}), '(Z, mask=Z == 0)\n', (22327, 22343), True, 'import numpy as np\n'), ((23508, 23533), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (23531, 23533), False, 'import time, argparse, concurrent.futures, matplotlib\n'), ((24615, 24626), 'time.time', 'time.time', ([], {}), '()\n', (24624, 24626), False, 'import time, argparse, concurrent.futures, matplotlib\n'), ((1194, 1205), 'os.cpu_count', 'cpu_count', ([], {}), '()\n', (1203, 1205), False, 'from os import cpu_count\n'), ((4646, 4703), 'astropy.io.ascii.read', 'ascii.read', (["(fileroot + filt + '_stips.txt')"], {'format': '"""ipac"""'}), "(fileroot + filt + '_stips.txt', format='ipac')\n", (4656, 4703), False, 'from astropy.io import ascii, fits\n'), ((10424, 10437), 'numpy.array', 'np.array', (['_rr'], {}), '(_rr)\n', (10432, 10437), True, 'import numpy as np\n'), ((10439, 10452), 'numpy.array', 'np.array', (['_fr'], {}), '(_fr)\n', (10447, 10452), True, 'import numpy as np\n'), ((10454, 10467), 'numpy.array', 'np.array', (['_tt'], {}), '(_tt)\n', (10462, 10467), True, 'import numpy as np\n'), ((10469, 10486), 'numpy.array', 'np.array', (['sigcuts'], {}), '(sigcuts)\n', (10477, 10486), True, 'import numpy as np\n'), ((10733, 10747), 'numpy.argmin', 'np.argmin', (['_fr'], {}), '(_fr)\n', (10742, 10747), True, 'import numpy as np\n'), ((19883, 19945), 'matplotlib.pyplot.plot', 'plt.plot', (['m1m2t', 'm2t', '"""k."""'], {'markersize': '(2)', 'alpha': '(0.75)', 'zorder': '(3)'}), "(m1m2t, m2t, 'k.', markersize=2, alpha=0.75, zorder=3)\n", (19891, 19945), True, 'from matplotlib import pyplot as plt\n'), ((20212, 20242), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(4)', 'fontsize': '(20)'}), '(loc=4, fontsize=20)\n', (20222, 20242), True, 'from matplotlib import pyplot as plt\n'), ((20286, 20312), 'numpy.sqrt', 'np.sqrt', (['(e1 ** 2 + e2 ** 2)'], {}), '(e1 ** 2 + e2 ** 2)\n', (20293, 20312), True, 'import numpy as np\n'), ((20634, 20644), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20642, 20644), True, 'from matplotlib import pyplot as plt\n'), ((21127, 21172), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'markersize': '(1)', 'alpha': '(0.5)'}), "(x, y, 'k.', markersize=1, alpha=0.5)\n", (21135, 21172), True, 'from matplotlib import pyplot as plt\n'), ((21431, 21461), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(4)', 'fontsize': '(20)'}), '(loc=4, fontsize=20)\n', (21441, 21461), True, 'from matplotlib import pyplot as plt\n'), ((21710, 21720), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (21718, 21720), True, 'from matplotlib import pyplot as plt\n'), ((21944, 21956), 'numpy.amin', 'np.amin', (['mag'], {}), '(mag)\n', (21951, 21956), True, 'import numpy as np\n'), ((21957, 21969), 'numpy.amax', 'np.amax', (['mag'], {}), '(mag)\n', (21964, 21969), True, 'import numpy as np\n'), ((21986, 22000), 'numpy.amin', 'np.amin', (['color'], {}), '(color)\n', (21993, 22000), True, 'import numpy as np\n'), ((22001, 22015), 'numpy.amax', 'np.amax', (['color'], {}), '(color)\n', (22008, 22015), True, 'import numpy as np\n'), ((22369, 22388), 'numpy.log10', 'np.log10', (['threshold'], {}), '(threshold)\n', (22377, 22388), True, 'import numpy as np\n'), ((22504, 22563), 'matplotlib.pyplot.contourf', 'plt.contourf', (['x', 'y', 'z'], {'cmap': 'cm.jet', 'levels': 'levels', 'zorder': '(0)'}), '(x, y, z, cmap=cm.jet, levels=levels, zorder=0)\n', (22516, 22563), True, 'from matplotlib import pyplot as plt\n'), ((22725, 22743), 'numpy.zeros_like', 'np.zeros_like', (['mag'], {}), '(mag)\n', (22738, 22743), True, 'import numpy as np\n'), ((10632, 10646), 'numpy.argmax', 'np.argmax', (['_rr'], {}), '(_rr)\n', (10641, 10646), True, 'import numpy as np\n'), ((22412, 22422), 'numpy.amax', 'np.amax', (['z'], {}), '(z)\n', (22419, 22422), True, 'import numpy as np\n'), ((22452, 22462), 'numpy.amax', 'np.amax', (['z'], {}), '(z)\n', (22459, 22462), True, 'import numpy as np\n'), ((22904, 22931), 'numpy.ma.array', 'np.ma.array', (['mag'], {'mask': 'mask'}), '(mag, mask=mask)\n', (22915, 22931), True, 'import numpy as np\n'), ((22951, 22980), 'numpy.ma.array', 'np.ma.array', (['color'], {'mask': 'mask'}), '(color, mask=mask)\n', (22962, 22980), True, 'import numpy as np\n'), ((7972, 7990), 'numpy.array', 'np.array', (['[X1, Y1]'], {}), '([X1, Y1])\n', (7980, 7990), True, 'import numpy as np\n'), ((8036, 8054), 'numpy.array', 'np.array', (['[X2, Y2]'], {}), '([X2, Y2])\n', (8044, 8054), True, 'import numpy as np\n'), ((14840, 14856), 'numpy.array', 'np.array', (['[X, Y]'], {}), '([X, Y])\n', (14848, 14856), True, 'import numpy as np\n'), ((14902, 14918), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (14910, 14918), True, 'import numpy as np\n'), ((17536, 17549), 'numpy.sum', 'np.sum', (['stars'], {}), '(stars)\n', (17542, 17549), True, 'import numpy as np\n'), ((17555, 17568), 'numpy.sum', 'np.sum', (['other'], {}), '(other)\n', (17561, 17568), True, 'import numpy as np\n'), ((18738, 18751), 'numpy.sum', 'np.sum', (['stars'], {}), '(stars)\n', (18744, 18751), True, 'import numpy as np\n'), ((18757, 18770), 'numpy.sum', 'np.sum', (['other'], {}), '(other)\n', (18763, 18770), True, 'import numpy as np\n'), ((19069, 19082), 'numpy.sum', 'np.sum', (['stars'], {}), '(stars)\n', (19075, 19082), True, 'import numpy as np\n'), ((19088, 19101), 'numpy.sum', 'np.sum', (['other'], {}), '(other)\n', (19094, 19101), True, 'import numpy as np\n'), ((25099, 25110), 'time.time', 'time.time', ([], {}), '()\n', (25108, 25110), False, 'import time, argparse, concurrent.futures, matplotlib\n'), ((2310, 2338), 'astropy.io.fits.open', 'fits.open', (['(fileroot + imfile)'], {}), '(fileroot + imfile)\n', (2319, 2338), False, 'from astropy.io import ascii, fits\n'), ((4014, 4025), 'os.cpu_count', 'cpu_count', ([], {}), '()\n', (4023, 4025), False, 'from os import cpu_count\n')] |
import numpy as np
import os
import torch
import json
import nltk
from torch import nn
from torchtext import vocab
from collections import defaultdict
from modules.Utils import utils
class IO:
UNKNOWN = '**UNK**'
PADDING = '**PAD**'
# it's called "GO" but actually serves as a null alignment
GO = '**GO**'
def _generate_random_vector(self, size):
"""
Generate a random vector from a uniform distribution between
-0.1 and 0.1.
"""
return np.random.uniform(-0.1, 0.1, size)
def write_extra_embeddings(self, embeddings, dirname):
"""
Write the extra embeddings (for unknown, padding and null)
to a numpy file. They are assumed to be the first three in
the embeddings model.
"""
path = os.path.join(dirname, 'extra-embeddings.npy')
torch.save(embeddings[:3], path)
def load_embeddings(self, params, normalize=True, generate=True):
glove = vocab.GloVe(name='6B', dim=params.embedding_dim)
wordlist, embeddings = glove.stoi, glove.vectors
mapping = zip(wordlist, range(3, len(wordlist) + 3))
# always map OOV words to 0
wd = defaultdict(int, mapping)
wd[self.UNKNOWN] = 0
wd[self.PADDING] = 1
wd[self.GO] = 2
if generate:
vector_size = embeddings.shape[1]
extra = torch.FloatTensor([
self._generate_random_vector(vector_size),
self._generate_random_vector(vector_size),
self._generate_random_vector(vector_size)])
self.write_extra_embeddings(extra, params.save_loc)
else:
path = os.path.join(params.save_loc, 'extra-embeddings.npy')
extra = torch.load(path)
embeddings = torch.cat((extra, embeddings), 0)
print('Embeddings have shape {}'.format(embeddings.shape))
if normalize:
embeddings = utils.normalize_embeddings(embeddings)
nn_embedding = nn.Embedding(embeddings.shape[0],
embeddings.shape[1])
nn_embedding.weight.data.copy_(embeddings)
# Fix weights for training
nn_embedding.weight.requires_grad = False
return wd, nn_embedding
def read_corpus(self, filename, lowercase):
print('Reading data from %s' % filename)
# we are only interested in the actual sentences + gold label
# the corpus files has a few more things
useful_data = []
# the Multinli corpus has one JSON object per line
with open(filename, 'rb') as f:
for line in f:
line = line.decode('utf-8')
if lowercase:
line = line.lower()
data = json.loads(line)
if data['gold_label'] == '-':
# ignore items without a gold label
continue
sentence1_parse = data['sentence1_parse']
sentence2_parse = data['sentence2_parse']
label = data['gold_label']
tree1 = nltk.Tree.fromstring(sentence1_parse)
tree2 = nltk.Tree.fromstring(sentence2_parse)
tokens1 = tree1.leaves()
tokens2 = tree2.leaves()
t = (tokens1, tokens2, label)
useful_data.append(t)
return useful_data
def read_corpus_batched(self, filename, lowercase):
print('Reading data from %s' % filename)
# we are only interested in the actual sentences + gold label
# the corpus files has a few more things
useful_data = []
done = dict()
# the Multinli corpus has one JSON object per line
with open(filename, 'rb') as f:
for line in f:
line = line.decode('utf-8')
if lowercase:
line = line.lower()
data = json.loads(line)
if data['gold_label'] == '-':
# ignore items without a gold label
continue
prompt_id = data['promptid']
if prompt_id not in done:
done[prompt_id] = len(useful_data)
useful_data.append([])
sentence1_parse = data['sentence1_parse']
sentence2_parse = data['sentence2_parse']
label = data['gold_label']
tree1 = nltk.Tree.fromstring(sentence1_parse)
tree2 = nltk.Tree.fromstring(sentence2_parse)
tokens1 = tree1.leaves()
tokens2 = tree2.leaves()
t = (tokens1, tokens2, label)
useful_data[done[prompt_id]].append(t)
return useful_data
io = IO()
| [
"numpy.random.uniform",
"torchtext.vocab.GloVe",
"nltk.Tree.fromstring",
"json.loads",
"torch.nn.Embedding",
"torch.load",
"torch.cat",
"torch.save",
"collections.defaultdict",
"modules.Utils.utils.normalize_embeddings",
"os.path.join"
] | [((502, 536), 'numpy.random.uniform', 'np.random.uniform', (['(-0.1)', '(0.1)', 'size'], {}), '(-0.1, 0.1, size)\n', (519, 536), True, 'import numpy as np\n'), ((800, 845), 'os.path.join', 'os.path.join', (['dirname', '"""extra-embeddings.npy"""'], {}), "(dirname, 'extra-embeddings.npy')\n", (812, 845), False, 'import os\n'), ((854, 886), 'torch.save', 'torch.save', (['embeddings[:3]', 'path'], {}), '(embeddings[:3], path)\n', (864, 886), False, 'import torch\n'), ((974, 1022), 'torchtext.vocab.GloVe', 'vocab.GloVe', ([], {'name': '"""6B"""', 'dim': 'params.embedding_dim'}), "(name='6B', dim=params.embedding_dim)\n", (985, 1022), False, 'from torchtext import vocab\n'), ((1192, 1217), 'collections.defaultdict', 'defaultdict', (['int', 'mapping'], {}), '(int, mapping)\n', (1203, 1217), False, 'from collections import defaultdict\n'), ((1797, 1830), 'torch.cat', 'torch.cat', (['(extra, embeddings)', '(0)'], {}), '((extra, embeddings), 0)\n', (1806, 1830), False, 'import torch\n'), ((2009, 2063), 'torch.nn.Embedding', 'nn.Embedding', (['embeddings.shape[0]', 'embeddings.shape[1]'], {}), '(embeddings.shape[0], embeddings.shape[1])\n', (2021, 2063), False, 'from torch import nn\n'), ((1684, 1737), 'os.path.join', 'os.path.join', (['params.save_loc', '"""extra-embeddings.npy"""'], {}), "(params.save_loc, 'extra-embeddings.npy')\n", (1696, 1737), False, 'import os\n'), ((1758, 1774), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (1768, 1774), False, 'import torch\n'), ((1946, 1984), 'modules.Utils.utils.normalize_embeddings', 'utils.normalize_embeddings', (['embeddings'], {}), '(embeddings)\n', (1972, 1984), False, 'from modules.Utils import utils\n'), ((2776, 2792), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (2786, 2792), False, 'import json\n'), ((3109, 3146), 'nltk.Tree.fromstring', 'nltk.Tree.fromstring', (['sentence1_parse'], {}), '(sentence1_parse)\n', (3129, 3146), False, 'import nltk\n'), ((3171, 3208), 'nltk.Tree.fromstring', 'nltk.Tree.fromstring', (['sentence2_parse'], {}), '(sentence2_parse)\n', (3191, 3208), False, 'import nltk\n'), ((3938, 3954), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (3948, 3954), False, 'import json\n'), ((4457, 4494), 'nltk.Tree.fromstring', 'nltk.Tree.fromstring', (['sentence1_parse'], {}), '(sentence1_parse)\n', (4477, 4494), False, 'import nltk\n'), ((4519, 4556), 'nltk.Tree.fromstring', 'nltk.Tree.fromstring', (['sentence2_parse'], {}), '(sentence2_parse)\n', (4539, 4556), False, 'import nltk\n')] |
import numpy as np
import tempfile
from qtree.voronoi import ParticleVoronoiMesh
def test_voronoi():
np.random.seed(0x4d3d3d3)
input_npart = 1000
positions = np.random.normal(loc=0.5, scale=0.1, size=(input_npart, 2))
positions = np.clip(positions, 0, 1.0)
masses = np.ones(input_npart)
mesh = ParticleVoronoiMesh(positions, masses, [[0, 0], [1, 1]])
with tempfile.NamedTemporaryFile() as fp:
mesh.plot(fp.name)
| [
"tempfile.NamedTemporaryFile",
"numpy.random.seed",
"numpy.ones",
"numpy.clip",
"qtree.voronoi.ParticleVoronoiMesh",
"numpy.random.normal"
] | [((108, 132), 'numpy.random.seed', 'np.random.seed', (['(80991187)'], {}), '(80991187)\n', (122, 132), True, 'import numpy as np\n'), ((173, 232), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.5)', 'scale': '(0.1)', 'size': '(input_npart, 2)'}), '(loc=0.5, scale=0.1, size=(input_npart, 2))\n', (189, 232), True, 'import numpy as np\n'), ((249, 275), 'numpy.clip', 'np.clip', (['positions', '(0)', '(1.0)'], {}), '(positions, 0, 1.0)\n', (256, 275), True, 'import numpy as np\n'), ((290, 310), 'numpy.ones', 'np.ones', (['input_npart'], {}), '(input_npart)\n', (297, 310), True, 'import numpy as np\n'), ((323, 379), 'qtree.voronoi.ParticleVoronoiMesh', 'ParticleVoronoiMesh', (['positions', 'masses', '[[0, 0], [1, 1]]'], {}), '(positions, masses, [[0, 0], [1, 1]])\n', (342, 379), False, 'from qtree.voronoi import ParticleVoronoiMesh\n'), ((390, 419), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (417, 419), False, 'import tempfile\n')] |
# -*- coding: utf-8 -*-
# This file is part of RRMPG.
#
# RRMPG is free software with the aim to provide a playground for experiments
# with hydrological rainfall-runoff-models while achieving competitive
# performance results.
#
# You should have received a copy of the MIT License along with RRMPG. If not,
# see <https://opensource.org/licenses/MIT>
import unittest
import numpy as np
from rrmpg.models import ABCModel
from rrmpg.tools.monte_carlo import monte_carlo
class TestMonteCarlo(unittest.TestCase):
"""Test the monte carlo implementation."""
def setUp(self):
self.model = ABCModel()
self.rain = np.random.random(100)
unittest.TestCase.setUp(self)
def test_runs_for_correct_number(self):
num = 24
results = monte_carlo(self.model, num, prec=self.rain)
self.assertEqual(results['qsim'].shape[1], num)
| [
"rrmpg.tools.monte_carlo.monte_carlo",
"numpy.random.random",
"rrmpg.models.ABCModel",
"unittest.TestCase.setUp"
] | [((609, 619), 'rrmpg.models.ABCModel', 'ABCModel', ([], {}), '()\n', (617, 619), False, 'from rrmpg.models import ABCModel\n'), ((640, 661), 'numpy.random.random', 'np.random.random', (['(100)'], {}), '(100)\n', (656, 661), True, 'import numpy as np\n'), ((670, 699), 'unittest.TestCase.setUp', 'unittest.TestCase.setUp', (['self'], {}), '(self)\n', (693, 699), False, 'import unittest\n'), ((788, 832), 'rrmpg.tools.monte_carlo.monte_carlo', 'monte_carlo', (['self.model', 'num'], {'prec': 'self.rain'}), '(self.model, num, prec=self.rain)\n', (799, 832), False, 'from rrmpg.tools.monte_carlo import monte_carlo\n')] |
#!/usr/bin/env python3
"""This uses PyGame to visualize a COVID-19 outbreak in a population of 1000
people living relatively close and with a high rate of interaction. The
simulation is run until there are no more infectious people.
"""
import sys
from time import perf_counter
import pygame
import numpy as np
import infect_sim as infect
def step_sim(sim):
# Move the simulation one time step forward
for person in sim.pop.keys():
if sim.pop[person].alive:
sim.move(person)
conditions = [
sim.pop[person].infected, sim.pop[person].recovered
]
if conditions == [True, False]: # Person is infectious
sim.infect(person)
# Perform the clean up phase
sim.clean_up(remove_persons=False)
# Increment the time steps
sim.time_steps += 1
def run_viz(env_params):
"""Set up and run the simulation until there are no more infectious people.
"""
# Environment parameters that are used elsewhere for the visualization
env_dim = env_params['env_dim']
pop_size = env_params['pop_size']
initially_infected = env_params['initially_infected']
interaction_rate = env_params['interaction_rate']
# Instantiate the simulation environment
sim = infect.Environment(env_params)
# PYGAME VISUALIZATION
pygame.init()
# Define some visualization constants
TIME_DELAY = 250 # Milliseconds
CELL = 6
MARGIN = 1
SCREEN_DIM = env_dim * CELL + (MARGIN * env_dim + 1)
# RGB Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
OLIVE = (75, 150, 0)
BLUE = (0, 0, 255)
# Define screen size based on the env_dim, the cell size of the grid, and
# they margin size between cells
screen = pygame.display.set_mode((SCREEN_DIM, SCREEN_DIM))
running = True
while running:
start_time_step = perf_counter()
# Draw the current environment state
screen.fill(BLACK)
# Get a tuple object consisting of each coordinate in the environment
# that is part of a "mask" that represents the interaction rate of each
# infected person
mask_indices_set = []
for row, col in np.ndindex(sim.env.shape):
pygame.draw.rect(screen, WHITE,
[(MARGIN + CELL) * col + MARGIN,
(MARGIN + CELL) * row + MARGIN,
CELL,
CELL])
if sim.env[row, col] != np.Inf: # Cell is occupied by a person
person = sim.env[row, col]
r = sim.pop[person].interaction_rate
infectious = [sim.pop[person].alive,
sim.pop[person].infected,
sim.pop[person].recovered]
# If the person is infectious then get environment indices of
# their mask
if infectious == [True, True, False]:
y, x = np.ogrid[-col: env_dim - col, -row: env_dim - row]
mask = x*x + y*y <= r*r
mask_indices = np.where(mask == True)
mask_indices = [tuple(mask) for mask in mask_indices]
x_coordinates = mask_indices[1]
y_coordinates = mask_indices[0]
# Add their mask indices to the master list
for x, y in zip(x_coordinates, y_coordinates):
mask_indices_set.append((x, y))
# Draw in the masks
for coordinate in mask_indices_set:
row, col = coordinate[0], coordinate[1]
pygame.draw.rect(screen, OLIVE,
[(MARGIN + CELL) * col + MARGIN,
(MARGIN + CELL) * row + MARGIN,
CELL,
CELL])
# Draw in the people
for row, col in np.ndindex(sim.env.shape):
if sim.env[row, col] != np.Inf: # Cell is occupied by a person
person = sim.env[row, col]
infectious = [sim.pop[person].alive,
sim.pop[person].infected,
sim.pop[person].recovered]
# Change the color of the cell depending on the person's state
if infectious == [True, True, False]:
color = GREEN
elif sim.pop[person].recovered:
color = BLUE
elif not sim.pop[person].alive:
color = RED
else:
color = BLACK # Unaffected
# Fill in the cell's color
pygame.draw.rect(screen, color,
[(MARGIN + CELL) * col + MARGIN,
(MARGIN + CELL) * row + MARGIN,
CELL,
CELL])
step_sim(sim)
# Display the current environment state after a time delay
end_time_step = perf_counter()
run_time = (end_time_step - start_time_step) * 1000 # Milliseconds
delay = int(TIME_DELAY - run_time)
if run_time < TIME_DELAY:
pygame.time.delay(delay)
pygame.display.flip()
# Simulation is over when there are no more infectious persons
if sim.report['infectious'][-1] == 0:
sim.generate_plot() # Show summary stats
running = False
# Exit pygame without errors
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
pygame.quit()
sys.exit()
def main():
# Load environment parameters into a dict
env_params = {
'time_steps': 0, # Run the sim until there are no infectious people
'env_dim': 100,
'pop_size': 1000,
'initially_infected': 3,
'interaction_rate': 3,
'infection_rate': .4, # Percent likelihood of spreading the disease
'mortality_rate': .02, # Percent likelihood of dieing from the disease
'recovery_mean': 19, # Mean number of days it takes to recover
'death_sd': 4, # Standard deviation of days it takes to die
'asymptomatic_prob': 0.25, # Probability of being asymptomatic
'days_unitl_infectious': 2
}
run_viz(env_params)
if __name__ == '__main__':
main()
| [
"pygame.quit",
"numpy.ndindex",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.rect",
"infect_sim.Environment",
"time.perf_counter",
"pygame.init",
"pygame.display.flip",
"pygame.time.delay",
"numpy.where",
"sys.exit"
] | [((1280, 1310), 'infect_sim.Environment', 'infect.Environment', (['env_params'], {}), '(env_params)\n', (1298, 1310), True, 'import infect_sim as infect\n'), ((1343, 1356), 'pygame.init', 'pygame.init', ([], {}), '()\n', (1354, 1356), False, 'import pygame\n'), ((1813, 1862), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(SCREEN_DIM, SCREEN_DIM)'], {}), '((SCREEN_DIM, SCREEN_DIM))\n', (1836, 1862), False, 'import pygame\n'), ((5603, 5621), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (5619, 5621), False, 'import pygame\n'), ((1928, 1942), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (1940, 1942), False, 'from time import perf_counter\n'), ((2255, 2280), 'numpy.ndindex', 'np.ndindex', (['sim.env.shape'], {}), '(sim.env.shape)\n', (2265, 2280), True, 'import numpy as np\n'), ((3989, 4014), 'numpy.ndindex', 'np.ndindex', (['sim.env.shape'], {}), '(sim.env.shape)\n', (3999, 4014), True, 'import numpy as np\n'), ((5119, 5133), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (5131, 5133), False, 'from time import perf_counter\n'), ((5332, 5353), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (5351, 5353), False, 'import pygame\n'), ((2294, 2407), 'pygame.draw.rect', 'pygame.draw.rect', (['screen', 'WHITE', '[(MARGIN + CELL) * col + MARGIN, (MARGIN + CELL) * row + MARGIN, CELL, CELL]'], {}), '(screen, WHITE, [(MARGIN + CELL) * col + MARGIN, (MARGIN +\n CELL) * row + MARGIN, CELL, CELL])\n', (2310, 2407), False, 'import pygame\n'), ((3706, 3819), 'pygame.draw.rect', 'pygame.draw.rect', (['screen', 'OLIVE', '[(MARGIN + CELL) * col + MARGIN, (MARGIN + CELL) * row + MARGIN, CELL, CELL]'], {}), '(screen, OLIVE, [(MARGIN + CELL) * col + MARGIN, (MARGIN +\n CELL) * row + MARGIN, CELL, CELL])\n', (3722, 3819), False, 'import pygame\n'), ((5299, 5323), 'pygame.time.delay', 'pygame.time.delay', (['delay'], {}), '(delay)\n', (5316, 5323), False, 'import pygame\n'), ((5671, 5684), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (5682, 5684), False, 'import pygame\n'), ((5697, 5707), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5705, 5707), False, 'import sys\n'), ((4759, 4872), 'pygame.draw.rect', 'pygame.draw.rect', (['screen', 'color', '[(MARGIN + CELL) * col + MARGIN, (MARGIN + CELL) * row + MARGIN, CELL, CELL]'], {}), '(screen, color, [(MARGIN + CELL) * col + MARGIN, (MARGIN +\n CELL) * row + MARGIN, CELL, CELL])\n', (4775, 4872), False, 'import pygame\n'), ((3180, 3202), 'numpy.where', 'np.where', (['(mask == True)'], {}), '(mask == True)\n', (3188, 3202), True, 'import numpy as np\n')] |
import logging
import random
import numpy as np
import math
from argparse import ArgumentParser
from itertools import chain
from pprint import pformat
import warnings
import json
import torch
import torch.nn.functional as F
from transformers import Model2Model, BertTokenizer, BertConfig, BertJapaneseTokenizer
from train_id import SPECIAL_TOKENS, add_special_tokens_
from utils import get_dataset
import os
from metrics.eval_metrics import moses_multi_bleu
LOSS = torch.nn.CrossEntropyLoss(ignore_index=-1)
def build_input_from_segments(persona, history, reply, tokenizer, lang_id, special_map, lm_labels=False, with_eos=True):
""" Build a sequence of input from 3 segments: persona, history and last reply. """
bos, eos, persona_token, speaker1, speaker2 = [special_map[token] for token in SPECIAL_TOKENS[:5]]
if lang_id is None:
lang_id_token = 0
else:
lang_id_token = [special_map[lang_id]]
personality = []
for sent in persona:
personality+=[persona_token]+sent
sequence = [personality] + history #+ [reply + ([eos] if with_eos else [])]
sequence = [sequence[0]] + [[speaker2 if i % 2 else speaker1] + s for i, s in enumerate(sequence[1:])]
response = [bos] + reply + ([eos] if with_eos else [])
instance = {}
instance["input_ids"] = list(chain(*sequence))
instance["token_type_ids"] = [persona_token]*len(sequence[0]) + [speaker2 if i % 2 else speaker1 for i, s in enumerate(sequence[1:]) for _ in s]
instance["lm_labels"] = [-1] * len(response)
instance["lang_id"] = lang_id_token
if lm_labels:
instance["lm_labels"] = response
# print(tokenizer.decode(instance["lang_id"]))
# print(tokenizer.decode(instance["input_ids"]))
# print(tokenizer.decode(instance["token_type_ids"]) )
# print(tokenizer.decode(response))
return instance
def top_filtering(logits, top_k=0., top_p=0.9, threshold=-float('Inf'), filter_value=-float('Inf')):
""" Filter a distribution of logits using top-k, top-p (nucleus) and/or threshold filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k: <=0: no filtering, >0: keep only top k tokens with highest probability.
top_p: <=0.0: no filtering, >0.0: keep only a subset S of candidates, where S is the smallest subset
whose total probability mass is greater than or equal to the threshold top_p.
In practice, we select the highest probability tokens whose cumulative probability mass exceeds
the threshold top_p.
threshold: a minimal threshold to keep logits
"""
assert logits.dim() == 1 # Only work for batch size 1 for now - could update but it would obfuscate a bit the code
top_k = min(top_k, logits.size(-1))
if top_k > 0:
# Remove all tokens with a probability less than the last token in the top-k tokens
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = filter_value
if top_p > 0.0:
# Compute cumulative probabilities of sorted tokens
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probabilities = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probabilities > top_p
# Shift the indices to the right to keep also the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
# Back to unsorted indices and set them to -infinity
indices_to_remove = sorted_indices[sorted_indices_to_remove]
logits[indices_to_remove] = filter_value
indices_to_remove = logits < threshold
logits[indices_to_remove] = filter_value
return logits
def sample_sequence(personality, history, tokenizer, model, args, lang, special_map, current_output=None, ref = None, ):
special_tokens_ids = [special_map[token] for token in SPECIAL_TOKENS]
if current_output is None:
current_output = []
if args.test_lang in ["En", "Fr", "It", "Id", "Jp", "Ko", "Zh"]:
lang=None
for i in range(args.max_length):
instance = build_input_from_segments(personality, history, current_output, tokenizer, lang, special_map, lm_labels=True, with_eos=False)
input_ids = torch.tensor(instance["input_ids"], device=args.device).unsqueeze(0)
token_type_ids = torch.tensor(instance["token_type_ids"], device=args.device).unsqueeze(0)
encoder_mask = torch.tensor(len(instance["input_ids"])*[1], device=args.device).unsqueeze(0)
decoder_mask = torch.tensor(len(instance["lm_labels"])*[1], device=args.device).unsqueeze(0)
decoder_type_ids = torch.tensor(instance["lang_id"], device=args.device).unsqueeze(0)
#print(decoder_type_ids)
model_kwargs = {"encoder_token_type_ids":token_type_ids,"decoder_token_type_ids":decoder_type_ids, "encoder_attention_mask":encoder_mask, "decoder_attention_mask":decoder_mask}
decoder_input_ids = torch.tensor(instance["lm_labels"], device=args.device).unsqueeze(0)
logits, *_ = model(encoder_input_ids = input_ids, decoder_input_ids = decoder_input_ids, **model_kwargs)
if isinstance(logits, tuple): # for gpt2 and maybe others
logits = logits[0]
logits = logits[0, -1, :] / args.temperature
logits = top_filtering(logits, top_k=args.top_k, top_p=args.top_p)
probs = F.softmax(logits, dim=-1)
prev = torch.topk(probs, 1)[1] if args.no_sample else torch.multinomial(probs, 1)
if i < args.min_length and prev.item() in special_tokens_ids:
while prev.item() in special_tokens_ids:
if probs.max().item() == 1:
warnings.warn("Warning: model generating special token with probability 1.")
break # avoid infinitely looping over special token
prev = torch.multinomial(probs, num_samples=1)
if prev.item() in special_tokens_ids:
break
current_output.append(prev.item())
# compute PPL
instance = build_input_from_segments(personality, history, ref, tokenizer, lang, special_map, lm_labels=True, with_eos=True)
decoder_mask = torch.tensor(len(instance["lm_labels"])*[1], device=args.device).unsqueeze(0)
model_kwargs = {"encoder_token_type_ids":token_type_ids,"decoder_token_type_ids":decoder_type_ids, "encoder_attention_mask":encoder_mask, "decoder_attention_mask":decoder_mask}
decoder_input_ids = torch.tensor(instance["lm_labels"], device=args.device).unsqueeze(0)
logits, *_ = model(encoder_input_ids = input_ids, decoder_input_ids = decoder_input_ids, **model_kwargs)
lm_logits_flat_shifted = logits[..., :-1, :].contiguous().view(-1, logits.size(-1))
lm_labels_flat_shifted = decoder_input_ids[..., 1:].contiguous().view(-1)
loss = LOSS(lm_logits_flat_shifted, lm_labels_flat_shifted)
return current_output, loss.item()
def run():
parser = ArgumentParser()
parser.add_argument("--dataset_path", type=str, default="", help="Path or url of the dataset. If empty download from S3.")
parser.add_argument("--dataset_cache", type=str, default='./dataset_cache', help="Path or url of the dataset cache")
parser.add_argument("--model", type=str, default="multi-bert", help="Model type") # anything besides gpt2 will load openai-gpt
parser.add_argument("--model_checkpoint", type=str, default="", help="Path, url or short name of the model")
parser.add_argument("--max_turns", type=int, default=3, help="Number of previous utterances to keep in history")
parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu", help="Device (cuda or cpu)")
parser.add_argument("--no_sample", action='store_true', help="Set to use greedy decoding instead of sampling")
parser.add_argument("--max_length", type=int, default=20, help="Maximum length of the output utterances")
parser.add_argument("--min_length", type=int, default=1, help="Minimum length of the output utterances")
parser.add_argument("--seed", type=int, default=0, help="Seed")
parser.add_argument("--temperature", type=int, default=0.7, help="Sampling softmax temperature")
parser.add_argument("--top_k", type=int, default=0, help="Filter top-k tokens before sampling (<=0: no filtering)")
parser.add_argument("--top_p", type=float, default=0.9, help="Nucleus filtering (top-p) before sampling (<=0.0: no filtering)")
parser.add_argument("--test_lang", type=str, default="", help="test monolingual model")
parser.add_argument("--no_lang_id", action='store_true')
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__file__)
logger.info(pformat(args))
if args.seed != 0:
random.seed(args.seed)
torch.random.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
logger.info("Get pretrained model and tokenizer")
tokenizer = BertTokenizer.from_pretrained(args.model_checkpoint)
if args.test_lang == "Jp":
tokenizer = BertJapaneseTokenizer.from_pretrained(args.model_checkpoint)
bertconfig = BertConfig.from_pretrained(args.model_checkpoint)
bertconfig.is_decoder=True
model = Model2Model.from_pretrained(args.model_checkpoint, **{"decoder_config":bertconfig})
with open(args.model_checkpoint+"/added_tokens.json", encoding="utf-8") as f:
special_map = json.load(f)
model.load_state_dict(torch.load(args.model_checkpoint+"/pytorch_model.bin"))
model.to(args.device)
model.eval()
personachat = get_dataset(tokenizer, args.dataset_path, args.dataset_cache, args.test_lang)
persona_text = {}
context_text = {}
output_text = {}
ref_text = {}
ppl = {}
BLEU_score = {}
if args.test_lang in ["En", "Fr", "It", "Id", "Jp", "Ko", "Zh"]:
logdir = args.test_lang+"_bert2bert/"
else:
logdir = "multilingual_bert2bert/"
for lang, dials in personachat["test"].items():
if args.test_lang in ["En", "Fr", "It", "Id", "Jp", "Ko", "Zh"]:
if lang!=args.test_lang:
continue
persona_text[lang] = []
context_text[lang] = []
output_text[lang] = []
ref_text[lang] = []
loss_list = []
for dial in dials: #dial: {"persona":[], "history":[], "response":str}
with torch.no_grad():
out_ids, loss = sample_sequence(dial["persona"], dial["history"][-args.max_turns:], tokenizer, model, args, "<{}>".format(lang.lower()), special_map, ref = dial["response"])
output_text[lang].append(tokenizer.decode(out_ids, skip_special_tokens=True))
# print(tokenizer.decode(dial["history"][-1]))
# print(output_text[lang][-1])
# print("-")
ref_text[lang].append(tokenizer.decode(dial["response"], skip_special_tokens=True))
context_text[lang].append([tokenizer.decode(turn, skip_special_tokens=True) for turn in dial["history"]])
persona_text[lang].append([tokenizer.decode(sent, skip_special_tokens=True) for sent in dial["persona"]])
loss_list.append(loss)
ppl[lang] = math.exp(np.mean(loss_list))
print("{} PPL:{}".format(lang, ppl[lang]))
if not os.path.exists("results/"+logdir):
os.makedirs("results/"+logdir)
with open("results/"+logdir+lang+"_output.txt", 'w', encoding='utf-8') as f:
for line in output_text[lang]:
f.write(line)
f.write('\n')
with open("results/"+logdir+lang+"_ref.txt", 'w', encoding='utf-8') as f:
for line in ref_text[lang]:
f.write(line)
f.write('\n')
print("Computing BLEU for {}".format(lang))
BLEU = moses_multi_bleu(np.array(output_text[lang]),np.array(ref_text[lang]))
print("BLEU:{}".format(BLEU))
BLEU_score[lang] = BLEU
with open("results/"+logdir+lang+"_all.txt", 'w', encoding='utf-8') as f:
for i in range(len(ref_text[lang])):
f.write("=====================================================\n")
f.write("Persona:\n")
for sent in persona_text[lang][i]:
f.write("".join(sent.split()) if lang in ["jp", "zh"] else sent )
f.write('\n')
f.write("History:\n")
for sent in context_text[lang][i]:
f.write("".join(sent.split()) if lang in ["jp", "zh"] else sent)
f.write('\n')
f.write("Response: ")
f.write("".join(output_text[lang][i].split()) if lang in ["jp", "zh"] else output_text[lang][i])
f.write('\n')
f.write("Ref: ")
f.write("".join(ref_text[lang][i].split()) if lang in ["jp", "zh"] else ref_text[lang][i])
f.write('\n')
with open("results/"+logdir+"BLEU_score.txt", "w", encoding='utf-8') as f:
for language, score in BLEU_score.items():
f.write("{}\t PPL:{}, BLEU:{}\n".format(language, ppl[language],score))
if __name__ == "__main__":
run() | [
"pprint.pformat",
"torch.multinomial",
"argparse.ArgumentParser",
"numpy.mean",
"torch.no_grad",
"utils.get_dataset",
"transformers.BertJapaneseTokenizer.from_pretrained",
"torch.load",
"os.path.exists",
"random.seed",
"itertools.chain",
"torch.topk",
"torch.random.manual_seed",
"torch.cud... | [((467, 509), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'ignore_index': '(-1)'}), '(ignore_index=-1)\n', (492, 509), False, 'import torch\n'), ((7189, 7205), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (7203, 7205), False, 'from argparse import ArgumentParser\n'), ((8892, 8931), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (8911, 8931), False, 'import logging\n'), ((8945, 8972), 'logging.getLogger', 'logging.getLogger', (['__file__'], {}), '(__file__)\n', (8962, 8972), False, 'import logging\n'), ((9208, 9260), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['args.model_checkpoint'], {}), '(args.model_checkpoint)\n', (9237, 9260), False, 'from transformers import Model2Model, BertTokenizer, BertConfig, BertJapaneseTokenizer\n'), ((9390, 9439), 'transformers.BertConfig.from_pretrained', 'BertConfig.from_pretrained', (['args.model_checkpoint'], {}), '(args.model_checkpoint)\n', (9416, 9439), False, 'from transformers import Model2Model, BertTokenizer, BertConfig, BertJapaneseTokenizer\n'), ((9483, 9571), 'transformers.Model2Model.from_pretrained', 'Model2Model.from_pretrained', (['args.model_checkpoint'], {}), "(args.model_checkpoint, **{'decoder_config':\n bertconfig})\n", (9510, 9571), False, 'from transformers import Model2Model, BertTokenizer, BertConfig, BertJapaneseTokenizer\n'), ((9834, 9911), 'utils.get_dataset', 'get_dataset', (['tokenizer', 'args.dataset_path', 'args.dataset_cache', 'args.test_lang'], {}), '(tokenizer, args.dataset_path, args.dataset_cache, args.test_lang)\n', (9845, 9911), False, 'from utils import get_dataset\n'), ((1322, 1338), 'itertools.chain', 'chain', (['*sequence'], {}), '(*sequence)\n', (1327, 1338), False, 'from itertools import chain\n'), ((3173, 3208), 'torch.sort', 'torch.sort', (['logits'], {'descending': '(True)'}), '(logits, descending=True)\n', (3183, 3208), False, 'import torch\n'), ((5642, 5667), 'torch.nn.functional.softmax', 'F.softmax', (['logits'], {'dim': '(-1)'}), '(logits, dim=-1)\n', (5651, 5667), True, 'import torch.nn.functional as F\n'), ((8989, 9002), 'pprint.pformat', 'pformat', (['args'], {}), '(args)\n', (8996, 9002), False, 'from pprint import pformat\n'), ((9033, 9055), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (9044, 9055), False, 'import random\n'), ((9061, 9096), 'torch.random.manual_seed', 'torch.random.manual_seed', (['args.seed'], {}), '(args.seed)\n', (9085, 9096), False, 'import torch\n'), ((9102, 9135), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['args.seed'], {}), '(args.seed)\n', (9124, 9135), False, 'import torch\n'), ((9312, 9372), 'transformers.BertJapaneseTokenizer.from_pretrained', 'BertJapaneseTokenizer.from_pretrained', (['args.model_checkpoint'], {}), '(args.model_checkpoint)\n', (9349, 9372), False, 'from transformers import Model2Model, BertTokenizer, BertConfig, BertJapaneseTokenizer\n'), ((9672, 9684), 'json.load', 'json.load', (['f'], {}), '(f)\n', (9681, 9684), False, 'import json\n'), ((9712, 9768), 'torch.load', 'torch.load', (["(args.model_checkpoint + '/pytorch_model.bin')"], {}), "(args.model_checkpoint + '/pytorch_model.bin')\n", (9722, 9768), False, 'import torch\n'), ((3257, 3289), 'torch.nn.functional.softmax', 'F.softmax', (['sorted_logits'], {'dim': '(-1)'}), '(sorted_logits, dim=-1)\n', (3266, 3289), True, 'import torch.nn.functional as F\n'), ((5731, 5758), 'torch.multinomial', 'torch.multinomial', (['probs', '(1)'], {}), '(probs, 1)\n', (5748, 5758), False, 'import torch\n'), ((6717, 6772), 'torch.tensor', 'torch.tensor', (["instance['lm_labels']"], {'device': 'args.device'}), "(instance['lm_labels'], device=args.device)\n", (6729, 6772), False, 'import torch\n'), ((11477, 11495), 'numpy.mean', 'np.mean', (['loss_list'], {}), '(loss_list)\n', (11484, 11495), True, 'import numpy as np\n'), ((11563, 11598), 'os.path.exists', 'os.path.exists', (["('results/' + logdir)"], {}), "('results/' + logdir)\n", (11577, 11598), False, 'import os\n'), ((11610, 11642), 'os.makedirs', 'os.makedirs', (["('results/' + logdir)"], {}), "('results/' + logdir)\n", (11621, 11642), False, 'import os\n'), ((12096, 12123), 'numpy.array', 'np.array', (['output_text[lang]'], {}), '(output_text[lang])\n', (12104, 12123), True, 'import numpy as np\n'), ((12124, 12148), 'numpy.array', 'np.array', (['ref_text[lang]'], {}), '(ref_text[lang])\n', (12132, 12148), True, 'import numpy as np\n'), ((4497, 4552), 'torch.tensor', 'torch.tensor', (["instance['input_ids']"], {'device': 'args.device'}), "(instance['input_ids'], device=args.device)\n", (4509, 4552), False, 'import torch\n'), ((4591, 4651), 'torch.tensor', 'torch.tensor', (["instance['token_type_ids']"], {'device': 'args.device'}), "(instance['token_type_ids'], device=args.device)\n", (4603, 4651), False, 'import torch\n'), ((4894, 4947), 'torch.tensor', 'torch.tensor', (["instance['lang_id']"], {'device': 'args.device'}), "(instance['lang_id'], device=args.device)\n", (4906, 4947), False, 'import torch\n'), ((5208, 5263), 'torch.tensor', 'torch.tensor', (["instance['lm_labels']"], {'device': 'args.device'}), "(instance['lm_labels'], device=args.device)\n", (5220, 5263), False, 'import torch\n'), ((5684, 5704), 'torch.topk', 'torch.topk', (['probs', '(1)'], {}), '(probs, 1)\n', (5694, 5704), False, 'import torch\n'), ((6119, 6158), 'torch.multinomial', 'torch.multinomial', (['probs'], {'num_samples': '(1)'}), '(probs, num_samples=1)\n', (6136, 6158), False, 'import torch\n'), ((7880, 7905), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7903, 7905), False, 'import torch\n'), ((10625, 10640), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10638, 10640), False, 'import torch\n'), ((2959, 2984), 'torch.topk', 'torch.topk', (['logits', 'top_k'], {}), '(logits, top_k)\n', (2969, 2984), False, 'import torch\n'), ((5946, 6022), 'warnings.warn', 'warnings.warn', (['"""Warning: model generating special token with probability 1."""'], {}), "('Warning: model generating special token with probability 1.')\n", (5959, 6022), False, 'import warnings\n')] |
"""
This module is designed to generate trials for our task with the
correct statistics
Example usage:
>>>> trials = Trials(prob_cp=0.8, num_trials=204, marginal_tolerance=0.02)
>>>> trials.attempt_number
>>>> trials.save_to_csv('/foo/bar.csv') # a .json file gets created for meta data
>>>> reloaded_trials = Trials(from_file='/foo/bar.csv') # also loads meta data from .json file
"""
import numpy as np
import pandas as pd
import json
import hashlib
ALLOWED_PROB_CP = {0, 0.2, 0.5, 0.8} # overall probability of a change-point trial
CP_TIME = 200 # in msec
MARGINALS_TEMPLATE = {
'coh': {0: 0, 'th': 0, 100: 0},
'vd': {100: 0, 200: 0, 300: 0, 400: 0},
'dir': {'left': 0, 'right': 0},
'cp': {True: 0, False: 0}
}
def check_extension(f, extension):
"""
check that filename has the given extension
:param f: (str) filename
:param extension: (str) extension with or without the dot. So 'csv', '.csv', 'json', '.json' are all valid
:return: asserts that string ends with proper extension
"""
if extension[0] == '.':
full_extension = extension
else:
full_extension = '.' + extension
assert f[-len(extension):] == extension, f'data filename {f} does not have a {full_extension} extension'
def standard_meta_filename(filename):
"""
utility to quickly define the filename for the metadata, given the filename for the data
:param filename: (str) path to data file
:return: (str) path to metadata file
"""
check_extension(filename, 'csv')
return filename[:-4] + '_metadata.json'
def md5(fname):
"""
function taken from here
https://stackoverflow.com/a/3431838
:param fname: filename
:return: string of hexadecimal number
"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def validate_marginal_keys(marg_type, marg_dict):
"""
asserts validity of keys of marg_dict
:param marg_type: (str) one of the keys from marginals_template defined inside function
:param marg_dict: (dict) dict representing the marginals for a single independent variable
:return: None
"""
assert set(MARGINALS_TEMPLATE[marg_type].keys()) == set(marg_dict.keys())
def validate_marginal_values(marg_dict, precision=1 / 10000000):
"""
checks the marginals sum to 1, up to some precision
:param marg_dict: (dict) dict representing the marginals for a single independent variable
:param precision: positive number under which any number is assimilated with 0
:return: None
"""
assert abs(sum(marg_dict.values()) - 1) < precision
def validate_marginal(marg_type, marg_dict):
"""
convenience function which validates keys and values of a marginals dict with default kwargs
:param marg_type: (str) one of the keys from marginals_template defined inside function
:param marg_dict: (dict) dict representing the marginals for a single independent variable
:return:
"""
validate_marginal_keys(marg_type, marg_dict)
validate_marginal_values(marg_dict)
def get_marginals(df):
"""
computes marginal distributions of all independent variables
:param df: dataframe of trials as returned by self.get_n_trials()
:return: dict with same format than MARGINALS_TEMPLATE, but empirical probs as values
"""
emp_marginals = {
'coh': {0: 0, 'th': 0, 100: 0},
'vd': {100: 0, 200: 0, 300: 0, 400: 0},
'dir': {'left': 0, 'right': 0},
'cp': {True: 0, False: 0}}
assert set(emp_marginals.keys()) == set(MARGINALS_TEMPLATE.keys())
tot_trials = len(df)
for indep_var in emp_marginals.keys():
for k in emp_marginals[indep_var].keys():
emp_marginals[indep_var][k] = len(df[df[indep_var] == k]) / tot_trials
validate_marginal(indep_var, emp_marginals[indep_var])
return emp_marginals
class Trials:
"""
class to create data frames of trials
Note, this class may be instantiated in two ways, controlled by the from_file kwarg to the __init__ method.
These ways result in a slightly distinct attribute list for this class. What should always be true, is that any
attribute appearing when the object is 'loaded from file' should also exist when the object is 'generated'.
We list below the attributes in these two cases, as of 03 June 2019
generated:
attempt_number
combinations
cond_prob_cp
csv_filename
csv_md5
empirical_marginals
loaded_from_file
marginal_tolerance
num_trials
prob_cp
seed
theoretical_marginals
trial_data
loaded:
cond_prob_cp
csv_filename
csv_md5
empirical_marginals
loaded_from_file
marginal_tolerance
num_trials
prob_cp
seed
theoretical_marginals
trial_data
"""
def __init__(self,
prob_cp=0,
num_trials=204,
seed=1,
coh_marginals={0: .4, 'th': .5, 100: .1},
vd_marginals={100: .1, 200: .1, 300: .4, 400: .4},
dir_marginals={'left': 0.5, 'right': 0.5},
max_attempts=10000,
marginal_tolerance=0.05,
from_file=None):
"""
:param prob_cp: theoretical proba of a CP trials over all trials
:param num_trials: number of trials in the data attached to object
:param seed: seed used to generate the data
:param coh_marginals: marginal probabilities for coherence values, across all trials
:param vd_marginals: marginal probabilities for viewing duration values, across all trials
:param dir_marginals: marginal probabilities for direction values, across all trials
:param max_attempts: max number of iterations to do to try to generate trials with correct statistics
:param marginal_tolerance: tolerance in the empirical marginals of the generated trials
:param from_file: filename to load data from. If None, data is randomly generated. If a filename is provided,
it should have a .csv extension and a corresponding metadata file with name equal to standard_
meta_filename(filename) should exist. Note that if data and meta_data are loaded from files,
all other kwargs provided to __init__ will be overriden by self._load_from_file()
"""
if from_file is None:
self.loaded_from_file = False
assert 0 < marginal_tolerance < 1
self.marginal_tolerance = marginal_tolerance
# for reproducibility
assert isinstance(seed, int)
self.seed = seed
np.random.seed(self.seed)
# validate core marginals
validate_marginal('coh', coh_marginals)
validate_marginal('vd', vd_marginals)
validate_marginal('dir', dir_marginals)
# validate prob_cp and its corresponding marginal
assert prob_cp in ALLOWED_PROB_CP
self.prob_cp = prob_cp
cp_marginals = {False: 1 - self.prob_cp, True: self.prob_cp}
validate_marginal('cp', cp_marginals)
# compute cond_prob_cp (i.e. the probability of a CP, given that it is a long trial)
prob_long_trial = 0
for k, v in vd_marginals.items():
if k > CP_TIME:
prob_long_trial += v
cond_prob_cp = self.prob_cp / prob_long_trial
assert 0 <= cond_prob_cp <= 1
self.cond_prob_cp = cond_prob_cp # probability of a CP, given that it is a long trial
self.theoretical_marginals = {
'coh': coh_marginals,
'vd': vd_marginals,
'dir': dir_marginals,
'cp': cp_marginals
}
assert set(self.theoretical_marginals.keys()) == set(MARGINALS_TEMPLATE.keys())
"""
the following attribute will be set to an actual data frame if generation succeeds with self.check_conditions()
"""
self.empirical_marginals = None
# build all combinations of independent variables, each comb will correspond to a trial
self.combinations = {} # dict where the values are the joint probabilities
for dir_k, dir_val in self.theoretical_marginals['dir'].items():
for coh_k, coh_val in self.theoretical_marginals['coh'].items():
for vd_k, vd_val in self.theoretical_marginals['vd'].items():
self.combinations[(coh_k, vd_k, dir_k)] = coh_val * vd_val * dir_val
attempt = 0
assert attempt < max_attempts
try_again = True
while attempt < max_attempts and try_again:
trial_df = self.get_n_trials(num_trials)
attempt += 1
"""
the following line is important because 'coh' column might be interpreted as int if no 'th' value
appears, and this produces a TypeError when filtering against the string 'th'
"""
trial_df.coh = trial_df.coh.astype('category')
# try again unless conditions are met
try_again = not self.check_conditions(trial_df)
if try_again:
print(f'after {attempt} attempts, no trial set met the conditions\n'
f'trial generation failed. You may try again with another seed,\n'
f'or increase the max_attempts argument')
self.trial_data = None # generation failed
self.num_trials = 0
else:
self.trial_data = trial_df
self.num_trials = len(trial_df)
self.attempt_number = attempt
self.csv_md5 = None
self.csv_filename = None
else:
self._load_from_file(from_file)
@staticmethod
def load_meta_data(filename):
"""
load metadata about trials from file
:param filename: (str) filename of either the trials data in csv format or its corresponding metadata in json
format. If filename with .csv extension is provided, standard_meta_filename() is invoked
:return: (dict) metadata
"""
try:
check_extension(filename, 'csv')
meta_filename = standard_meta_filename(filename)
except AssertionError:
try:
check_extension(filename, 'json')
meta_filename = filename
except AssertionError:
print(f'file {filename} has neither .csv nor .json extension')
raise ValueError
with open(meta_filename, 'r') as fp:
meta_data = json.load(fp)
return meta_data
@staticmethod
def md5check_from_metadata(csv_filename, meta_filename=None):
"""
checks whether the data in the csv file corresponds to the MD5 checksum stored in the metadata file
:param csv_filename: (str)
:param meta_filename: (str)
:return: simply asserts equality of checksums
"""
if meta_filename is None:
meta_filename = standard_meta_filename(csv_filename)
assert Trials.load_meta_data(meta_filename)['csv_md5'] == md5(csv_filename), 'MD5 check failed!'
print('MD5 verified!')
def _load_from_file(self, fname, meta_file=None):
"""
load full object from .csv file and its corresponding metadata file
:param fname: (str) path to csv file
:param meta_file: (str or None) either path to metadatafile or None (default).
If None, standard_meta_filename() is called
:return: sets many attributes
"""
if meta_file is None:
meta_file = standard_meta_filename(fname)
Trials.md5check_from_metadata(fname, meta_filename=meta_file)
meta_data = Trials.load_meta_data(meta_file)
# load data into pandas.DataFrame and attach it as attribute
self.trial_data = pd.read_csv(fname)
# set key-value pairs from metadata as attributes
for k, v in meta_data.items():
setattr(self, k, v)
self.loaded_from_file = True
def get_n_trials(self, n):
rows = [] # will be a list of dicts, where each dict is a pandas.DataFrame row
for trial in range(n):
comb_keys = list(self.combinations.keys())
comb_number = np.random.choice(len(comb_keys), p=list(self.combinations.values()))
comb = comb_keys[comb_number]
# this is a CP trial only if VD > 200 and biased coin flip turns out HEADS
is_cp = comb[1] > CP_TIME and np.random.random() < self.cond_prob_cp
rows.append({'coh': comb[0], 'vd': comb[1], 'dir': comb[2], 'cp': is_cp})
trials_dataframe = pd.DataFrame(rows)
return trials_dataframe
def check_conditions(self, df, append_marginals=True):
"""
we want at least five trials per Coh-VD pairs
we don't want the empirical marginals to deviate from the theoretical ones by more than 5%
"""
num_cohvd_pairs = np.sum(df.duplicated(subset=['coh', 'vd'], keep=False))
if num_cohvd_pairs < 5:
return False
emp_marginals = get_marginals(df)
for indep_var in emp_marginals.keys():
for key in emp_marginals[indep_var].keys():
error = abs(emp_marginals[indep_var][key] - self.theoretical_marginals[indep_var][key])
if error > self.marginal_tolerance:
return False
if append_marginals:
self.empirical_marginals = emp_marginals
return True
def save_to_csv(self, filename, with_meta_data=True):
if self.trial_data is None:
print('No data to write')
else:
check_extension(filename, 'csv')
self.trial_data.to_csv(filename, index=False)
print(f"file {filename} created")
if with_meta_data:
meta_filename = standard_meta_filename(filename)
meta_dict = {
'seed': self.seed,
'num_trials': self.num_trials,
'prob_cp': self.prob_cp,
'cond_prob_cp': self.cond_prob_cp,
'theoretical_marginals': self.theoretical_marginals,
'empirical_marginals': self.empirical_marginals,
'marginal_tolerance': self.marginal_tolerance,
'csv_filename': filename,
'csv_md5': md5(filename)
}
with open(meta_filename, 'w') as fp:
json.dump(meta_dict, fp, indent=4)
print(f"medatadata file {meta_filename} created")
def count_conditions(self, ind_vars):
# todo: to count number of trials for a given combination of independent variables values
pass
if __name__ == '__main__':
"""
todo: creates N blocks of trials per prob_cp value, gives standardized names to files
"""
marg_tol = 0.01 # max deviation allowed between theoretical and empirical marginal probabilities
all_vals = list(ALLOWED_PROB_CP - {0})
# number of blocks in total for the dual-report task
num_dual_report_blocks = 9
# number of blocks to enforce for each prob_cp value (other than 0)
# ensure the latter divides the former
assert np.mod(num_dual_report_blocks, len(all_vals)) == 0
num_blocks_single_prob_cp = num_dual_report_blocks / len(all_vals)
def gen_rand_prob_cp_seq(cp_vals, tot_num_blocks):
"""
Generates a random sequence of prob_cp values to assign to each block.
In effect, samples a path from a len(cp_vals)-state Discrete Time Markov Chain
where the prob of transitioning from one state to itself is 0 for all states,
and the probability of transitioning from one state to any other state is uniform.
:param cp_vals: list of possible prob_cp values
:param tot_num_blocks: total number of blocks
:return: list of prob_cp values
"""
# build random ordering of prob_cp across blocks
last_idx = np.random.randint(3) # draws a number at random in the set {0, 1, 2}
num_vals = len(cp_vals)
val_idxs = {i for i in range(num_vals)}
prob_list = [cp_vals[last_idx]]
for r in range(tot_num_blocks - 1):
new_idxs = list(val_idxs - {last_idx}) # update allowed indices for this block (enforce a transition)
last_idx = new_idxs[np.random.randint(num_vals - 1)] # pick one of the other two indices at random
prob_list.append(all_vals[last_idx])
return prob_list
def validate_prob_cp_seq(seq, num_blocks, num_blocks_seq, cp_vals):
assert len(seq) == num_blocks
for prob_cp in cp_vals:
cc = 0 # counter
for s in seq:
if s == prob_cp:
cc += 1
if cc != num_blocks_seq:
return False
return True
prob_cp_list = [0 for _ in range(num_dual_report_blocks)]
maxout = 1000 # total number of iterations allowed for the following while loop
counter = 0
while not validate_prob_cp_seq(prob_cp_list, num_dual_report_blocks, num_blocks_single_prob_cp, all_vals):
prob_cp_list = gen_rand_prob_cp_seq(all_vals, num_dual_report_blocks)
counter += 1
# print('all_vals', all_vals)
# print('num_dual_report_blocks', num_dual_report_blocks)
# print('prob_cp_list', prob_cp_list)
# print('counter in while loop', counter)
if counter == maxout:
print(f"after {counter} attempts, not proper prob_cp list was reached")
break
else:
print(f'prob cp list for dual-report blocks found after {counter} attempts')
print(prob_cp_list)
dual_report_start_index = 3
block_length = 250 # number of trials to use for each block
filenames = ['Tut1.csv', 'Tut2.csv', 'Block2.csv', 'Tut3.csv']
for idx in range(num_dual_report_blocks):
filenames.append('Block' + str(idx + dual_report_start_index) + '.csv')
count = 0
dual_report_block_count = 0
for file in filenames:
count += 1
# todo: deal with tutorials
if file[:3] == 'Tut':
pass
# deal with blocks
if file == 'Block2.csv': # Block2 is the standard dots task
t = Trials(prob_cp=0, num_trials=block_length, seed=count, marginal_tolerance=marg_tol)
t.save_to_csv(file)
elif file[:5] == 'Block': # the other ones are dual-report blocks
t = Trials(prob_cp=prob_cp_list[dual_report_block_count], num_trials=block_length, seed=count,
marginal_tolerance=marg_tol)
t.save_to_csv(file)
dual_report_block_count += 1
| [
"pandas.DataFrame",
"json.dump",
"hashlib.md5",
"numpy.random.seed",
"json.load",
"pandas.read_csv",
"numpy.random.randint",
"numpy.random.random"
] | [((1772, 1785), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (1783, 1785), False, 'import hashlib\n'), ((12344, 12362), 'pandas.read_csv', 'pd.read_csv', (['fname'], {}), '(fname)\n', (12355, 12362), True, 'import pandas as pd\n'), ((13158, 13176), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {}), '(rows)\n', (13170, 13176), True, 'import pandas as pd\n'), ((16550, 16570), 'numpy.random.randint', 'np.random.randint', (['(3)'], {}), '(3)\n', (16567, 16570), True, 'import numpy as np\n'), ((6901, 6926), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (6915, 6926), True, 'import numpy as np\n'), ((11030, 11043), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (11039, 11043), False, 'import json\n'), ((16936, 16967), 'numpy.random.randint', 'np.random.randint', (['(num_vals - 1)'], {}), '(num_vals - 1)\n', (16953, 16967), True, 'import numpy as np\n'), ((13004, 13022), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (13020, 13022), True, 'import numpy as np\n'), ((15030, 15064), 'json.dump', 'json.dump', (['meta_dict', 'fp'], {'indent': '(4)'}), '(meta_dict, fp, indent=4)\n', (15039, 15064), False, 'import json\n')] |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# TOOLBOX.ELLIPSE
# <NAME> [<EMAIL>]
# -----------------------------------------------------------------------------
from __future__ import division, print_function
import numpy as np
def ellipse(a, b, xc=0., yc=0., rot=0., n=101):
"""
Program calculates the x and y coordinates of an ellipse.
INPUTS
a : semi-major axis length
b : semi-minor axis length
OPTIONS
xc : x-coordinate of the centre (default: 0.)
yc : y-coordinate of the centre (default: 0.)
rot : rotation angle of the major axis measured counterclockwise from
the x-axis [radians] (default: 0. = x-axis)
n : number of points to generate (default: 101)
"""
# generate eccentric anomaly values
ea = np.linspace(0., 2.*np.pi, n)
# x and y coordinates
x = a*np.cos(ea)*np.cos(rot) - b*np.sin(ea)*np.sin(rot) + xc
y = a*np.cos(ea)*np.sin(rot) + b*np.sin(ea)*np.cos(rot) + yc
return x, y
| [
"numpy.sin",
"numpy.cos",
"numpy.linspace"
] | [((867, 899), 'numpy.linspace', 'np.linspace', (['(0.0)', '(2.0 * np.pi)', 'n'], {}), '(0.0, 2.0 * np.pi, n)\n', (878, 899), True, 'import numpy as np\n'), ((948, 959), 'numpy.cos', 'np.cos', (['rot'], {}), '(rot)\n', (954, 959), True, 'import numpy as np\n'), ((975, 986), 'numpy.sin', 'np.sin', (['rot'], {}), '(rot)\n', (981, 986), True, 'import numpy as np\n'), ((1013, 1024), 'numpy.sin', 'np.sin', (['rot'], {}), '(rot)\n', (1019, 1024), True, 'import numpy as np\n'), ((1040, 1051), 'numpy.cos', 'np.cos', (['rot'], {}), '(rot)\n', (1046, 1051), True, 'import numpy as np\n'), ((937, 947), 'numpy.cos', 'np.cos', (['ea'], {}), '(ea)\n', (943, 947), True, 'import numpy as np\n'), ((964, 974), 'numpy.sin', 'np.sin', (['ea'], {}), '(ea)\n', (970, 974), True, 'import numpy as np\n'), ((1002, 1012), 'numpy.cos', 'np.cos', (['ea'], {}), '(ea)\n', (1008, 1012), True, 'import numpy as np\n'), ((1029, 1039), 'numpy.sin', 'np.sin', (['ea'], {}), '(ea)\n', (1035, 1039), True, 'import numpy as np\n')] |
import math as m
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from collections import Counter, namedtuple
import scipy as sp
import numpy as np
import regex
def create_clusters(tweetsSrs):
freqcutoff = int(m.log(len(tweetsSrs))/2)
word_vectorizer = TfidfVectorizer(ngram_range=(1, 2), lowercase=False, norm='l2', min_df=freqcutoff, token_pattern=r"\b\w+\b|[\U00010000-\U0010ffff]")
text_vectors = word_vectorizer.fit_transform(tweetsSrs)
doc_feat_mtrx = text_vectors
n_clust = int(m.sqrt(len(tweetsSrs)))
n_initt = int(m.log10(len(tweetsSrs)))
km = KMeans(n_clusters=n_clust, init='k-means++', max_iter=1000, n_init=n_initt) # , n_jobs=16
km.fit(doc_feat_mtrx)
return km, doc_feat_mtrx, word_vectorizer
def get_cluster_sizes(kmeans_result,doclist):
clust_len_cntr = Counter()
for l in set(kmeans_result.labels_):
clust_len_cntr[str(l)] = len(doclist[np.where(kmeans_result.labels_ == l)])
return clust_len_cntr
def get_candidate_clusters(clusters, doc_feat_mtrx, word_vectorizer, tweetsDF, tok_result_col, min_dist_thres, max_dist_thres, printsize=True, selection=True):
cluster_str_list = []
Cluster = namedtuple('Cluster', ['cno', 'cstr','tw_ids'])
clustersizes = get_cluster_sizes(clusters, tweetsDF[tok_result_col].values)
for cn, csize in clustersizes.most_common():#range(args.ksize):#clustersizes.most_common():
cn = int(cn)
similar_indices = (clusters.labels_== cn).nonzero()[0]
similar = []
for i in similar_indices:
dist = sp.linalg.norm((clusters.cluster_centers_[cn] - doc_feat_mtrx[i]))
similar.append(str(dist) + "\t" + tweetsDF['id_str'].values[i]+"\t"+ tweetsDF[tok_result_col].values[i])
similar = sorted(similar, reverse=False)
cluster_info_str = ''
if selection:
if (float(similar[0][:4]) < min_dist_thres) and (float(similar[-1][:4]) < max_dist_thres) and ((float(similar[0][:4])+0.5) > float(similar[-1][:4])): # # the smallest and biggest distance to the centroid should not be very different, we allow 0.4 for now!
cluster_info_str+="cluster number and size are: "+str(cn)+' '+str(clustersizes[str(cn)]) + "\n"
cluster_bigram_cntr = Counter()
for txt in tweetsDF[tok_result_col].values[similar_indices]:
cluster_bigram_cntr.update(regex.findall(r"\b\w+[-]?\w+\s\w+", txt, overlapped=True))
cluster_bigram_cntr.update(txt.split()) # unigrams
topterms = [k+":"+str(v) for k,v in cluster_bigram_cntr.most_common() if k in word_vectorizer.get_feature_names()]
if len(topterms) < 2:
continue # a term with unknown words, due to frequency threshold, may cause a cluster. We want analyze this tweets one unknown terms became known as the freq. threshold decrease.
cluster_info_str+="Top terms are:"+", ".join(topterms) + "\n"
cluster_info_str+="distance_to_centroid"+"\t"+"tweet_id"+"\t"+"tweet_text\n"
if len(similar)>20:
cluster_info_str+='First 10 documents:\n'
cluster_info_str+= "\n".join(similar[:10]) + "\n"
#print(*similar[:10], sep='\n', end='\n')
cluster_info_str+='Last 10 documents:\n'
cluster_info_str+= "\n".join(similar[-10:]) + "\n"
else:
cluster_info_str+="Tweets for this cluster are:\n"
cluster_info_str+= "\n".join(similar) + "\n"
else:
cluster_info_str+="cluster number and size are: "+str(cn)+' '+str(clustersizes[str(cn)]) + "\n"
cluster_bigram_cntr = Counter()
for txt in tweetsDF[tok_result_col].values[similar_indices]:
cluster_bigram_cntr.update(regex.findall(r"\b\w+[-]?\w+\s\w+", txt, overlapped=True))
cluster_bigram_cntr.update(txt.split()) # unigrams
topterms = [k+":"+str(v) for k,v in cluster_bigram_cntr.most_common() if k in word_vectorizer.get_feature_names()]
if len(topterms) < 2:
continue # a term with unknown words, due to frequency threshold, may cause a cluster. We want analyze this tweets one unknown terms became known as the freq. threshold decrease.
cluster_info_str+="Top terms are:"+", ".join(topterms) + "\n"
cluster_info_str+="distance_to_centroid"+"\t"+"tweet_id"+"\t"+"tweet_text\n"
if len(similar)>20:
cluster_info_str+='First 10 documents:\n'
cluster_info_str+= "\n".join(similar[:10]) + "\n"
#print(*similar[:10], sep='\n', end='\n')
cluster_info_str+='Last 10 documents:\n'
cluster_info_str+= "\n".join(similar[-10:]) + "\n"
else:
cluster_info_str+="Tweets for this cluster are:\n"
cluster_info_str+= "\n".join(similar) + "\n"
if len(cluster_info_str) > 0: # that means there is some information in the cluster.
cluster_str_list.append(Cluster(cno=cn, cstr=cluster_info_str, tw_ids=list(tweetsDF[np.in1d(clusters.labels_,[cn])]["id_str"].values)))
return cluster_str_list
| [
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.cluster.KMeans",
"regex.findall",
"numpy.where",
"scipy.linalg.norm",
"collections.namedtuple",
"collections.Counter",
"numpy.in1d"
] | [((306, 447), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'ngram_range': '(1, 2)', 'lowercase': '(False)', 'norm': '"""l2"""', 'min_df': 'freqcutoff', 'token_pattern': '"""\\\\b\\\\w+\\\\b|[\\\\U00010000-\\\\U0010ffff]"""'}), "(ngram_range=(1, 2), lowercase=False, norm='l2', min_df=\n freqcutoff, token_pattern='\\\\b\\\\w+\\\\b|[\\\\U00010000-\\\\U0010ffff]')\n", (321, 447), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n'), ((618, 693), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'n_clust', 'init': '"""k-means++"""', 'max_iter': '(1000)', 'n_init': 'n_initt'}), "(n_clusters=n_clust, init='k-means++', max_iter=1000, n_init=n_initt)\n", (624, 693), False, 'from sklearn.cluster import KMeans\n'), ((841, 850), 'collections.Counter', 'Counter', ([], {}), '()\n', (848, 850), False, 'from collections import Counter, namedtuple\n'), ((1187, 1235), 'collections.namedtuple', 'namedtuple', (['"""Cluster"""', "['cno', 'cstr', 'tw_ids']"], {}), "('Cluster', ['cno', 'cstr', 'tw_ids'])\n", (1197, 1235), False, 'from collections import Counter, namedtuple\n'), ((1543, 1607), 'scipy.linalg.norm', 'sp.linalg.norm', (['(clusters.cluster_centers_[cn] - doc_feat_mtrx[i])'], {}), '(clusters.cluster_centers_[cn] - doc_feat_mtrx[i])\n', (1557, 1607), True, 'import scipy as sp\n'), ((3447, 3456), 'collections.Counter', 'Counter', ([], {}), '()\n', (3454, 3456), False, 'from collections import Counter, namedtuple\n'), ((928, 964), 'numpy.where', 'np.where', (['(kmeans_result.labels_ == l)'], {}), '(kmeans_result.labels_ == l)\n', (936, 964), True, 'import numpy as np\n'), ((2200, 2209), 'collections.Counter', 'Counter', ([], {}), '()\n', (2207, 2209), False, 'from collections import Counter, namedtuple\n'), ((3554, 3615), 'regex.findall', 'regex.findall', (['"""\\\\b\\\\w+[-]?\\\\w+\\\\s\\\\w+"""', 'txt'], {'overlapped': '(True)'}), "('\\\\b\\\\w+[-]?\\\\w+\\\\s\\\\w+', txt, overlapped=True)\n", (3567, 3615), False, 'import regex\n'), ((2307, 2368), 'regex.findall', 'regex.findall', (['"""\\\\b\\\\w+[-]?\\\\w+\\\\s\\\\w+"""', 'txt'], {'overlapped': '(True)'}), "('\\\\b\\\\w+[-]?\\\\w+\\\\s\\\\w+', txt, overlapped=True)\n", (2320, 2368), False, 'import regex\n'), ((4723, 4754), 'numpy.in1d', 'np.in1d', (['clusters.labels_', '[cn]'], {}), '(clusters.labels_, [cn])\n', (4730, 4754), True, 'import numpy as np\n')] |
import tensorflow as tf
import parallax
import argparse
import os
import random
import numpy as np
import sys
import time
import nmt
import attention_model
import gnmt_model
import model as nmt_model
import parallax_config
import model_helper
from utils import misc_utils as utils
import train
FLAGS = None
def add_arguments(parser):
"""Build ArgumentParser for Parallax."""
parser.add_argument("--resource_info_file", type=str, default=os.path.abspath(os.path.join(os.path.dirname(__file__), ".", "resource_info")), help="Filename containing cluster information")
parser.add_argument("--max_steps", type=int, default=1000000, help="Number of iterations to run for each workers.")
parser.add_argument("--log_frequency", type=int, default=100, help="How many steps between two runop logs.")
parser.add_argument("--sync", type="bool", nargs="?", const=True, default=True)
parser.add_argument("--epoch_size", type=int, default=0, help="total number of data instances")
def before_train(train_model, train_sess, global_step, hparams, log_f, num_replicas_per_worker):
"""Misc tasks to do before training."""
stats = train.init_stats()
lr = train_sess.run(train_model.model.learning_rate)[0]
info = {"train_ppl": 0.0, "speed": 0.0, "avg_step_time": 0.0, "avg_grad_norm": 0.0, "learning_rate": lr}
start_train_time = time.time()
utils.print_out("# Start step %d, lr %g, %s" % (global_step, info["learning_rate"], time.ctime()), log_f)
skip_count = hparams.batch_size * hparams.epoch_step
utils.print_out("# Init train iterator, skipping %d elements" % skip_count)
skip_count = train_model.skip_count_placeholder
feed_dict = {}
feed_dict[skip_count] = [0 for i in range(num_replicas_per_worker)]
initializers = []
init = train_model.iterator.initializer
train_sess.run(init, feed_dict=feed_dict)
return stats, info, start_train_time
def main(_):
default_hparams = nmt.create_hparams(FLAGS)
out_dir = FLAGS.out_dir
if not tf.gfile.Exists(out_dir):
tf.gfile.MakeDirs(out_dir)
hparams = nmt.create_or_load_hparams(out_dir, default_hparams, FLAGS.hparams_path, save_hparams=False)
log_device_placement = hparams.log_device_placement
out_dir = hparams.out_dir
num_train_steps = hparams.num_train_steps
steps_per_stats = hparams.steps_per_stats
avg_ckpts = hparams.avg_ckpts
if not hparams.attention:
model_creator = nmt_model.Model
else:
if hparams.encoder_type == "gnmt" or hparams.attention_architecture in ["gnmt", "gnmt_v2"]:
model_creator = gnmt_model.GNMTModel
elif hparams.attention_architecture == "standard":
model_creator = attention_model.AttentionModel
else:
raise ValueError("Unknown attention architecture %s" % hparams.attention_architecture)
train_model = model_helper.create_train_model(model_creator, hparams, scope=None)
config_proto = utils.get_config_proto(log_device_placement=log_device_placement, num_intra_threads=1, num_inter_threads=36)
def run(train_sess, num_workers, worker_id, num_replicas_per_worker):
random_seed = FLAGS.random_seed
if random_seed is not None and random_seed > 0:
utils.print_out("# Set random seed to %d" % random_seed)
random.seed(random_seed + worker_id)
np.random.seed(random_seed + worker_id)
log_file = os.path.join(out_dir, "log_%d" % time.time())
log_f = tf.gfile.GFile(log_file, mode="a")
utils.print_out("# log_file=%s" % log_file, log_f)
global_step = train_sess.run(train_model.model.global_step)[0]
last_stats_step = global_step
stats, info, start_train_time = before_train(train_model, train_sess, global_step, hparams, log_f, num_replicas_per_worker)
epoch_steps = FLAGS.epoch_size / (FLAGS.batch_size * num_workers * num_replicas_per_worker)
for i in range(FLAGS.max_steps):
start_time = time.time()
if hparams.epoch_step != 0 and hparams.epoch_step % epoch_steps == 0:
hparams.epoch_step = 0
skip_count = train_model.skip_count_placeholder
feed_dict = {}
feed_dict[skip_count] = [0 for i in range(num_replicas_per_worker)]
init = train_model.iterator.initializer
train_sess.run(init, feed_dict=feed_dict)
if worker_id == 0:
results = train_sess.run([train_model.model.update, train_model.model.train_loss, train_model.model.predict_count, train_model.model.train_summary, train_model.model.global_step, train_model.model.word_count, train_model.model.batch_size, train_model.model.grad_norm, train_model.model.learning_rate])
step_result = [r[0] for r in results]
else:
global_step, _ = train_sess.run([train_model.model.global_step, train_model.model.update])
hparams.epoch_step += 1
if worker_id == 0:
global_step, info["learning_rate"], step_summary = train.update_stats(stats, start_time, step_result)
if global_step - last_stats_step >= steps_per_stats:
last_stats_step = global_step
is_overflow = train.process_stats(stats, info, global_step, steps_per_stats, log_f)
train.print_step_info(" ", global_step, info, train._get_best_results(hparams), log_f)
if is_overflow:
break
stats = train.init_stats()
sess, num_workers, worker_id, num_replicas_per_worker = parallax.parallel_run(train_model.graph, FLAGS.resource_info_file, sync=FLAGS.sync, parallax_config=parallax_config.build_config())
run(sess, num_workers, worker_id, num_replicas_per_worker)
if __name__ == "__main__":
import logging
logging.getLogger("tensorflow").setLevel(logging.DEBUG)
nmt_parser = argparse.ArgumentParser()
nmt.add_arguments(nmt_parser)
add_arguments(nmt_parser)
FLAGS, unparsed = nmt_parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) | [
"tensorflow.gfile.Exists",
"numpy.random.seed",
"argparse.ArgumentParser",
"train.process_stats",
"time.ctime",
"os.path.dirname",
"model_helper.create_train_model",
"nmt.create_hparams",
"random.seed",
"train._get_best_results",
"parallax_config.build_config",
"train.update_stats",
"nmt.add... | [((1119, 1137), 'train.init_stats', 'train.init_stats', ([], {}), '()\n', (1135, 1137), False, 'import train\n'), ((1321, 1332), 'time.time', 'time.time', ([], {}), '()\n', (1330, 1332), False, 'import time\n'), ((1495, 1570), 'utils.misc_utils.print_out', 'utils.print_out', (["('# Init train iterator, skipping %d elements' % skip_count)"], {}), "('# Init train iterator, skipping %d elements' % skip_count)\n", (1510, 1570), True, 'from utils import misc_utils as utils\n'), ((1878, 1903), 'nmt.create_hparams', 'nmt.create_hparams', (['FLAGS'], {}), '(FLAGS)\n', (1896, 1903), False, 'import nmt\n'), ((2003, 2099), 'nmt.create_or_load_hparams', 'nmt.create_or_load_hparams', (['out_dir', 'default_hparams', 'FLAGS.hparams_path'], {'save_hparams': '(False)'}), '(out_dir, default_hparams, FLAGS.hparams_path,\n save_hparams=False)\n', (2029, 2099), False, 'import nmt\n'), ((2711, 2778), 'model_helper.create_train_model', 'model_helper.create_train_model', (['model_creator', 'hparams'], {'scope': 'None'}), '(model_creator, hparams, scope=None)\n', (2742, 2778), False, 'import model_helper\n'), ((2795, 2907), 'utils.misc_utils.get_config_proto', 'utils.get_config_proto', ([], {'log_device_placement': 'log_device_placement', 'num_intra_threads': '(1)', 'num_inter_threads': '(36)'}), '(log_device_placement=log_device_placement,\n num_intra_threads=1, num_inter_threads=36)\n', (2817, 2907), True, 'from utils import misc_utils as utils\n'), ((5403, 5428), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5426, 5428), False, 'import argparse\n'), ((5430, 5459), 'nmt.add_arguments', 'nmt.add_arguments', (['nmt_parser'], {}), '(nmt_parser)\n', (5447, 5459), False, 'import nmt\n'), ((5537, 5589), 'tensorflow.app.run', 'tf.app.run', ([], {'main': 'main', 'argv': '([sys.argv[0]] + unparsed)'}), '(main=main, argv=[sys.argv[0]] + unparsed)\n', (5547, 5589), True, 'import tensorflow as tf\n'), ((1937, 1961), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['out_dir'], {}), '(out_dir)\n', (1952, 1961), True, 'import tensorflow as tf\n'), ((1965, 1991), 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['out_dir'], {}), '(out_dir)\n', (1982, 1991), True, 'import tensorflow as tf\n'), ((3271, 3305), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['log_file'], {'mode': '"""a"""'}), "(log_file, mode='a')\n", (3285, 3305), True, 'import tensorflow as tf\n'), ((3308, 3358), 'utils.misc_utils.print_out', 'utils.print_out', (["('# log_file=%s' % log_file)", 'log_f'], {}), "('# log_file=%s' % log_file, log_f)\n", (3323, 3358), True, 'from utils import misc_utils as utils\n'), ((3062, 3118), 'utils.misc_utils.print_out', 'utils.print_out', (["('# Set random seed to %d' % random_seed)"], {}), "('# Set random seed to %d' % random_seed)\n", (3077, 3118), True, 'from utils import misc_utils as utils\n'), ((3122, 3158), 'random.seed', 'random.seed', (['(random_seed + worker_id)'], {}), '(random_seed + worker_id)\n', (3133, 3158), False, 'import random\n'), ((3162, 3201), 'numpy.random.seed', 'np.random.seed', (['(random_seed + worker_id)'], {}), '(random_seed + worker_id)\n', (3176, 3201), True, 'import numpy as np\n'), ((3727, 3738), 'time.time', 'time.time', ([], {}), '()\n', (3736, 3738), False, 'import time\n'), ((5197, 5227), 'parallax_config.build_config', 'parallax_config.build_config', ([], {}), '()\n', (5225, 5227), False, 'import parallax_config\n'), ((5333, 5364), 'logging.getLogger', 'logging.getLogger', (['"""tensorflow"""'], {}), "('tensorflow')\n", (5350, 5364), False, 'import logging\n'), ((1418, 1430), 'time.ctime', 'time.ctime', ([], {}), '()\n', (1428, 1430), False, 'import time\n'), ((3248, 3259), 'time.time', 'time.time', ([], {}), '()\n', (3257, 3259), False, 'import time\n'), ((4650, 4700), 'train.update_stats', 'train.update_stats', (['stats', 'start_time', 'step_result'], {}), '(stats, start_time, step_result)\n', (4668, 4700), False, 'import train\n'), ((468, 493), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (483, 493), False, 'import os\n'), ((4812, 4881), 'train.process_stats', 'train.process_stats', (['stats', 'info', 'global_step', 'steps_per_stats', 'log_f'], {}), '(stats, info, global_step, steps_per_stats, log_f)\n', (4831, 4881), False, 'import train\n'), ((5021, 5039), 'train.init_stats', 'train.init_stats', ([], {}), '()\n', (5037, 5039), False, 'import train\n'), ((4934, 4966), 'train._get_best_results', 'train._get_best_results', (['hparams'], {}), '(hparams)\n', (4957, 4966), False, 'import train\n')] |
"""Crank-Nicholson (implicit) finite difference method for Burger's equation. Code written by <NAME>. Implicit finite
difference method derived by <NAME>, <NAME>, <NAME>, and <NAME>.
2018-12-04
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# TODO: Turn this into a more general implicit finite difference solver that accepts A and B as arguments (or
# something).
def conditions(U1, U0, K1, K2, h, h_aj, c_aj, d_aj, h_bj, c_bj, d_bj):
"""Return the conditions for Burgers' equation.
Returns nonlinear implicit Crank-Nicholson equations for the transformed Burgers' equation, derived using forward
difference approximations for u_x and center difference for u_xx. Boundary conditions were derived similarly.
out = [
h h_aj - (h c_aj - d_aj) U1[0] - d_aj U1[1]
(U1[1]-U0[1]) - K1[-U1[1](U1[2]-U1[0]) - U0[1](U0[2]-U0[0])] - K2[(U1[2]-2*U1[1]+U1[0]) + (U0[2]-2*U0[1]+U0[0])]
`-.
(U1[k]-U0[k]) - K1[-U1[k](U1[k+1]-U1[k-1]) - U0[k](U0[k+1]-U0[k-1])] # cont'd
- K2[(U1[k+1]-2*U1[k]+U1[k-1]) + (U0[k+1]-2*U0[k]+U0[k-1])]
`-.
(U1[-2]-U0[-2]) - K1[-U1[-2](U1[-1]-U1[-3]) - U0[-2](U0[-1]-U0[-3])] # cont'd
- K2[(U1[-1]-2*U1[-2]+U1[-3]) + (U0[-1]-2*U0[-2]+U0[-3])]
h h_bj - (h c_bj + d_bj) U1[-1] - d_bj U1[-2]
]
Parameters
U1 (ndarray): The values of U^(n+1)
U0 (ndarray): The values of U^n
K1 (float): first constant in the equations
K2 (float): second constant in the equations
h (float): spatial difference constant, usually (b - a) / num_x_steps
h_aj (float): h_a evaluated at this time step
c_aj (float): c_a evaluated at this time step
d_aj (float): d_a evaluated at this time step
h_bj (float): h_b evaluated at this time step
c_bj (float): c_b evaluated at this time step
d_bj (float): d_b evaluated at this time step
Returns
out (ndarray): The residuals (differences between right- and left-hand sides) of the equation, accounting for
boundary conditions.
"""
# compute Crank-Nicolson conditions on interior
lhs = U1[1:-1] - U0[1:-1]
K1_term = K1 * (-U1[1:-1] * (U1[2:] - U1[:-2]) - U0[1:-1] * (U0[2:] - U0[:-2]))
K2_term = K2 * (U1[2:] - 2 * U1[1:-1] + U1[:-2] + U0[2:] - 2 * U0[1:-1] + U0[:-2])
rhs = K1_term + K2_term
# calculate boundary conditions
a_condition = (h * c_aj - d_aj) * U1[0] + d_aj * U1[1]
b_condition = (h * c_bj + d_bj) * U1[-1] - d_bj * U1[-2]
# We want to require the interior according to the finite difference method, and the boundary conditions separately.
return np.concatenate(([h * h_aj - a_condition], lhs - rhs, [h * h_bj - b_condition]))
def conditions_jac(U1, U0, K1, K2, h, h_aj, c_aj, d_aj, h_bj, c_bj, d_bj):
"""Returns the Jacobian of the conditions for Burgers' equation.
Returns the Jacobian of the nonlinear Crank-Nicholson equations for the Burgers' equation:
_ _
| (-h c_aj + d_aj) (-d_aj) 0 0 0 ... 0 |
| (K1 U1[1] - K2) (K1 (U1[0] - U1[2])) (K1 U1[1] - K2) 0 0 ... 0 |
jac = | 0 ... 0 `-. `-. `-. 0 ... 0 |
| 0 ... 0 (K1 U1[k] - K2) (K1 (U1[k-1] - U1[k+1])) (K1 U1[k] - K2) 0 ... 0 |
| 0 ... 0 `-. `-. `-. `-. ... 0 |
| 0 ... ... ... ... (-d_bj) ... (-h c_bj - d_bj) |
-- --
Parameters
U1 (ndarray): The values of U^(n+1)
U0 (ndarray): The values of U^n
K1 (float): first constant in the equations
K2 (float): second constant in the equations
h (float): spatial difference constant, usually (b - a) / num_x_steps
h_aj (float): h_a evaluated at this time step
c_aj (float): c_a evaluated at this time step
d_aj (float): d_a evaluated at this time step
h_bj (float): h_b evaluated at this time step
c_bj (float): c_b evaluated at this time step
d_bj (float): d_b evaluated at this time step
Returns
jac (ndarray): The residuals (differences between right- and left-hand sides) of the equation, accounting for
boundary conditions.
"""
jac = np.zeros((len(U0), len(U0)))
# fill the main diagonal
jac[1:-1, 1:-1] = np.diag(1 + K1 * (U1[2:] - U1[:-2]) + 2 * K2)
jac[0, 0] = d_aj - h * c_aj
jac[-1, -1] = -d_bj - h * c_bj
# fill the left off-diagonal
jac[1:-1, :-2] = jac[1:-1, :-2] + np.diag(-K1 * U1[1:-1] - K2)
jac[-1, -2] = -d_bj
# fill the right off-diagonal
jac[1:-1, 2:] = jac[1:-1, 2:] + np.diag(K1 * U1[1:-1] - K2)
jac[0, 1] = -d_aj
return jac
def newton(f, x0, Df, tol=1e-5, maxiters=30, alpha=1., args=()):
"""Use Newton's method to approximate a zero of the function f.
Parameters:
f (lambda): a function from R^n to R^n (assume n=1 until Problem 5).
x0 (float or ndarray): The initial guess for the zero of f.
Df (lambda): The derivative of f, a function from R^n to R^(n*n).
tol (float): Convergence tolerance. The function should return when the difference between successive
approximations is less than tol.
maxiters (int): The maximum number of iterations to compute.
alpha (float): Backtracking scalar (Problem 3).
Returns:
(float or ndarray): The approximation for a zero of f.
(bool): Whether or not Newton's method converged.
(int): The number of iterations computed.
"""
i = 0
if np.isscalar(x0):
while i < maxiters:
fut = x0 - alpha * f(x0, *args) / Df(x0, *args)
i += 1
if abs(fut - x0) < tol:
return fut, True, i
else:
x0 = fut
return x0, False, i
else:
while i < maxiters:
fut = x0 - alpha * np.linalg.solve(Df(x0, *args), f(x0, *args))
i += 1
if np.linalg.norm(fut - x0) < tol:
return fut, True, i
else:
x0 = fut
return x0, False, i
def burgers_equation(a, b, T, N_x, N_t, u_0, c_a, d_a, h_a, c_b, d_b, h_b):
"""Returns a solution to Burgers' equation.
Returns a Crank-Nicolson approximation of the solution u(x, t) for the following system:
u_t + (u ** 2 / 2)_x = u_xx, a <= x <= b, 0 < t <= T
u(x, 0) = u_0(x),
h_a(t) = c_a(t) * u(a, t) + d_a(t) * u_x(a, t),
h_b(t) = c_b(t) * u(b, t) + d_b(t) * u_x(b, t).
Parameters:
a (float): left spatial endpoint
b (float): right spatial endpoint
T (float): final time value
N_x (int): number of mesh nodes in the spatial dimension
N_t (int): number of mesh nodes in the temporal dimension
u_0 (callable): function specifying the initial condition
c_a (callable): function specifying left boundary condition
d_a (callable): function specifying left boundary condition
h_a (callable): function specifying left boundary condition
c_b (callable): function specifying right boundary condition
d_b (callable): function specifying right boundary condition
h_b (callable): function specifying right boundary condition
Returns:
Us (np.ndarray): finite difference approximation of u(x,t). Us[j] = u(x,t_j), where j is the index corresponding
to time t_j.
"""
if a >= b:
raise ValueError('a must be less than b')
if T <= 0:
raise ValueError('T must be greater than or equal to zero')
if N_x <= 2:
raise ValueError('N_x must be greater than zero')
if N_t <= 1:
raise ValueError('N_t must be greater than zero')
x, delx = np.linspace(a, b, N_x, retstep=True)
t, delt = np.linspace(0, T, N_t, retstep=True)
# evaluate the boundary condition functions along t
H_a = h_a(t)
C_a = c_a(t)
D_a = d_a(t)
H_b = h_b(t)
C_b = c_b(t)
D_b = d_b(t)
# evaluate the initial condition function
f_x0 = u_0(x)
K1 = delt / 4 / delx
K2 = delt / 2 / delx / delx
# temporal iteration
Us = [f_x0]
for j in range(1, N_t):
result, converged, _ = newton(conditions,
Us[-1],
conditions_jac,
args=(Us[-1], K1, K2, delx, H_a[j], C_a[j], D_a[j], H_b[j], C_b[j], D_b[j])
)
if not converged:
print('warning: Newton\'s method did not converge')
Us.append(result)
# Use the following code instead of the above to solve using scipy.optimize.fsolve
# from scipy.optimize import fsolve
# Us.append(fsolve(conditions,
# Us[-1],
# args=(Us[-1], K1, K2, h, H_a[j], C_a[j], D_a[j], H_b[j], C_b[j], D_b[j])))
return np.array(Us)
def test_burgers_equation():
"""With initial condition u_0(x) = 1 - tanh(x / 2) and boundary conditions specified by
c_a(t) = 1, d_a(t) = 1, h_a(t) = 1 - tanh((a - t) / 2) - 0.5 * sech^2((a - t) / 2),
c_b(t) = 1, d_b(t) = 1, and h_b(t) = 1 - tanh((b - t) / 2) - 0.5 * sech^2((b - t) / 2),
the solution is u(x, t)= 1 - tanh((x - t) / 2). We test `burgers_equation` using this fact. The correct result is
displayed as an animation in test_burgers_equation.mp4.
"""
a = -1
b = 1
T = 1
N_x = 151
N_t = 351
u_0 = lambda x: 1 - np.tanh(x / 2)
c_a = lambda t: np.ones_like(t) if type(t) == np.ndarray else 1
d_a = lambda t: np.ones_like(t) if type(t) == np.ndarray else 1
h_a = lambda t: 1 - np.tanh((a - t) / 2) - 1 / 2 / (np.cosh((a - t) / 2) ** 2)
c_b = lambda t: np.ones_like(t) if type(t) == np.ndarray else 1
d_b = lambda t: np.ones_like(t) if type(t) == np.ndarray else 1
h_b = lambda t: 1 - np.tanh((b - t) / 2) - 1 / 2 / (np.cosh((b - t) / 2) ** 2)
x = np.linspace(a, b, N_x)
Us = burgers_equation(a, b, T, N_x, N_t, u_0, c_a, d_a, h_a, c_b, d_b, h_b)
# animation
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim((x[0], x[-1]))
ax.set_ylim((0, 3))
# correct solution at t=1
u_1 = lambda x: 1 - np.tanh((x - 1) / 2)
plt.plot(x, u_0(x))
plt.plot(x, u_1(x))
traj, = plt.plot([], [], color='r', alpha=0.5)
def update(i):
traj.set_data(x, Us[i])
return traj
plt.legend(['theoretical $u(x,0)$', 'theoretical $u(x,1)$', 'approximated $u(x,t)$'])
ani = animation.FuncAnimation(fig, update, frames=range(len(Us)), interval=25)
ani.save('test_burgers_equation.mp4')
plt.close()
if __name__ == '__main__':
test_burgers_equation()
| [
"numpy.ones_like",
"numpy.tanh",
"matplotlib.pyplot.plot",
"numpy.isscalar",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.linalg.norm",
"numpy.linspace",
"numpy.cosh",
"numpy.diag",
"numpy.concatenate"
] | [((2726, 2805), 'numpy.concatenate', 'np.concatenate', (['([h * h_aj - a_condition], lhs - rhs, [h * h_bj - b_condition])'], {}), '(([h * h_aj - a_condition], lhs - rhs, [h * h_bj - b_condition]))\n', (2740, 2805), True, 'import numpy as np\n'), ((4687, 4732), 'numpy.diag', 'np.diag', (['(1 + K1 * (U1[2:] - U1[:-2]) + 2 * K2)'], {}), '(1 + K1 * (U1[2:] - U1[:-2]) + 2 * K2)\n', (4694, 4732), True, 'import numpy as np\n'), ((5932, 5947), 'numpy.isscalar', 'np.isscalar', (['x0'], {}), '(x0)\n', (5943, 5947), True, 'import numpy as np\n'), ((8158, 8194), 'numpy.linspace', 'np.linspace', (['a', 'b', 'N_x'], {'retstep': '(True)'}), '(a, b, N_x, retstep=True)\n', (8169, 8194), True, 'import numpy as np\n'), ((8209, 8245), 'numpy.linspace', 'np.linspace', (['(0)', 'T', 'N_t'], {'retstep': '(True)'}), '(0, T, N_t, retstep=True)\n', (8220, 8245), True, 'import numpy as np\n'), ((9342, 9354), 'numpy.array', 'np.array', (['Us'], {}), '(Us)\n', (9350, 9354), True, 'import numpy as np\n'), ((10399, 10421), 'numpy.linspace', 'np.linspace', (['a', 'b', 'N_x'], {}), '(a, b, N_x)\n', (10410, 10421), True, 'import numpy as np\n'), ((10529, 10541), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (10539, 10541), True, 'from matplotlib import pyplot as plt\n'), ((10765, 10803), 'matplotlib.pyplot.plot', 'plt.plot', (['[]', '[]'], {'color': '"""r"""', 'alpha': '(0.5)'}), "([], [], color='r', alpha=0.5)\n", (10773, 10803), True, 'from matplotlib import pyplot as plt\n'), ((10881, 10970), 'matplotlib.pyplot.legend', 'plt.legend', (["['theoretical $u(x,0)$', 'theoretical $u(x,1)$', 'approximated $u(x,t)$']"], {}), "(['theoretical $u(x,0)$', 'theoretical $u(x,1)$',\n 'approximated $u(x,t)$'])\n", (10891, 10970), True, 'from matplotlib import pyplot as plt\n'), ((11096, 11107), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (11105, 11107), True, 'from matplotlib import pyplot as plt\n'), ((4872, 4900), 'numpy.diag', 'np.diag', (['(-K1 * U1[1:-1] - K2)'], {}), '(-K1 * U1[1:-1] - K2)\n', (4879, 4900), True, 'import numpy as np\n'), ((4996, 5023), 'numpy.diag', 'np.diag', (['(K1 * U1[1:-1] - K2)'], {}), '(K1 * U1[1:-1] - K2)\n', (5003, 5023), True, 'import numpy as np\n'), ((9937, 9951), 'numpy.tanh', 'np.tanh', (['(x / 2)'], {}), '(x / 2)\n', (9944, 9951), True, 'import numpy as np\n'), ((9972, 9987), 'numpy.ones_like', 'np.ones_like', (['t'], {}), '(t)\n', (9984, 9987), True, 'import numpy as np\n'), ((10040, 10055), 'numpy.ones_like', 'np.ones_like', (['t'], {}), '(t)\n', (10052, 10055), True, 'import numpy as np\n'), ((10191, 10206), 'numpy.ones_like', 'np.ones_like', (['t'], {}), '(t)\n', (10203, 10206), True, 'import numpy as np\n'), ((10259, 10274), 'numpy.ones_like', 'np.ones_like', (['t'], {}), '(t)\n', (10271, 10274), True, 'import numpy as np\n'), ((10682, 10702), 'numpy.tanh', 'np.tanh', (['((x - 1) / 2)'], {}), '((x - 1) / 2)\n', (10689, 10702), True, 'import numpy as np\n'), ((6347, 6371), 'numpy.linalg.norm', 'np.linalg.norm', (['(fut - x0)'], {}), '(fut - x0)\n', (6361, 6371), True, 'import numpy as np\n'), ((10112, 10132), 'numpy.tanh', 'np.tanh', (['((a - t) / 2)'], {}), '((a - t) / 2)\n', (10119, 10132), True, 'import numpy as np\n'), ((10331, 10351), 'numpy.tanh', 'np.tanh', (['((b - t) / 2)'], {}), '((b - t) / 2)\n', (10338, 10351), True, 'import numpy as np\n'), ((10144, 10164), 'numpy.cosh', 'np.cosh', (['((a - t) / 2)'], {}), '((a - t) / 2)\n', (10151, 10164), True, 'import numpy as np\n'), ((10363, 10383), 'numpy.cosh', 'np.cosh', (['((b - t) / 2)'], {}), '((b - t) / 2)\n', (10370, 10383), True, 'import numpy as np\n')] |
import numpy as np
import os
import urllib.request
import gzip
import tkinter as tk
from PIL import Image, ImageDraw, ImageOps
import idx2numpy
""" Functions necessary to set up neural network for digit recognition
and run associated GUI.
Contents
--------
NeuralNetwork: class
Defines functions necessary to setup, train, evaluate and save a
neural network.
pre_processing: function
Downloads, imports and preprocess data for digit recognition.
install_network: function
Sets up neural network by running the functions defined in the
NeuralNetwork class with certain arguments chosen by the author.
Gui: class
Defines functions necessary for digit recognition GUI.
run_gui: function
Runs GUI in infinite loop.
"""
class NeuralNetwork:
""" Defines functions necessary to setup, train, evaluate and save
a neural network.
Attributes
----------
design: list
Contains the number of nodes in each layer (length is number
of layers)
weights: list
Contains weight matrices
step_size: float
Step size for training algorithm
activation_function: function
Activation function used in neural network
bias: boolean
Bias nodes on or off
activation: list
Contains activation of nodes at each layer
confusion_matrix: np.array
Confusion matrix produced in 'evaluate' method (true labels
in rows, predicitons in columns)
accuracy, recall, precision: float
Accuracy, recall, and precision of neural network produced in
'evaluate' method
Methods
-------
train(input_data, target_data, epochs=1)
Loops of 'one_training' function
one_training(input_data, target_data)
Computes cost and updates weights accordingly using backpropagation
run(input_data)
Forward propagation for single input
evaluate(input_data, target_data)
Assesses performance of neural network and computes performance
measures
save(file_name)
Saves weights of neural network as np.array
"""
def sigmoid(x):
""" Activation function used in neural network. """
return 1/(1+np.exp(-x))
def __init__(
self, design,
weights=None, step_size=0.01,
activation_function=sigmoid, bias=False):
""" Set up basic attributes of neural network.
Arguments
---------
design: list
List containing the number of nodes in each layer. Can
have any length (above 1). E.g., [784, 20, 10].
weights: list
List containing numpy arrays with desired weights.
Defaults to None. If no weights are specified, random
ones are generated.
step_size: float
Step size used for backpropagation. Defaults to 0.01
activation_function: function
Specifies activation function of neural network. Only a
sigmoid function is given, but others, e.g., ReLU, could
be added.
bias: boolean
Should bias node be added to neural network? Defaults to
False.
"""
self.design = design
self.weights = weights
self.step_size = step_size
self.activation_function = activation_function
self.bias = bias
self.activation = []
# Create random weights
if self.weights is None:
self.weights = [np.zeros(0)]
for i in np.arange(len(self.design) - 1):
self.weights.append(np.random.uniform(-1, 1,
[self.design[i+1], self.design[i]+self.bias]))
# Function check
if self.weights[1].shape == (self.design[1], self.design[0]+self.bias):
print('Network created successfully')
else:
print('Network creation failed')
def train(self, input_data, target_data, epochs=1):
""" Loop for 'one_train' (backpropagation) function (see below).
Arguments
---------
input_data: array
3-dimensional numpy array containing input data (see
pre_processing function for exact format).
target_data: array
2-dimensional numpy array containing target data in one-hot
representation.
epochs: int
Number of times the training algorithms iterates through
the *entire* dataset. Defaults to 1.
"""
print('Training...')
for epoch in np.arange(epochs):
print('Epoch: ' + str(epoch + 1) + ' (of ' + str(epochs) + ')')
for i in np.arange(len(input_data)):
self.one_training(input_data[i], target_data[i])
# Function check
if i == len(input_data) - 1:
print('Network trained successfully')
else:
print('Training failed')
def one_training(self, input_data, target_data):
""" Backpropagation algorithm to train neural network.
Arguments
---------
input_data: array
2-dimensional numpy array containing a single input. Passed
by train function (see above).
target_data: array
2-dimensional numpy array containing a single target. Passed
by train function (see above).
"""
# Convert data into coumn vectors
input_vector = np.array(input_data.flatten(), ndmin=2).T
if self.bias:
input_vector = np.array(np.append(1, input_vector), ndmin=2).T
target_vector = np.array(target_data, ndmin=2).T
# Forward propagation to compute activation
self.activation = []
self.activation.append(input_vector)
for i in np.arange(len(self.design)-1):
self.activation.append(self.activation_function(
self.weights[i+1] @ self.activation[i]))
if self.bias:
self.activation[i+1] = np.array(
np.append(1, self.activation[i+1]), ndmin=2).T
# Compute error
error = target_vector - self.activation[-1][self.bias:]
# Backpropagation to update weights
for i in np.arange(len(self.design) - 1, 0, -1):
gradient = (error * self.activation[i][self.bias:]
* (1.0 - self.activation[i][self.bias:])) @ self.activation[i-1].T
correction = self.step_size * gradient
self.weights[i] += correction
error = self.weights[i].T @ error
error = error[self.bias:]
def run(self, input_data):
""" Forward propagation algorithm.
Computes output of neural network for a single input.
Arguments
---------
input_data: array
2-dimensional numpy array containing a single input.
"""
# Convert data into column vector
input_vector = np.array(input_data.flatten(), ndmin=2).T
if self.bias:
input_vector = np.array(np.append(1, input_vector), ndmin=2).T
# Compute layer outputs/activations
self.activation = []
self.activation.append(input_vector)
for i in np.arange(len(self.design)-1):
self.activation.append(self.activation_function(
self.weights[i+1] @ self.activation[i]))
if self.bias and i != len(self.design) - 2:
self.activation[i+1] = np.array(
np.append(1, self.activation[i+1]), ndmin=2).T
return self.activation[-1]
def evaluate(self, input_data, target_data):
""" Evaluates performance of neural network.
Computes accuracy of neural network, as well as recall and precision
for each class using a confusion matrix. Results are printed to the
console, but also defined as attributes of the neural network.
Note: Use independent test data!
Arguments
---------
input_data: array
3-dimensional numpy array containing test input data.
target_data: array
2-dimensional numpy array containing test target data in
one-hot representation.
"""
self.confusion_matrix = np.zeros(
[target_data.shape[-1], target_data.shape[-1]])
# Compute confusion matrix (one data point at a time)
for i in np.arange(len(input_data)):
output = self.run(input_data[i])
true_label = np.array(target_data[i], ndmin=2).T
# Compute result and add to confusion matrix
# (true label in rows, prediction in columns)
confusion_result = true_label @ output.T
confusion_result[confusion_result == np.max(confusion_result)] = 1
confusion_result[confusion_result != 1] = 0
self.confusion_matrix += confusion_result
total_predictions = np.sum(self.confusion_matrix)
correct_predictions = np.sum(np.diag(self.confusion_matrix))
false_predictions = total_predictions - correct_predictions
# Accuracy
self.accuracy = correct_predictions / total_predictions
# Recall (per class)
self.recall = np.array([])
for i in np.arange(target_data.shape[-1]):
self.recall = np.append(
self.recall,
self.confusion_matrix[i,i] / np.sum(self.confusion_matrix[i,:]),
)
# Precision (per class)
self.precision = np.array([])
for i in np.arange(target_data.shape[-1]):
self.precision = np.append(
self.precision,
self.confusion_matrix[i,i] / np.sum(self.confusion_matrix[:,i]),
)
# Print accuracy measures
print('Accuracy: ' + str('%.2f' % (self.accuracy * 100)) + '%')
for i in np.arange(target_data.shape[-1]):
print('Recall for ' + str(i) + ': '
+ str('%.2f' % (self.recall[i] * 100)) + '%')
print('Precision for ' + str(i) + ': '
+ str('%.2f' % (self.precision[i] * 100)) + '%')
def save(self, file_name):
""" Saves weights of neural network as np.array
Arguments
---------
file_name: string
Name of the file that is saved (without file extension)
"""
np.save(file_name + '.npy', np.asarray(self.weights))
if os.path.isfile(file_name + '.npy'):
print('Network saved successfully as ' + file_name + '.npy')
else:
print('Saving failed')
def pre_processing():
""" Downloads, imports and preprocess data for digit recognition.
Data is downloaded from the MNIST database. Consists of 70.000
handwritten digits of 28x28 pixels. Each with a corresponding,
manually added label. Data is split into 60.000 instances for
training and 10.000 instances for testing.
Returns:
Matrix representations of digits and correspondings
labels in a format optimized for the neural network.
"""
# Download data (to 'DR_Data' folder)
downloaded = os.path.exists('DR_Data')
if not downloaded:
os.mkdir('DR_Data')
print('Downloading dataset...')
url = 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz'
urllib.request.urlretrieve(url, 'DR_Data/train-images-idx3-ubyte.gz')
url = 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz'
urllib.request.urlretrieve(url, 'DR_Data/train-labels-idx1-ubyte.gz')
url = 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz'
urllib.request.urlretrieve(url, 'DR_Data/t10k-images-idx3-ubyte.gz')
url = 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz'
urllib.request.urlretrieve(url, 'DR_Data/t10k-labels-idx1-ubyte.gz')
# Check download
if (os.path.isfile('DR_Data/train-images-idx3-ubyte.gz')
and os.path.isfile('DR_Data/train-labels-idx1-ubyte.gz')
and os.path.isfile('DR_Data/t10k-images-idx3-ubyte.gz')
and os.path.isfile('DR_Data/t10k-labels-idx1-ubyte.gz')):
print('Data downloaded successfully')
else:
print('Download failed')
else:
print('Data has been downloaded')
# Load data and convert data to numpy arrays
os.chdir('DR_Data')
train_images = idx2numpy.convert_from_file(
gzip.open('train-images-idx3-ubyte.gz','r'))
train_labels = idx2numpy.convert_from_file(
gzip.open('train-labels-idx1-ubyte.gz','r'))
test_images = idx2numpy.convert_from_file(
gzip.open('t10k-images-idx3-ubyte.gz','r'))
test_labels = idx2numpy.convert_from_file(
gzip.open('t10k-labels-idx1-ubyte.gz','r'))
os.chdir('..')
# Re-scale input values from intervals [0,255] to [0.01,1]
# (necessary for optimal performance of NN)
train_images = train_images * (0.99/255) + 0.01
test_images = test_images * (0.99/255) + 0.01
# Convert label data to one-hot representation with either 0.01 or 0.99
# (also necessary for optimal performance of NN
# and to compute confusion matrix)
train_labels = np.asfarray(train_labels)
test_labels = np.asfarray(test_labels)
train_labels = np.array(train_labels, ndmin=2).T
test_labels = np.array(test_labels, ndmin=2).T
train_labels = (np.arange(10) == train_labels).astype(np.float)
test_labels = (np.arange(10) == test_labels).astype(np.float)
train_labels[train_labels == 1] = 0.99
test_labels[test_labels == 1] = 0.99
train_labels[train_labels == 0] = 0.01
test_labels[test_labels == 0] = 0.01
# Function check
if (train_images.shape == (60000, 28, 28)
and train_labels.shape == (60000, 10)):
print('Data preprocessed successfully')
else:
print('Preprocessing failed')
return train_images, train_labels, test_images, test_labels
def install_network(design=[784,200,100,10],
bias=True,
epochs=3,
file_name='my_network'
):
""" Sets up neural network by running the functions defined above
with certain arguments chosen by the author.
Purpose of the function is to make the set up the neural network
easier.
Arguments
---------
design: list, optional
List containing the number of nodes in each layer. Default
to [784,200,100,10]
bias: boolean, optional
Should bias node be added to neural network? Defaults to
True.
epochs: int, optional
Number of times the training algorithms iterates through the
*entire* dataset. Defaults to 3.
file_name: string, optional
Name of the file that is saved (without file extension).
Defaults to 'my_network'
"""
# Import data
train_images, train_labels, test_images, test_labels = pre_processing()
# Build neural network (with two hidden layers of 200/100 nodes respectively)
neural_network = NeuralNetwork(design, bias=bias)
neural_network.train(train_images, train_labels, epochs=epochs)
neural_network.evaluate(test_images, test_labels)
# Export neural network
os.chdir('DR_Data')
neural_network.save(file_name)
os.chdir('..')
class Gui:
""" Defines functions necessary for digit recognition GUI.
Gui registers drawing input from user, runs it through neural
network (using the 'run' function defined above), and displays
output.
Note: Current directory needs to contain 'DR_Data' folder with npy
file containing the weights of the neural network
Attributes
----------
design: list
Design of neural network (number of nodes in each layer)
weights: list
Weights of neural network (saved as numpy array by, e.g.,
'install_network' function).
neural_network: NeuralNetwork-object
Neural network created by NeuralNetwork class (see above).
master: tk-object
Window where the interface is created.
button_reset: tk-object
button_recognize: tk-object
drawing_field: tk-object
prediction_field: tk-object
confidence_field: tk-object
alternative_field: tk-object
PIL_drawing: PIL-object
PIL_draw: PIL-object
input_image: np.array
Processed user drawing passed to neural network
prediction: int
Output
confidence: float
Output
alternative: int
Output
Methods
-------
previous_position(event)
Saves last position of the mouse.
draw(event)
Draws line when mouse button 1 is pressed.
run_nn()
Feeds image to neural network and retreives output.
reset()
Empties drawing and feedback fields.
"""
def __init__(self, master, design):
""" Set up layout and basic functionality of interface.
Creates window with input and feedback frame. The input frame contains
two drawing applications: One from tkinter that is used to display the
number that is drawn in the interface and one from PIL that is passed
to the neural network. The feedback frame contains three fields that
display various outputs of the neural network.
Arguments
---------
master: tk-object
Window where the interface is created.
design: list
Design of neural network (number of nodes in each layer)
"""
# Build neural network
self.design = design
os.chdir('DR_Data')
self.weights = np.load('my_network.npy', allow_pickle=True).tolist()
os.chdir('..')
self.neural_network = NeuralNetwork(
design,
weights=self.weights,
bias=True,
)
# Layout and frames
self.master = master
self.master.title('Digit Recognition')
self.master.geometry('450x330')
border_color='white' # Not visible, just for development purposes
input_frame = tk.Frame(master,
highlightbackground=border_color, highlightthickness=2)
input_frame.grid(row=2, column=0)
feedback_frame = tk.Frame(master,
highlightbackground=border_color, highlightthickness=2)
feedback_frame.grid(row=2, column=2)
# Empty frames/labels for layout
empty_frame_1 = tk.Frame(master,
highlightbackground=border_color, highlightthickness=2)
empty_frame_1.grid(row=2, column=1)
empty_label_1 = tk.Label(empty_frame_1,
text=' ', font=("Helvetica", 30))
empty_label_1.pack()
# Buttons
self.button_reset = tk.Button(input_frame,
text='Reset', width=10, command=self.reset)
self.button_reset.pack(side=tk.BOTTOM)
self.button_recognize = tk.Button(input_frame,
text='Recognize!', width=10, command=self.run_nn)
self.button_recognize.pack(side=tk.BOTTOM)
# Drawing field
heading_1 = tk.Label(input_frame,
text='Write your digit!', font=("Helvetica", 15))
heading_1.pack(side=tk.TOP)
self.drawing_field = tk.Canvas(input_frame,
height=250, width=250, cursor='cross',
highlightbackground="black", highlightthickness=2)
self.drawing_field.pack()
self.drawing_field.bind("<Motion>", self.previous_position)
self.drawing_field.bind("<B1-Motion>", self.draw)
# Indication where to draw the digit
self.drawing_field.create_rectangle(70,40, 180,210,
fill='light grey', outline='light grey')
# Feedback field
heading_2 = tk.Label(feedback_frame,
text='Recognized as...', font=("Helvetica", 15))
heading_2.pack(side=tk.TOP)
self.prediction_field = tk.Text(feedback_frame,
height=1, width=1, font=("Helvetica", 50), bg='light grey',
state='disabled')
self.prediction_field.pack(side=tk.TOP)
heading_3 = tk.Label(feedback_frame,
text='Confidence...', font=("Helvetica", 15))
heading_3.pack(side=tk.TOP)
self.confidence_field = tk.Text(feedback_frame,
height=1, width=5, font=("Helvetica", 50), bg='light grey',
state='disabled')
self.confidence_field.pack(side=tk.TOP)
heading_4 = tk.Label(feedback_frame,
text='Alternative...', font=("Helvetica", 15))
heading_4.pack(side=tk.TOP)
self.alternative_field = tk.Text(feedback_frame,
height=1, width=1, font=("Helvetica", 50), bg='light grey',
state='disabled')
self.alternative_field.pack(side=tk.TOP)
# PIL drawing field
self.PIL_drawing = Image.new("RGB",(250,250),(255,255,255))
self.PIL_draw = ImageDraw.Draw(self.PIL_drawing)
def previous_position(self, event):
""" Saves last position of the mouse.
(no matter if mouse button has been pressed or not)
Arguments
---------
event: Mouse input
"""
self.previous_x = event.x
self.previous_y = event.y
def draw(self, event):
""" Draws line when mouse button 1 is pressed.
Connects previous mouse position to current mouse position in both
the tkinter image and the PIL image.
Arguments
---------
event: Mouse input
"""
# Get current position
self.x = event.x
self.y = event.y
# Connect previous and current position
self.drawing_field.create_polygon(self.previous_x, self.previous_y,
self.x, self.y,
width=20, outline='black')
self.PIL_draw.line(((self.previous_x, self.previous_y),
(self.x, self.y)),
(1,1,1), width=20)
# Save as previous position
self.previous_x = self.x
self.previous_y = self.y
def run_nn(self):
""" Feeds image to neural network and retreives output. """
# Convert PIL image to appropriate matrix representation
img_inverted = ImageOps.invert(self.PIL_drawing)
img_resized = img_inverted.resize((28,28), Image.ANTIALIAS)
self.input_image = np.asarray(img_resized)[:,:,0] * (0.99/255) + 0.01
if self.input_image.sum() > 0.01*784: # make sure drawing is not empty
# Forward propagation of neural network
output = self.neural_network.run(self.input_image).T[0]
linear_output = np.log(output/(1-output))
softmax_output = np.exp(linear_output) / np.sum(np.exp(linear_output),
axis=0)
# Extract output from neural network
self.prediction = np.argmax(output)
self.confidence = np.max(softmax_output)
self.alternative = np.argsort(output)[-2]
# Display output
self.prediction_field.configure(state='normal')
self.prediction_field.delete(1.0,tk.END) # reset fields first
self.prediction_field.insert(tk.END, str(self.prediction))
self.prediction_field.configure(state='disabled') # don't allow input
self.confidence_field.configure(state='normal')
self.confidence_field.delete(1.0,tk.END)
self.confidence_field.insert(tk.END, '%.0f%%' %(self.confidence*100))
self.confidence_field.configure(state='disabled')
self.alternative_field.configure(state='normal')
if self.confidence < 0.8:
self.alternative_field.delete(1.0,tk.END)
self.alternative_field.insert(tk.END, str(self.alternative))
else:
self.alternative_field.delete(1.0,tk.END)
self.alternative_field.insert(tk.END, ' ')
self.alternative_field.configure(state='disabled')
def reset(self):
""" Empties drawing and feedback fields. """
# Reset tkinter
self.prediction_field.configure(state='normal')
self.confidence_field.configure(state='normal')
self.alternative_field.configure(state='normal')
self.prediction_field.delete(1.0,tk.END)
self.confidence_field.delete(1.0,tk.END)
self.alternative_field.delete(1.0,tk.END)
self.prediction_field.configure(state='disabled')
self.confidence_field.configure(state='disabled')
self.alternative_field.configure(state='disabled')
self.drawing_field.delete('all')
self.drawing_field.create_rectangle(70,40, 180,210,
fill='light grey', outline='light grey')
# Reset PIL
self.PIL_drawing=Image.new("RGB",(250,250),(255,255,255))
self.PIL_draw=ImageDraw.Draw(self.PIL_drawing)
def run_gui(design=[784,200,100,10]):
""" Runs GUI (defined above) in infinite loop.
Arguments
---------
design: list
Design of neural network (numer of nodes in each layer).
Defaults to [784,200,100,10], just as in 'install_network'
function.
Note: Needs to correspond to design of neural network saved in
npy-file!
"""
root = tk.Tk()
a = Gui(root, design)
root.mainloop() | [
"os.mkdir",
"tkinter.Text",
"PIL.Image.new",
"numpy.sum",
"numpy.load",
"numpy.argmax",
"numpy.argsort",
"os.path.isfile",
"numpy.arange",
"numpy.exp",
"tkinter.Frame",
"numpy.diag",
"tkinter.Label",
"os.chdir",
"tkinter.Button",
"numpy.asfarray",
"os.path.exists",
"PIL.ImageOps.in... | [((11332, 11357), 'os.path.exists', 'os.path.exists', (['"""DR_Data"""'], {}), "('DR_Data')\n", (11346, 11357), False, 'import os\n'), ((12582, 12601), 'os.chdir', 'os.chdir', (['"""DR_Data"""'], {}), "('DR_Data')\n", (12590, 12601), False, 'import os\n'), ((13006, 13020), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (13014, 13020), False, 'import os\n'), ((13425, 13450), 'numpy.asfarray', 'np.asfarray', (['train_labels'], {}), '(train_labels)\n', (13436, 13450), True, 'import numpy as np\n'), ((13469, 13493), 'numpy.asfarray', 'np.asfarray', (['test_labels'], {}), '(test_labels)\n', (13480, 13493), True, 'import numpy as np\n'), ((15487, 15506), 'os.chdir', 'os.chdir', (['"""DR_Data"""'], {}), "('DR_Data')\n", (15495, 15506), False, 'import os\n'), ((15546, 15560), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (15554, 15560), False, 'import os\n'), ((25545, 25552), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (25550, 25552), True, 'import tkinter as tk\n'), ((4581, 4598), 'numpy.arange', 'np.arange', (['epochs'], {}), '(epochs)\n', (4590, 4598), True, 'import numpy as np\n'), ((8370, 8426), 'numpy.zeros', 'np.zeros', (['[target_data.shape[-1], target_data.shape[-1]]'], {}), '([target_data.shape[-1], target_data.shape[-1]])\n', (8378, 8426), True, 'import numpy as np\n'), ((9066, 9095), 'numpy.sum', 'np.sum', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (9072, 9095), True, 'import numpy as np\n'), ((9385, 9397), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (9393, 9397), True, 'import numpy as np\n'), ((9415, 9447), 'numpy.arange', 'np.arange', (['target_data.shape[-1]'], {}), '(target_data.shape[-1])\n', (9424, 9447), True, 'import numpy as np\n'), ((9681, 9693), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (9689, 9693), True, 'import numpy as np\n'), ((9711, 9743), 'numpy.arange', 'np.arange', (['target_data.shape[-1]'], {}), '(target_data.shape[-1])\n', (9720, 9743), True, 'import numpy as np\n'), ((10049, 10081), 'numpy.arange', 'np.arange', (['target_data.shape[-1]'], {}), '(target_data.shape[-1])\n', (10058, 10081), True, 'import numpy as np\n'), ((10628, 10662), 'os.path.isfile', 'os.path.isfile', (["(file_name + '.npy')"], {}), "(file_name + '.npy')\n", (10642, 10662), False, 'import os\n'), ((11391, 11410), 'os.mkdir', 'os.mkdir', (['"""DR_Data"""'], {}), "('DR_Data')\n", (11399, 11410), False, 'import os\n'), ((12658, 12702), 'gzip.open', 'gzip.open', (['"""train-images-idx3-ubyte.gz"""', '"""r"""'], {}), "('train-images-idx3-ubyte.gz', 'r')\n", (12667, 12702), False, 'import gzip\n'), ((12759, 12803), 'gzip.open', 'gzip.open', (['"""train-labels-idx1-ubyte.gz"""', '"""r"""'], {}), "('train-labels-idx1-ubyte.gz', 'r')\n", (12768, 12803), False, 'import gzip\n'), ((12859, 12902), 'gzip.open', 'gzip.open', (['"""t10k-images-idx3-ubyte.gz"""', '"""r"""'], {}), "('t10k-images-idx3-ubyte.gz', 'r')\n", (12868, 12902), False, 'import gzip\n'), ((12958, 13001), 'gzip.open', 'gzip.open', (['"""t10k-labels-idx1-ubyte.gz"""', '"""r"""'], {}), "('t10k-labels-idx1-ubyte.gz', 'r')\n", (12967, 13001), False, 'import gzip\n'), ((13513, 13544), 'numpy.array', 'np.array', (['train_labels'], {'ndmin': '(2)'}), '(train_labels, ndmin=2)\n', (13521, 13544), True, 'import numpy as np\n'), ((13565, 13595), 'numpy.array', 'np.array', (['test_labels'], {'ndmin': '(2)'}), '(test_labels, ndmin=2)\n', (13573, 13595), True, 'import numpy as np\n'), ((17838, 17857), 'os.chdir', 'os.chdir', (['"""DR_Data"""'], {}), "('DR_Data')\n", (17846, 17857), False, 'import os\n'), ((17943, 17957), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (17951, 17957), False, 'import os\n'), ((18345, 18417), 'tkinter.Frame', 'tk.Frame', (['master'], {'highlightbackground': 'border_color', 'highlightthickness': '(2)'}), '(master, highlightbackground=border_color, highlightthickness=2)\n', (18353, 18417), True, 'import tkinter as tk\n'), ((18498, 18570), 'tkinter.Frame', 'tk.Frame', (['master'], {'highlightbackground': 'border_color', 'highlightthickness': '(2)'}), '(master, highlightbackground=border_color, highlightthickness=2)\n', (18506, 18570), True, 'import tkinter as tk\n'), ((18703, 18775), 'tkinter.Frame', 'tk.Frame', (['master'], {'highlightbackground': 'border_color', 'highlightthickness': '(2)'}), '(master, highlightbackground=border_color, highlightthickness=2)\n', (18711, 18775), True, 'import tkinter as tk\n'), ((18857, 18914), 'tkinter.Label', 'tk.Label', (['empty_frame_1'], {'text': '""" """', 'font': "('Helvetica', 30)"}), "(empty_frame_1, text=' ', font=('Helvetica', 30))\n", (18865, 18914), True, 'import tkinter as tk\n'), ((19012, 19078), 'tkinter.Button', 'tk.Button', (['input_frame'], {'text': '"""Reset"""', 'width': '(10)', 'command': 'self.reset'}), "(input_frame, text='Reset', width=10, command=self.reset)\n", (19021, 19078), True, 'import tkinter as tk\n'), ((19171, 19243), 'tkinter.Button', 'tk.Button', (['input_frame'], {'text': '"""Recognize!"""', 'width': '(10)', 'command': 'self.run_nn'}), "(input_frame, text='Recognize!', width=10, command=self.run_nn)\n", (19180, 19243), True, 'import tkinter as tk\n'), ((19353, 19424), 'tkinter.Label', 'tk.Label', (['input_frame'], {'text': '"""Write your digit!"""', 'font': "('Helvetica', 15)"}), "(input_frame, text='Write your digit!', font=('Helvetica', 15))\n", (19361, 19424), True, 'import tkinter as tk\n'), ((19503, 19619), 'tkinter.Canvas', 'tk.Canvas', (['input_frame'], {'height': '(250)', 'width': '(250)', 'cursor': '"""cross"""', 'highlightbackground': '"""black"""', 'highlightthickness': '(2)'}), "(input_frame, height=250, width=250, cursor='cross',\n highlightbackground='black', highlightthickness=2)\n", (19512, 19619), True, 'import tkinter as tk\n'), ((20017, 20090), 'tkinter.Label', 'tk.Label', (['feedback_frame'], {'text': '"""Recognized as..."""', 'font': "('Helvetica', 15)"}), "(feedback_frame, text='Recognized as...', font=('Helvetica', 15))\n", (20025, 20090), True, 'import tkinter as tk\n'), ((20172, 20278), 'tkinter.Text', 'tk.Text', (['feedback_frame'], {'height': '(1)', 'width': '(1)', 'font': "('Helvetica', 50)", 'bg': '"""light grey"""', 'state': '"""disabled"""'}), "(feedback_frame, height=1, width=1, font=('Helvetica', 50), bg=\n 'light grey', state='disabled')\n", (20179, 20278), True, 'import tkinter as tk\n'), ((20377, 20447), 'tkinter.Label', 'tk.Label', (['feedback_frame'], {'text': '"""Confidence..."""', 'font': "('Helvetica', 15)"}), "(feedback_frame, text='Confidence...', font=('Helvetica', 15))\n", (20385, 20447), True, 'import tkinter as tk\n'), ((20529, 20635), 'tkinter.Text', 'tk.Text', (['feedback_frame'], {'height': '(1)', 'width': '(5)', 'font': "('Helvetica', 50)", 'bg': '"""light grey"""', 'state': '"""disabled"""'}), "(feedback_frame, height=1, width=5, font=('Helvetica', 50), bg=\n 'light grey', state='disabled')\n", (20536, 20635), True, 'import tkinter as tk\n'), ((20733, 20804), 'tkinter.Label', 'tk.Label', (['feedback_frame'], {'text': '"""Alternative..."""', 'font': "('Helvetica', 15)"}), "(feedback_frame, text='Alternative...', font=('Helvetica', 15))\n", (20741, 20804), True, 'import tkinter as tk\n'), ((20887, 20993), 'tkinter.Text', 'tk.Text', (['feedback_frame'], {'height': '(1)', 'width': '(1)', 'font': "('Helvetica', 50)", 'bg': '"""light grey"""', 'state': '"""disabled"""'}), "(feedback_frame, height=1, width=1, font=('Helvetica', 50), bg=\n 'light grey', state='disabled')\n", (20894, 20993), True, 'import tkinter as tk\n'), ((21127, 21172), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(250, 250)', '(255, 255, 255)'], {}), "('RGB', (250, 250), (255, 255, 255))\n", (21136, 21172), False, 'from PIL import Image, ImageDraw, ImageOps\n'), ((21192, 21224), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['self.PIL_drawing'], {}), '(self.PIL_drawing)\n', (21206, 21224), False, 'from PIL import Image, ImageDraw, ImageOps\n'), ((22497, 22530), 'PIL.ImageOps.invert', 'ImageOps.invert', (['self.PIL_drawing'], {}), '(self.PIL_drawing)\n', (22512, 22530), False, 'from PIL import Image, ImageDraw, ImageOps\n'), ((25052, 25097), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(250, 250)', '(255, 255, 255)'], {}), "('RGB', (250, 250), (255, 255, 255))\n", (25061, 25097), False, 'from PIL import Image, ImageDraw, ImageOps\n'), ((25115, 25147), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['self.PIL_drawing'], {}), '(self.PIL_drawing)\n', (25129, 25147), False, 'from PIL import Image, ImageDraw, ImageOps\n'), ((5664, 5694), 'numpy.array', 'np.array', (['target_data'], {'ndmin': '(2)'}), '(target_data, ndmin=2)\n', (5672, 5694), True, 'import numpy as np\n'), ((9133, 9163), 'numpy.diag', 'np.diag', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (9140, 9163), True, 'import numpy as np\n'), ((10591, 10615), 'numpy.asarray', 'np.asarray', (['self.weights'], {}), '(self.weights)\n', (10601, 10615), True, 'import numpy as np\n'), ((12107, 12159), 'os.path.isfile', 'os.path.isfile', (['"""DR_Data/train-images-idx3-ubyte.gz"""'], {}), "('DR_Data/train-images-idx3-ubyte.gz')\n", (12121, 12159), False, 'import os\n'), ((12177, 12229), 'os.path.isfile', 'os.path.isfile', (['"""DR_Data/train-labels-idx1-ubyte.gz"""'], {}), "('DR_Data/train-labels-idx1-ubyte.gz')\n", (12191, 12229), False, 'import os\n'), ((12247, 12298), 'os.path.isfile', 'os.path.isfile', (['"""DR_Data/t10k-images-idx3-ubyte.gz"""'], {}), "('DR_Data/t10k-images-idx3-ubyte.gz')\n", (12261, 12298), False, 'import os\n'), ((12316, 12367), 'os.path.isfile', 'os.path.isfile', (['"""DR_Data/t10k-labels-idx1-ubyte.gz"""'], {}), "('DR_Data/t10k-labels-idx1-ubyte.gz')\n", (12330, 12367), False, 'import os\n'), ((22906, 22935), 'numpy.log', 'np.log', (['(output / (1 - output))'], {}), '(output / (1 - output))\n', (22912, 22935), True, 'import numpy as np\n'), ((23120, 23137), 'numpy.argmax', 'np.argmax', (['output'], {}), '(output)\n', (23129, 23137), True, 'import numpy as np\n'), ((23168, 23190), 'numpy.max', 'np.max', (['softmax_output'], {}), '(softmax_output)\n', (23174, 23190), True, 'import numpy as np\n'), ((2205, 2215), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (2211, 2215), True, 'import numpy as np\n'), ((3501, 3512), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (3509, 3512), True, 'import numpy as np\n'), ((8626, 8659), 'numpy.array', 'np.array', (['target_data[i]'], {'ndmin': '(2)'}), '(target_data[i], ndmin=2)\n', (8634, 8659), True, 'import numpy as np\n'), ((13618, 13631), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (13627, 13631), True, 'import numpy as np\n'), ((13685, 13698), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (13694, 13698), True, 'import numpy as np\n'), ((17881, 17925), 'numpy.load', 'np.load', (['"""my_network.npy"""'], {'allow_pickle': '(True)'}), "('my_network.npy', allow_pickle=True)\n", (17888, 17925), True, 'import numpy as np\n'), ((22961, 22982), 'numpy.exp', 'np.exp', (['linear_output'], {}), '(linear_output)\n', (22967, 22982), True, 'import numpy as np\n'), ((23222, 23240), 'numpy.argsort', 'np.argsort', (['output'], {}), '(output)\n', (23232, 23240), True, 'import numpy as np\n'), ((3604, 3678), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', '[self.design[i + 1], self.design[i] + self.bias]'], {}), '(-1, 1, [self.design[i + 1], self.design[i] + self.bias])\n', (3621, 3678), True, 'import numpy as np\n'), ((5601, 5627), 'numpy.append', 'np.append', (['(1)', 'input_vector'], {}), '(1, input_vector)\n', (5610, 5627), True, 'import numpy as np\n'), ((7140, 7166), 'numpy.append', 'np.append', (['(1)', 'input_vector'], {}), '(1, input_vector)\n', (7149, 7166), True, 'import numpy as np\n'), ((8889, 8913), 'numpy.max', 'np.max', (['confusion_result'], {}), '(confusion_result)\n', (8895, 8913), True, 'import numpy as np\n'), ((9561, 9596), 'numpy.sum', 'np.sum', (['self.confusion_matrix[i, :]'], {}), '(self.confusion_matrix[i, :])\n', (9567, 9596), True, 'import numpy as np\n'), ((9863, 9898), 'numpy.sum', 'np.sum', (['self.confusion_matrix[:, i]'], {}), '(self.confusion_matrix[:, i])\n', (9869, 9898), True, 'import numpy as np\n'), ((22626, 22649), 'numpy.asarray', 'np.asarray', (['img_resized'], {}), '(img_resized)\n', (22636, 22649), True, 'import numpy as np\n'), ((22992, 23013), 'numpy.exp', 'np.exp', (['linear_output'], {}), '(linear_output)\n', (22998, 23013), True, 'import numpy as np\n'), ((6093, 6129), 'numpy.append', 'np.append', (['(1)', 'self.activation[i + 1]'], {}), '(1, self.activation[i + 1])\n', (6102, 6129), True, 'import numpy as np\n'), ((7597, 7633), 'numpy.append', 'np.append', (['(1)', 'self.activation[i + 1]'], {}), '(1, self.activation[i + 1])\n', (7606, 7633), True, 'import numpy as np\n')] |
import base64
import json
import os
import pickle
from typing import List
from docarray import Document, DocumentArray
from docarray.document.mixins.multimodal import AttributeType
from docarray.types.multimodal import Text, Image, Audio, Field, JSON
from docarray.types.multimodal import dataclass
import pytest
import numpy as np
cur_dir = os.path.dirname(os.path.abspath(__file__))
AUDIO_URI = os.path.join(cur_dir, 'toydata/hello.wav')
IMAGE_URI = os.path.join(cur_dir, 'toydata/test.png')
def _assert_doc_schema(doc, schema):
for field, attr_type, _type, position in schema:
assert doc._metadata['multi_modal_schema'][field]['attribute_type'] == attr_type
assert doc._metadata['multi_modal_schema'][field]['type'] == _type
if position is not None:
assert doc._metadata['multi_modal_schema'][field]['position'] == position
else:
assert 'position' not in doc._metadata['multi_modal_schema'][field]
def test_simple():
@dataclass
class MMDocument:
title: Text
image: Image
version: int
obj = MMDocument(title='hello world', image=np.random.rand(10, 10, 3), version=20)
doc = Document.from_dataclass(obj)
assert doc.chunks[0].text == 'hello world'
assert doc.chunks[1].tensor.shape == (10, 10, 3)
assert doc.tags['version'] == 20
assert 'multi_modal_schema' in doc._metadata
expected_schema = [
('title', AttributeType.DOCUMENT, 'Text', 0),
('image', AttributeType.DOCUMENT, 'Image', 1),
('version', AttributeType.PRIMITIVE, 'int', None),
]
_assert_doc_schema(doc, expected_schema)
translated_obj = MMDocument.from_document(doc)
assert translated_obj == obj
def test_simple_default():
@dataclass
class MMDocument:
title: Text = 'hello world'
image: Image = IMAGE_URI
version: int = 1
obj = MMDocument()
assert obj.title == 'hello world'
assert obj.image == IMAGE_URI
assert obj.version == 1
doc = Document.from_dataclass(obj)
assert doc.chunks[0].text == 'hello world'
assert doc.chunks[1].tensor.shape == (85, 152, 3)
assert doc.tags['version'] == 1
obj = MMDocument(title='custom text')
assert obj.title == 'custom text'
assert obj.image == IMAGE_URI
assert obj.version == 1
def test_nested():
@dataclass
class SubDocument:
image: Image
date: str
version: float
@dataclass
class MMDocument:
sub_doc: SubDocument
value: str
image: Image
obj = MMDocument(
sub_doc=SubDocument(image=IMAGE_URI, date='10.03.2022', version=1.5),
image=np.random.rand(10, 10, 3),
value='abc',
)
doc = Document.from_dataclass(obj)
assert doc.tags['value'] == 'abc'
assert doc.chunks[0].tags['date'] == '10.03.2022'
assert doc.chunks[0].tags['version'] == 1.5
assert doc.chunks[0].chunks[0].tensor.shape == (85, 152, 3)
assert doc.chunks[1].tensor.shape == (10, 10, 3)
assert 'multi_modal_schema' in doc._metadata
expected_schema = [
('sub_doc', AttributeType.NESTED, 'SubDocument', 0),
('image', AttributeType.DOCUMENT, 'Image', 1),
('value', AttributeType.PRIMITIVE, 'str', None),
]
_assert_doc_schema(doc, expected_schema)
translated_obj = MMDocument.from_document(doc)
assert translated_obj == obj
def test_with_tags():
@dataclass
class MMDocument:
attr1: str
attr2: int
attr3: float
attr4: bool
attr5: bytes
obj = MMDocument(attr1='123', attr2=10, attr3=1.1, attr4=True, attr5=b'ab1234')
doc = Document.from_dataclass(obj)
assert doc.tags['attr1'] == '123'
assert doc.tags['attr2'] == 10
assert doc.tags['attr3'] == 1.1
assert doc.tags['attr4'] == True
assert doc.tags['attr5'] == base64.b64encode(b'ab1234').decode()
assert 'multi_modal_schema' in doc._metadata
expected_schema = [
('attr1', AttributeType.PRIMITIVE, 'str', None),
('attr2', AttributeType.PRIMITIVE, 'int', None),
('attr3', AttributeType.PRIMITIVE, 'float', None),
('attr4', AttributeType.PRIMITIVE, 'bool', None),
('attr5', AttributeType.PRIMITIVE, 'bytes', None),
]
_assert_doc_schema(doc, expected_schema)
translated_obj = MMDocument.from_document(doc)
assert translated_obj == obj
def test_iterable_doc():
@dataclass
class SocialPost:
comments: List[str]
ratings: List[int]
images: List[Image]
obj = SocialPost(
comments=['hello world', 'goodbye world'],
ratings=[1, 5, 4, 2],
images=[np.random.rand(10, 10, 3) for _ in range(3)],
)
doc = Document.from_dataclass(obj)
assert doc.tags['comments'] == ['hello world', 'goodbye world']
assert doc.tags['ratings'] == [1, 5, 4, 2]
assert len(doc.chunks[0].chunks) == 3
for image_doc in doc.chunks[0].chunks:
assert image_doc.tensor.shape == (10, 10, 3)
assert 'multi_modal_schema' in doc._metadata
expected_schema = [
('comments', AttributeType.ITERABLE_PRIMITIVE, 'List[str]', None),
('ratings', AttributeType.ITERABLE_PRIMITIVE, 'List[int]', None),
('images', AttributeType.ITERABLE_DOCUMENT, 'List[Image]', 0),
]
_assert_doc_schema(doc, expected_schema)
translated_obj = SocialPost.from_document(doc)
assert translated_obj == obj
def test_iterable_nested():
@dataclass
class SubtitleDocument:
text: Text
frames: List[int]
@dataclass
class VideoDocument:
frames: List[Image]
subtitles: List[SubtitleDocument]
obj = VideoDocument(
frames=[np.random.rand(10, 10, 3) for _ in range(3)],
subtitles=[
SubtitleDocument(text='subtitle 0', frames=[0]),
SubtitleDocument(text='subtitle 1', frames=[1, 2]),
],
)
doc = Document.from_dataclass(obj)
assert len(doc.chunks) == 2
assert len(doc.chunks[0].chunks) == 3
for image_doc in doc.chunks[0].chunks:
assert image_doc.tensor.shape == (10, 10, 3)
assert len(doc.chunks[1].chunks) == 2
for i, subtitle_doc in enumerate(doc.chunks[1].chunks):
assert subtitle_doc.chunks[0].text == f'subtitle {i}'
assert 'multi_modal_schema' in doc._metadata
expected_schema = [
('frames', AttributeType.ITERABLE_DOCUMENT, 'List[Image]', 0),
('subtitles', AttributeType.ITERABLE_NESTED, 'List[SubtitleDocument]', 1),
]
_assert_doc_schema(doc, expected_schema)
expected_nested_schema = [
('text', AttributeType.DOCUMENT, 'Text', 0),
('frames', AttributeType.ITERABLE_PRIMITIVE, 'List[int]', None),
]
for subtitle in doc.chunks[1].chunks:
_assert_doc_schema(subtitle, expected_nested_schema)
translated_obj = VideoDocument.from_document(doc)
assert translated_obj == obj
def test_get_multi_modal_attribute():
@dataclass
class MMDocument:
image: Image
texts: List[Text]
audio: Audio
primitive: int
mm_doc = MMDocument(
image=np.random.rand(10, 10, 3),
texts=['text 1', 'text 2'],
audio=AUDIO_URI,
primitive=1,
)
doc = Document.from_dataclass(mm_doc)
images = doc.get_multi_modal_attribute('image')
texts = doc.get_multi_modal_attribute('texts')
audios = doc.get_multi_modal_attribute('audio')
assert len(images) == 1
assert len(texts) == 2
assert len(audios) == 1
assert images[0].tensor.shape == (10, 10, 3)
assert texts[0].text == 'text 1'
assert audios[0].tensor.shape == (15417,)
with pytest.raises(ValueError):
doc.get_multi_modal_attribute('primitive')
@pytest.mark.parametrize(
'text_selector',
[
'@.[text]',
'@r.[text]',
'@r. [ text]',
'@r:.[text]',
'@.text',
'@r.text',
'@r . text',
],
)
@pytest.mark.parametrize(
'audio_selector',
['@.[audio]', '@r.[audio]', '@r. [ audio]', '@r:.[audio]', '@.audio', '@ . audio'],
)
def test_traverse_simple(text_selector, audio_selector):
from PIL.Image import open as PIL_open
@dataclass
class MMDocument:
text: Text
audio: Audio
image: Image
mm_docs = DocumentArray(
[
Document.from_dataclass(
MMDocument(text=f'text {i}', audio=AUDIO_URI, image=PIL_open(IMAGE_URI))
)
for i in range(5)
]
)
assert len(mm_docs[text_selector]) == 5
for i, doc in enumerate(mm_docs[text_selector]):
assert doc.text == f'text {i}'
assert len(mm_docs[audio_selector]) == 5
for i, doc in enumerate(mm_docs[audio_selector]):
assert doc.tensor.shape == (15417,)
assert len(mm_docs['@r.[image]']) == 5
for i, doc in enumerate(mm_docs['@r.[image]']):
assert doc.tensor.shape == (85, 152, 3)
def test_traverse_attributes():
@dataclass
class MMDocument:
attr1: Text
attr2: Audio
attr3: Image
mm_docs = DocumentArray(
[
Document.from_dataclass(
MMDocument(
attr1='text',
attr2=AUDIO_URI,
attr3=np.random.rand(10, 10, 3),
)
)
for _ in range(5)
]
)
assert len(mm_docs['@.[attr1,attr3]']) == 10
for i, doc in enumerate(mm_docs['@.[attr1,attr3]']):
if i % 2 == 0:
assert doc.text == 'text'
else:
assert doc.tensor.shape == (10, 10, 3)
@pytest.mark.parametrize('selector', ['@r-3:.[attr]', '@r[-3:].[attr]', '@r[-3:].attr'])
def test_traverse_slice(selector):
@dataclass
class MMDocument:
attr: Text
mm_docs = DocumentArray(
[
Document.from_dataclass(
MMDocument(
attr=f'text {i}',
)
)
for i in range(5)
]
)
assert len(mm_docs[selector]) == 3
for i, doc in enumerate(mm_docs[selector], start=2):
assert doc.text == f'text {i}'
def test_traverse_iterable():
@dataclass
class MMDocument:
attr1: List[Text]
attr2: List[Audio]
mm_da = DocumentArray(
[
Document.from_dataclass(
MMDocument(attr1=['text 1', 'text 2', 'text 3'], attr2=[AUDIO_URI] * 2)
),
Document.from_dataclass(
MMDocument(attr1=['text 3', 'text 4'], attr2=[AUDIO_URI] * 3)
),
]
)
assert len(mm_da['@.[attr1]']) == 5
assert len(mm_da['@.[attr2]']) == 5
assert len(mm_da['@.[attr1]:1']) == 2
assert len(mm_da['@.[attr1]:1,.[attr2]-2:']) == 6
for i, text_doc in enumerate(mm_da['@.[attr1]:2'], start=1):
assert text_doc.text == f'text {i}'
for i, blob_doc in enumerate(mm_da['@.[attr2]-2:'], start=1):
assert blob_doc.tensor.shape == (15417,)
def test_traverse_chunks_attribute():
@dataclass
class MMDocument:
attr: Text
da = DocumentArray.empty(5)
for i, d in enumerate(da):
d.chunks.extend(
[Document.from_dataclass(MMDocument(attr=f'text {i}{j}')) for j in range(5)]
)
assert len(da['@r:3c:2.[attr]']) == 6
for i, doc in enumerate(da['@r:3c:2.[attr]']):
assert doc.text == f'text {int(i / 2)}{i % 2}'
def test_paths_separator():
@dataclass
class MMDocument:
attr0: Text
attr1: Text
attr2: Text
attr3: Text
attr4: Text
da = DocumentArray(
[
Document.from_dataclass(
MMDocument(**{f'attr{i}': f'text {i}' for i in range(5)})
)
for _ in range(3)
]
)
assert len(da['@r:2.[attr0,attr2,attr3],r:2.[attr1,attr4]']) == 10
flattened = da['@r.[attr0,attr1,attr2],.[attr3,attr4]']
for i in range(9):
if i % 3 == 0:
assert flattened[i].text == 'text 0'
elif i % 3 == 1:
assert flattened[i].text == 'text 1'
else:
assert flattened[i].text == 'text 2'
for i in range(9, 15):
if i % 2 == 1:
assert flattened[i].text == 'text 3'
else:
assert flattened[i].text == 'text 4'
def test_proto_serialization():
@dataclass
class MMDocument:
title: Text
image: Image
version: int
obj = MMDocument(title='hello world', image=np.random.rand(10, 10, 3), version=20)
doc = Document.from_dataclass(obj)
proto = doc.to_protobuf()
assert proto._metadata is not None
assert proto._metadata['multi_modal_schema']
deserialized_doc = Document.from_protobuf(proto)
assert deserialized_doc.chunks[0].text == 'hello world'
assert deserialized_doc.chunks[1].tensor.shape == (10, 10, 3)
assert deserialized_doc.tags['version'] == 20
assert 'multi_modal_schema' in deserialized_doc._metadata
expected_schema = [
('title', AttributeType.DOCUMENT, 'Text', 0),
('image', AttributeType.DOCUMENT, 'Image', 1),
('version', AttributeType.PRIMITIVE, 'int', None),
]
_assert_doc_schema(deserialized_doc, expected_schema)
translated_obj = MMDocument.from_document(doc)
assert translated_obj == obj
def test_json_type():
@dataclass
class MMDocument:
attr: JSON
inp = {'a': 123, 'b': 'abc', 'c': 1.1}
obj = MMDocument(attr=inp)
doc = Document.from_dataclass(obj)
assert doc.chunks[0].tags['attr'] == inp
translated_obj = MMDocument.from_document(doc)
assert translated_obj == obj
obj = MMDocument(attr=json.dumps(inp))
doc = Document.from_dataclass(obj)
assert doc.chunks[0].tags['attr'] == inp
translated_obj = MMDocument.from_document(doc)
assert translated_obj == obj
def test_custom_field_type():
from PIL.Image import Image as PILImage
from PIL.Image import open as PIL_open
def ndarray_serializer(inp, attribute_name, doc: 'Document'):
doc.blob = base64.b64encode(inp)
def ndarray_deserializer(attribute_name, doc: 'Document'):
return np.frombuffer(base64.decodebytes(doc.blob), dtype=np.float64)
def pil_image_serializer(inp, attribute_name, doc: 'Document'):
doc.blob = pickle.dumps(inp)
def pil_image_deserializer(attribute_name, doc: 'Document'):
return pickle.loads(doc.blob)
@dataclass
class MMDocument:
base64_encoded_ndarray: str = Field(
serializer=ndarray_serializer, deserializer=ndarray_deserializer
)
pickled_image: PILImage = Field(
serializer=pil_image_serializer, deserializer=pil_image_deserializer
)
obj = MMDocument(
base64_encoded_ndarray=np.array([1, 2, 3], dtype=np.float64),
pickled_image=PIL_open(IMAGE_URI),
)
doc = Document.from_dataclass(obj)
assert doc.chunks[0].blob is not None
assert doc.chunks[1].blob is not None
translated_obj: MMDocument = MMDocument.from_document(doc)
assert isinstance(translated_obj.pickled_image, PILImage)
assert isinstance(translated_obj.base64_encoded_ndarray, np.ndarray)
assert (obj.base64_encoded_ndarray == translated_obj.base64_encoded_ndarray).all()
assert (
np.array(obj.pickled_image).shape
== np.array(translated_obj.pickled_image).shape
)
def test_invalid_type_annotations():
@dataclass
class MMDocument:
attr: List
inp = ['something']
obj = MMDocument(attr=inp)
with pytest.raises(Exception) as exc_info:
doc = Document.from_dataclass(obj)
assert exc_info.value.args[0] == 'Unsupported type annotation'
assert str(exc_info.value) == 'Unsupported type annotation'
def test_not_data_class():
class MMDocument:
pass
obj = MMDocument()
with pytest.raises(Exception) as exc_info:
doc = Document.from_dataclass(obj)
assert exc_info.value.args[0] == 'Object MMDocument is not a dataclass instance'
assert str(exc_info.value) == 'Object MMDocument is not a dataclass instance'
| [
"pickle.loads",
"os.path.abspath",
"docarray.types.multimodal.Field",
"json.dumps",
"docarray.Document.from_protobuf",
"PIL.Image.open",
"pytest.raises",
"docarray.DocumentArray.empty",
"base64.b64encode",
"numpy.array",
"numpy.random.rand",
"pytest.mark.parametrize",
"docarray.Document.from... | [((400, 442), 'os.path.join', 'os.path.join', (['cur_dir', '"""toydata/hello.wav"""'], {}), "(cur_dir, 'toydata/hello.wav')\n", (412, 442), False, 'import os\n'), ((455, 496), 'os.path.join', 'os.path.join', (['cur_dir', '"""toydata/test.png"""'], {}), "(cur_dir, 'toydata/test.png')\n", (467, 496), False, 'import os\n'), ((7776, 7910), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""text_selector"""', "['@.[text]', '@r.[text]', '@r. [ text]', '@r:.[text]', '@.text', '@r.text',\n '@r . text']"], {}), "('text_selector', ['@.[text]', '@r.[text]',\n '@r. [ text]', '@r:.[text]', '@.text', '@r.text', '@r . text'])\n", (7799, 7910), False, 'import pytest\n'), ((7982, 8111), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""audio_selector"""', "['@.[audio]', '@r.[audio]', '@r. [ audio]', '@r:.[audio]', '@.audio',\n '@ . audio']"], {}), "('audio_selector', ['@.[audio]', '@r.[audio]',\n '@r. [ audio]', '@r:.[audio]', '@.audio', '@ . audio'])\n", (8005, 8111), False, 'import pytest\n'), ((9645, 9736), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""selector"""', "['@r-3:.[attr]', '@r[-3:].[attr]', '@r[-3:].attr']"], {}), "('selector', ['@r-3:.[attr]', '@r[-3:].[attr]',\n '@r[-3:].attr'])\n", (9668, 9736), False, 'import pytest\n'), ((360, 385), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (375, 385), False, 'import os\n'), ((1184, 1212), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (1207, 1212), False, 'from docarray import Document, DocumentArray\n'), ((2023, 2051), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (2046, 2051), False, 'from docarray import Document, DocumentArray\n'), ((2740, 2768), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (2763, 2768), False, 'from docarray import Document, DocumentArray\n'), ((3669, 3697), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (3692, 3697), False, 'from docarray import Document, DocumentArray\n'), ((4744, 4772), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (4767, 4772), False, 'from docarray import Document, DocumentArray\n'), ((5947, 5975), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (5970, 5975), False, 'from docarray import Document, DocumentArray\n'), ((7281, 7312), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['mm_doc'], {}), '(mm_doc)\n', (7304, 7312), False, 'from docarray import Document, DocumentArray\n'), ((11137, 11159), 'docarray.DocumentArray.empty', 'DocumentArray.empty', (['(5)'], {}), '(5)\n', (11156, 11159), False, 'from docarray import Document, DocumentArray\n'), ((12595, 12623), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (12618, 12623), False, 'from docarray import Document, DocumentArray\n'), ((12767, 12796), 'docarray.Document.from_protobuf', 'Document.from_protobuf', (['proto'], {}), '(proto)\n', (12789, 12796), False, 'from docarray import Document, DocumentArray\n'), ((13544, 13572), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (13567, 13572), False, 'from docarray import Document, DocumentArray\n'), ((13757, 13785), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (13780, 13785), False, 'from docarray import Document, DocumentArray\n'), ((14948, 14976), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (14971, 14976), False, 'from docarray import Document, DocumentArray\n'), ((7695, 7720), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7708, 7720), False, 'import pytest\n'), ((14120, 14141), 'base64.b64encode', 'base64.b64encode', (['inp'], {}), '(inp)\n', (14136, 14141), False, 'import base64\n'), ((14371, 14388), 'pickle.dumps', 'pickle.dumps', (['inp'], {}), '(inp)\n', (14383, 14388), False, 'import pickle\n'), ((14470, 14492), 'pickle.loads', 'pickle.loads', (['doc.blob'], {}), '(doc.blob)\n', (14482, 14492), False, 'import pickle\n'), ((14569, 14640), 'docarray.types.multimodal.Field', 'Field', ([], {'serializer': 'ndarray_serializer', 'deserializer': 'ndarray_deserializer'}), '(serializer=ndarray_serializer, deserializer=ndarray_deserializer)\n', (14574, 14640), False, 'from docarray.types.multimodal import Text, Image, Audio, Field, JSON\n'), ((14697, 14772), 'docarray.types.multimodal.Field', 'Field', ([], {'serializer': 'pil_image_serializer', 'deserializer': 'pil_image_deserializer'}), '(serializer=pil_image_serializer, deserializer=pil_image_deserializer)\n', (14702, 14772), False, 'from docarray.types.multimodal import Text, Image, Audio, Field, JSON\n'), ((15627, 15651), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (15640, 15651), False, 'import pytest\n'), ((15679, 15707), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (15702, 15707), False, 'from docarray import Document, DocumentArray\n'), ((15937, 15961), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (15950, 15961), False, 'import pytest\n'), ((15989, 16017), 'docarray.Document.from_dataclass', 'Document.from_dataclass', (['obj'], {}), '(obj)\n', (16012, 16017), False, 'from docarray import Document, DocumentArray\n'), ((1135, 1160), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), '(10, 10, 3)\n', (1149, 1160), True, 'import numpy as np\n'), ((2675, 2700), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), '(10, 10, 3)\n', (2689, 2700), True, 'import numpy as np\n'), ((7155, 7180), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), '(10, 10, 3)\n', (7169, 7180), True, 'import numpy as np\n'), ((12546, 12571), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), '(10, 10, 3)\n', (12560, 12571), True, 'import numpy as np\n'), ((13730, 13745), 'json.dumps', 'json.dumps', (['inp'], {}), '(inp)\n', (13740, 13745), False, 'import json\n'), ((14235, 14263), 'base64.decodebytes', 'base64.decodebytes', (['doc.blob'], {}), '(doc.blob)\n', (14253, 14263), False, 'import base64\n'), ((14849, 14886), 'numpy.array', 'np.array', (['[1, 2, 3]'], {'dtype': 'np.float64'}), '([1, 2, 3], dtype=np.float64)\n', (14857, 14886), True, 'import numpy as np\n'), ((14910, 14929), 'PIL.Image.open', 'PIL_open', (['IMAGE_URI'], {}), '(IMAGE_URI)\n', (14918, 14929), True, 'from PIL.Image import open as PIL_open\n'), ((15371, 15398), 'numpy.array', 'np.array', (['obj.pickled_image'], {}), '(obj.pickled_image)\n', (15379, 15398), True, 'import numpy as np\n'), ((15416, 15454), 'numpy.array', 'np.array', (['translated_obj.pickled_image'], {}), '(translated_obj.pickled_image)\n', (15424, 15454), True, 'import numpy as np\n'), ((3876, 3903), 'base64.b64encode', 'base64.b64encode', (["b'ab1234'"], {}), "(b'ab1234')\n", (3892, 3903), False, 'import base64\n'), ((4681, 4706), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), '(10, 10, 3)\n', (4695, 4706), True, 'import numpy as np\n'), ((5728, 5753), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), '(10, 10, 3)\n', (5742, 5753), True, 'import numpy as np\n'), ((8463, 8482), 'PIL.Image.open', 'PIL_open', (['IMAGE_URI'], {}), '(IMAGE_URI)\n', (8471, 8482), True, 'from PIL.Image import open as PIL_open\n'), ((9304, 9329), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), '(10, 10, 3)\n', (9318, 9329), True, 'import numpy as np\n')] |
from pathlib import Path
import shutil
import unittest
from Cryptodome import Random
import numpy as np
import pandas as pd
import torch
import yaml
import siml.inferer as inferer
import siml.prepost as prepost
import siml.setting as setting
import siml.trainer as trainer
torch.autograd.set_detect_anomaly(True)
def conversion_function(fem_data, raw_directory=None):
# To be used in test_preprocess_deform
adj = fem_data.calculate_adjacency_matrix_element()
nadj = prepost.normalize_adjacency_matrix(adj)
x_grad, y_grad, z_grad = \
fem_data.calculate_spatial_gradient_adjacency_matrices(
'elemental')
global_modulus = np.mean(
fem_data.elemental_data.get_attribute_data('modulus'), keepdims=True)
return {
'adj': adj, 'nadj': nadj, 'global_modulus': global_modulus,
'x_grad': x_grad, 'y_grad': y_grad, 'z_grad': z_grad}
class TestTrainer(unittest.TestCase):
def test_train_cpu_short_on_memory(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_short.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 10.)
def test_train_cpu_short_lazy(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_short.yml'))
main_setting.trainer.lazy = True
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 10.)
def test_train_general_block_without_support(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/general_block_wo_support.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 3.)
def test_train_general_block(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/general_block.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 3.)
def test_train_general_block_input_selection(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/general_block_input_selection.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 50.)
# Confirm input feature dimension is as expected
self.assertEqual(
tr.model.dict_block['ResGCN1'].subchains[0][0].in_features, 6)
self.assertEqual(tr.model.dict_block['MLP'].linears[0].in_features, 1)
def test_train_element_wise(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_element_wise.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 10.)
self.assertEqual(len(tr.train_loader.dataset), 1000)
self.assertEqual(tr.trainer.state.iteration, 1000 // 10 * 100)
def test_train_element_batch(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_element_batch.yml'))
tr_element_batch = trainer.Trainer(main_setting)
if tr_element_batch.setting.trainer.output_directory.exists():
shutil.rmtree(tr_element_batch.setting.trainer.output_directory)
loss_element_batch = tr_element_batch.train()
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_element_batch.yml'))
main_setting.trainer.element_batch_size = -1
main_setting.trainer.batch_size = 2
tr_std = trainer.Trainer(main_setting)
if tr_std.setting.trainer.output_directory.exists():
shutil.rmtree(tr_std.setting.trainer.output_directory)
loss_std = tr_std.train()
self.assertLess(loss_element_batch, loss_std)
def test_updater_equivalent(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_element_batch.yml'))
main_setting.trainer.batch_size = 1
main_setting.trainer.element_batch_size = 100000
eb1_tr = trainer.Trainer(main_setting)
if eb1_tr.setting.trainer.output_directory.exists():
shutil.rmtree(eb1_tr.setting.trainer.output_directory)
eb1_loss = eb1_tr.train()
main_setting.trainer.element_batch_size = -1
ebneg_tr = trainer.Trainer(main_setting)
if ebneg_tr.setting.trainer.output_directory.exists():
shutil.rmtree(ebneg_tr.setting.trainer.output_directory)
ebneg_loss = ebneg_tr.train()
np.testing.assert_almost_equal(eb1_loss, ebneg_loss)
def test_train_element_learning_rate(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_short_lr.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 10.)
def test_gradient_consistency_with_padding(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_timeseries.yml'))
main_setting.trainer.output_directory.mkdir(
parents=True, exist_ok=True)
tr = trainer.Trainer(main_setting)
tr.prepare_training()
x = np.reshape(np.arange(10*5*3), (10, 5, 3)).astype(np.float32) * .1
y = torch.from_numpy((x[:, :, :2] * 2 - .5))
tr.model.eval()
pred_y_wo_padding = tr.model({'x': torch.from_numpy(x)})
tr.optimizer.zero_grad()
loss_wo_padding = tr.loss(
pred_y_wo_padding, y, original_shapes=np.array([[10, 5]]))
loss_wo_padding.backward(retain_graph=True)
w_grad_wo_padding = tr.model.dict_block['Block'].linears[0].weight.grad
b_grad_wo_padding = tr.model.dict_block['Block'].linears[0].bias.grad
tr.optimizer.zero_grad()
padded_x = np.concatenate([x, np.zeros((3, 5, 3))], axis=0).astype(
np.float32)
padded_y = np.concatenate([y, np.zeros((3, 5, 2))], axis=0).astype(
np.float32)
pred_y_w_padding = tr.model({'x': torch.from_numpy(padded_x)})
loss_w_padding = tr.loss(
pred_y_w_padding, torch.from_numpy(padded_y),
original_shapes=np.array([[10, 5]]))
loss_wo_padding.backward()
w_grad_w_padding = tr.model.dict_block['Block'].linears[0].weight.grad
b_grad_w_padding = tr.model.dict_block['Block'].linears[0].bias.grad
np.testing.assert_almost_equal(
loss_wo_padding.detach().numpy(), loss_w_padding.detach().numpy())
np.testing.assert_almost_equal(
w_grad_wo_padding.numpy(), w_grad_w_padding.numpy())
np.testing.assert_almost_equal(
b_grad_wo_padding.numpy(), b_grad_w_padding.numpy())
def test_train_simplified_model(self):
setting_yaml = Path('tests/data/simplified/mlp.yml')
main_setting = setting.MainSetting.read_settings_yaml(setting_yaml)
if main_setting.data.preprocessed_root.exists():
shutil.rmtree(main_setting.data.preprocessed_root)
preprocessor = prepost.Preprocessor.read_settings(setting_yaml)
preprocessor.preprocess_interim_data()
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
np.testing.assert_array_less(loss, 0.01)
def test_evaluation_loss_not_depending_on_batch_size(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/mlp.yml'))
if main_setting.trainer.output_directory.exists():
shutil.rmtree(main_setting.trainer.output_directory)
main_setting.trainer.validation_batch_size = 1
tr_batch_1 = trainer.Trainer(main_setting)
loss_batch_1 = tr_batch_1.train()
if main_setting.trainer.output_directory.exists():
shutil.rmtree(main_setting.trainer.output_directory)
main_setting.trainer.validation_batch_size = 2
tr_batch_2 = trainer.Trainer(main_setting)
loss_batch_2 = tr_batch_2.train()
self.assertEqual(tr_batch_1.validation_loader.batch_size, 1)
self.assertEqual(tr_batch_2.validation_loader.batch_size, 2)
np.testing.assert_array_almost_equal(loss_batch_1, loss_batch_2)
def test_early_stopping(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/use_pretrained.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
tr.train()
self.assertLess(tr.trainer.state.epoch, main_setting.trainer.n_epoch)
self.assertEqual(
tr.trainer.state.epoch % main_setting.trainer.stop_trigger_epoch,
0)
def test_whole_processs(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/whole.yml'))
shutil.rmtree(main_setting.data.interim_root, ignore_errors=True)
shutil.rmtree(main_setting.data.preprocessed_root, ignore_errors=True)
raw_converter = prepost.RawConverter(
main_setting, conversion_function=conversion_function)
raw_converter.convert()
p = prepost.Preprocessor(main_setting)
p.preprocess_interim_data()
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
loss = tr.train()
self.assertLess(loss, 1e-1)
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=main_setting.data.preprocessed_root
/ 'preprocessors.pkl',
conversion_function=conversion_function, save=False)
results = ir.infer(
data_directories=main_setting.data.raw_root
/ 'train/tet2_3_modulusx0.9000', perform_preprocess=True)
self.assertLess(results[0]['loss'], 1e-1)
def test_whole_wildcard_processs(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/whole_wildcard.yml'))
shutil.rmtree(main_setting.data.interim_root, ignore_errors=True)
shutil.rmtree(main_setting.data.preprocessed_root, ignore_errors=True)
raw_converter = prepost.RawConverter(
main_setting, conversion_function=conversion_function)
raw_converter.convert()
p = prepost.Preprocessor(main_setting)
p.preprocess_interim_data()
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
loss = tr.train()
self.assertLess(loss, 1e-1)
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=main_setting.data.preprocessed_root
/ 'preprocessors.pkl',
conversion_function=conversion_function, save=False)
results = ir.infer(
data_directories=main_setting.data.raw_root
/ 'train/tet2_3_modulusx0.9000', perform_preprocess=True)
self.assertLess(results[0]['loss'], 1e-1)
def test_output_stats(self):
original_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/general_block.yml'))
original_tr = trainer.Trainer(original_setting)
if original_tr.setting.trainer.output_directory.exists():
shutil.rmtree(original_tr.setting.trainer.output_directory)
original_loss = original_tr.train()
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/output_stats.yml'))
tr = trainer.Trainer(main_setting)
if tr.setting.trainer.output_directory.exists():
shutil.rmtree(tr.setting.trainer.output_directory)
loss = tr.train()
# Loss should not change depending on output_stats
np.testing.assert_almost_equal(loss, original_loss, decimal=3)
stats_file = tr.setting.trainer.output_directory \
/ 'stats_epoch37_iteration74.yml'
with open(stats_file, 'r') as f:
dict_data = yaml.load(f, Loader=yaml.SafeLoader)
self.assertEqual(dict_data['iteration'], 74)
def test_trainer_train_test_split(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/split/mlp.yml'))
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
tr.train()
trained_setting = setting.MainSetting.read_settings_yaml(
tr.setting.trainer.output_directory / 'settings.yml')
self.assertEqual(
len(trained_setting.data.train), 5)
self.assertEqual(
len(trained_setting.data.validation), 3)
self.assertEqual(
len(trained_setting.data.test), 2)
def test_trainer_train_test_split_test0(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/split/mlp_test0.yml'))
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
tr.train()
trained_setting = setting.MainSetting.read_settings_yaml(
tr.setting.trainer.output_directory / 'settings.yml')
self.assertEqual(
len(trained_setting.data.train), 9)
self.assertEqual(
len(trained_setting.data.validation), 1)
self.assertEqual(
len(trained_setting.data.test), 0)
def test_trainer_train_test_split_sample1(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/split/mlp_sample1.yml'))
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
tr.train()
train_state, _ = tr.evaluate()
train_loss = train_state.metrics['loss']
trained_setting = setting.MainSetting.read_settings_yaml(
tr.setting.trainer.output_directory / 'settings.yml')
self.assertEqual(
len(trained_setting.data.train), 1)
self.assertEqual(
len(trained_setting.data.validation), 0)
self.assertEqual(
len(trained_setting.data.test), 0)
data_directory = main_setting.data.develop[0] # pylint: disable=E1136
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=data_directory.parent
/ 'preprocessors.pkl', save=False)
results = ir.infer(data_directories=data_directory)
np.testing.assert_almost_equal(results[0]['loss'], train_loss)
def test_trainer_train_dict_input(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/dict_input.yml'))
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
loss = tr.train()
np.testing.assert_array_less(loss, 1.)
def test_trainer_train_dict_input_w_support(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/dict_input_w_support.yml'))
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
loss = tr.train()
np.testing.assert_array_less(loss, 1.)
def test_restart(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_short.yml'))
# Complete training for reference
complete_tr = trainer.Trainer(main_setting)
complete_tr.setting.trainer.output_directory = Path(
'tests/data/linear/linear_short_completed')
if complete_tr.setting.trainer.output_directory.exists():
shutil.rmtree(complete_tr.setting.trainer.output_directory)
complete_tr.train()
# Incomplete training
incomplete_tr = trainer.Trainer(main_setting)
incomplete_tr.setting.trainer.n_epoch = 20
incomplete_tr.setting.trainer.output_directory = Path(
'tests/data/linear/linear_short_incomplete')
if incomplete_tr.setting.trainer.output_directory.exists():
shutil.rmtree(incomplete_tr.setting.trainer.output_directory)
incomplete_tr.train()
# Restart training
main_setting.trainer.restart_directory \
= incomplete_tr.setting.trainer.output_directory
restart_tr = trainer.Trainer(main_setting)
restart_tr.setting.trainer.n_epoch = 100
restart_tr.setting.trainer.output_directory = Path(
'tests/data/linear/linear_short_restart')
if restart_tr.setting.trainer.output_directory.exists():
shutil.rmtree(restart_tr.setting.trainer.output_directory)
loss = restart_tr.train()
df = pd.read_csv(
'tests/data/linear/linear_short_completed/log.csv',
header=0, index_col=None, skipinitialspace=True)
np.testing.assert_almost_equal(
loss, df['validation_loss'].values[-1], decimal=3)
restart_df = pd.read_csv(
restart_tr.setting.trainer.output_directory / 'log.csv',
header=0, index_col=None, skipinitialspace=True)
self.assertEqual(len(restart_df.values), 8)
def test_pretrain(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/linear/linear_short.yml'))
tr_wo_pretrain = trainer.Trainer(main_setting)
if tr_wo_pretrain.setting.trainer.output_directory.exists():
shutil.rmtree(tr_wo_pretrain.setting.trainer.output_directory)
loss_wo_pretrain = tr_wo_pretrain.train()
main_setting.trainer.pretrain_directory \
= tr_wo_pretrain.setting.trainer.output_directory
tr_w_pretrain = trainer.Trainer(main_setting)
if tr_w_pretrain.setting.trainer.output_directory.exists():
shutil.rmtree(tr_w_pretrain.setting.trainer.output_directory)
loss_w_pretrain = tr_w_pretrain.train()
self.assertLess(loss_w_pretrain, loss_wo_pretrain)
def test_whole_process_encryption(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/whole.yml'))
main_setting.data.interim = [Path(
'tests/data/deform/test_prepost/encrypt/interim')]
main_setting.data.preprocessed = [Path(
'tests/data/deform/test_prepost/encrypt/preprocessed')]
main_setting.data.train = [Path(
'tests/data/deform/test_prepost/encrypt/preprocessed/train')]
main_setting.data.validation = [Path(
'tests/data/deform/test_prepost/encrypt/preprocessed/validation')]
main_setting.data.test = [Path(
'tests/data/deform/test_prepost/encrypt/preprocessed/test')]
main_setting.data.encrypt_key = Random.get_random_bytes(16)
shutil.rmtree(main_setting.data.interim_root, ignore_errors=True)
shutil.rmtree(main_setting.data.preprocessed_root, ignore_errors=True)
raw_converter = prepost.RawConverter(
main_setting, conversion_function=conversion_function)
raw_converter.convert()
p = prepost.Preprocessor(main_setting)
p.preprocess_interim_data()
with self.assertRaises(ValueError):
np.load(
main_setting.data.interim[0]
/ 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')
with self.assertRaises(OSError):
np.load(
main_setting.data.interim[0]
/ 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc',
allow_pickle=True)
with self.assertRaises(ValueError):
np.load(
main_setting.data.preprocessed[0]
/ 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')
with self.assertRaises(OSError):
np.load(
main_setting.data.preprocessed[0]
/ 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc',
allow_pickle=True)
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
loss = tr.train()
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=main_setting.data.preprocessed[0]
/ 'preprocessors.pkl', save=False)
results = ir.infer(
data_directories=main_setting.data.preprocessed[0]
/ 'train/tet2_3_modulusx0.9000')
self.assertLess(results[0]['loss'], loss * 5)
def test_trainer_skip_dict_output(self):
main_setting = setting.MainSetting.read_settings_yaml(Path(
'tests/data/rotation_thermal_stress/iso_gcn_skip_dict_output.yml'))
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
loss = tr.train()
np.testing.assert_array_less(loss, 1.)
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=main_setting.data.preprocessed[0]
/ 'preprocessed/preprocessors.pkl', save=False)
ir.setting.inferer.perform_inverse = False
results = ir.infer(
data_directories=Path(
'tests/data/rotation_thermal_stress/preprocessed/'
'cube/original'))
t_mse_w_skip = np.mean((
results[0]['dict_y']['cnt_temperature']
- results[0]['dict_x']['cnt_temperature'])**2)
# Traiing without skip
main_setting.trainer.outputs['out_rank0'][0]['skip'] = False
tr = trainer.Trainer(main_setting)
loss = tr.train()
np.testing.assert_array_less(loss, 1.)
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=main_setting.data.preprocessed[0]
/ 'preprocessed/preprocessors.pkl', save=False)
ir.setting.inferer.perform_inverse = False
results = ir.infer(
data_directories=Path(
'tests/data/rotation_thermal_stress/preprocessed/'
'cube/original'))
t_mse_wo_skip = np.mean((
results[0]['dict_y']['cnt_temperature']
- results[0]['dict_x']['cnt_temperature'])**2)
print(t_mse_wo_skip, t_mse_w_skip)
self.assertLess(t_mse_wo_skip, t_mse_w_skip)
def test_trainer_skip_list_output(self):
main_setting = setting.MainSetting.read_settings_yaml(Path(
'tests/data/rotation_thermal_stress/gcn_skip_list_output.yml'))
shutil.rmtree(
main_setting.trainer.output_directory, ignore_errors=True)
tr = trainer.Trainer(main_setting)
tr.train()
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=main_setting.data.preprocessed[0]
/ 'preprocessed/preprocessors.pkl', save=False)
ir.setting.inferer.perform_inverse = False
results = ir.infer(
data_directories=Path(
'tests/data/rotation_thermal_stress/preprocessed/'
'cube/original'))
t_mse_w_skip = np.mean((
results[0]['dict_y']['cnt_temperature']
- results[0]['dict_x']['cnt_temperature'])**2)
# Traiing without skip
main_setting.trainer.outputs[0]['skip'] = False
tr = trainer.Trainer(main_setting)
tr.train()
ir = inferer.Inferer(
main_setting,
model=main_setting.trainer.output_directory,
converter_parameters_pkl=main_setting.data.preprocessed[0]
/ 'preprocessed/preprocessors.pkl', save=False)
ir.setting.inferer.perform_inverse = False
results = ir.infer(
data_directories=Path(
'tests/data/rotation_thermal_stress/preprocessed/'
'cube/original'))
t_mse_wo_skip = np.mean((
results[0]['dict_y']['cnt_temperature']
- results[0]['dict_x']['cnt_temperature'])**2)
print(t_mse_wo_skip, t_mse_w_skip)
self.assertLess(t_mse_wo_skip, t_mse_w_skip)
| [
"yaml.load",
"numpy.load",
"siml.inferer.Inferer",
"pandas.read_csv",
"pathlib.Path",
"numpy.mean",
"torch.autograd.set_detect_anomaly",
"numpy.arange",
"siml.trainer.Trainer",
"shutil.rmtree",
"numpy.testing.assert_array_almost_equal",
"siml.prepost.normalize_adjacency_matrix",
"numpy.testi... | [((277, 316), 'torch.autograd.set_detect_anomaly', 'torch.autograd.set_detect_anomaly', (['(True)'], {}), '(True)\n', (310, 316), False, 'import torch\n'), ((484, 523), 'siml.prepost.normalize_adjacency_matrix', 'prepost.normalize_adjacency_matrix', (['adj'], {}), '(adj)\n', (518, 523), True, 'import siml.prepost as prepost\n'), ((1114, 1143), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (1129, 1143), True, 'import siml.trainer as trainer\n'), ((1298, 1338), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(10.0)'], {}), '(loss, 10.0)\n', (1326, 1338), True, 'import numpy as np\n'), ((1553, 1582), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (1568, 1582), True, 'import siml.trainer as trainer\n'), ((1737, 1777), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(10.0)'], {}), '(loss, 10.0)\n', (1765, 1777), True, 'import numpy as np\n'), ((1978, 2007), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (1993, 2007), True, 'import siml.trainer as trainer\n'), ((2162, 2201), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(3.0)'], {}), '(loss, 3.0)\n', (2190, 2201), True, 'import numpy as np\n'), ((2375, 2404), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (2390, 2404), True, 'import siml.trainer as trainer\n'), ((2559, 2598), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(3.0)'], {}), '(loss, 3.0)\n', (2587, 2598), True, 'import numpy as np\n'), ((2804, 2833), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (2819, 2833), True, 'import siml.trainer as trainer\n'), ((2988, 3028), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(50.0)'], {}), '(loss, 50.0)\n', (3016, 3028), True, 'import numpy as np\n'), ((3445, 3474), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (3460, 3474), True, 'import siml.trainer as trainer\n'), ((3629, 3669), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(10.0)'], {}), '(loss, 10.0)\n', (3657, 3669), True, 'import numpy as np\n'), ((3996, 4025), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (4011, 4025), True, 'import siml.trainer as trainer\n'), ((4470, 4499), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (4485, 4499), True, 'import siml.trainer as trainer\n'), ((5003, 5032), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (5018, 5032), True, 'import siml.trainer as trainer\n'), ((5268, 5297), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (5283, 5297), True, 'import siml.trainer as trainer\n'), ((5477, 5529), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['eb1_loss', 'ebneg_loss'], {}), '(eb1_loss, ebneg_loss)\n', (5507, 5529), True, 'import numpy as np\n'), ((5714, 5743), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (5729, 5743), True, 'import siml.trainer as trainer\n'), ((5898, 5938), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(10.0)'], {}), '(loss, 10.0)\n', (5926, 5938), True, 'import numpy as np\n'), ((6224, 6253), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (6239, 6253), True, 'import siml.trainer as trainer\n'), ((6374, 6413), 'torch.from_numpy', 'torch.from_numpy', (['(x[:, :, :2] * 2 - 0.5)'], {}), '(x[:, :, :2] * 2 - 0.5)\n', (6390, 6413), False, 'import torch\n'), ((7888, 7925), 'pathlib.Path', 'Path', (['"""tests/data/simplified/mlp.yml"""'], {}), "('tests/data/simplified/mlp.yml')\n", (7892, 7925), False, 'from pathlib import Path\n'), ((7949, 8001), 'siml.setting.MainSetting.read_settings_yaml', 'setting.MainSetting.read_settings_yaml', (['setting_yaml'], {}), '(setting_yaml)\n', (7987, 8001), True, 'import siml.setting as setting\n'), ((8146, 8194), 'siml.prepost.Preprocessor.read_settings', 'prepost.Preprocessor.read_settings', (['setting_yaml'], {}), '(setting_yaml)\n', (8180, 8194), True, 'import siml.prepost as prepost\n'), ((8256, 8285), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (8271, 8285), True, 'import siml.trainer as trainer\n'), ((8440, 8480), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(0.01)'], {}), '(loss, 0.01)\n', (8468, 8480), True, 'import numpy as np\n'), ((8857, 8886), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (8872, 8886), True, 'import siml.trainer as trainer\n'), ((9130, 9159), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (9145, 9159), True, 'import siml.trainer as trainer\n'), ((9350, 9414), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['loss_batch_1', 'loss_batch_2'], {}), '(loss_batch_1, loss_batch_2)\n', (9386, 9414), True, 'import numpy as np\n'), ((9585, 9614), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (9600, 9614), True, 'import siml.trainer as trainer\n'), ((10107, 10172), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.data.interim_root'], {'ignore_errors': '(True)'}), '(main_setting.data.interim_root, ignore_errors=True)\n', (10120, 10172), False, 'import shutil\n'), ((10181, 10251), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.data.preprocessed_root'], {'ignore_errors': '(True)'}), '(main_setting.data.preprocessed_root, ignore_errors=True)\n', (10194, 10251), False, 'import shutil\n'), ((10277, 10352), 'siml.prepost.RawConverter', 'prepost.RawConverter', (['main_setting'], {'conversion_function': 'conversion_function'}), '(main_setting, conversion_function=conversion_function)\n', (10297, 10352), True, 'import siml.prepost as prepost\n'), ((10410, 10444), 'siml.prepost.Preprocessor', 'prepost.Preprocessor', (['main_setting'], {}), '(main_setting)\n', (10430, 10444), True, 'import siml.prepost as prepost\n'), ((10490, 10562), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (10503, 10562), False, 'import shutil\n'), ((10589, 10618), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (10604, 10618), True, 'import siml.trainer as trainer\n'), ((10695, 10914), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(main_setting.data.preprocessed_root / 'preprocessors.pkl')", 'conversion_function': 'conversion_function', 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=main_setting.data.preprocessed_root /\n 'preprocessors.pkl', conversion_function=conversion_function, save=False)\n", (10710, 10914), True, 'import siml.inferer as inferer\n'), ((11346, 11411), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.data.interim_root'], {'ignore_errors': '(True)'}), '(main_setting.data.interim_root, ignore_errors=True)\n', (11359, 11411), False, 'import shutil\n'), ((11420, 11490), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.data.preprocessed_root'], {'ignore_errors': '(True)'}), '(main_setting.data.preprocessed_root, ignore_errors=True)\n', (11433, 11490), False, 'import shutil\n'), ((11516, 11591), 'siml.prepost.RawConverter', 'prepost.RawConverter', (['main_setting'], {'conversion_function': 'conversion_function'}), '(main_setting, conversion_function=conversion_function)\n', (11536, 11591), True, 'import siml.prepost as prepost\n'), ((11649, 11683), 'siml.prepost.Preprocessor', 'prepost.Preprocessor', (['main_setting'], {}), '(main_setting)\n', (11669, 11683), True, 'import siml.prepost as prepost\n'), ((11729, 11801), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (11742, 11801), False, 'import shutil\n'), ((11828, 11857), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (11843, 11857), True, 'import siml.trainer as trainer\n'), ((11934, 12153), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(main_setting.data.preprocessed_root / 'preprocessors.pkl')", 'conversion_function': 'conversion_function', 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=main_setting.data.preprocessed_root /\n 'preprocessors.pkl', conversion_function=conversion_function, save=False)\n", (11949, 12153), True, 'import siml.inferer as inferer\n'), ((12591, 12624), 'siml.trainer.Trainer', 'trainer.Trainer', (['original_setting'], {}), '(original_setting)\n', (12606, 12624), True, 'import siml.trainer as trainer\n'), ((12940, 12969), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (12955, 12969), True, 'import siml.trainer as trainer\n'), ((13184, 13246), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['loss', 'original_loss'], {'decimal': '(3)'}), '(loss, original_loss, decimal=3)\n', (13214, 13246), True, 'import numpy as np\n'), ((13671, 13743), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (13684, 13743), False, 'import shutil\n'), ((13770, 13799), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (13785, 13799), True, 'import siml.trainer as trainer\n'), ((13846, 13942), 'siml.setting.MainSetting.read_settings_yaml', 'setting.MainSetting.read_settings_yaml', (["(tr.setting.trainer.output_directory / 'settings.yml')"], {}), "(tr.setting.trainer.output_directory /\n 'settings.yml')\n", (13884, 13942), True, 'import siml.setting as setting\n'), ((14353, 14425), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (14366, 14425), False, 'import shutil\n'), ((14452, 14481), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (14467, 14481), True, 'import siml.trainer as trainer\n'), ((14528, 14624), 'siml.setting.MainSetting.read_settings_yaml', 'setting.MainSetting.read_settings_yaml', (["(tr.setting.trainer.output_directory / 'settings.yml')"], {}), "(tr.setting.trainer.output_directory /\n 'settings.yml')\n", (14566, 14624), True, 'import siml.setting as setting\n'), ((15039, 15111), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (15052, 15111), False, 'import shutil\n'), ((15138, 15167), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (15153, 15167), True, 'import siml.trainer as trainer\n'), ((15302, 15398), 'siml.setting.MainSetting.read_settings_yaml', 'setting.MainSetting.read_settings_yaml', (["(tr.setting.trainer.output_directory / 'settings.yml')"], {}), "(tr.setting.trainer.output_directory /\n 'settings.yml')\n", (15340, 15398), True, 'import siml.setting as setting\n'), ((15727, 15891), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(data_directory.parent / 'preprocessors.pkl')", 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=data_directory.parent / 'preprocessors.pkl',\n save=False)\n", (15742, 15891), True, 'import siml.inferer as inferer\n'), ((16001, 16063), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["results[0]['loss']", 'train_loss'], {}), "(results[0]['loss'], train_loss)\n", (16031, 16063), True, 'import numpy as np\n'), ((16235, 16307), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (16248, 16307), False, 'import shutil\n'), ((16334, 16363), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (16349, 16363), True, 'import siml.trainer as trainer\n'), ((16398, 16437), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(1.0)'], {}), '(loss, 1.0)\n', (16426, 16437), True, 'import numpy as np\n'), ((16628, 16700), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (16641, 16700), False, 'import shutil\n'), ((16727, 16756), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (16742, 16756), True, 'import siml.trainer as trainer\n'), ((16791, 16830), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(1.0)'], {}), '(loss, 1.0)\n', (16819, 16830), True, 'import numpy as np\n'), ((17043, 17072), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (17058, 17072), True, 'import siml.trainer as trainer\n'), ((17128, 17176), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short_completed"""'], {}), "('tests/data/linear/linear_short_completed')\n", (17132, 17176), False, 'from pathlib import Path\n'), ((17411, 17440), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (17426, 17440), True, 'import siml.trainer as trainer\n'), ((17549, 17598), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short_incomplete"""'], {}), "('tests/data/linear/linear_short_incomplete')\n", (17553, 17598), False, 'from pathlib import Path\n'), ((17943, 17972), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (17958, 17972), True, 'import siml.trainer as trainer\n'), ((18076, 18122), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short_restart"""'], {}), "('tests/data/linear/linear_short_restart')\n", (18080, 18122), False, 'from pathlib import Path\n'), ((18320, 18436), 'pandas.read_csv', 'pd.read_csv', (['"""tests/data/linear/linear_short_completed/log.csv"""'], {'header': '(0)', 'index_col': 'None', 'skipinitialspace': '(True)'}), "('tests/data/linear/linear_short_completed/log.csv', header=0,\n index_col=None, skipinitialspace=True)\n", (18331, 18436), True, 'import pandas as pd\n'), ((18466, 18551), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['loss', "df['validation_loss'].values[-1]"], {'decimal': '(3)'}), "(loss, df['validation_loss'].values[-1],\n decimal=3)\n", (18496, 18551), True, 'import numpy as np\n'), ((18583, 18705), 'pandas.read_csv', 'pd.read_csv', (["(restart_tr.setting.trainer.output_directory / 'log.csv')"], {'header': '(0)', 'index_col': 'None', 'skipinitialspace': '(True)'}), "(restart_tr.setting.trainer.output_directory / 'log.csv', header\n =0, index_col=None, skipinitialspace=True)\n", (18594, 18705), True, 'import pandas as pd\n'), ((18952, 18981), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (18967, 18981), True, 'import siml.trainer as trainer\n'), ((19313, 19342), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (19328, 19342), True, 'import siml.trainer as trainer\n'), ((20367, 20394), 'Cryptodome.Random.get_random_bytes', 'Random.get_random_bytes', (['(16)'], {}), '(16)\n', (20390, 20394), False, 'from Cryptodome import Random\n'), ((20404, 20469), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.data.interim_root'], {'ignore_errors': '(True)'}), '(main_setting.data.interim_root, ignore_errors=True)\n', (20417, 20469), False, 'import shutil\n'), ((20478, 20548), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.data.preprocessed_root'], {'ignore_errors': '(True)'}), '(main_setting.data.preprocessed_root, ignore_errors=True)\n', (20491, 20548), False, 'import shutil\n'), ((20574, 20649), 'siml.prepost.RawConverter', 'prepost.RawConverter', (['main_setting'], {'conversion_function': 'conversion_function'}), '(main_setting, conversion_function=conversion_function)\n', (20594, 20649), True, 'import siml.prepost as prepost\n'), ((20707, 20741), 'siml.prepost.Preprocessor', 'prepost.Preprocessor', (['main_setting'], {}), '(main_setting)\n', (20727, 20741), True, 'import siml.prepost as prepost\n'), ((21599, 21671), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (21612, 21671), False, 'import shutil\n'), ((21698, 21727), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (21713, 21727), True, 'import siml.trainer as trainer\n'), ((21768, 21944), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(main_setting.data.preprocessed[0] / 'preprocessors.pkl')", 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=main_setting.data.preprocessed[0] /\n 'preprocessors.pkl', save=False)\n", (21783, 21944), True, 'import siml.inferer as inferer\n'), ((22378, 22450), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (22391, 22450), False, 'import shutil\n'), ((22477, 22506), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (22492, 22506), True, 'import siml.trainer as trainer\n'), ((22541, 22580), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(1.0)'], {}), '(loss, 1.0)\n', (22569, 22580), True, 'import numpy as np\n'), ((22594, 22783), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(main_setting.data.preprocessed[0] / 'preprocessed/preprocessors.pkl')", 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=main_setting.data.preprocessed[0] /\n 'preprocessed/preprocessors.pkl', save=False)\n", (22609, 22783), True, 'import siml.inferer as inferer\n'), ((23064, 23166), 'numpy.mean', 'np.mean', (["((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)"], {}), "((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)\n", (23071, 23166), True, 'import numpy as np\n'), ((23299, 23328), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (23314, 23328), True, 'import siml.trainer as trainer\n'), ((23363, 23402), 'numpy.testing.assert_array_less', 'np.testing.assert_array_less', (['loss', '(1.0)'], {}), '(loss, 1.0)\n', (23391, 23402), True, 'import numpy as np\n'), ((23416, 23605), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(main_setting.data.preprocessed[0] / 'preprocessed/preprocessors.pkl')", 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=main_setting.data.preprocessed[0] /\n 'preprocessed/preprocessors.pkl', save=False)\n", (23431, 23605), True, 'import siml.inferer as inferer\n'), ((23886, 23988), 'numpy.mean', 'np.mean', (["((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)"], {}), "((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)\n", (23893, 23988), True, 'import numpy as np\n'), ((24302, 24374), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {'ignore_errors': '(True)'}), '(main_setting.trainer.output_directory, ignore_errors=True)\n', (24315, 24374), False, 'import shutil\n'), ((24401, 24430), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (24416, 24430), True, 'import siml.trainer as trainer\n'), ((24464, 24653), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(main_setting.data.preprocessed[0] / 'preprocessed/preprocessors.pkl')", 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=main_setting.data.preprocessed[0] /\n 'preprocessed/preprocessors.pkl', save=False)\n", (24479, 24653), True, 'import siml.inferer as inferer\n'), ((24934, 25036), 'numpy.mean', 'np.mean', (["((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)"], {}), "((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)\n", (24941, 25036), True, 'import numpy as np\n'), ((25156, 25185), 'siml.trainer.Trainer', 'trainer.Trainer', (['main_setting'], {}), '(main_setting)\n', (25171, 25185), True, 'import siml.trainer as trainer\n'), ((25219, 25408), 'siml.inferer.Inferer', 'inferer.Inferer', (['main_setting'], {'model': 'main_setting.trainer.output_directory', 'converter_parameters_pkl': "(main_setting.data.preprocessed[0] / 'preprocessed/preprocessors.pkl')", 'save': '(False)'}), "(main_setting, model=main_setting.trainer.output_directory,\n converter_parameters_pkl=main_setting.data.preprocessed[0] /\n 'preprocessed/preprocessors.pkl', save=False)\n", (25234, 25408), True, 'import siml.inferer as inferer\n'), ((25689, 25791), 'numpy.mean', 'np.mean', (["((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)"], {}), "((results[0]['dict_y']['cnt_temperature'] - results[0]['dict_x'][\n 'cnt_temperature']) ** 2)\n", (25696, 25791), True, 'import numpy as np\n'), ((1057, 1099), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short.yml"""'], {}), "('tests/data/linear/linear_short.yml')\n", (1061, 1099), False, 'from pathlib import Path\n'), ((1213, 1263), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (1226, 1263), False, 'import shutil\n'), ((1455, 1497), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short.yml"""'], {}), "('tests/data/linear/linear_short.yml')\n", (1459, 1497), False, 'from pathlib import Path\n'), ((1652, 1702), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (1665, 1702), False, 'import shutil\n'), ((1909, 1963), 'pathlib.Path', 'Path', (['"""tests/data/deform/general_block_wo_support.yml"""'], {}), "('tests/data/deform/general_block_wo_support.yml')\n", (1913, 1963), False, 'from pathlib import Path\n'), ((2077, 2127), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (2090, 2127), False, 'import shutil\n'), ((2317, 2360), 'pathlib.Path', 'Path', (['"""tests/data/deform/general_block.yml"""'], {}), "('tests/data/deform/general_block.yml')\n", (2321, 2360), False, 'from pathlib import Path\n'), ((2474, 2524), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (2487, 2524), False, 'import shutil\n'), ((2730, 2789), 'pathlib.Path', 'Path', (['"""tests/data/deform/general_block_input_selection.yml"""'], {}), "('tests/data/deform/general_block_input_selection.yml')\n", (2734, 2789), False, 'from pathlib import Path\n'), ((2903, 2953), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (2916, 2953), False, 'import shutil\n'), ((3381, 3430), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_element_wise.yml"""'], {}), "('tests/data/linear/linear_element_wise.yml')\n", (3385, 3430), False, 'from pathlib import Path\n'), ((3544, 3594), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (3557, 3594), False, 'import shutil\n'), ((3917, 3967), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_element_batch.yml"""'], {}), "('tests/data/linear/linear_element_batch.yml')\n", (3921, 3967), False, 'from pathlib import Path\n'), ((4109, 4173), 'shutil.rmtree', 'shutil.rmtree', (['tr_element_batch.setting.trainer.output_directory'], {}), '(tr_element_batch.setting.trainer.output_directory)\n', (4122, 4173), False, 'import shutil\n'), ((4304, 4354), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_element_batch.yml"""'], {}), "('tests/data/linear/linear_element_batch.yml')\n", (4308, 4354), False, 'from pathlib import Path\n'), ((4573, 4627), 'shutil.rmtree', 'shutil.rmtree', (['tr_std.setting.trainer.output_directory'], {}), '(tr_std.setting.trainer.output_directory)\n', (4586, 4627), False, 'import shutil\n'), ((4832, 4882), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_element_batch.yml"""'], {}), "('tests/data/linear/linear_element_batch.yml')\n", (4836, 4882), False, 'from pathlib import Path\n'), ((5106, 5160), 'shutil.rmtree', 'shutil.rmtree', (['eb1_tr.setting.trainer.output_directory'], {}), '(eb1_tr.setting.trainer.output_directory)\n', (5119, 5160), False, 'import shutil\n'), ((5373, 5429), 'shutil.rmtree', 'shutil.rmtree', (['ebneg_tr.setting.trainer.output_directory'], {}), '(ebneg_tr.setting.trainer.output_directory)\n', (5386, 5429), False, 'import shutil\n'), ((5654, 5699), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short_lr.yml"""'], {}), "('tests/data/linear/linear_short_lr.yml')\n", (5658, 5699), False, 'from pathlib import Path\n'), ((5813, 5863), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (5826, 5863), False, 'import shutil\n'), ((6068, 6115), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_timeseries.yml"""'], {}), "('tests/data/linear/linear_timeseries.yml')\n", (6072, 6115), False, 'from pathlib import Path\n'), ((7223, 7249), 'torch.from_numpy', 'torch.from_numpy', (['padded_y'], {}), '(padded_y)\n', (7239, 7249), False, 'import torch\n'), ((8072, 8122), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.data.preprocessed_root'], {}), '(main_setting.data.preprocessed_root)\n', (8085, 8122), False, 'import shutil\n'), ((8355, 8405), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (8368, 8405), False, 'import shutil\n'), ((8621, 8654), 'pathlib.Path', 'Path', (['"""tests/data/deform/mlp.yml"""'], {}), "('tests/data/deform/mlp.yml')\n", (8625, 8654), False, 'from pathlib import Path\n'), ((8728, 8780), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {}), '(main_setting.trainer.output_directory)\n', (8741, 8780), False, 'import shutil\n'), ((9001, 9053), 'shutil.rmtree', 'shutil.rmtree', (['main_setting.trainer.output_directory'], {}), '(main_setting.trainer.output_directory)\n', (9014, 9053), False, 'import shutil\n'), ((9526, 9570), 'pathlib.Path', 'Path', (['"""tests/data/linear/use_pretrained.yml"""'], {}), "('tests/data/linear/use_pretrained.yml')\n", (9530, 9570), False, 'from pathlib import Path\n'), ((9684, 9734), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (9697, 9734), False, 'import shutil\n'), ((10062, 10097), 'pathlib.Path', 'Path', (['"""tests/data/deform/whole.yml"""'], {}), "('tests/data/deform/whole.yml')\n", (10066, 10097), False, 'from pathlib import Path\n'), ((11292, 11336), 'pathlib.Path', 'Path', (['"""tests/data/deform/whole_wildcard.yml"""'], {}), "('tests/data/deform/whole_wildcard.yml')\n", (11296, 11336), False, 'from pathlib import Path\n'), ((12524, 12567), 'pathlib.Path', 'Path', (['"""tests/data/deform/general_block.yml"""'], {}), "('tests/data/deform/general_block.yml')\n", (12528, 12567), False, 'from pathlib import Path\n'), ((12703, 12762), 'shutil.rmtree', 'shutil.rmtree', (['original_tr.setting.trainer.output_directory'], {}), '(original_tr.setting.trainer.output_directory)\n', (12716, 12762), False, 'import shutil\n'), ((12883, 12925), 'pathlib.Path', 'Path', (['"""tests/data/deform/output_stats.yml"""'], {}), "('tests/data/deform/output_stats.yml')\n", (12887, 12925), False, 'from pathlib import Path\n'), ((13039, 13089), 'shutil.rmtree', 'shutil.rmtree', (['tr.setting.trainer.output_directory'], {}), '(tr.setting.trainer.output_directory)\n', (13052, 13089), False, 'import shutil\n'), ((13418, 13454), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml.SafeLoader'}), '(f, Loader=yaml.SafeLoader)\n', (13427, 13454), False, 'import yaml\n'), ((13629, 13661), 'pathlib.Path', 'Path', (['"""tests/data/split/mlp.yml"""'], {}), "('tests/data/split/mlp.yml')\n", (13633, 13661), False, 'from pathlib import Path\n'), ((14305, 14343), 'pathlib.Path', 'Path', (['"""tests/data/split/mlp_test0.yml"""'], {}), "('tests/data/split/mlp_test0.yml')\n", (14309, 14343), False, 'from pathlib import Path\n'), ((14989, 15029), 'pathlib.Path', 'Path', (['"""tests/data/split/mlp_sample1.yml"""'], {}), "('tests/data/split/mlp_sample1.yml')\n", (14993, 15029), False, 'from pathlib import Path\n'), ((16185, 16225), 'pathlib.Path', 'Path', (['"""tests/data/deform/dict_input.yml"""'], {}), "('tests/data/deform/dict_input.yml')\n", (16189, 16225), False, 'from pathlib import Path\n'), ((16568, 16618), 'pathlib.Path', 'Path', (['"""tests/data/deform/dict_input_w_support.yml"""'], {}), "('tests/data/deform/dict_input_w_support.yml')\n", (16572, 16618), False, 'from pathlib import Path\n'), ((16934, 16976), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short.yml"""'], {}), "('tests/data/linear/linear_short.yml')\n", (16938, 16976), False, 'from pathlib import Path\n'), ((17268, 17327), 'shutil.rmtree', 'shutil.rmtree', (['complete_tr.setting.trainer.output_directory'], {}), '(complete_tr.setting.trainer.output_directory)\n', (17281, 17327), False, 'import shutil\n'), ((17692, 17753), 'shutil.rmtree', 'shutil.rmtree', (['incomplete_tr.setting.trainer.output_directory'], {}), '(incomplete_tr.setting.trainer.output_directory)\n', (17705, 17753), False, 'import shutil\n'), ((18213, 18271), 'shutil.rmtree', 'shutil.rmtree', (['restart_tr.setting.trainer.output_directory'], {}), '(restart_tr.setting.trainer.output_directory)\n', (18226, 18271), False, 'import shutil\n'), ((18883, 18925), 'pathlib.Path', 'Path', (['"""tests/data/linear/linear_short.yml"""'], {}), "('tests/data/linear/linear_short.yml')\n", (18887, 18925), False, 'from pathlib import Path\n'), ((19063, 19125), 'shutil.rmtree', 'shutil.rmtree', (['tr_wo_pretrain.setting.trainer.output_directory'], {}), '(tr_wo_pretrain.setting.trainer.output_directory)\n', (19076, 19125), False, 'import shutil\n'), ((19423, 19484), 'shutil.rmtree', 'shutil.rmtree', (['tr_w_pretrain.setting.trainer.output_directory'], {}), '(tr_w_pretrain.setting.trainer.output_directory)\n', (19436, 19484), False, 'import shutil\n'), ((19713, 19748), 'pathlib.Path', 'Path', (['"""tests/data/deform/whole.yml"""'], {}), "('tests/data/deform/whole.yml')\n", (19717, 19748), False, 'from pathlib import Path\n'), ((19787, 19841), 'pathlib.Path', 'Path', (['"""tests/data/deform/test_prepost/encrypt/interim"""'], {}), "('tests/data/deform/test_prepost/encrypt/interim')\n", (19791, 19841), False, 'from pathlib import Path\n'), ((19898, 19957), 'pathlib.Path', 'Path', (['"""tests/data/deform/test_prepost/encrypt/preprocessed"""'], {}), "('tests/data/deform/test_prepost/encrypt/preprocessed')\n", (19902, 19957), False, 'from pathlib import Path\n'), ((20008, 20073), 'pathlib.Path', 'Path', (['"""tests/data/deform/test_prepost/encrypt/preprocessed/train"""'], {}), "('tests/data/deform/test_prepost/encrypt/preprocessed/train')\n", (20012, 20073), False, 'from pathlib import Path\n'), ((20128, 20198), 'pathlib.Path', 'Path', (['"""tests/data/deform/test_prepost/encrypt/preprocessed/validation"""'], {}), "('tests/data/deform/test_prepost/encrypt/preprocessed/validation')\n", (20132, 20198), False, 'from pathlib import Path\n'), ((20247, 20311), 'pathlib.Path', 'Path', (['"""tests/data/deform/test_prepost/encrypt/preprocessed/test"""'], {}), "('tests/data/deform/test_prepost/encrypt/preprocessed/test')\n", (20251, 20311), False, 'from pathlib import Path\n'), ((20835, 20933), 'numpy.load', 'np.load', (["(main_setting.data.interim[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')"], {}), "(main_setting.data.interim[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')\n", (20842, 20933), True, 'import numpy as np\n'), ((21016, 21133), 'numpy.load', 'np.load', (["(main_setting.data.interim[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')"], {'allow_pickle': '(True)'}), "(main_setting.data.interim[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc', allow_pickle=True)\n", (21023, 21133), True, 'import numpy as np\n'), ((21236, 21339), 'numpy.load', 'np.load', (["(main_setting.data.preprocessed[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')"], {}), "(main_setting.data.preprocessed[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')\n", (21243, 21339), True, 'import numpy as np\n'), ((21422, 21544), 'numpy.load', 'np.load', (["(main_setting.data.preprocessed[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc')"], {'allow_pickle': '(True)'}), "(main_setting.data.preprocessed[0] /\n 'train/tet2_3_modulusx0.9000/elemental_strain.npy.enc', allow_pickle=True)\n", (21429, 21544), True, 'import numpy as np\n'), ((22284, 22355), 'pathlib.Path', 'Path', (['"""tests/data/rotation_thermal_stress/iso_gcn_skip_dict_output.yml"""'], {}), "('tests/data/rotation_thermal_stress/iso_gcn_skip_dict_output.yml')\n", (22288, 22355), False, 'from pathlib import Path\n'), ((24212, 24279), 'pathlib.Path', 'Path', (['"""tests/data/rotation_thermal_stress/gcn_skip_list_output.yml"""'], {}), "('tests/data/rotation_thermal_stress/gcn_skip_list_output.yml')\n", (24216, 24279), False, 'from pathlib import Path\n'), ((6483, 6502), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (6499, 6502), False, 'import torch\n'), ((6623, 6642), 'numpy.array', 'np.array', (['[[10, 5]]'], {}), '([[10, 5]])\n', (6631, 6642), True, 'import numpy as np\n'), ((7130, 7156), 'torch.from_numpy', 'torch.from_numpy', (['padded_x'], {}), '(padded_x)\n', (7146, 7156), False, 'import torch\n'), ((7279, 7298), 'numpy.array', 'np.array', (['[[10, 5]]'], {}), '([[10, 5]])\n', (7287, 7298), True, 'import numpy as np\n'), ((22933, 23002), 'pathlib.Path', 'Path', (['"""tests/data/rotation_thermal_stress/preprocessed/cube/original"""'], {}), "('tests/data/rotation_thermal_stress/preprocessed/cube/original')\n", (22937, 23002), False, 'from pathlib import Path\n'), ((23755, 23824), 'pathlib.Path', 'Path', (['"""tests/data/rotation_thermal_stress/preprocessed/cube/original"""'], {}), "('tests/data/rotation_thermal_stress/preprocessed/cube/original')\n", (23759, 23824), False, 'from pathlib import Path\n'), ((24803, 24872), 'pathlib.Path', 'Path', (['"""tests/data/rotation_thermal_stress/preprocessed/cube/original"""'], {}), "('tests/data/rotation_thermal_stress/preprocessed/cube/original')\n", (24807, 24872), False, 'from pathlib import Path\n'), ((25558, 25627), 'pathlib.Path', 'Path', (['"""tests/data/rotation_thermal_stress/preprocessed/cube/original"""'], {}), "('tests/data/rotation_thermal_stress/preprocessed/cube/original')\n", (25562, 25627), False, 'from pathlib import Path\n'), ((6307, 6328), 'numpy.arange', 'np.arange', (['(10 * 5 * 3)'], {}), '(10 * 5 * 3)\n', (6316, 6328), True, 'import numpy as np\n'), ((6926, 6945), 'numpy.zeros', 'np.zeros', (['(3, 5, 3)'], {}), '((3, 5, 3))\n', (6934, 6945), True, 'import numpy as np\n'), ((7026, 7045), 'numpy.zeros', 'np.zeros', (['(3, 5, 2)'], {}), '((3, 5, 2))\n', (7034, 7045), True, 'import numpy as np\n')] |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense
from tensorflow.keras import Sequential
from tensorflow.keras.optimizers import Adam
data = np.loadtxt("../../data/cross-entropy.txt", dtype=np.float32)
x_data = data[:, 1:3]
y_data = data[:, 3:]
print(x_data.shape)
print(y_data.shape)
IO = Dense(units=3, input_shape=[2], activation="cross-entropy")
model = Sequential([IO])
model.compile(loss="categorical_crossentropy", optimizer=Adam(learning_rate=0.01), metrics=["accuracy"])
history = model.fit(x_data, y_data, epochs=1000)
print(IO.get_weights())
p = model.predict( np.array([[3., 6.]]))
print(history.history['acc'][-1])
| [
"tensorflow.keras.layers.Dense",
"tensorflow.keras.optimizers.Adam",
"numpy.array",
"numpy.loadtxt",
"tensorflow.keras.Sequential"
] | [((211, 271), 'numpy.loadtxt', 'np.loadtxt', (['"""../../data/cross-entropy.txt"""'], {'dtype': 'np.float32'}), "('../../data/cross-entropy.txt', dtype=np.float32)\n", (221, 271), True, 'import numpy as np\n'), ((363, 422), 'tensorflow.keras.layers.Dense', 'Dense', ([], {'units': '(3)', 'input_shape': '[2]', 'activation': '"""cross-entropy"""'}), "(units=3, input_shape=[2], activation='cross-entropy')\n", (368, 422), False, 'from tensorflow.keras.layers import Dense\n'), ((431, 447), 'tensorflow.keras.Sequential', 'Sequential', (['[IO]'], {}), '([IO])\n', (441, 447), False, 'from tensorflow.keras import Sequential\n'), ((648, 670), 'numpy.array', 'np.array', (['[[3.0, 6.0]]'], {}), '([[3.0, 6.0]])\n', (656, 670), True, 'import numpy as np\n'), ((505, 529), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'learning_rate': '(0.01)'}), '(learning_rate=0.01)\n', (509, 529), False, 'from tensorflow.keras.optimizers import Adam\n')] |
import logging
import os
import lightkurve as lk
import numpy as np
import pandas as pd
from tess_atlas.utils import NOTEBOOK_LOGGER_NAME
from .data_object import DataObject
from ..utils import get_cache_dir
logger = logging.getLogger(NOTEBOOK_LOGGER_NAME)
class LightCurveData(DataObject):
"""Stores Light Curve data for a single target"""
def __init__(
self,
time: np.ndarray,
flux: np.ndarray,
flux_err: np.ndarray,
outdir: str,
):
"""
:param np.ndarray time: The time in days.
:param np.ndarray flux: The relative flux in parts per thousand.
:param np.ndarray fluex_err: The flux err in parts per thousand.
:param str: the outdir to store lk data
"""
self.time = time
self.flux = flux
self.flux_err = flux_err
self.outdir = outdir
@classmethod
def from_database(cls, tic: int, outdir: str):
"""Uses lightkurve to get TESS data for a TIC from MAST"""
logger.info("Downloading LightCurveData from MAST")
search = lk.search_lightcurve(target=f"TIC {tic}", mission="TESS")
logger.debug(f"Search succeeded: {search}")
# Restrict to short cadence no "fast" cadence
search = search[np.where(search.table["t_exptime"] == 120)]
logger.info(
f"Downloading {len(search)} observations of light curve data "
f"(TIC {tic})"
)
cache_dir = get_cache_dir(default=outdir)
data = search.download_all(download_dir=cache_dir)
if data is None:
raise ValueError(f"No light curves for TIC {tic}")
logger.info("Completed light curve data download")
data = data.stitch()
data = data.remove_nans().remove_outliers(sigma=7)
t = data.time.value
inds = np.argsort(t)
return cls(
time=np.ascontiguousarray(t[inds], dtype=np.float64),
flux=np.ascontiguousarray(
1e3 * (data.flux.value[inds] - 1), dtype=np.float64
),
flux_err=np.ascontiguousarray(
1e3 * data.flux_err.value[inds], dtype=np.float64
),
outdir=outdir,
)
@classmethod
def from_cache(cls, tic: int, outdir: str):
fname = LightCurveData.get_filepath(outdir)
df = pd.read_csv(fname)
logger.info(f"Lightcurve loaded from {fname}")
return cls(
time=np.array(df.time),
flux=np.array(df.flux),
flux_err=np.array(df.flux_err),
outdir=outdir,
)
def to_dict(self):
return dict(time=self.time, flux=self.flux, flux_err=self.flux_err)
def save_data(self, outdir):
fpath = self.get_filepath(outdir)
df = pd.DataFrame(self.to_dict())
df.to_csv(fpath, index=False)
@staticmethod
def get_filepath(outdir, fname="lightcurve.csv"):
return os.path.join(outdir, fname)
| [
"pandas.read_csv",
"numpy.ascontiguousarray",
"lightkurve.search_lightcurve",
"numpy.argsort",
"numpy.where",
"numpy.array",
"os.path.join",
"logging.getLogger"
] | [((221, 260), 'logging.getLogger', 'logging.getLogger', (['NOTEBOOK_LOGGER_NAME'], {}), '(NOTEBOOK_LOGGER_NAME)\n', (238, 260), False, 'import logging\n'), ((1088, 1145), 'lightkurve.search_lightcurve', 'lk.search_lightcurve', ([], {'target': 'f"""TIC {tic}"""', 'mission': '"""TESS"""'}), "(target=f'TIC {tic}', mission='TESS')\n", (1108, 1145), True, 'import lightkurve as lk\n'), ((1843, 1856), 'numpy.argsort', 'np.argsort', (['t'], {}), '(t)\n', (1853, 1856), True, 'import numpy as np\n'), ((2357, 2375), 'pandas.read_csv', 'pd.read_csv', (['fname'], {}), '(fname)\n', (2368, 2375), True, 'import pandas as pd\n'), ((2948, 2975), 'os.path.join', 'os.path.join', (['outdir', 'fname'], {}), '(outdir, fname)\n', (2960, 2975), False, 'import os\n'), ((1278, 1320), 'numpy.where', 'np.where', (["(search.table['t_exptime'] == 120)"], {}), "(search.table['t_exptime'] == 120)\n", (1286, 1320), True, 'import numpy as np\n'), ((1894, 1941), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['t[inds]'], {'dtype': 'np.float64'}), '(t[inds], dtype=np.float64)\n', (1914, 1941), True, 'import numpy as np\n'), ((1960, 2036), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['(1000.0 * (data.flux.value[inds] - 1))'], {'dtype': 'np.float64'}), '(1000.0 * (data.flux.value[inds] - 1), dtype=np.float64)\n', (1980, 2036), True, 'import numpy as np\n'), ((2086, 2160), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['(1000.0 * data.flux_err.value[inds])'], {'dtype': 'np.float64'}), '(1000.0 * data.flux_err.value[inds], dtype=np.float64)\n', (2106, 2160), True, 'import numpy as np\n'), ((2468, 2485), 'numpy.array', 'np.array', (['df.time'], {}), '(df.time)\n', (2476, 2485), True, 'import numpy as np\n'), ((2504, 2521), 'numpy.array', 'np.array', (['df.flux'], {}), '(df.flux)\n', (2512, 2521), True, 'import numpy as np\n'), ((2544, 2565), 'numpy.array', 'np.array', (['df.flux_err'], {}), '(df.flux_err)\n', (2552, 2565), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from typing import List
from .util import (
assert_pandas_dtypes,
get_upper_matrix,
set_pair_ids,
get_available_eval_metrics,
get_available_similarity_metrics,
)
available_pairwise_similarity_metrics = get_available_similarity_metrics()
available_evaluation_metrics = get_available_eval_metrics()
def get_pairwise_metric(df: pd.DataFrame, similarity_metric: str) -> pd.DataFrame:
df = assert_pandas_dtypes(df=df, col_fix=np.float64)
assert (
similarity_metric in available_pairwise_similarity_metrics
), "{m} not supported. Available similarity metrics: {avail}".format(
m=similarity_metric, avail=available_pairwise_similarity_metrics
)
pair_df = df.transpose().corr(method=similarity_metric)
# Check if the metric calculation went wrong
# (Current pandas version makes this check redundant)
if pair_df.shape == (0, 0):
raise TypeError(
"Something went wrong - check that 'features' are profile measurements"
)
return pair_df
def process_melt(
df: pd.DataFrame, meta_df: pd.DataFrame, eval_metric: str = "percent_strong"
) -> pd.DataFrame:
assert df.shape[0] == df.shape[1], "Matrix must be symmetrical"
assert (
eval_metric in available_evaluation_metrics
), "{m} not supported. Available evaluation metrics: {avail}".format(
m=eval_metric, avail=available_evaluation_metrics
)
# Get identifiers for pairing metadata
pair_ids = set_pair_ids()
# Subset the pairwise similarity metric depending on the eval metric given:
# "percent_strong" - requires only the upper triangle of a symmetric matrix
# "precision_recall" - requires the full symmetric matrix (no diagonal)
# Remove pairwise matrix diagonal and redundant pairwise comparisons
if eval_metric == "percent_strong":
upper_tri = get_upper_matrix(df)
df = df.where(upper_tri)
else:
np.fill_diagonal(df.values, np.nan)
# Convert pairwise matrix to melted (long) version based on index value
metric_unlabeled_df = (
pd.melt(
df.reset_index(),
id_vars="index",
value_vars=df.columns,
var_name=pair_ids["pair_b"]["index"],
value_name="similarity_metric",
)
.dropna()
.reset_index(drop=True)
.rename({"index": pair_ids["pair_a"]["index"]}, axis="columns")
)
# Merge metadata on index for both comparison pairs
output_df = meta_df.merge(
meta_df.merge(
metric_unlabeled_df, left_index=True, right_on=pair_ids["pair_b"]["index"],
),
left_index=True,
right_on=pair_ids["pair_a"]["index"],
suffixes=[pair_ids["pair_a"]["suffix"], pair_ids["pair_b"]["suffix"]],
).reset_index(drop=True)
return output_df
def metric_melt(
df: pd.DataFrame,
features: List[str],
metadata_features: List[str],
eval_metric: str = "percent_strong",
similarity_metric: str = "pearson",
) -> pd.DataFrame:
# Subset dataframes to specific features
df = df.reset_index(drop=True)
assert all(
[x in df.columns for x in metadata_features]
), "Metadata feature not found"
assert all([x in df.columns for x in features]), "Profile feature not found"
meta_df = df.loc[:, metadata_features]
df = df.loc[:, features]
# Convert and assert conversion success
meta_df = assert_pandas_dtypes(df=meta_df, col_fix=np.str)
df = assert_pandas_dtypes(df=df, col_fix=np.float64)
# Get pairwise metric matrix
pair_df = get_pairwise_metric(df=df, similarity_metric=similarity_metric)
# Convert pairwise matrix into metadata-labeled melted matrix
output_df = process_melt(df=pair_df, meta_df=meta_df, eval_metric=eval_metric)
return output_df
| [
"numpy.fill_diagonal"
] | [((1986, 2021), 'numpy.fill_diagonal', 'np.fill_diagonal', (['df.values', 'np.nan'], {}), '(df.values, np.nan)\n', (2002, 2021), True, 'import numpy as np\n')] |
# This code takes the Radiosonde data from the website http://weather.uwyo.edu/upperair/sounding.html
# For any issue contact kvng vikram
year = 2018
month = 9
day = 27
time = 00
code = 43371
ask = False # set true if you want program to ask for a date to look at
mintemp = -100 # C
maxtemp = 40 # C
minthta = 280 # K
maxthta = 1000
# pressure axis range
minpress = 100 # hPa
maxpress = 1050 # hPa
pressres = 50 # resolution in p axis in hPa
# For constant mixing ration lines in g/kg
waxis = [0.01,0.05,0.1,0.2,0.35,0.5,0.75,1,1.5,2,3,4,5.5,6.5,8,10,12,16,20,24,28,32,40,48,56,64,72]
# constants
Rdry = 287.05 # J/(kg K)
Rvap = 461.52 # J/(kg K)
L = 2.27*10**6 # J/kg
Ttp = 0.01 # C
Etp = 6.11657 # hPa
Cp = 1004.0
CK = 273.0 # centrigrade to kelvin conversion offset
Epsilon = Rdry/Rvap
if ask :
print('\n\n\n\t\tGive the details of the date of the data\n\n')
date = input('\t\tdate\t:\t')
month = input('\t\tmonth\t:\t')
year = input('\t\tyear\t:\t')
print('\n\n\n')
from bs4 import BeautifulSoup as mbs
import requests
import numpy as np
import matplotlib.pyplot as plt
year = str(year)
month = str(month) if (int(month)>=10) else ('0'+str(month))
day = str(day) if (int(day) >= 10) else ('0'+str(day))
code = str(code)
webaddress = 'http://weather.uwyo.edu/cgi-bin/sounding?region=seasia&TYPE=TEXT%3ALIST&YEAR='+year+'&MONTH='+month+'&FROM='+day+'00&TO='+day+'00&STNM='+code
page = requests.get(webaddress)
#print('connection successful' if page.status_code == 200 else 'connection failed')
soup = mbs(page.text,'html.parser')
#print(soup)
dat = soup.find("pre")
#print(dat)
if dat is None :
print('\n\n\n\tSomething went wrong dude.')
print('\n\tCheck if you have given the right dates.')
print('\n\tIf nothing works then call KVNG Vikram, and both of you search in google together.\n\n\n\n')
else :
# not mydat is a string
mydat = str(dat)
#print(mydat)
# removing the headders and other characters so that only numbers are left
mydat = mydat[318:len(mydat)-7]
#print(mydat)
# removing the last line of data as it can be incomplete
mydata = mydat[:len(mydat)-78]
#print(mydata)
lines = mydata.splitlines()
p = np.array([])
h = np.array([])
t = np.array([])
td = np.array([])
rh = np.array([])
w = np.array([])
d = np.array([])
v = np.array([])
thta = np.array([])
thte = np.array([])
thtv = np.array([])
for i in range(len(lines)):
dummy = lines[i].split()
p = np.pad(p,(0,1),'constant',constant_values = float(dummy[0]))
h = np.pad(h,(0,1),'constant',constant_values = float(dummy[1]))
t = np.pad(t,(0,1),'constant',constant_values = float(dummy[2]))
td = np.pad(td,(0,1),'constant',constant_values = float(dummy[3]))
rh = np.pad(rh,(0,1),'constant',constant_values = float(dummy[4]))
w = np.pad(w,(0,1),'constant',constant_values = float(dummy[5]))
d = np.pad(d,(0,1),'constant',constant_values = float(dummy[6]))
v = np.pad(v,(0,1),'constant',constant_values = float(dummy[7]))
thta = np.pad(thta,(0,1),'constant',constant_values = float(dummy[8]))
# thte = np.pad(thte,(0,1),'constant',constant_values = float(dummy[9]))
# thtv = np.pad(thtv,(0,1),'constant',constant_values = float(dummy[10]))
def PT_to_ThetaT(P,T): # Units : hPa,C to K,C
return (T+CK)*(1000.0/P)**(Rdry/Cp) , T
def ThetaT_to_PT(Theta,T): # Units : K,C to hPa,C
return 1000.0*((T+CK)/Theta)**(Cp/Rdry) , T # from Poisson's equation
def WT_to_PT(W,T): # Units : g/kg,C to hPa,C
return ((Epsilon+(W/1000.0))/(W/1000.0))*Etp*np.exp((1/(Ttp+CK)-1/(T+CK))*L/Rvap) , T # from Clausius-Clapeyron Equation
plt.figure()
plt.axis([mintemp,maxtemp,minthta,np.max(thta)])
# plotting each isobar in a loop
paxis = np.linspace(maxpress,minpress,int((maxpress-minpress)/pressres)+1)
for pvar in paxis :
tmpx = np.linspace(mintemp,maxtemp,2)
tmpy,tmpx = PT_to_ThetaT(pvar,tmpx)
plt.plot(tmpx,tmpy,'g',linewidth=0.5)
for wvar in waxis:
tmpx = np.linspace(mintemp,maxtemp,50)
tmpp , tmpx = WT_to_PT(wvar,tmpx)
tmpy , tmpx = PT_to_ThetaT(tmpp,tmpx)
plt.plot(tmpx,tmpy,'r',linewidth=0.5)
plt.xlabel('Temperature in C')
plt.ylabel('Potentail temperature in K')
plt.grid(True)
plt.title('Tephigram')
# plt.legend()
TdTheta,td = PT_to_ThetaT(p,td)
TTheta , t = PT_to_ThetaT(p, t)
plt.plot(t,TTheta,label='TEMP',linewidth=2)
plt.plot(td,TdTheta,label='DWPT',linewidth=2)
plt.scatter(t,TTheta,label='TEMP',s=10)
plt.scatter(td,TdTheta,label='DWPT',s=10)
plt.show()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.figure",
"numpy.max",
"numpy.array",
"numpy.exp",
"requests.get",
"numpy.linspace",
"bs4.BeautifulSoup",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"m... | [((1480, 1504), 'requests.get', 'requests.get', (['webaddress'], {}), '(webaddress)\n', (1492, 1504), False, 'import requests\n'), ((1600, 1629), 'bs4.BeautifulSoup', 'mbs', (['page.text', '"""html.parser"""'], {}), "(page.text, 'html.parser')\n", (1603, 1629), True, 'from bs4 import BeautifulSoup as mbs\n'), ((2263, 2275), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2271, 2275), True, 'import numpy as np\n'), ((2282, 2294), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2290, 2294), True, 'import numpy as np\n'), ((2301, 2313), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2309, 2313), True, 'import numpy as np\n'), ((2321, 2333), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2329, 2333), True, 'import numpy as np\n'), ((2341, 2353), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2349, 2353), True, 'import numpy as np\n'), ((2360, 2372), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2368, 2372), True, 'import numpy as np\n'), ((2379, 2391), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2387, 2391), True, 'import numpy as np\n'), ((2398, 2410), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2406, 2410), True, 'import numpy as np\n'), ((2420, 2432), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2428, 2432), True, 'import numpy as np\n'), ((2442, 2454), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2450, 2454), True, 'import numpy as np\n'), ((2464, 2476), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2472, 2476), True, 'import numpy as np\n'), ((3740, 3752), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3750, 3752), True, 'import matplotlib.pyplot as plt\n'), ((4252, 4282), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Temperature in C"""'], {}), "('Temperature in C')\n", (4262, 4282), True, 'import matplotlib.pyplot as plt\n'), ((4285, 4325), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Potentail temperature in K"""'], {}), "('Potentail temperature in K')\n", (4295, 4325), True, 'import matplotlib.pyplot as plt\n'), ((4328, 4342), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (4336, 4342), True, 'import matplotlib.pyplot as plt\n'), ((4345, 4367), 'matplotlib.pyplot.title', 'plt.title', (['"""Tephigram"""'], {}), "('Tephigram')\n", (4354, 4367), True, 'import matplotlib.pyplot as plt\n'), ((4462, 4508), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'TTheta'], {'label': '"""TEMP"""', 'linewidth': '(2)'}), "(t, TTheta, label='TEMP', linewidth=2)\n", (4470, 4508), True, 'import matplotlib.pyplot as plt\n'), ((4508, 4556), 'matplotlib.pyplot.plot', 'plt.plot', (['td', 'TdTheta'], {'label': '"""DWPT"""', 'linewidth': '(2)'}), "(td, TdTheta, label='DWPT', linewidth=2)\n", (4516, 4556), True, 'import matplotlib.pyplot as plt\n'), ((4556, 4598), 'matplotlib.pyplot.scatter', 'plt.scatter', (['t', 'TTheta'], {'label': '"""TEMP"""', 's': '(10)'}), "(t, TTheta, label='TEMP', s=10)\n", (4567, 4598), True, 'import matplotlib.pyplot as plt\n'), ((4598, 4642), 'matplotlib.pyplot.scatter', 'plt.scatter', (['td', 'TdTheta'], {'label': '"""DWPT"""', 's': '(10)'}), "(td, TdTheta, label='DWPT', s=10)\n", (4609, 4642), True, 'import matplotlib.pyplot as plt\n'), ((4645, 4655), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4653, 4655), True, 'import matplotlib.pyplot as plt\n'), ((3951, 3983), 'numpy.linspace', 'np.linspace', (['mintemp', 'maxtemp', '(2)'], {}), '(mintemp, maxtemp, 2)\n', (3962, 3983), True, 'import numpy as np\n'), ((4024, 4064), 'matplotlib.pyplot.plot', 'plt.plot', (['tmpx', 'tmpy', '"""g"""'], {'linewidth': '(0.5)'}), "(tmpx, tmpy, 'g', linewidth=0.5)\n", (4032, 4064), True, 'import matplotlib.pyplot as plt\n'), ((4096, 4129), 'numpy.linspace', 'np.linspace', (['mintemp', 'maxtemp', '(50)'], {}), '(mintemp, maxtemp, 50)\n', (4107, 4129), True, 'import numpy as np\n'), ((4209, 4249), 'matplotlib.pyplot.plot', 'plt.plot', (['tmpx', 'tmpy', '"""r"""'], {'linewidth': '(0.5)'}), "(tmpx, tmpy, 'r', linewidth=0.5)\n", (4217, 4249), True, 'import matplotlib.pyplot as plt\n'), ((3789, 3801), 'numpy.max', 'np.max', (['thta'], {}), '(thta)\n', (3795, 3801), True, 'import numpy as np\n'), ((3658, 3708), 'numpy.exp', 'np.exp', (['((1 / (Ttp + CK) - 1 / (T + CK)) * L / Rvap)'], {}), '((1 / (Ttp + CK) - 1 / (T + CK)) * L / Rvap)\n', (3664, 3708), True, 'import numpy as np\n')] |
from typing import Dict
import numpy as np
from PIL import Image
from plyfile import PlyData
def load_model_points(path: str) -> np.ndarray:
"""
Load the model points from given path. The given path must be .xyz file of the object, the .ply file does not work here.
:param path: given path
:return: the loaded points of the model
"""
xyz = []
with open(path, 'r') as f:
_ = f.readline()
while True:
line = f.readline().rstrip()
if line == '':
break
xyz.append(list(map(float, line.split())))
xyz = np.float32(xyz)
return xyz[:, :3] # we only need the coordinates
def get_ply_model(path):
"""
Load the ply model of the object
"""
ply = PlyData.read(path)
data = ply.elements[0].data
x = data['x']
y = data['y']
z = data['z']
model = np.stack([x, y, z], axis=-1) * 100. # convert m to cm
return model
def load_depth_image(path: str) -> np.ndarray:
# shape (h, w), single channel
depth: np.ndarray = np.array(Image.open(path)) / 10. # depth from densefusion(unit is mm), we need cm as unit here
return depth
def save_dict_to_txt(d: Dict, fp: str) -> None:
"""
Save dict to txt file
:param d: dict to be saved
:param fp: file name
:return:
"""
content = str()
for key, value in d.items():
content += str(key) + ': ' + str(value) + '\n'
with open(fp, 'w') as f:
f.write(content)
| [
"numpy.stack",
"numpy.float32",
"plyfile.PlyData.read",
"PIL.Image.open"
] | [((525, 540), 'numpy.float32', 'np.float32', (['xyz'], {}), '(xyz)\n', (535, 540), True, 'import numpy as np\n'), ((670, 688), 'plyfile.PlyData.read', 'PlyData.read', (['path'], {}), '(path)\n', (682, 688), False, 'from plyfile import PlyData\n'), ((772, 800), 'numpy.stack', 'np.stack', (['[x, y, z]'], {'axis': '(-1)'}), '([x, y, z], axis=-1)\n', (780, 800), True, 'import numpy as np\n'), ((952, 968), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (962, 968), False, 'from PIL import Image\n')] |
import cv2
import gym
import gym_ple # NOQA
import numpy as np
from skimage.transform import rescale as sk_rescale
def create_env(env_hparams):
env = gym.make(env_hparams['env_id'])
env = PreprocessedEnv(env, **env_hparams)
return env
def rgb2gray(rgb):
return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])
def draw_shadow(image, of, thresh=0.6):
shadows = np.ones_like(image)
of_y = of[0:, 0:, 1]
shadows[of_y < thresh] = 0
return shadows
class PreprocessedEnv(gym.Wrapper):
def __init__(self, env, **kwargs):
super().__init__(env)
# observation settings
self.original_dim = list(self.env.observation_space.shape)
self.obs_shape = self.original_dim
self.normalize = False
self.opt_flow = False
# observation rescale settings
rescaled_shape = kwargs['observation']['rescaled_shape']
self.rescale = rescaled_shape is not None and len(rescaled_shape) > 0
if self.rescale:
zoom = [1, 1]
for i, dim in enumerate(self.original_dim[0:-1]):
zoom[i] = rescaled_shape[i]/dim
zoom[0], zoom[1] = zoom[1], zoom[0]
self.rescaled_shape = rescaled_shape
self.zoom = zoom
self.obs_shape = self.rescaled_shape
# action settings
self.actions = [] # mapped its index and action_space index
excluded_actions = kwargs['action']['excluded_actions']
if excluded_actions is None:
excluded_actions = []
for action in range(self.env.action_space.n):
if action not in excluded_actions:
self.actions.append(action)
# pre-activation
self._reset(**kwargs['observation'])
def _reset(self, **kwargs):
for kw in ['normalize', 'opt_flow', 'rescale']:
if kw in kwargs:
setattr(self, kw, kwargs[kw])
del kwargs[kw]
self.last_obs = None
self.last_obs_raw = None
self.last_action = None
self.last_action_raw = None
return kwargs
def reset(self, **kwargs):
kwargs = self._reset(**kwargs)
observation = self.env.reset(**kwargs)
return self.observation(observation)
def step(self, action):
action = self.action(action)
observation, reward, done, info = self.env.step(action)
return self.observation(observation), reward, done, info
def action(self, action):
self.last_action_raw = action
self.last_action = self.actions[action]
return self.last_action
def observation(self, observation):
self.last_obs_raw = np.copy(observation)
if self.rescale:
observation = sk_rescale(
observation, self.zoom, preserve_range=True)
if self.opt_flow:
observation = self.optical_flow(observation)
if self.normalize:
# TODO: /255 to (/127.5)-1
observation = observation/255.0
self.last_obs = np.copy(observation)
return observation
def optical_flow(self, observation):
gray = rgb2gray(observation)
if self.last_obs is not None:
of = cv2.calcOpticalFlowFarneback(
self.last_obs[0:, 0:, 0]*255,
gray*255, None, 0.5, 3, 5, 3, 5, 1.2, 0)
observation[0:, 0:, 0] = gray
observation[0:, 0:, 1] = of[0:, 0:, 0]/10
observation[0:, 0:, 2] = of[0:, 0:, 1]/10
else:
observation[0:, 0:, 0] = gray
observation[0:, 0:, 1] = observation[0:, 0:, 1]*0
observation[0:, 0:, 2] = observation[0:, 0:, 2]*0
return observation
| [
"numpy.ones_like",
"gym.make",
"numpy.copy",
"skimage.transform.rescale",
"cv2.calcOpticalFlowFarneback",
"numpy.dot"
] | [((157, 188), 'gym.make', 'gym.make', (["env_hparams['env_id']"], {}), "(env_hparams['env_id'])\n", (165, 188), False, 'import gym\n'), ((282, 325), 'numpy.dot', 'np.dot', (['rgb[..., :3]', '[0.299, 0.587, 0.114]'], {}), '(rgb[..., :3], [0.299, 0.587, 0.114])\n', (288, 325), True, 'import numpy as np\n'), ((382, 401), 'numpy.ones_like', 'np.ones_like', (['image'], {}), '(image)\n', (394, 401), True, 'import numpy as np\n'), ((2680, 2700), 'numpy.copy', 'np.copy', (['observation'], {}), '(observation)\n', (2687, 2700), True, 'import numpy as np\n'), ((3042, 3062), 'numpy.copy', 'np.copy', (['observation'], {}), '(observation)\n', (3049, 3062), True, 'import numpy as np\n'), ((2752, 2807), 'skimage.transform.rescale', 'sk_rescale', (['observation', 'self.zoom'], {'preserve_range': '(True)'}), '(observation, self.zoom, preserve_range=True)\n', (2762, 2807), True, 'from skimage.transform import rescale as sk_rescale\n'), ((3224, 3331), 'cv2.calcOpticalFlowFarneback', 'cv2.calcOpticalFlowFarneback', (['(self.last_obs[0:, 0:, 0] * 255)', '(gray * 255)', 'None', '(0.5)', '(3)', '(5)', '(3)', '(5)', '(1.2)', '(0)'], {}), '(self.last_obs[0:, 0:, 0] * 255, gray * 255,\n None, 0.5, 3, 5, 3, 5, 1.2, 0)\n', (3252, 3331), False, 'import cv2\n')] |
import numpy as np
import os
import wget
import zipfile
import logging
import pandas as pd
from scipy.stats import bernoulli
from sklearn.preprocessing import OneHotEncoder
from mskernel import util
class MeanShift():
def __init__(self, n_dim, n_change=10):
self.n_dim = n_dim
self.n_change = n_change
mu_change = np.zeros(n_dim)
for i in range(n_change):
mu_change[i] = 0.5
self.mu_change = mu_change
def sample(self, n_samples, seed):
n_dim = self.n_dim
with util.NumpySeedContext(seed=seed+2):
p = np.random.multivariate_normal(self.mu_change, np.eye(n_dim),size=(n_samples))
with util.NumpySeedContext(seed=seed+5):
r = np.random.multivariate_normal(np.zeros(n_dim), np.eye(n_dim),size=(n_samples))
return p, r
def is_true(self, s_feats):
true = s_feats < self.n_change
return true
class VarianceShift():
def __init__(self, n_dim, n_change=10):
self.n_dim = n_dim
self.n_change = n_change
v_change = np.ones(n_dim)
for i in range(n_change):
v_change[i] = 1.5
self.v_change = v_change
def sample(self, n_samples, seed):
n_dim = self.n_dim
with util.NumpySeedContext(seed=seed+2):
p = np.random.multivariate_normal(np.zeros(n_dim), np.eye(n_dim),size=(n_samples))
with util.NumpySeedContext(seed=seed+5):
r = np.random.multivariate_normal(np.zeros(n_dim), np.diag(self.v_change),size=(n_samples))
return p, r
def is_true(self, s_feats):
true = s_feats < self.n_change
return true
class Benchmark_MMD():
def __init__(self,
n_fakes=30,
path=None,
target=None,
classes=[0,1]):
# If needed download and unzip dataset.
if not os.path.isdir(path):
'''
url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00326/TV_News_Channel_Commercial_Detection_Dataset.zip'
location = path + '/dataset.zip'
os.makedirs(path)
wget.download(url, location)
zf = zipfile.ZipFile(location)
zf.extractall(path)
'''
self.df = pd.read_csv(path)
self.n_fakes = n_fakes
self.n_true = self.df.shape[1]-1
self.target = target
self.classes = classes
self.df.replace('', np.nan, inplace=True)
self.df = self.df.dropna()
def sample(self, n_samples, seed=5):
l_samples = []
for i, c in enumerate(self.classes):
df_samples = self.df[self.df[self.target]==c].drop(self.target,axis=1).sample(n_samples,
random_state=seed+i).values
with util.NumpySeedContext(seed=seed * (i+1)):
fakes = np.random.randn(n_samples, self.n_fakes)
l_samples.append(np.hstack((df_samples,fakes)))
return l_samples
def is_true(self, s_feats):
true = s_feats < self.n_true
return true
class Benchmark_HSIC():
def __init__(self,
n_fakes=30,
path=None,
target=None,
classes=[0,1],
**args):
# If needed download and unzip dataset.
if not os.path.isdir(path):
'''
url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00326/TV_News_Channel_Commercial_Detection_Dataset.zip'
location = path + '/dataset.zip'
os.makedirs(path)
wget.download(url, location)
zf = zipfile.ZipFile(location)
zf.extractall(path)
'''
self.df = pd.read_csv(path, **args)
self.n_fakes = n_fakes
self.n_true = self.df.shape[1]-1
self.target = target
self.classes = classes
enc = OneHotEncoder()
y = np.expand_dims(self.df[self.target].values,
axis=1)
enc.fit(y)
self.enc = enc
self.df.replace('', np.nan, inplace=True)
self.df.replace('?', np.nan, inplace=True)
self.df = self.df.dropna()
def sample(self, n_samples, seed=5):
l_samples = []
target_indices = np.isin(self.df[self.target].values, self.classes)
with util.NumpySeedContext(seed=seed):
df_samples = self.df[target_indices].sample(n_samples,
random_state=seed)
fakes = np.random.randn(n_samples, self.n_fakes)
y = np.expand_dims(df_samples[self.target].values,
axis=1)
y_enc = self.enc.transform(y).toarray()
x = df_samples.drop(self.target,axis=1).values
x = np.hstack((x,fakes)).astype(float)
return x, y_enc
def is_true(self, s_feats):
true = s_feats < self.n_true
return true
class CelebA():
def __init__(self, model_classes_mix, ref_classes_mix):
# Download dataset
feature_url = "http://ftp.tuebingen.mpg.de/pub/is/wittawat/kmod_share/problems/celeba/inception_features/"
feature_dir = "./dataset/celeba_features"
celeba_classes = ['gen_smile', 'gen_nonsmile', 'ref_smile', 'ref_nonsmile']
if not os.path.isdir(feature_dir):
logging.warning("Downloading dataset can take a long time")
os.makedirs(feature_dir)
for celeba_class in celeba_classes:
filename= '{}.npy'.format(celeba_class)
npy_path = os.path.join(feature_dir, filename)
url_path = os.path.join(feature_url, filename)
download_to(url_path,npy_path)
celeba_features = []
for celeba_class in celeba_classes:
filename= '{}.npy'.format(celeba_class)
npy_path = os.path.join(feature_dir, filename)
celeba_features.append(np.load(npy_path))
self.celeba_features = dict(zip(celeba_classes, celeba_features))
self.model_classes_mix = model_classes_mix
self.ref_classes_mix = ref_classes_mix
def is_true(self, s_feats):
true = s_feats < 0
return true
def sample(self, n_samples, seed=5):
## DISJOINT SET
model_features = {}
ref_samples = []
with util.NumpySeedContext(seed=seed):
## FOR EACH CELEBA CLASS
for key, features in self.celeba_features.items():
# CALCULATE HOW MUCH SHOULD BE IN THE REFERENCE POOL
n_ref_samples = int(np.round(self.ref_classes_mix[key] * n_samples))
random_features = np.random.permutation(features)
## FOR THE CANDIDATE MODELS
model_features[key] = random_features[n_ref_samples:]
## FOR THE REFERENCE
ref_samples.append(random_features[:n_ref_samples])
## samples for models
model_samples = []
for j,class_ratios in enumerate(self.model_classes_mix):
model_class_samples = []
for i, data_class in enumerate(class_ratios.keys()):
n_class_samples = int(np.round(class_ratios[data_class] * n_samples))
seed_class = i*n_samples+seed*j
with util.NumpySeedContext(seed=seed_class):
indices = np.random.choice(model_features[data_class].shape[0], n_class_samples)
model_class_samples.append(model_features[data_class][indices])
class_samples = dict(zip(class_ratios.keys(),model_class_samples))
model_class_stack = np.vstack(list(class_samples.values()))
model_samples.append(model_class_stack)
#assert model_class_stack.shape[0] == n_samples, "Sample size mismatch: {0} instead of {1}".format(samples.shape[0],n)
with util.NumpySeedContext(seed=seed+5):
ref_samples = np.random.permutation(np.vstack(ref_samples))
model_samples = [np.random.permutation(samples) for samples in model_samples]
assert ref_samples.shape[0] == n_samples, \
"Sample size mismatch: {0} instead of {1}".format(samples.shape[0],n)
return np.stack(model_samples,axis=1),\
np.repeat(ref_samples[:,np.newaxis] ,axis=1, repeats=len(model_samples))
class Logit():
def __init__(self, n_true, n_dim):
assert(n_true <= n_dim)
self.n_true = n_true
self.n_dim = n_dim
def sample(self, n_samples, seed=5):
with util.NumpySeedContext(seed=seed):
x = np.random.randn(n_samples, self.n_dim)
x_true = x[:,:self.n_true]
p = np.expand_dims(np.exp(np.sum(x_true, axis=1))/(1 + np.exp(np.sum(x_true, axis=1))),1)
with util.NumpySeedContext(seed=seed+1):
y_bern = bernoulli.rvs(p=p,size=(p.shape[0],1))
return x, y_bern
def is_true(self, select):
return select < self.n_true
def download_to(url, file_path):
"""
Download the file specified by the URL and save it to the file specified
by the file_path. Overwrite the file if exist.
"""
# see https://stackoverflow.com/questions/7243750/download-file-from-web-in-python-3
import urllib.request
import shutil
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, \
open(file_path, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
| [
"numpy.isin",
"numpy.load",
"numpy.sum",
"pandas.read_csv",
"numpy.ones",
"mskernel.util.NumpySeedContext",
"numpy.diag",
"os.path.join",
"numpy.round",
"numpy.random.randn",
"logging.warning",
"numpy.random.choice",
"shutil.copyfileobj",
"numpy.stack",
"scipy.stats.bernoulli.rvs",
"sk... | [((345, 360), 'numpy.zeros', 'np.zeros', (['n_dim'], {}), '(n_dim)\n', (353, 360), True, 'import numpy as np\n'), ((1076, 1090), 'numpy.ones', 'np.ones', (['n_dim'], {}), '(n_dim)\n', (1083, 1090), True, 'import numpy as np\n'), ((2271, 2288), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (2282, 2288), True, 'import pandas as pd\n'), ((3686, 3711), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path, **args)\n', (3697, 3711), True, 'import pandas as pd\n'), ((3858, 3873), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {}), '()\n', (3871, 3873), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((3886, 3937), 'numpy.expand_dims', 'np.expand_dims', (['self.df[self.target].values'], {'axis': '(1)'}), '(self.df[self.target].values, axis=1)\n', (3900, 3937), True, 'import numpy as np\n'), ((4222, 4272), 'numpy.isin', 'np.isin', (['self.df[self.target].values', 'self.classes'], {}), '(self.df[self.target].values, self.classes)\n', (4229, 4272), True, 'import numpy as np\n'), ((9376, 9414), 'shutil.copyfileobj', 'shutil.copyfileobj', (['response', 'out_file'], {}), '(response, out_file)\n', (9394, 9414), False, 'import shutil\n'), ((542, 578), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': '(seed + 2)'}), '(seed=seed + 2)\n', (563, 578), False, 'from mskernel import util\n'), ((686, 722), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': '(seed + 5)'}), '(seed=seed + 5)\n', (707, 722), False, 'from mskernel import util\n'), ((1269, 1305), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': '(seed + 2)'}), '(seed=seed + 2)\n', (1290, 1305), False, 'from mskernel import util\n'), ((1414, 1450), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': '(seed + 5)'}), '(seed=seed + 5)\n', (1435, 1450), False, 'from mskernel import util\n'), ((1876, 1895), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (1889, 1895), False, 'import os\n'), ((3291, 3310), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (3304, 3310), False, 'import os\n'), ((4286, 4318), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': 'seed'}), '(seed=seed)\n', (4307, 4318), False, 'from mskernel import util\n'), ((4446, 4486), 'numpy.random.randn', 'np.random.randn', (['n_samples', 'self.n_fakes'], {}), '(n_samples, self.n_fakes)\n', (4461, 4486), True, 'import numpy as np\n'), ((4503, 4557), 'numpy.expand_dims', 'np.expand_dims', (['df_samples[self.target].values'], {'axis': '(1)'}), '(df_samples[self.target].values, axis=1)\n', (4517, 4557), True, 'import numpy as np\n'), ((5223, 5249), 'os.path.isdir', 'os.path.isdir', (['feature_dir'], {}), '(feature_dir)\n', (5236, 5249), False, 'import os\n'), ((5263, 5322), 'logging.warning', 'logging.warning', (['"""Downloading dataset can take a long time"""'], {}), "('Downloading dataset can take a long time')\n", (5278, 5322), False, 'import logging\n'), ((5335, 5359), 'os.makedirs', 'os.makedirs', (['feature_dir'], {}), '(feature_dir)\n', (5346, 5359), False, 'import os\n'), ((5788, 5823), 'os.path.join', 'os.path.join', (['feature_dir', 'filename'], {}), '(feature_dir, filename)\n', (5800, 5823), False, 'import os\n'), ((6267, 6299), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': 'seed'}), '(seed=seed)\n', (6288, 6299), False, 'from mskernel import util\n'), ((7789, 7825), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': '(seed + 5)'}), '(seed=seed + 5)\n', (7810, 7825), False, 'from mskernel import util\n'), ((8140, 8171), 'numpy.stack', 'np.stack', (['model_samples'], {'axis': '(1)'}), '(model_samples, axis=1)\n', (8148, 8171), True, 'import numpy as np\n'), ((8460, 8492), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': 'seed'}), '(seed=seed)\n', (8481, 8492), False, 'from mskernel import util\n'), ((8510, 8548), 'numpy.random.randn', 'np.random.randn', (['n_samples', 'self.n_dim'], {}), '(n_samples, self.n_dim)\n', (8525, 8548), True, 'import numpy as np\n'), ((8695, 8731), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': '(seed + 1)'}), '(seed=seed + 1)\n', (8716, 8731), False, 'from mskernel import util\n'), ((8752, 8792), 'scipy.stats.bernoulli.rvs', 'bernoulli.rvs', ([], {'p': 'p', 'size': '(p.shape[0], 1)'}), '(p=p, size=(p.shape[0], 1))\n', (8765, 8792), False, 'from scipy.stats import bernoulli\n'), ((640, 653), 'numpy.eye', 'np.eye', (['n_dim'], {}), '(n_dim)\n', (646, 653), True, 'import numpy as np\n'), ((768, 783), 'numpy.zeros', 'np.zeros', (['n_dim'], {}), '(n_dim)\n', (776, 783), True, 'import numpy as np\n'), ((785, 798), 'numpy.eye', 'np.eye', (['n_dim'], {}), '(n_dim)\n', (791, 798), True, 'import numpy as np\n'), ((1351, 1366), 'numpy.zeros', 'np.zeros', (['n_dim'], {}), '(n_dim)\n', (1359, 1366), True, 'import numpy as np\n'), ((1368, 1381), 'numpy.eye', 'np.eye', (['n_dim'], {}), '(n_dim)\n', (1374, 1381), True, 'import numpy as np\n'), ((1496, 1511), 'numpy.zeros', 'np.zeros', (['n_dim'], {}), '(n_dim)\n', (1504, 1511), True, 'import numpy as np\n'), ((1513, 1535), 'numpy.diag', 'np.diag', (['self.v_change'], {}), '(self.v_change)\n', (1520, 1535), True, 'import numpy as np\n'), ((2778, 2820), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': '(seed * (i + 1))'}), '(seed=seed * (i + 1))\n', (2799, 2820), False, 'from mskernel import util\n'), ((2844, 2884), 'numpy.random.randn', 'np.random.randn', (['n_samples', 'self.n_fakes'], {}), '(n_samples, self.n_fakes)\n', (2859, 2884), True, 'import numpy as np\n'), ((2914, 2944), 'numpy.hstack', 'np.hstack', (['(df_samples, fakes)'], {}), '((df_samples, fakes))\n', (2923, 2944), True, 'import numpy as np\n'), ((5492, 5527), 'os.path.join', 'os.path.join', (['feature_dir', 'filename'], {}), '(feature_dir, filename)\n', (5504, 5527), False, 'import os\n'), ((5555, 5590), 'os.path.join', 'os.path.join', (['feature_url', 'filename'], {}), '(feature_url, filename)\n', (5567, 5590), False, 'import os\n'), ((5859, 5876), 'numpy.load', 'np.load', (['npy_path'], {}), '(npy_path)\n', (5866, 5876), True, 'import numpy as np\n'), ((6589, 6620), 'numpy.random.permutation', 'np.random.permutation', (['features'], {}), '(features)\n', (6610, 6620), True, 'import numpy as np\n'), ((7873, 7895), 'numpy.vstack', 'np.vstack', (['ref_samples'], {}), '(ref_samples)\n', (7882, 7895), True, 'import numpy as np\n'), ((7926, 7956), 'numpy.random.permutation', 'np.random.permutation', (['samples'], {}), '(samples)\n', (7947, 7956), True, 'import numpy as np\n'), ((4705, 4726), 'numpy.hstack', 'np.hstack', (['(x, fakes)'], {}), '((x, fakes))\n', (4714, 4726), True, 'import numpy as np\n'), ((6506, 6553), 'numpy.round', 'np.round', (['(self.ref_classes_mix[key] * n_samples)'], {}), '(self.ref_classes_mix[key] * n_samples)\n', (6514, 6553), True, 'import numpy as np\n'), ((7104, 7150), 'numpy.round', 'np.round', (['(class_ratios[data_class] * n_samples)'], {}), '(class_ratios[data_class] * n_samples)\n', (7112, 7150), True, 'import numpy as np\n'), ((7221, 7259), 'mskernel.util.NumpySeedContext', 'util.NumpySeedContext', ([], {'seed': 'seed_class'}), '(seed=seed_class)\n', (7242, 7259), False, 'from mskernel import util\n'), ((7291, 7361), 'numpy.random.choice', 'np.random.choice', (['model_features[data_class].shape[0]', 'n_class_samples'], {}), '(model_features[data_class].shape[0], n_class_samples)\n', (7307, 7361), True, 'import numpy as np\n'), ((8618, 8640), 'numpy.sum', 'np.sum', (['x_true'], {'axis': '(1)'}), '(x_true, axis=1)\n', (8624, 8640), True, 'import numpy as np\n'), ((8654, 8676), 'numpy.sum', 'np.sum', (['x_true'], {'axis': '(1)'}), '(x_true, axis=1)\n', (8660, 8676), True, 'import numpy as np\n')] |
"""
NAM: Data Reduction (module)
DES: contains the Data analysis methods for the MDAP pipeline.
"""
# ----------------------------------------------------------------------------------
# ----- Import ---------------------------------------------------------------------
# ----------------------------------------------------------------------------------
import Utilities as ut
from astropy.io import ascii
import numpy as np
import os
import tkinter as tk
from tkinter import filedialog
import concurrent.futures
import pickle
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema, argrelmin, argrelmax
import heapq
from astropy.stats import sigma_clip
# ----------------------------------------------------------------------------------
# ----- File Selection class -------------------------------------------------------
# ----------------------------------------------------------------------------------
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"
class BinaryConvert:
"""
Contains modules for the BINARY CONVERSION and Artifact Removal (Cleaning)
"""
def __init__(self):
self.mkid_exclude = []
self.idMKIDs_use = []
self.len_chunks = []
print(f"{bcolors.BOLD}Welcome!{bcolors.ENDC}")
print(f"Start by defining a path to the folder with the MKID readout data using {bcolors.RED}select_files(){bcolors.ENDC} method")
def select_files(self):
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilenames()
return file_path
def average_sweeps(self, filename):
"""
filename: file index.
Averages the up and down sweep values.
This is to be used internally.
"""
data = ascii.read(filename)
data_av = (data['col3'] + data['col4']) / 2. # averaging the two sweeps
print('File {} has been averaged'.format(filename))
return data_av
def read_single_col(self, filename, col=1):
"""
filename: file index.
Reads and returns the value from a column of a file
"""
data = ascii.read(filename)
data = [row[col] for row in data]
print("File {} has been read".format(filename))
return data
def save_fsp_pickle(self, fsp_files, filename, mode="average"):
# TODO: Add antlog and obs, time shift files as well into Xarray format.
"""
fsp_files: the list of MKID frequency shift raw files to be used.
filename: name of the file to be created.
Averages the up and down frequency sweep values values.
"""
average_values = []
if mode=="average":
with concurrent.futures.ProcessPoolExecutor() as executor:
for prime in executor.map(self.average_sweeps, fsp_files):
average_values.append(prime)
if mode =="single_col":
with concurrent.futures.ProcessPoolExecutor() as executor:
for prime in executor.map(self.read_single_col, fsp_files):
average_values.append(prime)
with open(str(filename)+'.pickle', 'wb') as handle:
pickle.dump(average_values, handle, protocol=pickle.HIGHEST_PROTOCOL)
print(f"File {filename} has been created successfully!")
def save_as_pickle(self, data, filename):
"""
fsp_files: the list of MKID frequency shift raw files to be used.
filename: name of the file to be created.
Averages the up and down frequency sweep values values.
"""
with open(str(filename)+'.pickle', 'wb') as handle:
pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)
print(f"File {filename} has been created successfully!")
def load_pickle(self, filename):
"""
filename: name of the pickle file to be loaded.
Loads the pickle file.
"""
with open(str(filename), 'rb') as handle:
data = pickle.load(handle)
self.idMKIDs_use = self.num_of_pixels(num=len(data)) # automatically creates num pixels
return data
def num_of_pixels(self, num):
"""
num: the number of pixels in the dataset
create a list of pixels to be used internally, does not return anything.
If not defined, exclusively, will use the length of data as number of pixels.
"""
return np.arange(1, num+1, 1)
def plot(self, data, id):
"""
data: the averaged data from fsp.
id: the index of the data to be plotted
plots the data for visualization.
"""
# TODO: make a window with plot where one can decide whether to use it or discard the TOD.
plt.title(f"TOD of MKID{id}")
plt.plot(data[id-1], ',')
plt.show()
def pixels_to_exclude(self, ids):
"""
ids: ids of MKIDs to be excluded
takes in ids and identifies bad mkids such that it is not used for data analysis stages.
"""
try:
if type(ids) is list :
self.mkid_exclude = ids
else:
raise TypeError
except TypeError:
print("the ids should be a list")
# ------------------ FREQUENCY IDENTIFICATION CODE--------------------
def identify_frequencies(self, data, minima_order=4000, exclude=True, plot=False, save_file=True, file_path="./"):
"""
data: is the TOD of frequency shift including the Hot-Rod reading.
return: file with frequency shift values, can save it as well as well.
"""
leave = []
frequencies = []
if exclude:
leave = self.mkid_exclude
else:
leave = []
for mkidid in range(len(data)):
if mkidid + 1 in leave:
print(mkidid + 1, 'excluded')
frequencies.append([mkidid + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
else:
l1 = data[mkidid]
minima_index, minima = self.minima_func(l1, minima_order) # 400 is chosen as an optimum order of argrelextrema to get
# just one minima at the load while recognising signal minimas near the load
fon, fonindex, fload, floadindex = self.indentify(minima_index, minima)
if plot:
plt.plot(l1)
plt.plot(minima_index, minima, 'o', color='purple')
plt.plot(fonindex, fon, 'o', color='red', label='f_brightest')
plt.plot(floadindex, fload, 'o', color='green', label='f_load')
plt.legend()
plt.title("MKID{:03}".format(mkidid + 1))
# plt.savefig('MKID{:03}frequency_detected.png'.format(mkidid + 1))
plt.show()
plt.close()
f_off = np.amax(l1)
f_off_index = [i for i, j in enumerate(l1) if j == f_off]
f_base = self.fbase_load_subtractor(l1, fload, floadindex)
f = [mkidid + 1, fon[0], fonindex[0], fload[0], floadindex[0], fload[1], floadindex[1], f_off,
f_off_index[0], f_base[0], f_base[1]]
frequencies.append(f)
if save_file:
np.savetxt((file_path + 'frequencies.txt'), frequencies, fmt='%s')
print("the Frequencies have been saved into a file titled \"Frequencies.txt\"")
return frequencies
def fbase_load_subtractor(self, data, fload, floadindex):
fbase1 = np.average(data[floadindex[0] + 2000:floadindex[0] + 3000])
fbase2 = np.average(data[floadindex[1] - 3000:floadindex[1] - 2000])
fbase = [fbase1 - fload[0], fbase2 - fload[1]]
# print( fbase, 'FBASE')
return fbase
def minima_func(self, data, order):
minima_index = argrelextrema(data, np.less, order=order)
minima = [data[i] for i in minima_index]
# print minima[0], minima_index[0]
return minima_index[0], minima[0]
def indentify(self, minima_index, minima):
fload = [heapq.nsmallest(1, minima)[-1], heapq.nsmallest(2, minima)[-1]]
# print fload, 'fload'
floadindex = [minima_index[i] for i, x in enumerate(minima) if x in fload]
fon = [heapq.nsmallest(3, minima)[-1]]
fonindex = [minima_index[i] for i, x in enumerate(minima) if x in fon]
# print fon, fonindex, fload, floadindex
return fon, fonindex, fload, floadindex
def average(self, data, value):
l = len(data)
print('total number of data points are', l)
############Reducing the data points by taking average-----------------------
ml = divmod(l, value)
print('to make an average over 100 data point,', ml[1], 'data from the end are rejected')
data = data[:-ml[1]]
x = np.array(data)
nx = np.mean(x.reshape(-1, value), axis=1) # averages it out over 100 points
print('the total data points after averaging are', len(nx))
return nx
# ------------------ CLEANING THE DATASET --------------------
def outlier_remove(self, data):
"""
data: The data from which the outlier is to be removed.
Automatically detects and removes outliers.
"""
# TODO: Outliers
pass
def changepoint_remove(self, data, patch, jump_at):
"""
data: The data from which the outlier is to be removed.
Automatically detects and removes outliers.
"""
# TODO: Actual Changepoint detection using an algorithm
for i in range(len(data)):
f = data[i]
mean_left = np.mean(f[jump_at - patch:jump_at])
mean_right = np.mean(f[jump_at: jump_at + patch])
diff_mean = mean_left - mean_right
f[jump_at:-1] = f[jump_at:-1] + diff_mean
data[i] = f
return data
# ------------------ Decorrelation --------------------
def mkids_used(self):
used = []
for idMKID in self.idMKIDs_use:
if idMKID not in self.mkid_exclude:
used.append(idMKID)
return used
def clip(self, data, starting_index, ending_index):
"""
Clips the data for decorrealtion
"""
res =[]
for idMKID in self.idMKIDs_use:
if idMKID not in self.mkid_exclude:
raw_data = data[idMKID-1]
raw_data = np.array(raw_data, dtype=float).transpose()
dat_FS = raw_data[starting_index:ending_index]
res.append(dat_FS)
res = np.array(res) # Very important
return res
def mean_center(self, data):
"""
removes the mean from each TOD
"""
for i in range(len(data)):
m = np.mean(data[i])
data[i] = data[i] - m
return data
def pca_decor(self, data, n_components=2):
"""
Decorrelates using PCA function
"""
res = ut.work_pca(data, n_components)
res = np.array(res)
return res
def flatten(self, pca_data, index, save=False):
flat = []
for i in range(len(pca_data)):
flat.append(pca_data[i][:, index])
flat = np.array(flat)
# TODO: see if flat is top be saved or not
return flat
def get_sigmaclipped_mask(self, data, avg_points=32, sigma=4, maxiters=5, axis = 1):
"""
Returns mask
"""
running_avged = []
for i in range(len(data)):
running_avged.append(np.convolve(data[i], np.ones((avg_points,)) / avg_points, mode='same'))
print(np.shape(running_avged))
# running_avged = normalize(running_avged)
filtered_data = sigma_clip(running_avged, sigma=sigma, maxiters=maxiters, axis=axis)
mask = np.ma.getmask(filtered_data)
return mask
def make_chunk_matrix(self, mask, num_chunks):
"""
returns the chunk matrix
"""
num_chunks = num_chunks
len_chunks = int(mask.shape[1] / num_chunks) # TODO: make it take fraction as well
self.len_chunks = len_chunks
len_remaining = mask.shape[1] % num_chunks # see if there are left over data
if len_remaining != 0:
chunk_matrix = np.zeros((len(mask), num_chunks + 1))
for i in range(len(mask)):
for j in range(num_chunks):
dot_val = np.prod(~mask[i][(j * len_chunks):(len_chunks * (j + 1))])
chunk_matrix[i][j] = (~dot_val + 2)
chunk_matrix[i][num_chunks] = (~(np.prod(~mask[i][(-len_chunks):-1])) + 2)
return chunk_matrix
elif len_remaining == 0:
chunk_matrix = np.zeros((len(mask), num_chunks))
for i in range(len(mask)):
for j in range(num_chunks):
dot_val = np.prod(~mask[i][(j * len_chunks):(len_chunks * (j + 1))])
chunk_matrix[i][j] = (~dot_val + 2)
return chunk_matrix
def chunkpca_decor(self, mask, chunk_matrix, data):
"""
returns decorrelated data using ChunkPCA
"""
t_chunk = chunk_matrix.T
len_chunks = self.len_chunks
for i in range(len(t_chunk)): # range(len(t_chunk))
pooled_data = []
full = []
empty = []
for j in range(len(t_chunk[i])): # LET'S CALL IT THE "POOLING METHOD"
if t_chunk[i][j] == 0:
val = data[j][(i * len_chunks):(len_chunks * (i + 1))]
pooled_data.append(val - np.mean(val)) # mean centering the pooled_data
full.append(j)
elif t_chunk[i][j] == 1:
empty.append(j)
print("chunk {} pool data length is {}".format(i, np.shape(pooled_data)))
result_masked_pca = ut.work_pca(pooled_data, n_components=3) # pca on the pool
result_masked_pca = np.array(result_masked_pca)
##### TODO: make sure the empty doesn't have too much of the pixels, since then the pca won't work.
# print("unused pixels in chunk {}".format(i + 1))
# print(empty)
############# Finding the baseline using the most correlated components from the pooled_data #############
correlated = []
for q in empty:
val = data[q][(i * len_chunks):(len_chunks * (i + 1))]
correlation_matrix = np.corrcoef(np.vstack((pooled_data, val)))
fpr = []
for w, t in enumerate(correlation_matrix[-1]):
if t > 0:
fpr.append(w)
correlated.append([q, fpr[:-1]])
############# Putting the missing pixels values with proper data, baseline #############
for k in empty:
val = data[k][(i * len_chunks):(len_chunks * (i + 1))]
masked_val = np.ma.masked_array(data[k][(i * len_chunks):(len_chunks * (i + 1))],
mask[k][(i * len_chunks):(len_chunks * (i + 1))])
val = val - np.mean(masked_val)
for x in correlated:
if x[0] == k:
empty_baseline_pool = []
for p in x[1]:
if p not in empty:
got = result_masked_pca[p][:, 1]
empty_baseline_pool.append(got)
baseline = np.mean(empty_baseline_pool, axis=0)
dat = val - baseline
average = np.stack([dat, baseline, val], axis=1)
result_masked_pca = np.insert(result_masked_pca, k, average, 0)
# print("Final", np.shape(result_masked_pca))
##### JOINING ALL THE CHUNKS ######
if i == 0:
final = result_masked_pca
else:
final = np.concatenate([final, result_masked_pca], axis=1)
return final
# ------------------ Calibration --------------------
def load_frequency(self):
"""
loads and returns frequency file
"""
try:
freq = np.loadtxt("frequencies.txt")
except FileNotFoundError:
print("File \'frequencies.txt\' not found! create it using identify_frequencies, with save=True")
return freq
def find_source_frequency(self, data, minimaorder):
"""
data: The decorrelated data, with the source being the lowest point in the observation
returns the frequency at the brightest point of the source observation(lowest)
"""
f_bright = []
# find the lowest point.
# TODO: Make this parallel
for i in range(len(data)):
l1 = data[i]
minima_index, minima = self.minima_func(l1, minimaorder)
# print(minima_index, minima)
f_brightest = heapq.nsmallest(1, minima)[-1]
f_bright.append([i + 1, f_brightest])
print(f_bright)
#find the matching pixel id.
pix_bright = []
index = []
for idMKID in self.idMKIDs_use:
if idMKID not in self.mkid_exclude:
index.append(idMKID)
for i in range(len(f_bright)):
pix_bright.append([index[i], f_bright[i][1]])
return pix_bright
def antenna_temperature(self, frequency_table, pix_fbright, t_atm, exclude, plot=False):
"""
frequency_table: the frequency file generated using "identify_frequencies"
frequency_brightest: ferq and f_brightest created using find_source_frequency
t_atm: the atmospheric temperature that day
exclude: 1darray of elements filtered by beamsize
returns the pixel-id and antenna temperature.
"""
t_a = []
f_load_av = []
for k in range(len(pix_fbright)):
index = pix_fbright[k][0]
if index not in exclude:
# print(index)
j = int(index - 1)
f_load = np.mean([frequency_table[j][-1], frequency_table[j][-2]])
f_load_av.append(f_load)
if f_load != 0:
# print(j, f_load)
# print(k)
t_a.append([index, -t_atm * (pix_fbright[k][1] / f_load)])
t_a = np.array(t_a)
if plot:
plt.rcParams['figure.figsize'] = [10, 6]
plt.title("$T_a^*$ plot")
plt.plot(t_a[:, 0], t_a[:, 1], "o", c='r')
plt.hlines(np.average(t_a[:, 1]), xmin=0, xmax=np.amax(t_a[:, 0]), label="average :{: .2f} K".format(np.average(t_a[:, 1])))
plt.xlabel("elements")
plt.ylabel("Antenna temperature (K)")
plt.ylim(0,50)
plt.legend()
plt.show()
return t_a
def _planck(self, nu, T):
h = 6.626e-34
# c = 3.0e+8
k = 1.38e-23
a = (h * nu) / k
b = (np.exp((h * nu) / (k * T)) - 1)
intensity = a / b
return intensity
def _main_beam_efficiency(self, ta_star, nu, t_source, theta_eq, theta_pol, theta_mb):
mb_eff = ta_star / (t_source * (1 - np.exp(-np.log(2)*((theta_eq * theta_pol)/(theta_mb**2)))))
# mb_eff = (0.5 * ta_star) / ((self._planck(nu, t_source) - self._planck(nu, 2.28)) * (
# 1 - np.exp(-np.log(2) * ((theta_eq * theta_pol) / (theta_mb ** 2)))))
return mb_eff
def get_main_beam_efficiency(self, ta_star, nu, t_source, theta_eq, theta_pol, beamsize, plot=False):
eta_mb = []
beamsize = np.array(beamsize)
print(len(ta_star))
print(len(beamsize))
for i in range(len(ta_star)):
eta_mb.append([ta_star[i][0], self._main_beam_efficiency(ta_star[i][1], nu, t_source, theta_eq, theta_pol, beamsize[i][1])])
eta_mb = np.array(eta_mb)
eta_mb[:, 1] = eta_mb[:, 1] * 100
if plot:
plt.rcParams['figure.figsize'] = [10, 6]
plt.title("$\eta_{\mathrm{mb}}$ plot")
plt.plot(eta_mb[:, 0],eta_mb[:, 1], "o")
plt.hlines(np.average(eta_mb[:, 1]), xmin=0, xmax=np.amax(eta_mb[:, 0]), label="average :{: .2f} %".format(np.average(eta_mb[:, 1])))
plt.xlabel("elements")
plt.ylabel("Main Beam efficiency")
plt.ylim(0,60)
plt.legend()
plt.show()
return eta_mb
def aperture_efficiency(self, etamb, beamsize, wavelength=0.00285517, D=45, plot = True):
"""
etamb: etamb from main beam effieciency output
wavelength: wavelength of observation
Ap: Aperture area
"""
tmb = []
for i in range(len(etamb)):
val = ((etamb[i][1]/100) / ((((beamsize[i][1] * np.pi)/(180*3600))**2) * 0.8899 * ((D**2)/(wavelength**2))))
# val = ((D**2)/(wavelength**2))
tmb.append([etamb[i][0], val])
tmb = np.array(tmb)
tmb[:, 1] = tmb[:, 1] * 100
if plot:
plt.rcParams['figure.figsize'] = [10, 6]
plt.title("$\eta_{\mathrm{A}}$ plot")
plt.plot(tmb[:, 0],tmb[:, 1], "o", c="purple")
plt.hlines(np.average(tmb[:, 1]), xmin=0, xmax=np.amax(tmb[:, 0]), label="average :{: .2f} %".format(np.average(tmb[:, 1])))
plt.xlabel("elements")
plt.ylabel("Aperture efficiency")
plt.ylim(0,40)
plt.legend()
plt.show()
return eta_mb | [
"matplotlib.pyplot.title",
"pickle.dump",
"astropy.io.ascii.read",
"Utilities.work_pca",
"numpy.ones",
"numpy.shape",
"pickle.load",
"numpy.arange",
"numpy.mean",
"numpy.exp",
"numpy.ma.masked_array",
"numpy.ma.getmask",
"numpy.prod",
"astropy.stats.sigma_clip",
"scipy.signal.argrelextre... | [((1772, 1779), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (1777, 1779), True, 'import tkinter as tk\n'), ((1825, 1854), 'tkinter.filedialog.askopenfilenames', 'filedialog.askopenfilenames', ([], {}), '()\n', (1852, 1854), False, 'from tkinter import filedialog\n'), ((2080, 2100), 'astropy.io.ascii.read', 'ascii.read', (['filename'], {}), '(filename)\n', (2090, 2100), False, 'from astropy.io import ascii\n'), ((2445, 2465), 'astropy.io.ascii.read', 'ascii.read', (['filename'], {}), '(filename)\n', (2455, 2465), False, 'from astropy.io import ascii\n'), ((4747, 4771), 'numpy.arange', 'np.arange', (['(1)', '(num + 1)', '(1)'], {}), '(1, num + 1, 1)\n', (4756, 4771), True, 'import numpy as np\n'), ((5068, 5097), 'matplotlib.pyplot.title', 'plt.title', (['f"""TOD of MKID{id}"""'], {}), "(f'TOD of MKID{id}')\n", (5077, 5097), True, 'import matplotlib.pyplot as plt\n'), ((5106, 5133), 'matplotlib.pyplot.plot', 'plt.plot', (['data[id - 1]', '""","""'], {}), "(data[id - 1], ',')\n", (5114, 5133), True, 'import matplotlib.pyplot as plt\n'), ((5140, 5150), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5148, 5150), True, 'import matplotlib.pyplot as plt\n'), ((7888, 7947), 'numpy.average', 'np.average', (['data[floadindex[0] + 2000:floadindex[0] + 3000]'], {}), '(data[floadindex[0] + 2000:floadindex[0] + 3000])\n', (7898, 7947), True, 'import numpy as np\n'), ((7965, 8024), 'numpy.average', 'np.average', (['data[floadindex[1] - 3000:floadindex[1] - 2000]'], {}), '(data[floadindex[1] - 3000:floadindex[1] - 2000])\n', (7975, 8024), True, 'import numpy as np\n'), ((8198, 8239), 'scipy.signal.argrelextrema', 'argrelextrema', (['data', 'np.less'], {'order': 'order'}), '(data, np.less, order=order)\n', (8211, 8239), False, 'from scipy.signal import argrelextrema, argrelmin, argrelmax\n'), ((9211, 9225), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (9219, 9225), True, 'import numpy as np\n'), ((10970, 10983), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (10978, 10983), True, 'import numpy as np\n'), ((11368, 11399), 'Utilities.work_pca', 'ut.work_pca', (['data', 'n_components'], {}), '(data, n_components)\n', (11379, 11399), True, 'import Utilities as ut\n'), ((11414, 11427), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (11422, 11427), True, 'import numpy as np\n'), ((11619, 11633), 'numpy.array', 'np.array', (['flat'], {}), '(flat)\n', (11627, 11633), True, 'import numpy as np\n'), ((12124, 12192), 'astropy.stats.sigma_clip', 'sigma_clip', (['running_avged'], {'sigma': 'sigma', 'maxiters': 'maxiters', 'axis': 'axis'}), '(running_avged, sigma=sigma, maxiters=maxiters, axis=axis)\n', (12134, 12192), False, 'from astropy.stats import sigma_clip\n'), ((12208, 12236), 'numpy.ma.getmask', 'np.ma.getmask', (['filtered_data'], {}), '(filtered_data)\n', (12221, 12236), True, 'import numpy as np\n'), ((18824, 18837), 'numpy.array', 'np.array', (['t_a'], {}), '(t_a)\n', (18832, 18837), True, 'import numpy as np\n'), ((20093, 20111), 'numpy.array', 'np.array', (['beamsize'], {}), '(beamsize)\n', (20101, 20111), True, 'import numpy as np\n'), ((20364, 20380), 'numpy.array', 'np.array', (['eta_mb'], {}), '(eta_mb)\n', (20372, 20380), True, 'import numpy as np\n'), ((21453, 21466), 'numpy.array', 'np.array', (['tmb'], {}), '(tmb)\n', (21461, 21466), True, 'import numpy as np\n'), ((3504, 3573), 'pickle.dump', 'pickle.dump', (['average_values', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(average_values, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (3515, 3573), False, 'import pickle\n'), ((3973, 4032), 'pickle.dump', 'pickle.dump', (['data', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(data, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (3984, 4032), False, 'import pickle\n'), ((4319, 4338), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (4330, 4338), False, 'import pickle\n'), ((7621, 7685), 'numpy.savetxt', 'np.savetxt', (["(file_path + 'frequencies.txt')", 'frequencies'], {'fmt': '"""%s"""'}), "(file_path + 'frequencies.txt', frequencies, fmt='%s')\n", (7631, 7685), True, 'import numpy as np\n'), ((10028, 10063), 'numpy.mean', 'np.mean', (['f[jump_at - patch:jump_at]'], {}), '(f[jump_at - patch:jump_at])\n', (10035, 10063), True, 'import numpy as np\n'), ((10089, 10124), 'numpy.mean', 'np.mean', (['f[jump_at:jump_at + patch]'], {}), '(f[jump_at:jump_at + patch])\n', (10096, 10124), True, 'import numpy as np\n'), ((11170, 11186), 'numpy.mean', 'np.mean', (['data[i]'], {}), '(data[i])\n', (11177, 11186), True, 'import numpy as np\n'), ((12023, 12046), 'numpy.shape', 'np.shape', (['running_avged'], {}), '(running_avged)\n', (12031, 12046), True, 'import numpy as np\n'), ((14271, 14311), 'Utilities.work_pca', 'ut.work_pca', (['pooled_data'], {'n_components': '(3)'}), '(pooled_data, n_components=3)\n', (14282, 14311), True, 'import Utilities as ut\n'), ((14363, 14390), 'numpy.array', 'np.array', (['result_masked_pca'], {}), '(result_masked_pca)\n', (14371, 14390), True, 'import numpy as np\n'), ((16635, 16664), 'numpy.loadtxt', 'np.loadtxt', (['"""frequencies.txt"""'], {}), "('frequencies.txt')\n", (16645, 16664), True, 'import numpy as np\n'), ((18922, 18947), 'matplotlib.pyplot.title', 'plt.title', (['"""$T_a^*$ plot"""'], {}), "('$T_a^*$ plot')\n", (18931, 18947), True, 'import matplotlib.pyplot as plt\n'), ((18960, 19002), 'matplotlib.pyplot.plot', 'plt.plot', (['t_a[:, 0]', 't_a[:, 1]', '"""o"""'], {'c': '"""r"""'}), "(t_a[:, 0], t_a[:, 1], 'o', c='r')\n", (18968, 19002), True, 'import matplotlib.pyplot as plt\n'), ((19152, 19174), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""elements"""'], {}), "('elements')\n", (19162, 19174), True, 'import matplotlib.pyplot as plt\n'), ((19187, 19224), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Antenna temperature (K)"""'], {}), "('Antenna temperature (K)')\n", (19197, 19224), True, 'import matplotlib.pyplot as plt\n'), ((19237, 19252), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(50)'], {}), '(0, 50)\n', (19245, 19252), True, 'import matplotlib.pyplot as plt\n'), ((19264, 19276), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (19274, 19276), True, 'import matplotlib.pyplot as plt\n'), ((19289, 19299), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19297, 19299), True, 'import matplotlib.pyplot as plt\n'), ((19455, 19479), 'numpy.exp', 'np.exp', (['(h * nu / (k * T))'], {}), '(h * nu / (k * T))\n', (19461, 19479), True, 'import numpy as np\n'), ((20507, 20547), 'matplotlib.pyplot.title', 'plt.title', (['"""$\\\\eta_{\\\\mathrm{mb}}$ plot"""'], {}), "('$\\\\eta_{\\\\mathrm{mb}}$ plot')\n", (20516, 20547), True, 'import matplotlib.pyplot as plt\n'), ((20558, 20599), 'matplotlib.pyplot.plot', 'plt.plot', (['eta_mb[:, 0]', 'eta_mb[:, 1]', '"""o"""'], {}), "(eta_mb[:, 0], eta_mb[:, 1], 'o')\n", (20566, 20599), True, 'import matplotlib.pyplot as plt\n'), ((20757, 20779), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""elements"""'], {}), "('elements')\n", (20767, 20779), True, 'import matplotlib.pyplot as plt\n'), ((20792, 20826), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Main Beam efficiency"""'], {}), "('Main Beam efficiency')\n", (20802, 20826), True, 'import matplotlib.pyplot as plt\n'), ((20839, 20854), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(60)'], {}), '(0, 60)\n', (20847, 20854), True, 'import matplotlib.pyplot as plt\n'), ((20866, 20878), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20876, 20878), True, 'import matplotlib.pyplot as plt\n'), ((20891, 20901), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20899, 20901), True, 'import matplotlib.pyplot as plt\n'), ((21587, 21626), 'matplotlib.pyplot.title', 'plt.title', (['"""$\\\\eta_{\\\\mathrm{A}}$ plot"""'], {}), "('$\\\\eta_{\\\\mathrm{A}}$ plot')\n", (21596, 21626), True, 'import matplotlib.pyplot as plt\n'), ((21637, 21684), 'matplotlib.pyplot.plot', 'plt.plot', (['tmb[:, 0]', 'tmb[:, 1]', '"""o"""'], {'c': '"""purple"""'}), "(tmb[:, 0], tmb[:, 1], 'o', c='purple')\n", (21645, 21684), True, 'import matplotlib.pyplot as plt\n'), ((21833, 21855), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""elements"""'], {}), "('elements')\n", (21843, 21855), True, 'import matplotlib.pyplot as plt\n'), ((21868, 21901), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Aperture efficiency"""'], {}), "('Aperture efficiency')\n", (21878, 21901), True, 'import matplotlib.pyplot as plt\n'), ((21914, 21929), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(40)'], {}), '(0, 40)\n', (21922, 21929), True, 'import matplotlib.pyplot as plt\n'), ((21941, 21953), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (21951, 21953), True, 'import matplotlib.pyplot as plt\n'), ((21966, 21976), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (21974, 21976), True, 'import matplotlib.pyplot as plt\n'), ((7217, 7228), 'numpy.amax', 'np.amax', (['l1'], {}), '(l1)\n', (7224, 7228), True, 'import numpy as np\n'), ((8440, 8466), 'heapq.nsmallest', 'heapq.nsmallest', (['(1)', 'minima'], {}), '(1, minima)\n', (8455, 8466), False, 'import heapq\n'), ((8472, 8498), 'heapq.nsmallest', 'heapq.nsmallest', (['(2)', 'minima'], {}), '(2, minima)\n', (8487, 8498), False, 'import heapq\n'), ((8634, 8660), 'heapq.nsmallest', 'heapq.nsmallest', (['(3)', 'minima'], {}), '(3, minima)\n', (8649, 8660), False, 'import heapq\n'), ((15359, 15473), 'numpy.ma.masked_array', 'np.ma.masked_array', (['data[k][i * len_chunks:len_chunks * (i + 1)]', 'mask[k][i * len_chunks:len_chunks * (i + 1)]'], {}), '(data[k][i * len_chunks:len_chunks * (i + 1)], mask[k][i *\n len_chunks:len_chunks * (i + 1)])\n', (15377, 15473), True, 'import numpy as np\n'), ((16044, 16082), 'numpy.stack', 'np.stack', (['[dat, baseline, val]'], {'axis': '(1)'}), '([dat, baseline, val], axis=1)\n', (16052, 16082), True, 'import numpy as np\n'), ((16119, 16162), 'numpy.insert', 'np.insert', (['result_masked_pca', 'k', 'average', '(0)'], {}), '(result_masked_pca, k, average, 0)\n', (16128, 16162), True, 'import numpy as np\n'), ((16379, 16429), 'numpy.concatenate', 'np.concatenate', (['[final, result_masked_pca]'], {'axis': '(1)'}), '([final, result_masked_pca], axis=1)\n', (16393, 16429), True, 'import numpy as np\n'), ((17387, 17413), 'heapq.nsmallest', 'heapq.nsmallest', (['(1)', 'minima'], {}), '(1, minima)\n', (17402, 17413), False, 'import heapq\n'), ((18529, 18586), 'numpy.mean', 'np.mean', (['[frequency_table[j][-1], frequency_table[j][-2]]'], {}), '([frequency_table[j][-1], frequency_table[j][-2]])\n', (18536, 18586), True, 'import numpy as np\n'), ((19026, 19047), 'numpy.average', 'np.average', (['t_a[:, 1]'], {}), '(t_a[:, 1])\n', (19036, 19047), True, 'import numpy as np\n'), ((20622, 20646), 'numpy.average', 'np.average', (['eta_mb[:, 1]'], {}), '(eta_mb[:, 1])\n', (20632, 20646), True, 'import numpy as np\n'), ((21707, 21728), 'numpy.average', 'np.average', (['tmb[:, 1]'], {}), '(tmb[:, 1])\n', (21717, 21728), True, 'import numpy as np\n'), ((6694, 6706), 'matplotlib.pyplot.plot', 'plt.plot', (['l1'], {}), '(l1)\n', (6702, 6706), True, 'import matplotlib.pyplot as plt\n'), ((6727, 6778), 'matplotlib.pyplot.plot', 'plt.plot', (['minima_index', 'minima', '"""o"""'], {'color': '"""purple"""'}), "(minima_index, minima, 'o', color='purple')\n", (6735, 6778), True, 'import matplotlib.pyplot as plt\n'), ((6799, 6861), 'matplotlib.pyplot.plot', 'plt.plot', (['fonindex', 'fon', '"""o"""'], {'color': '"""red"""', 'label': '"""f_brightest"""'}), "(fonindex, fon, 'o', color='red', label='f_brightest')\n", (6807, 6861), True, 'import matplotlib.pyplot as plt\n'), ((6882, 6945), 'matplotlib.pyplot.plot', 'plt.plot', (['floadindex', 'fload', '"""o"""'], {'color': '"""green"""', 'label': '"""f_load"""'}), "(floadindex, fload, 'o', color='green', label='f_load')\n", (6890, 6945), True, 'import matplotlib.pyplot as plt\n'), ((6966, 6978), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (6976, 6978), True, 'import matplotlib.pyplot as plt\n'), ((7149, 7159), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7157, 7159), True, 'import matplotlib.pyplot as plt\n'), ((7180, 7191), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7189, 7191), True, 'import matplotlib.pyplot as plt\n'), ((12823, 12877), 'numpy.prod', 'np.prod', (['(~mask[i][j * len_chunks:len_chunks * (j + 1)])'], {}), '(~mask[i][j * len_chunks:len_chunks * (j + 1)])\n', (12830, 12877), True, 'import numpy as np\n'), ((14215, 14236), 'numpy.shape', 'np.shape', (['pooled_data'], {}), '(pooled_data)\n', (14223, 14236), True, 'import numpy as np\n'), ((14892, 14921), 'numpy.vstack', 'np.vstack', (['(pooled_data, val)'], {}), '((pooled_data, val))\n', (14901, 14921), True, 'import numpy as np\n'), ((15554, 15573), 'numpy.mean', 'np.mean', (['masked_val'], {}), '(masked_val)\n', (15561, 15573), True, 'import numpy as np\n'), ((19062, 19080), 'numpy.amax', 'np.amax', (['t_a[:, 0]'], {}), '(t_a[:, 0])\n', (19069, 19080), True, 'import numpy as np\n'), ((20661, 20682), 'numpy.amax', 'np.amax', (['eta_mb[:, 0]'], {}), '(eta_mb[:, 0])\n', (20668, 20682), True, 'import numpy as np\n'), ((21743, 21761), 'numpy.amax', 'np.amax', (['tmb[:, 0]'], {}), '(tmb[:, 0])\n', (21750, 21761), True, 'import numpy as np\n'), ((10814, 10845), 'numpy.array', 'np.array', (['raw_data'], {'dtype': 'float'}), '(raw_data, dtype=float)\n', (10822, 10845), True, 'import numpy as np\n'), ((11958, 11980), 'numpy.ones', 'np.ones', (['(avg_points,)'], {}), '((avg_points,))\n', (11965, 11980), True, 'import numpy as np\n'), ((12987, 13020), 'numpy.prod', 'np.prod', (['(~mask[i][-len_chunks:-1])'], {}), '(~mask[i][-len_chunks:-1])\n', (12994, 13020), True, 'import numpy as np\n'), ((13268, 13322), 'numpy.prod', 'np.prod', (['(~mask[i][j * len_chunks:len_chunks * (j + 1)])'], {}), '(~mask[i][j * len_chunks:len_chunks * (j + 1)])\n', (13275, 13322), True, 'import numpy as np\n'), ((15944, 15980), 'numpy.mean', 'np.mean', (['empty_baseline_pool'], {'axis': '(0)'}), '(empty_baseline_pool, axis=0)\n', (15951, 15980), True, 'import numpy as np\n'), ((19116, 19137), 'numpy.average', 'np.average', (['t_a[:, 1]'], {}), '(t_a[:, 1])\n', (19126, 19137), True, 'import numpy as np\n'), ((20718, 20742), 'numpy.average', 'np.average', (['eta_mb[:, 1]'], {}), '(eta_mb[:, 1])\n', (20728, 20742), True, 'import numpy as np\n'), ((21797, 21818), 'numpy.average', 'np.average', (['tmb[:, 1]'], {}), '(tmb[:, 1])\n', (21807, 21818), True, 'import numpy as np\n'), ((13993, 14005), 'numpy.mean', 'np.mean', (['val'], {}), '(val)\n', (14000, 14005), True, 'import numpy as np\n'), ((19683, 19692), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (19689, 19692), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib_scalebar.scalebar import ScaleBar, ANGULAR
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(X ** 2) - Y ** 2)
Z2 = np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = (Z1 - Z2) * 2
fig, axes = plt.subplots(1, 3, figsize=(9, 3))
for ax, dx in zip(axes, [delta, delta / 60, delta / 3600]):
ax.imshow(Z)
scalebar = ScaleBar(dx, "deg", ANGULAR)
ax.add_artist(scalebar)
ax.set_title("dx = {:.6f}deg".format(dx))
fig.savefig("example_angular.png")
| [
"numpy.meshgrid",
"numpy.arange",
"numpy.exp",
"matplotlib_scalebar.scalebar.ScaleBar",
"matplotlib.pyplot.subplots"
] | [((166, 193), 'numpy.arange', 'np.arange', (['(-3.0)', '(3.0)', 'delta'], {}), '(-3.0, 3.0, delta)\n', (175, 193), True, 'import numpy as np\n'), ((201, 218), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (212, 218), True, 'import numpy as np\n'), ((224, 248), 'numpy.exp', 'np.exp', (['(-X ** 2 - Y ** 2)'], {}), '(-X ** 2 - Y ** 2)\n', (230, 248), True, 'import numpy as np\n'), ((256, 292), 'numpy.exp', 'np.exp', (['(-(X - 1) ** 2 - (Y - 1) ** 2)'], {}), '(-(X - 1) ** 2 - (Y - 1) ** 2)\n', (262, 292), True, 'import numpy as np\n'), ((326, 360), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(9, 3)'}), '(1, 3, figsize=(9, 3))\n', (338, 360), True, 'import matplotlib.pyplot as plt\n'), ((455, 483), 'matplotlib_scalebar.scalebar.ScaleBar', 'ScaleBar', (['dx', '"""deg"""', 'ANGULAR'], {}), "(dx, 'deg', ANGULAR)\n", (463, 483), False, 'from matplotlib_scalebar.scalebar import ScaleBar, ANGULAR\n')] |
"""
Created by: <NAME>
Sep 21
IEEE Fraud Detection Model
- FE009
- Adding raddar user level features
- Add first, second, third digit of addr1 and addr2 features
- Drop only DOY features with low importance
- Different Parameters
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import sys
import matplotlib.pylab as plt
from sklearn.model_selection import KFold
from datetime import datetime
import time
import logging
from sklearn.metrics import roc_auc_score
from catboost import CatBoostClassifier, Pool
from timeit import default_timer as timer
import lightgbm as lgb
import gc
start = timer()
##################
# PARAMETERS
###################
run_id = "{:%m%d_%H%M}".format(datetime.now())
KERNEL_RUN = False
MODEL_NUMBER = os.path.basename(__file__).split('.')[0]
if KERNEL_RUN:
INPUT_DIR = '../input/champs-scalar-coupling/'
FE_DIR = '../input/molecule-fe024/'
FOLDS_DIR = '../input/champs-3fold-ids/'
TARGET = "isFraud"
N_ESTIMATORS = 100000
N_META_ESTIMATORS = 500000
LEARNING_RATE = 0.005
VERBOSE = 100
EARLY_STOPPING_ROUNDS = 100
RANDOM_STATE = 529
N_THREADS = 58
DEPTH = -1 #14
N_FOLDS = 5
SHUFFLE = False
FE_SET = 'FE010' # Feature Engineering Version
MODEL_TYPE = "lightgbm"
#####################
## SETUP LOGGER
#####################
def get_logger():
"""
credits to: https://www.kaggle.com/ogrellier/user-level-lightgbm-lb-1-4480
"""
os.environ["TZ"] = "US/Eastern"
time.tzset()
FORMAT = "[%(levelname)s]%(asctime)s:%(name)s:%(message)s"
logging.basicConfig(format=FORMAT)
logger = logging.getLogger("main")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
fhandler = logging.FileHandler(f'../logs/{MODEL_NUMBER}_{run_id}.log')
formatter = logging.Formatter(FORMAT)
handler.setFormatter(formatter)
# logger.addHandler(handler)
logger.addHandler(fhandler)
return logger
logger = get_logger()
logger.info(f'Running for Model Number {MODEL_NUMBER}')
##################
# PARAMETERS
###################
if MODEL_TYPE == 'xgboost':
EVAL_METRIC = "AUC"
elif MODEL_TYPE == 'lightgbm':
EVAL_METRIC = 'auc'
elif MODEL_TYPE == 'catboost':
EVAL_METRIC = "AUC"
##################
# TRACKING FUNCTION
###################
def update_tracking(run_id,
field,
value, csv_file="../tracking/tracking.csv", integer=False, digits=None, drop_incomplete_rows=False):
"""
Function to update the tracking CSV with information about the model
"""
try:
df = pd.read_csv(csv_file, index_col=[0])
except FileNotFoundError:
df = pd.DataFrame()
if integer:
value = round(value)
elif digits is not None:
value = round(value, digits)
if drop_incomplete_rows:
df = df.loc[~df['AUC'].isna()]
df.loc[run_id, field] = value # Model number is index
df.to_csv(csv_file)
update_tracking(run_id, "model_number", MODEL_NUMBER, drop_incomplete_rows=True)
update_tracking(run_id, "n_estimators", N_ESTIMATORS)
update_tracking(run_id, "early_stopping_rounds", EARLY_STOPPING_ROUNDS)
update_tracking(run_id, "random_state", RANDOM_STATE)
update_tracking(run_id, "n_threads", N_THREADS)
update_tracking(run_id, "learning_rate", LEARNING_RATE)
update_tracking(run_id, "n_fold", N_FOLDS)
update_tracking(run_id, "model_type", MODEL_TYPE)
update_tracking(run_id, "eval_metric", EVAL_METRIC)
update_tracking(run_id, "depth", DEPTH)
update_tracking(run_id, "shuffle", SHUFFLE)
update_tracking(run_id, "fe", FE_SET)
#####################
# PREPARE MODEL DATA
#####################
folds = KFold(n_splits=N_FOLDS, random_state=RANDOM_STATE, shuffle=SHUFFLE)
logger.info('Loading Data...')
train_df = pd.read_parquet(f'../data/train_{FE_SET}.parquet')
test_df = pd.read_parquet(f'../data/test_{FE_SET}.parquet')
logger.info('Done loading Data...')
###########
# FEATURES
###########
FEATURES = ['V85',
'bank_type_TransactionAmt_mean',
'D5_fq_enc',
'V12',
'V81',
'V282',
'bank_type_D7_std',
'id_15',
'V13',
'C12_fq_enc',
'anomaly',
'D7_DT_D_std_score',
'D3_DT_D_min_max',
'card4_count_full',
'D14_DT_D_min_max',
'card1_count_full',
'V169',
'D3_DT_M_min_max',
'V279',
'V91',
'bank_type_D10_std',
'D14',
'D6_DT_M_std_score',
'D4_DT_W_min_max',
'V152',
'V56',
'D3_intercept_bin0',
'D14_intercept_bin0',
'V220',
'V277',
'D12_intercept',
'ProductCD_W_00cents',
'D13_intercept_bin0',
'V291',
'V189',
'D15_DT_M_min_max',
'C5_fq_enc',
'D3_fq_enc',
'card5_fq_enc',
'addr1_count_full',
'V266',
'D11_intercept_bin2',
'V23',
'D4_intercept_bin3',
'bank_type_D10_mean',
'D2_intercept_bin3',
'V306',
'DeviceType',
'V285',
'D5_DT_W_std_score',
'V131',
'V37',
'V296',
'bank_type_D1_mean',
'V75',
'D3_DT_W_std_score',
'D10_DT_M_min_max',
'id_33_0',
'V67',
'D4_intercept_bin4',
'V256',
'V143',
'uid5_D6_std',
'ProductCD_target_mean',
'mxC3',
'V129',
'D13_DT_M_std_score',
'V24',
'D3_DT_M_std_score',
'mxC4',
'D9',
'id_30_version_fq_enc',
'D5_DT_D_std_score',
'D11_DT_M_std_score',
'uid5_D6_mean',
'D14_DT_M_std_score',
'card5_TransactionAmt_std',
'V20',
'C8_fq_enc',
'V70',
'V127',
'D6_intercept',
'D15_DT_W_min_max',
'sum_Cxx_binary_higher_than_q95',
'V156',
'uid4_D12_mean',
'C5',
'uid4_D12_std',
'id_30_fq_enc',
'V61',
'id_33',
'D15_to_std_addr1',
'bank_type_D9_mean',
'D5_intercept',
'D10_DT_W_min_max',
'V130',
'bank_type_D9_std',
'uid5_D7_std',
'bank_type_D14_mean',
'bank_type_D3_std',
'bank_type_D5_mean',
'ProductCD',
'M8',
'V44',
'D6_fq_enc',
'D15_DT_D_min_max',
'D11_intercept_bin0',
'V257',
'bank_type_D7_mean',
'V76',
'D15',
'V38',
'V55',
'V261',
'V149',
'D4',
'D8_intercept_bin0',
'M2',
'bank_type_D6_std',
'id_30_version',
'D4_intercept_bin1',
'D15_to_mean_card4',
'V82',
'D3_DT_D_std_score',
'D10_intercept_bin3',
'bank_type_D2_std',
'V77',
'M7',
'D11',
'D4_intercept_bin2',
'email_check',
'V294',
'V317',
'V308',
'id_33_fq_enc',
'bank_type_D5_std',
'D8_intercept',
'V62',
'V187',
'card5_TransactionAmt_mean',
'bank_type_D12_mean',
'id_33_count_dist',
'D2_intercept_bin2',
'C10',
'V86',
'D8_DT_M_min_max',
'D15_intercept_bin4',
'D6_DT_W_std_score',
'uid5_D7_mean',
'C9_fq_enc',
'mxC10',
'D14_DT_W_std_score',
'card2_count_full',
'V258',
'bank_type_D14_std',
'D10_intercept_bin4',
'V83',
'bank_type_D13_std',
'D8_DT_W_min_max',
'TransactionAmt',
'V312',
'D14_intercept',
'id_33_1',
'D15_intercept_bin2',
'D12_DT_W_std_score',
'V78',
'D8_D9_decimal_dist',
'M9',
'V281',
'bank_type_D12_std',
'V54',
'C9',
'M4_target_mean',
'sum_Cxx_binary_higher_than_q90',
'D10_DT_D_min_max',
'bank_type_D3_mean',
'bank_type_D8_mean',
'R_emaildomain_prefix',
'bank_type_D6_mean',
'V314',
'D11_DT_W_std_score',
'D10',
'D4_DT_D_min_max',
'V283',
'D10_intercept_bin2',
'D13_intercept',
'D8_DT_D_min_max',
'C2_fq_enc',
'V165',
'D1_intercept_bin4',
'bank_type_D13_mean',
'D3_intercept',
'TransactionAmt_2Dec',
'card3_div_Mean_D9_DOY',
'C12',
'D4_DT_M_std_score',
'D2_intercept_bin1',
'mxC8',
'D2_fq_enc',
'addr1_third_digit',
'D4_fq_enc',
'D1_fq_enc',
'mxC12',
'D8',
'D10_intercept_bin1',
'id_01',
'id_09',
'id_03',
'addr1_second_digit',
'D15_to_mean_addr1',
'sum_Cxx_binary_higher_than_q80',
'V53',
'TransactionAmt_decimal',
'card3_div_Mean_D6_DOY',
'D15_intercept_bin3',
'V45',
'id_02_to_std_card4',
'addr2_div_Mean_D10_DOY_productCD',
'DeviceInfo_version',
'DeviceInfo_device',
'D1_intercept_bin3',
'D11_intercept',
'DeviceInfo_version_fq_enc',
'C6',
'uid5_D13_std',
'TransactionAmt_DT_M_min_max',
'dist2',
'C8',
'D15_intercept_bin1',
'M3',
'R_emaildomain_fq_enc',
'DeviceInfo_device_fq_enc',
'D6_DT_D_std_score',
'sum_Cxx_binary_higher_than_q60',
'D11__DeviceInfo',
'TranAmt_div_Mean_D12_DOY_productCD',
'D10_DT_M_std_score',
'uid5_D13_mean',
'mxC5',
'id_30',
'addr2_div_Mean_D4_DOY',
'uid2_D12_std',
'C11_fq_enc',
'id_06',
'uid2_D12_mean',
'sum_Cxx_binary_higher_than_q70',
'V310',
'V307',
'C6_fq_enc',
'D8_fq_enc',
'dist2_fq_enc',
'D2_intercept_bin0',
'addr1_div_Mean_D10_DOY_productCD',
'addr1_div_Mean_D10_DOY',
'addr1_div_Mean_D11_DOY',
'uid2_D8_std',
'id_02__id_20',
'V313',
'D4_intercept_bin0',
'D11_DT_D_std_score',
'Transaction_day_of_week',
'card6_div_Mean_D3_DOY',
'uid2_D1_std',
'uid5_D11_mean',
'uid_fq_enc',
'D14_DT_D_std_score',
'D12_DT_D_std_score',
'id_02_to_mean_card4',
'uid4_D13_std',
'D1_intercept_bin1',
'id_02_to_std_card1',
'uid5_D11_std',
'P_emaildomain_prefix',
'DT_day',
'D8_DT_M_std_score',
'uid2_D1_mean',
'TransactionAmt_to_mean_card4',
'card5_div_Mean_D11_DOY',
'D15_DT_M_std_score',
'V87',
'uid_D12_std',
'id_31_device_fq_enc',
'uid2_D11_mean',
'card3_DT_W_week_day_dist_best',
'uid5_D14_std',
'uid2_D15_mean',
'sum_Cxx_binary_higher_than_q50',
'id_13',
'card3_div_Mean_D11_DOY',
'C11',
'bank_type_DT_W_week_day_dist_best',
'card4_div_Mean_D11_DOY',
'addr1_div_Mean_D1_DOY',
'uid2_D4_mean',
'card2_div_Mean_D11_DOY',
'C13_fq_enc',
'uid4_D13_mean',
'card5_DT_W_week_day_dist_best',
'id_02',
'uid5_D14_mean',
'uid2_D10_mean',
'id_01_count_dist',
'D13_DT_W_std_score',
'C2',
'C14',
'addr2_div_Mean_D10_DOY',
'uid2_D11_std',
'addr1_div_Mean_D1_DOY_productCD',
'id_02_to_mean_card1',
'dist1_fq_enc',
'card1_div_Mean_D11_DOY',
'D15_to_std_card1',
'TransactionAmt_DT_M_std_score',
'uid2_D6_std',
'TransactionAmt_to_std_card4',
'uid2_D15_std',
'uid3_D8_std',
'card6_div_Mean_D11_DOY',
'TranAmt_div_Mean_D14_DOY',
'card3_div_Mean_D14_DOY',
'D2',
'D1',
'uid_D15_mean',
'uid4_D6_std',
'uid_D15_std',
'D10_intercept_bin0',
'DeviceInfo_fq_enc',
'uid2_D13_std',
'uid_D12_mean',
'uid4_D6_mean',
'uid_D1_std',
'D1_intercept_bin2',
'uid_D10_mean',
'card2__id_20',
'uid4_D7_std',
'uid3_D13_std',
'C14_fq_enc',
'uid_D8_std',
'uid3_D13_mean',
'uid2_D4_std',
'addr1_div_Mean_D4_DOY',
'uid_D4_mean',
'D4_DT_W_std_score',
'addr2_div_Mean_D1_DOY_productCD',
'uid_D11_mean',
'D15_intercept_bin0',
'uid2_D10_std',
'uid_D13_std',
'uid2_fq_enc',
'uid2_D13_mean',
'uid2_D2_mean',
'D2_intercept',
'uid_D11_std',
'card2',
'uid4_D14_std',
'C_sum_after_clip75',
'R_emaildomain',
'dist1',
'id_05',
'uid_TransactionAmt_mean',
'uid_D1_mean',
'uid3_D1_std',
'uid5_D8_std',
'uid3_D6_std',
'Transaction_hour_of_day',
'uid4_D14_mean',
'uid5_D10_std',
'uid3_D10_std',
'uid5_D1_std',
'uid5_D15_std',
'uid2_D7_mean',
'uid3_D11_std',
'uid4_D8_std',
'D13_DT_D_std_score',
'uid3_D11_mean',
'uid2_D14_std',
'uid2_D7_std',
'uid2_D14_mean',
'uid_D13_mean',
'uid_D10_std',
'uid2_D3_std',
'uid_D6_std',
'uid3_D15_std',
'addr1_fq_enc',
'id_31',
'uid_TransactionAmt_std',
'card1_div_Mean_D4_DOY_productCD',
'uid2_TransactionAmt_mean',
'C_sum_after_clip90',
'uid2_TransactionAmt_std',
'uid4_D7_mean',
'uid2_D6_mean',
'uid3_D15_mean',
'D15_to_mean_card1',
'uid5_D15_mean',
'M4',
'uid3_D7_std',
'card2_div_Mean_D4_DOY',
'card5_div_Mean_D4_DOY_productCD',
'card5_div_Mean_D4_DOY',
'D4_intercept',
'uid_D4_std',
'card6_div_Mean_D4_DOY_productCD',
'card5__P_emaildomain',
'card1_fq_enc',
'uid5_D10_mean',
'card1_div_Mean_D4_DOY',
'C1',
'M6',
'uid2_D2_std',
'P_emaildomain_fq_enc',
'card1_TransactionAmt_mean',
'uid3_D10_mean',
'TransactionAmt_DT_W_min_max',
'uid5_D4_std',
'card1_div_Mean_D10_DOY_productCD',
'uid3_D1_mean',
'card1_div_Mean_D10_DOY',
'uid_D14_mean',
'mxC9',
'TranAmt_div_Mean_D4_DOY_productCD',
'D15_DT_W_std_score',
'DeviceInfo__P_emaildomain',
'uid3_D14_mean',
'bank_type_DT_M',
'mxC11',
'uid5_D1_mean',
'uid_D2_mean',
'D10_DT_W_std_score',
'card3_DT_M_month_day_dist_best',
'uid3_D2_std',
'TranAmt_div_Mean_D4_DOY',
'card1_TransactionAmt_std',
'card3_div_Mean_D4_DOY_productCD',
'D1_intercept_bin0',
'uid3_D4_std',
'card2_div_Mean_D10_DOY',
'uid_D2_std',
'uid3_D14_std',
'uid3_D4_mean',
'uid_D7_mean',
'uid5_D2_std',
'card4_div_Mean_D4_DOY_productCD',
'card6_div_Mean_D4_DOY',
'TranAmt_div_Mean_D10_DOY',
'uid2_D9_std',
'TransactionAmt_DT_W_std_score',
'C1_fq_enc',
'card1_div_Mean_D1_DOY',
'uid5_D4_mean',
'uid3_D6_mean',
'mxC14',
'uid5_D2_mean',
'card4_div_Mean_D4_DOY',
'card3_div_Mean_D4_DOY',
'uid_D14_std',
'M5',
'C13',
'mxC6',
'card5_div_Mean_D10_DOY_productCD',
'card3_DT_M_month_day_dist',
'card2_div_Mean_D10_DOY_productCD',
'uid_D7_std',
'card2_div_Mean_D4_DOY_productCD',
'bank_type_DT_M_month_day_dist',
'uid3_D7_mean',
'uid_D3_std',
'uid5_fq_enc',
'uid3_fq_enc',
'uid_D3_mean',
'D4_DT_D_std_score',
'uid3_D2_mean',
'uid4_D1_std',
'uid2_D5_std',
'uid4_D10_std',
'bank_type_DT_D_hour_dist_best',
'uid2_D8_mean',
'card6_div_Mean_D10_DOY_productCD',
'card1_div_Mean_D1_DOY_productCD',
'uid5_D9_std',
'card4_div_Mean_D10_DOY_productCD',
'uid2_D3_mean',
'uid_D6_mean',
'card2_div_Mean_D1_DOY',
'card5_div_Mean_D10_DOY',
'mxC2',
'card2_TransactionAmt_std',
'bank_type_DT_W_week_day_dist',
'card2_TransactionAmt_mean',
'uid4_D10_mean',
'id_31_count_dist',
'TranAmt_div_Mean_D1_DOY',
'uid3_D3_std',
'uid4_D15_std',
'card5_div_Mean_D1_DOY_productCD',
'card4_div_Mean_D10_DOY',
'card5_DT_D_hour_dist_best',
'uid4_D4_std',
'card5_DT_M_month_day_dist',
'bank_type_DT_W',
'addr1__card1',
'bank_type_DT_M_month_day_dist_best',
'card2_div_Mean_D1_DOY_productCD',
'card6_div_Mean_D10_DOY',
'uid2_D5_mean',
'uid_DT_M',
'card2__dist1',
'uid2_D9_mean',
'card5_DT_M_month_day_dist_best',
'TranAmt_div_Mean_D10_DOY_productCD',
'uid4_D11_std',
'uid_D5_mean',
'uid5_D3_std',
'TransactionAmt_DT_D_std_score',
'D8_DT_W_std_score',
'card5_DT_W_week_day_dist',
'uid5_D5_std',
'card3_DT_W_week_day_dist',
'uid4_D9_std',
'D10_intercept',
'uid3_D3_mean',
'uid4_D5_std',
'uid_D5_std',
'card5_div_Mean_D1_DOY',
'uid5_D3_mean',
'bank_type_DT_D',
'uid4_D1_mean',
'uid_D8_mean',
'uid3_D5_mean',
'D15_intercept',
'uid5_TransactionAmt_std',
'uid3_D5_std',
'uid4_D4_mean',
'uid4_D15_mean',
'uid5_D8_mean',
'uid5_D9_mean',
'uid_D9_std',
'uid_D9_mean',
'uid5_D5_mean',
'mtransamt',
'bank_type_DT_D_hour_dist',
'uid4_D11_mean',
'D15_DT_D_std_score',
'TransactionAmt_DT_D_min_max',
'uid4_D2_mean',
'ntrans',
'addr2_div_Mean_D1_DOY',
'uid5_TransactionAmt_mean',
'uid3_D9_std',
'TransactionAmt_Dec',
'uid3_TransactionAmt_std',
'card5_DT_D_hour_dist',
'card1',
'card4_div_Mean_D1_DOY_productCD',
'P_emaildomain__C2',
'card3_div_Mean_D10_DOY',
'uid4_D3_std',
'card3_DT_D_hour_dist_best',
'uid4_D8_mean',
'uid4_D2_std',
'card6_div_Mean_D1_DOY_productCD',
'uid_DT_W',
'Sum_TransAmt_Day',
'uid4_D5_mean',
'card4_div_Mean_D1_DOY',
'card3_div_Mean_D10_DOY_productCD',
'uid3_D8_mean',
'TransactionAmt_userid_median',
'uid4_fq_enc',
'uid3_TransactionAmt_mean',
'uid3_D9_mean',
'card6_div_Mean_D1_DOY',
'Trans_Count_Day',
'mxC1',
'D10_DT_D_std_score',
'card3_div_Mean_D1_DOY',
'TransactionAmt_to_mean_card1',
'card2_fq_enc',
'product_type',
'card3_div_Mean_D1_DOY_productCD',
'TransactionAmt_to_std_card1',
'uid_DT_D',
'uid4_D9_mean',
'D1_intercept',
'card3_DT_D_hour_dist',
'TranAmt_div_Mean_D1_DOY_productCD',
'product_type_DT_M',
'uid4_D3_mean',
'uid4_TransactionAmt_mean',
'uid4_TransactionAmt_std',
'D8_DT_D_std_score',
'Mean_TransAmt_Day',
'minDT',
'product_type_DT_W',
'mintransamt',
'maxtransamt',
'TransactionAmt_userid_std',
'P_emaildomain',
'card1__card5',
'product_type_DT_D',
'mxC13',
'maxDT',
'id_19',
'DeviceInfo',
'id_20',
'addr1']
CAT_FEATURES = ['ProductCD', 'card4', 'card6',
'id_12', 'id_13', 'id_14',
'id_15', 'id_16', 'id_17',
'id_18', 'id_19', 'id_20',
'id_21',
'id_22',
'id_23',
'id_24',
'id_25',
'id_26',
'id_27',
'id_28',
'id_29',
'id_32',
'id_34',
'id_35',
'id_36', 'id_37', 'id_38',
'DeviceType', 'DeviceInfo',
'M4','P_emaildomain',
'R_emaildomain', 'addr1', 'addr2',
'M1', 'M2', 'M3', 'M5', 'M6', 'M7', 'M8', 'M9',
'ProductCD_W_95cents','ProductCD_W_00cents','ProductCD_W_50cents',
'ProductCD_W_50_95_0_cents','ProductCD_W_NOT_50_95_0_cents']
CAT_FEATURES = [c for c in CAT_FEATURES if c in FEATURES]
X = train_df[FEATURES].copy()
y = train_df[TARGET].copy()
X_test = test_df[FEATURES].copy()
X = X.fillna(-9999)
X_test = X_test.fillna(-9999)
logger.info('Running with features...')
logger.info(FEATURES)
logger.info(f'Target is {TARGET}')
update_tracking(run_id, "n_features", len(FEATURES), integer=True)
############################
#### TRAIN MODELS FUNCTIONS
############################
def train_catboost(X_train, y_train, X_valid, y_valid, X_test, CAT_FEATURES, fold_n, feature_importance):
train_dataset = Pool(data=X_train, label=y_train, cat_features=CAT_FEATURES)
valid_dataset = Pool(data=X_valid, label=y_valid, cat_features=CAT_FEATURES)
test_dataset = Pool(data=X_test, cat_features=CAT_FEATURES)
model = CatBoostClassifier(
iterations=N_ESTIMATORS,
learning_rate=LEARNING_RATE,
depth=DEPTH,
eval_metric=EVAL_METRIC,
verbose=VERBOSE,
random_state=RANDOM_STATE,
thread_count=N_THREADS,
task_type="GPU")
model.fit(
train_dataset,
eval_set=valid_dataset,
early_stopping_rounds=EARLY_STOPPING_ROUNDS,
)
y_pred_valid = model.predict_proba(valid_dataset)[:,1]
y_pred = model.predict_proba(test_dataset)[:,1]
fold_importance = pd.DataFrame()
fold_importance["feature"] = model.feature_names_
fold_importance["importance"] = model.get_feature_importance()
fold_importance["fold"] = fold_n + 1
feature_importance = pd.concat([feature_importance, fold_importance],
axis=0)
best_iteration = model.best_iteration_
return y_pred, y_pred_valid, feature_importance, best_iteration
lgb_params = {
'objective':'binary',
'boosting_type':'gbdt',
'metric': EVAL_METRIC,
'n_jobs':N_THREADS,
'learning_rate':LEARNING_RATE,
'num_leaves': 2**8,
'max_depth':DEPTH,
'tree_learner':'serial',
'colsample_bytree': 0.85,
'subsample_freq':1,
'subsample':0.85,
'n_estimators':N_ESTIMATORS,
'max_bin':255,
'verbose':-1,
'seed': RANDOM_STATE,
#'early_stopping_rounds':EARLY_STOPPING_ROUNDS,
'reg_alpha':0.3,
'reg_lamdba':0.243,
#'categorical_feature': CAT_FEATURES
}
# lgb_params = {
# 'min_data_in_leaf': 106,
# 'num_leaves': 500,
# 'learning_rate': LEARNING_RATE, #0.008,
# 'min_child_weight': 0.03454472573214212,
# 'bagging_fraction': 0.4181193142567742,
# 'feature_fraction': 0.3797454081646243,
# 'reg_lambda': 0.6485237330340494,
# 'reg_alpha': 0.3899927210061127,
# 'max_depth': DEPTH, #-1,
# 'objective': 'binary',
# 'seed': RANDOM_STATE, #13,
# 'feature_fraction_seed': RANDOM_STATE, #13,
# 'bagging_seed': RANDOM_STATE, #13,
# 'drop_seed': RANDOM_STATE, #13,
# 'data_random_seed': RANDOM_STATE, #13,
# 'boosting_type': 'gbdt',
# 'verbose': 1,
# 'metric':'auc',
# 'n_estimators':N_ESTIMATORS,
# }
def train_lightgbm(X_train, y_train, X_valid, y_valid, X_test, CAT_FEATURES, fold_n, feature_importance):
X_train = X_train.copy()
X_valid = X_valid.copy()
X_test = X_test.copy()
X_train[CAT_FEATURES] = X_train[CAT_FEATURES].astype('category')
X_valid[CAT_FEATURES] = X_valid[CAT_FEATURES].astype('category')
X_test[CAT_FEATURES] = X_test[CAT_FEATURES].astype('category')
model = lgb.LGBMClassifier(**lgb_params)
model.fit(X_train, y_train,
eval_set = [(X_train, y_train),
(X_valid, y_valid)],
verbose = VERBOSE,
early_stopping_rounds=EARLY_STOPPING_ROUNDS)
y_pred_valid = model.predict_proba(X_valid)[:,1]
y_pred = model.predict_proba(X_test)[:,1]
fold_importance = pd.DataFrame()
fold_importance["feature"] = X_train.columns
fold_importance["importance"] = model.feature_importances_
fold_importance["fold"] = fold_n + 1
feature_importance = pd.concat([feature_importance, fold_importance],
axis=0)
best_iteration = model.best_iteration_
return y_pred, y_pred_valid, feature_importance, best_iteration
################################
# Dataframes for storing results
#################################
feature_importance = pd.DataFrame()
oof = np.zeros(len(X))
pred = np.zeros(len(X_test))
oof_df = train_df[['isFraud']].copy()
oof_df['oof'] = np.nan
oof_df['fold'] = np.nan
scores = []
best_iterations = []
del train_df, test_df
gc.collect()
for fold_n, (train_idx, valid_idx) in enumerate(folds.split(X, y)):
X_train = X.iloc[train_idx]
y_train = y.iloc[train_idx]
X_valid = X.iloc[valid_idx]
y_valid = y.iloc[valid_idx]
if MODEL_TYPE == "catboost":
y_pred, y_pred_valid, feature_importance, best_iteration = train_catboost(X_train, y_train, X_valid, y_valid, X_test, CAT_FEATURES, fold_n, feature_importance)
if MODEL_TYPE == 'lightgbm':
y_pred, y_pred_valid, feature_importance, best_iteration = train_lightgbm(X_train, y_train, X_valid, y_valid, X_test, CAT_FEATURES, fold_n, feature_importance)
best_iterations.append(best_iteration)
fold_score = roc_auc_score(y_valid, y_pred_valid)
scores.append(fold_score)
update_tracking(run_id, "AUC_f{}".format(fold_n + 1),
fold_score,
integer=False,)
logger.info('Fold {} of {} CV mean AUC score: {:.4f}. Best iteration {}'.format(fold_n + 1,
N_FOLDS,
fold_score,
best_iteration))
oof_df.iloc[valid_idx, oof_df.columns.get_loc('oof')] = y_pred_valid.reshape(-1)
oof_df.iloc[valid_idx, oof_df.columns.get_loc('fold')] = fold_n + 1
pred += y_pred
update_tracking(run_id, 'avg_best_iteration',
np.mean(best_iterations),
integer=True)
###############
# Store Results
###############
pred /= N_FOLDS
score = np.mean(scores)
sub = pd.read_csv('../input/sample_submission.csv')
sub['isFraud'] = pred
sub.to_csv(f'../sub/sub_{MODEL_NUMBER}_{run_id}_{score:.4f}.csv', index=False)
oof_df.to_csv(f'../oof/oof_{MODEL_NUMBER}_{run_id}_{score:.4f}.csv')
logger.info('CV mean AUC score: {:.4f}, std: {:.4f}.'.format(np.mean(scores),
np.std(scores)))
total_score = roc_auc_score(oof_df['isFraud'], oof_df['oof'])
feature_importance.to_csv(f'../fi/fi_{MODEL_NUMBER}_{run_id}_{score:.4f}.csv')
update_tracking(run_id, "AUC",
total_score,
integer=False,)
logger.info('OOF AUC Score: {:.4f}'.format(total_score))
end = timer()
update_tracking(run_id, "training_time", (end - start), integer=True)
logger.info('Done!')
| [
"lightgbm.LGBMClassifier",
"pandas.read_csv",
"logging.Formatter",
"gc.collect",
"numpy.mean",
"catboost.CatBoostClassifier",
"pandas.DataFrame",
"logging.FileHandler",
"numpy.std",
"datetime.datetime.now",
"pandas.concat",
"time.tzset",
"os.path.basename",
"logging.StreamHandler",
"skle... | [((668, 675), 'timeit.default_timer', 'timer', ([], {}), '()\n', (673, 675), True, 'from timeit import default_timer as timer\n'), ((3685, 3752), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'N_FOLDS', 'random_state': 'RANDOM_STATE', 'shuffle': 'SHUFFLE'}), '(n_splits=N_FOLDS, random_state=RANDOM_STATE, shuffle=SHUFFLE)\n', (3690, 3752), False, 'from sklearn.model_selection import KFold\n'), ((3796, 3846), 'pandas.read_parquet', 'pd.read_parquet', (['f"""../data/train_{FE_SET}.parquet"""'], {}), "(f'../data/train_{FE_SET}.parquet')\n", (3811, 3846), True, 'import pandas as pd\n'), ((3857, 3906), 'pandas.read_parquet', 'pd.read_parquet', (['f"""../data/test_{FE_SET}.parquet"""'], {}), "(f'../data/test_{FE_SET}.parquet')\n", (3872, 3906), True, 'import pandas as pd\n'), ((25787, 25801), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (25799, 25801), True, 'import pandas as pd\n'), ((25995, 26007), 'gc.collect', 'gc.collect', ([], {}), '()\n', (26005, 26007), False, 'import gc\n'), ((27563, 27578), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (27570, 27578), True, 'import numpy as np\n'), ((27585, 27630), 'pandas.read_csv', 'pd.read_csv', (['"""../input/sample_submission.csv"""'], {}), "('../input/sample_submission.csv')\n", (27596, 27630), True, 'import pandas as pd\n'), ((27971, 28018), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (["oof_df['isFraud']", "oof_df['oof']"], {}), "(oof_df['isFraud'], oof_df['oof'])\n", (27984, 28018), False, 'from sklearn.metrics import roc_auc_score\n'), ((28254, 28261), 'timeit.default_timer', 'timer', ([], {}), '()\n', (28259, 28261), True, 'from timeit import default_timer as timer\n'), ((760, 774), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (772, 774), False, 'from datetime import datetime\n'), ((1504, 1516), 'time.tzset', 'time.tzset', ([], {}), '()\n', (1514, 1516), False, 'import time\n'), ((1584, 1618), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'FORMAT'}), '(format=FORMAT)\n', (1603, 1618), False, 'import logging\n'), ((1632, 1657), 'logging.getLogger', 'logging.getLogger', (['"""main"""'], {}), "('main')\n", (1649, 1657), False, 'import logging\n'), ((1707, 1740), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (1728, 1740), False, 'import logging\n'), ((1756, 1815), 'logging.FileHandler', 'logging.FileHandler', (['f"""../logs/{MODEL_NUMBER}_{run_id}.log"""'], {}), "(f'../logs/{MODEL_NUMBER}_{run_id}.log')\n", (1775, 1815), False, 'import logging\n'), ((1832, 1857), 'logging.Formatter', 'logging.Formatter', (['FORMAT'], {}), '(FORMAT)\n', (1849, 1857), False, 'import logging\n'), ((21793, 21853), 'catboost.Pool', 'Pool', ([], {'data': 'X_train', 'label': 'y_train', 'cat_features': 'CAT_FEATURES'}), '(data=X_train, label=y_train, cat_features=CAT_FEATURES)\n', (21797, 21853), False, 'from catboost import CatBoostClassifier, Pool\n'), ((21874, 21934), 'catboost.Pool', 'Pool', ([], {'data': 'X_valid', 'label': 'y_valid', 'cat_features': 'CAT_FEATURES'}), '(data=X_valid, label=y_valid, cat_features=CAT_FEATURES)\n', (21878, 21934), False, 'from catboost import CatBoostClassifier, Pool\n'), ((21954, 21998), 'catboost.Pool', 'Pool', ([], {'data': 'X_test', 'cat_features': 'CAT_FEATURES'}), '(data=X_test, cat_features=CAT_FEATURES)\n', (21958, 21998), False, 'from catboost import CatBoostClassifier, Pool\n'), ((22012, 22216), 'catboost.CatBoostClassifier', 'CatBoostClassifier', ([], {'iterations': 'N_ESTIMATORS', 'learning_rate': 'LEARNING_RATE', 'depth': 'DEPTH', 'eval_metric': 'EVAL_METRIC', 'verbose': 'VERBOSE', 'random_state': 'RANDOM_STATE', 'thread_count': 'N_THREADS', 'task_type': '"""GPU"""'}), "(iterations=N_ESTIMATORS, learning_rate=LEARNING_RATE,\n depth=DEPTH, eval_metric=EVAL_METRIC, verbose=VERBOSE, random_state=\n RANDOM_STATE, thread_count=N_THREADS, task_type='GPU')\n", (22030, 22216), False, 'from catboost import CatBoostClassifier, Pool\n'), ((22585, 22599), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (22597, 22599), True, 'import pandas as pd\n'), ((22787, 22843), 'pandas.concat', 'pd.concat', (['[feature_importance, fold_importance]'], {'axis': '(0)'}), '([feature_importance, fold_importance], axis=0)\n', (22796, 22843), True, 'import pandas as pd\n'), ((24902, 24934), 'lightgbm.LGBMClassifier', 'lgb.LGBMClassifier', ([], {}), '(**lgb_params)\n', (24920, 24934), True, 'import lightgbm as lgb\n'), ((25268, 25282), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (25280, 25282), True, 'import pandas as pd\n'), ((25461, 25517), 'pandas.concat', 'pd.concat', (['[feature_importance, fold_importance]'], {'axis': '(0)'}), '([feature_importance, fold_importance], axis=0)\n', (25470, 25517), True, 'import pandas as pd\n'), ((26669, 26705), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_valid', 'y_pred_valid'], {}), '(y_valid, y_pred_valid)\n', (26682, 26705), False, 'from sklearn.metrics import roc_auc_score\n'), ((27434, 27458), 'numpy.mean', 'np.mean', (['best_iterations'], {}), '(best_iterations)\n', (27441, 27458), True, 'import numpy as np\n'), ((2621, 2657), 'pandas.read_csv', 'pd.read_csv', (['csv_file'], {'index_col': '[0]'}), '(csv_file, index_col=[0])\n', (2632, 2657), True, 'import pandas as pd\n'), ((27862, 27877), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (27869, 27877), True, 'import numpy as np\n'), ((27940, 27954), 'numpy.std', 'np.std', (['scores'], {}), '(scores)\n', (27946, 27954), True, 'import numpy as np\n'), ((810, 836), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (826, 836), False, 'import os\n'), ((2701, 2715), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2713, 2715), True, 'import pandas as pd\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides :class:`TimeSeries` class.
"""
import copy
import os
from collections import OrderedDict
from datetime import datetime, timedelta
import numpy as np
from scipy.interpolate import interp1d
from scipy.stats import kurtosis, skew, tstd
import matplotlib.pyplot as plt
from matplotlib import cm
from .fatigue.rainflow import count_cycles, rebin as rebin_cycles, mesh
from .signal import lowpass, highpass, bandblock, bandpass, threshold as thresholdpass, smooth, taper, \
average_frequency, find_maxima, psd
from .stats.weibull import Weibull, weibull2gumbel, pwm
from .stats.gumbel import Gumbel
# todo: weibull and gumbel + plotting (self.pd = Weibull(), self.evd = Gumbel())
# todo: autocorrelation (see signal module)
# todo: turning-points
# todo: peaks(narrow_band=True)
# todo: valleys(narrow_band=True)
# todo: stats2dict
# todo: write (different file formats, chosen based on suffix e.g. .csv, .ts, .bin, resample as necessary)
# todo: plot (subplots: history=True, histogram=False, psd=False, peaks=False, level_crossing=False, peak_cdf=False)
# todo: level crossings (see Moan&Naess book)
# todo: cross spectrum(scipy.signal.csd)
# todo: coherence (scipy.signal.coherence)
# todo: smarter sizing of scatter dots in plot_cycle_rangemean()
class TimeSeries(object):
"""
A class for storage, processing and presentation of time series.
Parameters
----------
name : str
time series name/identifier
t : array_like
time array; floats (seconds) or datetime objects
x : array_like
data points corresponding to time
parent : str, optional
Path to file it originates from, absolute or relative. Should not be specified for new (calculated)
time series.
dtg_ref : datetime.datetime, optional
Date-time referring to ``t=0`` (time equal zero). Enables output of entire time array as list of
datetime.datetime objects.
kind : str, optional
Kind/type of signal e.g. 'force' or 'acceleration'
unit : str, optional
Unit of measure e.g. 'N' (Newton), 'kN' (kilo Newton), 'm/s2'
Attributes
----------
name : str
Time series name/identifier
x : array_like
Data points corresponding to time, see property :attr:`~TimeSeries.t`.
parent : str
Absolute or relative path to file it originates from.
kind : str
Kind of signal e.g. 'force' or 'acceleration'.
unit : str
Unit of measure e.g. 'N' (Newton) or 'm/s2'.
Notes
-----
If time is given as array of datetime objects and `dtg_ref` is not specified, `dtg_ref` will be set to time
array start value.
"""
def __init__(self, name, t, x, parent=None, dtg_ref=None, kind=None, unit=None):
self.name = name
self._t = np.array(t).flatten()
self.x = np.array(x).flatten()
self.parent = parent
self._dtg_ref = dtg_ref
self._dtg_time = None
self.kind = kind
self.unit = unit
# todo: diagnose t series on initiation. check for nans, infs etc. before storing data on self.
# check input parameters
assert self._t.size == self.x.size, "Time and data must be of equal length."
assert isinstance(self._dtg_ref, datetime) or self._dtg_ref is None, "Expected 'dtg_ref' datetime object or None"
# handle time given as array of datetime objects
_t0 = self._t[0]
if isinstance(_t0, (float, np.float32)):
pass
elif isinstance(_t0, datetime):
# set dtg_ref to start value, unless explicitly specified
if self._dtg_ref is None:
self._dtg_ref = _t0
self._dtg_time = self._t # store specified time array as 'dtg_time'
self._t = np.array([(t - self._dtg_ref).total_seconds() for t in self._t])
else:
raise TypeError("time must be given as array of floats or datetime objects, not '%s'" % type(_t0))
def __copy__(self):
"""
Return copy current TimeSeries object without binding to the original
Returns
-------
TimeSeries
Copy of current TimeSeries
"""
# copy used to avoid bindings between copied instances and the original instances
name = copy.copy(self.name)
t = copy.copy(self.t)
x = copy.copy(self.x)
parent = copy.copy(self.parent)
dt_ref = copy.copy(self._dtg_ref)
new = TimeSeries(name, t, x, parent=parent, dtg_ref=dt_ref)
return new
def __iter__(self):
"""
Generator yielding pairs of time and data
Returns
-------
tuple
(t, x)
"""
i = 0
while i < self.n:
yield (self._t[i], self.x[i])
i += 1
def __repr__(self):
return str('<TimeSeries "%s">') % self.name
# todo: consider including self.__deepcopy__
@property
def average_frequency(self):
"""
Average frequency of mean level crossings
Returns
-------
float
average frequency of mean level crossings
"""
return average_frequency(self.t, self.x, up=True)
@property
def average_period(self):
"""
Average period between mean level crossings
Returns
-------
float
average period between mean level crossings
"""
return 1. / self.average_frequency
@property
def data(self):
"""
Return dictionary of attributes and properties
Returns
-------
dict
Attributes and properties
"""
# todo: QA/debugging on TimeSeries.data (dictionary)
'''
# make dict with all non callable items from class dir(), skip private '__<>__' and itself ("data")
d = OrderedDict()
# d.update(self.__dict__)
for prop in dir(self):
if prop.startswith("__"):
continue
if prop == "data":
continue
attr = self.__getattribute__(prop)
if not callable(attr):
d[prop] = copy.copy(attr)
# todo: ts.data (dict): consider to include output from selected methods (e.g. mean, std, skewness, kurtosis)
return d
'''
raise NotImplementedError("data property is not yet implemented")
@property
def dt(self):
"""
Average time step
Returns
-------
float
average time step
Notes
-----
The TimeSeries class does not require equidistant time vector.
"""
return np.mean(np.diff(self.t))
@property
def dtg_ref(self):
return self._dtg_ref
@property
def dtg_time(self):
"""
Time array formatted as datetime.datetime objects.
Returns
-------
array
Time array formatted as array of datetime.datetime objects, provided that `dtg_ref` is defined.
Otherwise, returns None.
"""
if self._dtg_ref is not None:
if self._dtg_time is None:
# create array of datetime objects (reference is dtg_ref given on class initiation)
# assuming time array is provided in seconds
self._dtg_time = np.array([self._dtg_ref + timedelta(seconds=t) for t in self.t])
else:
pass
return self._dtg_time
else:
# dtg_ref not provided
return None
@property
def fullname(self):
"""
Full name.
Returns
-------
str
parent and name joined to single string
"""
if self.parent is None:
return self.name
else:
return os.path.join(self.parent, self.name)
@property
def n(self):
"""
Number of time steps
Returns
-------
int
number of time steps
"""
return self.t.size
@property
def is_constant_dt(self):
"""
Boolean telling whether the time series is sampled at constant intervals or not.
Returns
-------
bool
Constant sampling interval or not
"""
dt = np.diff(self.t)
dt_avg = np.ones(np.shape(dt)) * self.dt
if np.allclose(dt, dt_avg, rtol=1.e-5, atol=0.):
return True
else:
return False
@property
def start(self):
"""
Start time.
Returns
-------
float
start time
"""
return self.t[0]
@property
def t(self):
"""
Time array
"""
return self._t
@property
def end(self):
"""
End time.
Returns
-------
float
end time
"""
return self.t[-1]
@property
def dtg_start(self):
"""
Start time as datetime object.
Returns
-------
datetime
Start time as datetime.datetime instanc, provided that `dtg_ref` is defined.
Otherwise, returns None.
"""
if self._dtg_ref is not None:
return self._dtg_ref + timedelta(seconds=self.start)
else:
return None
@property
def dtg_end(self):
"""
End time as datetime object.
Returns
-------
datetime
End time as datetime.datetime instance, provided that `dtg_ref` is defined.
Otherwise, returns None.
"""
if self._dtg_ref is not None:
return self._dtg_ref + timedelta(seconds=self.end)
else:
return None
@property
def duration(self):
"""
Duration of time series.
Returns
-------
float
time series duration
"""
return self.end - self.start
def copy(self, newname=None):
"""
Return copy of this TimeSeries object
Parameters
----------
newname: str, optional
Name to assign to copy.
Returns
-------
TimeSeries
Copy of this TimeSeries object
Notes
-----
Does not support parameters for the get() method. It is recommended to modify the copied object
instead of the original.
"""
newts = self.__copy__()
if newname is not None:
newts.name = newname
return newts
def filter(self, filtertype, freq, twin=None, taperfrac=None):
"""
Apply FFT filter
Parameters
----------
filtertype : str
Type of filter to apply. Available options:
- 'lp' - low-pass filter time series
- 'hp' - high-pass filter time series
- 'bp' - band-pass filter time series
- 'bs' - band-stop filter time series
- 'tp' - threshold filter time series
freq : float or tuple
Filter frequency [Hz]. One frequency for 'lp', 'hp' and 'tp' filters, two frequencies for 'bp' and 'bs'.
twin : tuple, optional
Time window (start, stop) to consider (removes away signal outside time window).
taperfrac : float, optional
Fraction of time domain signal to be tapered. For details, see `get()`.
Returns
-------
tuple
Tuple with to arrays: time array and filtered signal.
See Also
--------
get()
Notes
-----
filter() is a special case of the get() method. For instance; assuming `ts` is a TimeSeries instance, the code:
>>> t, xlo = ts.filter('lp', 0.03, twin=(1000, 11800))
... is equivalent to:
>>> t, xlo = ts.get(twin=(1000, 11800), filterargs=('lp', 0.03))
Examples
--------
Low-pass filter the time series at period of 30 [s] (assuming `ts` is a TimeSeries instance):
>>> t, xlo = ts.filter('lp', 1/30)
High-pass filter at period of 30 [s]:
>>> t, xhi = ts.filter('hp', 1/30)
Band-pass filter, preserving signal between 0.01 and 0.1 [Hz]:
>>> t, xband = ts.filter('bp', (0.01, 0.1))
If the signal includes a significant transient, this may be omitted by specifying time window to consider:
>>> t, xlo = ts.filter('lp', 0.03, twin=(1000, 1e12))
"""
# make 'freq' a tuple if float is given
if isinstance(freq, float):
freq = freq,
# check input parameters
if filtertype in ("lp", "hp", "tp"):
if len(freq) != 1:
raise ValueError("One frequency is expected for filter types 'lp', 'hp' and 'tp'")
elif filtertype in ("bp", "bs"):
if len(freq) != 2:
raise ValueError("Two frequencies are expected for filter types 'bp' and 'bs'")
else:
raise ValueError("Invalid filter type: '%s'" % filtertype)
# perform filtering
if isinstance(freq, float):
fargs = (filtertype, freq)
elif isinstance(freq, tuple):
fargs = (filtertype,) + freq
else:
raise TypeError("Unexpected type '%s' of freq." % type(freq))
t, x = self.get(twin=twin, filterargs=fargs, taperfrac=taperfrac)
return t, x
def fit_weibull(self, twin=None, method='msm'):
"""
Fit Weibull distribution to sample of global maxima.
Parameters
----------
twin : tuple, optional
Time window to consider.
method : {'msm', 'lse', 'mle', 'pwm', 'pwm2'}, optional
See `qats.weibull.Weibull.fit` for description of options.
Returns
-------
Weibull
Class instance.
See Also
--------
maxima()
qats.signal.find_maxima
qats.stats.weibull.Weibull.fit
qats.stats.weibull.Weibull.fromsignal
Examples
--------
>>> weib = ts.fit_weibull(twin=(200., 1e12), method='msm')
>>> print(weib.params)
(372.90398322024936, 5.2533589509069714, 0.8516538181105509)
The fit in example above is equivalent to:
>>> from qats.weibull import Weibull
>>> maxima = ts.maxima(local=False, threshold=None, twin=(200., 1e12), rettime=False)
>>> weib = Weibull.fit(maxima, method='msm')
"""
maxima = self.maxima(local=False, threshold=None, twin=twin, rettime=False)
return Weibull.fit(maxima, method=method)
def get(self, twin=None, resample=None, window_len=None, filterargs=None, window="rectangular", taperfrac=None):
"""
Return time series processed according to parameters
Parameters
----------
twin : tuple, optional
time window, cuts away time series beyond time window
filterargs : tuple, optional
Apply filtering. Argument options:
- ('lp', f) - Low-pass filter at frequency f
- ('hp', f) - High-pass filter at frequency f
- ('bp', flo, fhi) - Band-pass filter between frequencies flo and fhi
- ('bs', flo, fhi) - Band-stop filter between frequencies flo and fhi
- ('tp', a) - Threshold-pass filter at amplitude a
resample : float or ndarray or list, optional
Resample time series:
- to specified constant time step if `resample` is a float
- to specified time if `resample` is an array or list
window_len : int, optional
Smooth time serie based on convoluting the time series with a rectangular window of specified length. An odd
number is recommended.
window : str, optional
Type of window function, default 'rectangular', see `qats.filters.smooth` for options.
taperfrac : float, optional
Fraction of time domain signal to be tapered. A taper of 0.001-0.01 is recommended before calculation of
the power spectral density.
Returns
-------
tuple
Tuple of two numpy arrays; ``(time, data)``
Notes
-----
The data is modified in the following order
1. Windowing
2. Resampling
3. Tapering
4. Filtering
5. Smoothing
Mean value of signal is subtracted before step 3, and then re-added after step 4 (except if high-pass filter is
specified).
Resampling is achieved by specifying either `dt` or `t`. If both are specified `t` overrules. Resampling to a
a specified time array `t` cannot be specified at the same time as a time window `twin`.
Filtering is achieved by FFT truncation.
When smoothing the central data point is calculated at the weighted average of the windowed data points. In the
case of the rectangular window all windowed data points are equally weighted. Other window functions are
available on request. Note that windowing have some similarities to filtering.
Windowing is achieved by direct truncation of time series within specified time range.
Data tapering is performed by multiplying the time series with a Tukey window (tapered cosine window).
See Also
--------
TimeSeries.resample(), TimeSeries.interpolate(), qats.signal.smooth()
"""
assert not ((isinstance(resample, np.ndarray)) and (twin is not None)), \
"Cannot specify both resampling to `newt` and cropping to time window `twin`."
# copy time series
t = copy.copy(self.t)
x = copy.copy(self.x)
# windowing
if twin is not None:
t_start, t_end = twin
i = (t >= t_start) & (t <= t_end)
t, x = t[i], x[i]
def new_timearray(t0, t1, d):
""" Establish time array from specified start (t0), end (t1) and time step (d) """
n = int(round((t1 - t0) / d)) + 1
t_ = np.linspace(t0, t1, n, retstep=False)
return t_
# resampling
if resample is not None:
if isinstance(resample, (np.ndarray, list)):
# specified time array
t = resample
elif isinstance(resample, (float, np.float32)):
# specified time step
t = new_timearray(t[0], t[-1], resample)
else:
raise TypeError("Parameter resample should be either a float or a numpy.ndarray type, not %s." % type(resample))
x = self.interpolate(t)
elif filterargs is not None and not self.is_constant_dt:
# filtering is specified but the time step is not constant (use the average time step)
t = new_timearray(t[0], t[-1], self.dt)
x = self.interpolate(t)
else:
pass
# remove mean value (added later except for highpass filtered time series)
xmean = np.mean(x)
x = x - xmean
# data tapering
if (taperfrac is not None) and (isinstance(taperfrac, float)) and (taperfrac > 0.) and (taperfrac < 1.):
x, _ = taper(x, window='tukey', alpha=taperfrac)
# filtering
if filterargs is not None:
assert isinstance(filterargs, tuple) or isinstance(filterargs, list), \
"Parameter filter should be either a list or tuple, not %s." % type(filterargs)
# time step for the filter calculation
_dt = t[1] - t[0]
if filterargs[0] == 'lp':
assert len(filterargs) == 2, "Excepted 2 values in filterargs but got %d." % len(filterargs)
x = lowpass(x, _dt, filterargs[1])
elif filterargs[0] == 'hp':
assert len(filterargs) == 2, "Excepted 2 values in filterargs but got %d." % len(filterargs)
x = highpass(x, _dt, filterargs[1])
elif filterargs[0] == 'bp':
assert len(filterargs) == 3, "Excepted 3 values in filterargs but got %d." % len(filterargs)
x = bandpass(x, _dt, filterargs[1], filterargs[2])
elif filterargs[0] == 'bs':
assert len(filterargs) == 3, "Excepted 3 values in filterargs but got %d." % len(filterargs)
x = bandblock(x, _dt, filterargs[1], filterargs[2])
elif filterargs[0] == 'tp':
assert len(filterargs) == 2, "Excepted 2 values in filterargs but got %d." % len(filterargs)
x = thresholdpass(x, filterargs[1])
else:
# invalid filter type
raise ValueError(f"Invalid filter type: {filterargs[0]}")
# re-add mean value (except if high-pass filter has been applied)
if filterargs is None or filterargs[0] != 'hp':
x = x + xmean
# smoothing
if (window_len is not None) and (isinstance(window_len, int)) and (window_len > 0):
x = smooth(x, window_len=window_len, window=window, mode='same')
return t, x
def interpolate(self, time):
"""
Interpolate linearly in data to values a specified time
Parameters
----------
time : array_like
time at which data is interpolated
Returns
-------
array_like
interpolated data values
Raises
------
ValueError
If interpolation is attempted on values outside the range of `t`.
Notes
-----
Extrapolation outside the range of `t` is not allowed since that does not make sense when analysing generally
irregular timeseries.
"""
f = interp1d(self.t, self.x, bounds_error=True)
return f(time)
def kurtosis(self, fisher=False, bias=False, **kwargs):
"""
Kurtosis of time series
Parameters
----------
fisher : bool, optional
If True, Fisher’s definition is used (normal ==> 0.0). If False (default), Pearson’s definition
is used (normal ==> 3.0).
bias : bool, optional
If False (default), then the calculations are corrected for statistical bias.
kwargs : optional
see documentation of get() method for available options
Returns
-------
float
Sample kurtosis
See also
--------
scipy.stats.kurtosis
"""
# get data array, time does not matter
_, x = self.get(**kwargs)
return kurtosis(x, fisher=fisher, bias=bias)
def max(self, **kwargs):
"""
Maximum value of time series.
Parameters
----------
kwargs : optional
See documentation of :meth:`get()` method for available options.
Returns
-------
float
Maximum value of time series
Examples
--------
Get maximum of entire time series:
>>> xmax = ts.max()
Get maximum within a specified time window:
>>> xmax = ts.max(twin=(1200, 12000))
"""
_, x = self.get(**kwargs)
return x.max()
def maxima(self, twin=None, local=False, threshold=None, rettime=False, **kwargs):
"""
Return sorted maxima
Parameters
----------
twin : tuple, optional
Time window (start, end) to consider.
local : bool, optional
return local maxima also, default only global maxima are considered
threshold : float, optional
consider only maxima larger than specified treshold. Default mean value.
rettime : bool, optional
If True, (maxima, time_maxima), where `time_maxima` is an array of time instants associated with the
maxima sample.
kwargs : optional
See documentation of :meth:`get()` method for available options.
Returns
-------
array
Signal maxima, sorted from smallest to largest.
array
Only returned if `rettime` is True.
Time instants of signal maxima.
See Also
--------
qats.signal.find_maxima
Notes
-----
By default only 'global' maxima are considered, i.e. the largest maximum between each mean-level up-crossing.
If ``local=True``, local maxima are also included (first derivative is zero, second derivative is negative).
"""
# get time and data
t, x = self.get(twin=twin, **kwargs)
# find maxima (and associated time, if specified)
if rettime is True:
m, ind = find_maxima(x, local=local, threshold=threshold, retind=True)
return m, t[ind]
else:
m = find_maxima(x, local=local, threshold=threshold, retind=False)
return m
def mean(self, **kwargs):
"""
Mean value of time series.
Parameters
----------
kwargs : optional
see documentation of get() method for available options
Returns
-------
float
Sample mean
See also
--------
numpy.mean
"""
# get data array
_, x = self.get(**kwargs)
return np.mean(x)
def min(self, **kwargs):
"""
Minimum value of time series.
Parameters
----------
kwargs : optional
See documentation of get() method for available options.
Returns
-------
float
Minimum value of time series
"""
_, x = self.get(**kwargs)
return x.min()
def minima(self, twin=None, local=False, threshold=None, rettime=False, **kwargs):
"""
Return sorted minima
Parameters
----------
twin : tuple, optional
Time window (start, end) to consider.
local : bool, optional
return local minima also, default only global minima are considered
threshold : float, optional
consider only minima smaller (considering the sign) than specified threshold. Default mean value.
rettime : bool, optional
If True, (maxima, time_maxima), where `time_maxima` is an array of time instants associated with the
maxima sample.
kwargs : optional
See documentation of :meth:`get()` method for available options
Returns
-------
array
Signal minima, sorted from smallest to largest.
array
Only returned if `rettime` is True.
Time instants of signal minima.
Notes
-----
Minima are found by multiplying the time series with -1, finding the maxima using the maxima() method and then
multiplying the maxima with -1 again.
By default only 'global' minima are considered, that is the smallest minimum between each mean-level up-crossing.
If local=True local minima are also considered.
See Also
--------
maxima()
"""
# get time and data
t, x = self.get(twin=twin, **kwargs)
# flip the time series to that minima becomes maxima
x *= -1.
# find minima (and associated time, if specified)
if rettime is True:
m, ind = find_maxima(x, local=local, threshold=threshold, retind=True)
return -1. * m, t[ind] # reverse flip
else:
m = find_maxima(x, local=local, threshold=threshold, retind=False)
return -1. * m # reverse flip
def modify(self, **kwargs):
"""
Modify TimeSeries object
Parameters
----------
kwargs : optional
see documentation of get() method for available options
Notes
-----
Modifies ´t´ and ´x´ on current TimeSeries object. This is irreversible.
"""
self._t, self.x = self.get(**kwargs)
def plot(self, figurename=None, **kwargs):
"""
Plot time series trace.
Parameters
----------
names : str/list/tuple, optional
Time series names
figurename : str, optional
Save figure to file 'figurename' instead of displaying on screen.
kwargs : optional
See documentation of TimeSeries.get() method for available options
"""
# dict with numpy arrays: time and data
t, x = self.get(**kwargs)
plt.figure(1)
plt.plot(t, x, label=self.name)
plt.xlabel('Time (s)')
plt.grid()
plt.legend()
if figurename is not None:
plt.savefig(figurename)
else:
plt.show()
def plot_psd(self, figurename=None, **kwargs):
"""
Plot time series power spectral density.
Parameters
----------
figurename : str, optional
Save figure to file 'figurename' instead of displaying on screen.
kwargs : optional
see documentation of TimeSeries.psd() method for available options
"""
# dict with TimeSeries objects
plt.figure(1)
f, p = self.psd(**kwargs)
plt.plot(f, p, label=self.name)
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power spectral density')
plt.grid()
plt.legend()
if figurename is not None:
plt.savefig(figurename)
else:
plt.show()
def plot_cycle_range(self, n=200, w=None, figurename=None, **kwargs):
"""
Plot cycle range versus number of occurrences.
Parameters
----------
n : int, optional
Group by cycle range in *n* equidistant bins.
w : float, optional
Group by cycle range in *w* wide equidistant bins. Overrides *n*.
figurename : str, optional
Save figure to file 'figurename' instead of displaying on screen.
kwargs : optional
see documentation of TimeSeries.rfc() method for available options
See Also
--------
TimeSeries.rfc, qats.fatigue.rainflow.count_cycles, qats.fatigue.rainflow.rebin
"""
cycles = self.rfc(**kwargs)
# rebin cycles
assert (n is not None) or (w is not None), "Cycles must be rebinned for this plot - either 'n' or 'w' must " \
"be different from None"
cycles = rebin_cycles(cycles, binby='range', n=n, w=w)
r, _, c = zip(*cycles) # unpack cycle range and count, ignore mean value
dr = r[1] - r[0] # bar width
plt.bar(r, c, dr, label=self.name)
plt.xlabel('Cycle range')
plt.ylabel('Cycle count (-)')
plt.grid()
plt.legend()
if figurename is not None:
plt.savefig(figurename)
else:
plt.show()
def plot_cycle_rangemean(self, n=None, w=None, figurename=None, **kwargs):
"""
Plot cycle range-mean versus number of occurrences.
Parameters
----------
n : int, optional
Group by cycle range in *n* equidistant bins.
w : float, optional
Group by cycle range in *w* wide equidistant bins. Overrides *n*.
figurename : str, optional
Save figure to file 'figurename' instead of displaying on screen.
kwargs : optional
see documentation of TimeSeries.rfc() method for available options
Notes
-----
Cycle means are represented by weighted averages in each bin.
See Also
--------
TimeSeries.rfc, TimeSeries.plot_cyclerange,
qats.fatigue.rainflow.count_cycles, qats.fatigue.rainflow.rebin
"""
cycles = self.rfc(**kwargs)
# rebin cycles
if (n is not None) or (w is not None):
cycles = rebin_cycles(cycles, binby='range', n=n, w=w)
ranges, means, counts = zip(*cycles) # unpack cycle range, mean and count
# the scatter plot (with double marker size for improved readability)
plt.scatter(means, ranges, s=[2. * c for c in counts], alpha=0.4, label=self.name)
plt.xlabel('Cycle mean')
plt.ylabel('Cycle range')
plt.grid()
plt.legend()
if figurename is not None:
plt.savefig(figurename)
else:
plt.show()
def plot_cycle_rangemean3d(self, nr=100, nm=100, figurename=None, **kwargs):
"""
Plot cycle range-mean versus number of occurrences as 3D surface.
Parameters
----------
nr : int, optional
Group by cycle range in *nr* equidistant bins.
nm : int, optional
Group by cycle mean in *nm* equidistant bins.
figurename : str, optional
Save figure to file 'figurename' instead of displaying on screen.
kwargs : optional
see documentation of TimeSeries.get() method for available options
"""
# This import registers the 3D projection, but is otherwise unused.
# noinspection PyUnresolvedReferences
from mpl_toolkits.mplot3d import Axes3D
cycles = self.rfc(**kwargs)
ranges, means, counts = mesh(cycles, nr=nr, nm=nm)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(means, ranges, counts, cmap=cm.coolwarm)
ax.set_xlabel('Cycle mean')
ax.set_ylabel('Cycle range')
ax.set_zlabel('Cycle count')
if figurename is not None:
plt.savefig(figurename)
else:
plt.show()
def psd(self, nperseg=None, noverlap=None, detrend='constant', nfft=None, **kwargs):
"""
Estimate power spectral density using Welch’s method.
Parameters
----------
nperseg : int, optional
Length of each segment. Can be set equal to the signal length to provide full frequency resolution.
Default 1/4 of the total signal length.
noverlap : int, optional
Number of points to overlap between segments. If None, noverlap = nperseg / 2. Defaults to None.
nfft : int, optional
Length of the FFT used, if a zero padded FFT is desired. Default the FFT length is nperseg.
detrend : str or function, optional
Specifies how to detrend each segment. If detrend is a string, it is passed as the type argument to
detrend. If it is a function, it takes a segment and returns a detrended segment. Defaults to ‘constant’.
kwargs : optional
see documentation of get() method for available options
Returns
-------
tuple
Two arrays: sample frequencies and corresponding power spectral density
Notes
-----
For description of Welch's method and references, see :meth:`qats.signal.psd()`.
See also
--------
qats.signal.psd, scipy.signal.welch, scipy.signal.periodogram
"""
# get time and data arrays
t, x = self.get(**kwargs)
# ensure constant time step
_dt = np.diff(t)
# (use atol not zero to avoid false positives for zero values)
if not np.isclose(min(_dt), max(_dt), rtol=1.e-2, atol=1.e-6):
raise ValueError(f"The time step of '{self.name}' varies with more than 1%. A constant time step is "
f"required when estimating power spectral density using FFT. Resample to constant "
f"time step.")
# average time step for requested series
dt = float(np.mean(_dt))
# estimate psd using qats.signal.psd (which uses welch's definition)
f, p = psd(x, dt, nperseg=nperseg, noverlap=noverlap, detrend=detrend, nfft=nfft)
return f, p
def resample(self, dt=None, t=None):
"""
Resample with constant sampling interval dt
Parameters
----------
dt : float, optional
Constant sampling interval
t : array_like, optional
Time array to which the data is resampled
Returns
-------
array_like
Resampled data
Notes
-----
Either `dt` or `t` have to specified. If both are specified `t` overrules.
If `dt` is used the resampled data cover the period given by the objects `t` attribute, in other words from
`start` to `end`.
"""
assert dt is not None or t is not None, "Either new time step 'dt' or new time array 't' has to be specified."
if t is not None:
assert t.min() >= self.start and t.max() <= self.end, "The new specified time array exceeds the original " \
"time array. Extrapolation is not allowed."
return self.interpolate(t)
else:
assert dt > 0., "The specified time step is to small."
return self.interpolate(np.arange(self.start, self.end, step=dt))
def rfc(self, **kwargs):
"""
Returns a sorted list containing with cycle range, mean and count.
Parameters
----------
kwargs : optional
see documentation of get() method for available options
Returns
-------
list
Cycle range, mean and count sorted ascending by cycle range.
Examples
--------
Unpack cycle ranges, means and counts as list
>>> cycles = ts.rfc()
>>> ranges, means, counts = zip(*cycles)
Notes
-----
Half cycles are counted as 0.5, so the returned counts may not be whole numbers.
Rebinning is not applied if specified *n* is larger than the original number of bins.
See Also
--------
qats.fatigue.rainflow.count_cycles
"""
# get data array
_, x = self.get(**kwargs)
cycles = count_cycles(x)
return cycles
def set_dtg_ref(self, new_ref=None):
"""
Set or adjust the dtg reference.
If there is no pre-defined dtg reference for the time series, dtg reference (`dtg_ref`) is set to the specified
value.
If the time series already has a dtg reference, time array is updated so that t=0 now refers to the new
dtg reference. This implies that time array is shifted as follows::
t += (dtg_ref - new_ref).total_seconds()
If no new value is specified, `dtg_ref` is adjusted so that time array starts at zero (if it doesn't already).
Parameters
----------
new_ref: datetime
New dtg reference.
Raises
------
ValueError
If `new_ref` is not a `datetime.datetime` instance, or if `dtg_ref` is not pre-defined and `new_dtg` is not
given.
"""
if new_ref is not None and not isinstance(new_ref, datetime):
raise ValueError("`new_ref` must be a datetime.datetime instance")
elif new_ref is None and self._dtg_ref is None:
raise ValueError("New dtg reference must be given if attribute `dtg_ref` is not pre-defined")
if new_ref is not None and self._dtg_ref is None:
# set dtg_ref to new_ref, then return (no basis to adjust time array)
self._dtg_ref = new_ref
elif new_ref is not None and self._dtg_ref is not None:
# adjust time array so that t=0 refers to new ref
delta = (self._dtg_ref - new_ref).total_seconds()
self._dtg_ref = new_ref
self._t += delta
self._dtg_time = None # reset, no need to initiate new array until requested
elif new_ref is None and self._dtg_ref is not None:
# adjust dtg_ref and time array so that dtg_ref refers to t=0
delta = -self.start
self._dtg_ref = self.dtg_start
self._t += delta
self._dtg_time = None # reset, no need to initiate new array until requested
def stats(self, statsdur=None, quantiles=None, **kwargs):
"""
Returns dictionary with time series properties and statistics
Parameters
----------
statsdur : float
Duration in seconds for estimation of extreme value distribution (Gumbel) from peak distribution (Weibull).
Default is 3 hours.
quantiles : tuple, optional
Quantiles in the Gumbel distribution used for extreme value estimation
kwargs
Optional parameters passed to TimeSeries.get()
Returns
-------
OrderedDict
Time series statistics (for details, see Notes below).
Notes
-----
The returned dictionary contains::
Key Description
-------- -----------
start First value of time array [s]
end Last value of time array [s]
duration end - start [s]
dtavg Average time step [s]
mean Mean value of signal array
std Unbiased standard deviation of signal array
skew Unbiased skewness of signal array (=0 for normal distribution)
kurt Unbiased kurtosis of signal array (=3 for normal distribution)
min Minimum value of signal array
max Maximum value of signal array
tz Average mean crossing period [s]
wloc Weibull distribution location parameter fitted to sample of global maxima
wscale Weibull distribution scale parameter fitted to sample of global maxima
wshape Weibull distribution shape parameter fitted to sample of global maxima
gloc Gumbel distribution location parameter estimated from Weibull distribution and `statsdur`
gscale Gumbel distribution scale parameter estimated from Weibull distribution and `statsdur`
p_* .. Extreme values estimated from the Gumbel distribution, e.g. p_90 is the 0.9 quantile
See Also
--------
qats.stats.weibull.weibull2gumbel, qats.stats.weibull.pwm
Examples
--------
Generate statistics for entire time series, unfiltered:
>>> stats = ts.stats()
To get statistics for filtered time series, one may specify the filter to apply:
>>> stats_lf = ts.stats(filterargs=('lp', 0.3))
>>> stats_hf = ts.stats(filterargs=('hp', 0.3))
To ignore the transient part of the time series, time window may be specified:
>>> stats = ts.stats(twin=(500., 1e12))
"""
# handle defaults
if not statsdur:
statsdur = 10800.
if not quantiles:
quantiles = (0.37, 0.57, 0.9)
# get time series as array
t, x = self.get(**kwargs)
# find global maxima, estimate weibull and gumbel parameters
maxima = find_maxima(x)
if maxima is not None:
wloc, wscale, wshape = pwm(maxima)
nmax = maxima.size
n = round(statsdur / (t[-1] - t[0]) * nmax)
gloc, gscale = weibull2gumbel(wloc, wscale, wshape, n)
tz = 1. / average_frequency(t, x)
else:
wloc = wscale = wshape = gloc = gscale = tz = None
# establish output dictionary
d = OrderedDict(
start=t[0], end=t[-1], duration=t[-1] - t[0], dtavg=np.mean(np.diff(t)),
mean=x.mean(), std=tstd(x), skew=skew(x, bias=False),
kurt=kurtosis(x, fisher=False, bias=False), min=x.min(), max=x.max(), tz=tz,
wloc=wloc, wscale=wscale, wshape=wshape, gloc=gloc, gscale=gscale
)
# estimate extreme values
if maxima is not None:
g = Gumbel(loc=gloc, scale=gscale)
try:
values = g.invcdf(p=quantiles)
except AssertionError:
# return none for invalid combinations of distribution parameters
values = np.array([None] * len(quantiles))
for q, v in zip(quantiles, values):
d["p_%.2f" % (100 * q)] = v
return d
def std(self, **kwargs):
"""
Unbiased standard deviation of time series.
Parameters
----------
kwargs : optional
see documentation of :meth:`get()` method for available options
Returns
-------
float
Sample standard deviation
Notes
-----
Computes the unbiased sample standard deviation, i.e. it uses a correction factor n / (n - ddof).
See also
--------
scipy.stats.tstd
"""
# get data array, time does not matter
_, x = self.get(**kwargs)
return tstd(x)
def skew(self, bias=False, **kwargs):
"""
Skewness of time series
Parameters
----------
bias : bool, optional
If False (default), then the calculations are corrected for statistical bias.
kwargs : optional
see documentation of get() method for available options
Returns
-------
float
Sample skewness
See also
--------
scipy.stats.skew
"""
# get data array, time does not matter
_, x = self.get(**kwargs)
return skew(x, bias=bias)
| [
"scipy.stats.tstd",
"numpy.allclose",
"matplotlib.pyplot.bar",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"scipy.interpolate.interp1d",
"os.path.join",
"datetime.timedelta",
"numpy.linspace",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"matplotlib.py... | [((4337, 4357), 'copy.copy', 'copy.copy', (['self.name'], {}), '(self.name)\n', (4346, 4357), False, 'import copy\n'), ((4370, 4387), 'copy.copy', 'copy.copy', (['self.t'], {}), '(self.t)\n', (4379, 4387), False, 'import copy\n'), ((4400, 4417), 'copy.copy', 'copy.copy', (['self.x'], {}), '(self.x)\n', (4409, 4417), False, 'import copy\n'), ((4435, 4457), 'copy.copy', 'copy.copy', (['self.parent'], {}), '(self.parent)\n', (4444, 4457), False, 'import copy\n'), ((4475, 4499), 'copy.copy', 'copy.copy', (['self._dtg_ref'], {}), '(self._dtg_ref)\n', (4484, 4499), False, 'import copy\n'), ((8391, 8406), 'numpy.diff', 'np.diff', (['self.t'], {}), '(self.t)\n', (8398, 8406), True, 'import numpy as np\n'), ((8468, 8513), 'numpy.allclose', 'np.allclose', (['dt', 'dt_avg'], {'rtol': '(1e-05)', 'atol': '(0.0)'}), '(dt, dt_avg, rtol=1e-05, atol=0.0)\n', (8479, 8513), True, 'import numpy as np\n'), ((17856, 17873), 'copy.copy', 'copy.copy', (['self.t'], {}), '(self.t)\n', (17865, 17873), False, 'import copy\n'), ((17886, 17903), 'copy.copy', 'copy.copy', (['self.x'], {}), '(self.x)\n', (17895, 17903), False, 'import copy\n'), ((19224, 19234), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (19231, 19234), True, 'import numpy as np\n'), ((21951, 21994), 'scipy.interpolate.interp1d', 'interp1d', (['self.t', 'self.x'], {'bounds_error': '(True)'}), '(self.t, self.x, bounds_error=True)\n', (21959, 21994), False, 'from scipy.interpolate import interp1d\n'), ((22802, 22839), 'scipy.stats.kurtosis', 'kurtosis', (['x'], {'fisher': 'fisher', 'bias': 'bias'}), '(x, fisher=fisher, bias=bias)\n', (22810, 22839), False, 'from scipy.stats import kurtosis, skew, tstd\n'), ((25553, 25563), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (25560, 25563), True, 'import numpy as np\n'), ((28785, 28798), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (28795, 28798), True, 'import matplotlib.pyplot as plt\n'), ((28807, 28838), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'x'], {'label': 'self.name'}), '(t, x, label=self.name)\n', (28815, 28838), True, 'import matplotlib.pyplot as plt\n'), ((28847, 28869), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {}), "('Time (s)')\n", (28857, 28869), True, 'import matplotlib.pyplot as plt\n'), ((28878, 28888), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (28886, 28888), True, 'import matplotlib.pyplot as plt\n'), ((28897, 28909), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (28907, 28909), True, 'import matplotlib.pyplot as plt\n'), ((29448, 29461), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (29458, 29461), True, 'import matplotlib.pyplot as plt\n'), ((29504, 29535), 'matplotlib.pyplot.plot', 'plt.plot', (['f', 'p'], {'label': 'self.name'}), '(f, p, label=self.name)\n', (29512, 29535), True, 'import matplotlib.pyplot as plt\n'), ((29544, 29572), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency (Hz)"""'], {}), "('Frequency (Hz)')\n", (29554, 29572), True, 'import matplotlib.pyplot as plt\n'), ((29581, 29617), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power spectral density"""'], {}), "('Power spectral density')\n", (29591, 29617), True, 'import matplotlib.pyplot as plt\n'), ((29626, 29636), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (29634, 29636), True, 'import matplotlib.pyplot as plt\n'), ((29645, 29657), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (29655, 29657), True, 'import matplotlib.pyplot as plt\n'), ((30951, 30985), 'matplotlib.pyplot.bar', 'plt.bar', (['r', 'c', 'dr'], {'label': 'self.name'}), '(r, c, dr, label=self.name)\n', (30958, 30985), True, 'import matplotlib.pyplot as plt\n'), ((30994, 31019), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Cycle range"""'], {}), "('Cycle range')\n", (31004, 31019), True, 'import matplotlib.pyplot as plt\n'), ((31028, 31057), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cycle count (-)"""'], {}), "('Cycle count (-)')\n", (31038, 31057), True, 'import matplotlib.pyplot as plt\n'), ((31066, 31076), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (31074, 31076), True, 'import matplotlib.pyplot as plt\n'), ((31085, 31097), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (31095, 31097), True, 'import matplotlib.pyplot as plt\n'), ((32424, 32514), 'matplotlib.pyplot.scatter', 'plt.scatter', (['means', 'ranges'], {'s': '[(2.0 * c) for c in counts]', 'alpha': '(0.4)', 'label': 'self.name'}), '(means, ranges, s=[(2.0 * c) for c in counts], alpha=0.4, label=\n self.name)\n', (32435, 32514), True, 'import matplotlib.pyplot as plt\n'), ((32515, 32539), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Cycle mean"""'], {}), "('Cycle mean')\n", (32525, 32539), True, 'import matplotlib.pyplot as plt\n'), ((32548, 32573), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cycle range"""'], {}), "('Cycle range')\n", (32558, 32573), True, 'import matplotlib.pyplot as plt\n'), ((32582, 32592), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (32590, 32592), True, 'import matplotlib.pyplot as plt\n'), ((32601, 32613), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (32611, 32613), True, 'import matplotlib.pyplot as plt\n'), ((33612, 33624), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (33622, 33624), True, 'import matplotlib.pyplot as plt\n'), ((35475, 35485), 'numpy.diff', 'np.diff', (['t'], {}), '(t)\n', (35482, 35485), True, 'import numpy as np\n'), ((45236, 45243), 'scipy.stats.tstd', 'tstd', (['x'], {}), '(x)\n', (45240, 45243), False, 'from scipy.stats import kurtosis, skew, tstd\n'), ((45828, 45846), 'scipy.stats.skew', 'skew', (['x'], {'bias': 'bias'}), '(x, bias=bias)\n', (45832, 45846), False, 'from scipy.stats import kurtosis, skew, tstd\n'), ((6748, 6763), 'numpy.diff', 'np.diff', (['self.t'], {}), '(self.t)\n', (6755, 6763), True, 'import numpy as np\n'), ((7901, 7937), 'os.path.join', 'os.path.join', (['self.parent', 'self.name'], {}), '(self.parent, self.name)\n', (7913, 7937), False, 'import os\n'), ((18261, 18298), 'numpy.linspace', 'np.linspace', (['t0', 't1', 'n'], {'retstep': '(False)'}), '(t0, t1, n, retstep=False)\n', (18272, 18298), True, 'import numpy as np\n'), ((28957, 28980), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figurename'], {}), '(figurename)\n', (28968, 28980), True, 'import matplotlib.pyplot as plt\n'), ((29007, 29017), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (29015, 29017), True, 'import matplotlib.pyplot as plt\n'), ((29705, 29728), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figurename'], {}), '(figurename)\n', (29716, 29728), True, 'import matplotlib.pyplot as plt\n'), ((29755, 29765), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (29763, 29765), True, 'import matplotlib.pyplot as plt\n'), ((31145, 31168), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figurename'], {}), '(figurename)\n', (31156, 31168), True, 'import matplotlib.pyplot as plt\n'), ((31195, 31205), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (31203, 31205), True, 'import matplotlib.pyplot as plt\n'), ((32661, 32684), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figurename'], {}), '(figurename)\n', (32672, 32684), True, 'import matplotlib.pyplot as plt\n'), ((32711, 32721), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (32719, 32721), True, 'import matplotlib.pyplot as plt\n'), ((33885, 33908), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figurename'], {}), '(figurename)\n', (33896, 33908), True, 'import matplotlib.pyplot as plt\n'), ((33935, 33945), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (33943, 33945), True, 'import matplotlib.pyplot as plt\n'), ((35968, 35980), 'numpy.mean', 'np.mean', (['_dt'], {}), '(_dt)\n', (35975, 35980), True, 'import numpy as np\n'), ((2840, 2851), 'numpy.array', 'np.array', (['t'], {}), '(t)\n', (2848, 2851), True, 'import numpy as np\n'), ((2879, 2890), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2887, 2890), True, 'import numpy as np\n'), ((8432, 8444), 'numpy.shape', 'np.shape', (['dt'], {}), '(dt)\n', (8440, 8444), True, 'import numpy as np\n'), ((9372, 9401), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'self.start'}), '(seconds=self.start)\n', (9381, 9401), False, 'from datetime import datetime, timedelta\n'), ((9787, 9814), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'self.end'}), '(seconds=self.end)\n', (9796, 9814), False, 'from datetime import datetime, timedelta\n'), ((37350, 37390), 'numpy.arange', 'np.arange', (['self.start', 'self.end'], {'step': 'dt'}), '(self.start, self.end, step=dt)\n', (37359, 37390), True, 'import numpy as np\n'), ((43936, 43943), 'scipy.stats.tstd', 'tstd', (['x'], {}), '(x)\n', (43940, 43943), False, 'from scipy.stats import kurtosis, skew, tstd\n'), ((43950, 43969), 'scipy.stats.skew', 'skew', (['x'], {'bias': '(False)'}), '(x, bias=False)\n', (43954, 43969), False, 'from scipy.stats import kurtosis, skew, tstd\n'), ((43988, 44025), 'scipy.stats.kurtosis', 'kurtosis', (['x'], {'fisher': '(False)', 'bias': '(False)'}), '(x, fisher=False, bias=False)\n', (43996, 44025), False, 'from scipy.stats import kurtosis, skew, tstd\n'), ((43892, 43902), 'numpy.diff', 'np.diff', (['t'], {}), '(t)\n', (43899, 43902), True, 'import numpy as np\n'), ((7443, 7463), 'datetime.timedelta', 'timedelta', ([], {'seconds': 't'}), '(seconds=t)\n', (7452, 7463), False, 'from datetime import datetime, timedelta\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import warnings
import numpy as np
import pandas as pd
import scipy.ndimage as ndi
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import PathPatch
from matplotlib.patches import Polygon
from matplotlib.patches import Rectangle
from matplotlib.path import Path
from scipy.spatial import ConvexHull
from .google_static_maps_api import GoogleStaticMapsAPI
from .google_static_maps_api import MAPTYPE
from .google_static_maps_api import MAX_SIZE
from .google_static_maps_api import SCALE
BLANK_THRESH = 2 * 1e-3 # Value below which point in a heatmap should be blank
def register_api_key(api_key):
"""Register a Google Static Maps API key to enable queries to Google.
Create your own Google Static Maps API key on https://console.developers.google.com.
:param str api_key: the API key
:return: None
"""
GoogleStaticMapsAPI.register_api_key(api_key)
def background_and_pixels(latitudes, longitudes, size, maptype):
"""Queries the proper background map and translate geo coordinated into pixel locations on this map.
:param pandas.Series latitudes: series of sample latitudes
:param pandas.Series longitudes: series of sample longitudes
:param int size: target size of the map, in pixels
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:return: map and pixels
:rtype: (PIL.Image, pandas.DataFrame)
"""
# From lat/long to pixels, zoom and position in the tile
center_lat = (latitudes.max() + latitudes.min()) / 2
center_long = (longitudes.max() + longitudes.min()) / 2
zoom = GoogleStaticMapsAPI.get_zoom(latitudes, longitudes, size, SCALE)
pixels = GoogleStaticMapsAPI.to_tile_coordinates(latitudes, longitudes, center_lat, center_long, zoom, size, SCALE)
# Google Map
img = GoogleStaticMapsAPI.map(
center=(center_lat, center_long),
zoom=zoom,
scale=SCALE,
size=(size, size),
maptype=maptype,
)
return img, pixels
def scatter(latitudes, longitudes, colors=None, maptype=MAPTYPE, alpha=0.5):
"""Scatter plot over a map. Can be used to visualize clusters by providing the marker colors.
:param pandas.Series latitudes: series of sample latitudes
:param pandas.Series longitudes: series of sample longitudes
:param pandas.Series colors: marker colors, as integers
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:param float alpha: transparency for plot markers between 0 (transparent) and 1 (opaque)
:return: None
"""
width = SCALE * MAX_SIZE
colors = pd.Series(0, index=latitudes.index) if colors is None else colors
img, pixels = background_and_pixels(latitudes, longitudes, MAX_SIZE, maptype)
plt.figure(figsize=(10, 10))
plt.imshow(np.array(img)) # Background map
plt.scatter( # Scatter plot
pixels['x_pixel'],
pixels['y_pixel'],
c=colors,
s=width / 40,
linewidth=0,
alpha=alpha,
)
plt.gca().invert_yaxis() # Origin of map is upper left
plt.axis([0, width, width, 0]) # Remove margin
plt.axis('off')
plt.tight_layout()
plt.show()
def plot_markers(markers, maptype=MAPTYPE):
"""Plot markers on a map.
:param pandas.DataFrame markers: DataFrame with at least 'latitude' and 'longitude' columns, and optionally
* 'color' column, see GoogleStaticMapsAPI docs for more info
* 'label' column, see GoogleStaticMapsAPI docs for more info
* 'size' column, see GoogleStaticMapsAPI docs for more info
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:return: None
"""
# Checking input columns
fields = markers.columns.intersection(['latitude', 'longitude', 'color', 'label', 'size'])
if not fields or 'latitude' not in fields or 'longitude' not in fields:
msg = 'Input dataframe should contain at least colums \'latitude\' and \'longitude\' '
msg += '(and columns \'color\', \'label\', \'size\' optionally).'
raise KeyError(msg)
# Checking NaN input
nans = (markers.latitude.isnull() | markers.longitude.isnull())
if nans.sum() > 0:
warnings.warn('Ignoring {} example(s) containing NaN latitude or longitude.'.format(nans.sum()))
# Querying map
img = GoogleStaticMapsAPI.map(
scale=SCALE,
markers=markers[fields].loc[~nans].T.to_dict().values(),
maptype=maptype,
)
plt.figure(figsize=(10, 10))
plt.imshow(np.array(img))
plt.tight_layout()
plt.axis('off')
plt.show()
def heatmap(latitudes, longitudes, values, resolution=None, maptype=MAPTYPE, alpha=0.25):
"""Plot a geographical heatmap of the given metric.
:param pandas.Series latitudes: series of sample latitudes
:param pandas.Series longitudes: series of sample longitudes
:param pandas.Series values: series of sample values
:param int resolution: resolution (in pixels) for the heatmap
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:param float alpha: transparency for heatmap overlay, between 0 (transparent) and 1 (opaque)
:return: None
"""
img, pixels = background_and_pixels(latitudes, longitudes, MAX_SIZE, maptype)
# Smooth metric
z = grid_density_gaussian_filter(
zip(pixels['x_pixel'], pixels['y_pixel'], values),
MAX_SIZE * SCALE,
resolution=resolution if resolution else MAX_SIZE * SCALE, # Heuristic for pretty plots
)
# Plot
width = SCALE * MAX_SIZE
plt.figure(figsize=(10, 10))
plt.imshow(np.array(img)) # Background map
plt.imshow(z, origin='lower', extent=[0, width, 0, width], alpha=alpha) # Foreground, transparent heatmap
plt.scatter(pixels['x_pixel'], pixels['y_pixel'], s=1) # Markers of all points
plt.gca().invert_yaxis() # Origin of map is upper left
plt.axis([0, width, width, 0]) # Remove margin
plt.axis('off')
plt.tight_layout()
plt.show()
def density_plot(latitudes, longitudes, resolution=None, maptype=MAPTYPE, alpha=0.25):
"""Given a set of geo coordinates, draw a density plot on a map.
:param pandas.Series latitudes: series of sample latitudes
:param pandas.Series longitudes: series of sample longitudes
:param int resolution: resolution (in pixels) for the heatmap
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:param float alpha: transparency for heatmap overlay, between 0 (transparent) and 1 (opaque)
:return: None
"""
heatmap(latitudes, longitudes, np.ones(latitudes.shape[0]), resolution=resolution, maptype=maptype, alpha=alpha)
def grid_density_gaussian_filter(data, size, resolution=None, smoothing_window=None):
"""Smoothing grid values with a Gaussian filter.
:param [(float, float, float)] data: list of 3-dimensional grid coordinates
:param int size: grid size
:param int resolution: desired grid resolution
:param int smoothing_window: size of the gaussian kernels for smoothing
:return: smoothed grid values
:rtype: numpy.ndarray
"""
resolution = resolution if resolution else size
k = (resolution - 1) / size
w = smoothing_window if smoothing_window else int(0.01 * resolution) # Heuristic
imgw = (resolution + 2 * w)
img = np.zeros((imgw, imgw))
for x, y, z in data:
ix = int(x * k) + w
iy = int(y * k) + w
if 0 <= ix < imgw and 0 <= iy < imgw:
img[iy][ix] += z
z = ndi.gaussian_filter(img, (w, w)) # Gaussian convolution
z[z <= BLANK_THRESH] = np.nan # Making low values blank
return z[w:-w, w:-w]
def polygons(latitudes, longitudes, clusters, maptype=MAPTYPE, alpha=0.25):
"""Plot clusters of points on map, including them in a polygon defining their convex hull.
:param pandas.Series latitudes: series of sample latitudes
:param pandas.Series longitudes: series of sample longitudes
:param pandas.Series clusters: marker clusters
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:param float alpha: transparency for polygons overlay, between 0 (transparent) and 1 (opaque)
:return: None
"""
width = SCALE * MAX_SIZE
img, pixels = background_and_pixels(latitudes, longitudes, MAX_SIZE, maptype)
# Building collection of polygons
polygon_list = []
unique_clusters = clusters.unique()
cmap = pd.Series(np.arange(unique_clusters.shape[0] - 1, -1, -1), index=unique_clusters)
for c in unique_clusters:
in_polygon = clusters == c
if in_polygon.sum() < 3:
print('[WARN] Cannot draw polygon for cluster {} - only {} samples.'.format(c, in_polygon.sum()))
continue
cluster_pixels = pixels.loc[clusters == c]
polygon_list.append(Polygon(cluster_pixels.iloc[ConvexHull(cluster_pixels).vertices], closed=True))
# Background map
plt.figure(figsize=(10, 10))
ax = plt.subplot(111)
plt.imshow(np.array(img))
# Collection of polygons
p = PatchCollection(polygon_list, cmap='jet', alpha=alpha)
p.set_array(cmap.values)
ax.add_collection(p)
# Scatter plot
plt.scatter(
pixels['x_pixel'],
pixels['y_pixel'],
c=cmap.loc[clusters],
cmap='jet',
s=width / 40,
linewidth=0,
alpha=alpha,
)
# Axis options
plt.gca().invert_yaxis() # Origin of map is upper left
plt.axis([0, width, width, 0]) # Remove margin
plt.axis('off')
plt.tight_layout()
# Building legend box
jet_cmap = cm.get_cmap('jet')
plt.legend(
[Rectangle((0, 0), 1, 1, fc=jet_cmap(i / max(cmap.shape[0] - 1, 1)), alpha=alpha) for i in cmap.values],
cmap.index,
loc=4,
bbox_to_anchor=(1.1, 0),
)
plt.show()
def polyline(latitudes, longitudes, closed=False, maptype=MAPTYPE, alpha=1.):
"""Plot a polyline on a map, joining (lat lon) pairs in the order defined by the input.
:param pandas.Series latitudes: series of sample latitudes
:param pandas.Series longitudes: series of sample longitudes
:param bool closed: set to `True` if you want to close the line, from last (lat, lon) pair back to first one
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:param float alpha: transparency for polyline overlay, between 0 (transparent) and 1 (opaque)
:return: None
"""
width = SCALE * MAX_SIZE
img, pixels = background_and_pixels(latitudes, longitudes, MAX_SIZE, maptype)
# Building polyline
verts = pixels.values.tolist()
codes = [Path.MOVETO] + [Path.LINETO for _ in range(max(pixels.shape[0] - 1, 0))]
if closed:
verts.append(verts[0])
codes.append(Path.CLOSEPOLY)
# Background map
plt.figure(figsize=(10, 10))
ax = plt.subplot(111)
plt.imshow(np.array(img))
# Polyline
patch = PathPatch(Path(verts, codes), facecolor='none', lw=2, alpha=alpha)
ax.add_patch(patch)
# Axis options
plt.gca().invert_yaxis() # Origin of map is upper left
plt.axis([0, width, width, 0]) # Remove margin
plt.axis('off')
plt.tight_layout()
plt.show()
| [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.cm.get_cmap",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.imshow",
"scipy.ndimage.gaussian_filter",
"numpy.zeros",
"matplotlib.pyplot.axis",
"numpy.ones",
"matplotlib.path.Path",
"matplotlib.pyplot.figure",
"numpy.array",
... | [((3018, 3046), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (3028, 3046), True, 'from matplotlib import pyplot as plt\n'), ((3144, 3247), 'matplotlib.pyplot.scatter', 'plt.scatter', (["pixels['x_pixel']", "pixels['y_pixel']"], {'c': 'colors', 's': '(width / 40)', 'linewidth': '(0)', 'alpha': 'alpha'}), "(pixels['x_pixel'], pixels['y_pixel'], c=colors, s=width / 40,\n linewidth=0, alpha=alpha)\n", (3155, 3247), True, 'from matplotlib import pyplot as plt\n'), ((3483, 3513), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, width, width, 0]'], {}), '([0, width, width, 0])\n', (3491, 3513), True, 'from matplotlib import pyplot as plt\n'), ((3575, 3590), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3583, 3590), True, 'from matplotlib import pyplot as plt\n'), ((3595, 3613), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3611, 3613), True, 'from matplotlib import pyplot as plt\n'), ((3618, 3628), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3626, 3628), True, 'from matplotlib import pyplot as plt\n'), ((4928, 4956), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (4938, 4956), True, 'from matplotlib import pyplot as plt\n'), ((4991, 5009), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5007, 5009), True, 'from matplotlib import pyplot as plt\n'), ((5014, 5029), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (5022, 5029), True, 'from matplotlib import pyplot as plt\n'), ((5034, 5044), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5042, 5044), True, 'from matplotlib import pyplot as plt\n'), ((6037, 6065), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (6047, 6065), True, 'from matplotlib import pyplot as plt\n'), ((6167, 6238), 'matplotlib.pyplot.imshow', 'plt.imshow', (['z'], {'origin': '"""lower"""', 'extent': '[0, width, 0, width]', 'alpha': 'alpha'}), "(z, origin='lower', extent=[0, width, 0, width], alpha=alpha)\n", (6177, 6238), True, 'from matplotlib import pyplot as plt\n'), ((6281, 6335), 'matplotlib.pyplot.scatter', 'plt.scatter', (["pixels['x_pixel']", "pixels['y_pixel']"], {'s': '(1)'}), "(pixels['x_pixel'], pixels['y_pixel'], s=1)\n", (6292, 6335), True, 'from matplotlib import pyplot as plt\n'), ((6495, 6525), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, width, width, 0]'], {}), '([0, width, width, 0])\n', (6503, 6525), True, 'from matplotlib import pyplot as plt\n'), ((6591, 6606), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (6599, 6606), True, 'from matplotlib import pyplot as plt\n'), ((6611, 6629), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6627, 6629), True, 'from matplotlib import pyplot as plt\n'), ((6634, 6644), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6642, 6644), True, 'from matplotlib import pyplot as plt\n'), ((7986, 8008), 'numpy.zeros', 'np.zeros', (['(imgw, imgw)'], {}), '((imgw, imgw))\n', (7994, 8008), True, 'import numpy as np\n'), ((8173, 8205), 'scipy.ndimage.gaussian_filter', 'ndi.gaussian_filter', (['img', '(w, w)'], {}), '(img, (w, w))\n', (8192, 8205), True, 'import scipy.ndimage as ndi\n'), ((9672, 9700), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (9682, 9700), True, 'from matplotlib import pyplot as plt\n'), ((9710, 9726), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (9721, 9726), True, 'from matplotlib import pyplot as plt\n'), ((9794, 9848), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['polygon_list'], {'cmap': '"""jet"""', 'alpha': 'alpha'}), "(polygon_list, cmap='jet', alpha=alpha)\n", (9809, 9848), False, 'from matplotlib.collections import PatchCollection\n'), ((9926, 10053), 'matplotlib.pyplot.scatter', 'plt.scatter', (["pixels['x_pixel']", "pixels['y_pixel']"], {'c': 'cmap.loc[clusters]', 'cmap': '"""jet"""', 's': '(width / 40)', 'linewidth': '(0)', 'alpha': 'alpha'}), "(pixels['x_pixel'], pixels['y_pixel'], c=cmap.loc[clusters],\n cmap='jet', s=width / 40, linewidth=0, alpha=alpha)\n", (9937, 10053), True, 'from matplotlib import pyplot as plt\n'), ((10242, 10272), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, width, width, 0]'], {}), '([0, width, width, 0])\n', (10250, 10272), True, 'from matplotlib import pyplot as plt\n'), ((10334, 10349), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (10342, 10349), True, 'from matplotlib import pyplot as plt\n'), ((10354, 10372), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10370, 10372), True, 'from matplotlib import pyplot as plt\n'), ((10414, 10432), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['"""jet"""'], {}), "('jet')\n", (10425, 10432), False, 'from matplotlib import cm\n'), ((10640, 10650), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10648, 10650), True, 'from matplotlib import pyplot as plt\n'), ((11638, 11666), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (11648, 11666), True, 'from matplotlib import pyplot as plt\n'), ((11676, 11692), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (11687, 11692), True, 'from matplotlib import pyplot as plt\n'), ((11970, 12000), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, width, width, 0]'], {}), '([0, width, width, 0])\n', (11978, 12000), True, 'from matplotlib import pyplot as plt\n'), ((12062, 12077), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (12070, 12077), True, 'from matplotlib import pyplot as plt\n'), ((12082, 12100), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (12098, 12100), True, 'from matplotlib import pyplot as plt\n'), ((12105, 12115), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12113, 12115), True, 'from matplotlib import pyplot as plt\n'), ((2866, 2901), 'pandas.Series', 'pd.Series', (['(0)'], {'index': 'latitudes.index'}), '(0, index=latitudes.index)\n', (2875, 2901), True, 'import pandas as pd\n'), ((3062, 3075), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (3070, 3075), True, 'import numpy as np\n'), ((4972, 4985), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (4980, 4985), True, 'import numpy as np\n'), ((6081, 6094), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (6089, 6094), True, 'import numpy as np\n'), ((7241, 7268), 'numpy.ones', 'np.ones', (['latitudes.shape[0]'], {}), '(latitudes.shape[0])\n', (7248, 7268), True, 'import numpy as np\n'), ((9186, 9233), 'numpy.arange', 'np.arange', (['(unique_clusters.shape[0] - 1)', '(-1)', '(-1)'], {}), '(unique_clusters.shape[0] - 1, -1, -1)\n', (9195, 9233), True, 'import numpy as np\n'), ((9742, 9755), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (9750, 9755), True, 'import numpy as np\n'), ((11708, 11721), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (11716, 11721), True, 'import numpy as np\n'), ((11760, 11778), 'matplotlib.path.Path', 'Path', (['verts', 'codes'], {}), '(verts, codes)\n', (11764, 11778), False, 'from matplotlib.path import Path\n'), ((3377, 3386), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3384, 3386), True, 'from matplotlib import pyplot as plt\n'), ((6385, 6394), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (6392, 6394), True, 'from matplotlib import pyplot as plt\n'), ((10136, 10145), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (10143, 10145), True, 'from matplotlib import pyplot as plt\n'), ((11864, 11873), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (11871, 11873), True, 'from matplotlib import pyplot as plt\n'), ((9594, 9620), 'scipy.spatial.ConvexHull', 'ConvexHull', (['cluster_pixels'], {}), '(cluster_pixels)\n', (9604, 9620), False, 'from scipy.spatial import ConvexHull\n')] |
""" Read stock data from 163
"""
from six import iteritems
from six import string_types
from six import StringIO
from pandas import DataFrame
from china_stock_data_api.cn_stock_util import DAILY_K_LINE_COLUMNS, \
NETEASE_STOCK_INFO_COLUMNS
from china_stock_data_api.cn_stock_base import CnStockBase
import json
import int_date
import re
import numpy as np
import pandas as pd
__author__ = 'WangHao'
__all__ = ["latest"]
def latest(*indices):
return NeteaseStock.latest(indices)
class NeteaseStock(CnStockBase):
_BASE = "http://quotes.money.163.com/service/chddata.html?code={}&\
start={}&end={}&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER"
@classmethod
def _get_base(cls):
return cls._BASE
@classmethod
def _parse_daily_data(cls,body,index):
df = pd.read_csv(StringIO(body))
df.columns=DAILY_K_LINE_COLUMNS
df=df.drop(columns=['股票代码','名称'])
df['日期'] = df.日期.apply(int_date.to_int_date)
df.set_index('日期', inplace=True)
df.columns.name = index
return df
@classmethod
def _process_index(cls, index):
return cls._trans_index(index)
@classmethod
def _trans_index(cls, index):
ret = index
if index.startswith('sh'):
ret = index.replace('sh', '0')
elif index.startswith('sz'):
ret = index.replace('sz', '1')
return ret
class NeteaseStockInfo(CnStockBase):
"""get stock info from netease html
sample url looks like this:
report data
`http://quotes.money.163.com/f10/zycwzb_600010,report.html`
season data
`http://quotes.money.163.com/f10/zycwzb_600010,season.html`
year data
`http://quotes.money.163.com/f10/zycwzb_600010,year.html`
season is the preferred source.
"""
_BASE = "http://quotes.money.163.com/f10/zycwzb_{},report.html"
@classmethod
def _get_base(cls):
return cls._BASE
@classmethod
def _get_batch_size(cls):
return 1
@classmethod
def _join_indices(cls, indices):
length = len(indices)
if length != 1:
raise ValueError('only accept one stock per request.')
return cls._process_index(indices[0])
@classmethod
def _process_index(cls, index):
if index.startswith(('sh', 'sz')):
index = index[2:]
return index
@classmethod
def _parse(cls, body):
matched = re.search(r'<div class="col_r" style="">(.*?)</div>', body,
re.MULTILINE | re.DOTALL | re.UNICODE)
if matched is None or len(matched.groups()) == 0:
raise ValueError('no matched data found.')
lines = matched.group(1).strip().split('\n')
value_pattern = re.compile(r'>(.*?)<', re.UNICODE)
data_array = []
stock_name = cls._get_stock_name(body)
for line in lines:
if r'<tr' not in line:
continue
data = []
line = line.strip()
for value in re.findall(value_pattern, line):
value = cls._normalize(value)
if isinstance(value, string_types) and len(value) == 0:
continue
data.append(value)
if len(data) > 0:
data_array.append(data)
if data_array:
data_array.insert(0, [stock_name] * len(data_array[0]))
data_array = np.array(data_array).T
df = DataFrame(data_array, columns=NETEASE_STOCK_INFO_COLUMNS)
df.set_index('日期', inplace=True)
return df
@classmethod
def _get_stock_name(cls, text):
ret = ''
name_pattern = re.compile(r"var STOCKNAME = '(.+)';", re.UNICODE)
for value in re.findall(name_pattern, text):
ret = value
break
return ret
@classmethod
def _normalize(cls, value):
value = value.strip()
if value == '--':
value = None
elif '-' in value and not value.startswith('-'):
value = int_date.to_int_date(value)
elif len(value) > 0:
if ',' in value:
value = value.replace(',', '')
value = float(value)
return value
@classmethod
def _trans_index(cls, index):
ret = index
if index.startswith('sh'):
ret = index.replace('sh', '0')
elif index.startswith('sz'):
ret = index.replace('sz', '1')
return ret
| [
"pandas.DataFrame",
"int_date.to_int_date",
"six.StringIO",
"re.findall",
"numpy.array",
"re.search",
"re.compile"
] | [((2544, 2645), 're.search', 're.search', (['"""<div class="col_r" style="">(.*?)</div>"""', 'body', '(re.MULTILINE | re.DOTALL | re.UNICODE)'], {}), '(\'<div class="col_r" style="">(.*?)</div>\', body, re.MULTILINE |\n re.DOTALL | re.UNICODE)\n', (2553, 2645), False, 'import re\n'), ((2870, 2903), 're.compile', 're.compile', (['""">(.*?)<"""', 're.UNICODE'], {}), "('>(.*?)<', re.UNICODE)\n", (2880, 2903), False, 'import re\n'), ((3601, 3658), 'pandas.DataFrame', 'DataFrame', (['data_array'], {'columns': 'NETEASE_STOCK_INFO_COLUMNS'}), '(data_array, columns=NETEASE_STOCK_INFO_COLUMNS)\n', (3610, 3658), False, 'from pandas import DataFrame\n'), ((3819, 3868), 're.compile', 're.compile', (['"""var STOCKNAME = \'(.+)\';"""', 're.UNICODE'], {}), '("var STOCKNAME = \'(.+)\';", re.UNICODE)\n', (3829, 3868), False, 'import re\n'), ((3892, 3922), 're.findall', 're.findall', (['name_pattern', 'text'], {}), '(name_pattern, text)\n', (3902, 3922), False, 'import re\n'), ((868, 882), 'six.StringIO', 'StringIO', (['body'], {}), '(body)\n', (876, 882), False, 'from six import StringIO\n'), ((3152, 3183), 're.findall', 're.findall', (['value_pattern', 'line'], {}), '(value_pattern, line)\n', (3162, 3183), False, 'import re\n'), ((3564, 3584), 'numpy.array', 'np.array', (['data_array'], {}), '(data_array)\n', (3572, 3584), True, 'import numpy as np\n'), ((4204, 4231), 'int_date.to_int_date', 'int_date.to_int_date', (['value'], {}), '(value)\n', (4224, 4231), False, 'import int_date\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def exhaustive_loss(encoders, decoders, batch, device, alpha=0.1, margin=1.0):
# Translation loss.
embeddings = {}
for source_feature in batch.keys():
source_descriptors = batch[source_feature]
embeddings[source_feature] = encoders[source_feature](source_descriptors)
all_embeddings = torch.cat(list(embeddings.values()), dim=0)
t_loss = torch.tensor(0.).float().to(device)
for target_feature in batch.keys():
target_descriptors = batch[target_feature]
output_descriptors = decoders[target_feature](all_embeddings)
if target_feature == 'brief':
current_loss = F.binary_cross_entropy(
output_descriptors,
torch.cat([target_descriptors] * len(batch), dim=0)
)
else:
current_loss = torch.mean(
torch.norm(output_descriptors - torch.cat([target_descriptors] * len(batch), dim=0), dim=1)
)
t_loss += current_loss
t_loss /= len(batch)
# Triplet loss in embedding space.
e_loss = torch.tensor(0.).float().to(device)
if alpha > 0:
for source_feature in embeddings.keys():
for target_feature in embeddings.keys():
# TODO: Implement symmetric negative mining.
sqdist_matrix = 2 - 2 * embeddings[source_feature] @ embeddings[target_feature].T
pos_dist = torch.norm(torch.diag(sqdist_matrix).unsqueeze(-1), dim=-1)
sqdist_matrix = sqdist_matrix + torch.diag(torch.full((sqdist_matrix.shape[0],), np.inf)).to(device)
# neg_sqdist = torch.min(torch.min(sqdist_matrix, dim=-1)[0], torch.min(sqdist_matrix, dim=0)[0])
neg_sqdist = torch.min(sqdist_matrix, dim=-1)[0]
neg_dist = torch.norm(neg_sqdist.unsqueeze(-1), dim=-1)
e_loss = e_loss + torch.mean(
F.relu(margin + pos_dist - neg_dist)
)
e_loss /= (len(batch) ** 2)
# Final loss.
if alpha > 0:
loss = t_loss + alpha * e_loss
else:
loss = t_loss
return loss, (t_loss.detach(), e_loss.detach())
def autoencoder_loss(encoders, decoders, batch, device, alpha=0.1, margin=1.0):
# AE loss.
embeddings = {}
t_loss = torch.tensor(0.).float().to(device)
for source_feature in batch.keys():
source_descriptors = batch[source_feature]
current_embeddings = encoders[source_feature](source_descriptors)
embeddings[source_feature] = current_embeddings
output_descriptors = decoders[source_feature](current_embeddings)
if source_feature == 'brief':
current_loss = F.binary_cross_entropy(
output_descriptors, source_descriptors
)
else:
current_loss = torch.mean(
torch.norm(output_descriptors - source_descriptors, dim=1)
)
t_loss += current_loss
t_loss /= len(batch)
# Triplet loss in embedding space.
e_loss = torch.tensor(0.).float().to(device)
if alpha > 0:
for source_feature in embeddings.keys():
for target_feature in embeddings.keys():
# TODO: Implement symmetric negative mining.
sqdist_matrix = 2 - 2 * embeddings[source_feature] @ embeddings[target_feature].T
pos_dist = torch.norm(torch.diag(sqdist_matrix).unsqueeze(-1), dim=-1)
sqdist_matrix = sqdist_matrix + torch.diag(torch.full((sqdist_matrix.shape[0],), np.inf)).to(device)
# neg_sqdist = torch.min(torch.min(sqdist_matrix, dim=-1)[0], torch.min(sqdist_matrix, dim=0)[0])
neg_sqdist = torch.min(sqdist_matrix, dim=-1)[0]
neg_dist = torch.norm(neg_sqdist.unsqueeze(-1), dim=-1)
e_loss = e_loss + torch.mean(
F.relu(margin + pos_dist - neg_dist)
)
e_loss /= (len(batch) ** 2)
# Final loss.
if alpha > 0:
loss = t_loss + alpha * e_loss
else:
loss = t_loss
return loss, (t_loss.detach(), e_loss.detach())
def subset_loss(encoders, decoders, batch, device, alpha=0.1, margin=1.0):
# Select random pairs of descriptors.
# Make sure that all encoders and all encoders are used.
source_features = np.array(list(batch.keys()))
target_features = np.array(source_features)
np.random.shuffle(target_features)
# Translation loss.
embeddings = {}
t_loss = torch.tensor(0.).float().to(device)
for source_feature, target_feature in zip(source_features, target_features):
source_descriptors = batch[source_feature]
target_descriptors = batch[target_feature]
current_embeddings = encoders[source_feature](source_descriptors)
embeddings[source_feature] = current_embeddings
output_descriptors = decoders[target_feature](current_embeddings)
if target_feature == 'brief':
current_loss = F.binary_cross_entropy(
output_descriptors, target_descriptors
)
else:
current_loss = torch.mean(
torch.norm(output_descriptors - target_descriptors, dim=1)
)
t_loss += current_loss
t_loss /= len(batch)
# Triplet loss in embedding space.
e_loss = torch.tensor(0.).float().to(device)
if alpha > 0:
for source_feature, target_feature in zip(source_features, target_features):
# TODO: Implement symmetric negative mining.
sqdist_matrix = 2 - 2 * embeddings[source_feature] @ embeddings[target_feature].T
pos_dist = torch.norm(torch.diag(sqdist_matrix).unsqueeze(-1), dim=-1)
sqdist_matrix = sqdist_matrix + torch.diag(torch.full((sqdist_matrix.shape[0],), np.inf)).to(device)
# neg_sqdist = torch.min(torch.min(sqdist_matrix, dim=-1)[0], torch.min(sqdist_matrix, dim=0)[0])
neg_sqdist = torch.min(sqdist_matrix, dim=-1)[0]
neg_dist = torch.norm(neg_sqdist.unsqueeze(-1), dim=-1)
e_loss = e_loss + torch.mean(
F.relu(margin + pos_dist - neg_dist)
)
e_loss /= len(batch)
# Final loss.
if alpha > 0:
loss = t_loss + alpha * e_loss
else:
loss = t_loss
return loss, (t_loss.detach(), e_loss.detach())
| [
"torch.nn.functional.binary_cross_entropy",
"torch.norm",
"torch.diag",
"torch.full",
"numpy.array",
"torch.nn.functional.relu",
"torch.tensor",
"torch.min",
"numpy.random.shuffle"
] | [((4464, 4489), 'numpy.array', 'np.array', (['source_features'], {}), '(source_features)\n', (4472, 4489), True, 'import numpy as np\n'), ((4494, 4528), 'numpy.random.shuffle', 'np.random.shuffle', (['target_features'], {}), '(target_features)\n', (4511, 4528), True, 'import numpy as np\n'), ((2775, 2837), 'torch.nn.functional.binary_cross_entropy', 'F.binary_cross_entropy', (['output_descriptors', 'source_descriptors'], {}), '(output_descriptors, source_descriptors)\n', (2797, 2837), True, 'import torch.nn.functional as F\n'), ((5075, 5137), 'torch.nn.functional.binary_cross_entropy', 'F.binary_cross_entropy', (['output_descriptors', 'target_descriptors'], {}), '(output_descriptors, target_descriptors)\n', (5097, 5137), True, 'import torch.nn.functional as F\n'), ((2937, 2995), 'torch.norm', 'torch.norm', (['(output_descriptors - source_descriptors)'], {'dim': '(1)'}), '(output_descriptors - source_descriptors, dim=1)\n', (2947, 2995), False, 'import torch\n'), ((5237, 5295), 'torch.norm', 'torch.norm', (['(output_descriptors - target_descriptors)'], {'dim': '(1)'}), '(output_descriptors - target_descriptors, dim=1)\n', (5247, 5295), False, 'import torch\n'), ((6040, 6072), 'torch.min', 'torch.min', (['sqdist_matrix'], {'dim': '(-1)'}), '(sqdist_matrix, dim=-1)\n', (6049, 6072), False, 'import torch\n'), ((469, 486), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (481, 486), False, 'import torch\n'), ((1157, 1174), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (1169, 1174), False, 'import torch\n'), ((1819, 1851), 'torch.min', 'torch.min', (['sqdist_matrix'], {'dim': '(-1)'}), '(sqdist_matrix, dim=-1)\n', (1828, 1851), False, 'import torch\n'), ((2379, 2396), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (2391, 2396), False, 'import torch\n'), ((3119, 3136), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (3131, 3136), False, 'import torch\n'), ((3781, 3813), 'torch.min', 'torch.min', (['sqdist_matrix'], {'dim': '(-1)'}), '(sqdist_matrix, dim=-1)\n', (3790, 3813), False, 'import torch\n'), ((4587, 4604), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (4599, 4604), False, 'import torch\n'), ((5419, 5436), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (5431, 5436), False, 'import torch\n'), ((6202, 6238), 'torch.nn.functional.relu', 'F.relu', (['(margin + pos_dist - neg_dist)'], {}), '(margin + pos_dist - neg_dist)\n', (6208, 6238), True, 'import torch.nn.functional as F\n'), ((1993, 2029), 'torch.nn.functional.relu', 'F.relu', (['(margin + pos_dist - neg_dist)'], {}), '(margin + pos_dist - neg_dist)\n', (1999, 2029), True, 'import torch.nn.functional as F\n'), ((3955, 3991), 'torch.nn.functional.relu', 'F.relu', (['(margin + pos_dist - neg_dist)'], {}), '(margin + pos_dist - neg_dist)\n', (3961, 3991), True, 'import torch.nn.functional as F\n'), ((5743, 5768), 'torch.diag', 'torch.diag', (['sqdist_matrix'], {}), '(sqdist_matrix)\n', (5753, 5768), False, 'import torch\n'), ((1510, 1535), 'torch.diag', 'torch.diag', (['sqdist_matrix'], {}), '(sqdist_matrix)\n', (1520, 1535), False, 'import torch\n'), ((3472, 3497), 'torch.diag', 'torch.diag', (['sqdist_matrix'], {}), '(sqdist_matrix)\n', (3482, 3497), False, 'import torch\n'), ((5847, 5892), 'torch.full', 'torch.full', (['(sqdist_matrix.shape[0],)', 'np.inf'], {}), '((sqdist_matrix.shape[0],), np.inf)\n', (5857, 5892), False, 'import torch\n'), ((1618, 1663), 'torch.full', 'torch.full', (['(sqdist_matrix.shape[0],)', 'np.inf'], {}), '((sqdist_matrix.shape[0],), np.inf)\n', (1628, 1663), False, 'import torch\n'), ((3580, 3625), 'torch.full', 'torch.full', (['(sqdist_matrix.shape[0],)', 'np.inf'], {}), '((sqdist_matrix.shape[0],), np.inf)\n', (3590, 3625), False, 'import torch\n')] |
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
import numpy as np
class SelfAttn(nn.Module):
'''
self-attention with learnable parameters
make a single continuous representation for a sentence.
'''
def __init__(self, dhid):
super().__init__()
self.scorer = nn.Linear(dhid, 1)
def forward(self, inp):
'''
inp: shape (B, T, *)
'''
# shape (B, T, 1), per word score normalized across each sentence
scores = F.softmax(self.scorer(inp), dim=1)
# shape (B, 1, T) bmm shape (B, T, *)
# = shape (B, 1, *).squeeze(1) = shape (B, *)
cont = scores.transpose(1, 2).bmm(inp).squeeze(1)
return cont
class DotAttn(nn.Module):
'''
dot-attention (or soft-attention)
'''
def forward(self, inp, h):
'''
inp: shape (B, t, 2*args.dhid)
h: (B, args.2*dhid)
'''
# (B, t, 1)
score = self.softmax(inp, h)
# (B, t, 2*args.dhid) element multiply (B, t, 2*args.dhid) = (B, t, 2*args.dhid)
# sum(B, t, 2*args.dhid, dim=1) = (B, 2*args.dhid)
# (B, 2*args.dhid), (B, t, 1)
return score.expand_as(inp).mul(inp).sum(1), score
def softmax(self, inp, h):
# (B, t, 2*args.dhid) mm (B, args.2*dhid, 1) = (B, t, 1)
raw_score = inp.bmm(h.unsqueeze(2))
# (B, t, 1)
score = F.softmax(raw_score, dim=1)
return score
class DotSigmoidAttn(nn.Module):
'''
dot-attention (or soft-attention) with sigmoid
'''
def forward(self, inp, h):
'''
inp: shape (B, t, args.dhid)
h: (B, args.dhid)
'''
# (B, t, 1)
score = self.sigmoid(inp, h)
# (B, t, args.dhid) element multiply (B, t, args.dhid) = (B, t, args.dhid)
# max(B, t, args.dhid, dim=1) = (B, args.dhid)
# (B, args.dhid), (B, t, 1)
return score.expand_as(inp).mul(inp).max(1)[0], score
def sigmoid(self, inp, h):
# (B, t, args.dhid) mm (B, args.dhid, 1) = (B, t, 1)
raw_score = inp.bmm(h.unsqueeze(2))
# (B, t, 1)
score = torch.sigmoid(raw_score)
return score
class ResnetVisualEncoder(nn.Module):
'''
visual encoder
'''
def __init__(self, dframe):
super(ResnetVisualEncoder, self).__init__()
self.dframe = dframe
self.flattened_size = 64*7*7
self.conv1 = nn.Conv2d(512, 256, kernel_size=1, stride=1, padding=0)
self.conv2 = nn.Conv2d(256, 64, kernel_size=1, stride=1, padding=0)
self.fc = nn.Linear(self.flattened_size, self.dframe)
self.bn1 = nn.BatchNorm2d(256)
self.bn2 = nn.BatchNorm2d(64)
def forward(self, x):
x = self.conv1(x)
x = F.relu(self.bn1(x))
x = self.conv2(x)
x = F.relu(self.bn2(x))
x = x.view(-1, self.flattened_size)
x = self.fc(x)
return x
class ActionFrameAttnEncoder(nn.Module):
'''
action and frame sequence encoder base
'''
def __init__(self, emb, dframe, dhid,
act_dropout=0., vis_dropout=0., bidirectional=True, gpu=False):
super(ActionFrameAttnEncoder, self).__init__()
# Embedding matrix for Actions
self.emb = emb
self.dhid = dhid
self.bidirectional = bidirectional
self.dframe = dframe
self.demb = emb.weight.size(1)
# Dropouts
self.vis_dropout = nn.Dropout(vis_dropout)
self.act_dropout = nn.Dropout(act_dropout, inplace=True)
# Image Frame encoder
self.vis_encoder = ResnetVisualEncoder(dframe=dframe)
# Self Attn
self.enc_att = SelfAttn(dhid*2)
def vis_enc_step(self, frames):
'''
encode image frames for all time steps
'''
B = frames.shape[0]
T = frames.shape[1]
# (B*T, 512, 7, 7)
frames = frames.reshape(B*T, frames.shape[2], frames.shape[3], frames.shape[4])
vis_feat = self.vis_encoder(frames)
vis_feat = vis_feat.reshape(B, T, self.dframe)
return vis_feat
class ActionFrameAttnEncoderFullSeq(ActionFrameAttnEncoder):
'''
action and frame sequence encoder. encode all subgoals at once.
'''
def __init__(self, emb, dframe, dhid,
act_dropout=0., vis_dropout=0., bidirectional=True):
super(ActionFrameAttnEncoderFullSeq, self).__init__(emb, dframe, dhid,
act_dropout=act_dropout, vis_dropout=vis_dropout, bidirectional=bidirectional)
# Image + Action encoder
self.encoder = nn.LSTM(self.demb+self.dframe, self.dhid,
bidirectional=self.bidirectional,
batch_first=True)
def forward(self, feat):
'''
encode low-level actions and image frames
'''
# Action Sequence
# (B, T) with T = max(L), already padded
pad_seq = feat['action_low']
# (B,). Each value is L for the example
seq_lengths = feat['action_low_seq_lengths']
# (B, T, args.demb)
emb_act = self.emb(pad_seq)
# Image Frames
# (B, T, 512, 7, 7) with T = max(L), already padded
frames = self.vis_dropout(feat['frames'])
# (B, T, args.dframe)
vis_feat = self.vis_enc_step(frames)
# Pack inputs together
# (B, T, args.demb+args.dframe)
inp_seq = torch.cat([emb_act, vis_feat], dim=2)
packed_input = pack_padded_sequence(inp_seq, seq_lengths, batch_first=True, enforce_sorted=False)
# Encode entire sequence
# packed sequence object
enc_act, _ = self.encoder(packed_input)
# (B, T, args.dhid*2) -- *2 for birdirectional
enc_act, _ = pad_packed_sequence(enc_act, batch_first=True)
self.act_dropout(enc_act)
# Apply learned self-attention
# (B, args.dhid*2)
cont_act = self.enc_att(enc_act)
# return both compact and per-step representations
return cont_act, enc_act
class ActionFrameAttnEncoderPerSubgoal(ActionFrameAttnEncoder):
'''
action and frame sequence encoder. encode one subgoal at a time.
'''
def __init__(self, emb, obj_emb, object_repr, dframe, dhid, instance_fc,
act_dropout=0., vis_dropout=0., input_dropout=0., hstate_dropout=0., attn_dropout=0., bidirectional=True):
super(ActionFrameAttnEncoderPerSubgoal, self).__init__(emb=emb, dframe=dframe, dhid=dhid,
act_dropout=act_dropout, vis_dropout=vis_dropout, bidirectional=bidirectional)
# Image + Action encoder
# action embedding + image vector dim
# or action embedding + image vector dim
self.encoder = nn.LSTM( self.demb+self.dframe,
self.dhid,
bidirectional=self.bidirectional,
batch_first=True)
self.input_dropout = nn.Dropout(input_dropout)
self.hstate_dropout = nn.Dropout(hstate_dropout)
self.attn_dropout = nn.Dropout(attn_dropout)
# object handling
# (V, dhid)
self.obj_emb = obj_emb
# self.obj_demb = self.obj_emb.weight.size(1)
self.object_repr = object_repr # 'type' or 'instance
if self.object_repr == 'instance':
assert instance_fc is not None
self.instance_fc = instance_fc
def make_instance_embeddings(self, object_indices, receptacle_indices, object_distances):
'''
object_indices: (B, t, max_num_objects in batch)
receptacle_indices: (B, t, max_num_objects in batch)
object_distance: (B, t, max_num_objects in batch)
'''
# concat and transform
# (B, t, max_num_objects in batch, obj demb)
obj_embeddings = self.obj_emb(object_indices)
# (B, t, max_num_objects in batch, obj demb)
recep_embeddings = self.obj_emb(receptacle_indices)
# (B, t, max_num_objects in batch, obj demb + obj demb + 1)
cat_embeddings = torch.cat([obj_embeddings, recep_embeddings, object_distances.unsqueeze(-1)], dim=len(obj_embeddings.shape) - 1)
# (B, t, max_num_objects in batch, dhid)
return self.instance_fc(cat_embeddings)
def forward(self, feat_subgoal, last_subgoal_hx):
'''
encode low-level actions and image frames
Args:
last_subgoal_hx: tuple. (h_0, c_0) argument per nn.LSTM documentation.
'''
# Action Sequence
# (B, t) with t = max(l), already padded
pad_seq = feat_subgoal['action_low']
# (B,). Each value is l for the example
seq_lengths = feat_subgoal['action_low_seq_lengths']
# (B, t, args.demb)
emb_act = self.emb(pad_seq)
# Image Frames
# (B, t, 512, 7, 7) with t = max(l), already padded
frames = self.vis_dropout(feat_subgoal['frames'])
# (B, t, args.dframe)
vis_feat = self.vis_enc_step(frames)
# ( B, t, args.demb+args.dframe)
inp_seq = torch.cat([emb_act, vis_feat], dim=2)
packed_input = pack_padded_sequence(inp_seq, seq_lengths, batch_first=True, enforce_sorted=False)
# Encode entire subgoal sequence
# packed sequence object, (h_n, c_n) tuple
enc_act, curr_subgoal_states = self.encoder(input=packed_input, hx=last_subgoal_hx)
# (B, t, args.dhid*2)
enc_act, _ = pad_packed_sequence(enc_act, batch_first=True)
self.act_dropout(enc_act)
# Apply learned self-attention
# (B, args.dhid*2)
cont_act = self.enc_att(enc_act)
# return both compact, per-step representations, (h_n, c_n) for starting next subgoal encoding
return cont_act, enc_act, curr_subgoal_states
class ActionFrameAttnEncoderPerSubgoalObjAttn(ActionFrameAttnEncoderPerSubgoal):
'''
action and frame sequence encoder. encode one subgoal at a time. use attention over object states
'''
def __init__(self, emb, obj_emb, object_repr, dframe, dhid, instance_fc,
act_dropout=0., vis_dropout=0., input_dropout=0., hstate_dropout=0., attn_dropout=0., bidirectional=True):
super(ActionFrameAttnEncoderPerSubgoalObjAttn, self).__init__(emb=emb, obj_emb=obj_emb, object_repr=object_repr, dframe=dframe, dhid=dhid, instance_fc=instance_fc,
act_dropout=act_dropout, vis_dropout=vis_dropout, input_dropout=input_dropout ,hstate_dropout=hstate_dropout, attn_dropout=attn_dropout, bidirectional=bidirectional)
# object states handling
# dhid to dhid
# self.obj_attn = DotAttn()
self.obj_attn = DotSigmoidAttn()
# linear for hidden state before attention
self.h_tm1_fc = nn.Linear(dhid, dhid)
# Image + Action + obj attn encoder
# action embedding + image vector dim + obj embed + obj embed
self.forward_cell = nn.LSTMCell(self.demb+self.dframe+self.dhid+self.dhid, self.dhid)
if bidirectional:
self.backward_cell = nn.LSTMCell(self.demb+self.dframe+self.dhid+self.dhid, self.dhid)
def filter_obj_embeds(self, object_indices, object_boolean_features, receptacle_indices=None, object_distances=None):
'''
make continuous repr for object embeddding, visibility and state change.
object_indices: (B, t, max_num_objects in batch)
object_boolean_features: (B, t, max_num_objects in batch)
'''
if self.object_repr == 'instance':
# (B, t, max_num_objects in batch, dhid)
obj_embeddings = self.make_instance_embeddings(object_indices, receptacle_indices, object_distances)
else: # 'type'
# (B, t, max_num_objects in batch, dhid)
obj_embeddings = self.obj_emb(object_indices)
# (B, t, max_num_objects in batch, dhid)
obj_embeddings = object_boolean_features.unsqueeze(-1).expand_as(obj_embeddings).mul(obj_embeddings)
return obj_embeddings
def step(self, cell, emb_act_t, vis_feat_t, obj_vis_t, obj_stc_t, state_tm1):
# previous decoder hidden state
# (B, args.dhid)
h_tm1 = state_tm1[0]
# inputs (B, V, args.dhid), (B, args.dhid)
# output (B, args.dhid), (B, t, 1)
weighted_obj_vis_t, obj_vis_attn_t = self.obj_attn(self.attn_dropout(obj_vis_t), self.h_tm1_fc(h_tm1))
weighted_obj_stc_t, obj_stc_attn_t = self.obj_attn(self.attn_dropout(obj_stc_t), self.h_tm1_fc(h_tm1))
# action embedding + image vector dim + obj vis embed + obj stc embed
inp_t = torch.cat([emb_act_t, vis_feat_t, weighted_obj_vis_t, weighted_obj_stc_t], dim=1)
inp_t = self.input_dropout(inp_t)
# update hidden state
# (B, args.dhid, ), (B, args.dhid, )
state_t = cell(inp_t, state_tm1)
state_t = [self.hstate_dropout(x) for x in state_t]
return state_t, obj_vis_attn_t, obj_stc_attn_t
def encode_sequence_one_direction(self, emb_act, vis_feat, obj_vis, obj_stc, last_subgoal_hx, backward=False):
'''
encode entire sequence of inputs in a single direction
emb_act: (B, t, args.demb)
vis_feat: (B, t, args.dframe)
obj_vis: (B, t, max_num_objects in batch, demb)
obj_stc: (B, t, max_num_objects in batch, demb)
last_subgoal_hx: tuple. (h_0, c_0) argument per nn.LSTM documentation. This has shape =((B, args.dhid), (B, args.dhid)).
'''
assert last_subgoal_hx[0].shape == last_subgoal_hx[1].shape == (emb_act.shape[0], self.dhid)
max_t = emb_act.shape[1]
timesteps = range(max_t) if not backward else range(max_t)[::-1]
cell = self.forward_cell if not backward else self.backward_cell
state_t = last_subgoal_hx
assert last_subgoal_hx[0].shape == last_subgoal_hx[1].shape == (emb_act.shape[0], self.dhid)
# (B, t, args.dhid)
enc_act = torch.zeros(emb_act.shape[0], max_t, self.dhid, device=emb_act.device, dtype=torch.float)
# obj_vis_attn_scores, obj_stc_attn_scores = [], []
for t in timesteps:
state_t, obj_vis_attn_t, obj_stc_attn_t = self.step(cell, emb_act[:,t,:], vis_feat[:,t,:], obj_vis[:,t,:], obj_stc[:,t,:], state_t)
enc_act[:,t,:] = state_t[0]
# (h_n, c_n)=((B, args.dhid), (B, args.dhid)) tuple
curr_subgoal_states = state_t
# (B, t, args.dhid), (h_n, c_n)=((B, args.dhid), (B, args.dhid)) tuple
return enc_act, curr_subgoal_states
def encode_sequence(self, emb_act, vis_feat, obj_vis, obj_stc, last_subgoal_hx):
'''
encode entire sequence of inputs
emb_act: (B, t, args.demb)
vis_feat: (B, t, args.dframe)
obj_vis: (B, t, max_num_objects in batch, demb)
obj_stc: (B, t, max_num_objects in batch, demb)
last_subgoal_hx: tuple. (h_0, c_0) argument per nn.LSTM documentation. For bidirectional, this has shape =((B, args.dhid*2), (B, args.dhid*2)).
'''
assert emb_act.shape[1] == vis_feat.shape[1] == obj_vis.shape[1] == obj_stc.shape[1]
if not self.bidirectional:
# (B, t, args.dhid), (h_n, c_n) tuple
enc_act, curr_subgoal_states = self.encode_sequence_one_direction(emb_act, vis_feat, obj_vis, obj_stc, last_subgoal_hx)
# (B, t, args.dhid), (h_n, c_n)=((B, args.dhid), (B, args.dhid)) tuple
return enc_act, curr_subgoal_states
else:
# (B, t, args.dhid), (h_n, c_n) tuple
enc_act_forward, curr_subgoal_states_forward = self.encode_sequence_one_direction(emb_act, vis_feat, obj_vis, obj_stc, (last_subgoal_hx[0][:,:self.dhid], last_subgoal_hx[1][:,:self.dhid]))
# (B, t, args.dhid), (h_n, c_n) tuple
enc_act_backward, curr_subgoal_states_backward = self.encode_sequence_one_direction(emb_act, vis_feat, obj_vis, obj_stc, (last_subgoal_hx[0][:,self.dhid:], last_subgoal_hx[1][:,self.dhid:]), backward=True)
# (B, t, args.dhid*2)
enc_act = torch.cat([enc_act_forward, enc_act_backward], dim=2)
# ((B, args.dhid*2), (B, args.dhid*2))
curr_subgoal_states = (
torch.cat([curr_subgoal_states_forward[0], curr_subgoal_states_backward[0]], dim=1),
torch.cat([curr_subgoal_states_forward[1], curr_subgoal_states_backward[1]], dim=1)
)
# (B, t, args.dhid*2), (h_n, c_n)=((B, args.dhid*2), (B, args.dhid*2)) tuple
return enc_act, curr_subgoal_states
def forward(self, feat_subgoal, last_subgoal_hx):
'''
encode low-level actions and image frames
Args:
last_subgoal_hx: tuple. (h_0, c_0) argument per nn.LSTM documentation. For bidirectional, this has shape =((B, args.dhid*2), (B, args.dhid*2)).
'''
# Action Sequence
# (B, t) with t = max(l), already padded
pad_seq = feat_subgoal['action_low']
# (B,). Each value is l for the example
seq_lengths = feat_subgoal['action_low_seq_lengths']
# (B, t, args.demb)
emb_act = self.emb(pad_seq)
# Image Frames
# (B, t, 512, 7, 7) with t = max(l), already padded
frames = self.vis_dropout(feat_subgoal['frames'])
# (B, t, args.dframe)
vis_feat = self.vis_enc_step(frames)
# Make object representation
if self.object_repr == 'instance':
# (B, t, max_num_objects in batch, dhid)
obj_vis = self.filter_obj_embeds(
feat_subgoal['object_token_id'], feat_subgoal['object_visibility'],
receptacle_indices=feat_subgoal['receptacle_token_id'], object_distances=feat_subgoal['object_distance'])
obj_stc = self.filter_obj_embeds(
feat_subgoal['object_token_id'], feat_subgoal['object_state_change'],
receptacle_indices=feat_subgoal['receptacle_token_id'], object_distances=feat_subgoal['object_distance'])
else: # 'type'
# (B, t, max_num_objects in batch, dhid)
obj_vis = self.filter_obj_embeds(feat_subgoal['object_token_id'], feat_subgoal['object_visibility'])
obj_stc = self.filter_obj_embeds(feat_subgoal['object_token_id'], feat_subgoal['object_state_change'])
# hidden state at timestep 0
if last_subgoal_hx is None:
h_0 = torch.zeros(emb_act.shape[0], 2*self.dhid if self.bidirectional else self.dhid, dtype=torch.float, device=pad_seq.device)
c_0 = torch.zeros_like(h_0)
last_subgoal_hx = (h_0, c_0)
# (B, t, args.dhid), (h_n, c_n) tuple
enc_act, curr_subgoal_states = self.encode_sequence(emb_act, vis_feat, obj_vis, obj_stc, last_subgoal_hx)
self.act_dropout(enc_act)
# Apply learned self-attention
# (B, args.dhid*2)
cont_act = self.enc_att(enc_act)
# (B, args.dhid*2), (B, t, args.dhid*2), (h_n, c_n)
return cont_act, enc_act, curr_subgoal_states
class ActionFrameAttnEncoderPerSubgoalMaxPool(ActionFrameAttnEncoderPerSubgoal):
'''
action and frame sequence encoder. encode one subgoal at a time. max-pool over object states
'''
def __init__(self, emb, obj_emb, object_repr, dframe, dhid, instance_fc,
act_dropout=0., vis_dropout=0., input_dropout=0., hstate_dropout=0., attn_dropout=0., bidirectional=True):
super(ActionFrameAttnEncoderPerSubgoalMaxPool, self).__init__(emb=emb, obj_emb=obj_emb, object_repr=object_repr, dframe=dframe, dhid=dhid, instance_fc=instance_fc,
act_dropout=act_dropout, vis_dropout=vis_dropout, input_dropout=input_dropout, hstate_dropout=hstate_dropout, attn_dropout=attn_dropout, bidirectional=bidirectional)
# Image + Action encoder
# action embedding + image vector dim + obj embedding + obj embedding
# or action embedding + image vector dim
self.encoder = nn.LSTM( self.demb+self.dframe+self.dhid+self.dhid ,
self.dhid,
bidirectional=self.bidirectional,
batch_first=True)
def max_pool_object_features(self, object_indices, object_boolean_features, receptacle_indices=None, object_distances=None):
'''
Max pool each embedding val across objects.
object_indices : shape (B, t, max_num_objects in batch). each int index for object vocab.
object_boolean_features : shape (B, t, max_num_objects in batch). each 1/0
'''
if self.object_repr == 'instance':
# (B, t, max_num_objects in batch, dhid)
obj_embeddings = self.make_instance_embeddings(object_indices, receptacle_indices, object_distances)
else: # 'type'
# (B, t, max_num_objects in batch, dhid)
obj_embeddings = self.obj_emb(object_indices)
# (B, t, max_num_objects in batch, dhid)
obj_embeddings = object_boolean_features.unsqueeze(-1).expand_as(obj_embeddings).mul(obj_embeddings)
# (B, t, dhid)
return obj_embeddings.max(2)[0]
def forward(self, feat_subgoal, last_subgoal_hx):
'''
encode low-level actions and image frames
Args:
last_subgoal_hx: tuple. (h_0, c_0) argument per nn.LSTM documentation.
'''
# Action Sequence
# (B, t) with t = max(l), already padded
pad_seq = feat_subgoal['action_low']
# (B,). Each value is l for the example
seq_lengths = feat_subgoal['action_low_seq_lengths']
# (B, t, args.demb)
emb_act = self.emb(pad_seq)
# Image Frames
# (B, t, 512, 7, 7) with t = max(l), already padded
frames = self.vis_dropout(feat_subgoal['frames'])
# (B, t, args.dframe)
vis_feat = self.vis_enc_step(frames)
# Make object representation
if self.object_repr == 'instance':
# (B, t, dhid), (B, t, dhid)
obj_visible = self.max_pool_object_features(
feat_subgoal['object_token_id'], feat_subgoal['object_visibility'],
receptacle_indices=feat_subgoal['receptacle_token_id'], object_distances=feat_subgoal['object_distance'])
obj_state_change = self.max_pool_object_features(
feat_subgoal['object_token_id'], feat_subgoal['object_state_change'],
receptacle_indices=feat_subgoal['receptacle_token_id'], object_distances=feat_subgoal['object_distance'])
else: # 'type'
# (B, t, dhid)
obj_visible = self.max_pool_object_features(feat_subgoal['object_token_id'], feat_subgoal['object_visibility'])
obj_state_change = self.max_pool_object_features(feat_subgoal['object_token_id'], feat_subgoal['object_state_change'])
# ( B, t, args.demb+args.dframe+args.dhid+args.dhid)
inp_seq = torch.cat([emb_act, vis_feat, obj_visible, obj_state_change], dim=2)
packed_input = pack_padded_sequence(inp_seq, seq_lengths, batch_first=True, enforce_sorted=False)
# Encode entire subgoal sequence
# packed sequence object, (h_n, c_n) tuple
enc_act, curr_subgoal_states = self.encoder(input=packed_input, hx=last_subgoal_hx)
# (B, t, args.dhid*2)
enc_act, _ = pad_packed_sequence(enc_act, batch_first=True)
self.act_dropout(enc_act)
# Apply learned self-attention
# (B, args.dhid*2)
cont_act = self.enc_att(enc_act)
# (B, args.dhid*2), (B, t, args.dhid*2), (h_n, c_n)
return cont_act, enc_act, curr_subgoal_states
class MaskDecoder(nn.Module):
'''
mask decoder
'''
def __init__(self, dhid, pframe=300, hshape=(64,7,7)):
super(MaskDecoder, self).__init__()
self.dhid = dhid
self.hshape = hshape
self.pframe = pframe
self.d1 = nn.Linear(self.dhid, hshape[0]*hshape[1]*hshape[2])
self.upsample = nn.UpsamplingNearest2d(scale_factor=2)
self.bn2 = nn.BatchNorm2d(32)
self.bn1 = nn.BatchNorm2d(16)
self.dconv3 = nn.ConvTranspose2d(64, 32, kernel_size=4, stride=2, padding=1)
self.dconv2 = nn.ConvTranspose2d(32, 16, kernel_size=4, stride=2, padding=1)
self.dconv1 = nn.ConvTranspose2d(16, 1, kernel_size=4, stride=2, padding=1)
def forward(self, x):
x = F.relu(self.d1(x))
x = x.view(-1, *self.hshape)
x = self.upsample(x)
x = self.dconv3(x)
x = F.relu(self.bn2(x))
x = self.upsample(x)
x = self.dconv2(x)
x = F.relu(self.bn1(x))
x = self.dconv1(x)
x = F.interpolate(x, size=(self.pframe, self.pframe), mode='bilinear')
return x
class ConvFrameMaskDecoder(nn.Module):
'''
action decoder
'''
def __init__(self, emb, dframe, dhid, pframe=300,
attn_dropout=0., hstate_dropout=0., actor_dropout=0., input_dropout=0.,
teacher_forcing=False):
super().__init__()
demb = emb.weight.size(1)
self.emb = emb
self.pframe = pframe
self.dhid = dhid
self.vis_encoder = ResnetVisualEncoder(dframe=dframe)
self.cell = nn.LSTMCell(dhid+dframe+demb, dhid)
self.attn = DotAttn()
self.input_dropout = nn.Dropout(input_dropout)
self.attn_dropout = nn.Dropout(attn_dropout)
self.hstate_dropout = nn.Dropout(hstate_dropout)
self.actor_dropout = nn.Dropout(actor_dropout)
# a learned initial action embedding to speed up learning
self.go = nn.Parameter(torch.Tensor(demb))
self.actor = nn.Linear(dhid+dhid+dframe+demb, demb)
self.mask_dec = MaskDecoder(dhid=dhid+dhid+dframe+demb, pframe=self.pframe)
self.teacher_forcing = teacher_forcing
self.h_tm1_fc = nn.Linear(dhid, dhid)
nn.init.uniform_(self.go, -0.1, 0.1)
def step(self, enc, frame, e_t, state_tm1):
# previous decoder hidden state
h_tm1 = state_tm1[0]
# encode vision and lang feat
vis_feat_t = self.vis_encoder(frame)
lang_feat_t = enc # language is encoded once at the start
# attend over language
weighted_lang_t, lang_attn_t = self.attn(self.attn_dropout(lang_feat_t), self.h_tm1_fc(h_tm1))
# concat visual feats, weight lang, and previous action embedding
inp_t = torch.cat([vis_feat_t, weighted_lang_t, e_t], dim=1)
inp_t = self.input_dropout(inp_t)
# update hidden state
state_t = self.cell(inp_t, state_tm1)
state_t = [self.hstate_dropout(x) for x in state_t]
h_t = state_t[0]
# decode action and mask
# (B, dhid+ dhid+dframe+demb)
cont_t = torch.cat([h_t, inp_t], dim=1)
action_emb_t = self.actor(self.actor_dropout(cont_t))
action_t = action_emb_t.mm(self.emb.weight.t())
mask_t = self.mask_dec(cont_t)
return action_t, mask_t, state_t, lang_attn_t
def forward(self, enc, frames, gold=None, max_decode=150, state_0=None):
max_t = gold.size(1) if self.training else min(max_decode, frames.shape[1])
batch = enc.size(0)
e_t = self.go.repeat(batch, 1)
state_t = state_0
actions = []
masks = []
attn_scores = []
for t in range(max_t):
action_t, mask_t, state_t, attn_score_t = self.step(enc, frames[:, t], e_t, state_t)
masks.append(mask_t)
actions.append(action_t)
attn_scores.append(attn_score_t)
if self.teacher_forcing and self.training:
w_t = gold[:, t]
else:
w_t = action_t.max(1)[1]
e_t = self.emb(w_t)
results = {
'out_action_low': torch.stack(actions, dim=1),
'out_action_low_mask': torch.stack(masks, dim=1),
'out_attn_scores': torch.stack(attn_scores, dim=1),
'state_t': state_t
}
return results
class ConvFrameMaskDecoderProgressMonitor(nn.Module):
'''
action decoder with subgoal and progress monitoring
'''
def __init__(self, emb, dframe, dhid, pframe=300,
attn_dropout=0., hstate_dropout=0., actor_dropout=0., input_dropout=0.,
teacher_forcing=False):
super().__init__()
demb = emb.weight.size(1)
self.emb = emb
self.pframe = pframe
self.dhid = dhid
self.vis_encoder = ResnetVisualEncoder(dframe=dframe)
self.cell = nn.LSTMCell(dhid+dframe+demb, dhid)
self.attn = DotAttn()
self.input_dropout = nn.Dropout(input_dropout)
self.attn_dropout = nn.Dropout(attn_dropout)
self.hstate_dropout = nn.Dropout(hstate_dropout)
self.actor_dropout = nn.Dropout(actor_dropout)
self.go = nn.Parameter(torch.Tensor(demb))
self.actor = nn.Linear(dhid+dhid+dframe+demb, demb)
self.mask_dec = MaskDecoder(dhid=dhid+dhid+dframe+demb, pframe=self.pframe)
self.teacher_forcing = teacher_forcing
self.h_tm1_fc = nn.Linear(dhid, dhid)
self.subgoal = nn.Linear(dhid+dhid+dframe+demb, 1)
self.progress = nn.Linear(dhid+dhid+dframe+demb, 1)
nn.init.uniform_(self.go, -0.1, 0.1)
def step(self, enc, frame, e_t, state_tm1):
# previous decoder hidden state
h_tm1 = state_tm1[0]
# encode vision and lang feat
vis_feat_t = self.vis_encoder(frame)
lang_feat_t = enc # language is encoded once at the start
# attend over language
weighted_lang_t, lang_attn_t = self.attn(self.attn_dropout(lang_feat_t), self.h_tm1_fc(h_tm1))
# concat visual feats, weight lang, and previous action embedding
inp_t = torch.cat([vis_feat_t, weighted_lang_t, e_t], dim=1)
inp_t = self.input_dropout(inp_t)
# update hidden state
state_t = self.cell(inp_t, state_tm1)
state_t = [self.hstate_dropout(x) for x in state_t]
h_t, c_t = state_t[0], state_t[1]
# decode action and mask
cont_t = torch.cat([h_t, inp_t], dim=1)
action_emb_t = self.actor(self.actor_dropout(cont_t))
action_t = action_emb_t.mm(self.emb.weight.t())
mask_t = self.mask_dec(cont_t)
# predict subgoals completed and task progress
subgoal_t = torch.sigmoid(self.subgoal(cont_t))
progress_t = torch.sigmoid(self.progress(cont_t))
return action_t, mask_t, state_t, lang_attn_t, subgoal_t, progress_t
def forward(self, enc, frames, gold=None, max_decode=150, state_0=None):
max_t = gold.size(1) if self.training else min(max_decode, frames.shape[1])
batch = enc.size(0)
e_t = self.go.repeat(batch, 1)
state_t = state_0
actions = []
masks = []
attn_scores = []
subgoals = []
progresses = []
for t in range(max_t):
action_t, mask_t, state_t, attn_score_t, subgoal_t, progress_t = self.step(enc, frames[:, t], e_t, state_t)
masks.append(mask_t)
actions.append(action_t)
attn_scores.append(attn_score_t)
subgoals.append(subgoal_t)
progresses.append(progress_t)
# find next emb
if self.teacher_forcing and self.training:
w_t = gold[:, t]
else:
w_t = action_t.max(1)[1]
e_t = self.emb(w_t)
results = {
'out_action_low': torch.stack(actions, dim=1),
'out_action_low_mask': torch.stack(masks, dim=1),
'out_attn_scores': torch.stack(attn_scores, dim=1),
'out_subgoal': torch.stack(subgoals, dim=1),
'out_progress': torch.stack(progresses, dim=1),
'state_t': state_t
}
return results
class LanguageDecoder(nn.Module):
'''
Language (instr / goal/ both) decoder
'''
def __init__(self, emb, dhid, attn_dropout=0., hstate_dropout=0.,
word_dropout=0., input_dropout=0., train_teacher_forcing=False, train_student_forcing_prob=0.1,
obj_emb=None, aux_loss_over_object_states=False, object_repr=None, instance_fc=None):
super().__init__()
# args.demb
demb = emb.weight.size(1)
# embedding module for words
self.emb = emb
# embedding module for objects
self.obj_emb = obj_emb
# hidden layer size
# 2*args.dhids
self.dhid = dhid
# LSTM cell, unroll one time step per call
self.cell = nn.LSTMCell(dhid+demb, dhid)
# attn to encoder output
self.attn = DotAttn()
# dropout concat input to LSTM cell
self.input_dropout = nn.Dropout(input_dropout)
# dropout on encoder output, before attn is applied
self.attn_dropout = nn.Dropout(attn_dropout)
# dropout on hidden state passed between steps
self.hstate_dropout = nn.Dropout(hstate_dropout)
# dropout on word fc
self.word_dropout = nn.Dropout(word_dropout)
# a learned initial word embedding to speed up learning
self.go = nn.Parameter(torch.Tensor(demb))
# word fc per time step
# (1024 + 1024 + 100, 100)
self.word = nn.Linear(dhid+dhid+demb, demb)
self.train_teacher_forcing = train_teacher_forcing
self.train_student_forcing_prob = train_student_forcing_prob
self.h_tm1_fc = nn.Linear(dhid, dhid)
# Aux Loss
self.aux_loss_over_object_states = aux_loss_over_object_states
if self.aux_loss_over_object_states:
self.object_repr = object_repr
self.h_enc_fc = nn.Linear(1, 2)
self.instance_fc = instance_fc
nn.init.uniform_(self.go, -0.1, 0.1)
def step(self, enc, e_t, state_tm1):
'''
enc: (B, T, args.dhid). LSTM encoder per action output
e_t: (B, demb) learned <go> embedding.
'''
# previous decoder hidden state
# (B, 2*args.dhid) for bidirectional
h_tm1 = state_tm1[0]
# encode action feat
# (B, t, 2*args.dhid) for bidirectional
act_feat_t = enc # actions are encoded once at the start
# attend over actions
# inputs (B, t, 2*args.dhid), (B, 2*args.dhid)
# output (B, 2*args.dhid), (B, t, 1)
weighted_act_t, act_attn_t = self.attn(self.attn_dropout(act_feat_t), self.h_tm1_fc(h_tm1))
# concat weight act, and previous word embedding
# (B, 2*args.dhid + demb)
inp_t = torch.cat([weighted_act_t, e_t], dim=1)
inp_t = self.input_dropout(inp_t)
# update hidden state
# (B, 2*args.dhid, ), (B, 2*args.dhid, )
state_t = self.cell(inp_t, state_tm1)
state_t = [self.hstate_dropout(x) for x in state_t]
h_t, c_t = state_t[0], state_t[1]
# decode next word
# (B, 2*args.dhid + 2*args.dhid + demb)
cont_t = torch.cat([h_t, inp_t], dim=1)
# (B, demb)
word_emb_t = self.word(self.word_dropout(cont_t))
# (B, demb).mm(demb, vocab size) = (B, vocab size)
word_t = word_emb_t.mm(self.emb.weight.t())
return word_t, state_t, act_attn_t
def make_instance_embeddings(self, object_indices, receptacle_indices, object_distances):
'''
object_indices: (B, max_num_objects in batch)
receptacle_indices: (B, max_num_objects in batch)
object_distance: (B, max_num_objects in batch)
'''
# (B, max_num_objects in batch, obj demb)
obj_embeddings = self.obj_emb(object_indices)
# (B, max_num_objects in batch, obj demb)
recep_embeddings = self.obj_emb(receptacle_indices)
# (B, max_num_objects in batch, obj demb + obj demb + 1)
cat_embeddings = torch.cat([obj_embeddings, recep_embeddings, object_distances.unsqueeze(-1)], dim=len(obj_embeddings.shape) - 1)
# (B, max_num_objects in batch, dhid)
return self.instance_fc(cat_embeddings)
def forward(self, enc, feat_subgoal, max_decode=50, state_0=None, valid_object_indices=None,
validate_teacher_forcing=False, validate_sample_output=False, temperature=1.0):
'''
enc : (B, T, args.dhid). LSTM encoder per action output
gold: (B, T). padded_sequence of word index tokens.
max_decode: integer. maximum timesteps - length of language instruction.
state_0: tuple (cont_act, torch.zeros.like(cont_act)).
valid_object_indices: (B, max_num_objects of batch)
validate_teacher_forcing: boolean. Whether to use ground-truth to score loss and perplexity.
Student-forcing is used otherwise.
validate_sample_output: boolean. With student-forcing, whether to decode by sampling (1) or argmax (0).
'''
# Aux Loss---------------------------------------------------
# (B, 2*args.dhid)
h_enc_tm1 = state_0[0]
# Simple Aux Loss prediction using dot products
obj_visibilty_scores, obj_state_change_scores = None, None
if self.aux_loss_over_object_states:
# raise Exception
# Max pool hidden state
# (B, args.dhid)
h_enc_max_pooled = torch.max(h_enc_tm1.reshape(h_enc_tm1.shape[0], 2, -1), dim=1)[0]
assert h_enc_max_pooled.shape == (h_enc_tm1.shape[0], h_enc_tm1.shape[1]/2)
# Expand by linear layer
# (B, args.dhid, 1) -> (B, args.dhid, 2)
h_enc_extended = self.h_enc_fc(h_enc_max_pooled.unsqueeze(-1))
# (B, 2, args.dhid)
h_enc_extended = h_enc_extended.transpose(1, 2)
if self.object_repr == 'instance':
# Taken at beginning of subgoal with [:,0,:]
# (B, max_num_objects, args.dhid)
obj_m = self.make_instance_embeddings(
object_indices=feat_subgoal['object_token_id'][:, 0, :], # (B, max_num_objects)
receptacle_indices=feat_subgoal['receptacle_token_id'][:, 0, :], # (B, max_num_objects)
object_distances=feat_subgoal['object_distance'][:, 0, :]) # (B, max_num_objects)
# (B, args.dhid, max_num_objects)
obj_m = obj_m.transpose(1, 2)
else: # 'type'
# Taken at beginning of subgoal
# (B, max_num_objects)
object_indices = feat_subgoal['object_token_id'][:, 0, :]
# (B, args.dhid, max_num_objects)
obj_m = self.obj_emb(object_indices).transpose(1, 2)
# obj_m = self.obj_emb.weight.t().unsqueeze(0).repeat(h_enc_tm1.shape[0],1,1)
# (B, 2, args.dhid) bmm (B, args.dhid, max_num_objects) = (B, 2, max_num_objects)
aux_scores = h_enc_extended.bmm(obj_m)
# (B, max_num_objects), (B, max_num_objects)
obj_visibilty_scores, obj_state_change_scores = aux_scores[:,0,:], aux_scores[:,1,:]
# deal with valid object indices in compute_loss
# Language Model----------------------------------------------
if self.training or validate_teacher_forcing:
gold = feat_subgoal['lang_instr']
max_t = gold.size(1)
else:
max_t = max_decode
batch = enc.size(0)
# go is a learned embedding
e_t = self.go.repeat(batch, 1)
state_t = state_0
words = []
words_chosen_indices = []
probs = []
attn_scores = []
for t in range(max_t):
word_t, state_t, attn_score_t = self.step(enc, e_t, state_t)
words.append(word_t)
attn_scores.append(attn_score_t)
# next word choice
if self.training:
if self.train_teacher_forcing:
# 1. teacher forcing
w_t = gold[:, t]
else:
# 2. teaching forcing but occasionally swap in student
use_student = np.random.binomial(1, self.train_student_forcing_prob)
if use_student:
w_t = word_t.max(1)[1]
else:
w_t = gold[:, t]
else:
if validate_teacher_forcing:
# 3. eval with teacher forcing to compare perplexity across models
w_t = gold[:, t]
else:
if validate_sample_output:
# 4. student forcing, with temperature
# shape (B, 1)
w_t = torch.multinomial(F.softmax(word_t/temperature), 1).squeeze(-1)
else:
# 5. student focing, with argmax
# argmax
w_t = word_t.max(1)[1]
# prob for chosen word
# shape (B,)
prob_t = F.softmax(word_t, dim=1).gather(1, w_t.view(-1, 1)).squeeze(-1)
# record chosen word index
words_chosen_indices.append(w_t)
# record prob for word index
probs.append(prob_t)
# word embedding for next step
e_t = self.emb(w_t)
results = {
# shape (B, T , Vocab size)
'out_lang_instr': torch.stack(words, dim=1),
# shape (B, T)
'out_lang_instr_idxs': torch.stack(words_chosen_indices, dim=1),
# shape (B, T)
'out_lang_probs': torch.stack(probs, dim=1),
'out_attn_scores': torch.stack(attn_scores, dim=1),
'state_t': state_t,
'out_obj_vis_score': obj_visibilty_scores,
'out_state_change_score': obj_state_change_scores,
'valid_object_indices': valid_object_indices
}
return results, state_t | [
"torch.nn.Dropout",
"torch.nn.init.uniform_",
"torch.nn.LSTMCell",
"torch.cat",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.Tensor",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LSTM",
"numpy.random.binomial",
"torch.zeros_like",
"torch.nn.Conv2... | [((406, 424), 'torch.nn.Linear', 'nn.Linear', (['dhid', '(1)'], {}), '(dhid, 1)\n', (415, 424), False, 'from torch import nn\n'), ((1495, 1522), 'torch.nn.functional.softmax', 'F.softmax', (['raw_score'], {'dim': '(1)'}), '(raw_score, dim=1)\n', (1504, 1522), True, 'from torch.nn import functional as F\n'), ((2231, 2255), 'torch.sigmoid', 'torch.sigmoid', (['raw_score'], {}), '(raw_score)\n', (2244, 2255), False, 'import torch\n'), ((2525, 2580), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', '(256)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(512, 256, kernel_size=1, stride=1, padding=0)\n', (2534, 2580), False, 'from torch import nn\n'), ((2602, 2656), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(64)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(256, 64, kernel_size=1, stride=1, padding=0)\n', (2611, 2656), False, 'from torch import nn\n'), ((2675, 2718), 'torch.nn.Linear', 'nn.Linear', (['self.flattened_size', 'self.dframe'], {}), '(self.flattened_size, self.dframe)\n', (2684, 2718), False, 'from torch import nn\n'), ((2738, 2757), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(256)'], {}), '(256)\n', (2752, 2757), False, 'from torch import nn\n'), ((2777, 2795), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(64)'], {}), '(64)\n', (2791, 2795), False, 'from torch import nn\n'), ((3553, 3576), 'torch.nn.Dropout', 'nn.Dropout', (['vis_dropout'], {}), '(vis_dropout)\n', (3563, 3576), False, 'from torch import nn\n'), ((3604, 3641), 'torch.nn.Dropout', 'nn.Dropout', (['act_dropout'], {'inplace': '(True)'}), '(act_dropout, inplace=True)\n', (3614, 3641), False, 'from torch import nn\n'), ((4698, 4798), 'torch.nn.LSTM', 'nn.LSTM', (['(self.demb + self.dframe)', 'self.dhid'], {'bidirectional': 'self.bidirectional', 'batch_first': '(True)'}), '(self.demb + self.dframe, self.dhid, bidirectional=self.\n bidirectional, batch_first=True)\n', (4705, 4798), False, 'from torch import nn\n'), ((5536, 5573), 'torch.cat', 'torch.cat', (['[emb_act, vis_feat]'], {'dim': '(2)'}), '([emb_act, vis_feat], dim=2)\n', (5545, 5573), False, 'import torch\n'), ((5597, 5684), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['inp_seq', 'seq_lengths'], {'batch_first': '(True)', 'enforce_sorted': '(False)'}), '(inp_seq, seq_lengths, batch_first=True, enforce_sorted\n =False)\n', (5617, 5684), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((5871, 5917), 'torch.nn.utils.rnn.pad_packed_sequence', 'pad_packed_sequence', (['enc_act'], {'batch_first': '(True)'}), '(enc_act, batch_first=True)\n', (5890, 5917), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((6872, 6972), 'torch.nn.LSTM', 'nn.LSTM', (['(self.demb + self.dframe)', 'self.dhid'], {'bidirectional': 'self.bidirectional', 'batch_first': '(True)'}), '(self.demb + self.dframe, self.dhid, bidirectional=self.\n bidirectional, batch_first=True)\n', (6879, 6972), False, 'from torch import nn\n'), ((7094, 7119), 'torch.nn.Dropout', 'nn.Dropout', (['input_dropout'], {}), '(input_dropout)\n', (7104, 7119), False, 'from torch import nn\n'), ((7150, 7176), 'torch.nn.Dropout', 'nn.Dropout', (['hstate_dropout'], {}), '(hstate_dropout)\n', (7160, 7176), False, 'from torch import nn\n'), ((7205, 7229), 'torch.nn.Dropout', 'nn.Dropout', (['attn_dropout'], {}), '(attn_dropout)\n', (7215, 7229), False, 'from torch import nn\n'), ((9218, 9255), 'torch.cat', 'torch.cat', (['[emb_act, vis_feat]'], {'dim': '(2)'}), '([emb_act, vis_feat], dim=2)\n', (9227, 9255), False, 'import torch\n'), ((9279, 9366), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['inp_seq', 'seq_lengths'], {'batch_first': '(True)', 'enforce_sorted': '(False)'}), '(inp_seq, seq_lengths, batch_first=True, enforce_sorted\n =False)\n', (9299, 9366), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((9598, 9644), 'torch.nn.utils.rnn.pad_packed_sequence', 'pad_packed_sequence', (['enc_act'], {'batch_first': '(True)'}), '(enc_act, batch_first=True)\n', (9617, 9644), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((10913, 10934), 'torch.nn.Linear', 'nn.Linear', (['dhid', 'dhid'], {}), '(dhid, dhid)\n', (10922, 10934), False, 'from torch import nn\n'), ((11078, 11149), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(self.demb + self.dframe + self.dhid + self.dhid)', 'self.dhid'], {}), '(self.demb + self.dframe + self.dhid + self.dhid, self.dhid)\n', (11089, 11149), False, 'from torch import nn\n'), ((12754, 12839), 'torch.cat', 'torch.cat', (['[emb_act_t, vis_feat_t, weighted_obj_vis_t, weighted_obj_stc_t]'], {'dim': '(1)'}), '([emb_act_t, vis_feat_t, weighted_obj_vis_t, weighted_obj_stc_t],\n dim=1)\n', (12763, 12839), False, 'import torch\n'), ((14115, 14208), 'torch.zeros', 'torch.zeros', (['emb_act.shape[0]', 'max_t', 'self.dhid'], {'device': 'emb_act.device', 'dtype': 'torch.float'}), '(emb_act.shape[0], max_t, self.dhid, device=emb_act.device,\n dtype=torch.float)\n', (14126, 14208), False, 'import torch\n'), ((20159, 20282), 'torch.nn.LSTM', 'nn.LSTM', (['(self.demb + self.dframe + self.dhid + self.dhid)', 'self.dhid'], {'bidirectional': 'self.bidirectional', 'batch_first': '(True)'}), '(self.demb + self.dframe + self.dhid + self.dhid, self.dhid,\n bidirectional=self.bidirectional, batch_first=True)\n', (20166, 20282), False, 'from torch import nn\n'), ((23141, 23209), 'torch.cat', 'torch.cat', (['[emb_act, vis_feat, obj_visible, obj_state_change]'], {'dim': '(2)'}), '([emb_act, vis_feat, obj_visible, obj_state_change], dim=2)\n', (23150, 23209), False, 'import torch\n'), ((23233, 23320), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['inp_seq', 'seq_lengths'], {'batch_first': '(True)', 'enforce_sorted': '(False)'}), '(inp_seq, seq_lengths, batch_first=True, enforce_sorted\n =False)\n', (23253, 23320), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((23552, 23598), 'torch.nn.utils.rnn.pad_packed_sequence', 'pad_packed_sequence', (['enc_act'], {'batch_first': '(True)'}), '(enc_act, batch_first=True)\n', (23571, 23598), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((24136, 24191), 'torch.nn.Linear', 'nn.Linear', (['self.dhid', '(hshape[0] * hshape[1] * hshape[2])'], {}), '(self.dhid, hshape[0] * hshape[1] * hshape[2])\n', (24145, 24191), False, 'from torch import nn\n'), ((24212, 24250), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (24234, 24250), False, 'from torch import nn\n'), ((24270, 24288), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(32)'], {}), '(32)\n', (24284, 24288), False, 'from torch import nn\n'), ((24308, 24326), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(16)'], {}), '(16)\n', (24322, 24326), False, 'from torch import nn\n'), ((24349, 24411), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(64)', '(32)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(64, 32, kernel_size=4, stride=2, padding=1)\n', (24367, 24411), False, 'from torch import nn\n'), ((24434, 24496), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(32)', '(16)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(32, 16, kernel_size=4, stride=2, padding=1)\n', (24452, 24496), False, 'from torch import nn\n'), ((24519, 24580), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(16)', '(1)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(16, 1, kernel_size=4, stride=2, padding=1)\n', (24537, 24580), False, 'from torch import nn\n'), ((24894, 24960), 'torch.nn.functional.interpolate', 'F.interpolate', (['x'], {'size': '(self.pframe, self.pframe)', 'mode': '"""bilinear"""'}), "(x, size=(self.pframe, self.pframe), mode='bilinear')\n", (24907, 24960), True, 'from torch.nn import functional as F\n'), ((25461, 25500), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(dhid + dframe + demb)', 'dhid'], {}), '(dhid + dframe + demb, dhid)\n', (25472, 25500), False, 'from torch import nn\n'), ((25556, 25581), 'torch.nn.Dropout', 'nn.Dropout', (['input_dropout'], {}), '(input_dropout)\n', (25566, 25581), False, 'from torch import nn\n'), ((25610, 25634), 'torch.nn.Dropout', 'nn.Dropout', (['attn_dropout'], {}), '(attn_dropout)\n', (25620, 25634), False, 'from torch import nn\n'), ((25665, 25691), 'torch.nn.Dropout', 'nn.Dropout', (['hstate_dropout'], {}), '(hstate_dropout)\n', (25675, 25691), False, 'from torch import nn\n'), ((25721, 25746), 'torch.nn.Dropout', 'nn.Dropout', (['actor_dropout'], {}), '(actor_dropout)\n', (25731, 25746), False, 'from torch import nn\n'), ((25885, 25929), 'torch.nn.Linear', 'nn.Linear', (['(dhid + dhid + dframe + demb)', 'demb'], {}), '(dhid + dhid + dframe + demb, demb)\n', (25894, 25929), False, 'from torch import nn\n'), ((26079, 26100), 'torch.nn.Linear', 'nn.Linear', (['dhid', 'dhid'], {}), '(dhid, dhid)\n', (26088, 26100), False, 'from torch import nn\n'), ((26110, 26146), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.go', '(-0.1)', '(0.1)'], {}), '(self.go, -0.1, 0.1)\n', (26126, 26146), False, 'from torch import nn\n'), ((26641, 26693), 'torch.cat', 'torch.cat', (['[vis_feat_t, weighted_lang_t, e_t]'], {'dim': '(1)'}), '([vis_feat_t, weighted_lang_t, e_t], dim=1)\n', (26650, 26693), False, 'import torch\n'), ((26987, 27017), 'torch.cat', 'torch.cat', (['[h_t, inp_t]'], {'dim': '(1)'}), '([h_t, inp_t], dim=1)\n', (26996, 27017), False, 'import torch\n'), ((28777, 28816), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(dhid + dframe + demb)', 'dhid'], {}), '(dhid + dframe + demb, dhid)\n', (28788, 28816), False, 'from torch import nn\n'), ((28872, 28897), 'torch.nn.Dropout', 'nn.Dropout', (['input_dropout'], {}), '(input_dropout)\n', (28882, 28897), False, 'from torch import nn\n'), ((28926, 28950), 'torch.nn.Dropout', 'nn.Dropout', (['attn_dropout'], {}), '(attn_dropout)\n', (28936, 28950), False, 'from torch import nn\n'), ((28981, 29007), 'torch.nn.Dropout', 'nn.Dropout', (['hstate_dropout'], {}), '(hstate_dropout)\n', (28991, 29007), False, 'from torch import nn\n'), ((29037, 29062), 'torch.nn.Dropout', 'nn.Dropout', (['actor_dropout'], {}), '(actor_dropout)\n', (29047, 29062), False, 'from torch import nn\n'), ((29135, 29179), 'torch.nn.Linear', 'nn.Linear', (['(dhid + dhid + dframe + demb)', 'demb'], {}), '(dhid + dhid + dframe + demb, demb)\n', (29144, 29179), False, 'from torch import nn\n'), ((29329, 29350), 'torch.nn.Linear', 'nn.Linear', (['dhid', 'dhid'], {}), '(dhid, dhid)\n', (29338, 29350), False, 'from torch import nn\n'), ((29375, 29416), 'torch.nn.Linear', 'nn.Linear', (['(dhid + dhid + dframe + demb)', '(1)'], {}), '(dhid + dhid + dframe + demb, 1)\n', (29384, 29416), False, 'from torch import nn\n'), ((29435, 29476), 'torch.nn.Linear', 'nn.Linear', (['(dhid + dhid + dframe + demb)', '(1)'], {}), '(dhid + dhid + dframe + demb, 1)\n', (29444, 29476), False, 'from torch import nn\n'), ((29480, 29516), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.go', '(-0.1)', '(0.1)'], {}), '(self.go, -0.1, 0.1)\n', (29496, 29516), False, 'from torch import nn\n'), ((30011, 30063), 'torch.cat', 'torch.cat', (['[vis_feat_t, weighted_lang_t, e_t]'], {'dim': '(1)'}), '([vis_feat_t, weighted_lang_t, e_t], dim=1)\n', (30020, 30063), False, 'import torch\n'), ((30336, 30366), 'torch.cat', 'torch.cat', (['[h_t, inp_t]'], {'dim': '(1)'}), '([h_t, inp_t], dim=1)\n', (30345, 30366), False, 'import torch\n'), ((32831, 32861), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(dhid + demb)', 'dhid'], {}), '(dhid + demb, dhid)\n', (32842, 32861), False, 'from torch import nn\n'), ((32996, 33021), 'torch.nn.Dropout', 'nn.Dropout', (['input_dropout'], {}), '(input_dropout)\n', (33006, 33021), False, 'from torch import nn\n'), ((33110, 33134), 'torch.nn.Dropout', 'nn.Dropout', (['attn_dropout'], {}), '(attn_dropout)\n', (33120, 33134), False, 'from torch import nn\n'), ((33220, 33246), 'torch.nn.Dropout', 'nn.Dropout', (['hstate_dropout'], {}), '(hstate_dropout)\n', (33230, 33246), False, 'from torch import nn\n'), ((33304, 33328), 'torch.nn.Dropout', 'nn.Dropout', (['word_dropout'], {}), '(word_dropout)\n', (33314, 33328), False, 'from torch import nn\n'), ((33531, 33566), 'torch.nn.Linear', 'nn.Linear', (['(dhid + dhid + demb)', 'demb'], {}), '(dhid + dhid + demb, demb)\n', (33540, 33566), False, 'from torch import nn\n'), ((33715, 33736), 'torch.nn.Linear', 'nn.Linear', (['dhid', 'dhid'], {}), '(dhid, dhid)\n', (33724, 33736), False, 'from torch import nn\n'), ((34012, 34048), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.go', '(-0.1)', '(0.1)'], {}), '(self.go, -0.1, 0.1)\n', (34028, 34048), False, 'from torch import nn\n'), ((34822, 34861), 'torch.cat', 'torch.cat', (['[weighted_act_t, e_t]'], {'dim': '(1)'}), '([weighted_act_t, e_t], dim=1)\n', (34831, 34861), False, 'import torch\n'), ((35225, 35255), 'torch.cat', 'torch.cat', (['[h_t, inp_t]'], {'dim': '(1)'}), '([h_t, inp_t], dim=1)\n', (35234, 35255), False, 'import torch\n'), ((11203, 11274), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(self.demb + self.dframe + self.dhid + self.dhid)', 'self.dhid'], {}), '(self.demb + self.dframe + self.dhid + self.dhid, self.dhid)\n', (11214, 11274), False, 'from torch import nn\n'), ((16236, 16289), 'torch.cat', 'torch.cat', (['[enc_act_forward, enc_act_backward]'], {'dim': '(2)'}), '([enc_act_forward, enc_act_backward], dim=2)\n', (16245, 16289), False, 'import torch\n'), ((18579, 18707), 'torch.zeros', 'torch.zeros', (['emb_act.shape[0]', '(2 * self.dhid if self.bidirectional else self.dhid)'], {'dtype': 'torch.float', 'device': 'pad_seq.device'}), '(emb_act.shape[0], 2 * self.dhid if self.bidirectional else self\n .dhid, dtype=torch.float, device=pad_seq.device)\n', (18590, 18707), False, 'import torch\n'), ((18719, 18740), 'torch.zeros_like', 'torch.zeros_like', (['h_0'], {}), '(h_0)\n', (18735, 18740), False, 'import torch\n'), ((25844, 25862), 'torch.Tensor', 'torch.Tensor', (['demb'], {}), '(demb)\n', (25856, 25862), False, 'import torch\n'), ((28024, 28051), 'torch.stack', 'torch.stack', (['actions'], {'dim': '(1)'}), '(actions, dim=1)\n', (28035, 28051), False, 'import torch\n'), ((28088, 28113), 'torch.stack', 'torch.stack', (['masks'], {'dim': '(1)'}), '(masks, dim=1)\n', (28099, 28113), False, 'import torch\n'), ((28146, 28177), 'torch.stack', 'torch.stack', (['attn_scores'], {'dim': '(1)'}), '(attn_scores, dim=1)\n', (28157, 28177), False, 'import torch\n'), ((29094, 29112), 'torch.Tensor', 'torch.Tensor', (['demb'], {}), '(demb)\n', (29106, 29112), False, 'import torch\n'), ((31745, 31772), 'torch.stack', 'torch.stack', (['actions'], {'dim': '(1)'}), '(actions, dim=1)\n', (31756, 31772), False, 'import torch\n'), ((31809, 31834), 'torch.stack', 'torch.stack', (['masks'], {'dim': '(1)'}), '(masks, dim=1)\n', (31820, 31834), False, 'import torch\n'), ((31867, 31898), 'torch.stack', 'torch.stack', (['attn_scores'], {'dim': '(1)'}), '(attn_scores, dim=1)\n', (31878, 31898), False, 'import torch\n'), ((31927, 31955), 'torch.stack', 'torch.stack', (['subgoals'], {'dim': '(1)'}), '(subgoals, dim=1)\n', (31938, 31955), False, 'import torch\n'), ((31985, 32015), 'torch.stack', 'torch.stack', (['progresses'], {'dim': '(1)'}), '(progresses, dim=1)\n', (31996, 32015), False, 'import torch\n'), ((33424, 33442), 'torch.Tensor', 'torch.Tensor', (['demb'], {}), '(demb)\n', (33436, 33442), False, 'import torch\n'), ((33944, 33959), 'torch.nn.Linear', 'nn.Linear', (['(1)', '(2)'], {}), '(1, 2)\n', (33953, 33959), False, 'from torch import nn\n'), ((41704, 41729), 'torch.stack', 'torch.stack', (['words'], {'dim': '(1)'}), '(words, dim=1)\n', (41715, 41729), False, 'import torch\n'), ((41794, 41834), 'torch.stack', 'torch.stack', (['words_chosen_indices'], {'dim': '(1)'}), '(words_chosen_indices, dim=1)\n', (41805, 41834), False, 'import torch\n'), ((41893, 41918), 'torch.stack', 'torch.stack', (['probs'], {'dim': '(1)'}), '(probs, dim=1)\n', (41904, 41918), False, 'import torch\n'), ((41951, 41982), 'torch.stack', 'torch.stack', (['attn_scores'], {'dim': '(1)'}), '(attn_scores, dim=1)\n', (41962, 41982), False, 'import torch\n'), ((16393, 16480), 'torch.cat', 'torch.cat', (['[curr_subgoal_states_forward[0], curr_subgoal_states_backward[0]]'], {'dim': '(1)'}), '([curr_subgoal_states_forward[0], curr_subgoal_states_backward[0]],\n dim=1)\n', (16402, 16480), False, 'import torch\n'), ((16495, 16582), 'torch.cat', 'torch.cat', (['[curr_subgoal_states_forward[1], curr_subgoal_states_backward[1]]'], {'dim': '(1)'}), '([curr_subgoal_states_forward[1], curr_subgoal_states_backward[1]],\n dim=1)\n', (16504, 16582), False, 'import torch\n'), ((40411, 40465), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'self.train_student_forcing_prob'], {}), '(1, self.train_student_forcing_prob)\n', (40429, 40465), True, 'import numpy as np\n'), ((41314, 41338), 'torch.nn.functional.softmax', 'F.softmax', (['word_t'], {'dim': '(1)'}), '(word_t, dim=1)\n', (41323, 41338), True, 'from torch.nn import functional as F\n'), ((41022, 41053), 'torch.nn.functional.softmax', 'F.softmax', (['(word_t / temperature)'], {}), '(word_t / temperature)\n', (41031, 41053), True, 'from torch.nn import functional as F\n')] |
import torch
import torch.nn as nn
import numpy as np
import math
from scipy.linalg import block_diag
import pdb
class SparseAttentionStrided(nn.Module):
def __init__(self):
super().__init__()
def forward(self, qk):
batch_size, n_heads, seq_len, dim, device = *qk.shape, qk.device
l = math.floor(seq_len ** 0.5)
local_mask = torch.ones(seq_len, seq_len, device=device)
local_mask = torch.triu(local_mask, -l).permute(1, 0)
local_mask = torch.triu(local_mask, -l)
local_mask = torch.where(local_mask==1, torch.tensor(0., device=device), torch.tensor(-10000., device=device))
local_mask = torch.unsqueeze(torch.unsqueeze(local_mask, 0), 0).expand(batch_size, int(n_heads/2), -1, -1)
x = torch.arange(seq_len, device=device).unsqueeze(-1)
y = x.permute(1, 0)
z = torch.zeros(seq_len, seq_len, device=device)
q = z + x
k = z + y
c1 = q >= k
c2 = (torch.fmod(q-k, l) == 0)
# global_mask = (c1 * c2).to(torch.float32)
global_mask = c2.to(torch.float32)
global_mask = torch.where(global_mask==1, torch.tensor(0., device=device), torch.tensor(-10000., device=device))
global_mask = torch.unsqueeze(torch.unsqueeze(global_mask, 0), 0).expand(batch_size, int(n_heads/2), -1, -1)
result = torch.cat((local_mask, global_mask), 1)
return result.detach()
class SparseAttentionFixed(nn.Module):
def __init__(self):
super().__init__()
def forward(self, qk):
batch_size, n_heads, seq_len, dim, device = *qk.shape, qk.device
l = math.floor(seq_len ** 0.5)
num_of_block = math.ceil(seq_len / l)
small_block = np.ones([l, l])
_tmp = [small_block for _ in range(num_of_block)]
local_mask = block_diag(*_tmp)
local_mask = local_mask[:seq_len, :seq_len] * 10000. - 10000.
local_mask = torch.tensor(local_mask, device=device, dtype=torch.float32)
local_mask = local_mask.unsqueeze(0).unsqueeze(0).expand(batch_size, int(n_heads/2), -1, -1)
global_mask = torch.zeros(seq_len, seq_len, device=device)
global_mask[:, l-1::l] = 1.
global_mask = global_mask * 10000. -10000.
global_mask = global_mask.unsqueeze(0).unsqueeze(0).expand(batch_size, int(n_heads/2), -1, -1)
result = torch.cat((local_mask, global_mask), 1)
return result.detach()
| [
"torch.ones",
"math.ceil",
"scipy.linalg.block_diag",
"torch.fmod",
"torch.unsqueeze",
"math.floor",
"torch.cat",
"numpy.ones",
"torch.arange",
"torch.triu",
"torch.zeros",
"torch.tensor"
] | [((324, 350), 'math.floor', 'math.floor', (['(seq_len ** 0.5)'], {}), '(seq_len ** 0.5)\n', (334, 350), False, 'import math\n'), ((372, 415), 'torch.ones', 'torch.ones', (['seq_len', 'seq_len'], {'device': 'device'}), '(seq_len, seq_len, device=device)\n', (382, 415), False, 'import torch\n'), ((499, 525), 'torch.triu', 'torch.triu', (['local_mask', '(-l)'], {}), '(local_mask, -l)\n', (509, 525), False, 'import torch\n'), ((873, 917), 'torch.zeros', 'torch.zeros', (['seq_len', 'seq_len'], {'device': 'device'}), '(seq_len, seq_len, device=device)\n', (884, 917), False, 'import torch\n'), ((1364, 1403), 'torch.cat', 'torch.cat', (['(local_mask, global_mask)', '(1)'], {}), '((local_mask, global_mask), 1)\n', (1373, 1403), False, 'import torch\n'), ((1654, 1680), 'math.floor', 'math.floor', (['(seq_len ** 0.5)'], {}), '(seq_len ** 0.5)\n', (1664, 1680), False, 'import math\n'), ((1704, 1726), 'math.ceil', 'math.ceil', (['(seq_len / l)'], {}), '(seq_len / l)\n', (1713, 1726), False, 'import math\n'), ((1750, 1765), 'numpy.ones', 'np.ones', (['[l, l]'], {}), '([l, l])\n', (1757, 1765), True, 'import numpy as np\n'), ((1845, 1862), 'scipy.linalg.block_diag', 'block_diag', (['*_tmp'], {}), '(*_tmp)\n', (1855, 1862), False, 'from scipy.linalg import block_diag\n'), ((1963, 2023), 'torch.tensor', 'torch.tensor', (['local_mask'], {'device': 'device', 'dtype': 'torch.float32'}), '(local_mask, device=device, dtype=torch.float32)\n', (1975, 2023), False, 'import torch\n'), ((2148, 2192), 'torch.zeros', 'torch.zeros', (['seq_len', 'seq_len'], {'device': 'device'}), '(seq_len, seq_len, device=device)\n', (2159, 2192), False, 'import torch\n'), ((2409, 2448), 'torch.cat', 'torch.cat', (['(local_mask, global_mask)', '(1)'], {}), '((local_mask, global_mask), 1)\n', (2418, 2448), False, 'import torch\n'), ((574, 606), 'torch.tensor', 'torch.tensor', (['(0.0)'], {'device': 'device'}), '(0.0, device=device)\n', (586, 606), False, 'import torch\n'), ((607, 644), 'torch.tensor', 'torch.tensor', (['(-10000.0)'], {'device': 'device'}), '(-10000.0, device=device)\n', (619, 644), False, 'import torch\n'), ((988, 1008), 'torch.fmod', 'torch.fmod', (['(q - k)', 'l'], {}), '(q - k, l)\n', (998, 1008), False, 'import torch\n'), ((1158, 1190), 'torch.tensor', 'torch.tensor', (['(0.0)'], {'device': 'device'}), '(0.0, device=device)\n', (1170, 1190), False, 'import torch\n'), ((1191, 1228), 'torch.tensor', 'torch.tensor', (['(-10000.0)'], {'device': 'device'}), '(-10000.0, device=device)\n', (1203, 1228), False, 'import torch\n'), ((437, 463), 'torch.triu', 'torch.triu', (['local_mask', '(-l)'], {}), '(local_mask, -l)\n', (447, 463), False, 'import torch\n'), ((782, 818), 'torch.arange', 'torch.arange', (['seq_len'], {'device': 'device'}), '(seq_len, device=device)\n', (794, 818), False, 'import torch\n'), ((682, 712), 'torch.unsqueeze', 'torch.unsqueeze', (['local_mask', '(0)'], {}), '(local_mask, 0)\n', (697, 712), False, 'import torch\n'), ((1267, 1298), 'torch.unsqueeze', 'torch.unsqueeze', (['global_mask', '(0)'], {}), '(global_mask, 0)\n', (1282, 1298), False, 'import torch\n')] |
# This code can be used for ploting shape functions of linear element in 1D.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 11)
def basisf(x,i):
n = len(x) - 1
phi = np.zeros((n+1,1))
if i == 0:
phi[0] = 1
elif i == n:
phi[n] = 1
else:
for j in range(n):
if i-1 < j <= i:
phi[j] = (x[j] - x[i-1])/(x[i] - x[i-1])
elif i < j < i+1:
phi[j] = (x[j] - x[i])/(x[i+1] - x[i])
else:
phi[j] = 0
return phi
for i in range(len(x)):
plt.plot(x,basisf(x,i))
plt.xlabel('x')
plt.ylabel('$\phi_i (x)$')
plt.title('Linear shape functions in 1D')
plt.grid()
plt.show()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] | [((135, 157), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(11)'], {}), '(0, 10, 11)\n', (146, 157), True, 'import numpy as np\n'), ((633, 648), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (643, 648), True, 'import matplotlib.pyplot as plt\n'), ((649, 676), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\phi_i (x)$"""'], {}), "('$\\\\phi_i (x)$')\n", (659, 676), True, 'import matplotlib.pyplot as plt\n'), ((676, 717), 'matplotlib.pyplot.title', 'plt.title', (['"""Linear shape functions in 1D"""'], {}), "('Linear shape functions in 1D')\n", (685, 717), True, 'import matplotlib.pyplot as plt\n'), ((718, 728), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (726, 728), True, 'import matplotlib.pyplot as plt\n'), ((729, 739), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (737, 739), True, 'import matplotlib.pyplot as plt\n'), ((210, 230), 'numpy.zeros', 'np.zeros', (['(n + 1, 1)'], {}), '((n + 1, 1))\n', (218, 230), True, 'import numpy as np\n')] |
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from itertools import product
from ml_novel_nonexp_nce import *
from amazon_utils import *
from multiprocessing import Pool
## Load pre-trained models for the amazon data and perform product
## recommendation
import constants
try:
import cPickle as pickle
except ImportError:
import pickle
DATA_PATH = constants.DATA_PATH
MODEL_PATH = os.path.join(DATA_PATH, 'models')
RANKING_PATH = os.path.join(DATA_PATH, 'ranking_test')
N_CPUS = 4
n_folds = 10
folds_range = range(1, n_folds + 1)
n_propose = 1
f_model = None
datasets = ['path_set']
dim_range = [2, 10]
def get_proposal(Sorig, sample='topN'):
"""
Get the proposal for an additional item from f, given S
"""
f = f_model # use global model
# print("SANITY... MODEL TYPE: ", f.tpe)
if isinstance(f, ModularFun):
assert False # This should happen somewhere else
assert n_propose == 1 # modified to work for this case only
V = f.V
N = len(V)
S = Sorig[:]
Vred = np.array(list(set(V).difference(set(S))))
f_S = f(S)
probs = []
gains = []
vals = f.all_singleton_adds(S)
vals = np.delete(vals, S)
gains = vals - f_S
# for i in Vred:
# f_Si = f(list(set(S).union(set([i]))))
# probs.append(f_Si)
# gains.append(f_Si - f_S)
probs = np.exp(vals - lse(vals))
order = Vred[np.argsort(probs)[::-1]]
probs = np.sort(probs)[::-1]
return {'order': order, 'probs': probs}
def save_to_csv(filename, lst):
with open(filename, "wt") as f:
for sample in lst:
for i, k in enumerate(sample):
f.write("%d" % k)
if i < len(sample) - 1:
f.write(",")
f.write("\n")
if __name__ == '__main__':
for dataset, fold in product(datasets, folds_range):
np.random.seed(20150820)
print('-' * 30)
print('dataset: %s (fold %d)' % (dataset, fold))
result_ranking_partial_f = os.path.join(RANKING_PATH, '{}_partial_fold_{}.pkl'.format(dataset, fold))
# load all models
f_models = dict()
for dim in dim_range:
result_submod_f = os.path.join(MODEL_PATH, '{}_submod_d_{}_fold_{}.pkl'.format(dataset, dim, fold))
results_model = pickle.load(open(result_submod_f, 'rb'))
f_tmp_model = results_model['model']
f_models[dim] = f_tmp_model
result_ranking_gt_f = os.path.join(RANKING_PATH, '{}_gt_fold_{}.pkl'.format(dataset, fold))
result_ranking_partial_f = os.path.join(RANKING_PATH, '{}_partial_fold_{}.pkl'.format(dataset, fold))
data_ranking = load_amazon_ranking_data(result_ranking_partial_f)
print("Performing ranking.")
list_prop_model = dict()
for dim in dim_range:
list_prop_model[dim] = []
V = f_tmp_model.V
for dim in dim_range:
print("... dim=%d" % dim)
f_model = f_models[dim]
pool = Pool(N_CPUS)
prop_model_dicts = pool.map(get_proposal, data_ranking) # get_proposal(f_models[dim], s_partial[:], n_propose=n_propose)
pool.close()
pool.join()
# extract proposals from list of dictionaries
prop_model = []
for d in prop_model_dicts:
prop_model.append(d['order'])
# bookkeeping
list_prop_model[dim] = prop_model
# for i, s_partial in enumerate(data_ranking):
# if i % 100 == 0:
# print("%d/%d ..." % (i, len(data_ranking)))
# for dim in dim_range:
# prop_model = get_proposal(f_models[dim], s_partial[:], n_propose=n_propose)
# list_prop_model[dim].append(prop_model)
for dim in dim_range:
result_ranking_submod_f = os.path.join(RANKING_PATH, '{}_submod_d_{}_fold_{}.pkl'.format(dataset, dim, fold))
save_to_csv(result_ranking_submod_f, list_prop_model[dim])
| [
"numpy.random.seed",
"numpy.argsort",
"numpy.sort",
"multiprocessing.Pool",
"itertools.product",
"os.path.join",
"numpy.delete"
] | [((447, 480), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""models"""'], {}), "(DATA_PATH, 'models')\n", (459, 480), False, 'import os\n'), ((496, 535), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""ranking_test"""'], {}), "(DATA_PATH, 'ranking_test')\n", (508, 535), False, 'import os\n'), ((1219, 1237), 'numpy.delete', 'np.delete', (['vals', 'S'], {}), '(vals, S)\n', (1228, 1237), True, 'import numpy as np\n'), ((1879, 1909), 'itertools.product', 'product', (['datasets', 'folds_range'], {}), '(datasets, folds_range)\n', (1886, 1909), False, 'from itertools import product\n'), ((1487, 1501), 'numpy.sort', 'np.sort', (['probs'], {}), '(probs)\n', (1494, 1501), True, 'import numpy as np\n'), ((1919, 1943), 'numpy.random.seed', 'np.random.seed', (['(20150820)'], {}), '(20150820)\n', (1933, 1943), True, 'import numpy as np\n'), ((1450, 1467), 'numpy.argsort', 'np.argsort', (['probs'], {}), '(probs)\n', (1460, 1467), True, 'import numpy as np\n'), ((3066, 3078), 'multiprocessing.Pool', 'Pool', (['N_CPUS'], {}), '(N_CPUS)\n', (3070, 3078), False, 'from multiprocessing import Pool\n')] |
import numpy as np
from scipy import pi
import matplotlib.pyplot as plt
import cPickle
#Sine wave
N = 128
def get_sine_wave():
x_sin = np.array([0.0 for i in range(N)])
# print(x_sin)
for i in range(N):
# print("h")
x_sin[i] = np.sin(2.0*pi*i/16.0)
plt.plot(x_sin)
plt.title('Sine wave')
plt.show()
# y_sin = np.fft.fft(x_sin, N)
# plt.plot(abs(y_sin))
# plt.title('FFT sine wave')
# plt.show()
return x_sin
def get_bpsk_carrier():
x = np.fromfile('gnuradio_dumps/bpsk_carrier', dtype = 'float32')
x_bpsk_carrier = x[9000:9000+N]
plt.plot(x_bpsk_carrier)
plt.title('BPSK carrier')
plt.show()
# y_bpsk_carrier = np.fft.fft(x_bpsk_carrier, N)
# plt.plot(abs(y_bpsk_carrier))
# plt.title('FFT BPSK carrier')
# plt.show()
def get_qpsk_carrier():
x = np.fromfile('gnuradio_dumps/qpsk_carrier', dtype = 'float32')
x_qpsk_carrier = x[12000:12000+N]
plt.plot(x_qpsk_carrier)
plt.title('QPSK carrier')
plt.show()
# y_qpsk_carrier = np.fft.fft(x_qpsk_carrier, N)
# plt.plot(abs(y_qpsk_carrier))
# plt.title('FFT QPSK carrier')
# plt.show()
def get_bpsk():
x = np.fromfile('gnuradio_dumps/bpsk', dtype = 'complex64')
x_bpsk = x[9000:9000+N]
plt.plot(x_bpsk.real)
plt.plot(x_bpsk.imag)
plt.title('BPSK')
plt.show()
# y_bpsk = np.fft.fft(x_bpsk, N)
# plt.plot(abs(y_bpsk))
# plt.title('FFT BPSK')
# plt.show()
def get_qpsk():
x = np.fromfile('gnuradio_dumps/qpsk', dtype = 'complex64')
x_qpsk = x[11000:11000+N]
plt.plot(x_qpsk.real)
plt.plot(x_qpsk.imag)
plt.title('QPSK')
plt.show()
# y_qpsk = np.fft.fft(x_bpsk, N)
# plt.plot(abs(y_bqsk))
# plt.title('FFT QPSK')
# plt.show()
def load_dataset(location="../../datasets/radioml.dat"):
f = open(location)
ds = cPickle.load(f)
return ds
def get_from_dataset(dataset, key):
"""Returns complex version of dataset[key][500]"""
xr = dataset[key][500][0]
xi = dataset[key][500][1]
plt.plot(xr)
plt.plot(xi)
plt.title(key)
plt.show()
return xr
def main():
x_sin = get_sine_wave()
x_bpsk_carrier = get_bpsk_carrier()
x_qpsk_carrier = get_qpsk_carrier()
x_bpsk = get_bpsk()
x_qpsk = get_qpsk()
ds = load_dataset()
x_amssb = get_from_dataset(dataset=ds, key=('AM-SSB', 18))
x_amdsb = get_from_dataset(dataset=ds, key= ('AM-DSB', 18))
x_gfsk = get_from_dataset(dataset=ds, key=('GFSK', 18))
if __name__ == "__main__":
main() | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.fromfile",
"cPickle.load",
"numpy.sin"
] | [((265, 280), 'matplotlib.pyplot.plot', 'plt.plot', (['x_sin'], {}), '(x_sin)\n', (273, 280), True, 'import matplotlib.pyplot as plt\n'), ((282, 304), 'matplotlib.pyplot.title', 'plt.title', (['"""Sine wave"""'], {}), "('Sine wave')\n", (291, 304), True, 'import matplotlib.pyplot as plt\n'), ((306, 316), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (314, 316), True, 'import matplotlib.pyplot as plt\n'), ((463, 522), 'numpy.fromfile', 'np.fromfile', (['"""gnuradio_dumps/bpsk_carrier"""'], {'dtype': '"""float32"""'}), "('gnuradio_dumps/bpsk_carrier', dtype='float32')\n", (474, 522), True, 'import numpy as np\n'), ((559, 583), 'matplotlib.pyplot.plot', 'plt.plot', (['x_bpsk_carrier'], {}), '(x_bpsk_carrier)\n', (567, 583), True, 'import matplotlib.pyplot as plt\n'), ((585, 610), 'matplotlib.pyplot.title', 'plt.title', (['"""BPSK carrier"""'], {}), "('BPSK carrier')\n", (594, 610), True, 'import matplotlib.pyplot as plt\n'), ((612, 622), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (620, 622), True, 'import matplotlib.pyplot as plt\n'), ((785, 844), 'numpy.fromfile', 'np.fromfile', (['"""gnuradio_dumps/qpsk_carrier"""'], {'dtype': '"""float32"""'}), "('gnuradio_dumps/qpsk_carrier', dtype='float32')\n", (796, 844), True, 'import numpy as np\n'), ((883, 907), 'matplotlib.pyplot.plot', 'plt.plot', (['x_qpsk_carrier'], {}), '(x_qpsk_carrier)\n', (891, 907), True, 'import matplotlib.pyplot as plt\n'), ((909, 934), 'matplotlib.pyplot.title', 'plt.title', (['"""QPSK carrier"""'], {}), "('QPSK carrier')\n", (918, 934), True, 'import matplotlib.pyplot as plt\n'), ((936, 946), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (944, 946), True, 'import matplotlib.pyplot as plt\n'), ((1102, 1155), 'numpy.fromfile', 'np.fromfile', (['"""gnuradio_dumps/bpsk"""'], {'dtype': '"""complex64"""'}), "('gnuradio_dumps/bpsk', dtype='complex64')\n", (1113, 1155), True, 'import numpy as np\n'), ((1184, 1205), 'matplotlib.pyplot.plot', 'plt.plot', (['x_bpsk.real'], {}), '(x_bpsk.real)\n', (1192, 1205), True, 'import matplotlib.pyplot as plt\n'), ((1207, 1228), 'matplotlib.pyplot.plot', 'plt.plot', (['x_bpsk.imag'], {}), '(x_bpsk.imag)\n', (1215, 1228), True, 'import matplotlib.pyplot as plt\n'), ((1230, 1247), 'matplotlib.pyplot.title', 'plt.title', (['"""BPSK"""'], {}), "('BPSK')\n", (1239, 1247), True, 'import matplotlib.pyplot as plt\n'), ((1249, 1259), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1257, 1259), True, 'import matplotlib.pyplot as plt\n'), ((1384, 1437), 'numpy.fromfile', 'np.fromfile', (['"""gnuradio_dumps/qpsk"""'], {'dtype': '"""complex64"""'}), "('gnuradio_dumps/qpsk', dtype='complex64')\n", (1395, 1437), True, 'import numpy as np\n'), ((1468, 1489), 'matplotlib.pyplot.plot', 'plt.plot', (['x_qpsk.real'], {}), '(x_qpsk.real)\n', (1476, 1489), True, 'import matplotlib.pyplot as plt\n'), ((1491, 1512), 'matplotlib.pyplot.plot', 'plt.plot', (['x_qpsk.imag'], {}), '(x_qpsk.imag)\n', (1499, 1512), True, 'import matplotlib.pyplot as plt\n'), ((1514, 1531), 'matplotlib.pyplot.title', 'plt.title', (['"""QPSK"""'], {}), "('QPSK')\n", (1523, 1531), True, 'import matplotlib.pyplot as plt\n'), ((1533, 1543), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1541, 1543), True, 'import matplotlib.pyplot as plt\n'), ((1736, 1751), 'cPickle.load', 'cPickle.load', (['f'], {}), '(f)\n', (1748, 1751), False, 'import cPickle\n'), ((1911, 1923), 'matplotlib.pyplot.plot', 'plt.plot', (['xr'], {}), '(xr)\n', (1919, 1923), True, 'import matplotlib.pyplot as plt\n'), ((1925, 1937), 'matplotlib.pyplot.plot', 'plt.plot', (['xi'], {}), '(xi)\n', (1933, 1937), True, 'import matplotlib.pyplot as plt\n'), ((1939, 1953), 'matplotlib.pyplot.title', 'plt.title', (['key'], {}), '(key)\n', (1948, 1953), True, 'import matplotlib.pyplot as plt\n'), ((1955, 1965), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1963, 1965), True, 'import matplotlib.pyplot as plt\n'), ((241, 268), 'numpy.sin', 'np.sin', (['(2.0 * pi * i / 16.0)'], {}), '(2.0 * pi * i / 16.0)\n', (247, 268), True, 'import numpy as np\n')] |
from collections import defaultdict
import os
import numpy as np
from ding.utils.data.collate_fn import default_collate, default_decollate
from easydict import EasyDict
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from torch.optim import Adam
from core.policy import CILRSPolicy
from core.data import CILRSDataset
config = dict(
exp_name='cilrs_train',
policy=dict(
cuda=True,
cudnn=True,
resume=False,
ckpt_path=None,
model=dict(
num_branch=4,
),
learn=dict(
epoches=200,
batch_size=128,
loss='l1',
lr=1e-4,
speed_weight=0.05,
control_weights=[0.5, 0.45, 0.05],
),
eval=dict(
eval_freq=10,
)
),
data=dict(
train=dict(
root_dir='./datasets_train/cilrs_datasets_train',
preloads='./_preloads/cilrs_datasets_train.npy',
transform=True,
),
val=dict(
root_dir='./datasets_train/cilrs_datasets_val',
preloads='./_preloads/cilrs_datasets_val.npy',
transform=True,
),
)
)
main_config = EasyDict(config)
def train(policy, optimizer, loader, tb_logger=None, start_iter=0):
loss_epoch = defaultdict(list)
iter_num = start_iter
policy.reset()
for data in tqdm(loader):
log_vars = policy.forward(data)
optimizer.zero_grad()
total_loss = log_vars['total_loss']
total_loss.backward()
optimizer.step()
log_vars['cur_lr'] = optimizer.defaults['lr']
for k, v in log_vars.items():
loss_epoch[k] += [log_vars[k].item()]
if iter_num % 50 == 0 and tb_logger is not None:
tb_logger.add_scalar("train_iter/" + k, v, iter_num)
iter_num += 1
loss_epoch = {k: np.mean(v) for k, v in loss_epoch.items()}
return iter_num, loss_epoch
def validate(policy, loader, tb_logger=None, epoch=0):
loss_epoch = defaultdict(list)
policy.reset()
for data in tqdm(loader):
with torch.no_grad():
log_vars = policy.forward(data)
for k in list(log_vars.keys()):
loss_epoch[k] += [log_vars[k]]
loss_epoch = {k: np.mean(v) for k, v in loss_epoch.items()}
if tb_logger is not None:
for k, v in loss_epoch.items():
tb_logger.add_scalar("validate_epoch/" + k, v, epoch)
return loss_epoch
def save_ckpt(state, name=None, exp_name=''):
os.makedirs('checkpoints/' + exp_name, exist_ok=True)
ckpt_path = 'checkpoints/{}/{}_ckpt.pth'.format(exp_name, name)
torch.save(state, ckpt_path)
def load_best_ckpt(policy, optimizer=None, root_dir='checkpoints', exp_name='', ckpt_path=None):
ckpt_dir = os.path.join(root_dir, exp_name)
assert os.path.isdir(ckpt_dir), ckpt_dir
files = os.listdir(ckpt_dir)
assert files, 'No ckpt files found'
if ckpt_path and ckpt_path in files:
pass
elif os.path.exists(os.path.join(ckpt_dir, 'best_ckpt.pth')):
ckpt_path = 'best_ckpt.pth'
else:
ckpt_path = sorted(files)[-1]
print('Load ckpt:', ckpt_path)
state_dict = torch.load(os.path.join(ckpt_dir, ckpt_path))
policy.load_state_dict(state_dict)
if 'optimizer' in state_dict:
optimizer.load_state_dict(state_dict['optimizer'])
epoch = state_dict['epoch']
iterations = state_dict['iterations']
best_loss = state_dict['best_loss']
return epoch, iterations, best_loss
def main(cfg):
if cfg.policy.cudnn:
torch.backends.cudnn.benchmark = True
train_dataset = CILRSDataset(**cfg.data.train)
val_dataset = CILRSDataset(**cfg.data.val)
train_loader = DataLoader(train_dataset, cfg.policy.learn.batch_size, shuffle=True, num_workers=8)
val_loader = DataLoader(val_dataset, cfg.policy.learn.batch_size, num_workers=8)
cilrs_policy = CILRSPolicy(cfg.policy)
optimizer = Adam(cilrs_policy._model.parameters(), cfg.policy.learn.lr)
tb_logger = SummaryWriter('./log/{}/'.format(cfg.exp_name))
iterations = 0
best_loss = 1e8
start_epoch = 0
if cfg.policy.resume:
start_epoch, iterations, best_loss = load_best_ckpt(
cilrs_policy.learn_mode, optimizer, exp_name=cfg.exp_name, ckpt_path=cfg.policy.ckpt_path
)
for epoch in range(start_epoch, cfg.policy.learn.epoches):
iter_num, loss = train(cilrs_policy.learn_mode, optimizer, train_loader, tb_logger, iterations)
iterations = iter_num
tqdm.write(
f"Epoch {epoch:03d}, Iter {iter_num:06d}: Total: {loss['total_loss']:2.5f}" +
f" Speed: {loss['speed_loss']:2.5f} Str: {loss['steer_loss']:2.5f}" +
f" Thr: {loss['throttle_loss']:2.5f} Brk: {loss['brake_loss']:2.5f}"
)
if epoch % cfg.policy.eval.eval_freq == 0:
loss_dict = validate(cilrs_policy.learn_mode, val_loader, tb_logger, iterations)
total_loss = loss_dict['total_loss']
tqdm.write(f"Validate Total: {total_loss:2.5f}")
state_dict = cilrs_policy.learn_mode.state_dict()
state_dict['optimizer'] = optimizer.state_dict()
state_dict['epoch'] = epoch
state_dict['iterations'] = iterations
state_dict['best_loss'] = best_loss
if total_loss < best_loss and epoch > 0:
tqdm.write("Best Validation Loss!")
best_loss = total_loss
state_dict['best_loss'] = best_loss
save_ckpt(state_dict, 'best', cfg.exp_name)
save_ckpt(state_dict, '{:05d}'.format(epoch), cfg.exp_name)
if __name__ == '__main__':
main(main_config)
| [
"tqdm.tqdm",
"core.policy.CILRSPolicy",
"tqdm.tqdm.write",
"os.makedirs",
"torch.utils.data.DataLoader",
"os.path.isdir",
"collections.defaultdict",
"torch.save",
"core.data.CILRSDataset",
"numpy.mean",
"easydict.EasyDict",
"torch.no_grad",
"os.path.join",
"os.listdir"
] | [((1250, 1266), 'easydict.EasyDict', 'EasyDict', (['config'], {}), '(config)\n', (1258, 1266), False, 'from easydict import EasyDict\n'), ((1354, 1371), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1365, 1371), False, 'from collections import defaultdict\n'), ((1434, 1446), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (1438, 1446), False, 'from tqdm import tqdm\n'), ((2081, 2098), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2092, 2098), False, 'from collections import defaultdict\n'), ((2134, 2146), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (2138, 2146), False, 'from tqdm import tqdm\n'), ((2579, 2632), 'os.makedirs', 'os.makedirs', (["('checkpoints/' + exp_name)"], {'exist_ok': '(True)'}), "('checkpoints/' + exp_name, exist_ok=True)\n", (2590, 2632), False, 'import os\n'), ((2705, 2733), 'torch.save', 'torch.save', (['state', 'ckpt_path'], {}), '(state, ckpt_path)\n', (2715, 2733), False, 'import torch\n'), ((2848, 2880), 'os.path.join', 'os.path.join', (['root_dir', 'exp_name'], {}), '(root_dir, exp_name)\n', (2860, 2880), False, 'import os\n'), ((2892, 2915), 'os.path.isdir', 'os.path.isdir', (['ckpt_dir'], {}), '(ckpt_dir)\n', (2905, 2915), False, 'import os\n'), ((2938, 2958), 'os.listdir', 'os.listdir', (['ckpt_dir'], {}), '(ckpt_dir)\n', (2948, 2958), False, 'import os\n'), ((3697, 3727), 'core.data.CILRSDataset', 'CILRSDataset', ([], {}), '(**cfg.data.train)\n', (3709, 3727), False, 'from core.data import CILRSDataset\n'), ((3746, 3774), 'core.data.CILRSDataset', 'CILRSDataset', ([], {}), '(**cfg.data.val)\n', (3758, 3774), False, 'from core.data import CILRSDataset\n'), ((3794, 3881), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset', 'cfg.policy.learn.batch_size'], {'shuffle': '(True)', 'num_workers': '(8)'}), '(train_dataset, cfg.policy.learn.batch_size, shuffle=True,\n num_workers=8)\n', (3804, 3881), False, 'from torch.utils.data import DataLoader\n'), ((3895, 3962), 'torch.utils.data.DataLoader', 'DataLoader', (['val_dataset', 'cfg.policy.learn.batch_size'], {'num_workers': '(8)'}), '(val_dataset, cfg.policy.learn.batch_size, num_workers=8)\n', (3905, 3962), False, 'from torch.utils.data import DataLoader\n'), ((3983, 4006), 'core.policy.CILRSPolicy', 'CILRSPolicy', (['cfg.policy'], {}), '(cfg.policy)\n', (3994, 4006), False, 'from core.policy import CILRSPolicy\n'), ((1932, 1942), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (1939, 1942), True, 'import numpy as np\n'), ((2326, 2336), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (2333, 2336), True, 'import numpy as np\n'), ((3267, 3300), 'os.path.join', 'os.path.join', (['ckpt_dir', 'ckpt_path'], {}), '(ckpt_dir, ckpt_path)\n', (3279, 3300), False, 'import os\n'), ((4612, 4854), 'tqdm.tqdm.write', 'tqdm.write', (['(\n f"Epoch {epoch:03d}, Iter {iter_num:06d}: Total: {loss[\'total_loss\']:2.5f}"\n + f" Speed: {loss[\'speed_loss\']:2.5f} Str: {loss[\'steer_loss\']:2.5f}" +\n f" Thr: {loss[\'throttle_loss\']:2.5f} Brk: {loss[\'brake_loss\']:2.5f}")'], {}), '(\n f"Epoch {epoch:03d}, Iter {iter_num:06d}: Total: {loss[\'total_loss\']:2.5f}"\n + f" Speed: {loss[\'speed_loss\']:2.5f} Str: {loss[\'steer_loss\']:2.5f}" +\n f" Thr: {loss[\'throttle_loss\']:2.5f} Brk: {loss[\'brake_loss\']:2.5f}")\n', (4622, 4854), False, 'from tqdm import tqdm\n'), ((2161, 2176), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2174, 2176), False, 'import torch\n'), ((3078, 3117), 'os.path.join', 'os.path.join', (['ckpt_dir', '"""best_ckpt.pth"""'], {}), "(ckpt_dir, 'best_ckpt.pth')\n", (3090, 3117), False, 'import os\n'), ((5092, 5140), 'tqdm.tqdm.write', 'tqdm.write', (['f"""Validate Total: {total_loss:2.5f}"""'], {}), "(f'Validate Total: {total_loss:2.5f}')\n", (5102, 5140), False, 'from tqdm import tqdm\n'), ((5471, 5506), 'tqdm.tqdm.write', 'tqdm.write', (['"""Best Validation Loss!"""'], {}), "('Best Validation Loss!')\n", (5481, 5506), False, 'from tqdm import tqdm\n')] |
import pandas
from random import randint
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import preprocessing
from helper import svm,sgd,knn,dtree,lda
import numpy as np
setlist = [['a','m','n','s','t','g','q','x','o'],['b','e','c'],['h','k','u','v'],
['d','r','p'],['f'],['l'],['i'],['w'],['y']]
initialData = pandas.read_csv('../CSV_Data/dataset_6.csv')
allData = initialData
matrix = allData.drop('label',axis=1).values
matrix = preprocessing.scale(matrix)
allData = pandas.DataFrame(matrix,columns = initialData.columns.drop('label'))
allData['label'] = initialData['label']
sum_svm_acc=0
sum_knn_acc=0
sum_dtree_acc=0
sum_sgd_acc=0
sum_lda_acc=0
sum_svm_confusion = [[0 for x in range(9)] for y in range(9)]
sum_knn_confusion = [[0 for x in range(9)] for y in range(9)]
sum_dtree_confusion = [[0 for x in range(9)] for y in range(9)]
sum_lda_confusion = [[0 for x in range(9)] for y in range(9)]
sum_sgd_confusion = [[0 for x in range(9)] for y in range(9)]
for i in range(100):
master_set = []
for curr_set in setlist:
master_set.append(curr_set[randint(0,len(curr_set)-1)])
currentData = allData[allData['label'].isin(master_set)]
acc,con = svm.find_accuracy(currentData)
sum_svm_acc = sum_svm_acc + acc
sum_svm_confusion = np.add(sum_svm_confusion,con)
acc,con = sgd.find_accuracy(currentData)
sum_sgd_acc = sum_sgd_acc + acc
sum_sgd_confusion = np.add(sum_sgd_confusion,con)
acc,con = knn.find_accuracy(currentData)
sum_knn_acc = sum_knn_acc + acc
sum_knn_confusion = np.add(sum_knn_confusion,con)
acc,con = lda.find_accuracy(currentData)
sum_lda_acc = sum_lda_acc + acc
sum_lda_confusion = np.add(sum_lda_confusion,con)
acc,con = dtree.find_accuracy(currentData)
sum_dtree_acc = sum_dtree_acc + acc
sum_dtree_confusion = np.add(sum_dtree_confusion,con)
print("SVM : ")
print(sum_svm_confusion)
print("KNN : ")
print(sum_knn_confusion)
print("Dtree : ")
print(sum_dtree_confusion)
print("LDA : ")
print(sum_lda_confusion)
print("SGD : ")
print(sum_sgd_confusion)
print("SVM : ")
print(sum_svm_acc/100)
print("KNN : ")
print(sum_knn_acc/100)
print("Dtree : ")
print(sum_dtree_acc/100)
print("LDA : ")
print(sum_lda_acc/100)
print("SGD : ")
print(sum_sgd_acc/100)
| [
"helper.lda.find_accuracy",
"sklearn.preprocessing.scale",
"pandas.read_csv",
"helper.knn.find_accuracy",
"helper.sgd.find_accuracy",
"helper.dtree.find_accuracy",
"numpy.add",
"helper.svm.find_accuracy"
] | [((418, 462), 'pandas.read_csv', 'pandas.read_csv', (['"""../CSV_Data/dataset_6.csv"""'], {}), "('../CSV_Data/dataset_6.csv')\n", (433, 462), False, 'import pandas\n'), ((539, 566), 'sklearn.preprocessing.scale', 'preprocessing.scale', (['matrix'], {}), '(matrix)\n', (558, 566), False, 'from sklearn import preprocessing\n'), ((1280, 1310), 'helper.svm.find_accuracy', 'svm.find_accuracy', (['currentData'], {}), '(currentData)\n', (1297, 1310), False, 'from helper import svm, sgd, knn, dtree, lda\n'), ((1371, 1401), 'numpy.add', 'np.add', (['sum_svm_confusion', 'con'], {}), '(sum_svm_confusion, con)\n', (1377, 1401), True, 'import numpy as np\n'), ((1416, 1446), 'helper.sgd.find_accuracy', 'sgd.find_accuracy', (['currentData'], {}), '(currentData)\n', (1433, 1446), False, 'from helper import svm, sgd, knn, dtree, lda\n'), ((1507, 1537), 'numpy.add', 'np.add', (['sum_sgd_confusion', 'con'], {}), '(sum_sgd_confusion, con)\n', (1513, 1537), True, 'import numpy as np\n'), ((1552, 1582), 'helper.knn.find_accuracy', 'knn.find_accuracy', (['currentData'], {}), '(currentData)\n', (1569, 1582), False, 'from helper import svm, sgd, knn, dtree, lda\n'), ((1643, 1673), 'numpy.add', 'np.add', (['sum_knn_confusion', 'con'], {}), '(sum_knn_confusion, con)\n', (1649, 1673), True, 'import numpy as np\n'), ((1688, 1718), 'helper.lda.find_accuracy', 'lda.find_accuracy', (['currentData'], {}), '(currentData)\n', (1705, 1718), False, 'from helper import svm, sgd, knn, dtree, lda\n'), ((1779, 1809), 'numpy.add', 'np.add', (['sum_lda_confusion', 'con'], {}), '(sum_lda_confusion, con)\n', (1785, 1809), True, 'import numpy as np\n'), ((1824, 1856), 'helper.dtree.find_accuracy', 'dtree.find_accuracy', (['currentData'], {}), '(currentData)\n', (1843, 1856), False, 'from helper import svm, sgd, knn, dtree, lda\n'), ((1923, 1955), 'numpy.add', 'np.add', (['sum_dtree_confusion', 'con'], {}), '(sum_dtree_confusion, con)\n', (1929, 1955), True, 'import numpy as np\n')] |
import itertools
import re
import pandas as pd
import numpy as np
from catboost import Pool, FeaturesData
from constants import SCHOOLS_REVERSED, TARGET_LABELS
def _parse_str_nums(num_string):
"""
parse strings of numbers and take averages if there are multiple
:param num_string: a string of numbers and text
:type num_string: String
:return: float of the number found or average of multiple numbers found
:rtype: Float
:example:
>>> _parse_str_nums("40% to 50%")
>>> 45.
>>> _parse_str_nums("30%-50%")
>>> 40.
>>> _parse_str_nums("-20%")
>>> -20.
"""
num_string.upper().replace("ZERO", "0").replace("Forget it", "0")
# regex to find numbers
nums = re.findall(r'\d+', num_string)
# but if theres only one number, then we know its NOT a range and thus we can look for negative numbers
if len(nums) == 1:
nums = re.findall(r'[+-]?\d+(?:\.\d+)?', num_string)
# cast strings to ints
nums = [int(n) for n in nums]
# average ints derived from string
averaged = np.average(np.asarray(nums))
return averaged
def _squash_nested_lists(l_of_l):
"""
compress list of lists into one single list
:param l_of_l: list of lists
:type l_of_l: List
:return: single list with all elements of list of list
:rtype: List
:example:
>>> _squash_nested_list([['a','b'],['c'],['d','e']])
>>> ['a','b','c','d','e']
"""
return list(itertools.chain.from_iterable(l_of_l))
# TODO: do we care about case sensitivity?
def _preprocess_odds_string(string_of_odds):
"""
:param string_of_odds: string scraped from site describing an applicants odds of admittance
:type string_of_odds: String
:return: list of strings with entries for either schools or percent chances
:rtype: list
:example:
>>> _preprocess_odds_string("Harvard Business School: 85% Stanford: 80% Wharton: 90% Tuck: 95% Kellogg: 95%")
>>> ['Harvard Business School', '85', 'Stanford', '80', 'Wharton', '90', 'Tuck', '95', 'Kellogg', '95', '']
"""
# split on colons
divied_list_split_colon = string_of_odds.split(':')
# split on last occurrence of '%' using rsplit
divied_list_percent = [entry.rsplit('%', 1) for entry in divied_list_split_colon]
# recombine list of lists into one list of strings
divied_list_percent = _squash_nested_lists(divied_list_percent)
# split again on last occurence of new lines
# some snarky assessments have only text and no percent sign; i.e. "Forget it" or "Zero"
divied_list_of_lists = [entry.rsplit('\n', 1) for entry in divied_list_percent]
# recombine list of lists into one continuous list
compressed_divied_list = _squash_nested_lists(divied_list_of_lists)
# strip spaces for every entry
compressed_divied_list = [entry.strip() for entry in compressed_divied_list]
return compressed_divied_list
def _reduce_majors_dimensionality(data):
"""
The original dataset has a high number of majors specified
The dimensionality of the expanded numeric representation probably
hurts the model performance (in theory)
Thus we are reducing the dimensionality by combining all the stem into one category
and all the non stem into another category.
"""
stem_majors = ['Engineering', 'STEM']
# get all the majors that are not in the stem category
nonstem_majors = list(set(list(data.MAJOR.values)) - set(stem_majors))
majors_df = data.MAJOR
stem_replaced = majors_df.replace(to_replace=stem_majors, value=1.0)
new_majors_col = stem_replaced.replace(to_replace=nonstem_majors, value=0.0)
df_without_major_col = data.drop(['MAJOR'], axis=1, inplace=False)
reduced_df = df_without_major_col.join(pd.DataFrame({'STEM_MAJOR': new_majors_col}))
# print reduced_df
return reduced_df
def _reduce_race_dimensionality(data):
"""
The original dataset has a high number of races specified
The dimensionality of the expanded numeric representation probably
hurts the model performance (in theory)
Thus we are reducing the dimensionality by combining all the underrepresented into one category
and all the others into another
"""
underrepresented = ['Black', 'Latinx', 'Native American']
# get all the non-under represented races
non_underrepresented = list(set(list(data.RACE.values)) - set(underrepresented))
races_df = data.RACE
replace_races = races_df.replace(to_replace=underrepresented, value=1.0)
race_column = replace_races.replace(to_replace=non_underrepresented, value=0.0)
df_without_race_col = data.drop(['RACE'], axis=1, inplace=False)
reduced_df = df_without_race_col.join(pd.DataFrame({'UNDER_REP': race_column}))
return reduced_df
def _reduced_university_dimensionality(data):
"""
Use only binary classification. Tier 1 University Yes / No
"""
name_brand_schools = ['Tier 1', 'Tier 2']
small_schools = ['Tier 3']
uni_df = data.UNIVERSITY
replace_uni = uni_df.replace(to_replace=name_brand_schools, value=1.0)
uni_column = replace_uni.replace(to_replace=small_schools, value=0.0)
df_without_uni_col = data.drop(['UNIVERSITY'], axis=1, inplace=False)
reduced_df = df_without_uni_col.join(pd.DataFrame({'NAME_BRAND_SCHOOL': uni_column}))
return reduced_df
def _reduce_gender_dimensionality(data):
"""
Use only binary classification for simplifying dimensions
"""
gen_df = data.GENDER
replace_gen = gen_df.replace(to_replace=['Female'], value=1.0)
gen_column = replace_gen.replace(to_replace=['MALE'], value=0.0)
df_without_gen_col = data.drop(['GENDER'], axis=1, inplace=False)
reduced_df = df_without_gen_col.join(pd.DataFrame({'FEMALE': gen_column}))
return reduced_df
def _drop_unused_and_expand_categorical_columns(data):
"""
Drop data columns that were unused or have mostly NaNs
Expand categorical datas so they can be represented numerically
"""
# drop unused columns
data_after_drop = data.drop(['ODDS', 'INTERNATIONAL', 'JOBTITLE', 'AGE'], axis=1, inplace=False)
# dropped_data = data.drop(['ODDS','INTERNATIONAL','JOBTITLE','UNIVERSITY','MAJOR','GENDER','RACE'],axis=1,inplace=False)
# #change categorical data into numeric
# categorical_cols = ['UNIVERSITY','MAJOR','GENDER','RACE']
# # categorical_cols = []
# df_processed = pd.get_dummies(data=data_after_drop,columns=categorical_cols)
return data_after_drop
def preprocess_data_4_catboost(data_df, output_path=None):
"""
preprocess data for working with gradient boosting techniques
specifically with the catboost library. since this is going to use
the preprocessing built into the catboost library there are slightly
different steps to be done
"""
"""
train_data = Pool(
data=FeaturesData(
num_feature_data=np.array([[1, 4, 5, 6],
[4, 5, 6, 7],
[30, 40, 50, 60]],
dtype=np.float32),
cat_feature_data=np.array([[b"a", b"b"],
[b"a", b"b"],
[b"c", b"d"]],
dtype=object)
),
label=[1, 1, -1]
)
"""
new_df_w_labels = data_df.copy()
for idx, odds_string in data_df.ODDS.iteritems():
# skip data qual errors and abnormalities
if not isinstance(odds_string, str):
continue
divied_list = _preprocess_odds_string(odds_string)
for school_or_perc in divied_list:
if school_or_perc in SCHOOLS_REVERSED.keys():
school_idx = divied_list.index(school_or_perc)
# the percent is always the next index after the school
perc = divied_list[school_idx + 1]
# print "School: {};Odds: {}".format(school_or_perc,perc)
# use the standardized name
standard_school_name = SCHOOLS_REVERSED[school_or_perc]
# insert the specific name value for the correct row
new_df_w_labels.at[idx, standard_school_name] = _parse_str_nums(perc)
new_df_w_labels = _reduce_majors_dimensionality(new_df_w_labels)
# drop unused columns
data_after_drop = new_df_w_labels.drop(['ODDS', 'INTERNATIONAL', 'JOBTITLE'], axis=1, inplace=False)
# change categorical data into numeric
categorical_cols = ['UNIVERSITY', 'MAJOR', 'GENDER', 'RACE']
# a dataframe of ONLY the features
features_only_df = data_after_drop.drop(TARGET_LABELS, axis=1, inplace=False)
# determine the columns that are features by subtracting from labels
feature_cols = set(data_after_drop.columns) - set(TARGET_LABELS)
# a dataframe with ONLY labels
labels = data_after_drop.drop(feature_cols, axis=1, inplace=False)
multi_data_set_dict = {}
for school in labels.columns:
df_for_school = features_only_df.join(pd.DataFrame({school: labels[school]}))
# a holder dictionary that contains the features numpy ndarray for features and numpy ndarray for school label
school_dict = {}
# drop the NaNs from the dataset in any feature column or label. otherwise model training will fail
df_for_school.dropna(inplace=True)
# store the features as a numpy ndarray to be fed directly to model training
numerical_features_np_array = df_for_school.drop([school] + categorical_cols, axis=1, inplace=False).values
categorical_features_np_array = df_for_school[categorical_cols].values
# store the labels for a particular school as a numpy ndarray to be fed directly to model training
labels_as_list = df_for_school.drop(feature_cols, axis=1, inplace=False)[school].tolist()
datasetpool = Pool(
data=FeaturesData(
num_feature_data=np.array(numerical_features_np_array,
dtype=np.float32),
cat_feature_data=np.array(categorical_features_np_array,
dtype=object)
),
label=labels_as_list
)
multi_data_set_dict[school] = datasetpool
return multi_data_set_dict
def preprocess_data(data_df, output_path=None):
"""
preprocess data for general regression modeling
combines many steps such as working with the odds strings
and one hot encoding categorical features
input is a pandas dataframe of features and labels
output is a dictionary of datasets, where each key
is the feature set + lables for one school.
Since each school uses its own model, each school also needs its
own set of features/labels
"""
new_df_w_labels = data_df.copy()
for idx, odds_string in data_df.ODDS.iteritems():
# skip data qual errors and abnormalities
if isinstance(odds_string, bytes):
odds_string = odds_string.decode("utf-8")
elif not isinstance(odds_string, str):
continue
else:
print(odds_string)
print(type(odds_string))
divied_list = _preprocess_odds_string(odds_string)
for school_or_perc in divied_list:
if school_or_perc in SCHOOLS_REVERSED.keys():
school_idx = divied_list.index(school_or_perc)
perc = divied_list[school_idx + 1]
# print "School: {};Odds: {}".format(school_or_perc,perc)
# use the standardized name
standard_school_name = SCHOOLS_REVERSED[school_or_perc]
# insert the specific name value for the correct row
new_df_w_labels.at[idx, standard_school_name] = _parse_str_nums(perc)
# dataset currently has a ton of majors as categories. try combining them into STEM/NonSTEM to reduce dimensionality
new_df_w_labels = _reduce_majors_dimensionality(new_df_w_labels)
new_df_w_labels = _reduce_race_dimensionality(new_df_w_labels)
new_df_w_labels = _reduced_university_dimensionality(new_df_w_labels)
new_df_w_labels = _reduce_gender_dimensionality(new_df_w_labels)
df_processed = _drop_unused_and_expand_categorical_columns(new_df_w_labels)
# write dataframe to csv after processing for debugging and things
if output_path:
df_processed.to_csv(output_path)
# a dataframe of ONLY the features
features_only_df = df_processed.drop(TARGET_LABELS, axis=1, inplace=False)
# determine the columns that are features by subtracting from labels
feature_cols = set(df_processed.columns) - set(TARGET_LABELS)
# a dataframe with ONLY labels
labels = df_processed.drop(feature_cols, axis=1, inplace=False)
multi_data_set_dict = {}
# create a new dataset for each school that we are modeling
for school in labels.columns:
# create a dataframe with all the features and the labels for a particular school
df_for_school = features_only_df.join(pd.DataFrame({school: labels[school]}))
# a holder dictionary that contains the features numpy ndarray for features and numpy ndarray for school label
school_dict = {}
# drop the NaNs from the dataset in any feature column or label. otherwise model training will fail
df_for_school.dropna(inplace=True)
# store the features as a numpy ndarray to be fed directly to model training
school_dict['features'] = df_for_school.drop([school], axis=1, inplace=False)
# store the labels for a particular school as a numpy ndarray to be fed directly to model training
school_dict['labels'] = df_for_school.drop(feature_cols, axis=1, inplace=False)
# store the FEATURES & LABELS for a PARTICULAR SCHOOL in the dictionary
multi_data_set_dict[school] = school_dict
feature_col_names = features_only_df.columns
return multi_data_set_dict, feature_col_names
| [
"pandas.DataFrame",
"constants.SCHOOLS_REVERSED.keys",
"numpy.asarray",
"re.findall",
"numpy.array",
"itertools.chain.from_iterable"
] | [((777, 807), 're.findall', 're.findall', (['"""\\\\d+"""', 'num_string'], {}), "('\\\\d+', num_string)\n", (787, 807), False, 'import re\n'), ((955, 1002), 're.findall', 're.findall', (['"""[+-]?\\\\d+(?:\\\\.\\\\d+)?"""', 'num_string'], {}), "('[+-]?\\\\d+(?:\\\\.\\\\d+)?', num_string)\n", (965, 1002), False, 'import re\n'), ((1128, 1144), 'numpy.asarray', 'np.asarray', (['nums'], {}), '(nums)\n', (1138, 1144), True, 'import numpy as np\n'), ((1536, 1573), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['l_of_l'], {}), '(l_of_l)\n', (1565, 1573), False, 'import itertools\n'), ((3857, 3901), 'pandas.DataFrame', 'pd.DataFrame', (["{'STEM_MAJOR': new_majors_col}"], {}), "({'STEM_MAJOR': new_majors_col})\n", (3869, 3901), True, 'import pandas as pd\n'), ((4815, 4855), 'pandas.DataFrame', 'pd.DataFrame', (["{'UNDER_REP': race_column}"], {}), "({'UNDER_REP': race_column})\n", (4827, 4855), True, 'import pandas as pd\n'), ((5384, 5431), 'pandas.DataFrame', 'pd.DataFrame', (["{'NAME_BRAND_SCHOOL': uni_column}"], {}), "({'NAME_BRAND_SCHOOL': uni_column})\n", (5396, 5431), True, 'import pandas as pd\n'), ((5854, 5890), 'pandas.DataFrame', 'pd.DataFrame', (["{'FEMALE': gen_column}"], {}), "({'FEMALE': gen_column})\n", (5866, 5890), True, 'import pandas as pd\n'), ((8970, 9008), 'pandas.DataFrame', 'pd.DataFrame', (['{school: labels[school]}'], {}), '({school: labels[school]})\n', (8982, 9008), True, 'import pandas as pd\n'), ((12991, 13029), 'pandas.DataFrame', 'pd.DataFrame', (['{school: labels[school]}'], {}), '({school: labels[school]})\n', (13003, 13029), True, 'import pandas as pd\n'), ((7622, 7645), 'constants.SCHOOLS_REVERSED.keys', 'SCHOOLS_REVERSED.keys', ([], {}), '()\n', (7643, 7645), False, 'from constants import SCHOOLS_REVERSED, TARGET_LABELS\n'), ((11266, 11289), 'constants.SCHOOLS_REVERSED.keys', 'SCHOOLS_REVERSED.keys', ([], {}), '()\n', (11287, 11289), False, 'from constants import SCHOOLS_REVERSED, TARGET_LABELS\n'), ((9885, 9940), 'numpy.array', 'np.array', (['numerical_features_np_array'], {'dtype': 'np.float32'}), '(numerical_features_np_array, dtype=np.float32)\n', (9893, 9940), True, 'import numpy as np\n'), ((10017, 10070), 'numpy.array', 'np.array', (['categorical_features_np_array'], {'dtype': 'object'}), '(categorical_features_np_array, dtype=object)\n', (10025, 10070), True, 'import numpy as np\n')] |
import os
import argparse
import numpy as np
import open3d as o3d
parser = argparse.ArgumentParser()
parser.add_argument('--data_root', type=str, default='./ModelNet40')
parser.add_argument('--store_dir', type=str, default='./data')
args = parser.parse_args()
if __name__ == '__main__':
os.makedirs(args.store_dir, exist_ok=True)
folder_names = os.listdir(args.data_root)
folder_paths = [os.path.join(args.data_root, folder_name) for folder_name in folder_names]
splits = ['train', 'test']
for i, (folder_name, folder_path) in enumerate(zip(folder_names, folder_paths)):
for split in splits:
os.makedirs(os.path.join(args.store_dir, folder_name, split), exist_ok=True)
category_path = os.path.join(folder_path, split)
mesh_names = os.listdir(category_path)
mesh_paths = [os.path.join(category_path, mesh_name) for mesh_name in mesh_names]
for j, (mesh_name, mesh_path) in enumerate(zip(mesh_names, mesh_paths)):
store_path = os.path.join(args.store_dir, folder_name, split, f'{mesh_name[:-4]}.npy')
if os.path.exists(store_path):
continue
newf = ''
corrupt = False
with open(mesh_path, 'r') as f:
for line_i, line in enumerate(f):
if line_i == 0 and len(line) != 4:
newf += line[:3] + '\n' + line[3:]
corrupt = True
else:
newf += line
if not corrupt:
break
if corrupt:
with open(mesh_path, 'w') as f:
f.write(newf)
mesh = o3d.io.read_triangle_mesh(mesh_path)
pcd = mesh.sample_points_uniformly(number_of_points=2048)
pcd_array = np.asarray(pcd.points)
np.save(args.store_path, pcd_array)
| [
"numpy.save",
"os.makedirs",
"argparse.ArgumentParser",
"open3d.io.read_triangle_mesh",
"numpy.asarray",
"os.path.exists",
"os.path.join",
"os.listdir"
] | [((76, 101), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (99, 101), False, 'import argparse\n'), ((293, 335), 'os.makedirs', 'os.makedirs', (['args.store_dir'], {'exist_ok': '(True)'}), '(args.store_dir, exist_ok=True)\n', (304, 335), False, 'import os\n'), ((356, 382), 'os.listdir', 'os.listdir', (['args.data_root'], {}), '(args.data_root)\n', (366, 382), False, 'import os\n'), ((403, 444), 'os.path.join', 'os.path.join', (['args.data_root', 'folder_name'], {}), '(args.data_root, folder_name)\n', (415, 444), False, 'import os\n'), ((742, 774), 'os.path.join', 'os.path.join', (['folder_path', 'split'], {}), '(folder_path, split)\n', (754, 774), False, 'import os\n'), ((800, 825), 'os.listdir', 'os.listdir', (['category_path'], {}), '(category_path)\n', (810, 825), False, 'import os\n'), ((648, 696), 'os.path.join', 'os.path.join', (['args.store_dir', 'folder_name', 'split'], {}), '(args.store_dir, folder_name, split)\n', (660, 696), False, 'import os\n'), ((852, 890), 'os.path.join', 'os.path.join', (['category_path', 'mesh_name'], {}), '(category_path, mesh_name)\n', (864, 890), False, 'import os\n'), ((1035, 1108), 'os.path.join', 'os.path.join', (['args.store_dir', 'folder_name', 'split', 'f"""{mesh_name[:-4]}.npy"""'], {}), "(args.store_dir, folder_name, split, f'{mesh_name[:-4]}.npy')\n", (1047, 1108), False, 'import os\n'), ((1128, 1154), 'os.path.exists', 'os.path.exists', (['store_path'], {}), '(store_path)\n', (1142, 1154), False, 'import os\n'), ((1800, 1836), 'open3d.io.read_triangle_mesh', 'o3d.io.read_triangle_mesh', (['mesh_path'], {}), '(mesh_path)\n', (1825, 1836), True, 'import open3d as o3d\n'), ((1939, 1961), 'numpy.asarray', 'np.asarray', (['pcd.points'], {}), '(pcd.points)\n', (1949, 1961), True, 'import numpy as np\n'), ((1978, 2013), 'numpy.save', 'np.save', (['args.store_path', 'pcd_array'], {}), '(args.store_path, pcd_array)\n', (1985, 2013), True, 'import numpy as np\n')] |
import sys
import numpy as np
from collections import Counter
from sklearn.metrics import label_ranking_average_precision_score
from sklearn.metrics import coverage_error, label_ranking_loss, hamming_loss, accuracy_score
def patk(labels, predictions):
pak = np.zeros(3)
K = np.array([1, 3, 5])
for i in range(predictions.shape[0]):
pos = np.argsort(-predictions[i, :])
y = labels[i, :]
y = y[pos]
for j in range(3):
k = K[j]
pak[j] += (np.sum(y[:k]) / k)
pak = pak / predictions.shape[0]
return pak * 100.
'''
def precision_at_k(predictions, labels, k):
act_set =
'''
def cm_precision_recall(prediction,truth):
"""Evaluate confusion matrix, precision and recall for given set of labels and predictions
Args
prediction: a vector with predictions
truth: a vector with class labels
Returns:
cm: confusion matrix
precision: precision score
recall: recall score"""
confusion_matrix = Counter()
positives = [1]
binary_truth = [x in positives for x in truth]
binary_prediction = [x in positives for x in prediction]
for t, p in zip(binary_truth, binary_prediction):
confusion_matrix[t,p] += 1
cm = np.array([confusion_matrix[True,True], confusion_matrix[False,False], confusion_matrix[False,True], confusion_matrix[True,False]])
#print cm
precision = (cm[0]/(cm[0]+cm[2]+0.000001))
recall = (cm[0]/(cm[0]+cm[3]+0.000001))
return cm, precision, recall
def bipartition_scores(labels,predictions):
""" Computes bipartitation metrics for a given multilabel predictions and labels
Args:
logits: Logits tensor, float - [batch_size, NUM_LABELS].
labels: Labels tensor, int32 - [batch_size, NUM_LABELS].
Returns:
bipartiation: an array with micro_precision, micro_recall, micro_f1,macro_precision, macro_recall, macro_f1"""
sum_cm=np.zeros((4))
macro_precision=0
macro_recall=0
for i in range(labels.shape[1]):
truth=labels[:,i]
prediction=predictions[:,i]
cm,precision,recall=cm_precision_recall(prediction, truth)
sum_cm+=cm
macro_precision+=precision
macro_recall+=recall
macro_precision=macro_precision/labels.shape[1]
macro_recall=macro_recall/labels.shape[1]
macro_f1 = 2*(macro_precision)*(macro_recall)/(macro_precision+macro_recall+0.000001)
micro_precision = sum_cm[0]/(sum_cm[0]+sum_cm[2]+0.000001)
micro_recall=sum_cm[0]/(sum_cm[0]+sum_cm[3]+0.000001)
micro_f1 = 2*(micro_precision)*(micro_recall)/(micro_precision+micro_recall+0.000001)
bipartiation = np.asarray([micro_precision, micro_recall, micro_f1,macro_precision, macro_recall, macro_f1])
return bipartiation
def evaluate(predictions, labels, threshold=0.4, multi_label=True):
'''
True Positive : Label : 1, Prediction : 1
False Positive : Label : 0, Prediction : 1
False Negative : Label : 0, Prediction : 0
True Negative : Label : 1, Prediction : 0
Precision : TP/(TP + FP)
Recall : TP/(TP + FN)
F Score : 2.P.R/(P + R)
Ranking Loss : The average number of label pairs that are incorrectly ordered given predictions
Hammming Loss : The fraction of labels that are incorrectly predicted. (Hamming Distance between predictions and labels)
'''
assert predictions.shape == labels.shape, "Shapes: %s, %s" % (predictions.shape, labels.shape,)
metrics = dict()
if not multi_label:
metrics['bae'] = BAE(labels, predictions)
labels, predictions = np.argmax(labels, axis=1), np.argmax(predictions, axis=1)
metrics['accuracy'] = accuracy_score(labels, predictions)
metrics['micro_precision'], metrics['micro_recall'], metrics['micro_f1'], _ = \
precision_recall_fscore_support(labels, predictions, average='micro')
metrics['macro_precision'], metrics['macro_recall'], metrics['macro_f1'], metrics['coverage'], \
metrics['average_precision'], metrics['ranking_loss'], metrics['pak'], metrics['hamming_loss'] \
= 0, 0, 0, 0, 0, 0, 0, 0
else:
metrics['coverage'] = coverage_error(labels, predictions)
metrics['average_precision'] = label_ranking_average_precision_score(labels, predictions)
metrics['ranking_loss'] = label_ranking_loss(labels, predictions)
#metrics['hamming_loss'] = hamming_loss(labels, predictions)
for i in range(predictions.shape[0]):
predictions[i, :][predictions[i, :] >= threshold] = 1
predictions[i, :][predictions[i, :] < threshold] = 0
metrics['bae'] = 0
metrics['patk'] = patk(predictions, labels)
metrics['micro_precision'], metrics['micro_recall'], metrics['micro_f1'], metrics['macro_precision'], \
metrics['macro_recall'], metrics['macro_f1'] = bipartition_scores(labels, predictions)
return metrics | [
"numpy.sum",
"numpy.argmax",
"numpy.asarray",
"sklearn.metrics.accuracy_score",
"numpy.zeros",
"sklearn.metrics.label_ranking_average_precision_score",
"numpy.argsort",
"sklearn.metrics.coverage_error",
"sklearn.metrics.label_ranking_loss",
"numpy.array",
"collections.Counter"
] | [((263, 274), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (271, 274), True, 'import numpy as np\n'), ((283, 302), 'numpy.array', 'np.array', (['[1, 3, 5]'], {}), '([1, 3, 5])\n', (291, 302), True, 'import numpy as np\n'), ((995, 1004), 'collections.Counter', 'Counter', ([], {}), '()\n', (1002, 1004), False, 'from collections import Counter\n'), ((1225, 1363), 'numpy.array', 'np.array', (['[confusion_matrix[True, True], confusion_matrix[False, False],\n confusion_matrix[False, True], confusion_matrix[True, False]]'], {}), '([confusion_matrix[True, True], confusion_matrix[False, False],\n confusion_matrix[False, True], confusion_matrix[True, False]])\n', (1233, 1363), True, 'import numpy as np\n'), ((1903, 1914), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1911, 1914), True, 'import numpy as np\n'), ((2635, 2733), 'numpy.asarray', 'np.asarray', (['[micro_precision, micro_recall, micro_f1, macro_precision, macro_recall,\n macro_f1]'], {}), '([micro_precision, micro_recall, micro_f1, macro_precision,\n macro_recall, macro_f1])\n', (2645, 2733), True, 'import numpy as np\n'), ((359, 389), 'numpy.argsort', 'np.argsort', (['(-predictions[i, :])'], {}), '(-predictions[i, :])\n', (369, 389), True, 'import numpy as np\n'), ((3717, 3752), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['labels', 'predictions'], {}), '(labels, predictions)\n', (3731, 3752), False, 'from sklearn.metrics import coverage_error, label_ranking_loss, hamming_loss, accuracy_score\n'), ((4215, 4250), 'sklearn.metrics.coverage_error', 'coverage_error', (['labels', 'predictions'], {}), '(labels, predictions)\n', (4229, 4250), False, 'from sklearn.metrics import coverage_error, label_ranking_loss, hamming_loss, accuracy_score\n'), ((4290, 4348), 'sklearn.metrics.label_ranking_average_precision_score', 'label_ranking_average_precision_score', (['labels', 'predictions'], {}), '(labels, predictions)\n', (4327, 4348), False, 'from sklearn.metrics import label_ranking_average_precision_score\n'), ((4383, 4422), 'sklearn.metrics.label_ranking_loss', 'label_ranking_loss', (['labels', 'predictions'], {}), '(labels, predictions)\n', (4401, 4422), False, 'from sklearn.metrics import coverage_error, label_ranking_loss, hamming_loss, accuracy_score\n'), ((489, 502), 'numpy.sum', 'np.sum', (['y[:k]'], {}), '(y[:k])\n', (495, 502), True, 'import numpy as np\n'), ((3628, 3653), 'numpy.argmax', 'np.argmax', (['labels'], {'axis': '(1)'}), '(labels, axis=1)\n', (3637, 3653), True, 'import numpy as np\n'), ((3655, 3685), 'numpy.argmax', 'np.argmax', (['predictions'], {'axis': '(1)'}), '(predictions, axis=1)\n', (3664, 3685), True, 'import numpy as np\n')] |
import os.path as op
import warnings
import mne
import numpy as np
import pandas as pd
from jumeg.jumeg_volume_plotting import plot_vstc_sliced_old
from tqdm import tqdm
import config
from config import fname
from utils import set_directory
warnings.filterwarnings('ignore', category=DeprecationWarning)
###############################################################################
# Load volume source space
###############################################################################
info = mne.io.read_info(fname.sample_raw)
info = mne.pick_info(info, mne.pick_types(info, meg=True, eeg=False))
fwd = mne.read_forward_solution(fname.fwd_man)
fwd = mne.pick_types_forward(fwd, meg=True, eeg=False)
vsrc = fwd['src']
vertno = vsrc[0]['vertno']
# needs to be set for plot_vstc_sliced_old to work
if vsrc[0]['subject_his_id'] is None:
vsrc[0]['subject_his_id'] = 'sample'
###############################################################################
# Get data from csv files
###############################################################################
dfs = []
for vertex in tqdm(range(3756), total=3756):
try:
df = pd.read_csv(fname.lcmv_results(vertex=vertex, noise=0.1), index_col=0)
df['vertex'] = vertex
df['noise'] = config.noise
dfs.append(df)
except Exception as e:
print(e)
lcmv = pd.concat(dfs, ignore_index=True)
lcmv['pick_ori'].fillna('none', inplace=True)
lcmv['weight_norm'].fillna('none', inplace=True)
lcmv['ori_error'].fillna(-1, inplace=True)
def fix(x):
if x == np.nan:
return np.nan
elif x > 90:
return 180 - x
else:
return x
lcmv['ori_error'] = lcmv['ori_error'].map(fix)
cbar_range_dist = [0, lcmv['dist'].dropna().to_numpy().max()]
# fancy metric is very skewed, use 0.015 as fixed cutoff
cbar_range_eval = [0, 0.015]
cbar_range_corr = [0, 1]
cbar_range_ori = [0, lcmv['ori_error'].dropna().to_numpy().max()]
###############################################################################
# HTML settings
###############################################################################
html_header = '''
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table id="results">
<tr>
<th>reg</th>
<th>sensor type</th>
<th>pick_ori</th>
<th>inversion</th>
<th>weight_norm</th>
<th>normalize_fwd</th>
<th>use_noise_cov</th>
<th>reduce_rank</th>
<th>P2P distance</th>
<th>Fancy metric</th>
<th>Time course correlation</th>
<th>Orientation error</th>
</tr>
'''
html_footer = '''
<script src="tablefilter/tablefilter.js"></script>
<script>
var filtersConfig = {
base_path: 'tablefilter/',
col_0: 'checklist',
col_1: 'checklist',
col_2: 'checklist',
col_3: 'checklist',
col_4: 'checklist',
col_5: 'checklist',
col_6: 'checklist',
col_7: 'checklist',
col_8: 'none',
col_9: 'none',
col_10: 'none',
col_11: 'none',
filters_row_index: 1,
enable_checklist_reset_filter: false,
alternate_rows: true,
sticky_headers: true,
col_types: [
'number', 'string', 'string',
'string', 'string', 'string',
'string', 'string', 'image',
'image', 'image', 'image'
],
col_widths: [
'80px', '150px', '130px',
'110px', '170px', '150px',
'150px', '150px', '210px',
'210px', '210px', '210px'
]
};
var tf = new TableFilter('results', filtersConfig);
tf.init();
for (div of document.getElementsByClassName("div_checklist")) {
div.style.height = 100;
}
</script>
</body>
</html>
'''
html_table = ''
image_folder = 'lcmv'
image_path = op.join('html', image_folder)
set_directory(image_path)
for i, setting in enumerate(config.lcmv_settings):
# construct query
setting = tuple(['none' if s is None else s for s in setting])
(reg, sensor_type, pick_ori, inversion, weight_norm, normalize_fwd, use_noise_cov, reduce_rank) = setting
q = (f"reg=={reg:.2f} and sensor_type=='{sensor_type}' and pick_ori=='{pick_ori}' and inversion=='{inversion}' and "
f"weight_norm=='{weight_norm}' and normalize_fwd=={normalize_fwd} and use_noise_cov=={use_noise_cov} and reduce_rank=={reduce_rank}")
print(q)
sel = lcmv.query(q).dropna()
if len(sel) < 1000:
print('Not enough voxels. Did this run fail?')
continue
###############################################################################
# Create dist stc from simulated data
###############################################################################
vert_sel = sel['vertex'].to_numpy()
data_dist_sel = sel['dist'].to_numpy()
data_eval_sel = sel['eval'].to_numpy()
data_corr_sel = sel['corr'].to_numpy()
data_ori_sel = sel['ori_error'].to_numpy()
# do I want to add small value for thresholding in the plot, e.g., 0.001
# -> causes points with localization error equal to zero to be black in the plot
offset = 0.001
data_dist = np.zeros(shape=(vertno.shape[0], 1))
data_dist[vert_sel, 0] = data_dist_sel + offset
vstc_dist = mne.VolSourceEstimate(data=data_dist, vertices=vertno, tmin=0,
tstep=1 / info['sfreq'], subject='sample')
data_eval = np.zeros(shape=(vertno.shape[0], 1))
data_eval[vert_sel, 0] = data_eval_sel + offset
vstc_eval = mne.VolSourceEstimate(data=data_eval, vertices=vertno, tmin=0,
tstep=1 / info['sfreq'], subject='sample')
data_corr = np.zeros(shape=(vertno.shape[0], 1))
data_corr[vert_sel, 0] = data_corr_sel + offset
vstc_corr = mne.VolSourceEstimate(data=data_corr, vertices=vertno, tmin=0,
tstep=1 / info['sfreq'], subject='sample')
data_ori = np.zeros(shape=(vertno.shape[0], 1))
data_ori[vert_sel, 0] = data_ori_sel + offset
vstc_ori = mne.VolSourceEstimate(data=data_ori, vertices=vertno, tmin=0,
tstep=1 / info['sfreq'], subject='sample')
###############################################################################
# Plot
###############################################################################
fn_image_dist = '%03d_lcmv_dist_ortho.png' % i
fp_image_dist = op.join(image_path, fn_image_dist)
plot_vstc_sliced_old(vstc_dist, vsrc, vstc_dist.tstep,
subjects_dir=fname.subjects_dir,
time=vstc_dist.tmin, cut_coords=config.cut_coords,
display_mode='ortho', figure=None,
axes=None, colorbar=True, cmap='magma_r',
symmetric_cbar='auto', threshold=0,
cbar_range=cbar_range_dist,
save=True, fname_save=fp_image_dist)
fn_image_eval = '%03d_lcmv_eval_ortho.png' % i
fp_image_eval = op.join(image_path, fn_image_eval)
plot_vstc_sliced_old(vstc_eval, vsrc, vstc_eval.tstep,
subjects_dir=fname.subjects_dir,
time=vstc_eval.tmin, cut_coords=config.cut_coords,
display_mode='ortho', figure=None,
axes=None, colorbar=True, cmap='magma',
symmetric_cbar='auto', threshold=0,
cbar_range=cbar_range_eval,
save=True, fname_save=fp_image_eval)
fn_image_corr = '%03d_lcmv_corr_ortho.png' % i
fp_image_corr = op.join(image_path, fn_image_corr)
plot_vstc_sliced_old(vstc_corr, vsrc, vstc_corr.tstep,
subjects_dir=fname.subjects_dir,
time=vstc_corr.tmin, cut_coords=config.cut_coords,
display_mode='ortho', figure=None,
axes=None, colorbar=True, cmap='magma',
symmetric_cbar='auto', threshold=0,
cbar_range=cbar_range_corr,
save=True, fname_save=fp_image_corr)
if pick_ori == 'max-power':
fn_image_ori = '%03d_lcmv_ori_ortho.png' % i
fp_image_ori = op.join(image_path, fn_image_ori)
plot_vstc_sliced_old(vstc_ori, vsrc, vstc_ori.tstep,
subjects_dir=fname.subjects_dir,
time=vstc_ori.tmin, cut_coords=config.cut_coords,
display_mode='ortho', figure=None,
axes=None, colorbar=True, cmap='magma_r',
symmetric_cbar='auto', threshold=0,
cbar_range=cbar_range_ori,
save=True, fname_save=fp_image_ori)
###############################################################################
# Plot
###############################################################################
html_table += '<tr><td>' + '</td><td>'.join([str(s) for s in setting]) + '</td>'
html_table += '<td><img src="' + op.join(image_folder, fn_image_dist) + '"></td>'
html_table += '<td><img src="' + op.join(image_folder, fn_image_eval) + '"></td>'
html_table += '<td><img src="' + op.join(image_folder, fn_image_corr) + '"></td>'
if pick_ori == 'max-power':
html_table += '<td><img src="' + op.join(image_folder, fn_image_ori) + '"></td>'
else:
html_table += '<td></td>'
with open('html/lcmv_vol.html', 'w') as f:
f.write(html_header)
f.write(html_table)
f.write(html_footer)
| [
"mne.VolSourceEstimate",
"config.fname.lcmv_results",
"jumeg.jumeg_volume_plotting.plot_vstc_sliced_old",
"warnings.filterwarnings",
"mne.pick_types",
"numpy.zeros",
"mne.pick_types_forward",
"utils.set_directory",
"mne.io.read_info",
"mne.read_forward_solution",
"os.path.join",
"pandas.concat... | [((244, 306), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (267, 306), False, 'import warnings\n'), ((503, 537), 'mne.io.read_info', 'mne.io.read_info', (['fname.sample_raw'], {}), '(fname.sample_raw)\n', (519, 537), False, 'import mne\n'), ((615, 655), 'mne.read_forward_solution', 'mne.read_forward_solution', (['fname.fwd_man'], {}), '(fname.fwd_man)\n', (640, 655), False, 'import mne\n'), ((662, 710), 'mne.pick_types_forward', 'mne.pick_types_forward', (['fwd'], {'meg': '(True)', 'eeg': '(False)'}), '(fwd, meg=True, eeg=False)\n', (684, 710), False, 'import mne\n'), ((1362, 1395), 'pandas.concat', 'pd.concat', (['dfs'], {'ignore_index': '(True)'}), '(dfs, ignore_index=True)\n', (1371, 1395), True, 'import pandas as pd\n'), ((4242, 4271), 'os.path.join', 'op.join', (['"""html"""', 'image_folder'], {}), "('html', image_folder)\n", (4249, 4271), True, 'import os.path as op\n'), ((4272, 4297), 'utils.set_directory', 'set_directory', (['image_path'], {}), '(image_path)\n', (4285, 4297), False, 'from utils import set_directory\n'), ((565, 606), 'mne.pick_types', 'mne.pick_types', (['info'], {'meg': '(True)', 'eeg': '(False)'}), '(info, meg=True, eeg=False)\n', (579, 606), False, 'import mne\n'), ((5586, 5622), 'numpy.zeros', 'np.zeros', ([], {'shape': '(vertno.shape[0], 1)'}), '(shape=(vertno.shape[0], 1))\n', (5594, 5622), True, 'import numpy as np\n'), ((5692, 5801), 'mne.VolSourceEstimate', 'mne.VolSourceEstimate', ([], {'data': 'data_dist', 'vertices': 'vertno', 'tmin': '(0)', 'tstep': "(1 / info['sfreq'])", 'subject': '"""sample"""'}), "(data=data_dist, vertices=vertno, tmin=0, tstep=1 /\n info['sfreq'], subject='sample')\n", (5713, 5801), False, 'import mne\n'), ((5853, 5889), 'numpy.zeros', 'np.zeros', ([], {'shape': '(vertno.shape[0], 1)'}), '(shape=(vertno.shape[0], 1))\n', (5861, 5889), True, 'import numpy as np\n'), ((5959, 6068), 'mne.VolSourceEstimate', 'mne.VolSourceEstimate', ([], {'data': 'data_eval', 'vertices': 'vertno', 'tmin': '(0)', 'tstep': "(1 / info['sfreq'])", 'subject': '"""sample"""'}), "(data=data_eval, vertices=vertno, tmin=0, tstep=1 /\n info['sfreq'], subject='sample')\n", (5980, 6068), False, 'import mne\n'), ((6120, 6156), 'numpy.zeros', 'np.zeros', ([], {'shape': '(vertno.shape[0], 1)'}), '(shape=(vertno.shape[0], 1))\n', (6128, 6156), True, 'import numpy as np\n'), ((6226, 6335), 'mne.VolSourceEstimate', 'mne.VolSourceEstimate', ([], {'data': 'data_corr', 'vertices': 'vertno', 'tmin': '(0)', 'tstep': "(1 / info['sfreq'])", 'subject': '"""sample"""'}), "(data=data_corr, vertices=vertno, tmin=0, tstep=1 /\n info['sfreq'], subject='sample')\n", (6247, 6335), False, 'import mne\n'), ((6386, 6422), 'numpy.zeros', 'np.zeros', ([], {'shape': '(vertno.shape[0], 1)'}), '(shape=(vertno.shape[0], 1))\n', (6394, 6422), True, 'import numpy as np\n'), ((6489, 6597), 'mne.VolSourceEstimate', 'mne.VolSourceEstimate', ([], {'data': 'data_ori', 'vertices': 'vertno', 'tmin': '(0)', 'tstep': "(1 / info['sfreq'])", 'subject': '"""sample"""'}), "(data=data_ori, vertices=vertno, tmin=0, tstep=1 /\n info['sfreq'], subject='sample')\n", (6510, 6597), False, 'import mne\n'), ((6882, 6916), 'os.path.join', 'op.join', (['image_path', 'fn_image_dist'], {}), '(image_path, fn_image_dist)\n', (6889, 6916), True, 'import os.path as op\n'), ((6922, 7257), 'jumeg.jumeg_volume_plotting.plot_vstc_sliced_old', 'plot_vstc_sliced_old', (['vstc_dist', 'vsrc', 'vstc_dist.tstep'], {'subjects_dir': 'fname.subjects_dir', 'time': 'vstc_dist.tmin', 'cut_coords': 'config.cut_coords', 'display_mode': '"""ortho"""', 'figure': 'None', 'axes': 'None', 'colorbar': '(True)', 'cmap': '"""magma_r"""', 'symmetric_cbar': '"""auto"""', 'threshold': '(0)', 'cbar_range': 'cbar_range_dist', 'save': '(True)', 'fname_save': 'fp_image_dist'}), "(vstc_dist, vsrc, vstc_dist.tstep, subjects_dir=fname.\n subjects_dir, time=vstc_dist.tmin, cut_coords=config.cut_coords,\n display_mode='ortho', figure=None, axes=None, colorbar=True, cmap=\n 'magma_r', symmetric_cbar='auto', threshold=0, cbar_range=\n cbar_range_dist, save=True, fname_save=fp_image_dist)\n", (6942, 7257), False, 'from jumeg.jumeg_volume_plotting import plot_vstc_sliced_old\n'), ((7486, 7520), 'os.path.join', 'op.join', (['image_path', 'fn_image_eval'], {}), '(image_path, fn_image_eval)\n', (7493, 7520), True, 'import os.path as op\n'), ((7526, 7858), 'jumeg.jumeg_volume_plotting.plot_vstc_sliced_old', 'plot_vstc_sliced_old', (['vstc_eval', 'vsrc', 'vstc_eval.tstep'], {'subjects_dir': 'fname.subjects_dir', 'time': 'vstc_eval.tmin', 'cut_coords': 'config.cut_coords', 'display_mode': '"""ortho"""', 'figure': 'None', 'axes': 'None', 'colorbar': '(True)', 'cmap': '"""magma"""', 'symmetric_cbar': '"""auto"""', 'threshold': '(0)', 'cbar_range': 'cbar_range_eval', 'save': '(True)', 'fname_save': 'fp_image_eval'}), "(vstc_eval, vsrc, vstc_eval.tstep, subjects_dir=fname.\n subjects_dir, time=vstc_eval.tmin, cut_coords=config.cut_coords,\n display_mode='ortho', figure=None, axes=None, colorbar=True, cmap=\n 'magma', symmetric_cbar='auto', threshold=0, cbar_range=cbar_range_eval,\n save=True, fname_save=fp_image_eval)\n", (7546, 7858), False, 'from jumeg.jumeg_volume_plotting import plot_vstc_sliced_old\n'), ((8088, 8122), 'os.path.join', 'op.join', (['image_path', 'fn_image_corr'], {}), '(image_path, fn_image_corr)\n', (8095, 8122), True, 'import os.path as op\n'), ((8128, 8460), 'jumeg.jumeg_volume_plotting.plot_vstc_sliced_old', 'plot_vstc_sliced_old', (['vstc_corr', 'vsrc', 'vstc_corr.tstep'], {'subjects_dir': 'fname.subjects_dir', 'time': 'vstc_corr.tmin', 'cut_coords': 'config.cut_coords', 'display_mode': '"""ortho"""', 'figure': 'None', 'axes': 'None', 'colorbar': '(True)', 'cmap': '"""magma"""', 'symmetric_cbar': '"""auto"""', 'threshold': '(0)', 'cbar_range': 'cbar_range_corr', 'save': '(True)', 'fname_save': 'fp_image_corr'}), "(vstc_corr, vsrc, vstc_corr.tstep, subjects_dir=fname.\n subjects_dir, time=vstc_corr.tmin, cut_coords=config.cut_coords,\n display_mode='ortho', figure=None, axes=None, colorbar=True, cmap=\n 'magma', symmetric_cbar='auto', threshold=0, cbar_range=cbar_range_corr,\n save=True, fname_save=fp_image_corr)\n", (8148, 8460), False, 'from jumeg.jumeg_volume_plotting import plot_vstc_sliced_old\n'), ((8727, 8760), 'os.path.join', 'op.join', (['image_path', 'fn_image_ori'], {}), '(image_path, fn_image_ori)\n', (8734, 8760), True, 'import os.path as op\n'), ((8770, 9100), 'jumeg.jumeg_volume_plotting.plot_vstc_sliced_old', 'plot_vstc_sliced_old', (['vstc_ori', 'vsrc', 'vstc_ori.tstep'], {'subjects_dir': 'fname.subjects_dir', 'time': 'vstc_ori.tmin', 'cut_coords': 'config.cut_coords', 'display_mode': '"""ortho"""', 'figure': 'None', 'axes': 'None', 'colorbar': '(True)', 'cmap': '"""magma_r"""', 'symmetric_cbar': '"""auto"""', 'threshold': '(0)', 'cbar_range': 'cbar_range_ori', 'save': '(True)', 'fname_save': 'fp_image_ori'}), "(vstc_ori, vsrc, vstc_ori.tstep, subjects_dir=fname.\n subjects_dir, time=vstc_ori.tmin, cut_coords=config.cut_coords,\n display_mode='ortho', figure=None, axes=None, colorbar=True, cmap=\n 'magma_r', symmetric_cbar='auto', threshold=0, cbar_range=\n cbar_range_ori, save=True, fname_save=fp_image_ori)\n", (8790, 9100), False, 'from jumeg.jumeg_volume_plotting import plot_vstc_sliced_old\n'), ((1164, 1208), 'config.fname.lcmv_results', 'fname.lcmv_results', ([], {'vertex': 'vertex', 'noise': '(0.1)'}), '(vertex=vertex, noise=0.1)\n', (1182, 1208), False, 'from config import fname\n'), ((9588, 9624), 'os.path.join', 'op.join', (['image_folder', 'fn_image_dist'], {}), '(image_folder, fn_image_dist)\n', (9595, 9624), True, 'import os.path as op\n'), ((9674, 9710), 'os.path.join', 'op.join', (['image_folder', 'fn_image_eval'], {}), '(image_folder, fn_image_eval)\n', (9681, 9710), True, 'import os.path as op\n'), ((9760, 9796), 'os.path.join', 'op.join', (['image_folder', 'fn_image_corr'], {}), '(image_folder, fn_image_corr)\n', (9767, 9796), True, 'import os.path as op\n'), ((9882, 9917), 'os.path.join', 'op.join', (['image_folder', 'fn_image_ori'], {}), '(image_folder, fn_image_ori)\n', (9889, 9917), True, 'import os.path as op\n')] |
from gym import Env
import gym.spaces
import numpy as np
class DummyEnv(Env):
def __init__(self, image_shape = (64, 64, 3), state_shape=(3,)) -> None:
super().__init__()
self.image_shape = image_shape
self.state_shape = state_shape
self.action_shape = (4,)
self.observation_space = gym.spaces.Dict({
'image': gym.spaces.Box(0, 255, self.image_shape),
'state': gym.spaces.Box(-1, 1, self.state_shape)
})
self.action_space = gym.spaces.Box(-1, 1, self.action_shape)
def step(self, action):
return {
'image': np.zeros(self.image_shape).flatten(),
'state': np.zeros(self.state_shape)
}, 0, 0, {}
def reset(self):
return {
'image': np.zeros(self.image_shape).flatten(),
'state': np.zeros(self.state_shape)
}
| [
"numpy.zeros"
] | [((856, 882), 'numpy.zeros', 'np.zeros', (['self.state_shape'], {}), '(self.state_shape)\n', (864, 882), True, 'import numpy as np\n'), ((690, 716), 'numpy.zeros', 'np.zeros', (['self.state_shape'], {}), '(self.state_shape)\n', (698, 716), True, 'import numpy as np\n'), ((797, 823), 'numpy.zeros', 'np.zeros', (['self.image_shape'], {}), '(self.image_shape)\n', (805, 823), True, 'import numpy as np\n'), ((631, 657), 'numpy.zeros', 'np.zeros', (['self.image_shape'], {}), '(self.image_shape)\n', (639, 657), True, 'import numpy as np\n')] |
import numpy
''''
print(numpy.identity(3)) # 3 is for dimension 3 X 3
print(numpy.eye(8, 7, k=1)) # 8 X 7 Dimensional array with first upper diagonal 1.
'''
numpy.set_printoptions(legacy='1.13')
def process(line):
dimns = numpy.array(line, int)
# dimns = tuple(dimns)
print(numpy.eye(dimns[0], dimns[1], k=0))
if __name__ == "__main__":
line = input().strip().split()
process(line) | [
"numpy.eye",
"numpy.set_printoptions",
"numpy.array"
] | [((166, 203), 'numpy.set_printoptions', 'numpy.set_printoptions', ([], {'legacy': '"""1.13"""'}), "(legacy='1.13')\n", (188, 203), False, 'import numpy\n'), ((236, 258), 'numpy.array', 'numpy.array', (['line', 'int'], {}), '(line, int)\n', (247, 258), False, 'import numpy\n'), ((296, 330), 'numpy.eye', 'numpy.eye', (['dimns[0]', 'dimns[1]'], {'k': '(0)'}), '(dimns[0], dimns[1], k=0)\n', (305, 330), False, 'import numpy\n')] |
import pytest
def test_VerticalCut():
import numpy as np
from qtpy.QtWidgets import QApplication
app = QApplication([])
from xicam.SAXS.operations.verticalcuts import VerticalCutPlugin
t1 = VerticalCutPlugin()
t1.data.value = np.ones((10, 10))
t1.qz.value = np.tile(np.arange(10), (1, 10))
t1.qzminimum.value = 3
t1.qzmaximum.value = 6
t1.evaluate()
assert np.sum(t1.verticalcut.value) == 60
| [
"numpy.sum",
"numpy.ones",
"numpy.arange",
"xicam.SAXS.operations.verticalcuts.VerticalCutPlugin",
"qtpy.QtWidgets.QApplication"
] | [((118, 134), 'qtpy.QtWidgets.QApplication', 'QApplication', (['[]'], {}), '([])\n', (130, 134), False, 'from qtpy.QtWidgets import QApplication\n'), ((213, 232), 'xicam.SAXS.operations.verticalcuts.VerticalCutPlugin', 'VerticalCutPlugin', ([], {}), '()\n', (230, 232), False, 'from xicam.SAXS.operations.verticalcuts import VerticalCutPlugin\n'), ((253, 270), 'numpy.ones', 'np.ones', (['(10, 10)'], {}), '((10, 10))\n', (260, 270), True, 'import numpy as np\n'), ((297, 310), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (306, 310), True, 'import numpy as np\n'), ((404, 432), 'numpy.sum', 'np.sum', (['t1.verticalcut.value'], {}), '(t1.verticalcut.value)\n', (410, 432), True, 'import numpy as np\n')] |
# coding: utf-8
import cv2
from cv2 import aruco
import numpy as np
import math
import yaml
import sys
import os
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.optimize import least_squares
import python_scale_ezxr.lie_algebra as la
from python_scale_ezxr.io_tool import load_board_parameters
from python_scale_ezxr.charuco_detection import *
from python_scale_ezxr.visualization import *
from colmap_process.colmap_read_write_model import *
def umeyama_alignment(x, y, with_scale=False):
"""
R*x + t = y
Computes the least squares solution parameters of an Sim(m) matrix
that minimizes the distance between a set of registered points.
<NAME>: Least-squares estimation of transformation parameters
between two point patterns. IEEE PAMI, 1991
:param x: mxn matrix of points, m = dimension, n = nr. of data points
:param y: mxn matrix of points, m = dimension, n = nr. of data points
:param with_scale: set to True to align also the scale (default: 1.0 scale)
:return: r, t, c - rotation matrix, translation vector and scale factor
"""
if x.shape != y.shape:
print("data matrices must have the same shape")
sys.exit(0)
# m = dimension, n = nr. of data points
m, n = x.shape
# means, eq. 34 and 35
mean_x = x.mean(axis=1)
mean_y = y.mean(axis=1)
# variance, eq. 36
# "transpose" for column subtraction
sigma_x = 1.0 / n * (np.linalg.norm(x - mean_x[:, np.newaxis])**2)
# covariance matrix, eq. 38
outer_sum = np.zeros((m, m))
for i in range(n):
outer_sum += np.outer((y[:, i] - mean_y), (x[:, i] - mean_x))
cov_xy = np.multiply(1.0 / n, outer_sum)
# SVD (text betw. eq. 38 and 39)
u, d, v = np.linalg.svd(cov_xy)
# S matrix, eq. 43
s = np.eye(m)
if np.linalg.det(u) * np.linalg.det(v) < 0.0:
# Ensure a RHS coordinate system (Kabsch algorithm).
s[m - 1, m - 1] = -1
# rotation, eq. 40
r = u.dot(s).dot(v)
# scale & translation, eq. 42 and 41
c = 1 / sigma_x * np.trace(np.diag(d).dot(s)) if with_scale else 1.0
t = mean_y - np.multiply(c, r.dot(mean_x))
return r, t, c
def sim3_transform(xxx, yyy):
'''
umeyama_alignment(x, y, with_scale=False)
算出来的transform是from x to y
'''
# 把colmap的点转到gt,原因是:gt作为参考,不能尺度缩放
r, t, c = umeyama_alignment(xxx, yyy, True)
# 把r,t求逆,让transform是gt到colmap的点
r1 = r.transpose()
t1 = -np.matmul(r1, t.reshape(3,1))
# 把gt转到colmap地图坐标系
yyy_transformed = np.matmul(r1, yyy) + t1.reshape(3,1)
# colmap的点是需要尺度缩放的
xxx_scaled = xxx * c
# 计算误差
delta = xxx_scaled - yyy_transformed
mean_error = np.sum(np.linalg.norm(delta, axis=0)) / xxx.shape[1]
#visual_1
#visualize_pts_3d_two(xxx_scaled.transpose(), yyy_transformed.transpose())
# 注意,这里返回的是gt到colmap坐标系的transform
# 尺度因子则是作用colmap的点,因为它们不是真实尺度
ret = True
if mean_error > 0.015:
ret = False
print('Failed! mean error too big! skip this split_board...')
return ret, mean_error, r1, t1, c
def qvec2rotmat(qvec):
return np.array([
[1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,
2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],
[2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,
2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],
[2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])
def rotmat2qvec(R):
Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
K = np.array([
[Rxx - Ryy - Rzz, 0, 0, 0],
[Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
[Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
[Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0
eigvals, eigvecs = np.linalg.eigh(K)
qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
if qvec[0] < 0:
qvec *= -1
return qvec
def optimize_n_poses_and_scale(init_params, scale):
'''
init_params是个list,每个元素是(rot, trans, colmap_pts, gt_pts)
其中rot * gt_pts + trans = colmap_pts * scale
'''
n_poses = len(init_params)
init_x = np.zeros(n_poses * 7 + 1)
# 最后一位放尺度
init_x[-1] = scale
# 构建符合格式的待优化参数
for i in range(n_poses):
qvec = rotmat2qvec(init_params[i][0])
tvec = init_params[i][1]
init_x[i * 7 + 0] = qvec[0]
init_x[i * 7 + 1] = qvec[1]
init_x[i * 7 + 2] = qvec[2]
init_x[i * 7 + 3] = qvec[3]
init_x[i * 7 + 4] = tvec[0]
init_x[i * 7 + 5] = tvec[1]
init_x[i * 7 + 6] = tvec[2]
# 构建残差函数
# 优化目标是:n个pose和1个scale
# 优化残差是:三维点的平均误差
def residual_function(x):
n_poses = int( ( len(x) - 1 ) / 7 )
sum_error = 0.0
for i in range(n_poses):
qvec = x[i * 7 + 0 : i * 7 + 4]
rotmat = qvec2rotmat(qvec)
tvec = x[i * 7 + 4 : i * 7 + 7]
colmap_pts = init_params[i][2]
gt_pts = init_params[i][3]
colmap_pts_scaled = colmap_pts * x[-1]
gt_pts_transformed = np.matmul(rotmat, gt_pts) + tvec.reshape(3,1)
delta = colmap_pts_scaled - gt_pts_transformed
error = np.sum(np.linalg.norm(delta, axis=0))
sum_error = sum_error + error
return sum_error
print('optimizing...')
res = least_squares(residual_function, init_x, jac='3-point', loss='linear', verbose=1, max_nfev=100000)
return res.x
def compute_scale(match_folders, report_path):
report_file = open(report_path,'w')
#match_folder_names = os.listdir( match_folder )
init_params = []
scale_list = []
txt_name_list = []
report_file.write('----------------------------init scale----------------------------\n')
# subdirs = find_sub_dirs(image_parent_folder)
for match_folder_name in match_folders:
current_folder = match_folder_name + '/'
txt_names = os.listdir( current_folder )
for txt_name in txt_names:
txt_path_name = current_folder + txt_name
match_pts = np.loadtxt(txt_path_name, dtype=float)
xxx = match_pts[0:3, : ]
yyy = match_pts[3:6, : ]
ret, mean_error, rot, trans, scale = sim3_transform(xxx, yyy)
detailed_str = 'board id = ' + txt_name[0:-4] + ', mean error(unit:m) = ' + str(mean_error) + ', point number = '+ str(xxx.shape[1]) + ', scale = ' + str(scale)
report_str = ', failed! '
if ret:
init_params.append( (rot, trans, xxx, yyy) )
scale_list.append(scale)
report_str = ', successful! '
txt_name_list.append(txt_name[0:-4])
report_str = detailed_str + report_str + '\n'
report_file.write(report_str)
if len(scale_list) == 0:
print('failed! no board detected!')
report_file.close()
return -1
# 对scale进行分析
scale_list = np.array(scale_list)
scale_mean = np.mean(scale_list)
scale_std = np.std(scale_list)
report_str = 'scale mean = '+ str(scale_mean) + ', std = ' + str(scale_std) + '\n'
report_file.write(report_str)
report_file.close()
return scale_mean
'''
report_file = open(report_path,'a')
report_file.write('----------------------------opt scale----------------------------\n')
opt_x = optimize_n_poses_and_scale(init_params, scale_mean)
# 二次验证优化结果要比线性结果好
print('opted scale = ', opt_x[-1])
for i in range(len(init_params)):
qvec = opt_x[i * 7 + 0 : i * 7 + 4]
rotmat = qvec2rotmat(qvec)
tvec = opt_x[i * 7 + 4 : i * 7 + 7]
colmap_pts = init_params[i][2]
gt_pts = init_params[i][3]
colmap_pts_scaled = colmap_pts * opt_x[-1]
gt_pts_transformed = np.matmul(rotmat, gt_pts) + tvec.reshape(3,1)
delta = colmap_pts_scaled - gt_pts_transformed
mean_error = np.sum(np.linalg.norm(delta, axis=0)) / gt_pts.shape[1]
detailed_str = 'board id = ' + txt_name_list[i] + ', mean error(unit:m) = ' + str(mean_error) + ', point number = ' + str(gt_pts.shape[1]) + '\n'
report_file.write(detailed_str)
print(detailed_str)
scale_str = 'opted scale = ' + str(opt_x[-1]) + '\n'
print(scale_str)
report_file.write(scale_str)
report_file.close()
return opt_x[-1]
'''
def main():
if len(sys.argv) != 2:
print('scale_restoration [path to colmap project folder].')
return
match_folder = sys.argv[1] + '/images_charuco/match/'
report_path_name = sys.argv[1] + '/images_charuco/report.txt'
report_file = open(report_path_name,'w')
match_folder_names = os.listdir( match_folder )
init_params = []
scale_list = []
txt_name_list = []
report_file.write('----------------------------init scale----------------------------\n')
for match_folder_name in match_folder_names:
current_folder = match_folder + match_folder_name + '/'
txt_names = os.listdir( current_folder )
for txt_name in txt_names:
txt_path_name = current_folder + txt_name
match_pts = np.loadtxt(txt_path_name, dtype=float)
xxx = match_pts[0:3, : ]
yyy = match_pts[3:6, : ]
ret, mean_error, rot, trans, scale = sim3_transform(xxx, yyy)
detailed_str = 'board id = ' + txt_name[0:-4] + ', mean error(unit:m) = ' + str(mean_error) + ', point number = '+ str(xxx.shape[1]) + ', scale = ' + str(scale)
report_str = ', failed! '
if ret:
init_params.append( (rot, trans, xxx, yyy) )
scale_list.append(scale)
report_str = ', successful! '
txt_name_list.append(txt_name[0:-4])
report_str = detailed_str + report_str + '\n'
report_file.write(report_str)
if len(scale_list) == 0:
print('failed! no board detected!')
report_file.close()
return
# 对scale进行分析
scale_list = np.array(scale_list)
scale_mean = np.mean(scale_list)
scale_std = np.std(scale_list)
report_str = 'scale mean = '+ str(scale_mean) + ', std = ' + str(scale_std) + '\n'
report_file.write(report_str)
report_file.close()
report_file = open(report_path_name,'a')
report_file.write('----------------------------opt scale----------------------------\n')
opt_x = optimize_n_poses_and_scale(init_params, scale_mean)
# 二次验证优化结果要比线性结果好
print('opted scale = ', opt_x[-1])
for i in range(len(init_params)):
qvec = opt_x[i * 7 + 0 : i * 7 + 4]
rotmat = read_write_model.qvec2rotmat(qvec)
tvec = opt_x[i * 7 + 4 : i * 7 + 7]
colmap_pts = init_params[i][2]
gt_pts = init_params[i][3]
colmap_pts_scaled = colmap_pts * opt_x[-1]
gt_pts_transformed = np.matmul(rotmat, gt_pts) + tvec.reshape(3,1)
delta = colmap_pts_scaled - gt_pts_transformed
mean_error = np.sum(np.linalg.norm(delta, axis=0)) / gt_pts.shape[1]
detailed_str = 'board id = ' + txt_name_list[i] + ', mean error(unit:m) = ' + str(mean_error) + ', point number = ' + str(gt_pts.shape[1]) + '\n'
report_file.write(detailed_str)
print(detailed_str)
scale_str = 'opted scale = ' + str(opt_x[-1]) + '\n'
print(scale_str)
report_file.write(scale_str)
report_file.close()
print('All done!')
if __name__ == '__main__':
main()
| [
"numpy.diag",
"numpy.outer",
"numpy.multiply",
"numpy.argmax",
"numpy.std",
"numpy.zeros",
"numpy.linalg.eigh",
"scipy.optimize.least_squares",
"numpy.linalg.svd",
"numpy.array",
"numpy.mean",
"numpy.matmul",
"numpy.linalg.norm",
"numpy.linalg.det",
"numpy.eye",
"numpy.loadtxt",
"os.... | [((1575, 1591), 'numpy.zeros', 'np.zeros', (['(m, m)'], {}), '((m, m))\n', (1583, 1591), True, 'import numpy as np\n'), ((1698, 1729), 'numpy.multiply', 'np.multiply', (['(1.0 / n)', 'outer_sum'], {}), '(1.0 / n, outer_sum)\n', (1709, 1729), True, 'import numpy as np\n'), ((1782, 1803), 'numpy.linalg.svd', 'np.linalg.svd', (['cov_xy'], {}), '(cov_xy)\n', (1795, 1803), True, 'import numpy as np\n'), ((1836, 1845), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (1842, 1845), True, 'import numpy as np\n'), ((3146, 3588), 'numpy.array', 'np.array', (['[[1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2, 2 * qvec[1] * qvec[2] - 2 * qvec\n [0] * qvec[3], 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]], [2 *\n qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3], 1 - 2 * qvec[1] ** 2 - 2 * \n qvec[3] ** 2, 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]], [2 * qvec\n [3] * qvec[1] - 2 * qvec[0] * qvec[2], 2 * qvec[2] * qvec[3] + 2 * qvec\n [0] * qvec[1], 1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2]]'], {}), '([[1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2, 2 * qvec[1] * qvec[2] -\n 2 * qvec[0] * qvec[3], 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],\n [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3], 1 - 2 * qvec[1] ** 2 - \n 2 * qvec[3] ** 2, 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]], [2 *\n qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2], 2 * qvec[2] * qvec[3] + 2 *\n qvec[0] * qvec[1], 1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2]])\n', (3154, 3588), True, 'import numpy as np\n'), ((3955, 3972), 'numpy.linalg.eigh', 'np.linalg.eigh', (['K'], {}), '(K)\n', (3969, 3972), True, 'import numpy as np\n'), ((4302, 4327), 'numpy.zeros', 'np.zeros', (['(n_poses * 7 + 1)'], {}), '(n_poses * 7 + 1)\n', (4310, 4327), True, 'import numpy as np\n'), ((5496, 5598), 'scipy.optimize.least_squares', 'least_squares', (['residual_function', 'init_x'], {'jac': '"""3-point"""', 'loss': '"""linear"""', 'verbose': '(1)', 'max_nfev': '(100000)'}), "(residual_function, init_x, jac='3-point', loss='linear',\n verbose=1, max_nfev=100000)\n", (5509, 5598), False, 'from scipy.optimize import least_squares\n'), ((7088, 7108), 'numpy.array', 'np.array', (['scale_list'], {}), '(scale_list)\n', (7096, 7108), True, 'import numpy as np\n'), ((7126, 7145), 'numpy.mean', 'np.mean', (['scale_list'], {}), '(scale_list)\n', (7133, 7145), True, 'import numpy as np\n'), ((7162, 7180), 'numpy.std', 'np.std', (['scale_list'], {}), '(scale_list)\n', (7168, 7180), True, 'import numpy as np\n'), ((8810, 8834), 'os.listdir', 'os.listdir', (['match_folder'], {}), '(match_folder)\n', (8820, 8834), False, 'import os\n'), ((10139, 10159), 'numpy.array', 'np.array', (['scale_list'], {}), '(scale_list)\n', (10147, 10159), True, 'import numpy as np\n'), ((10177, 10196), 'numpy.mean', 'np.mean', (['scale_list'], {}), '(scale_list)\n', (10184, 10196), True, 'import numpy as np\n'), ((10213, 10231), 'numpy.std', 'np.std', (['scale_list'], {}), '(scale_list)\n', (10219, 10231), True, 'import numpy as np\n'), ((1230, 1241), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1238, 1241), False, 'import sys\n'), ((1636, 1680), 'numpy.outer', 'np.outer', (['(y[:, i] - mean_y)', '(x[:, i] - mean_x)'], {}), '(y[:, i] - mean_y, x[:, i] - mean_x)\n', (1644, 1680), True, 'import numpy as np\n'), ((2569, 2587), 'numpy.matmul', 'np.matmul', (['r1', 'yyy'], {}), '(r1, yyy)\n', (2578, 2587), True, 'import numpy as np\n'), ((3722, 3901), 'numpy.array', 'np.array', (['[[Rxx - Ryy - Rzz, 0, 0, 0], [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0], [Rzx + Rxz,\n Rzy + Ryz, Rzz - Rxx - Ryy, 0], [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx +\n Ryy + Rzz]]'], {}), '([[Rxx - Ryy - Rzz, 0, 0, 0], [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0], [\n Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0], [Ryz - Rzy, Rzx - Rxz, Rxy -\n Ryx, Rxx + Ryy + Rzz]])\n', (3730, 3901), True, 'import numpy as np\n'), ((6074, 6100), 'os.listdir', 'os.listdir', (['current_folder'], {}), '(current_folder)\n', (6084, 6100), False, 'import os\n'), ((9128, 9154), 'os.listdir', 'os.listdir', (['current_folder'], {}), '(current_folder)\n', (9138, 9154), False, 'import os\n'), ((1480, 1521), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - mean_x[:, np.newaxis])'], {}), '(x - mean_x[:, np.newaxis])\n', (1494, 1521), True, 'import numpy as np\n'), ((1853, 1869), 'numpy.linalg.det', 'np.linalg.det', (['u'], {}), '(u)\n', (1866, 1869), True, 'import numpy as np\n'), ((1872, 1888), 'numpy.linalg.det', 'np.linalg.det', (['v'], {}), '(v)\n', (1885, 1888), True, 'import numpy as np\n'), ((2730, 2759), 'numpy.linalg.norm', 'np.linalg.norm', (['delta'], {'axis': '(0)'}), '(delta, axis=0)\n', (2744, 2759), True, 'import numpy as np\n'), ((4006, 4024), 'numpy.argmax', 'np.argmax', (['eigvals'], {}), '(eigvals)\n', (4015, 4024), True, 'import numpy as np\n'), ((6216, 6254), 'numpy.loadtxt', 'np.loadtxt', (['txt_path_name'], {'dtype': 'float'}), '(txt_path_name, dtype=float)\n', (6226, 6254), True, 'import numpy as np\n'), ((9270, 9308), 'numpy.loadtxt', 'np.loadtxt', (['txt_path_name'], {'dtype': 'float'}), '(txt_path_name, dtype=float)\n', (9280, 9308), True, 'import numpy as np\n'), ((10972, 10997), 'numpy.matmul', 'np.matmul', (['rotmat', 'gt_pts'], {}), '(rotmat, gt_pts)\n', (10981, 10997), True, 'import numpy as np\n'), ((5229, 5254), 'numpy.matmul', 'np.matmul', (['rotmat', 'gt_pts'], {}), '(rotmat, gt_pts)\n', (5238, 5254), True, 'import numpy as np\n'), ((5361, 5390), 'numpy.linalg.norm', 'np.linalg.norm', (['delta'], {'axis': '(0)'}), '(delta, axis=0)\n', (5375, 5390), True, 'import numpy as np\n'), ((11101, 11130), 'numpy.linalg.norm', 'np.linalg.norm', (['delta'], {'axis': '(0)'}), '(delta, axis=0)\n', (11115, 11130), True, 'import numpy as np\n'), ((2107, 2117), 'numpy.diag', 'np.diag', (['d'], {}), '(d)\n', (2114, 2117), True, 'import numpy as np\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import multiprocessing
import numpy as np
import tensorflow as tf
tf1 = tf.compat.v1
from tflib.data.dataset import batch_dataset, Dataset
_N_CPU = multiprocessing.cpu_count()
def memory_data_batch_dataset(memory_data_dict,
batch_size,
prefetch_batch=_N_CPU + 1,
drop_remainder=True,
filter=None,
map_func=None,
num_threads=_N_CPU,
shuffle=True,
shuffle_buffer_size=None,
repeat=-1):
"""Memory data batch dataset.
`memory_data_dict` example:
{'img': img_ndarray, 'label': label_ndarray} or
{'img': img_tftensor, 'label': label_tftensor}
* The value of each item of `memory_data_dict` is in shape of (N, ...).
"""
dataset = tf1.data.Dataset.from_tensor_slices(memory_data_dict)
dataset = batch_dataset(dataset,
batch_size,
prefetch_batch,
drop_remainder,
filter,
map_func,
num_threads,
shuffle,
shuffle_buffer_size,
repeat)
return dataset
class MemoryData(Dataset):
"""MemoryData.
`memory_data_dict` example:
{'img': img_ndarray, 'label': label_ndarray} or
{'img': img_tftensor, 'label': label_tftensor}
* The value of each item of `memory_data_dict` is in shape of (N, ...).
"""
def __init__(self,
memory_data_dict,
batch_size,
prefetch_batch=_N_CPU + 1,
drop_remainder=True,
filter=None,
map_func=None,
num_threads=_N_CPU,
shuffle=True,
shuffle_buffer_size=None,
repeat=-1,
sess=None):
super(MemoryData, self).__init__()
dataset = memory_data_batch_dataset(memory_data_dict,
batch_size,
prefetch_batch,
drop_remainder,
filter,
map_func,
num_threads,
shuffle,
shuffle_buffer_size,
repeat)
self._bulid(dataset, sess)
if isinstance(list(memory_data_dict.values())[0], np.ndarray):
self._n_data = len(list(memory_data_dict.values())[0])
else:
self._n_data = list(memory_data_dict.values())[0].get_shape().as_list()[0]
def __len__(self):
return self._n_data
if __name__ == '__main__':
data = {'a': np.array([1.0, 2, 3, 4, 5]),
'b': np.array([[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6]])}
def filter(x):
return tf1.cond(x['a'] > 2, lambda: tf1.constant(True), lambda: tf1.constant(False))
def map_func(x):
x['a'] = x['a'] * 10
return x
# tf1.enable_eager_execution()
s = tf1.Session()
dataset = MemoryData(data,
2,
filter=None,
map_func=map_func,
shuffle=True,
shuffle_buffer_size=None,
drop_remainder=True,
repeat=4,
sess=s)
for i in range(5):
print(map(dataset.get_next().__getitem__, ['b', 'a']))
print([n.name for n in tf1.get_default_graph().as_graph_def().node])
| [
"tflib.data.dataset.batch_dataset",
"numpy.array",
"multiprocessing.cpu_count"
] | [((262, 289), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (287, 289), False, 'import multiprocessing\n'), ((1118, 1257), 'tflib.data.dataset.batch_dataset', 'batch_dataset', (['dataset', 'batch_size', 'prefetch_batch', 'drop_remainder', 'filter', 'map_func', 'num_threads', 'shuffle', 'shuffle_buffer_size', 'repeat'], {}), '(dataset, batch_size, prefetch_batch, drop_remainder, filter,\n map_func, num_threads, shuffle, shuffle_buffer_size, repeat)\n', (1131, 1257), False, 'from tflib.data.dataset import batch_dataset, Dataset\n'), ((3190, 3217), 'numpy.array', 'np.array', (['[1.0, 2, 3, 4, 5]'], {}), '([1.0, 2, 3, 4, 5])\n', (3198, 3217), True, 'import numpy as np\n'), ((3236, 3286), 'numpy.array', 'np.array', (['[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]'], {}), '([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])\n', (3244, 3286), True, 'import numpy as np\n')] |
# Import Required Modules
import os
import json
import random
import numpy as np
from skimage.io import imshow
import matplotlib.pyplot as plt
import keras.callbacks as callbacks
from Mask_Integer_Encoding import RGBs_to_Integers
##############################################################################
hight, width, channel, patch_size = 224, 224, 3, 224
input_shape = (hight, width, channel)
def color_label(img, id2code):
rows, cols = img.shape
result = np.zeros((rows, cols, 3), 'uint8')
for j in range(rows):
for k in range(cols):
result[j, k] = id2code[img[j, k]]
return result
rand_height = random.randint(0, hight - patch_size)
rand_width = random.randint(0, width - patch_size)
class WeightVisualizerCallback(callbacks.Callback):
# def __init__(self, images, masks, figsize=None, mask_decoding_func=None):
def __init__(self, images, masks, figPath, figPath2, jsonPath, H, W, patch_size, figsize, startAt =0 ):
super(WeightVisualizerCallback, self).__init__()
assert images.shape[:-1] == masks.shape[:-1]
if isinstance(figsize, int):
figsize = (figsize, figsize)
if figsize is None:
figsize = tuple(images.shape[1:3])
# if mask_decoding_func is None:
# mask_decoding_func = identity
self.figsize = figsize
self.images = images
self.masks = masks
self.figPath = figPath
self.figPath2 = figPath2
self.jsonPath = jsonPath
self.startAt = startAt
self.rand_height = random.randint(0, H - patch_size)
self.rand_width = random.randint(0, W - patch_size)
self.patch_size = patch_size
self.image_patch = images[0, 0:self.patch_size, 0:self.patch_size, :]
self.mask_patch = masks[0, 0:self.patch_size, 0:self.patch_size, :]
print(self.image_patch.shape)
print(self.mask_patch.shape)
def on_train_begin(self, logs={}):
self.H = {}
if self.jsonPath is not None:
if os.path.exists(self.jsonPath):
self.H = json.loads(open(self.jsonPath).read())
if self.startAt > 0:
for k in self.H.keys():
self.H[k] = self.H[k][:self.startAt]
def on_epoch_end(self, epoch, logs={}):
predicted_masks_1 = self.model.predict(np.expand_dims(self.image_patch, 0), 1)
input_shape = (hight, width, channel)
predicted_masks = np.argmax(predicted_masks_1, axis=-1) # int64 (1, 65536)
outcome = np.resize(predicted_masks, (input_shape[0], input_shape[1])) # unit8 (256, 256)
Mask_RGBs, Mask_Regions, RGBs_to_Integer = RGBs_to_Integers('.../.../Mask_Labels.txt')
print(list(zip(Mask_RGBs, Mask_Regions)))
Integers_to_RGBs = {val: key for (key, val) in RGBs_to_Integer.items()}
outcome = color_label(outcome, Integers_to_RGBs) # unit8 (256, 256, 3) --> Final Image
print('Image')
imshow(self.image_patch)
plt.show()
print('Mask')
imshow(self.mask_patch)
plt.show()
print('Predicted_Mask')
imshow(outcome)
plt.show()
for (k,v) in logs.items():
l = self.H.get(k, [])
l.append(v)
self.H[k] = l
if self.jsonPath is not None:
f = open(self.jsonPath, "w")
f.write(json.dumps(self.H))
f.close()
if len(self.H["loss"]) > 1:
N = np.arange(0, len(self.H["loss"]))
plt.style.use("ggplot")
plt.figure()
plt.plot(N, self.H["loss"], label = "Train_Loss")
plt.plot(N, self.H["val_loss"], label = "Validation_Loss")
plt.title("Training & Validation Loss [Epoch {}]".format(len(self.H["loss"])))
plt.xlabel("Epoch #")
plt.ylabel("Loss")
plt.legend()
plt.savefig(self.figPath)
plt.close()
plt.style.use("ggplot")
plt.figure()
plt.plot(N, self.H["acc"], label = "Train_Accuracy")
plt.plot(N, self.H["val_acc"], label = "Validation_Accuracy")
plt.title("Training & Validation Accuracy [Epoch {}]".format(len(self.H["loss"])))
plt.xlabel("Epoch #")
plt.ylabel("Accuracy")
plt.legend()
plt.savefig(self.figPath2)
plt.close()
| [
"Mask_Integer_Encoding.RGBs_to_Integers",
"matplotlib.pyplot.show",
"random.randint",
"numpy.resize",
"numpy.argmax",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"numpy.zeros",
"os.path.exists",
"numpy.expand_dims",
"json.dumps",
"matplotlib.pyplot.style.... | [((649, 686), 'random.randint', 'random.randint', (['(0)', '(hight - patch_size)'], {}), '(0, hight - patch_size)\n', (663, 686), False, 'import random\n'), ((700, 737), 'random.randint', 'random.randint', (['(0)', '(width - patch_size)'], {}), '(0, width - patch_size)\n', (714, 737), False, 'import random\n'), ((478, 512), 'numpy.zeros', 'np.zeros', (['(rows, cols, 3)', '"""uint8"""'], {}), "((rows, cols, 3), 'uint8')\n", (486, 512), True, 'import numpy as np\n'), ((1577, 1610), 'random.randint', 'random.randint', (['(0)', '(H - patch_size)'], {}), '(0, H - patch_size)\n', (1591, 1610), False, 'import random\n'), ((1637, 1670), 'random.randint', 'random.randint', (['(0)', '(W - patch_size)'], {}), '(0, W - patch_size)\n', (1651, 1670), False, 'import random\n'), ((2563, 2600), 'numpy.argmax', 'np.argmax', (['predicted_masks_1'], {'axis': '(-1)'}), '(predicted_masks_1, axis=-1)\n', (2572, 2600), True, 'import numpy as np\n'), ((2659, 2719), 'numpy.resize', 'np.resize', (['predicted_masks', '(input_shape[0], input_shape[1])'], {}), '(predicted_masks, (input_shape[0], input_shape[1]))\n', (2668, 2719), True, 'import numpy as np\n'), ((2796, 2839), 'Mask_Integer_Encoding.RGBs_to_Integers', 'RGBs_to_Integers', (['""".../.../Mask_Labels.txt"""'], {}), "('.../.../Mask_Labels.txt')\n", (2812, 2839), False, 'from Mask_Integer_Encoding import RGBs_to_Integers\n'), ((3152, 3176), 'skimage.io.imshow', 'imshow', (['self.image_patch'], {}), '(self.image_patch)\n', (3158, 3176), False, 'from skimage.io import imshow\n'), ((3185, 3195), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3193, 3195), True, 'import matplotlib.pyplot as plt\n'), ((3235, 3258), 'skimage.io.imshow', 'imshow', (['self.mask_patch'], {}), '(self.mask_patch)\n', (3241, 3258), False, 'from skimage.io import imshow\n'), ((3267, 3277), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3275, 3277), True, 'import matplotlib.pyplot as plt\n'), ((3327, 3342), 'skimage.io.imshow', 'imshow', (['outcome'], {}), '(outcome)\n', (3333, 3342), False, 'from skimage.io import imshow\n'), ((3351, 3361), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3359, 3361), True, 'import matplotlib.pyplot as plt\n'), ((2085, 2114), 'os.path.exists', 'os.path.exists', (['self.jsonPath'], {}), '(self.jsonPath)\n', (2099, 2114), False, 'import os\n'), ((2441, 2476), 'numpy.expand_dims', 'np.expand_dims', (['self.image_patch', '(0)'], {}), '(self.image_patch, 0)\n', (2455, 2476), True, 'import numpy as np\n'), ((3777, 3800), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (3790, 3800), True, 'import matplotlib.pyplot as plt\n'), ((3813, 3825), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3823, 3825), True, 'import matplotlib.pyplot as plt\n'), ((3838, 3885), 'matplotlib.pyplot.plot', 'plt.plot', (['N', "self.H['loss']"], {'label': '"""Train_Loss"""'}), "(N, self.H['loss'], label='Train_Loss')\n", (3846, 3885), True, 'import matplotlib.pyplot as plt\n'), ((3900, 3956), 'matplotlib.pyplot.plot', 'plt.plot', (['N', "self.H['val_loss']"], {'label': '"""Validation_Loss"""'}), "(N, self.H['val_loss'], label='Validation_Loss')\n", (3908, 3956), True, 'import matplotlib.pyplot as plt\n'), ((4063, 4084), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch #"""'], {}), "('Epoch #')\n", (4073, 4084), True, 'import matplotlib.pyplot as plt\n'), ((4097, 4115), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (4107, 4115), True, 'import matplotlib.pyplot as plt\n'), ((4128, 4140), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4138, 4140), True, 'import matplotlib.pyplot as plt\n'), ((4166, 4191), 'matplotlib.pyplot.savefig', 'plt.savefig', (['self.figPath'], {}), '(self.figPath)\n', (4177, 4191), True, 'import matplotlib.pyplot as plt\n'), ((4204, 4215), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4213, 4215), True, 'import matplotlib.pyplot as plt\n'), ((4241, 4264), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (4254, 4264), True, 'import matplotlib.pyplot as plt\n'), ((4277, 4289), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4287, 4289), True, 'import matplotlib.pyplot as plt\n'), ((4302, 4352), 'matplotlib.pyplot.plot', 'plt.plot', (['N', "self.H['acc']"], {'label': '"""Train_Accuracy"""'}), "(N, self.H['acc'], label='Train_Accuracy')\n", (4310, 4352), True, 'import matplotlib.pyplot as plt\n'), ((4367, 4426), 'matplotlib.pyplot.plot', 'plt.plot', (['N', "self.H['val_acc']"], {'label': '"""Validation_Accuracy"""'}), "(N, self.H['val_acc'], label='Validation_Accuracy')\n", (4375, 4426), True, 'import matplotlib.pyplot as plt\n'), ((4536, 4557), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch #"""'], {}), "('Epoch #')\n", (4546, 4557), True, 'import matplotlib.pyplot as plt\n'), ((4570, 4592), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (4580, 4592), True, 'import matplotlib.pyplot as plt\n'), ((4605, 4617), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4615, 4617), True, 'import matplotlib.pyplot as plt\n'), ((4643, 4669), 'matplotlib.pyplot.savefig', 'plt.savefig', (['self.figPath2'], {}), '(self.figPath2)\n', (4654, 4669), True, 'import matplotlib.pyplot as plt\n'), ((4682, 4693), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4691, 4693), True, 'import matplotlib.pyplot as plt\n'), ((3602, 3620), 'json.dumps', 'json.dumps', (['self.H'], {}), '(self.H)\n', (3612, 3620), False, 'import json\n')] |
import numpy as np
from numpy.random import uniform, randn
import matplotlib.pyplot as plt
from scipy import stats
def create_uniform_particles(x_range, y_range, heading_range, N):
particles = np.empty((N, 3))
particles[:, 0] = uniform(x_range[0], x_range[1], size=N)
particles[:, 1] = uniform(y_range[0], y_range[1], size=N)
particles[:, 2] = uniform(heading_range[0], heading_range[1], size=N)
particles[:, 2] %= 2 * np.pi
return particles
def create_gaussian_particles(mean, std, N):
particles = np.empty((N, 3))
particles[:, 0] = mean[0] + (randn(N) * std[0])
particles[:, 1] = mean[1] + (randn(N) * std[1])
particles[:, 2] = mean[2] + (randn(N) * std[2])
particles[:, 2] %= 2 * np.pi
return particles
def predict(particles, u, std, dt=1.):
"""
Moving according to the control input u=[heading change, velocity].
With noise Q (std heading change, std velocity change)
:param particles:
:param u:u[heading, velocity].
:param std:
:param dt: delta time.
:return:
"""
N = len(particles)
# predict heading with normal distribution.
particles[:, 2] = u[0] + (randn(N) * std[0])
particles[:, 2] %= 2 * np.pi
# update x, y axis.
dist = u[1] * dt + (randn(N) * std[1])
particles[:, 0] += dist * np.cos(particles[:, 2])
particles[:, 1] += dist * np.sin(particles[:, 2])
def update(particles, weights, z, R, landmarks):
"""
Update the weights according to the measurements.
P(x/z)=P(z/x)*P(x). P(x) prior of each particles' position, P(z/x) likelihood, how well the particles matched the
measurements. So, using the pdf to measure the matched confidence.
:param particles:
:param weights:
:param z:
:param R:
:param landmarks:
:return:
"""
for i, landmark in enumerate(landmarks):
distance = np.linalg.norm(particles[:, 0:2] - landmark, axis=1)
weights *= stats.norm(distance, R).pdf(z[i])
weights += 1e-300
weights /= sum(weights)
def estimate(particles, weights):
pos = particles[:, 0:2]
mean = np.average(pos, weights=weights, axis=0)
var = np.average((pos - mean) ** 2, weights=weights, axis=0)
return mean, var
# If we don't have new measurements, then, resampling.
def neff(weights):
return 1. / np.sum(np.square(weights))
def systematic_resampling(weights):
N = len(weights)
# Partition the weights into N subdivisions with a constant value/offset.
position = (np.arange(N) + np.random.random()) / N
indexes = np.zeros(N, 'i') # int
cumulative = np.cumsum(weights)
i, j = 0, 0
while i < N:
if position[i] < cumulative[j]:
indexes[i] = j
i += 1
else:
j += 1
return indexes
def resample_from_indexes(particles, weights, indexes):
particles[:] = particles[indexes]
weights.resize(len(particles))
weights.fill(1.0 / len(weights))
def run_particle_filter(N, iters=18, sensor_std_err=0.1, do_plot=True, plot_particles=False,
xlim=(0, 20), ylim=(0, 20), initial_x=None):
landmarks = np.array([[-1, 2], [5, 10], [12, 14], [18, 21]])
num_landmarks = len(landmarks)
plt.figure()
# create particles and weights.
if initial_x is not None:
particles = create_gaussian_particles(mean=initial_x, std=(5, 5, np.pi / 4), N=N)
else:
particles = create_uniform_particles(xlim, ylim, (0, 2 * np.pi), N)
weights = np.ones(N) / N
if plot_particles:
alpha = 0.20
if N > 5000:
alpha *= np.sqrt(5000) / np.sqrt(N)
plt.scatter(particles[:, 0], particles[:, 1],
alpha=alpha, color='g')
xs = []
robot_pos = np.array([0.0, 0.0])
for x in range(iters):
robot_pos += (1., 1.)
# distance from the robot to the each landmarks.
# this could be the measurement of the sensors to the robot.
zs = (np.linalg.norm(landmarks - robot_pos, axis=1) + (np.random.randn(num_landmarks) * sensor_std_err))
# move diagonally forward to (x+1, y+1), so, heading is pi/4, radius=1.414
# predict the particles position according to the given direction and move.
predict(particles, u=(0.78539, 1.414), std=(0.5, 0.5))
# weights.fill(1.0/len(weights))
# incorporate measurements, update the weights.
update(particles, weights, zs, R=sensor_std_err, landmarks=landmarks)
# resample if too few effective particles.
if neff(weights) < N / 2:
indexs = systematic_resampling(weights)
resample_from_indexes(particles, weights, indexs)
assert np.allclose(weights, 1 / N)
mu, var = estimate(particles, weights)
xs.append(mu)
if plot_particles:
plt.scatter(particles[:, 0], particles[:, 1], color='k', marker=',', s=1)
p1 = plt.scatter(robot_pos[0], robot_pos[1], color='k', marker='+', s=180, lw=3)
p2 = plt.scatter(mu[0], mu[1], marker='s', color='r')
xs = np.array(xs)
plt.legend([p1, p2], ['Actual', 'PF'], loc=4, numpoints=1)
plt.xlim(*xlim)
plt.ylim(*ylim)
print('final posisiton error, variance: \n\t', mu - np.array([iters, iters]), var)
plt.show()
if __name__ == '__main__':
from numpy.random import seed
# particles2 = np.array([0.1, 0.2, 0.2, 0.03, 0.1, 0.37])
# weights2 = np.array([0.1, 0.2, 0.2, 0.03, 0.1, 0.37])
# indexes2 = systematic_resampling(weights2)
# print(indexes2)
# resample_from_indexes(particles2, weights2, indexes2)
#
# particles1 = np.array([0.1, 0.2, 0.2, 0.03, 0.1, 0.37])
# weights1 = np.array([0.1, 0.2, 0.2, 0.03, 0.1, 0.37])
seed(4)
run_particle_filter(N=5000, plot_particles=False)
| [
"numpy.random.seed",
"numpy.empty",
"numpy.allclose",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.linalg.norm",
"numpy.arange",
"scipy.stats.norm",
"numpy.random.randn",
"numpy.cumsum",
"numpy.average",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylim",
"matplotlib.pyp... | [((199, 215), 'numpy.empty', 'np.empty', (['(N, 3)'], {}), '((N, 3))\n', (207, 215), True, 'import numpy as np\n'), ((238, 277), 'numpy.random.uniform', 'uniform', (['x_range[0]', 'x_range[1]'], {'size': 'N'}), '(x_range[0], x_range[1], size=N)\n', (245, 277), False, 'from numpy.random import uniform, randn\n'), ((300, 339), 'numpy.random.uniform', 'uniform', (['y_range[0]', 'y_range[1]'], {'size': 'N'}), '(y_range[0], y_range[1], size=N)\n', (307, 339), False, 'from numpy.random import uniform, randn\n'), ((362, 413), 'numpy.random.uniform', 'uniform', (['heading_range[0]', 'heading_range[1]'], {'size': 'N'}), '(heading_range[0], heading_range[1], size=N)\n', (369, 413), False, 'from numpy.random import uniform, randn\n'), ((531, 547), 'numpy.empty', 'np.empty', (['(N, 3)'], {}), '((N, 3))\n', (539, 547), True, 'import numpy as np\n'), ((2099, 2139), 'numpy.average', 'np.average', (['pos'], {'weights': 'weights', 'axis': '(0)'}), '(pos, weights=weights, axis=0)\n', (2109, 2139), True, 'import numpy as np\n'), ((2150, 2204), 'numpy.average', 'np.average', (['((pos - mean) ** 2)'], {'weights': 'weights', 'axis': '(0)'}), '((pos - mean) ** 2, weights=weights, axis=0)\n', (2160, 2204), True, 'import numpy as np\n'), ((2551, 2567), 'numpy.zeros', 'np.zeros', (['N', '"""i"""'], {}), "(N, 'i')\n", (2559, 2567), True, 'import numpy as np\n'), ((2592, 2610), 'numpy.cumsum', 'np.cumsum', (['weights'], {}), '(weights)\n', (2601, 2610), True, 'import numpy as np\n'), ((3130, 3178), 'numpy.array', 'np.array', (['[[-1, 2], [5, 10], [12, 14], [18, 21]]'], {}), '([[-1, 2], [5, 10], [12, 14], [18, 21]])\n', (3138, 3178), True, 'import numpy as np\n'), ((3218, 3230), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3228, 3230), True, 'import matplotlib.pyplot as plt\n'), ((3744, 3764), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (3752, 3764), True, 'import numpy as np\n'), ((5059, 5071), 'numpy.array', 'np.array', (['xs'], {}), '(xs)\n', (5067, 5071), True, 'import numpy as np\n'), ((5076, 5134), 'matplotlib.pyplot.legend', 'plt.legend', (['[p1, p2]', "['Actual', 'PF']"], {'loc': '(4)', 'numpoints': '(1)'}), "([p1, p2], ['Actual', 'PF'], loc=4, numpoints=1)\n", (5086, 5134), True, 'import matplotlib.pyplot as plt\n'), ((5139, 5154), 'matplotlib.pyplot.xlim', 'plt.xlim', (['*xlim'], {}), '(*xlim)\n', (5147, 5154), True, 'import matplotlib.pyplot as plt\n'), ((5159, 5174), 'matplotlib.pyplot.ylim', 'plt.ylim', (['*ylim'], {}), '(*ylim)\n', (5167, 5174), True, 'import matplotlib.pyplot as plt\n'), ((5266, 5276), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5274, 5276), True, 'import matplotlib.pyplot as plt\n'), ((5727, 5734), 'numpy.random.seed', 'seed', (['(4)'], {}), '(4)\n', (5731, 5734), False, 'from numpy.random import seed\n'), ((1311, 1334), 'numpy.cos', 'np.cos', (['particles[:, 2]'], {}), '(particles[:, 2])\n', (1317, 1334), True, 'import numpy as np\n'), ((1365, 1388), 'numpy.sin', 'np.sin', (['particles[:, 2]'], {}), '(particles[:, 2])\n', (1371, 1388), True, 'import numpy as np\n'), ((1868, 1920), 'numpy.linalg.norm', 'np.linalg.norm', (['(particles[:, 0:2] - landmark)'], {'axis': '(1)'}), '(particles[:, 0:2] - landmark, axis=1)\n', (1882, 1920), True, 'import numpy as np\n'), ((3489, 3499), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (3496, 3499), True, 'import numpy as np\n'), ((3625, 3694), 'matplotlib.pyplot.scatter', 'plt.scatter', (['particles[:, 0]', 'particles[:, 1]'], {'alpha': 'alpha', 'color': '"""g"""'}), "(particles[:, 0], particles[:, 1], alpha=alpha, color='g')\n", (3636, 3694), True, 'import matplotlib.pyplot as plt\n'), ((4911, 4986), 'matplotlib.pyplot.scatter', 'plt.scatter', (['robot_pos[0]', 'robot_pos[1]'], {'color': '"""k"""', 'marker': '"""+"""', 's': '(180)', 'lw': '(3)'}), "(robot_pos[0], robot_pos[1], color='k', marker='+', s=180, lw=3)\n", (4922, 4986), True, 'import matplotlib.pyplot as plt\n'), ((5000, 5048), 'matplotlib.pyplot.scatter', 'plt.scatter', (['mu[0]', 'mu[1]'], {'marker': '"""s"""', 'color': '"""r"""'}), "(mu[0], mu[1], marker='s', color='r')\n", (5011, 5048), True, 'import matplotlib.pyplot as plt\n'), ((581, 589), 'numpy.random.randn', 'randn', (['N'], {}), '(N)\n', (586, 589), False, 'from numpy.random import uniform, randn\n'), ((633, 641), 'numpy.random.randn', 'randn', (['N'], {}), '(N)\n', (638, 641), False, 'from numpy.random import uniform, randn\n'), ((685, 693), 'numpy.random.randn', 'randn', (['N'], {}), '(N)\n', (690, 693), False, 'from numpy.random import uniform, randn\n'), ((1161, 1169), 'numpy.random.randn', 'randn', (['N'], {}), '(N)\n', (1166, 1169), False, 'from numpy.random import uniform, randn\n'), ((1262, 1270), 'numpy.random.randn', 'randn', (['N'], {}), '(N)\n', (1267, 1270), False, 'from numpy.random import uniform, randn\n'), ((2325, 2343), 'numpy.square', 'np.square', (['weights'], {}), '(weights)\n', (2334, 2343), True, 'import numpy as np\n'), ((2498, 2510), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (2507, 2510), True, 'import numpy as np\n'), ((2513, 2531), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2529, 2531), True, 'import numpy as np\n'), ((3963, 4008), 'numpy.linalg.norm', 'np.linalg.norm', (['(landmarks - robot_pos)'], {'axis': '(1)'}), '(landmarks - robot_pos, axis=1)\n', (3977, 4008), True, 'import numpy as np\n'), ((4687, 4714), 'numpy.allclose', 'np.allclose', (['weights', '(1 / N)'], {}), '(weights, 1 / N)\n', (4698, 4714), True, 'import numpy as np\n'), ((4824, 4897), 'matplotlib.pyplot.scatter', 'plt.scatter', (['particles[:, 0]', 'particles[:, 1]'], {'color': '"""k"""', 'marker': '""","""', 's': '(1)'}), "(particles[:, 0], particles[:, 1], color='k', marker=',', s=1)\n", (4835, 4897), True, 'import matplotlib.pyplot as plt\n'), ((5231, 5255), 'numpy.array', 'np.array', (['[iters, iters]'], {}), '([iters, iters])\n', (5239, 5255), True, 'import numpy as np\n'), ((1940, 1963), 'scipy.stats.norm', 'stats.norm', (['distance', 'R'], {}), '(distance, R)\n', (1950, 1963), False, 'from scipy import stats\n'), ((3590, 3603), 'numpy.sqrt', 'np.sqrt', (['(5000)'], {}), '(5000)\n', (3597, 3603), True, 'import numpy as np\n'), ((3606, 3616), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (3613, 3616), True, 'import numpy as np\n'), ((4012, 4042), 'numpy.random.randn', 'np.random.randn', (['num_landmarks'], {}), '(num_landmarks)\n', (4027, 4042), True, 'import numpy as np\n')] |
import sys
import numpy as np
from scipy.sparse import csc_matrix, csr_matrix
import os
from math import factorial
from itertools import product
from representability.config import DATA_DIRECTORY
from openfermionpsi4 import run_psi4
from openfermion.hamiltonians import MolecularData
from openfermion.transforms import jordan_wigner
# from referenceqvm.unitary_generator import tensor_up
# from forestopenfermion import qubitop_to_pyquilpauli
from representability.fermions.basis_utils import generate_parity_permutations
def get_molecule_openfermion(molecule, eigen_index=0):
# check if the molecule is in the molecules data directory
if molecule.name + '.hdf5' in os.listdir(DATA_DIRECTORY):
print("\tLoading File from {}".format(DATA_DIRECTORY))
molecule.load()
else:
# compute properties with run_psi4
molecule = run_psi4(molecule, run_fci=True)
print("\tPsi4 Calculation Completed")
print("\tSaved in {}".format(DATA_DIRECTORY))
molecule.save()
fermion_hamiltonian = molecule.get_molecular_hamiltonian()
qubitop_hamiltonian = jordan_wigner(fermion_hamiltonian)
psum = qubitop_to_pyquilpauli(qubitop_hamiltonian)
ham = tensor_up(psum, molecule.n_qubits)
if isinstance(ham, (csc_matrix, csr_matrix)):
ham = ham.toarray()
w, v = np.linalg.eigh(ham)
gs_wf = v[:, [eigen_index]]
n_density = gs_wf.dot(np.conj(gs_wf).T)
return molecule, v[:, [eigen_index]], n_density, w[eigen_index]
def wedge_product(tensor_a, tensor_b):
"""
Returns the antisymmetric tensor product between two tensor operators
Tensor operators have the same number of upper and lower indices
:param tensor_a: tensor of p-rank.
:param tensor_b: tensor of q-rank
:returns: tensor_a_w_b antisymmetric tensor of p + q rank
"""
# get the number of upper and lower indices
rank_a = int(len(tensor_a.shape)/2)
rank_b = int(len(tensor_b.shape)/2)
permutations = generate_parity_permutations(rank_a + rank_b)
# define new tensor product which is the appropriate size
new_tensor = np.zeros((tensor_a.shape[:rank_a] + tensor_b.shape[:rank_b] +
tensor_a.shape[rank_a:] + tensor_b.shape[rank_b:]), dtype=complex)
for indices in product(*list(map(lambda x: range(x), new_tensor.shape))):
idx_upper = np.array(indices[:rank_a + rank_b])
idx_lower = np.array(indices[rank_a + rank_b:])
# sum over all over permutations and load into element of tensor
for perm_u, parity_u in permutations:
for perm_l, parity_l in permutations:
# index permutation
a_idx_u = list(idx_upper[perm_u][:rank_a])
b_idx_u = list(idx_upper[perm_u][rank_a:])
a_idx_l = list(idx_lower[perm_l][:rank_a])
b_idx_l = list(idx_lower[perm_l][rank_a:])
parity_term = parity_u * parity_l
# sum into new_tensor
new_tensor[indices] += parity_term * (tensor_a[tuple(a_idx_u + a_idx_l)] * tensor_b[tuple(b_idx_u + b_idx_l)])
new_tensor /= factorial(rank_a + rank_b)**2
return new_tensor
def map_d1_q1(opdm, oqdm):
"""
demonstrate mapping to opdm and oqdm
"""
m = opdm.shape[0]
I = np.eye(m)
for i, j in product(range(m), repeat=2):
# we will use hermetian constraints here
assert np.isclose(0.5*(opdm[i, j] + oqdm[j, i] + opdm[i, j] + oqdm[j, i]), I[i, j])
def map_d2_q2(tpdm, tqdm, opdm):
"""
demonstrate map
"""
sm_dim = opdm.shape[0]
krond = np.eye(sm_dim)
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = opdm[p, r]*krond[q, s] + opdm[q, s]*krond[p, r]
term2 = -1*(opdm[p, s]*krond[r, q] + opdm[q, r]*krond[s, p])
term3 = krond[s, p]*krond[r, q] - krond[q, s]*krond[r, p]
term4 = tqdm[r, s, p, q]
# print tpdm[p, q, r, s], term1 + term2 + term3 + term4
assert np.isclose(tpdm[p, q, r, s], term1 + term2 + term3 + term4)
def map_d2_q2_antisymm(tpdm, tqdm, opdm, bas):
"""
demonstrate map
"""
sm_dim = opdm.shape[0]
krond = np.eye(sm_dim)
for p, q, r, s in product(range(sm_dim), repeat=4):
if p < q and r < s:
term1 = 2.0 * opdm[p, r]*krond[q, s] + 2.0 * opdm[q, s]*krond[p, r]
term2 = -1*(2.0 * opdm[p, s]*krond[r, q] + 2.0 * opdm[q, r]*krond[s, p])
term3 = 2.0 * krond[s, p]*krond[r, q] - 2.0 * krond[q, s]*krond[r, p]
term4 = tqdm[bas[(r, s)], bas[(p, q)]]
# print tpdm[bas[(p, q)], bas[(r, s)]], term1 + term2 + term3 + term4
assert np.isclose(tpdm[bas[(p, q)], bas[(r, s)]], term1 + term2 + term3 + term4)
def map_d2_q2_ab(tpdm, tqdm, opdm_a, opdm_b):
"""
demonstrate map
"""
sm_dim = opdm_a.shape[0]
krond = np.eye(sm_dim)
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = opdm_a[p, r]*krond[q, s] + opdm_b[q, s]*krond[p, r]
term2 = -krond[p, r]*krond[q, s]
term3 = tqdm[r, s, p, q]
assert np.isclose(tpdm[p, q, r, s], term1 + term2 + term3)
def map_d2_q2_ab_mat(tpdm, tqdm, opdm_a, opdm_b):
"""
demonstrate map
"""
sm_dim = opdm_a.shape[0]
krond = np.eye(sm_dim)
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = opdm_a[p, r]*krond[q, s] + opdm_b[q, s]*krond[p, r]
term2 = -krond[p, r]*krond[q, s]
term3 = tqdm[r * sm_dim + s, p * sm_dim + q]
assert np.isclose(tpdm[p * sm_dim + q, r * sm_dim + s], term1 + term2 + term3)
def map_d2_g2(tpdm, tgdm, opdm):
"""
demonstrate map
"""
sm_dim = opdm.shape[0]
krond = np.eye(sm_dim)
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = opdm[p, r]*krond[q, s]
term2 = -1*tgdm[p, s, r, q]
assert np.isclose(tpdm[p, q, r, s], term1 + term2)
def map_d2_g2_sz_antisymm(tpdm, tgdm, opdm, bas):
"""
demonstrate map
"""
sm_dim = opdm.shape[0]
krond = np.eye(sm_dim)
for p, q, r, s in product(range(sm_dim), repeat=4):
if p < q and r < s:
term1 = 0.5 * (opdm[p, r]*krond[q, s] + opdm[q, s]*krond[p, r])
term2 = -0.5 * (opdm[q, r] * krond[p, s] + opdm[p, s] * krond[q, r])
term3 = -0.5 * (tgdm[p, s, r, q] + tgdm[q, r, s, p])
term4 = 0.5 * (tgdm[q, s, r, p] + tgdm[p, r, s, q])
# print tpdm[bas[(p, q)], bas[(r, s)]], term1 + term2 + term3 + term4
assert np.isclose(tpdm[bas[(p, q)], bas[(r, s)]], term1 + term2 + term3 + term4)
def map_g2_d2_sz_antisymm(tgdm, tpdm_anti, opdm, bas):
"""
map p, q, r, s of G2 to the elements of D2 antisymmetric
"""
sm_dim = opdm.shape[0]
krond = np.eye(sm_dim)
def compare(p, q, r, s, tgdm, tpdm, opdm, bas, factor=1.0):
term1 = tgdm[p, q, r, s]
term2 = 1.0 * opdm[p, r]*krond[q, s]
if p != s and r != q:
# print "non-zero term", p, s, r, q, p>s, r > q, (-1)**(p > s), (-1)**(r > q)
gem1 = tuple(sorted([p, s]))
gem2 = tuple(sorted([r, q]))
parity = (-1)**(p > s) * (-1)**(r > q)
term3 = parity * tpdm[bas[gem1], bas[gem2]] * -0.5
else:
# print "zero term"
term3 = 0.0
# print term1, term2 + term3
assert np.isclose(term1, term2 + term3)
for p, q, r, s in product(range(sm_dim), repeat=4):
if p * sm_dim + q <= r * sm_dim + s:
compare(p, q, r, s, tgdm, tpdm_anti, opdm, bas, factor=0.5)
def map_g2ab_ba_d2ab(tgdm_ab, tgdm_ba, tpdm_ab, opdm_a, opdm_b):
"""
Mapping pieces of G2ab/ba to D2ab
"""
m_dim = opdm_a.shape[0]
krond = np.eye(m_dim)
def compare(p, q, r, s, factor=1.0):
term1 = tgdm_ab[p, q, r, s] + tgdm_ba[s, r, q, p]
term2 = opdm_a[p, r] * krond[q, s] + opdm_b[s, q] * krond[p, r]
term3 = -2.0 * tpdm_ab[p * m_dim + s, r * m_dim + q]
# print term1, term2 + term3
assert np.isclose(term1, term2 + term3)
for p, q, r, s in product(range(m_dim), repeat=4):
compare(p, q, r, s)
def map_d2_g2_sz_antisymm_aabb(tpdm, tgdm_aabb, tgdm_bbaa, bas, sm_dim):
"""
demonstrate map
"""
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = tgdm_aabb[p, q, r, s] + tgdm_bbaa[r, s, p, q]
term2 = -1.0 * (tpdm[bas[(p, s)], bas[(q, r)]] + tpdm[bas[(q, r)], bas[(p, s)]])
# print term1, -term2
assert np.isclose(term1, -term2)
def map_d2_g2_sz(tgdm, tpdm, opdm, g2_block='aaaa'):
sm_dim = opdm.shape[0]
krond = np.eye(sm_dim)
if g2_block == 'aaaa' or g2_block == 'bbbb':
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = opdm[p, r]*krond[q, s]
term2 = -1*tpdm[p, s, r, q]
# print tgdm[p, q, r, s], term1 + term2
assert np.isclose(tgdm[p, q, r, s], term1 + term2)
elif g2_block == 'bbaa' or g2_block == 'aabb':
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = tpdm[p, s, q, r]
# print tgdm[p, q, r, s,], term1
assert np.isclose(tgdm[p, q, r, s], term1)
elif g2_block == 'abab' or g2_block == 'baba':
for p, q, r, s in product(range(sm_dim), repeat=4):
term1 = opdm[p, r]*krond[q, s]
if len(tpdm.shape) == 2:
term2 = -1*tpdm[p*sm_dim + s, r*sm_dim + q]
else:
term2 = -1*tpdm[p, s, r, q]
assert np.isclose(tgdm[p, q, r, s], term1 + term2)
def map_d2_d1(tpdm, opdm):
"""
map tpdm to trace corrected versions of 1-RDM
"""
sm_dim = opdm.shape[0]
N = np.trace(opdm)
Na = sum([opdm[2*i, 2*i] for i in range(sm_dim // 2)])
Nb = sum([opdm[2*i + 1, 2*i + 1] for i in range(sm_dim // 2)])
for p, q, in product(range(sm_dim), repeat=2):
term = 0
for r in range(sm_dim):
term += tpdm[p, r, q, r]
assert np.isclose(term/(N - 1), opdm[p, q])
# also check spin constraints. Contract just alpha terms and get answers.
# Contract just beta terms and get answers.
# print "number of alpha particles "
# print Na
# print "number of beta particles "
# print Nb
# # first contract alpha electrons
# print "single particle basis rank"
# print sm_dim
# print "alpha opdm"
for p, q in product(range(sm_dim/2), repeat=2):
term1 = 0
for r in range(sm_dim):
term1 += tpdm[2*p, r, 2*q, r]
# print term1/(Na + Nb - 1), opdm[2*p, 2*q]
assert np.isclose(term1/(Na + Nb - 1), opdm[2*p, 2*q])
def map_d2_d1_sz(tpdm, opdm, scalar):
assert np.allclose(np.einsum('ijkj', tpdm), opdm * scalar)
def map_d2_d1_sz_antisym(tpdm, opdm, scalar, bas):
test_opdm = np.zeros_like(opdm)
for i, j in product(range(opdm.shape[0]), repeat=2):
for r in range(opdm.shape[0]):
if i != r and j != r:
top_gem = tuple(sorted([i, r]))
bot_gem = tuple(sorted([j, r]))
parity = (-1)**(r < i) * (-1)**(r < j)
test_opdm[i, j] += tpdm[bas[top_gem], bas[bot_gem]] * 0.5 * parity
# print test_opdm[i, j] / scalar, opdm[i, j]
assert np.allclose(test_opdm / scalar, opdm)
def map_d2_d1_sz_symm(tpdm, opdm, scalar, bas):
test_opdm = np.zeros_like(opdm)
m = opdm.shape[0]
for i, j in product(range(opdm.shape[0]), repeat=2):
for r in range(opdm.shape[0]):
# top_gem = tuple([i, r])
# bot_gem = tuple([j, r])
# print top_gem, bot_gem
# test_opdm[i, j] += tpdm[bas[top_gem], bas[bot_gem]]
test_opdm[i, j] += tpdm[i * m + r, j * m + r]
assert np.allclose(test_opdm, opdm * scalar)
def check_antisymmetric_d2(tpdm):
m = tpdm.shape[0]
for p, q, r, s in product(range(m), repeat=4):
# assert np.isclose(tpdm[p, q, r, s], -1*tpdm[q, p, r, s])
# assert np.isclose(tpdm[p, q, r, s], -1*tpdm[p, q, s, r])
# assert np.isclose(tpdm[p, q, r, s], tpdm[q, p, s, r])
np.testing.assert_almost_equal(tpdm[p, q, r, s], -1*tpdm[q, p, r, s])
np.testing.assert_almost_equal(tpdm[p, q, r, s], -1*tpdm[p, q, s, r])
np.testing.assert_almost_equal(tpdm[p, q, r, s], tpdm[q, p, s, r])
def map_d2_e2_sz(tpdm, m_tensor, measured_tensor):
m = tpdm.shape[0]
assert np.allclose(m_tensor[:m**2, :m**2], np.eye(m**2))
# assert np.allclose(m_tensor[m**2:, m**2:], np.zeros((m**2, m**2)))
for p, q, r, s in product(range(m), repeat=4):
# print m_tensor[p*m + q + m**2, r*m + s], tpdm[p, q, r, s] - measured_tensor[p, q, r, s]
assert np.isclose(m_tensor[p*m + q + m**2, r*m + s], tpdm[p, q, r, s] - measured_tensor[p, q, r, s])
assert np.isclose(m_tensor[r*m + s + m**2, p*m + q], tpdm[r, s, p, q] - measured_tensor[r, s, p, q])
assert np.isclose(m_tensor[p*m + q, r*m + s + m**2], tpdm[p, q, r, s] - measured_tensor[p, q, r, s])
assert np.isclose(m_tensor[r*m + s, p*m + q + m**2], tpdm[r, s, p, q] - measured_tensor[r, s, p, q])
def map_d2_e2_sz_antisymm(tpdm, m_tensor, measured_tensor, m, bas):
tm = m*(m - 1)/2
assert np.allclose(m_tensor[:tm, :tm], np.eye(tm))
for p, q, r, s in product(range(m), repeat=4):
if p < q and r < s:
assert np.isclose(m_tensor[bas[(p, q)] + tm, bas[(r, s)]], tpdm[bas[(p, q)], bas[(r, s)]] - measured_tensor[bas[(p, q)], bas[(r, s)]])
assert np.isclose(m_tensor[bas[(r, s)] + tm, bas[(p, q)]], tpdm[bas[(r, s)], bas[(p, q)]] - measured_tensor[bas[(r, s)], bas[(p, q)]])
assert np.isclose(m_tensor[bas[(p, q)], bas[(r, s)] + tm], tpdm[bas[(p, q)], bas[(r, s)]] - measured_tensor[bas[(p, q)], bas[(r, s)]])
assert np.isclose(m_tensor[bas[(r, s)], bas[(p, q)] + tm], tpdm[bas[(r, s)], bas[(p, q)]] - measured_tensor[bas[(r, s)], bas[(p, q)]])
def map_d2_e2_sz_symm(tpdm, m_tensor, measured_tensor, m, bas):
mm = m*m
assert np.allclose(m_tensor[:mm, :mm], np.eye(mm))
for p, q, r, s in product(range(m), repeat=4):
assert np.isclose(m_tensor[bas[(p, q)] + mm, bas[(r, s)]], tpdm[bas[(p, q)], bas[(r, s)]] - measured_tensor[bas[(p, q)], bas[(r, s)]])
assert np.isclose(m_tensor[bas[(r, s)] + mm, bas[(p, q)]], tpdm[bas[(r, s)], bas[(p, q)]] - measured_tensor[bas[(r, s)], bas[(p, q)]])
assert np.isclose(m_tensor[bas[(p, q)], bas[(r, s)] + mm], tpdm[bas[(p, q)], bas[(r, s)]] - measured_tensor[bas[(p, q)], bas[(r, s)]])
assert np.isclose(m_tensor[bas[(r, s)], bas[(p, q)] + mm], tpdm[bas[(r, s)], bas[(p, q)]] - measured_tensor[bas[(r, s)], bas[(p, q)]])
def map_d1_e1_sz_symm(opdm, m_tensor, measured_tensor, m):
assert np.allclose(m_tensor[:m, :m], np.eye(m))
for p, q, in product(range(m), repeat=2):
assert np.isclose(m_tensor[p + m, q], opdm[p, q] - measured_tensor[p, q])
assert np.isclose(m_tensor[p, q + m], opdm[p, q] - measured_tensor[p, q])
def four_tensor2matrix(tensor):
dim = tensor.shape[0]
mat = np.zeros((dim**2, dim**2), dtype=tensor.dtype)
for p, q, r, s in product(range(dim), repeat=4):
mat[p*dim + q, r*dim + s] = tensor[p, q, r, s]
return mat
def matrix2four_tensor(matrix):
dim = matrix.shape[0]
sp_dim = int(np.sqrt(dim))
four_tensor = np.zeros((sp_dim, sp_dim, sp_dim, sp_dim), dtype=matrix.dtype)
for p, q, r, s in product(range(sp_dim), repeat=4):
four_tensor[p, q, r, s] = matrix[p * sp_dim + q, r * sp_dim + s]
return four_tensor
def write_sdpfile(sdpfile_name, nc, nv, nnz, nb, A, b, cvec, blocksize):
"""
Write an SDP down in standard format
:param sdpfile_name: File name to write information into
:param Int nc: number of constraints
:param Int nv: number of variables
:param Int nnz: number of non-zero elements in the constraint set
:param Int nb: number of blocks in the primal solution
:param A: Sparse matrix representing constraints on the primal vector
:param b: b-vector of Ax = b where A is the constraint matrix, x is the primal vector and b is the residual
:param cvec: const vector c' * x
:param blocksize: list of ints where each element is the block size
"""
with open(sdpfile_name, 'w') as fid:
# write top line
fid.write("%i %i %i %i\n" % (nc, nv, nnz, nb))
# write blocksize
for bb in blocksize:
fid.write("%i\n" % bb)
# write A matrix
for row in range(A.shape[0]):
for col in A.getrow(row).nonzero()[1]:
if not np.isclose(np.abs(A[row, col]), 0):
fid.write(
"%i %i %5.10E\n" % (row + 1, col + 1, A[row, col]))
# write b vector
for i in range(b.shape[0]):
fid.write("%5.10E\n" % b[i, 0])
# write c vector
for i in range(cvec.shape[0]):
fid.write("%5.10E\n" % cvec[i, 0])
| [
"numpy.conj",
"numpy.trace",
"numpy.zeros_like",
"numpy.abs",
"representability.fermions.basis_utils.generate_parity_permutations",
"numpy.testing.assert_almost_equal",
"numpy.allclose",
"numpy.zeros",
"numpy.einsum",
"openfermion.transforms.jordan_wigner",
"numpy.linalg.eigh",
"numpy.isclose"... | [((1113, 1147), 'openfermion.transforms.jordan_wigner', 'jordan_wigner', (['fermion_hamiltonian'], {}), '(fermion_hamiltonian)\n', (1126, 1147), False, 'from openfermion.transforms import jordan_wigner\n'), ((1337, 1356), 'numpy.linalg.eigh', 'np.linalg.eigh', (['ham'], {}), '(ham)\n', (1351, 1356), True, 'import numpy as np\n'), ((1990, 2035), 'representability.fermions.basis_utils.generate_parity_permutations', 'generate_parity_permutations', (['(rank_a + rank_b)'], {}), '(rank_a + rank_b)\n', (2018, 2035), False, 'from representability.fermions.basis_utils import generate_parity_permutations\n'), ((2116, 2247), 'numpy.zeros', 'np.zeros', (['(tensor_a.shape[:rank_a] + tensor_b.shape[:rank_b] + tensor_a.shape[rank_a:\n ] + tensor_b.shape[rank_b:])'], {'dtype': 'complex'}), '(tensor_a.shape[:rank_a] + tensor_b.shape[:rank_b] + tensor_a.shape\n [rank_a:] + tensor_b.shape[rank_b:], dtype=complex)\n', (2124, 2247), True, 'import numpy as np\n'), ((3309, 3318), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (3315, 3318), True, 'import numpy as np\n'), ((3615, 3629), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (3621, 3629), True, 'import numpy as np\n'), ((4181, 4195), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (4187, 4195), True, 'import numpy as np\n'), ((4878, 4892), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (4884, 4892), True, 'import numpy as np\n'), ((5287, 5301), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (5293, 5301), True, 'import numpy as np\n'), ((5717, 5731), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (5723, 5731), True, 'import numpy as np\n'), ((6049, 6063), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (6055, 6063), True, 'import numpy as np\n'), ((6782, 6796), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (6788, 6796), True, 'import numpy as np\n'), ((7746, 7759), 'numpy.eye', 'np.eye', (['m_dim'], {}), '(m_dim)\n', (7752, 7759), True, 'import numpy as np\n'), ((8645, 8659), 'numpy.eye', 'np.eye', (['sm_dim'], {}), '(sm_dim)\n', (8651, 8659), True, 'import numpy as np\n'), ((9722, 9736), 'numpy.trace', 'np.trace', (['opdm'], {}), '(opdm)\n', (9730, 9736), True, 'import numpy as np\n'), ((10850, 10869), 'numpy.zeros_like', 'np.zeros_like', (['opdm'], {}), '(opdm)\n', (10863, 10869), True, 'import numpy as np\n'), ((11298, 11335), 'numpy.allclose', 'np.allclose', (['(test_opdm / scalar)', 'opdm'], {}), '(test_opdm / scalar, opdm)\n', (11309, 11335), True, 'import numpy as np\n'), ((11402, 11421), 'numpy.zeros_like', 'np.zeros_like', (['opdm'], {}), '(opdm)\n', (11415, 11421), True, 'import numpy as np\n'), ((11789, 11826), 'numpy.allclose', 'np.allclose', (['test_opdm', '(opdm * scalar)'], {}), '(test_opdm, opdm * scalar)\n', (11800, 11826), True, 'import numpy as np\n'), ((15122, 15172), 'numpy.zeros', 'np.zeros', (['(dim ** 2, dim ** 2)'], {'dtype': 'tensor.dtype'}), '((dim ** 2, dim ** 2), dtype=tensor.dtype)\n', (15130, 15172), True, 'import numpy as np\n'), ((15401, 15463), 'numpy.zeros', 'np.zeros', (['(sp_dim, sp_dim, sp_dim, sp_dim)'], {'dtype': 'matrix.dtype'}), '((sp_dim, sp_dim, sp_dim, sp_dim), dtype=matrix.dtype)\n', (15409, 15463), True, 'import numpy as np\n'), ((679, 705), 'os.listdir', 'os.listdir', (['DATA_DIRECTORY'], {}), '(DATA_DIRECTORY)\n', (689, 705), False, 'import os\n'), ((866, 898), 'openfermionpsi4.run_psi4', 'run_psi4', (['molecule'], {'run_fci': '(True)'}), '(molecule, run_fci=True)\n', (874, 898), False, 'from openfermionpsi4 import run_psi4\n'), ((2371, 2406), 'numpy.array', 'np.array', (['indices[:rank_a + rank_b]'], {}), '(indices[:rank_a + rank_b])\n', (2379, 2406), True, 'import numpy as np\n'), ((2427, 2462), 'numpy.array', 'np.array', (['indices[rank_a + rank_b:]'], {}), '(indices[rank_a + rank_b:])\n', (2435, 2462), True, 'import numpy as np\n'), ((3141, 3167), 'math.factorial', 'factorial', (['(rank_a + rank_b)'], {}), '(rank_a + rank_b)\n', (3150, 3167), False, 'from math import factorial\n'), ((3428, 3506), 'numpy.isclose', 'np.isclose', (['(0.5 * (opdm[i, j] + oqdm[j, i] + opdm[i, j] + oqdm[j, i]))', 'I[i, j]'], {}), '(0.5 * (opdm[i, j] + oqdm[j, i] + opdm[i, j] + oqdm[j, i]), I[i, j])\n', (3438, 3506), True, 'import numpy as np\n'), ((3997, 4056), 'numpy.isclose', 'np.isclose', (['tpdm[p, q, r, s]', '(term1 + term2 + term3 + term4)'], {}), '(tpdm[p, q, r, s], term1 + term2 + term3 + term4)\n', (4007, 4056), True, 'import numpy as np\n'), ((5106, 5157), 'numpy.isclose', 'np.isclose', (['tpdm[p, q, r, s]', '(term1 + term2 + term3)'], {}), '(tpdm[p, q, r, s], term1 + term2 + term3)\n', (5116, 5157), True, 'import numpy as np\n'), ((5535, 5606), 'numpy.isclose', 'np.isclose', (['tpdm[p * sm_dim + q, r * sm_dim + s]', '(term1 + term2 + term3)'], {}), '(tpdm[p * sm_dim + q, r * sm_dim + s], term1 + term2 + term3)\n', (5545, 5606), True, 'import numpy as np\n'), ((5878, 5921), 'numpy.isclose', 'np.isclose', (['tpdm[p, q, r, s]', '(term1 + term2)'], {}), '(tpdm[p, q, r, s], term1 + term2)\n', (5888, 5921), True, 'import numpy as np\n'), ((7378, 7410), 'numpy.isclose', 'np.isclose', (['term1', '(term2 + term3)'], {}), '(term1, term2 + term3)\n', (7388, 7410), True, 'import numpy as np\n'), ((8045, 8077), 'numpy.isclose', 'np.isclose', (['term1', '(term2 + term3)'], {}), '(term1, term2 + term3)\n', (8055, 8077), True, 'import numpy as np\n'), ((8525, 8550), 'numpy.isclose', 'np.isclose', (['term1', '(-term2)'], {}), '(term1, -term2)\n', (8535, 8550), True, 'import numpy as np\n'), ((10016, 10054), 'numpy.isclose', 'np.isclose', (['(term / (N - 1))', 'opdm[p, q]'], {}), '(term / (N - 1), opdm[p, q])\n', (10026, 10054), True, 'import numpy as np\n'), ((10630, 10683), 'numpy.isclose', 'np.isclose', (['(term1 / (Na + Nb - 1))', 'opdm[2 * p, 2 * q]'], {}), '(term1 / (Na + Nb - 1), opdm[2 * p, 2 * q])\n', (10640, 10683), True, 'import numpy as np\n'), ((10741, 10764), 'numpy.einsum', 'np.einsum', (['"""ijkj"""', 'tpdm'], {}), "('ijkj', tpdm)\n", (10750, 10764), True, 'import numpy as np\n'), ((12142, 12213), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['tpdm[p, q, r, s]', '(-1 * tpdm[q, p, r, s])'], {}), '(tpdm[p, q, r, s], -1 * tpdm[q, p, r, s])\n', (12172, 12213), True, 'import numpy as np\n'), ((12220, 12291), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['tpdm[p, q, r, s]', '(-1 * tpdm[p, q, s, r])'], {}), '(tpdm[p, q, r, s], -1 * tpdm[p, q, s, r])\n', (12250, 12291), True, 'import numpy as np\n'), ((12298, 12364), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['tpdm[p, q, r, s]', 'tpdm[q, p, s, r]'], {}), '(tpdm[p, q, r, s], tpdm[q, p, s, r])\n', (12328, 12364), True, 'import numpy as np\n'), ((12487, 12501), 'numpy.eye', 'np.eye', (['(m ** 2)'], {}), '(m ** 2)\n', (12493, 12501), True, 'import numpy as np\n'), ((12738, 12841), 'numpy.isclose', 'np.isclose', (['m_tensor[p * m + q + m ** 2, r * m + s]', '(tpdm[p, q, r, s] - measured_tensor[p, q, r, s])'], {}), '(m_tensor[p * m + q + m ** 2, r * m + s], tpdm[p, q, r, s] -\n measured_tensor[p, q, r, s])\n', (12748, 12841), True, 'import numpy as np\n'), ((12847, 12950), 'numpy.isclose', 'np.isclose', (['m_tensor[r * m + s + m ** 2, p * m + q]', '(tpdm[r, s, p, q] - measured_tensor[r, s, p, q])'], {}), '(m_tensor[r * m + s + m ** 2, p * m + q], tpdm[r, s, p, q] -\n measured_tensor[r, s, p, q])\n', (12857, 12950), True, 'import numpy as np\n'), ((12956, 13059), 'numpy.isclose', 'np.isclose', (['m_tensor[p * m + q, r * m + s + m ** 2]', '(tpdm[p, q, r, s] - measured_tensor[p, q, r, s])'], {}), '(m_tensor[p * m + q, r * m + s + m ** 2], tpdm[p, q, r, s] -\n measured_tensor[p, q, r, s])\n', (12966, 13059), True, 'import numpy as np\n'), ((13065, 13168), 'numpy.isclose', 'np.isclose', (['m_tensor[r * m + s, p * m + q + m ** 2]', '(tpdm[r, s, p, q] - measured_tensor[r, s, p, q])'], {}), '(m_tensor[r * m + s, p * m + q + m ** 2], tpdm[r, s, p, q] -\n measured_tensor[r, s, p, q])\n', (13075, 13168), True, 'import numpy as np\n'), ((13293, 13303), 'numpy.eye', 'np.eye', (['tm'], {}), '(tm)\n', (13299, 13303), True, 'import numpy as np\n'), ((14094, 14104), 'numpy.eye', 'np.eye', (['mm'], {}), '(mm)\n', (14100, 14104), True, 'import numpy as np\n'), ((14172, 14291), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[p, q] + mm, bas[r, s]]', '(tpdm[bas[p, q], bas[r, s]] - measured_tensor[bas[p, q], bas[r, s]])'], {}), '(m_tensor[bas[p, q] + mm, bas[r, s]], tpdm[bas[p, q], bas[r, s]] -\n measured_tensor[bas[p, q], bas[r, s]])\n', (14182, 14291), True, 'import numpy as np\n'), ((14315, 14434), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[r, s] + mm, bas[p, q]]', '(tpdm[bas[r, s], bas[p, q]] - measured_tensor[bas[r, s], bas[p, q]])'], {}), '(m_tensor[bas[r, s] + mm, bas[p, q]], tpdm[bas[r, s], bas[p, q]] -\n measured_tensor[bas[r, s], bas[p, q]])\n', (14325, 14434), True, 'import numpy as np\n'), ((14458, 14577), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[p, q], bas[r, s] + mm]', '(tpdm[bas[p, q], bas[r, s]] - measured_tensor[bas[p, q], bas[r, s]])'], {}), '(m_tensor[bas[p, q], bas[r, s] + mm], tpdm[bas[p, q], bas[r, s]] -\n measured_tensor[bas[p, q], bas[r, s]])\n', (14468, 14577), True, 'import numpy as np\n'), ((14601, 14720), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[r, s], bas[p, q] + mm]', '(tpdm[bas[r, s], bas[p, q]] - measured_tensor[bas[r, s], bas[p, q]])'], {}), '(m_tensor[bas[r, s], bas[p, q] + mm], tpdm[bas[r, s], bas[p, q]] -\n measured_tensor[bas[r, s], bas[p, q]])\n', (14611, 14720), True, 'import numpy as np\n'), ((14831, 14840), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (14837, 14840), True, 'import numpy as np\n'), ((14903, 14969), 'numpy.isclose', 'np.isclose', (['m_tensor[p + m, q]', '(opdm[p, q] - measured_tensor[p, q])'], {}), '(m_tensor[p + m, q], opdm[p, q] - measured_tensor[p, q])\n', (14913, 14969), True, 'import numpy as np\n'), ((14985, 15051), 'numpy.isclose', 'np.isclose', (['m_tensor[p, q + m]', '(opdm[p, q] - measured_tensor[p, q])'], {}), '(m_tensor[p, q + m], opdm[p, q] - measured_tensor[p, q])\n', (14995, 15051), True, 'import numpy as np\n'), ((15369, 15381), 'numpy.sqrt', 'np.sqrt', (['dim'], {}), '(dim)\n', (15376, 15381), True, 'import numpy as np\n'), ((1415, 1429), 'numpy.conj', 'np.conj', (['gs_wf'], {}), '(gs_wf)\n', (1422, 1429), True, 'import numpy as np\n'), ((4679, 4748), 'numpy.isclose', 'np.isclose', (['tpdm[bas[p, q], bas[r, s]]', '(term1 + term2 + term3 + term4)'], {}), '(tpdm[bas[p, q], bas[r, s]], term1 + term2 + term3 + term4)\n', (4689, 4748), True, 'import numpy as np\n'), ((6535, 6604), 'numpy.isclose', 'np.isclose', (['tpdm[bas[p, q], bas[r, s]]', '(term1 + term2 + term3 + term4)'], {}), '(tpdm[bas[p, q], bas[r, s]], term1 + term2 + term3 + term4)\n', (6545, 6604), True, 'import numpy as np\n'), ((8924, 8967), 'numpy.isclose', 'np.isclose', (['tgdm[p, q, r, s]', '(term1 + term2)'], {}), '(tgdm[p, q, r, s], term1 + term2)\n', (8934, 8967), True, 'import numpy as np\n'), ((13403, 13522), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[p, q] + tm, bas[r, s]]', '(tpdm[bas[p, q], bas[r, s]] - measured_tensor[bas[p, q], bas[r, s]])'], {}), '(m_tensor[bas[p, q] + tm, bas[r, s]], tpdm[bas[p, q], bas[r, s]] -\n measured_tensor[bas[p, q], bas[r, s]])\n', (13413, 13522), True, 'import numpy as np\n'), ((13550, 13669), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[r, s] + tm, bas[p, q]]', '(tpdm[bas[r, s], bas[p, q]] - measured_tensor[bas[r, s], bas[p, q]])'], {}), '(m_tensor[bas[r, s] + tm, bas[p, q]], tpdm[bas[r, s], bas[p, q]] -\n measured_tensor[bas[r, s], bas[p, q]])\n', (13560, 13669), True, 'import numpy as np\n'), ((13697, 13816), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[p, q], bas[r, s] + tm]', '(tpdm[bas[p, q], bas[r, s]] - measured_tensor[bas[p, q], bas[r, s]])'], {}), '(m_tensor[bas[p, q], bas[r, s] + tm], tpdm[bas[p, q], bas[r, s]] -\n measured_tensor[bas[p, q], bas[r, s]])\n', (13707, 13816), True, 'import numpy as np\n'), ((13844, 13963), 'numpy.isclose', 'np.isclose', (['m_tensor[bas[r, s], bas[p, q] + tm]', '(tpdm[bas[r, s], bas[p, q]] - measured_tensor[bas[r, s], bas[p, q]])'], {}), '(m_tensor[bas[r, s], bas[p, q] + tm], tpdm[bas[r, s], bas[p, q]] -\n measured_tensor[bas[r, s], bas[p, q]])\n', (13854, 13963), True, 'import numpy as np\n'), ((9180, 9215), 'numpy.isclose', 'np.isclose', (['tgdm[p, q, r, s]', 'term1'], {}), '(tgdm[p, q, r, s], term1)\n', (9190, 9215), True, 'import numpy as np\n'), ((9548, 9591), 'numpy.isclose', 'np.isclose', (['tgdm[p, q, r, s]', '(term1 + term2)'], {}), '(tgdm[p, q, r, s], term1 + term2)\n', (9558, 9591), True, 'import numpy as np\n'), ((16676, 16695), 'numpy.abs', 'np.abs', (['A[row, col]'], {}), '(A[row, col])\n', (16682, 16695), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import measurement
import echo
import distance
import image
import argparse
parser = argparse.ArgumentParser(description='Estimate the shape of a room from room impulse response data')
parser.add_argument('dataset', help='Dataset containing the room impulse response data measured in a room using 2 or more sources and 5 microphones')
parser.add_argument('-N', help='Number of sources', default=4)
parser.add_argument('-et', help='Echo Threshold', default=0.005)
parser.add_argument('-rt', help='Result Threshold', default=0.05)
parser.add_argument('--verbose', '-v', help='Print information during the estimation process', action='store_true')
args = parser.parse_args()
dataset = sio.loadmat(args.dataset)
fs =float(dataset['fs'])
M = int(dataset['M'])
#N = int(dataset['N'])
h = float(dataset['h'])
l = float(dataset['l'])
w = float(dataset['w'])
r = dataset['receivers']
s = dataset['sources']
data = dataset['data'].T
c = float(dataset['c'])
N = int(args.N)
et = float(args.et)
rt = float(args.rt)
maxsize = np.sqrt(w**2+l**2+h**2) #m
max_delay = maxsize / float(c)
maxlength = int(2 * max_delay * fs)
measurements = [measurement.MeasurementData(data=np.hstack(source_data).T,
receivers=r,
sources=s[i],
room_dimensions=(w,l,h),
c=c,
fs=fs)
for i,source_data in enumerate(data)]
echo_data = [echo.EchoData(m.find_echoes(crop=maxlength, interpolate=10)) for m in measurements]
D = measurement.squared_distance_matrix(r, augmented=True)
S, E = zip(*[e.find_labels(D,threshold=et, parallel=True, verbose=args.verbose) for e in echo_data[:N]])
E = [e for e in E if len(e) > 0]
S = np.vstack(S)
distancedata = distance.DistanceData(S,E)
results = distancedata.find_images(r)
if len(results) > 0:
imagedata = image.ImageSourceData(results, N, r, (w,l,h))
wall_points,vertices = imagedata.find_walls(threshold=rt, bestN=10)
im = np.vstack(imagedata.images)
plt.scatter(im[:,0], im[:,1])
wp = np.vstack(wall_points)
plt.scatter(wp[:,0], wp[:,1], color=(1,0,0,1))
plt.scatter(vertices[:,0], vertices[:,1], color=(0,1,0,1))
plt.show()
else:
print('No results to show')
| [
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"scipy.io.loadmat",
"matplotlib.pyplot.scatter",
"distance.DistanceData",
"image.ImageSourceData",
"numpy.hstack",
"measurement.squared_distance_matrix",
"numpy.vstack",
"numpy.sqrt"
] | [((183, 287), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Estimate the shape of a room from room impulse response data"""'}), "(description=\n 'Estimate the shape of a room from room impulse response data')\n", (206, 287), False, 'import argparse\n'), ((781, 806), 'scipy.io.loadmat', 'sio.loadmat', (['args.dataset'], {}), '(args.dataset)\n', (792, 806), True, 'import scipy.io as sio\n'), ((1115, 1148), 'numpy.sqrt', 'np.sqrt', (['(w ** 2 + l ** 2 + h ** 2)'], {}), '(w ** 2 + l ** 2 + h ** 2)\n', (1122, 1148), True, 'import numpy as np\n'), ((1680, 1734), 'measurement.squared_distance_matrix', 'measurement.squared_distance_matrix', (['r'], {'augmented': '(True)'}), '(r, augmented=True)\n', (1715, 1734), False, 'import measurement\n'), ((1877, 1889), 'numpy.vstack', 'np.vstack', (['S'], {}), '(S)\n', (1886, 1889), True, 'import numpy as np\n'), ((1906, 1933), 'distance.DistanceData', 'distance.DistanceData', (['S', 'E'], {}), '(S, E)\n', (1927, 1933), False, 'import distance\n'), ((2009, 2056), 'image.ImageSourceData', 'image.ImageSourceData', (['results', 'N', 'r', '(w, l, h)'], {}), '(results, N, r, (w, l, h))\n', (2030, 2056), False, 'import image\n'), ((2136, 2163), 'numpy.vstack', 'np.vstack', (['imagedata.images'], {}), '(imagedata.images)\n', (2145, 2163), True, 'import numpy as np\n'), ((2168, 2199), 'matplotlib.pyplot.scatter', 'plt.scatter', (['im[:, 0]', 'im[:, 1]'], {}), '(im[:, 0], im[:, 1])\n', (2179, 2199), True, 'import matplotlib.pyplot as plt\n'), ((2207, 2229), 'numpy.vstack', 'np.vstack', (['wall_points'], {}), '(wall_points)\n', (2216, 2229), True, 'import numpy as np\n'), ((2234, 2285), 'matplotlib.pyplot.scatter', 'plt.scatter', (['wp[:, 0]', 'wp[:, 1]'], {'color': '(1, 0, 0, 1)'}), '(wp[:, 0], wp[:, 1], color=(1, 0, 0, 1))\n', (2245, 2285), True, 'import matplotlib.pyplot as plt\n'), ((2285, 2348), 'matplotlib.pyplot.scatter', 'plt.scatter', (['vertices[:, 0]', 'vertices[:, 1]'], {'color': '(0, 1, 0, 1)'}), '(vertices[:, 0], vertices[:, 1], color=(0, 1, 0, 1))\n', (2296, 2348), True, 'import matplotlib.pyplot as plt\n'), ((2348, 2358), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2356, 2358), True, 'import matplotlib.pyplot as plt\n'), ((1261, 1283), 'numpy.hstack', 'np.hstack', (['source_data'], {}), '(source_data)\n', (1270, 1283), True, 'import numpy as np\n')] |
# Copyright 2020 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for multiplayer_wrapper."""
from unittest import mock
from absl.testing import absltest
import dm_env
import numpy as np
import dmlab2d
from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper
ACT_SPEC = dm_env.specs.BoundedArray(shape=(), minimum=0, maximum=4, dtype=np.int8)
ACT_VALUE = np.ones([], dtype=np.int8)
RGB_SPEC = dm_env.specs.Array(shape=(8, 8, 3), dtype=np.int8)
RGB_VALUE = np.ones((8, 8, 3), np.int8)
REWARD_SPEC = dm_env.specs.Array(shape=(), dtype=np.float32)
REWARD_VALUE = np.ones((), dtype=np.float32)
class Lab2DToListsWrapperTest(absltest.TestCase):
def test_get_num_players(self):
env = mock.Mock(spec_set=dmlab2d.Environment)
env.action_spec.return_value = {
"1.MOVE": ACT_SPEC,
"2.MOVE": ACT_SPEC,
"3.MOVE": ACT_SPEC,
}
wrapped = multiplayer_wrapper.Wrapper(
env, individual_observation_names=[], global_observation_names=[]
)
self.assertEqual(wrapped._get_num_players(), 3)
def test_get_rewards(self):
env = mock.Mock(spec_set=dmlab2d.Environment)
env.action_spec.return_value = {
"1.MOVE": ACT_SPEC,
"2.MOVE": ACT_SPEC,
"3.MOVE": ACT_SPEC,
}
wrapped = multiplayer_wrapper.Wrapper(
env, individual_observation_names=[], global_observation_names=[]
)
source = {
"1.RGB": RGB_VALUE,
"2.RGB": RGB_VALUE * 2,
"3.RGB": RGB_VALUE * 3,
"1.REWARD": 10,
"2.REWARD": 20,
"3.REWARD": 30,
"WORLD.RGB": RGB_VALUE,
}
rewards = wrapped._get_rewards(source)
self.assertEqual(rewards, [10, 20, 30])
def test_get_observations(self):
env = mock.Mock(spec_set=dmlab2d.Environment)
env.action_spec.return_value = {
"1.MOVE": ACT_SPEC,
"2.MOVE": ACT_SPEC,
"3.MOVE": ACT_SPEC,
}
wrapped = multiplayer_wrapper.Wrapper(
env,
individual_observation_names=["RGB"],
global_observation_names=["WORLD.RGB"],
)
source = {
"1.RGB": RGB_VALUE * 1,
"2.RGB": RGB_VALUE * 2,
"3.RGB": RGB_VALUE * 3,
"1.OTHER": RGB_SPEC,
"2.OTHER": RGB_SPEC,
"3.OTHER": RGB_SPEC,
"WORLD.RGB": RGB_VALUE,
}
actual = wrapped._get_observations(source)
expected = [
{"RGB": RGB_VALUE * 1, "WORLD.RGB": RGB_VALUE},
{"RGB": RGB_VALUE * 2, "WORLD.RGB": RGB_VALUE},
{"RGB": RGB_VALUE * 3, "WORLD.RGB": RGB_VALUE},
]
np.testing.assert_equal(actual, expected)
def test_get_action(self):
env = mock.Mock(spec_set=dmlab2d.Environment)
env.action_spec.return_value = {
"1.MOVE": ACT_SPEC,
"2.MOVE": ACT_SPEC,
"3.MOVE": ACT_SPEC,
}
wrapped = multiplayer_wrapper.Wrapper(
env, individual_observation_names=[], global_observation_names=[]
)
source = [
{"MOVE": ACT_VALUE * 1},
{"MOVE": ACT_VALUE * 2},
{"MOVE": ACT_VALUE * 3},
]
actual = wrapped._get_action(source)
expected = {
"1.MOVE": ACT_VALUE * 1,
"2.MOVE": ACT_VALUE * 2,
"3.MOVE": ACT_VALUE * 3,
}
np.testing.assert_equal(actual, expected)
def test_spec(self):
env = mock.Mock(spec_set=dmlab2d.Environment)
env.action_spec.return_value = {
"1.MOVE": ACT_SPEC,
"2.MOVE": ACT_SPEC,
"3.MOVE": ACT_SPEC,
}
env.observation_spec.return_value = {
"1.RGB": RGB_SPEC,
"2.RGB": RGB_SPEC,
"3.RGB": RGB_SPEC,
"1.OTHER": RGB_SPEC,
"2.OTHER": RGB_SPEC,
"3.OTHER": RGB_SPEC,
"1.REWARD": REWARD_SPEC,
"2.REWARD": REWARD_SPEC,
"3.REWARD": REWARD_SPEC,
"WORLD.RGB": RGB_SPEC,
}
wrapped = multiplayer_wrapper.Wrapper(
env,
individual_observation_names=["RGB"],
global_observation_names=["WORLD.RGB"],
)
with self.subTest("action_spec"):
self.assertEqual(
wrapped.action_spec(),
[
{"MOVE": ACT_SPEC.replace(name="MOVE")},
{"MOVE": ACT_SPEC.replace(name="MOVE")},
{"MOVE": ACT_SPEC.replace(name="MOVE")},
],
)
with self.subTest("observation_spec"):
self.assertEqual(
wrapped.observation_spec(),
[
{"RGB": RGB_SPEC, "WORLD.RGB": RGB_SPEC},
{"RGB": RGB_SPEC, "WORLD.RGB": RGB_SPEC},
{"RGB": RGB_SPEC, "WORLD.RGB": RGB_SPEC},
],
)
with self.subTest("reward_spec"):
self.assertEqual(
wrapped.reward_spec(), [REWARD_SPEC, REWARD_SPEC, REWARD_SPEC]
)
def test_step(self):
env = mock.Mock(spec_set=dmlab2d.Environment)
env.action_spec.return_value = {
"1.MOVE": ACT_VALUE * 1,
"2.MOVE": ACT_VALUE * 2,
"3.MOVE": ACT_VALUE * 3,
}
env.step.return_value = dm_env.transition(
1,
{
"1.RGB": RGB_VALUE * 1,
# Intentionally missing 2.RGB
"3.RGB": RGB_VALUE * 3,
"1.OTHER": RGB_VALUE,
"2.OTHER": RGB_VALUE,
"3.OTHER": RGB_VALUE,
"1.REWARD": REWARD_VALUE * 10,
"2.REWARD": REWARD_VALUE * 20,
"3.REWARD": REWARD_VALUE * 30,
"WORLD.RGB": RGB_VALUE,
},
)
wrapped = multiplayer_wrapper.Wrapper(
env,
individual_observation_names=["RGB"],
global_observation_names=["WORLD.RGB"],
)
actions = [
{"MOVE": ACT_VALUE * 1},
{"MOVE": ACT_VALUE * 2},
{"MOVE": ACT_VALUE * 3},
]
actual = wrapped.step(actions)
expected = dm_env.transition(
reward=[REWARD_VALUE * 10, REWARD_VALUE * 20, REWARD_VALUE * 30,],
observation=[
{"RGB": RGB_VALUE * 1, "WORLD.RGB": RGB_VALUE},
{"WORLD.RGB": RGB_VALUE},
{"RGB": RGB_VALUE * 3, "WORLD.RGB": RGB_VALUE},
],
)
with self.subTest("timestep"):
np.testing.assert_equal(actual, expected)
with self.subTest("action"):
(action,), _ = env.step.call_args
np.testing.assert_equal(
action,
{
"1.MOVE": ACT_VALUE * 1,
"2.MOVE": ACT_VALUE * 2,
"3.MOVE": ACT_VALUE * 3,
},
)
def test_reset(self):
env = mock.Mock(spec_set=dmlab2d.Environment)
env.action_spec.return_value = {
"1.MOVE": ACT_VALUE * 1,
"2.MOVE": ACT_VALUE * 2,
"3.MOVE": ACT_VALUE * 3,
}
env.reset.return_value = dm_env.restart(
{
"1.RGB": RGB_VALUE * 1,
"2.RGB": RGB_VALUE * 2,
"3.RGB": RGB_VALUE * 3,
"1.OTHER": RGB_VALUE,
"2.OTHER": RGB_VALUE,
"3.OTHER": RGB_VALUE,
"1.REWARD": REWARD_VALUE * 0,
"2.REWARD": REWARD_VALUE * 0,
"3.REWARD": REWARD_VALUE * 0,
"WORLD.RGB": RGB_VALUE,
}
)
wrapped = multiplayer_wrapper.Wrapper(
env,
individual_observation_names=["RGB"],
global_observation_names=["WORLD.RGB"],
)
actual = wrapped.reset()
expected = dm_env.TimeStep(
step_type=dm_env.StepType.FIRST,
reward=[REWARD_VALUE * 0, REWARD_VALUE * 0, REWARD_VALUE * 0,],
discount=0.0,
observation=[
{"RGB": RGB_VALUE * 1, "WORLD.RGB": RGB_VALUE},
{"RGB": RGB_VALUE * 2, "WORLD.RGB": RGB_VALUE},
{"RGB": RGB_VALUE * 3, "WORLD.RGB": RGB_VALUE},
],
)
np.testing.assert_equal(actual, expected)
if __name__ == "__main__":
absltest.main()
| [
"dm_env.transition",
"dm_env.specs.Array",
"absl.testing.absltest.main",
"dm_env.TimeStep",
"meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper",
"unittest.mock.Mock",
"numpy.ones",
"dm_env.specs.BoundedArray",
"dm_env.restart",
"numpy.testing.assert_equal"
] | [((832, 904), 'dm_env.specs.BoundedArray', 'dm_env.specs.BoundedArray', ([], {'shape': '()', 'minimum': '(0)', 'maximum': '(4)', 'dtype': 'np.int8'}), '(shape=(), minimum=0, maximum=4, dtype=np.int8)\n', (857, 904), False, 'import dm_env\n'), ((917, 943), 'numpy.ones', 'np.ones', (['[]'], {'dtype': 'np.int8'}), '([], dtype=np.int8)\n', (924, 943), True, 'import numpy as np\n'), ((955, 1005), 'dm_env.specs.Array', 'dm_env.specs.Array', ([], {'shape': '(8, 8, 3)', 'dtype': 'np.int8'}), '(shape=(8, 8, 3), dtype=np.int8)\n', (973, 1005), False, 'import dm_env\n'), ((1018, 1045), 'numpy.ones', 'np.ones', (['(8, 8, 3)', 'np.int8'], {}), '((8, 8, 3), np.int8)\n', (1025, 1045), True, 'import numpy as np\n'), ((1060, 1106), 'dm_env.specs.Array', 'dm_env.specs.Array', ([], {'shape': '()', 'dtype': 'np.float32'}), '(shape=(), dtype=np.float32)\n', (1078, 1106), False, 'import dm_env\n'), ((1122, 1151), 'numpy.ones', 'np.ones', (['()'], {'dtype': 'np.float32'}), '((), dtype=np.float32)\n', (1129, 1151), True, 'import numpy as np\n'), ((9106, 9121), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (9119, 9121), False, 'from absl.testing import absltest\n'), ((1254, 1293), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec_set': 'dmlab2d.Environment'}), '(spec_set=dmlab2d.Environment)\n', (1263, 1293), False, 'from unittest import mock\n'), ((1459, 1557), 'meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper', 'multiplayer_wrapper.Wrapper', (['env'], {'individual_observation_names': '[]', 'global_observation_names': '[]'}), '(env, individual_observation_names=[],\n global_observation_names=[])\n', (1486, 1557), False, 'from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper\n'), ((1679, 1718), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec_set': 'dmlab2d.Environment'}), '(spec_set=dmlab2d.Environment)\n', (1688, 1718), False, 'from unittest import mock\n'), ((1884, 1982), 'meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper', 'multiplayer_wrapper.Wrapper', (['env'], {'individual_observation_names': '[]', 'global_observation_names': '[]'}), '(env, individual_observation_names=[],\n global_observation_names=[])\n', (1911, 1982), False, 'from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper\n'), ((2401, 2440), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec_set': 'dmlab2d.Environment'}), '(spec_set=dmlab2d.Environment)\n', (2410, 2440), False, 'from unittest import mock\n'), ((2606, 2720), 'meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper', 'multiplayer_wrapper.Wrapper', (['env'], {'individual_observation_names': "['RGB']", 'global_observation_names': "['WORLD.RGB']"}), "(env, individual_observation_names=['RGB'],\n global_observation_names=['WORLD.RGB'])\n", (2633, 2720), False, 'from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper\n'), ((3306, 3347), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['actual', 'expected'], {}), '(actual, expected)\n', (3329, 3347), True, 'import numpy as np\n'), ((3394, 3433), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec_set': 'dmlab2d.Environment'}), '(spec_set=dmlab2d.Environment)\n', (3403, 3433), False, 'from unittest import mock\n'), ((3599, 3697), 'meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper', 'multiplayer_wrapper.Wrapper', (['env'], {'individual_observation_names': '[]', 'global_observation_names': '[]'}), '(env, individual_observation_names=[],\n global_observation_names=[])\n', (3626, 3697), False, 'from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper\n'), ((4051, 4092), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['actual', 'expected'], {}), '(actual, expected)\n', (4074, 4092), True, 'import numpy as np\n'), ((4133, 4172), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec_set': 'dmlab2d.Environment'}), '(spec_set=dmlab2d.Environment)\n', (4142, 4172), False, 'from unittest import mock\n'), ((4732, 4846), 'meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper', 'multiplayer_wrapper.Wrapper', (['env'], {'individual_observation_names': "['RGB']", 'global_observation_names': "['WORLD.RGB']"}), "(env, individual_observation_names=['RGB'],\n global_observation_names=['WORLD.RGB'])\n", (4759, 4846), False, 'from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper\n'), ((5799, 5838), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec_set': 'dmlab2d.Environment'}), '(spec_set=dmlab2d.Environment)\n', (5808, 5838), False, 'from unittest import mock\n'), ((6033, 6298), 'dm_env.transition', 'dm_env.transition', (['(1)', "{'1.RGB': RGB_VALUE * 1, '3.RGB': RGB_VALUE * 3, '1.OTHER': RGB_VALUE,\n '2.OTHER': RGB_VALUE, '3.OTHER': RGB_VALUE, '1.REWARD': REWARD_VALUE * \n 10, '2.REWARD': REWARD_VALUE * 20, '3.REWARD': REWARD_VALUE * 30,\n 'WORLD.RGB': RGB_VALUE}"], {}), "(1, {'1.RGB': RGB_VALUE * 1, '3.RGB': RGB_VALUE * 3,\n '1.OTHER': RGB_VALUE, '2.OTHER': RGB_VALUE, '3.OTHER': RGB_VALUE,\n '1.REWARD': REWARD_VALUE * 10, '2.REWARD': REWARD_VALUE * 20,\n '3.REWARD': REWARD_VALUE * 30, 'WORLD.RGB': RGB_VALUE})\n", (6050, 6298), False, 'import dm_env\n'), ((6545, 6659), 'meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper', 'multiplayer_wrapper.Wrapper', (['env'], {'individual_observation_names': "['RGB']", 'global_observation_names': "['WORLD.RGB']"}), "(env, individual_observation_names=['RGB'],\n global_observation_names=['WORLD.RGB'])\n", (6572, 6659), False, 'from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper\n'), ((6903, 7135), 'dm_env.transition', 'dm_env.transition', ([], {'reward': '[REWARD_VALUE * 10, REWARD_VALUE * 20, REWARD_VALUE * 30]', 'observation': "[{'RGB': RGB_VALUE * 1, 'WORLD.RGB': RGB_VALUE}, {'WORLD.RGB': RGB_VALUE},\n {'RGB': RGB_VALUE * 3, 'WORLD.RGB': RGB_VALUE}]"}), "(reward=[REWARD_VALUE * 10, REWARD_VALUE * 20, \n REWARD_VALUE * 30], observation=[{'RGB': RGB_VALUE * 1, 'WORLD.RGB':\n RGB_VALUE}, {'WORLD.RGB': RGB_VALUE}, {'RGB': RGB_VALUE * 3,\n 'WORLD.RGB': RGB_VALUE}])\n", (6920, 7135), False, 'import dm_env\n'), ((7687, 7726), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec_set': 'dmlab2d.Environment'}), '(spec_set=dmlab2d.Environment)\n', (7696, 7726), False, 'from unittest import mock\n'), ((7922, 8203), 'dm_env.restart', 'dm_env.restart', (["{'1.RGB': RGB_VALUE * 1, '2.RGB': RGB_VALUE * 2, '3.RGB': RGB_VALUE * 3,\n '1.OTHER': RGB_VALUE, '2.OTHER': RGB_VALUE, '3.OTHER': RGB_VALUE,\n '1.REWARD': REWARD_VALUE * 0, '2.REWARD': REWARD_VALUE * 0, '3.REWARD':\n REWARD_VALUE * 0, 'WORLD.RGB': RGB_VALUE}"], {}), "({'1.RGB': RGB_VALUE * 1, '2.RGB': RGB_VALUE * 2, '3.RGB': \n RGB_VALUE * 3, '1.OTHER': RGB_VALUE, '2.OTHER': RGB_VALUE, '3.OTHER':\n RGB_VALUE, '1.REWARD': REWARD_VALUE * 0, '2.REWARD': REWARD_VALUE * 0,\n '3.REWARD': REWARD_VALUE * 0, 'WORLD.RGB': RGB_VALUE})\n", (7936, 8203), False, 'import dm_env\n'), ((8406, 8520), 'meltingpot.python.utils.substrates.wrappers.multiplayer_wrapper.Wrapper', 'multiplayer_wrapper.Wrapper', (['env'], {'individual_observation_names': "['RGB']", 'global_observation_names': "['WORLD.RGB']"}), "(env, individual_observation_names=['RGB'],\n global_observation_names=['WORLD.RGB'])\n", (8433, 8520), False, 'from meltingpot.python.utils.substrates.wrappers import multiplayer_wrapper\n'), ((8616, 8912), 'dm_env.TimeStep', 'dm_env.TimeStep', ([], {'step_type': 'dm_env.StepType.FIRST', 'reward': '[REWARD_VALUE * 0, REWARD_VALUE * 0, REWARD_VALUE * 0]', 'discount': '(0.0)', 'observation': "[{'RGB': RGB_VALUE * 1, 'WORLD.RGB': RGB_VALUE}, {'RGB': RGB_VALUE * 2,\n 'WORLD.RGB': RGB_VALUE}, {'RGB': RGB_VALUE * 3, 'WORLD.RGB': RGB_VALUE}]"}), "(step_type=dm_env.StepType.FIRST, reward=[REWARD_VALUE * 0, \n REWARD_VALUE * 0, REWARD_VALUE * 0], discount=0.0, observation=[{'RGB':\n RGB_VALUE * 1, 'WORLD.RGB': RGB_VALUE}, {'RGB': RGB_VALUE * 2,\n 'WORLD.RGB': RGB_VALUE}, {'RGB': RGB_VALUE * 3, 'WORLD.RGB': RGB_VALUE}])\n", (8631, 8912), False, 'import dm_env\n'), ((9031, 9072), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['actual', 'expected'], {}), '(actual, expected)\n', (9054, 9072), True, 'import numpy as np\n'), ((7274, 7315), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['actual', 'expected'], {}), '(actual, expected)\n', (7297, 7315), True, 'import numpy as np\n'), ((7411, 7524), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['action', "{'1.MOVE': ACT_VALUE * 1, '2.MOVE': ACT_VALUE * 2, '3.MOVE': ACT_VALUE * 3}"], {}), "(action, {'1.MOVE': ACT_VALUE * 1, '2.MOVE': \n ACT_VALUE * 2, '3.MOVE': ACT_VALUE * 3})\n", (7434, 7524), True, 'import numpy as np\n')] |
'''
This script performs an A/B test on two groups, where the groups are
evaluated by some metric = distinct(devices that passed) / distinct(total devices)
where `bool passed` is a binomial random variable. The outcomes of both groups
in the experiment are simulated with some noise factor in order to be able to
observe both True and False rejection of the null hypothesis (i.e. no
statistically significant difference between the control and test groups).
With reference to: https://classroom.udacity.com/courses/ud257
'''
from random import random
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# p_*: experiment metric: probability of binomial outcome
# as N_* gets large binomial distribution ~ normal distribution
# helper functions
p_noise = lambda p, noise: min(0.99, max(0.01, p + (random() - 0.5) * noise))
p_gen = lambda p, N: np.random.binomial(1, p, size=N)
margin_of_error = lambda z, stderr: z * stderr
confidence_interval = lambda p, moe: (p - moe, p + moe)
# simulation constants
noise = 0.1
p = random()
N = 2000
Z = {95: 1.96, 99: 2.33} # {percentile: number of std dev}
z_exp = 95 # set the confidence interval we want for this experiment
# simulate the control set
p_cont = p_noise(p, noise)
N_cont = N
stderr_cont = ((p_cont * (1 - p_cont)) / N_cont) ** (0.5)
moe_cont = margin_of_error(Z[z_exp], stderr_cont)
conf_cont = confidence_interval(p_cont, moe_cont)
# Run experiment N times of N samples
# TODO: rewrite using matrix math
set_cont = []
for _ in range(N_cont):
set_temp = p_gen(p_cont, N_cont)
set_cont.append(np.average(set_temp))
set_cont = np.array(set_cont)
# test set
p_test = p_noise(p, noise)
N_test = N
stderr_test = ((p_test * (1 - p_test)) / N_test) ** (0.5)
moe_test = margin_of_error(Z[z_exp], stderr_test)
conf_test = confidence_interval(p_test, moe_test)
# Run experiment N times of N samples
# TODO: rewrite using matrix math
set_test = []
for _ in range(N_test):
set_temp = p_gen(p_test, N_test)
set_test.append(np.average(set_temp))
set_test = np.array(set_test)
# pooled probabilities (gaussian mixture)
p_pool = ((p_cont * N_cont) + (p_test * N_test)) / (N_cont + N_test)
stderr_pool = (p_pool * (1 - p_pool) * (1/N_cont + 1/N_test)) ** 0.5
p_diff = abs(p_test - p_cont) # null hypothesis states that p_diff == 0
moe_pool = margin_of_error(Z[z_exp], stderr_pool)
# evaluate experiment results
print("\nReject null hypothesis: {}".format(p_diff > moe_pool))
# visualize results of both groups
sns.set_palette("Paired")
fig, ax = plt.subplots()
for ab in [set_cont, set_test]:
sns.distplot(ab, ax=ax, kde=True)
| [
"numpy.random.binomial",
"numpy.average",
"random.random",
"numpy.array",
"seaborn.distplot",
"seaborn.set_palette",
"matplotlib.pyplot.subplots"
] | [((1044, 1052), 'random.random', 'random', ([], {}), '()\n', (1050, 1052), False, 'from random import random\n'), ((1615, 1633), 'numpy.array', 'np.array', (['set_cont'], {}), '(set_cont)\n', (1623, 1633), True, 'import numpy as np\n'), ((2043, 2061), 'numpy.array', 'np.array', (['set_test'], {}), '(set_test)\n', (2051, 2061), True, 'import numpy as np\n'), ((2496, 2521), 'seaborn.set_palette', 'sns.set_palette', (['"""Paired"""'], {}), "('Paired')\n", (2511, 2521), True, 'import seaborn as sns\n'), ((2532, 2546), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2544, 2546), True, 'import matplotlib.pyplot as plt\n'), ((868, 900), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'p'], {'size': 'N'}), '(1, p, size=N)\n', (886, 900), True, 'import numpy as np\n'), ((2583, 2616), 'seaborn.distplot', 'sns.distplot', (['ab'], {'ax': 'ax', 'kde': '(True)'}), '(ab, ax=ax, kde=True)\n', (2595, 2616), True, 'import seaborn as sns\n'), ((1582, 1602), 'numpy.average', 'np.average', (['set_temp'], {}), '(set_temp)\n', (1592, 1602), True, 'import numpy as np\n'), ((2010, 2030), 'numpy.average', 'np.average', (['set_temp'], {}), '(set_temp)\n', (2020, 2030), True, 'import numpy as np\n'), ((821, 829), 'random.random', 'random', ([], {}), '()\n', (827, 829), False, 'from random import random\n')] |
import time
import numpy as np
from typing import List, Dict, Union
from mot.utils import Config
from mot.structures import Tracklet
from .metric import Metric, METRIC_REGISTRY, build_metric
@METRIC_REGISTRY.register()
class CombinedMetric(Metric):
def __init__(self, metrics: List[Config], name: str = 'combined', **kwargs):
self.metrics = [build_metric(metric_cfg) for metric_cfg in metrics]
super(CombinedMetric, self).__init__(encoding='', name=name, **kwargs)
def affinity_matrix(self, tracklets: List[Tracklet], detection_features: List[Dict]) -> Union[
np.ndarray, List[List[float]]]:
matrices = []
for i in range(len(self.metrics)):
matrix = self.metrics[i](tracklets, detection_features)
matrices.append(matrix)
matrices = np.array(matrices)
matrix = np.zeros_like(matrices[0])
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
matrix[i][j] = self.combine(matrices[:, i, j])
# For debugging
self._log_affinity_matrix(matrix, tracklets, self.name)
return matrix
def similarity(self, tracklet_encoding: np.ndarray, detection_encoding: np.ndarray) -> Union[float, np.ndarray]:
return 0.0
def combine(self, scores):
raise NotImplementedError('Extend the CombinedMetric class to implement your own combination method.')
@METRIC_REGISTRY.register()
class ProductMetric(CombinedMetric):
def combine(self, scores):
return np.product(scores)
@METRIC_REGISTRY.register()
class SummationMetric(CombinedMetric):
def combine(self, scores):
return np.sum(scores)
@METRIC_REGISTRY.register()
class WeightedMetric(CombinedMetric):
def __init__(self, metrics, weights):
super().__init__(metrics)
self.weights = weights
def combine(self, scores):
return np.sum([score * weight for (score, weight) in zip(scores, self.weights)])
| [
"numpy.product",
"numpy.zeros_like",
"numpy.array",
"numpy.sum"
] | [((818, 836), 'numpy.array', 'np.array', (['matrices'], {}), '(matrices)\n', (826, 836), True, 'import numpy as np\n'), ((854, 880), 'numpy.zeros_like', 'np.zeros_like', (['matrices[0]'], {}), '(matrices[0])\n', (867, 880), True, 'import numpy as np\n'), ((1535, 1553), 'numpy.product', 'np.product', (['scores'], {}), '(scores)\n', (1545, 1553), True, 'import numpy as np\n'), ((1669, 1683), 'numpy.sum', 'np.sum', (['scores'], {}), '(scores)\n', (1675, 1683), True, 'import numpy as np\n')] |
import time
import re
import warnings
import nltk
import tweepy
import csv
import sys
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import requests
import json
from nltk.stem.porter import *
from wordcloud import WordCloud, STOPWORDS
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from googletrans import Translator
from sentiment.src.keys import twitter_keys
warnings.filterwarnings("ignore", category=DeprecationWarning)
analyser = SentimentIntensityAnalyzer()
translator = Translator()
sns.set()
consumer_key = twitter_keys['consumer_key']
consumer_secret = twitter_keys['consumer_secret']
access_token = twitter_keys['access_token']
access_token_secret = twitter_keys['access_token_secret']
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def sentiment_analyzer_scores(text, engl=True):
if engl:
trans = text
else:
trans = translator.translate(text).text
score = analyser.polarity_scores(trans)
lb = score['compound']
if lb >= 0.05:
return 1
elif (lb > -0.05) and (lb < 0.05):
return 0
else:
return -1
def list_tweets(user_id, count, prt=False):
tweets = api.user_timeline(
"@" + user_id, count=count, tweet_mode='extended')
tw = []
for t in tweets:
tw.append(t.full_text)
if prt:
print(t.full_text)
print()
return tw
def remove_pattern(input_txt, pattern):
r = re.findall(pattern, input_txt)
for i in r:
input_txt = re.sub(i, '', input_txt)
return input_txt
def clean_tweets(lst):
# remove twitter Return handles (RT @xxx:)
lst = np.vectorize(remove_pattern)(lst, "RT @[\w]*:")
# remove twitter handles (@xxx)
lst = np.vectorize(remove_pattern)(lst, "@[\w]*")
# remove URL links (httpxxx)
lst = np.vectorize(remove_pattern)(lst, "https?://[A-Za-z0-9./]*")
# remove special characters, numbers, punctuations (except for #)
lst = np.core.defchararray.replace(lst, "[^a-zA-Z#]", " ")
return lst
def anl_tweets(lst, title='Tweets Sentiment', engl=True ):
sents = []
for tw in lst:
try:
st = sentiment_analyzer_scores(tw, engl)
sents.append(st)
except:
sents.append(0)
ax = sns.distplot(
sents,
kde=False,
bins=3)
ax.set(xlabel='Negative Neutral Positive',
ylabel='#Tweets',
title="Tweets of @"+title)
return sents
def word_cloud(wd_list):
stopwords = set(STOPWORDS)
all_words = ' '.join([text for text in wd_list])
wordcloud = WordCloud(
background_color='white',
stopwords=stopwords,
width=1600,
height=800,
random_state=21,
colormap='jet',
max_words=50,
max_font_size=200).generate(all_words)
plt.figure(figsize=(12, 10))
plt.axis('off')
plt.imshow(wordcloud, interpolation="bilinear");
def twitter_stream_listener(file_name,
filter_track,
follow=None,
locations=None,
languages=None,
time_limit=20):
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, time_limit):
self.start_time = time.time()
self.limit = time_limit
# self.saveFile = open('abcd.json', 'a')
super(CustomStreamListener, self).__init__()
def on_status(self, status):
if (time.time() - self.start_time) < self.limit:
print(".", end="")
# Writing status data
with open(file_name, 'a') as f:
writer = csv.writer(f)
writer.writerow([
status.author.screen_name, status.created_at, status.text
])
else:
print("\n\n[INFO] Closing file and ending streaming")
return False
def on_error(self, status_code):
if status_code == 420:
print('Encountered error code 420. Disconnecting the stream')
# returning False in on_data disconnects the stream
return False
else:
print('Encountered error with status code: {}'.format(
status_code))
return True # Don't kill the stream
def on_timeout(self):
print('Timeout...')
return True # Don't kill the stream
# Writing csv titles
print(
'\n[INFO] Open file: [{}] and starting {} seconds of streaming for {}\n'
.format(file_name, time_limit, filter_track))
with open(file_name, 'w') as f:
writer = csv.writer(f)
writer.writerow(['author', 'date', 'text'])
streamingAPI = tweepy.streaming.Stream(
auth, CustomStreamListener(time_limit=time_limit))
streamingAPI.filter(
track=filter_track,
follow=follow,
locations=locations,
languages=languages,
)
f.close()
def hashtag_extract(x):
hashtags = []
# Loop over the words in the tweet
for i in x:
ht = re.findall(r"#(\w+)", i)
hashtags.append(ht)
return hashtags
def get_tweets(handle):
tweets = api.user_timeline(handle, count=5250, tweet_mode='extended')
rows = []
for t in tweets:
rows.append([t.author.screen_name,t.created_at,t.full_text,analyser.polarity_scores(t.full_text),sentiment_analyzer_scores(t.full_text)])
df_tws=pd.DataFrame(rows, columns=['author','created','text','polarity','sentiment'])
df_tws['text'] = clean_tweets(df_tws['text'])
print(df_tws.head())
HT_positive = hashtag_extract(df_tws['text'][df_tws['sentiment'] == 1]) # extracting hashtags from positive tweets
HT_negative = hashtag_extract(df_tws['text'][df_tws['sentiment'] == -1]) # extracting hashtags from negative tweets
# unnesting list
HT_positive = sum(HT_positive,[])
HT_negative = sum(HT_negative,[])
# Plot Pareto of positive tweets
a = nltk.FreqDist(HT_positive)
d = pd.DataFrame({'Hashtag': list(a.keys()),
'Count': list(a.values())})
# Select top 10 most frequent hashtags
d = d.nlargest(columns="Count", n = 10)
# plt.figure(figsize=(16,15))
# ax = sns.barplot(data=d, x = "Hashtag", y="Count")
# ax.set(ylabel = 'Count')
# plt.show()
return d
def main():
# print(analyser.polarity_scores("The movie is bad"))
# print(translator.translate('la pelicula es mala').text)
# text = translator.translate('la pelicula es mala').text
# print(analyser.polarity_scores(text))
tweets = api.user_timeline('@DrCDavies', count=5, tweet_mode='extended')
for t in tweets:
print(t.full_text)
print(analyser.polarity_scores(t.full_text))
print(sentiment_analyzer_scores(t.full_text))
print()
# user_id = 'realDonaldTrump'
# count = 200
# tw_trump = list_tweets(user_id, count)
# tw_trump = clean_tweets(tw_trump)
# print(sentiment_analyzer_scores(tw_trump))
# tw_trump_sent = anl_tweets(tw_trump,user_id)
# word_cloud(tw_trump)
# filter_track = ['arts', 'health']
# file_name = 'arts_health.csv'
# twitter_stream_listener (file_name, filter_track, time_limit=60)
#
# df_tws = pd.read_csv(file_name)
# df_tws['text'] = clean_tweets(df_tws['text'])
# df_tws['sentiment'] = anl_tweets(df_tws.text)
#
# # Words in positive tweets
# tws_pos = df_tws['text'][df_tws['sentiment']==1]
# tws_neg = df_tws['text'][df_tws['sentiment'] == -1]
#
# print(df_tws.head())
# word_cloud(df_tws.text)
# word_cloud(tws_pos)
# word_cloud(tws_neg)
#
# # extracting hashtags from positive tweets
# HT_positive = hashtag_extract(df_tws['text'][df_tws['sentiment'] == 1])
# # extracting hashtags from negative tweets
# HT_negative = hashtag_extract(df_tws['text'][df_tws['sentiment'] == -1])
# # unnesting list
# HT_positive = sum(HT_positive,[])
# HT_negative = sum(HT_negative,[])
#
# # Plot Pareto of positive tweets
# a = nltk.FreqDist(HT_positive)
# d = pd.DataFrame({'Hashtag': list(a.keys()),
# 'Count': list(a.values())})
# # Select top 10 most frequent hashtags
# d = d.nlargest(columns="Count", n = 10)
# plt.figure(figsize=(16,15))
# ax = sns.barplot(data=d, x = "Hashtag", y="Count")
# ax.set(ylabel = 'Count')
# plt.show()
#
# # Plot Pareto of negative tweets
# b = nltk.FreqDist(HT_positive)
# e = pd.DataFrame({'Hashtag': list(b.keys()),
# 'Count': list(b.values())})
# # Select top 10 most frequent hashtags
# e = e.nlargest(columns="Count", n = 10)
# plt.figure(figsize=(16,15))
# ax = sns.barplot(data=e, x = "Hashtag", y="Count")
# ax.set(ylabel = 'Count')
# plt.show()
if __name__ == "__main__":
main()
| [
"wordcloud.WordCloud",
"matplotlib.pyplot.figure",
"googletrans.Translator",
"pandas.DataFrame",
"matplotlib.pyplot.imshow",
"re.findall",
"numpy.core.defchararray.replace",
"seaborn.set",
"re.sub",
"numpy.vectorize",
"tweepy.API",
"csv.writer",
"tweepy.OAuthHandler",
"warnings.filterwarni... | [((432, 494), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (455, 494), False, 'import warnings\n'), ((506, 534), 'vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer', 'SentimentIntensityAnalyzer', ([], {}), '()\n', (532, 534), False, 'from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n'), ((548, 560), 'googletrans.Translator', 'Translator', ([], {}), '()\n', (558, 560), False, 'from googletrans import Translator\n'), ((561, 570), 'seaborn.set', 'sns.set', ([], {}), '()\n', (568, 570), True, 'import seaborn as sns\n'), ((775, 825), 'tweepy.OAuthHandler', 'tweepy.OAuthHandler', (['consumer_key', 'consumer_secret'], {}), '(consumer_key, consumer_secret)\n', (794, 825), False, 'import tweepy\n'), ((889, 905), 'tweepy.API', 'tweepy.API', (['auth'], {}), '(auth)\n', (899, 905), False, 'import tweepy\n'), ((1569, 1599), 're.findall', 're.findall', (['pattern', 'input_txt'], {}), '(pattern, input_txt)\n', (1579, 1599), False, 'import re\n'), ((2085, 2137), 'numpy.core.defchararray.replace', 'np.core.defchararray.replace', (['lst', '"""[^a-zA-Z#]"""', '""" """'], {}), "(lst, '[^a-zA-Z#]', ' ')\n", (2113, 2137), True, 'import numpy as np\n'), ((2395, 2433), 'seaborn.distplot', 'sns.distplot', (['sents'], {'kde': '(False)', 'bins': '(3)'}), '(sents, kde=False, bins=3)\n', (2407, 2433), True, 'import seaborn as sns\n'), ((2982, 3010), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 10)'}), '(figsize=(12, 10))\n', (2992, 3010), True, 'import matplotlib.pyplot as plt\n'), ((3015, 3030), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3023, 3030), True, 'import matplotlib.pyplot as plt\n'), ((3035, 3082), 'matplotlib.pyplot.imshow', 'plt.imshow', (['wordcloud'], {'interpolation': '"""bilinear"""'}), "(wordcloud, interpolation='bilinear')\n", (3045, 3082), True, 'import matplotlib.pyplot as plt\n'), ((5707, 5793), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': "['author', 'created', 'text', 'polarity', 'sentiment']"}), "(rows, columns=['author', 'created', 'text', 'polarity',\n 'sentiment'])\n", (5719, 5793), True, 'import pandas as pd\n'), ((6245, 6271), 'nltk.FreqDist', 'nltk.FreqDist', (['HT_positive'], {}), '(HT_positive)\n', (6258, 6271), False, 'import nltk\n'), ((1636, 1660), 're.sub', 're.sub', (['i', '""""""', 'input_txt'], {}), "(i, '', input_txt)\n", (1642, 1660), False, 'import re\n'), ((1763, 1791), 'numpy.vectorize', 'np.vectorize', (['remove_pattern'], {}), '(remove_pattern)\n', (1775, 1791), True, 'import numpy as np\n'), ((1857, 1885), 'numpy.vectorize', 'np.vectorize', (['remove_pattern'], {}), '(remove_pattern)\n', (1869, 1885), True, 'import numpy as np\n'), ((1944, 1972), 'numpy.vectorize', 'np.vectorize', (['remove_pattern'], {}), '(remove_pattern)\n', (1956, 1972), True, 'import numpy as np\n'), ((4906, 4919), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (4916, 4919), False, 'import csv\n'), ((5341, 5365), 're.findall', 're.findall', (['"""#(\\\\w+)"""', 'i'], {}), "('#(\\\\w+)', i)\n", (5351, 5365), False, 'import re\n'), ((2746, 2897), 'wordcloud.WordCloud', 'WordCloud', ([], {'background_color': '"""white"""', 'stopwords': 'stopwords', 'width': '(1600)', 'height': '(800)', 'random_state': '(21)', 'colormap': '"""jet"""', 'max_words': '(50)', 'max_font_size': '(200)'}), "(background_color='white', stopwords=stopwords, width=1600, height\n =800, random_state=21, colormap='jet', max_words=50, max_font_size=200)\n", (2755, 2897), False, 'from wordcloud import WordCloud, STOPWORDS\n'), ((3464, 3475), 'time.time', 'time.time', ([], {}), '()\n', (3473, 3475), False, 'import time\n'), ((3675, 3686), 'time.time', 'time.time', ([], {}), '()\n', (3684, 3686), False, 'import time\n'), ((3870, 3883), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (3880, 3883), False, 'import csv\n')] |
import numpy as np
from state import *
count_in_center=0
index_diff_block=-1
opposite_block=-1
def eval(cur_state:State):
global_point=np.zeros(9)
i=0
for block in cur_state.blocks:
point=0
countX_row=-np.count_nonzero(block==1, axis=1)
countX_col=-np.count_nonzero(block==1, axis=0)
countO_row=np.count_nonzero(block==-1, axis=1)
countO_col=np.count_nonzero(block==-1, axis=0)
for i in range(0,3):
if (countX_row[i]<0) and (countO_row[i]>0):
continue
else:
point+=(countX_row[i]+countO_row[i])
for i in range(0,3):
if (countX_col[i]<0) and (countO_col[i]>0):
continue
else:
point+=(countX_col[i]+countO_col[i])
countX_diagnol_topright=0
countO_diagnol_topright=0
countX_diagnol_topleft=0
countO_diagnol_topleft=0
for i in range (0,3):
if(block[i][i]==1):
countX_diagnol_topleft-=1
elif (block[i][i]==-1):
countO_diagnol_topleft+=1
if(block[i][2-i]==1):
countX_diagnol_topright-=1
elif (block[i][2-i]==-1):
countO_diagnol_topright+=1
if (countX_diagnol_topleft)==0 or (countO_diagnol_topleft)==0:
point+=(countX_diagnol_topleft+countO_diagnol_topleft)
if (countX_diagnol_topright)==0 or (countO_diagnol_topright)==0:
point+=(countX_diagnol_topright+countO_diagnol_topright)
global_point[i]=point
i+=1
return global_point.sum()
def max_value(cur_state, alpha, beta, depth):
leaf_state_val=terminate_state(cur_state, depth)
if leaf_state_val!=None:
return leaf_state_val
else:
v=-np.inf
valid_moves=cur_state.get_valid_moves
for move in valid_moves:
temp_state=State(cur_state)
temp_state.free_move=cur_state.free_move
temp_state.act_move(move)
val=min_value(temp_state, alpha, beta,depth-1)
v=max(v,val)
if(v>=beta):
return v
alpha=max(alpha, v)
return v
def min_value(cur_state, alpha, beta, depth):
leaf_state_val=terminate_state(cur_state, depth)
if leaf_state_val!=None:
return leaf_state_val
else:
v=np.inf
valid_moves=cur_state.get_valid_moves
if(len(valid_moves)!=0):
for move in valid_moves:
temp_state=State(cur_state)
temp_state.free_move=cur_state.free_move
temp_state.act_move(move)
val=max_value(temp_state, alpha, beta,depth-1)
v=min(v,val)
if(v<=alpha):
return v
beta=min(beta, v)
return v
def terminate_state(cur_state, depth):
if(depth==0):
return eval(cur_state)
else:
result=cur_state.game_result(cur_state.global_cells.reshape(3,3))
if(result!=None):
if(result==0): return 0
return -np.inf*result
else:
return None
def minimax_ab_cutoff(cur_state, tree_depth):
alpha=-np.inf
beta=np.inf
v=-np.inf
valid_moves=cur_state.get_valid_moves
if(len(valid_moves)!=0):
optimal_move=valid_moves[0]
for move in valid_moves:
temp_state=State(cur_state)
temp_state.free_move=cur_state.free_move
temp_state.act_move(move)
new_val=min_value(temp_state, alpha, beta, tree_depth)
if new_val>v:
v=new_val
alpha=v
optimal_move=move
return optimal_move
def select_move(cur_state, remain_time):
global index_diff_block
global count_in_center
global opposite_block
valid_moves = cur_state.get_valid_moves
##Go first
if(cur_state.player_to_move==1):
if(cur_state.previous_move==None):
count_in_center=0
index_diff_block=-1
opposite_block=-1
return UltimateTTT_Move(4,1,1,cur_state.player_to_move)
elif (index_diff_block==-1):
index_valid_block=cur_state.previous_move.x*3+cur_state.previous_move.y
if(count_in_center<7):
count_in_center+=1
return UltimateTTT_Move(index_valid_block, 1,1, cur_state.player_to_move)
else:
index_diff_block=index_valid_block
opposite_block=8-index_diff_block
return UltimateTTT_Move(index_diff_block, cur_state.previous_move.x,cur_state.previous_move.y, cur_state.player_to_move)
else:
if(cur_state.free_move==False):
if(cur_state.blocks[valid_moves[0].index_local_board][int(index_diff_block/3)][index_diff_block%3]==0):
return UltimateTTT_Move(valid_moves[0].index_local_board,int(index_diff_block/3),index_diff_block%3, cur_state.player_to_move)
else:
return UltimateTTT_Move(valid_moves[0].index_local_board,int((8-index_diff_block)/3),(8-index_diff_block)%3, cur_state.player_to_move)
if(cur_state.free_move==True):
if(cur_state.blocks[opposite_block][int(index_diff_block/3)][index_diff_block%3]==0):
return UltimateTTT_Move(opposite_block,int(index_diff_block/3),index_diff_block%3, cur_state.player_to_move)
else:
return UltimateTTT_Move(opposite_block,int((8-index_diff_block)/3),(8-index_diff_block)%3, cur_state.player_to_move)
#Go second
else:
return minimax_ab_cutoff(cur_state, 4)
return None
| [
"numpy.count_nonzero",
"numpy.zeros"
] | [((142, 153), 'numpy.zeros', 'np.zeros', (['(9)'], {}), '(9)\n', (150, 153), True, 'import numpy as np\n'), ((342, 379), 'numpy.count_nonzero', 'np.count_nonzero', (['(block == -1)'], {'axis': '(1)'}), '(block == -1, axis=1)\n', (358, 379), True, 'import numpy as np\n'), ((397, 434), 'numpy.count_nonzero', 'np.count_nonzero', (['(block == -1)'], {'axis': '(0)'}), '(block == -1, axis=0)\n', (413, 434), True, 'import numpy as np\n'), ((233, 269), 'numpy.count_nonzero', 'np.count_nonzero', (['(block == 1)'], {'axis': '(1)'}), '(block == 1, axis=1)\n', (249, 269), True, 'import numpy as np\n'), ((288, 324), 'numpy.count_nonzero', 'np.count_nonzero', (['(block == 1)'], {'axis': '(0)'}), '(block == 1, axis=0)\n', (304, 324), True, 'import numpy as np\n')] |
import torch
import numpy as np
from torchvision.datasets import ImageFolder
from transformers.models.vit.feature_extraction_vit import ViTFeatureExtractor
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
class SimMIMDataset(ImageFolder):
def __init__(self, root: str, image_size=192,
model_patch_size: int = 4, mask_patch_size: int = 32, mask_ratio: float = 0.5,
feature_extractor=ViTFeatureExtractor()):
assert isinstance(image_size, int)
super().__init__(root)
self.feature_extractor = feature_extractor
self.mask_generator = MaskGenerator(
input_size=image_size,
mask_patch_size=mask_patch_size,
model_patch_size=model_patch_size,
mask_ratio=mask_ratio,
)
self.transform_image = Compose(
[
Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),
RandomResizedCrop(image_size, scale=(0.67, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0)),
RandomHorizontalFlip(),
ToTensor(),
Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std),
]
)
def __getitem__(self, index: int):
image, _ = super().__getitem__(index)
return dict(pixel_values=self.transform_image(image), mask=self.mask_generator())
class MaskGenerator:
"""
A class to generate boolean masks for the pretraining task.
A mask is a 1D tensor of shape (model_patch_size**2,) where the value is either 0 or 1,
where 1 indicates "masked".
"""
def __init__(self, input_size=192, mask_patch_size=32, model_patch_size=4, mask_ratio=0.6):
self.input_size = input_size
self.mask_patch_size = mask_patch_size
self.model_patch_size = model_patch_size
self.mask_ratio = mask_ratio
if self.input_size % self.mask_patch_size != 0:
raise ValueError("Input size must be divisible by mask patch size")
if self.mask_patch_size % self.model_patch_size != 0:
raise ValueError("Mask patch size must be divisible by model patch size")
self.rand_size = self.input_size // self.mask_patch_size
self.scale = self.mask_patch_size // self.model_patch_size
self.token_count = self.rand_size ** 2
self.mask_count = int(np.ceil(self.token_count * self.mask_ratio))
def __call__(self):
mask_idx = np.random.permutation(self.token_count)[: self.mask_count]
mask = np.zeros(self.token_count, dtype=int)
mask[mask_idx] = 1
mask = mask.reshape((self.rand_size, self.rand_size))
mask = mask.repeat(self.scale, axis=0).repeat(self.scale, axis=1)
return torch.tensor(mask.flatten())
| [
"transformers.models.vit.feature_extraction_vit.ViTFeatureExtractor",
"numpy.ceil",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.transforms.Normalize",
"numpy.zeros",
"numpy.random.permutation",
"torchvision.transforms.RandomResizedCrop",
"torchvision.transforms.ToTensor"
] | [((486, 507), 'transformers.models.vit.feature_extraction_vit.ViTFeatureExtractor', 'ViTFeatureExtractor', ([], {}), '()\n', (505, 507), False, 'from transformers.models.vit.feature_extraction_vit import ViTFeatureExtractor\n'), ((2605, 2642), 'numpy.zeros', 'np.zeros', (['self.token_count'], {'dtype': 'int'}), '(self.token_count, dtype=int)\n', (2613, 2642), True, 'import numpy as np\n'), ((2442, 2485), 'numpy.ceil', 'np.ceil', (['(self.token_count * self.mask_ratio)'], {}), '(self.token_count * self.mask_ratio)\n', (2449, 2485), True, 'import numpy as np\n'), ((2531, 2570), 'numpy.random.permutation', 'np.random.permutation', (['self.token_count'], {}), '(self.token_count)\n', (2552, 2570), True, 'import numpy as np\n'), ((1009, 1087), 'torchvision.transforms.RandomResizedCrop', 'RandomResizedCrop', (['image_size'], {'scale': '(0.67, 1.0)', 'ratio': '(3.0 / 4.0, 4.0 / 3.0)'}), '(image_size, scale=(0.67, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0))\n', (1026, 1087), False, 'from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor\n'), ((1105, 1127), 'torchvision.transforms.RandomHorizontalFlip', 'RandomHorizontalFlip', ([], {}), '()\n', (1125, 1127), False, 'from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor\n'), ((1145, 1155), 'torchvision.transforms.ToTensor', 'ToTensor', ([], {}), '()\n', (1153, 1155), False, 'from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor\n'), ((1173, 1250), 'torchvision.transforms.Normalize', 'Normalize', ([], {'mean': 'feature_extractor.image_mean', 'std': 'feature_extractor.image_std'}), '(mean=feature_extractor.image_mean, std=feature_extractor.image_std)\n', (1182, 1250), False, 'from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor\n')] |
# -*- coding: utf-8 -*-
import cv2
import cv2.cv as cv
import numpy as np
def logpolar(src, center, magnitude_scale = 40):
mat1 = cv.fromarray(np.float64(src))
mat2 = cv.CreateMat(src.shape[0], src.shape[1], mat1.type)
cv.LogPolar(mat1, mat2, center, magnitude_scale, \
cv.CV_INTER_CUBIC+cv.CV_WARP_FILL_OUTLIERS)
return np.asarray(mat2)
| [
"numpy.float64",
"numpy.asarray",
"cv2.cv.LogPolar",
"cv2.cv.CreateMat"
] | [((178, 229), 'cv2.cv.CreateMat', 'cv.CreateMat', (['src.shape[0]', 'src.shape[1]', 'mat1.type'], {}), '(src.shape[0], src.shape[1], mat1.type)\n', (190, 229), True, 'import cv2.cv as cv\n'), ((235, 334), 'cv2.cv.LogPolar', 'cv.LogPolar', (['mat1', 'mat2', 'center', 'magnitude_scale', '(cv.CV_INTER_CUBIC + cv.CV_WARP_FILL_OUTLIERS)'], {}), '(mat1, mat2, center, magnitude_scale, cv.CV_INTER_CUBIC + cv.\n CV_WARP_FILL_OUTLIERS)\n', (246, 334), True, 'import cv2.cv as cv\n'), ((358, 374), 'numpy.asarray', 'np.asarray', (['mat2'], {}), '(mat2)\n', (368, 374), True, 'import numpy as np\n'), ((150, 165), 'numpy.float64', 'np.float64', (['src'], {}), '(src)\n', (160, 165), True, 'import numpy as np\n')] |
import numpy as np
def beta_binomial_prior_distribution(phoneme_count, mel_count, scaling_factor=1.0):
from scipy.stats import betabinom
x = np.arange(0, phoneme_count)
mel_text_probs = []
for i in range(1, mel_count + 1):
a, b = scaling_factor * i, scaling_factor * (mel_count + 1 - i)
mel_i_prob = betabinom(phoneme_count, a, b).pmf(x)
mel_text_probs.append(mel_i_prob)
return np.array(mel_text_probs)
def mas(attn_map, width=1):
# assumes mel x text
opt = np.zeros_like(attn_map)
attn_map = np.log(attn_map)
attn_map[0, 1:] = -np.inf
log_p = np.zeros_like(attn_map)
log_p[0, :] = attn_map[0, :]
prev_ind = np.zeros_like(attn_map, dtype=np.int64)
for i in range(1, attn_map.shape[0]):
for j in range(attn_map.shape[1]):
prev_j = np.arange(max(0, j - width), j + 1)
prev_log = np.array([log_p[i - 1, prev_idx] for prev_idx in prev_j])
ind = np.argmax(prev_log)
log_p[i, j] = attn_map[i, j] + prev_log[ind]
prev_ind[i, j] = prev_j[ind]
# now backtrack
curr_text_idx = attn_map.shape[1] - 1
for i in range(attn_map.shape[0] - 1, -1, -1):
opt[i, curr_text_idx] = 1
curr_text_idx = prev_ind[i, curr_text_idx]
opt[0, curr_text_idx] = 1
assert opt.sum(0).all()
assert opt.sum(1).all()
return opt
def binarize_attention(attn, in_len, out_len):
b_size = attn.shape[0]
attn_cpu = attn
attn_out = np.zeros_like(attn)
for ind in range(b_size):
hard_attn = mas(attn_cpu[ind, 0, : out_len[ind], : in_len[ind]])
attn_out[ind, 0, : out_len[ind], : in_len[ind]] = hard_attn
return attn_out
| [
"numpy.zeros_like",
"numpy.log",
"numpy.argmax",
"numpy.array",
"numpy.arange",
"scipy.stats.betabinom"
] | [((152, 179), 'numpy.arange', 'np.arange', (['(0)', 'phoneme_count'], {}), '(0, phoneme_count)\n', (161, 179), True, 'import numpy as np\n'), ((426, 450), 'numpy.array', 'np.array', (['mel_text_probs'], {}), '(mel_text_probs)\n', (434, 450), True, 'import numpy as np\n'), ((516, 539), 'numpy.zeros_like', 'np.zeros_like', (['attn_map'], {}), '(attn_map)\n', (529, 539), True, 'import numpy as np\n'), ((555, 571), 'numpy.log', 'np.log', (['attn_map'], {}), '(attn_map)\n', (561, 571), True, 'import numpy as np\n'), ((614, 637), 'numpy.zeros_like', 'np.zeros_like', (['attn_map'], {}), '(attn_map)\n', (627, 637), True, 'import numpy as np\n'), ((686, 725), 'numpy.zeros_like', 'np.zeros_like', (['attn_map'], {'dtype': 'np.int64'}), '(attn_map, dtype=np.int64)\n', (699, 725), True, 'import numpy as np\n'), ((1499, 1518), 'numpy.zeros_like', 'np.zeros_like', (['attn'], {}), '(attn)\n', (1512, 1518), True, 'import numpy as np\n'), ((891, 948), 'numpy.array', 'np.array', (['[log_p[i - 1, prev_idx] for prev_idx in prev_j]'], {}), '([log_p[i - 1, prev_idx] for prev_idx in prev_j])\n', (899, 948), True, 'import numpy as np\n'), ((968, 987), 'numpy.argmax', 'np.argmax', (['prev_log'], {}), '(prev_log)\n', (977, 987), True, 'import numpy as np\n'), ((335, 365), 'scipy.stats.betabinom', 'betabinom', (['phoneme_count', 'a', 'b'], {}), '(phoneme_count, a, b)\n', (344, 365), False, 'from scipy.stats import betabinom\n')] |
import tvm
from tvm import te, topi,autotvm
from tvm.topi import nn
import tvm.testing
from tvm import te
import numpy
import numpy as np
import timeit
from tvm.topi.mali import mali_winograd as tune_winograd
from tvm.topi.testing import conv2d_nchw_python
from tvm.contrib.utils import tempdir
# The size of the matrix
# (M, K) x (K, N)
# You are free to try out different shapes, sometimes TVM optimization outperforms numpy with MKL.
MD = 4
K = 3
N = 3
IC=160
OC=320
# The default tensor type in tvm
ddtype = "climgfloatr32"
out_dtype = "climgfloatw32"
#ddtype=out_dtype='float32'
# using Intel AVX2(Advanced Vector Extensions) ISA for SIMD
# To get the best performance, please change the following line
# to llvm -mcpu=core-avx2, or specific type of CPU you use
target = "opencl"
ctx = tvm.context(target, 0)
# Random generated tensor for testing
MD=4
K=3
r = K
m = 2
A, B, G = tvm.topi.nn.winograd_util.winograd_transform_matrices(m, r, 'float32')
data_shape = (1, 128 // 4, 28, 28, 4)
kernel_shape = (128, 64 // 4, 3, 3, 1, 4)
out_shape = (1, 128 // 4, 28, 28, 4)
tile_size = 2
wino_size = tile_size + 2
wino_all_size = wino_size * wino_size
winop2_tile_size = wino_all_size
alpha = wino_size
img_H = data_shape[2]
img_W = data_shape[3]
wino2H = (img_H+tile_size-1)//tile_size
wino2W = (img_W + tile_size - 1) // tile_size
oc_chunk = out_shape[1]
CO = oc_chunk*4
CI=kernel_shape[0]
NTILE = wino2H*wino2H
data_pl = te.placeholder((1, CI//4, img_H, img_W, 4),
name='placeholder', dtype=ddtype)
kernel_pl = te.placeholder((CI, CO//4, 3, 3,1,4),
name='placeholder', dtype=ddtype)
conv_pl = topi.mali.conv2d_nchw_winograd_NCHWc_io(data_pl, kernel_pl, 1, 1,
1, "","",ddtype.replace('r','w'))
# Algorithm
# kernel transform
#k1 = te.reduce_axis((0, K), "k1")
#k2 = te.reduce_axis((0, K), "k2")
##G = te.placeholder((MD, K), name="G")
#filter_n = te.placeholder((IC,OC,K, K,1,4), name="filter")
#U = te.compute((IC, OC//4, wino_size, wino_size, 1, 4), lambda ic, oc, x, y, bi, bo:
# te.sum(G[x, k2] * filter_n[ic, oc, k2, k1, bi, bo]*G[y, k1],
# axis=[k2, k1]),
# name="U")
#U = tune_winograd.kernel_transform(kernel_shape, wino_size, G=G)
# Default schedule
#s = te.create_schedule(U.op)
# data transform
#k1 = te.reduce_axis((0, alpha), "r_a")
#k2 = te.reduce_axis((0, alpha), "r_b")
##B = te.placeholder((MD, MD), name="B")
#Data = te.placeholder((1,IC//4,img_H, img_W,4), name="Data")
#N=1
#pt = pl = pb = pr = tile_size - 1
#Data_pad = nn.pad(Data, (0, 0, pt, pl, 0), (0, 0, pb, pr, 0), name="Data_pad")
#def _transform_V(ic, oc, x, y, bo):
# tx = y // wino2W * wino_size + x // wino_size
# ty = (y % wino2W) * wino_size + x % wino_size
# ox = tx // wino_size * tile_size + k2 - 1
# oy = ty // wino_size * tile_size + k1 - 1
# return te.sum(B[k2, tx % wino_size]*Data_pad[ic, oc, ox, oy, bo]*B[k1, ty % wino_size],
# axis=[k2, k1],
# )
#
#
#V = te.compute((N, IC // 4, wino_size*wino_size, ((img_H + tile_size-1) // tile_size) * ((img_W + tile_size-1) // tile_size), 4),
# _transform_V,
# name="V")
#V = tune_winograd.data_transform(data_shape, wino_size, B=B)
#s = te.create_schedule(V.op)
#func = tvm.build(s, [Data,V], target=target)
#assert func
#print(func.imported_modules[0].get_source()) if len(func.imported_modules) > 0 else print("source not imported")
#print(tvm.lower(s, [Data,V], simple_mode=True))
#rc = te.reduce_axis((0, IC), "r_c")
#M = te.compute((N, OC//4, wino_all_size, wino2H * wino2W, 4), lambda n, oc, h, w, bo:
# te.sum(U[rc, oc, h//wino_size, h % wino_size, 0, bo]*V[n, rc//4, h, w, rc % 4],
# axis=[rc]),
# name="M"
# )
#M = tune_winograd.batch_gemm(U, V)
#s = te.create_schedule(M.op)
#func = tvm.build(s, [U,V,M], target=target)
#assert func
#print(func.imported_modules[0].get_source()) if len(func.imported_modules) > 0 else print("source not imported")
#print(tvm.lower(s, [U,V,M], simple_mode=True))
#print(tvm.lower(s, [filter_n,Data,M], simple_mode=True))
# inverse transform
#k1 = te.reduce_axis((0, alpha), "r_a")
#k2 = te.reduce_axis((0, alpha), "r_b")
#def _transform_inverse(n, oc, h, w, bo):
# th = h // tile_size * wino_size + k2
# tw = w // tile_size * wino_size + k1
#
# oh = (th % wino_size + tw // wino_size) * wino_size + tw % wino_size
# ow = tw // wino_size + (th // wino_size) * wino2W
#
# #AT(th % tile_size, k2) * M[ox][oy] * A(k1, tw % 2)
# return te.sum(A[k2, th % tile_size]*M[n, oc, oh, ow, bo]*A[k1, tw % tile_size],
# axis=[k1, k2])
#
##int th = int(h / tile_size) * wino_size + k2;
##int tw = int(w / tile_size) * wino_size + k1;
##
##int ox = (th % wino_size) * wino_size + tw % wino_size;
##int oy = int(tw / wino_size) + int(th / wino_size) * trans_image_size_block_W;
##output[h][w] += AT(th % tile_size, k2) * M[ox][oy] * A(k1, tw % 2);
#
#
#output = te.compute((1, OC//4, img_H, img_W, 4), _transform_inverse,
# name="output"
# )
#output = tune_winograd.inverse_transform(out_shape, A=A, M=M)
output = conv_pl
print(output.shape)
s = te.create_schedule(output.op)
# schedule for U
#========shedule begin=================================
def s1(s, G, filter_n, U):
s[G].compute_inline()
WL = s.cache_read(filter_n, "local", [U])
UL = s.cache_write(U, "local")
# Get the GPU thread indices
block_x = te.thread_axis("blockIdx.x")
block_y = te.thread_axis("blockIdx.y")
block_z = te.thread_axis("blockIdx.z")
thread_x = te.thread_axis( "threadIdx.x")
thread_y = te.thread_axis("threadIdx.y")
thread_z = te.thread_axis("threadIdx.z")
# Split the workloads
cp, kp, Uhp, Uwp, _, Up4 = s[U].op.axis
cpo,cpi=s[U].split(cp,factor=4)
kpo,kpi=s[U].split(kp,factor=4)
s[U].bind(cpo, block_x)
s[U].bind(kpo, block_y)
s[U].bind(kpi, thread_x)
s[U].bind(cpi, thread_y)
s[U].reorder(cpo,cpi,kpi,Uhp,Uwp,Up4,kpo)
# Schedule BL local write
s[UL].compute_at(s[U],kpo)
_,_,hp, wp, _, p4 = s[UL].op.axis
s[UL].reorder(hp,wp,p4)
s[UL].vectorize(p4)
k1,k2 = s[UL].op.reduce_axis
#s[UL].unroll(wp)
#s[UL].unroll(hp)
#s[UL].unroll(k1)
#s[UL].unroll(k2)
s[WL].compute_at(s[UL], hp)
_,_,hp, wp,_, p4 = s[WL].op.axis
s[WL].vectorize(p4) # vectorize memory load
#s[WL].unroll(wp)
#s[WL].unroll(hp)
s[U].vectorize(Up4) # vectorize memory load
#s[U].unroll(Uwp) # vectorize memory load
#s[U].unroll(Uhp) # vectorize memory load
##========shedule end=================================
## shedule for V
##========shedule begin=================================
def s2(s,B,DataPad,V):
s[B].compute_inline()
_, _Data = s[V].op.input_tensors
s[DataPad].compute_inline()
WL = s.cache_read(DataPad, "local", [V])
VL = s.cache_write(V, "local")
# Get the GPU thread indices
block_x = te.thread_axis("blockIdx.x")
block_y = te.thread_axis("blockIdx.y")
block_z = te.thread_axis("blockIdx.z")
thread_x = te.thread_axis( "threadIdx.x")
thread_y = te.thread_axis("threadIdx.y")
thread_z = te.thread_axis("threadIdx.z")
# Split the workloads
n, cp, hp, wp, Vp4 = s[V].op.axis
cpo,cpi=s[V].split(cp,factor=4)
wp,Vwp=s[V].split(wp,factor=4)
wpo,wpi=s[V].split(wp,factor=4)
hp,Vhp=s[V].split(hp,factor=4)
hpo,hpi=s[V].split(hp,factor=4)
s[V].bind(wpo, block_x)
s[V].bind(hpo, block_y)
s[V].bind(cpo, block_z)
s[V].bind(wpi, thread_x)
s[V].bind(hpi, thread_y)
s[V].bind(cpi, thread_z)
s[V].reorder(cpo,cpi,hpo,hpi,wpi,wpo,Vp4,n)
# Schedule BL local write
s[VL].compute_at(s[V],n)
_,_, hp, wp, p4 = s[VL].op.axis
s[VL].reorder(hp,wp,p4)
s[VL].vectorize(p4)
k1,k2 = s[VL].op.reduce_axis
#s[VL].unroll(wp)
#s[VL].unroll(hp)
#s[VL].unroll(k1)
#s[VL].unroll(k2)
s[WL].compute_at(s[VL], hp)
_,_,hp, wp, p4 = s[WL].op.axis
s[WL].vectorize(p4) # vectorize memory load
#s[WL].unroll(wp)
#s[WL].unroll(hp)
s[V].vectorize(Vp4) # vectorize memory load
#s[V].unroll(Vwp) # vectorize memory load
#s[V].unroll(Vhp) # vectorize memory load
##========shedule end=================================
## shedule for M
##========shedule begin=================================
def s3(s, U, V, M):
UL = s.cache_read(U, "local", [M])
VL = s.cache_read(V, "local", [M])
ML = s.cache_write(M, "local")
# Get the GPU thread indices
block_x = te.thread_axis("blockIdx.x")
block_y = te.thread_axis("blockIdx.y")
block_z = te.thread_axis("blockIdx.z")
thread_x = te.thread_axis( "threadIdx.x")
thread_y = te.thread_axis("threadIdx.y")
thread_z = te.thread_axis("threadIdx.z")
# Split the workloads
n, kp, hp, wp, Mp4 = s[M].op.axis
kpo,kpi=s[M].split(kp,factor=4)
wp,Mwp=s[M].split(wp,factor=4)
wpo,wpi=s[M].split(wp,factor=4)
hpo,hpi=s[M].split(hp,factor=4)
s[M].bind(wpo, block_x)
s[M].bind(hpo, block_z)
s[M].bind(kpo, block_y)
s[M].bind(wpi, thread_x)
s[M].bind(hpi, thread_z)
s[M].bind(kpi, thread_y)
s[M].reorder(kpo,hpo,hpi,wpi,wpo,Mwp,Mp4,kpi)
# Schedule BL local write
s[ML].compute_at(s[M],kpi)
s[M].reorder(kpi, Mwp, Mp4)
_,_, hp, wp, p4 = s[ML].op.axis
rc, = s[ML].op.reduce_axis
rco,rci = s[ML].split(rc,factor=4)
s[ML].reorder(rco,wp,rci,p4)
s[ML].vectorize(p4)
#s[ML].unroll(wp)
#s[ML].unroll(hp)
#s[ML].unroll(k1)
#schedule UL VL local read
s[UL].compute_at(s[ML], rco)
s[VL].compute_at(s[ML], rco)
#split Ul VL workload
a,b,hp, wp, _,p4 = s[UL].op.axis
s[UL].vectorize(p4) # vectorize memory load
#s[UL].unroll(wp)
#s[UL].unroll(hp)
_,_,hp, wp, p4 = s[VL].op.axis
s[VL].vectorize(p4) # vectorize memory load
#s[VL].unroll(wp)
#s[VL].unroll(hp)
s[M].vectorize(Mp4) # vectorize memory load
#s[M].unroll(Mwp) # vectorize memory load
#s[M].unroll(Mhp) # vectorize memory load
##========shedule end=================================
#
##shedule for output
##========shedule begin=================================
def s4(s, A, M, output):
O = output
s[A].compute_inline()
ML = s.cache_read(M, "local", [O])
OL = s.cache_write(O, "local")
# Get the GPU thread indices
block_x = te.thread_axis("blockIdx.x")
block_y = te.thread_axis("blockIdx.y")
block_z = te.thread_axis("blockIdx.z")
thread_x = te.thread_axis("threadIdx.x")
thread_y = te.thread_axis("threadIdx.y")
thread_z = te.thread_axis("threadIdx.z")
# Split the workloads
n, cp, hp, wp, Op4 = s[O].op.axis
cpo,cpi=s[O].split(cp,factor=4)
wp,Owp=s[O].split(wp,factor=4)
wpo,wpi=s[O].split(wp,factor=4)
hp,Ohp=s[O].split(hp,factor=4)
hpo,hpi=s[O].split(hp,factor=4)
s[O].bind(wpo, block_x)
s[O].bind(hpo, block_y)
s[O].bind(cpo, block_z)
s[O].bind(wpi, thread_x)
s[O].bind(hpi, thread_y)
s[O].bind(cpi, thread_z)
s[O].reorder(cpo,cpi,hpo,hpi,wpi,wpo,Owp,Ohp,Op4,n)
# Schedule BL local write
s[OL].compute_at(s[O],n)
_,_, hp, wp, p4 = s[OL].op.axis
s[OL].reorder(hp,wp,p4)
s[OL].vectorize(p4)
k1,k2 = s[OL].op.reduce_axis
#s[OL].unroll(wp)
#s[OL].unroll(hp)
#s[OL].unroll(k1)
#s[OL].unroll(k2)
s[ML].compute_at(s[OL], hp)
_,_,hp, wp, p4 = s[ML].op.axis
s[ML].vectorize(p4) # vectorize memory load
#s[ML].unroll(wp)
#s[ML].unroll(hp)
s[O].vectorize(Op4) # vectorize memory load
#s[O].unroll(Owp) # vectorize memory load
#s[O].unroll(Ohp) # vectorize memory load
##========shedule end=================================
O = output
A, M = s[O].op.input_tensors
U, V = s[M].op.input_tensors
G, filter_n = s[U].op.input_tensors
B, DataPad = s[V].op.input_tensors
Data, = s[DataPad].op.input_tensors
def shecule_default():
s1(s, G, filter_n, U)
s2(s, B, DataPad, V)
s3(s, U, V, M)
s4(s, A, M, output)
##========shedule begin=================================
##### space definition begin #####
cfg = tvm.autotvm.get_config()
cfg.define_split("inv_cp", oc_chunk, num_outputs=2, max_factor=8)
cfg.define_split("inv_wp", NTILE, num_outputs=3,
filter=lambda x: x.size[-1] == 4)
cfg.define_split("inv_hp", winop2_tile_size, num_outputs=3,
filter=lambda x: x.size[-1] == 4)
cfg.define_split("kernel_cp", CI, num_outputs=2, max_factor=32)
cfg.define_split("kernel_kp", oc_chunk, num_outputs=2, max_factor=32)
cfg.define_split("data_cp", oc_chunk, num_outputs=2, max_factor=32)
cfg.define_split("data_wp", oc_chunk, num_outputs=3,
filter=lambda x: x.size[-1] % 4 == 0)
cfg.define_split("data_hp", oc_chunk, num_outputs=3,
filter=lambda x: x.size[-1] % 4 == 0)
cfg.define_split("bgemm_kp", oc_chunk, num_outputs=2, max_factor=32)
cfg.define_split("bgemm_wp", oc_chunk, num_outputs=3,
filter=lambda x: x.size[-1] % 4 == 0)
cfg.define_split("bgemm_hp", oc_chunk, num_outputs=2)
##### space definition end #####
#tune_winograd._schedule_winograd_nchwc_io(cfg, s, output.op)
shecule_default()
##========shedule end=================================
#============for andriod=====================
arch = "arm64"
target_host = tvm.target.Target("llvm -mtriple=%s-linux-android" % arch)
target = tvm.target.Target("opencl -device=mali")
# Also replace this with the device key in your tracker
device_key = "MaliG72"
use_android=True
#===============anriod end==================
func = tvm.build(s, [Data, filter_n, output],
target=target,
target_host=target_host)
#assert func
#print(tvm.lower(s, [M,output], simple_mode=True))
#print(tvm.lower(s, [filter_n,Data,output], simple_mode=True))
with open('dd.cl','w') as fp:
print(func.imported_modules[0].get_source(), file=fp) if len(
func.imported_modules) > 0 else print("source not imported", file=fp)
dsp = tuple(int(i) for i in Data.shape)
fsp = tuple(int(i) for i in filter_n.shape)
osp = tuple(int(i) for i in output.shape)
###############test data=====================
#########andriod======================
tmp = tempdir()
if use_android:
from tvm.contrib import ndk
filename = "net.so"
func.export_library(tmp.relpath(filename), ndk.create_shared)
else:
filename = "net.tar"
func.export_library(tmp.relpath(filename))
# upload module to device
print("Upload...")
remote = autotvm.measure.request_remote(device_key, '0.0.0.0', 9090,
timeout=10000)
remote.upload(tmp.relpath(filename))
func = remote.load_module(filename)
# upload parameters to device
ctx = remote.context(str(target), 0)
#===============================================
a_np = np.arange(np.prod(dsp))
PACK4=4
H_P =img_H
W_P =img_W
C_P = CI//4
in_channel=CI
out_channel=CO
K_P=CO//4
a_np = a_np.reshape(1, C_P*PACK4, H_P, W_P)
a_np_t = a_np
w_np_t = np.arange(in_channel*out_channel*9).reshape(out_channel,in_channel,3,3)
w_np = w_np_t
#==A-tvm data prepare
a_np_tvm=np.ndarray(0)
for i in range(0,in_channel,4):
b=a_np[:,i:i+4,:,:].transpose(0,2,3,1)
ct=np.expand_dims(b,axis=1)
if len(a_np_tvm.shape)!=5:
a_np_tvm=ct
else:
a_np_tvm=np.concatenate((a_np_tvm,ct),axis=1)
a_np_tvm = a_np_tvm*1.0
#==W-tvm data prepare
w_np_tvm=np.ndarray(0)
for i in range(0,out_channel,4):
b=w_np[:,i:i+4,:,:].transpose(0,2,3,1)
ct=np.expand_dims(b,axis=1)
if len(w_np_tvm.shape)!=5:
w_np_tvm=ct
else:
w_np_tvm=np.concatenate((w_np_tvm,ct),axis=1)
w_np_tvm = np.expand_dims(w_np_tvm, axis=-2)
w_np_tvm = w_np_tvm* 1.0
##################=========end================
strides=1
padding=1
c_np = conv2d_nchw_python(a_np_t, w_np_t, strides, padding)
#=============##############
#data_tvm = tvm.nd.array(numpy.random.rand(*dsp).astype('float32'), ctx,dtype=ddtype)
#filter_tvm = tvm.nd.array(numpy.random.rand(
# *fsp).astype('float32'), ctx, dtype=ddtype)
data_tvm=tvm.nd.array(a_np_tvm, ctx,dtype=ddtype)
filter_tvm = tvm.nd.array(w_np_tvm, ctx,dtype=ddtype)
output_tvm = tvm.nd.empty(osp, ctx=ctx, dtype=ddtype.replace('r','w'))
func(data_tvm, filter_tvm, output_tvm)
#================validate===================
#==C-tvm data prepare
c_tvm_o = output_tvm.asnumpy()
c_np_v = c_np.T.reshape(K_P*H_P*W_P, 4)
B1 = c_np_v[0::K_P, :]
for i in range(K_P-1):
B1 = np.vstack((B1, c_np_v[i+1::K_P, :]))
c_np_v = B1.reshape(1, K_P, H_P, W_P, PACK4) * 1.0
#tvm.testing.assert_allclose(c_np_v, c_tvm_o, rtol=1e-2)
#exit(0)
evaluator = func.time_evaluator(func.entry_name, ctx, number=1)
gflops = numpy.prod(np.array(osp[2:4] + fsp).astype('float')) / 1e9 * 2
t_cost = evaluator(data_tvm,filter_tvm,output_tvm).mean
print("Convolution: %f ms %f GFLOPS" % (t_cost*1e3,gflops/t_cost))
| [
"numpy.arange",
"tvm.autotvm.measure.request_remote",
"numpy.ndarray",
"numpy.prod",
"tvm.te.placeholder",
"tvm.topi.nn.winograd_util.winograd_transform_matrices",
"tvm.contrib.utils.tempdir",
"tvm.nd.array",
"tvm.te.create_schedule",
"tvm.topi.testing.conv2d_nchw_python",
"tvm.context",
"tvm.... | [((792, 814), 'tvm.context', 'tvm.context', (['target', '(0)'], {}), '(target, 0)\n', (803, 814), False, 'import tvm\n'), ((886, 956), 'tvm.topi.nn.winograd_util.winograd_transform_matrices', 'tvm.topi.nn.winograd_util.winograd_transform_matrices', (['m', 'r', '"""float32"""'], {}), "(m, r, 'float32')\n", (939, 956), False, 'import tvm\n'), ((1428, 1507), 'tvm.te.placeholder', 'te.placeholder', (['(1, CI // 4, img_H, img_W, 4)'], {'name': '"""placeholder"""', 'dtype': 'ddtype'}), "((1, CI // 4, img_H, img_W, 4), name='placeholder', dtype=ddtype)\n", (1442, 1507), False, 'from tvm import te\n'), ((1546, 1621), 'tvm.te.placeholder', 'te.placeholder', (['(CI, CO // 4, 3, 3, 1, 4)'], {'name': '"""placeholder"""', 'dtype': 'ddtype'}), "((CI, CO // 4, 3, 3, 1, 4), name='placeholder', dtype=ddtype)\n", (1560, 1621), False, 'from tvm import te\n'), ((5279, 5308), 'tvm.te.create_schedule', 'te.create_schedule', (['output.op'], {}), '(output.op)\n', (5297, 5308), False, 'from tvm import te\n'), ((12274, 12298), 'tvm.autotvm.get_config', 'tvm.autotvm.get_config', ([], {}), '()\n', (12296, 12298), False, 'import tvm\n'), ((13488, 13546), 'tvm.target.Target', 'tvm.target.Target', (["('llvm -mtriple=%s-linux-android' % arch)"], {}), "('llvm -mtriple=%s-linux-android' % arch)\n", (13505, 13546), False, 'import tvm\n'), ((13556, 13596), 'tvm.target.Target', 'tvm.target.Target', (['"""opencl -device=mali"""'], {}), "('opencl -device=mali')\n", (13573, 13596), False, 'import tvm\n'), ((13747, 13825), 'tvm.build', 'tvm.build', (['s', '[Data, filter_n, output]'], {'target': 'target', 'target_host': 'target_host'}), '(s, [Data, filter_n, output], target=target, target_host=target_host)\n', (13756, 13825), False, 'import tvm\n'), ((14378, 14387), 'tvm.contrib.utils.tempdir', 'tempdir', ([], {}), '()\n', (14385, 14387), False, 'from tvm.contrib.utils import tempdir\n'), ((14659, 14733), 'tvm.autotvm.measure.request_remote', 'autotvm.measure.request_remote', (['device_key', '"""0.0.0.0"""', '(9090)'], {'timeout': '(10000)'}), "(device_key, '0.0.0.0', 9090, timeout=10000)\n", (14689, 14733), False, 'from tvm import te, topi, autotvm\n'), ((15261, 15274), 'numpy.ndarray', 'np.ndarray', (['(0)'], {}), '(0)\n', (15271, 15274), True, 'import numpy as np\n'), ((15554, 15567), 'numpy.ndarray', 'np.ndarray', (['(0)'], {}), '(0)\n', (15564, 15567), True, 'import numpy as np\n'), ((15802, 15835), 'numpy.expand_dims', 'np.expand_dims', (['w_np_tvm'], {'axis': '(-2)'}), '(w_np_tvm, axis=-2)\n', (15816, 15835), True, 'import numpy as np\n'), ((15939, 15991), 'tvm.topi.testing.conv2d_nchw_python', 'conv2d_nchw_python', (['a_np_t', 'w_np_t', 'strides', 'padding'], {}), '(a_np_t, w_np_t, strides, padding)\n', (15957, 15991), False, 'from tvm.topi.testing import conv2d_nchw_python\n'), ((16211, 16252), 'tvm.nd.array', 'tvm.nd.array', (['a_np_tvm', 'ctx'], {'dtype': 'ddtype'}), '(a_np_tvm, ctx, dtype=ddtype)\n', (16223, 16252), False, 'import tvm\n'), ((16265, 16306), 'tvm.nd.array', 'tvm.nd.array', (['w_np_tvm', 'ctx'], {'dtype': 'ddtype'}), '(w_np_tvm, ctx, dtype=ddtype)\n', (16277, 16306), False, 'import tvm\n'), ((5569, 5597), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.x"""'], {}), "('blockIdx.x')\n", (5583, 5597), False, 'from tvm import te\n'), ((5612, 5640), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.y"""'], {}), "('blockIdx.y')\n", (5626, 5640), False, 'from tvm import te\n'), ((5655, 5683), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.z"""'], {}), "('blockIdx.z')\n", (5669, 5683), False, 'from tvm import te\n'), ((5699, 5728), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.x"""'], {}), "('threadIdx.x')\n", (5713, 5728), False, 'from tvm import te\n'), ((5745, 5774), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.y"""'], {}), "('threadIdx.y')\n", (5759, 5774), False, 'from tvm import te\n'), ((5790, 5819), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.z"""'], {}), "('threadIdx.z')\n", (5804, 5819), False, 'from tvm import te\n'), ((7077, 7105), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.x"""'], {}), "('blockIdx.x')\n", (7091, 7105), False, 'from tvm import te\n'), ((7120, 7148), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.y"""'], {}), "('blockIdx.y')\n", (7134, 7148), False, 'from tvm import te\n'), ((7163, 7191), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.z"""'], {}), "('blockIdx.z')\n", (7177, 7191), False, 'from tvm import te\n'), ((7207, 7236), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.x"""'], {}), "('threadIdx.x')\n", (7221, 7236), False, 'from tvm import te\n'), ((7253, 7282), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.y"""'], {}), "('threadIdx.y')\n", (7267, 7282), False, 'from tvm import te\n'), ((7298, 7327), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.z"""'], {}), "('threadIdx.z')\n", (7312, 7327), False, 'from tvm import te\n'), ((8673, 8701), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.x"""'], {}), "('blockIdx.x')\n", (8687, 8701), False, 'from tvm import te\n'), ((8716, 8744), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.y"""'], {}), "('blockIdx.y')\n", (8730, 8744), False, 'from tvm import te\n'), ((8759, 8787), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.z"""'], {}), "('blockIdx.z')\n", (8773, 8787), False, 'from tvm import te\n'), ((8803, 8832), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.x"""'], {}), "('threadIdx.x')\n", (8817, 8832), False, 'from tvm import te\n'), ((8849, 8878), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.y"""'], {}), "('threadIdx.y')\n", (8863, 8878), False, 'from tvm import te\n'), ((8894, 8923), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.z"""'], {}), "('threadIdx.z')\n", (8908, 8923), False, 'from tvm import te\n'), ((10528, 10556), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.x"""'], {}), "('blockIdx.x')\n", (10542, 10556), False, 'from tvm import te\n'), ((10571, 10599), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.y"""'], {}), "('blockIdx.y')\n", (10585, 10599), False, 'from tvm import te\n'), ((10614, 10642), 'tvm.te.thread_axis', 'te.thread_axis', (['"""blockIdx.z"""'], {}), "('blockIdx.z')\n", (10628, 10642), False, 'from tvm import te\n'), ((10658, 10687), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.x"""'], {}), "('threadIdx.x')\n", (10672, 10687), False, 'from tvm import te\n'), ((10703, 10732), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.y"""'], {}), "('threadIdx.y')\n", (10717, 10732), False, 'from tvm import te\n'), ((10748, 10777), 'tvm.te.thread_axis', 'te.thread_axis', (['"""threadIdx.z"""'], {}), "('threadIdx.z')\n", (10762, 10777), False, 'from tvm import te\n'), ((14981, 14993), 'numpy.prod', 'np.prod', (['dsp'], {}), '(dsp)\n', (14988, 14993), True, 'import numpy as np\n'), ((15357, 15382), 'numpy.expand_dims', 'np.expand_dims', (['b'], {'axis': '(1)'}), '(b, axis=1)\n', (15371, 15382), True, 'import numpy as np\n'), ((15651, 15676), 'numpy.expand_dims', 'np.expand_dims', (['b'], {'axis': '(1)'}), '(b, axis=1)\n', (15665, 15676), True, 'import numpy as np\n'), ((16610, 16648), 'numpy.vstack', 'np.vstack', (['(B1, c_np_v[i + 1::K_P, :])'], {}), '((B1, c_np_v[i + 1::K_P, :]))\n', (16619, 16648), True, 'import numpy as np\n'), ((15144, 15183), 'numpy.arange', 'np.arange', (['(in_channel * out_channel * 9)'], {}), '(in_channel * out_channel * 9)\n', (15153, 15183), True, 'import numpy as np\n'), ((15460, 15498), 'numpy.concatenate', 'np.concatenate', (['(a_np_tvm, ct)'], {'axis': '(1)'}), '((a_np_tvm, ct), axis=1)\n', (15474, 15498), True, 'import numpy as np\n'), ((15754, 15792), 'numpy.concatenate', 'np.concatenate', (['(w_np_tvm, ct)'], {'axis': '(1)'}), '((w_np_tvm, ct), axis=1)\n', (15768, 15792), True, 'import numpy as np\n'), ((16848, 16872), 'numpy.array', 'np.array', (['(osp[2:4] + fsp)'], {}), '(osp[2:4] + fsp)\n', (16856, 16872), True, 'import numpy as np\n')] |
import sys
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
from constants import BATCH_FIRST, EMBED_DIM
from torch.functional import Tensor
sys.path.append("../..")
from utils.helper import custom_logistic, mult_normal_sample, phi_u_fn, sse_x
class SkipLSTM(nn.Module):
def __init__(
self,
input_size,
hidden_size,
output_size,
num_layers,
with_texts=False,
win_size=None,
):
super(SkipLSTM, self).__init__()
self.with_texts = with_texts
self.win_size = win_size
self.output_size = output_size
size = [hidden_size] + [hidden_size] * num_layers
self.layers = nn.ModuleList(
nn.LSTM(
size[i],
size[i + 1],
1,
batch_first=BATCH_FIRST,
)
for i in range(num_layers)
)
self.final_projs = nn.ModuleList(
nn.Linear(hidden_size, output_size) for i in range(num_layers)
)
self.input_proj = nn.ModuleList(
nn.Linear(input_size, hidden_size) for i in range(num_layers)
)
self.bias = torch.nn.Parameter(torch.randn(1))
if self.with_texts:
self.c_size = 1
self.window_proj = nn.Linear(hidden_size, win_size * self.c_size * 3)
self.win_splits: List[int] = list(
np.array([self.c_size, self.c_size, self.c_size]) * win_size
)
self.win_hidden_proj = nn.Linear(EMBED_DIM, hidden_size, bias=False)
self.layers[0] = nn.LSTMCell(hidden_size, hidden_size)
self.init_parameters("xavier")
def init_parameters(self, init_type, gain=1):
for param in self.parameters():
if isinstance(param, nn.Linear):
nn.init.xavier_uniform_(param.weight)
param.bias.data.fill_(0.01)
elif param.dim() == 1:
nn.init.constant_(param, 0.0)
elif param.dim() > 1:
if init_type == "xavier":
nn.init.xavier_uniform_(param, gain=gain)
elif init_type == "orthogonal":
nn.init.orthogonal_(param, gain=gain)
def compute_wt(self, seqs, h, _last_keta):
h = h.squeeze(1)
proj = self.window_proj(h)
b, _ = proj.shape
alpha, beta, keta = torch.split(proj, self.win_splits, dim=-1)
alpha = alpha.view(b, self.win_size, -1)
beta = beta.exp().view(b, self.win_size, -1)
keta = _last_keta + keta.exp().view(b, self.win_size, -1)
u_len = seqs.shape[1]
phi_u = phi_u_fn(
torch.arange(start=1, end=u_len + 1, device=alpha.device),
alpha,
beta,
keta,
)
w_t = phi_u.unsqueeze(-1) * seqs
w_t = w_t.sum(-2)
res = (w_t.unsqueeze(1), keta, phi_u) # shape b, 57
return res
@staticmethod
def _lstm_step(
layer: torch.nn.modules.rnn.LSTMCell, hs: Optional[Tuple[Tensor, Tensor]], inp
):
return layer.forward(inp) if hs is None else layer.forward(inp, (hs[0], hs[1]))
def _one_step_wt(self, x, _hs: Optional[Tuple[Tensor, Tensor]], seqs, _last_keta):
_hs = self._lstm_step(self.layers[0], _hs, x)
h_1 = _hs[0]
res = self.compute_wt(seqs, h_1, _last_keta)
w_1 = self.win_hidden_proj(res[0] if isinstance(res, tuple) else res)
ret = (w_1, h_1, _hs, res[1], res[2])
return ret
def run_first_layer(self, x, _hs: Optional[Tuple[Tensor, Tensor]], seqs):
_, s, _ = x.shape
last_w = 0
h_final = torch.zeros_like(x)
w_t = torch.zeros_like(x)
_last_keta = 0
for start in range(s):
inp = x[:, start : start + 1, :] + last_w
inp = inp.squeeze(1)
# try:
last_w, h_1, _hs, _last_keta, _ = self._one_step_wt(
inp, _hs, seqs, _last_keta=_last_keta
)
h_final[:, start, :] = h_1
w_t[:, start : start + 1, :] = last_w
output_proj = self.final_projs[0](h_final)
return w_t, h_final, _hs, output_proj
def forward(
self,
x,
hs: Optional[Tuple[Tensor, Tensor]] = None,
seqs: Tensor = torch.zeros(1),
):
last_inp: Optional[Tensor] = None
running_skip = 0
h_stack = [] # if hs is None else [hs[0]]
c_stack = [] # if hs is None else [hs[1]]
w_t = 0
for i, (layer, input_proj, final_proj) in enumerate(
zip(self.layers, self.input_proj, self.final_projs)
):
_hs = (hs[0][i].detach(), hs[1][i].detach()) if hs is not None else None
inp = input_proj(x)
if i == 0 and self.with_texts:
# send only 1 time step
w_t, h_final, _, output_proj = self.run_first_layer(inp, None, seqs)
last_inp = h_final
running_skip = running_skip + output_proj
else:
if last_inp is not None:
inp = inp + last_inp
if self.with_texts:
inp = inp + w_t
output, (_h, _c) = self._lstm_step(layer, _hs, inp)
h_stack.append(_h)
c_stack.append(_c)
last_inp = output
running_skip = running_skip + final_proj(output)
output = running_skip + self.bias
return output, (h_stack, c_stack)
class PredModel(nn.Module):
def __init__(
self, input_size, layers, num_mixtures, batch_size, hidden_dim, with_texts=False
):
super(PredModel, self).__init__()
self.hidden_dim = hidden_dim
output_dim = 1 + 6 * num_mixtures
self.output_dim = output_dim
self.win_size = 10
self.lstm = SkipLSTM(
input_size=input_size,
hidden_size=self.hidden_dim,
output_size=output_dim,
num_layers=layers,
with_texts=with_texts,
win_size=self.win_size,
)
self.num_mixtures = num_mixtures
self.split_sizes = list(np.array([1, 2, 2, 1]) * num_mixtures)
self.num_layers = layers
self.h_n = torch.zeros(
self.num_layers, batch_size, self.hidden_dim, requires_grad=True
)
self.c_n = torch.zeros(
self.num_layers, batch_size, self.hidden_dim, requires_grad=True
)
self.batch_size = batch_size
self.hidden = None
def reset(self):
self.hidden = None
def forward(self, x, seqs=None):
y_hat, self.hidden = self.lstm(x, None, seqs=seqs)
return y_hat
def _process_output(self, lstm_out, bias=0):
e_t = lstm_out[..., 0]
mp = lstm_out[..., 1:]
ws, means, log_std, corr = torch.split(mp, self.split_sizes, dim=-1)
b, s, _ = means.shape
ws = nn.LogSoftmax(-1)(ws * (1 + bias)).view(b, s, self.num_mixtures)
means = means.view(b, s, self.num_mixtures, 2)
std = (log_std - bias).exp().view(b, s, self.num_mixtures, 2)
corr = corr.tanh().view(b, s, self.num_mixtures)
std_1 = std[..., -2]
std_2 = std[..., -1]
covariance_mat = (std_1, std_2, corr)
return ws, means, covariance_mat, e_t
@staticmethod
def log_prob(points, means, std_1, std_2, rho):
eps = 1e-7
points = points.unsqueeze(1)
t1 = (points[..., 0] - means[..., 0]) / (std_1 + eps)
t2 = (points[..., 1] - means[..., 1]) / (std_2 + eps)
z = t1 ** 2 + t2 ** 2 - 2 * rho * t1 * t2
prob = -z / (2 * (1 - rho ** 2) + eps)
t = (
np.log(2 * 3.1415927410125732)
+ std_1.log()
+ std_2.log()
+ 0.5 * torch.log(1 - rho ** 2)
)
log_prob = prob - t
return log_prob
def infer(self, lstm_out, x, input_mask, label_mask):
ws, means, covariance_mat, e_t = self._process_output(lstm_out)
# apply mask
means = means[input_mask]
std_1, std_2, rho = covariance_mat
std_1 = std_1[input_mask]
std_2 = std_2[input_mask]
rho = rho[input_mask]
new_ws = ws[input_mask]
new_x = x[label_mask]
prob = PredModel.log_prob(new_x, means, std_1, std_2, rho)
prob = new_ws + prob
prob = torch.logsumexp(prob, -1)
seq_prob = prob
# eval sse for xs
sse = sse_x(new_x.detach(), new_ws.detach(), means.detach())
return seq_prob, e_t, sse
@torch.no_grad()
def generate_with_seq(self, seed, device, seqs, bias=0):
torch.manual_seed(seed)
np.random.seed(seed)
x = torch.zeros(3, device=device).unsqueeze(0).unsqueeze(0)
out = [x]
last_w = 0
hs = None
idx = 0
_last_keta = 0
while True:
h_stack = []
c_stack = []
inp = self.lstm.input_proj[0](x) + last_w
inp.squeeze_(1)
_hs = (hs[0][0].detach(), hs[1][0].detach()) if hs else None
last_w, h_1, _hs, _last_keta, phi = self.lstm._one_step_wt(
inp, _hs, seqs, _last_keta=_last_keta
)
h_stack.append(_hs[0])
c_stack.append(_hs[1])
if (phi[0, -1] > phi[0, :-1]).all():
break
idx += 1
h_1 = h_1.unsqueeze(1)
running_skip = self.lstm.final_projs[0](h_1)
last_inp = h_1
inp = self.lstm.input_proj[0](x) + last_w
for i, layer in enumerate(self.lstm.layers[1:]):
_hs = (hs[0][i + 1].detach(), hs[1][i + 1].detach()) if hs else None
layer_inp = inp + last_inp
output, (_h, _c) = self.lstm._lstm_step(layer, _hs, layer_inp)
h_stack.append(_h)
c_stack.append(_c)
last_inp = output
running_skip = running_skip + self.lstm.final_projs[i + 1](output)
y_hat = running_skip + self.lstm.bias
hs = (h_stack, c_stack)
ws, means, (std_1, std_2, corr), e_tt = self._process_output(
y_hat, bias=bias
)
ws = ws.squeeze().exp()
j = torch.multinomial(ws, 1)[0]
x_nt = means[..., j, :]
std_1 = std_1[..., j]
std_2 = std_2[..., j]
corr = corr[..., j]
x_nt = mult_normal_sample(x_nt, std_1, std_2, corr)
u = 0.5
e_tt = e_tt.sigmoid()
e_t = torch.zeros_like(e_tt)
e_t[e_tt <= u] = 0
e_t[e_tt > u] = 1
x = torch.cat([e_t.unsqueeze(0), x_nt], axis=-1)
out.append(x)
return out
@torch.no_grad()
def generate(self, seed, device, bias=0):
torch.manual_seed(seed)
np.random.seed(seed)
inp = torch.zeros(3, device=device).unsqueeze(0).unsqueeze(0)
hs = None
out = []
for i in range(700):
y_hat, hs = self.lstm(inp, hs)
ws, means, (std_1, std_2, corr), e_tt = self._process_output(
y_hat, bias=bias
)
ws = ws.squeeze().exp()
j = torch.multinomial(ws, 1)[0]
x_nt = means[..., j, :]
std_1 = std_1[..., j]
std_2 = std_2[..., j]
corr = corr[..., j]
x_nt = mult_normal_sample(x_nt, std_1, std_2, corr)
u = 0.5
e_tt = custom_logistic(e_tt)
e_t = torch.zeros_like(e_tt)
e_t[e_tt <= u] = 0
e_t[e_tt > u] = 1
inp = torch.cat([e_t.unsqueeze(0), x_nt], axis=-1)
out.append(inp)
return out
| [
"numpy.random.seed",
"torch.multinomial",
"torch.nn.LSTMCell",
"torch.randn",
"torch.nn.init.constant_",
"torch.arange",
"torch.no_grad",
"sys.path.append",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LSTM",
"torch.log",
"torch.logsumexp",
"utils.helper.mult_normal_sample",
"torch.zeros_... | [((196, 220), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (211, 220), False, 'import sys\n'), ((8660, 8675), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8673, 8675), False, 'import torch\n'), ((10874, 10889), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10887, 10889), False, 'import torch\n'), ((2434, 2476), 'torch.split', 'torch.split', (['proj', 'self.win_splits'], {'dim': '(-1)'}), '(proj, self.win_splits, dim=-1)\n', (2445, 2476), False, 'import torch\n'), ((3707, 3726), 'torch.zeros_like', 'torch.zeros_like', (['x'], {}), '(x)\n', (3723, 3726), False, 'import torch\n'), ((3741, 3760), 'torch.zeros_like', 'torch.zeros_like', (['x'], {}), '(x)\n', (3757, 3760), False, 'import torch\n'), ((4358, 4372), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (4369, 4372), False, 'import torch\n'), ((6329, 6406), 'torch.zeros', 'torch.zeros', (['self.num_layers', 'batch_size', 'self.hidden_dim'], {'requires_grad': '(True)'}), '(self.num_layers, batch_size, self.hidden_dim, requires_grad=True)\n', (6340, 6406), False, 'import torch\n'), ((6448, 6525), 'torch.zeros', 'torch.zeros', (['self.num_layers', 'batch_size', 'self.hidden_dim'], {'requires_grad': '(True)'}), '(self.num_layers, batch_size, self.hidden_dim, requires_grad=True)\n', (6459, 6525), False, 'import torch\n'), ((6927, 6968), 'torch.split', 'torch.split', (['mp', 'self.split_sizes'], {'dim': '(-1)'}), '(mp, self.split_sizes, dim=-1)\n', (6938, 6968), False, 'import torch\n'), ((8474, 8499), 'torch.logsumexp', 'torch.logsumexp', (['prob', '(-1)'], {}), '(prob, -1)\n', (8489, 8499), False, 'import torch\n'), ((8745, 8768), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (8762, 8768), False, 'import torch\n'), ((8777, 8797), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (8791, 8797), True, 'import numpy as np\n'), ((10944, 10967), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (10961, 10967), False, 'import torch\n'), ((10976, 10996), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (10990, 10996), True, 'import numpy as np\n'), ((1233, 1247), 'torch.randn', 'torch.randn', (['(1)'], {}), '(1)\n', (1244, 1247), False, 'import torch\n'), ((1337, 1387), 'torch.nn.Linear', 'nn.Linear', (['hidden_size', '(win_size * self.c_size * 3)'], {}), '(hidden_size, win_size * self.c_size * 3)\n', (1346, 1387), True, 'import torch.nn as nn\n'), ((1561, 1606), 'torch.nn.Linear', 'nn.Linear', (['EMBED_DIM', 'hidden_size'], {'bias': '(False)'}), '(EMBED_DIM, hidden_size, bias=False)\n', (1570, 1606), True, 'import torch.nn as nn\n'), ((1636, 1673), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['hidden_size', 'hidden_size'], {}), '(hidden_size, hidden_size)\n', (1647, 1673), True, 'import torch.nn as nn\n'), ((2714, 2771), 'torch.arange', 'torch.arange', ([], {'start': '(1)', 'end': '(u_len + 1)', 'device': 'alpha.device'}), '(start=1, end=u_len + 1, device=alpha.device)\n', (2726, 2771), False, 'import torch\n'), ((10561, 10605), 'utils.helper.mult_normal_sample', 'mult_normal_sample', (['x_nt', 'std_1', 'std_2', 'corr'], {}), '(x_nt, std_1, std_2, corr)\n', (10579, 10605), False, 'from utils.helper import custom_logistic, mult_normal_sample, phi_u_fn, sse_x\n'), ((10678, 10700), 'torch.zeros_like', 'torch.zeros_like', (['e_tt'], {}), '(e_tt)\n', (10694, 10700), False, 'import torch\n'), ((11531, 11575), 'utils.helper.mult_normal_sample', 'mult_normal_sample', (['x_nt', 'std_1', 'std_2', 'corr'], {}), '(x_nt, std_1, std_2, corr)\n', (11549, 11575), False, 'from utils.helper import custom_logistic, mult_normal_sample, phi_u_fn, sse_x\n'), ((11616, 11637), 'utils.helper.custom_logistic', 'custom_logistic', (['e_tt'], {}), '(e_tt)\n', (11631, 11637), False, 'from utils.helper import custom_logistic, mult_normal_sample, phi_u_fn, sse_x\n'), ((11656, 11678), 'torch.zeros_like', 'torch.zeros_like', (['e_tt'], {}), '(e_tt)\n', (11672, 11678), False, 'import torch\n'), ((756, 813), 'torch.nn.LSTM', 'nn.LSTM', (['size[i]', 'size[i + 1]', '(1)'], {'batch_first': 'BATCH_FIRST'}), '(size[i], size[i + 1], 1, batch_first=BATCH_FIRST)\n', (763, 813), True, 'import torch.nn as nn\n'), ((996, 1031), 'torch.nn.Linear', 'nn.Linear', (['hidden_size', 'output_size'], {}), '(hidden_size, output_size)\n', (1005, 1031), True, 'import torch.nn as nn\n'), ((1122, 1156), 'torch.nn.Linear', 'nn.Linear', (['input_size', 'hidden_size'], {}), '(input_size, hidden_size)\n', (1131, 1156), True, 'import torch.nn as nn\n'), ((1865, 1902), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['param.weight'], {}), '(param.weight)\n', (1888, 1902), True, 'import torch.nn as nn\n'), ((6238, 6260), 'numpy.array', 'np.array', (['[1, 2, 2, 1]'], {}), '([1, 2, 2, 1])\n', (6246, 6260), True, 'import numpy as np\n'), ((7886, 7909), 'torch.log', 'torch.log', (['(1 - rho ** 2)'], {}), '(1 - rho ** 2)\n', (7895, 7909), False, 'import torch\n'), ((10377, 10401), 'torch.multinomial', 'torch.multinomial', (['ws', '(1)'], {}), '(ws, 1)\n', (10394, 10401), False, 'import torch\n'), ((11348, 11372), 'torch.multinomial', 'torch.multinomial', (['ws', '(1)'], {}), '(ws, 1)\n', (11365, 11372), False, 'import torch\n'), ((1451, 1500), 'numpy.array', 'np.array', (['[self.c_size, self.c_size, self.c_size]'], {}), '([self.c_size, self.c_size, self.c_size])\n', (1459, 1500), True, 'import numpy as np\n'), ((1998, 2027), 'torch.nn.init.constant_', 'nn.init.constant_', (['param', '(0.0)'], {}), '(param, 0.0)\n', (2015, 2027), True, 'import torch.nn as nn\n'), ((7012, 7029), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', (['(-1)'], {}), '(-1)\n', (7025, 7029), True, 'import torch.nn as nn\n'), ((7783, 7813), 'numpy.log', 'np.log', (['(2 * 3.1415927410125732)'], {}), '(2 * 3.1415927410125732)\n', (7789, 7813), True, 'import numpy as np\n'), ((8810, 8839), 'torch.zeros', 'torch.zeros', (['(3)'], {'device': 'device'}), '(3, device=device)\n', (8821, 8839), False, 'import torch\n'), ((11011, 11040), 'torch.zeros', 'torch.zeros', (['(3)'], {'device': 'device'}), '(3, device=device)\n', (11022, 11040), False, 'import torch\n'), ((2124, 2165), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['param'], {'gain': 'gain'}), '(param, gain=gain)\n', (2147, 2165), True, 'import torch.nn as nn\n'), ((2234, 2271), 'torch.nn.init.orthogonal_', 'nn.init.orthogonal_', (['param'], {'gain': 'gain'}), '(param, gain=gain)\n', (2253, 2271), True, 'import torch.nn as nn\n')] |
import numpy as np
def compute_min_max(data_path, first_col_index=1, last_col_index=23):
"""
Get the minimum and maximum value for each column in a range of a pd datframe.
Parameters:
data_path (string): The data path
first_col_index (int): The start of the range
last_col_index (int): The end of the rnage
Returns:
(np.stack): A stack of tuples of the min and max of each column
"""
data = np.loadtxt(data_path, delimiter=",", dtype=np.float32, skiprows=1)[:, first_col_index:last_col_index]
return np.stack((data.min(axis=0), data.max(axis=0)))
| [
"numpy.loadtxt"
] | [((542, 608), 'numpy.loadtxt', 'np.loadtxt', (['data_path'], {'delimiter': '""","""', 'dtype': 'np.float32', 'skiprows': '(1)'}), "(data_path, delimiter=',', dtype=np.float32, skiprows=1)\n", (552, 608), True, 'import numpy as np\n')] |
#coding=utf-8
# Copyright 2017 - 2018 Baidu Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module provide the attack method of "CW".
L2 distance metrics especially
"""
from __future__ import division
import logging
import numpy as np
from tutorials.mnist_model import mnist_cnn_model
import paddle.fluid as fluid
import paddle.v2 as paddle
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.param_attr import ParamAttr
from .base import Attack
import pdb
__all__ = ['CW_L2_Attack', 'CW_L2']
# In[5]:
class CW_L2_Attack(Attack):
"""
Uses Adam to minimize the CW L2 objective function
Paper link: https://arxiv.org/abs/1608.04644
"""
def __init__(self, model, learning_rate):
super(CW_L2_Attack, self).__init__(model)
self._predicts_normalized = None
self._adversary = None # type: Adversary
#########################################
# build cw attack computation graph
# use CPU
self.place = fluid.CPUPlace()
# use GPU
# place = fluid.CUDAPlace(0)
self.exe = fluid.Executor(self.place)
# clone the prebuilt program that has cnn to attack
self.attack_main_program = fluid.Program() # prebuilt_program.clone(for_test=False)
# create an empty program for variable init
self.attack_startup_program = fluid.Program() # start_up_program.clone(for_test=False)
# build cw attack compute graph within attack programs
with fluid.program_guard(main_program=self.attack_main_program, startup_program=self.attack_startup_program):
img_0_1_placehold = fluid.layers.data(name='img_data_scaled', shape=[1, 28, 28], dtype="float32")
target_placehold = fluid.layers.data(name='target', shape=[10], dtype="float32")
shape_placehold = fluid.layers.data(name="shape", shape=[1], dtype="float32")
# k_placehold = fluid.layers.data(name='k',shape=[1],dtype="float32")
c_placehold = fluid.layers.data(name='c', shape=[1], dtype="float32")
# get fluid.layer object from prebuilt program
# img_placehold_from_prebuilt_program = attack_main_program.block(0).var(self.model._input_name)
# softmax_from_prebuilt_program = attack_main_program.block(0).var(self.model._softmax_name)
# logits_from_prebuilt_program = attack_main_program.block(0).var(self.model._predict_name)
t0, t1, t2, t3, t4 = self._loss_cw(img_0_1_placehold,
target_placehold,
shape_placehold,
c_placehold) # ,
# img_placehold_from_prebuilt_program,
# softmax_from_prebuilt_program,
# logits_from_prebuilt_program)
# Adam optimizer as suggested in paper
optimizer = fluid.optimizer.Adam(learning_rate=learning_rate)
optimizer.minimize(t2, parameter_list=['parameter'])
# initial variables and parameters every time before attack
self.exe.run(self.attack_startup_program)
# init ad perturbation
ret = fluid.global_scope().find_var("parameter").get_tensor()
# print(np.array(ret))
ret.set(0.001 * np.random.random_sample((1, 28, 28)).astype('float32'), self.place)
# print(np.array(ret))
# print(attack_main_program.current_block()["parameter"])
# pdb.set_trace()
c1 = self.attack_main_program.block(0).var("conv2d_2.b_0")
c2 = self.attack_main_program.block(0).var("conv2d_2.w_0")
c3 = self.attack_main_program.block(0).var("conv2d_3.b_0")
c4 = self.attack_main_program.block(0).var("conv2d_3.w_0")
f1 = self.attack_main_program.block(0).var("fc_2.b_0")
f2 = self.attack_main_program.block(0).var("fc_2.w_0")
f3 = self.attack_main_program.block(0).var("fc_3.b_0")
f4 = self.attack_main_program.block(0).var("fc_3.w_0")
var_list = [c1, c2, c3, c4, f1, f2, f3, f4]
fluid.io.load_vars(executor=self.exe, dirname="../advbox/attacks/mnist/", vars=var_list,
main_program=self.attack_main_program) # ../advbox/attacks/mnist/
#########################################
def _apply(self,
adversary,
nb_classes=10,
learning_rate=0.01,
attack_iterations=100,
epsilon=1,
targeted=True,
k=0,
noise=2):
# put adversary instance inside of the attack instance so all other function within can access
self._adversary = adversary
if not adversary.is_targeted_attack:
raise ValueError("This attack method only support targeted attack!")
# locate the range of c which makes the attack successful
c = epsilon
img = self._adversary.original # original image to be attacked
'''
guess = self.model.predict(img)
print('guess img before preprocess:',guess)
'''
for i in range(10):
c = 2 * c
print('Checking if the range {0:f} include a successful c.'.format(c))
is_adversary, f6 = self._cwb(img,
c,
attack_steps=attack_iterations,
k=k,
learning_rate=learning_rate,
noise=noise,
nb_classes=nb_classes)
if is_adversary:
break
if not is_adversary:
logging.info('This CW attack failed!')
return adversary
# binary search for smaller c that makes fx<=0
print('searching for the smallest c that makes attack possible.')
c_low = 0
c_high = c
while c_high - c_low >= epsilon:
logging.info('c_high={}, c_low={}, diff={}, epsilon={}'.format(c_high, c_low, c_high - c_low, epsilon))
c_half = (c_low + c_high) / 2
is_adversary, f6 = self._cwb(img,
c,
attack_steps=attack_iterations,
k=k,
learning_rate=learning_rate,
noise=noise,
nb_classes=nb_classes)
# pdb.set_trace()
is_f6_smaller_than_0 = f6 <= 0
if is_adversary and is_f6_smaller_than_0:
c_high = c_half
else:
c_low = c_half
return adversary
def _cwb(self, img, c, attack_steps, k, learning_rate, noise, nb_classes):
'''
use CW attack on an original image for a
limited number of iterations
:return bool
'''
smallest_f6 = None
corresponding_constrained = None
# inital data
screen_nontarget_logit = np.zeros(shape=[nb_classes], dtype="float32")
screen_nontarget_logit[self._adversary.target_label] = 1
feeder = fluid.DataFeeder(
feed_list=["img_data_scaled",
"target",
"shape",
"c"], # self.model._input_name,self.model._logits_name,
place=self.place,
program=self.attack_main_program)
sub = -1
div = 2
img_0_1 = self._process_input(img, sub, div)
# pdb.set_trace()
for i in range(attack_steps):
# print("steps:",i)
result = self.exe.run(self.attack_main_program,
feed=feeder.feed([(img_0_1,
screen_nontarget_logit,
np.zeros(shape=[1], dtype='float32'),
c)]), # img_0_1,0,
fetch_list=[self.maxlogit_i_not_t,
self.maxlogit_target,
self.loss,
self.logits_i_not_t,
self.constrained,
self.softmax])
'''
print("maxlogit_i_not_t:",result[0],\
"maxlogit_target:",result[1],\
"loss:",result[2],
"logits_i_not_t:",result[3],\
"softmax:",result[5])
'''
f6 = result[0] - result[1]
if i == 0:
smallest_f6 = f6
corresponding_constrained = result[4]
if f6 < smallest_f6:
smallest_f6 = f6
corresponding_constrained = result[4]
######
# pdb.set_trace()
# print(corresponding_constrained)
# recover image (-1,1) from corresponding_constrained which is within (0,1)
img_ad = self.reconstruct(corresponding_constrained)
# convert into img.shape
img_ad = np.squeeze(img_ad)
img_ad = img_ad.reshape(img.shape)
# let model guess
adv_label = np.argmax(self.model.predict(img_ad)) # img,img_ad
'''
print(self._adversary.original_label,self.model.predict(img))
print(self._adversary.target_label,screen_nontarget_logit)
print(adv_label,self.model.predict(img_ad))
#pdb.set_trace()
'''
# try to accept new result, success or fail
return self._adversary.try_accept_the_example(
img_ad, adv_label), f6 # img,img_ad
# this build up the CW attack computation graph in Paddle
def _loss_cw(self, img_0_1, target, shape, c): # ,img_input_entrance,softmax_entrance,logits_entrance
####
# use layerhelper to init w
self.helper = LayerHelper("Jay")
# name a name for later to take it out
self.param_attr = ParamAttr(name="parameter")
# add this perturbation on w space, then, reconstruct as an image within (0,1)
self.ad_perturbation = self.helper.create_parameter(attr=self.param_attr,
shape=[1, 28, 28],
dtype='float32',
is_bias=False)
self.y = 2 * img_0_1 - 1
# compute arctan for y to get w
self.xplus1 = 1 + self.y
self.xminus1 = 1 - self.y
self.ln = fluid.layers.log(self.xplus1 / self.xminus1)
self.w = fluid.layers.scale(x=self.ln, scale=0.5)
self.w_ad = self.w + self.ad_perturbation
self.tanh_w = fluid.layers.tanh(self.w_ad)
self.constrained = 0.5 * (self.tanh_w + 1)
self.softmax, self.logits = mnist_cnn_model(self.constrained)
self.sub = fluid.layers.elementwise_sub(img_0_1, self.constrained)
self.squared = fluid.layers.elementwise_mul(self.sub, self.sub)
self.distance_L2 = fluid.layers.reduce_sum(self.squared)
self.negetive_screen_nontarget_logit = fluid.layers.scale(target, scale=-1.0)
self.screen_target_logit = self.negetive_screen_nontarget_logit.__add__(
fluid.layers.ones(shape=[10], dtype="float32"))
self.logits_i_not_t = fluid.layers.elementwise_mul(self.screen_target_logit, self.logits)
self.logit_target = fluid.layers.elementwise_mul(target, self.logits)
self.maxlogit_i_not_t = fluid.layers.reduce_max(self.logits_i_not_t)
self.maxlogit_target = fluid.layers.reduce_sum(self.logit_target)
self.difference_between_two_logits = self.maxlogit_i_not_t - self.maxlogit_target
self.f6 = fluid.layers.relu(self.difference_between_two_logits)
self.loss = c * self.f6 + self.distance_L2
return self.maxlogit_i_not_t, self.maxlogit_target, self.loss, self.logits_i_not_t, self.constrained # distance_L2
# reconstruct corresponding_constrained to an image in MNIST format
def reconstruct(self, corresponding_constrained):
"""
Restore the img from corresponding_constrained float32
:return: numpy.ndarray
"""
return corresponding_constrained * 2 - 1 # mnist is belong to (-1,1)
def _f6(self, w):
'''
_f6 is the special f function CW chose as part of the
objective function, this returns the values directly
:return float32
'''
target = self._adversary.target_label
img = (np.tanh(w) + 1) / 2
Z_output = self._Z(img)
f6 = max(max([Z for i, Z in enumerate(Z_output) if i != target]) - Z_output[target], 0)
return f6
def _Z(self, img):
"""
Get the Zx logits as a numpy array.
:return: numpy.ndarray
"""
return self.model.get_logits(img)
def _process_input(self, input_, sub, div):
res = None
if np.any(sub != 0):
res = input_ - sub
if not np.all(sub == 1):
if res is None: # "res = input_ - sub" is not executed!
res = input_ / (div)
else:
res /= div
if res is None: # "res = (input_ - sub)/ div" is not executed!
return input_
res = np.where(res == 0, 0.00001, res)
res = np.where(res == 1, 0.99999, res) # no 0 or 1
return res
CW_L2 = CW_L2_Attack
class NumpyInitializer(fluid.initializer.Initializer):
def __init__(self, ndarray):
super(NumpyInitializer, self).__init__()
self._ndarray = ndarray.astype('float32')
def __call__(self, var, block):
values = [float(v) for v in self._ndarray.flat]
op = block.append_op(
type="assign_value",
outputs={"Out": [var]},
attrs={
"shape": var.shape,
"dtype": int(var.dtype),
"fp32_values": values,
})
var.op = op
return op | [
"numpy.random.random_sample",
"paddle.fluid.layers.data",
"paddle.fluid.layers.tanh",
"paddle.fluid.program_guard",
"tutorials.mnist_model.mnist_cnn_model",
"paddle.fluid.io.load_vars",
"paddle.fluid.layers.elementwise_sub",
"paddle.fluid.Executor",
"paddle.fluid.layers.reduce_sum",
"paddle.fluid.... | [((1510, 1526), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (1524, 1526), True, 'import paddle.fluid as fluid\n'), ((1601, 1627), 'paddle.fluid.Executor', 'fluid.Executor', (['self.place'], {}), '(self.place)\n', (1615, 1627), True, 'import paddle.fluid as fluid\n'), ((1724, 1739), 'paddle.fluid.Program', 'fluid.Program', ([], {}), '()\n', (1737, 1739), True, 'import paddle.fluid as fluid\n'), ((1872, 1887), 'paddle.fluid.Program', 'fluid.Program', ([], {}), '()\n', (1885, 1887), True, 'import paddle.fluid as fluid\n'), ((4586, 4717), 'paddle.fluid.io.load_vars', 'fluid.io.load_vars', ([], {'executor': 'self.exe', 'dirname': '"""../advbox/attacks/mnist/"""', 'vars': 'var_list', 'main_program': 'self.attack_main_program'}), "(executor=self.exe, dirname='../advbox/attacks/mnist/',\n vars=var_list, main_program=self.attack_main_program)\n", (4604, 4717), True, 'import paddle.fluid as fluid\n'), ((7638, 7683), 'numpy.zeros', 'np.zeros', ([], {'shape': '[nb_classes]', 'dtype': '"""float32"""'}), "(shape=[nb_classes], dtype='float32')\n", (7646, 7683), True, 'import numpy as np\n'), ((7767, 7894), 'paddle.fluid.DataFeeder', 'fluid.DataFeeder', ([], {'feed_list': "['img_data_scaled', 'target', 'shape', 'c']", 'place': 'self.place', 'program': 'self.attack_main_program'}), "(feed_list=['img_data_scaled', 'target', 'shape', 'c'],\n place=self.place, program=self.attack_main_program)\n", (7783, 7894), True, 'import paddle.fluid as fluid\n'), ((9797, 9815), 'numpy.squeeze', 'np.squeeze', (['img_ad'], {}), '(img_ad)\n', (9807, 9815), True, 'import numpy as np\n'), ((10592, 10610), 'paddle.fluid.layer_helper.LayerHelper', 'LayerHelper', (['"""Jay"""'], {}), "('Jay')\n", (10603, 10610), False, 'from paddle.fluid.layer_helper import LayerHelper\n'), ((10684, 10711), 'paddle.fluid.param_attr.ParamAttr', 'ParamAttr', ([], {'name': '"""parameter"""'}), "(name='parameter')\n", (10693, 10711), False, 'from paddle.fluid.param_attr import ParamAttr\n'), ((11272, 11316), 'paddle.fluid.layers.log', 'fluid.layers.log', (['(self.xplus1 / self.xminus1)'], {}), '(self.xplus1 / self.xminus1)\n', (11288, 11316), True, 'import paddle.fluid as fluid\n'), ((11334, 11374), 'paddle.fluid.layers.scale', 'fluid.layers.scale', ([], {'x': 'self.ln', 'scale': '(0.5)'}), '(x=self.ln, scale=0.5)\n', (11352, 11374), True, 'import paddle.fluid as fluid\n'), ((11447, 11475), 'paddle.fluid.layers.tanh', 'fluid.layers.tanh', (['self.w_ad'], {}), '(self.w_ad)\n', (11464, 11475), True, 'import paddle.fluid as fluid\n'), ((11564, 11597), 'tutorials.mnist_model.mnist_cnn_model', 'mnist_cnn_model', (['self.constrained'], {}), '(self.constrained)\n', (11579, 11597), False, 'from tutorials.mnist_model import mnist_cnn_model\n'), ((11618, 11673), 'paddle.fluid.layers.elementwise_sub', 'fluid.layers.elementwise_sub', (['img_0_1', 'self.constrained'], {}), '(img_0_1, self.constrained)\n', (11646, 11673), True, 'import paddle.fluid as fluid\n'), ((11697, 11745), 'paddle.fluid.layers.elementwise_mul', 'fluid.layers.elementwise_mul', (['self.sub', 'self.sub'], {}), '(self.sub, self.sub)\n', (11725, 11745), True, 'import paddle.fluid as fluid\n'), ((11773, 11810), 'paddle.fluid.layers.reduce_sum', 'fluid.layers.reduce_sum', (['self.squared'], {}), '(self.squared)\n', (11796, 11810), True, 'import paddle.fluid as fluid\n'), ((11859, 11897), 'paddle.fluid.layers.scale', 'fluid.layers.scale', (['target'], {'scale': '(-1.0)'}), '(target, scale=-1.0)\n', (11877, 11897), True, 'import paddle.fluid as fluid\n'), ((12070, 12137), 'paddle.fluid.layers.elementwise_mul', 'fluid.layers.elementwise_mul', (['self.screen_target_logit', 'self.logits'], {}), '(self.screen_target_logit, self.logits)\n', (12098, 12137), True, 'import paddle.fluid as fluid\n'), ((12166, 12215), 'paddle.fluid.layers.elementwise_mul', 'fluid.layers.elementwise_mul', (['target', 'self.logits'], {}), '(target, self.logits)\n', (12194, 12215), True, 'import paddle.fluid as fluid\n'), ((12249, 12293), 'paddle.fluid.layers.reduce_max', 'fluid.layers.reduce_max', (['self.logits_i_not_t'], {}), '(self.logits_i_not_t)\n', (12272, 12293), True, 'import paddle.fluid as fluid\n'), ((12325, 12367), 'paddle.fluid.layers.reduce_sum', 'fluid.layers.reduce_sum', (['self.logit_target'], {}), '(self.logit_target)\n', (12348, 12367), True, 'import paddle.fluid as fluid\n'), ((12478, 12531), 'paddle.fluid.layers.relu', 'fluid.layers.relu', (['self.difference_between_two_logits'], {}), '(self.difference_between_two_logits)\n', (12495, 12531), True, 'import paddle.fluid as fluid\n'), ((13699, 13715), 'numpy.any', 'np.any', (['(sub != 0)'], {}), '(sub != 0)\n', (13705, 13715), True, 'import numpy as np\n'), ((14045, 14075), 'numpy.where', 'np.where', (['(res == 0)', '(1e-05)', 'res'], {}), '(res == 0, 1e-05, res)\n', (14053, 14075), True, 'import numpy as np\n'), ((14092, 14124), 'numpy.where', 'np.where', (['(res == 1)', '(0.99999)', 'res'], {}), '(res == 1, 0.99999, res)\n', (14100, 14124), True, 'import numpy as np\n'), ((2007, 2115), 'paddle.fluid.program_guard', 'fluid.program_guard', ([], {'main_program': 'self.attack_main_program', 'startup_program': 'self.attack_startup_program'}), '(main_program=self.attack_main_program, startup_program=\n self.attack_startup_program)\n', (2026, 2115), True, 'import paddle.fluid as fluid\n'), ((2144, 2221), 'paddle.fluid.layers.data', 'fluid.layers.data', ([], {'name': '"""img_data_scaled"""', 'shape': '[1, 28, 28]', 'dtype': '"""float32"""'}), "(name='img_data_scaled', shape=[1, 28, 28], dtype='float32')\n", (2161, 2221), True, 'import paddle.fluid as fluid\n'), ((2253, 2314), 'paddle.fluid.layers.data', 'fluid.layers.data', ([], {'name': '"""target"""', 'shape': '[10]', 'dtype': '"""float32"""'}), "(name='target', shape=[10], dtype='float32')\n", (2270, 2314), True, 'import paddle.fluid as fluid\n'), ((2345, 2404), 'paddle.fluid.layers.data', 'fluid.layers.data', ([], {'name': '"""shape"""', 'shape': '[1]', 'dtype': '"""float32"""'}), "(name='shape', shape=[1], dtype='float32')\n", (2362, 2404), True, 'import paddle.fluid as fluid\n'), ((2513, 2568), 'paddle.fluid.layers.data', 'fluid.layers.data', ([], {'name': '"""c"""', 'shape': '[1]', 'dtype': '"""float32"""'}), "(name='c', shape=[1], dtype='float32')\n", (2530, 2568), True, 'import paddle.fluid as fluid\n'), ((3424, 3473), 'paddle.fluid.optimizer.Adam', 'fluid.optimizer.Adam', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (3444, 3473), True, 'import paddle.fluid as fluid\n'), ((6235, 6273), 'logging.info', 'logging.info', (['"""This CW attack failed!"""'], {}), "('This CW attack failed!')\n", (6247, 6273), False, 'import logging\n'), ((11991, 12037), 'paddle.fluid.layers.ones', 'fluid.layers.ones', ([], {'shape': '[10]', 'dtype': '"""float32"""'}), "(shape=[10], dtype='float32')\n", (12008, 12037), True, 'import paddle.fluid as fluid\n'), ((13763, 13779), 'numpy.all', 'np.all', (['(sub == 1)'], {}), '(sub == 1)\n', (13769, 13779), True, 'import numpy as np\n'), ((13287, 13297), 'numpy.tanh', 'np.tanh', (['w'], {}), '(w)\n', (13294, 13297), True, 'import numpy as np\n'), ((3703, 3723), 'paddle.fluid.global_scope', 'fluid.global_scope', ([], {}), '()\n', (3721, 3723), True, 'import paddle.fluid as fluid\n'), ((3814, 3850), 'numpy.random.random_sample', 'np.random.random_sample', (['(1, 28, 28)'], {}), '((1, 28, 28))\n', (3837, 3850), True, 'import numpy as np\n'), ((8486, 8522), 'numpy.zeros', 'np.zeros', ([], {'shape': '[1]', 'dtype': '"""float32"""'}), "(shape=[1], dtype='float32')\n", (8494, 8522), True, 'import numpy as np\n')] |
from sklearn.model_selection import cross_val_score, cross_validate
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold, train_test_split
from sklearn import datasets
import sklearn
import statistics
import pandas as pd
import copy
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import LinearSVC
from sklearn import svm
import numpy as np
from collections import Counter
from imblearn.over_sampling import SMOTE, BorderlineSMOTE, SVMSMOTE
from imblearn.under_sampling import RandomUnderSampler
from imblearn.ensemble import BalancedBaggingClassifier
from monitoring.time_it import timing
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report
import xlsxwriter
from mlxtend.classifier import EnsembleVoteClassifier
from sklearn.svm import LinearSVC, SVC
from openpyxl import load_workbook
from types import SimpleNamespace
import ast
import glob
from math import ceil
excel_weights_path = '../results/weights/svm'
@timing
def eval(X, y, config, crossvalidation, clf, sampling_percentage, random_state):
"""
Evaluate Machine Learning Algorithms on the dataset and save results in xlsx-file
:param X: feature matrix (pandas dataframe)
:param y: dependet variable (pandas dataframe)
:param config: configuration file (dictionary)
:param crossvalidation: k-fold crossvalidation (Integer)
:param clf: machine learning algorithm (scikit-learn)
:param sampling_percentage: ratio between failures and non-failures (float)
:param random_state: list of integers, where every Integer stands for a different data sample to perform the
machine learning evaluation (List)
:return: scores (dictionary)
"""
print('Configurations: ' + str(config))
def tp(y_true, y_pred): return confusion_matrix(y_true, y_pred, labels=[config['target_errorCode'], -1])[0, 0]
def tn(y_true, y_pred): return confusion_matrix(y_true, y_pred, labels=[config['target_errorCode'], -1])[1, 1]
def fp(y_true, y_pred): return confusion_matrix(y_true, y_pred, labels=[config['target_errorCode'], -1])[1, 0]
def fn(y_true, y_pred): return confusion_matrix(y_true, y_pred, labels=[config['target_errorCode'], -1])[0, 1]
scoring = {'accuracy': make_scorer(accuracy_score),
'precision': make_scorer(precision_score, pos_label=config['target_errorCode']),
'recall': make_scorer(recall_score, pos_label=config['target_errorCode']),
'f1_score': make_scorer(f1_score, pos_label=config['target_errorCode']),
'precision_neg': make_scorer(precision_score, pos_label=-1),
'recall_neg': make_scorer(recall_score, pos_label=-1),
'f1_score_neg': make_scorer(f1_score, pos_label=-1),
'tp': make_scorer(tp),
'tn': make_scorer(tn),
'fp': make_scorer(fp),
'fn': make_scorer(fn)}
number_of_errors = len(list(y[y == config['target_errorCode']].index))
number_of_non_errors = int(ceil(((number_of_errors / sampling_percentage) - number_of_errors)))
for state in random_state:
rus = RandomUnderSampler(random_state=state, sampling_strategy={config['target_errorCode']: number_of_errors,
-1: number_of_non_errors})
X_rus, y_rus = rus.fit_resample(X, y)
X_remain = X.drop(index=rus.sample_indices_)
y_remain = y.drop(index=rus.sample_indices_)
cv = StratifiedKFold(n_splits=crossvalidation, shuffle=True, random_state=42)
scores = {}
for element in scoring:
scores['test_' + element] = []
if config['oversampling_method']:
for train_idx, test_idx, in cv.split(X_rus, y_rus):
X_train, y_train = X_rus.iloc[train_idx], y_rus.iloc[train_idx]
X_test, y_test = X_rus.iloc[test_idx], y_rus.iloc[test_idx]
oversample = config['oversampling_method']
X_train_oversampled, y_train_oversampled = oversample.fit_sample(X_train, y_train)
clf.fit(X_train_oversampled, y_train_oversampled)
y_pred = clf.predict(X_test)
scores_dict = classification_report(y_test, y_pred, output_dict=True)
scores['test_accuracy'].append(scores_dict['accuracy'])
scores['test_precision'].append(scores_dict[str(config['target_errorCode'])]['precision'])
scores['test_precision_neg'].append(scores_dict['-1']['precision'])
scores['test_recall'].append(scores_dict[str(config['target_errorCode'])]['recall'])
scores['test_recall_neg'].append(scores_dict['-1']['recall'])
scores['test_f1_score'].append(scores_dict[str(config['target_errorCode'])]['f1-score'])
scores['test_f1_score_neg'].append(scores_dict['-1']['f1-score'])
scores['test_tp'].append(tp(y_test, y_pred))
scores['test_tn'].append(tn(y_test, y_pred))
scores['test_fp'].append(fp(y_test, y_pred))
scores['test_fn'].append(fn(y_test, y_pred))
for element in scores:
scores[element] = np.array(scores[element])
elif config['evaluate_all_data']:
for train_index, test_index in cv.split(X_rus, y_rus):
X_train = X_rus.iloc[train_index]
y_train = y_rus.iloc[train_index]
clf.fit(X_train, y_train)
X_test = X_rus.iloc[test_index]
X_test = pd.concat([X_test, X_remain], axis=0)
y_test = y_rus.iloc[test_index]
y_test = pd.concat([y_test, y_remain], axis=0)
y_pred = clf.predict(X_test)
scores_dict = classification_report(y_test, y_pred, output_dict=True)
scores['test_accuracy'].append(scores_dict['accuracy'])
scores['test_precision'].append(scores_dict[str(config['target_errorCode'])]['precision'])
scores['test_precision_neg'].append(scores_dict['-1']['precision'])
scores['test_recall'].append(scores_dict[str(config['target_errorCode'])]['recall'])
scores['test_recall_neg'].append(scores_dict['-1']['recall'])
scores['test_f1_score'].append(scores_dict[str(config['target_errorCode'])]['f1-score'])
scores['test_f1_score_neg'].append(scores_dict['-1']['f1-score'])
scores['test_tp'].append(tp(y_test, y_pred))
scores['test_tn'].append(tn(y_test, y_pred))
scores['test_fp'].append(fp(y_test, y_pred))
scores['test_fn'].append(fn(y_test, y_pred))
for element in scores:
scores[element] = np.array(scores[element])
else:
scores = cross_validate(clf.fit(X_rus, y_rus), X=X_rus, y=y_rus, cv=cv, scoring=scoring, return_estimator=False)
print('Evaluation with crossvalidation')
for key, value in scores.items():
print(str(key))
print(value)
print('M: ' + str(value.mean()))
print('SD: ' + str(value.std()))
wb = load_workbook(filename='../results/Evaluation_results_rus.xlsx')
ws1 = wb.active
counter = len(list(ws1.rows))
n = len(X)
n_error_class = len(y_rus[y_rus == config['target_errorCode']])
n_non_error_class = len(y_rus[y_rus != config['target_errorCode']])
sampling_frequency = config['sampling_frequency']
imputations_technique_str = config['imputations_technique_str']
imputation_technique_num = config['imputation_technique_num']
ts_fresh_window_length = config['ts_fresh_window_length']
ts_fresh_window_end = config['ts_fresh_window_end']
ts_fresh_minimal_features = config['ts_fresh_minimal_features']
target_col = config['target_col']
target_errorCode = config['target_errorCode']
rand_state = state
sampling_percentage = config['sampling_percentage']
balance = config['balance_ratio']
oversampling = str(config['oversampling_method'])
ml_algorithm = str(config['ml_algorithm'])
cv = config['cv']
Accuracy = str(scores['test_accuracy'])
Accuracy_mean = scores['test_accuracy'].mean()
Accuracy_std = scores['test_accuracy'].std()
Precision = str(scores['test_precision'])
Precision_neg = str(scores['test_precision_neg'])
Precision_mean = scores['test_precision'].mean()
Precision_mean_neg = scores['test_precision_neg'].mean()
Precision_std = scores['test_precision'].std()
Precision_std_neg = scores['test_precision_neg'].std()
Recall = str(scores['test_recall'])
Recall_neg = str(scores['test_recall_neg'])
Recall_mean = scores['test_recall'].mean()
Recall_mean_neg = scores['test_recall_neg'].mean()
Recall_std = scores['test_recall'].std()
Recall_std_neg = scores['test_recall_neg'].std()
F1_Score = str(scores['test_f1_score'])
F1_Score_neg = str(scores['test_f1_score_neg'])
F1_Score_mean = scores['test_f1_score'].mean()
F1_Score_mean_neg = scores['test_f1_score_neg'].mean()
F1_Score_std = scores['test_f1_score'].std()
F1_Score_std_neg = scores['test_f1_score_neg'].std()
tp_cv = str(scores['test_tp'])
tn_cv = str(scores['test_tn'])
fp_cv = str(scores['test_fp'])
fn_cv = str(scores['test_fn'])
tp_sum = scores['test_tp'].sum()
tn_sum = scores['test_tn'].sum()
fp_sum = scores['test_fp'].sum()
fn_sum = scores['test_fn'].sum()
tp_mean = scores['test_tp'].mean()
tn_mean = scores['test_tn'].mean()
fp_mean = scores['test_fp'].mean()
fn_mean = scores['test_fn'].mean()
list_to_write_to_file = [counter, n, n_error_class, n_non_error_class, sampling_frequency,
imputations_technique_str, imputation_technique_num, ts_fresh_window_length,
ts_fresh_window_end, ts_fresh_minimal_features, target_col, target_errorCode,
rand_state,
sampling_percentage, balance, oversampling,
ml_algorithm, cv, Accuracy, Accuracy_mean, Accuracy_std, Precision, Precision_neg,
Precision_mean, Precision_mean_neg,
Precision_std, Precision_std_neg, Recall, Recall_neg, Recall_mean, Recall_mean_neg,
Recall_std,
Recall_std_neg, F1_Score, F1_Score_neg, F1_Score_mean, F1_Score_mean_neg, F1_Score_std,
F1_Score_std_neg,
tp_cv, tn_cv, fp_cv, fn_cv, tp_sum, tn_sum, fp_sum, fn_sum, tp_mean, tn_mean, fp_mean,
fn_mean]
ws1.append(list_to_write_to_file)
wb.save(filename='../results/Evaluation_results_rus.xlsx')
return scores
| [
"imblearn.under_sampling.RandomUnderSampler",
"math.ceil",
"openpyxl.load_workbook",
"sklearn.metrics.classification_report",
"sklearn.metrics.make_scorer",
"sklearn.model_selection.StratifiedKFold",
"numpy.array",
"sklearn.metrics.confusion_matrix",
"pandas.concat"
] | [((2356, 2383), 'sklearn.metrics.make_scorer', 'make_scorer', (['accuracy_score'], {}), '(accuracy_score)\n', (2367, 2383), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2413, 2479), 'sklearn.metrics.make_scorer', 'make_scorer', (['precision_score'], {'pos_label': "config['target_errorCode']"}), "(precision_score, pos_label=config['target_errorCode'])\n", (2424, 2479), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2506, 2569), 'sklearn.metrics.make_scorer', 'make_scorer', (['recall_score'], {'pos_label': "config['target_errorCode']"}), "(recall_score, pos_label=config['target_errorCode'])\n", (2517, 2569), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2598, 2657), 'sklearn.metrics.make_scorer', 'make_scorer', (['f1_score'], {'pos_label': "config['target_errorCode']"}), "(f1_score, pos_label=config['target_errorCode'])\n", (2609, 2657), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2691, 2733), 'sklearn.metrics.make_scorer', 'make_scorer', (['precision_score'], {'pos_label': '(-1)'}), '(precision_score, pos_label=-1)\n', (2702, 2733), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2764, 2803), 'sklearn.metrics.make_scorer', 'make_scorer', (['recall_score'], {'pos_label': '(-1)'}), '(recall_score, pos_label=-1)\n', (2775, 2803), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2836, 2871), 'sklearn.metrics.make_scorer', 'make_scorer', (['f1_score'], {'pos_label': '(-1)'}), '(f1_score, pos_label=-1)\n', (2847, 2871), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2894, 2909), 'sklearn.metrics.make_scorer', 'make_scorer', (['tp'], {}), '(tp)\n', (2905, 2909), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2932, 2947), 'sklearn.metrics.make_scorer', 'make_scorer', (['tn'], {}), '(tn)\n', (2943, 2947), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2970, 2985), 'sklearn.metrics.make_scorer', 'make_scorer', (['fp'], {}), '(fp)\n', (2981, 2985), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((3008, 3023), 'sklearn.metrics.make_scorer', 'make_scorer', (['fn'], {}), '(fn)\n', (3019, 3023), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((3132, 3195), 'math.ceil', 'ceil', (['(number_of_errors / sampling_percentage - number_of_errors)'], {}), '(number_of_errors / sampling_percentage - number_of_errors)\n', (3136, 3195), False, 'from math import ceil\n'), ((3247, 3384), 'imblearn.under_sampling.RandomUnderSampler', 'RandomUnderSampler', ([], {'random_state': 'state', 'sampling_strategy': "{config['target_errorCode']: number_of_errors, (-1): number_of_non_errors}"}), "(random_state=state, sampling_strategy={config[\n 'target_errorCode']: number_of_errors, (-1): number_of_non_errors})\n", (3265, 3384), False, 'from imblearn.under_sampling import RandomUnderSampler\n'), ((3616, 3688), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'crossvalidation', 'shuffle': '(True)', 'random_state': '(42)'}), '(n_splits=crossvalidation, shuffle=True, random_state=42)\n', (3631, 3688), False, 'from sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold, train_test_split\n'), ((7335, 7399), 'openpyxl.load_workbook', 'load_workbook', ([], {'filename': '"""../results/Evaluation_results_rus.xlsx"""'}), "(filename='../results/Evaluation_results_rus.xlsx')\n", (7348, 7399), False, 'from openpyxl import load_workbook\n'), ((1903, 1976), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {'labels': "[config['target_errorCode'], -1]"}), "(y_true, y_pred, labels=[config['target_errorCode'], -1])\n", (1919, 1976), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2018, 2091), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {'labels': "[config['target_errorCode'], -1]"}), "(y_true, y_pred, labels=[config['target_errorCode'], -1])\n", (2034, 2091), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2133, 2206), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {'labels': "[config['target_errorCode'], -1]"}), "(y_true, y_pred, labels=[config['target_errorCode'], -1])\n", (2149, 2206), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((2248, 2321), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {'labels': "[config['target_errorCode'], -1]"}), "(y_true, y_pred, labels=[config['target_errorCode'], -1])\n", (2264, 2321), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((4347, 4402), 'sklearn.metrics.classification_report', 'classification_report', (['y_test', 'y_pred'], {'output_dict': '(True)'}), '(y_test, y_pred, output_dict=True)\n', (4368, 4402), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((5345, 5370), 'numpy.array', 'np.array', (['scores[element]'], {}), '(scores[element])\n', (5353, 5370), True, 'import numpy as np\n'), ((5695, 5732), 'pandas.concat', 'pd.concat', (['[X_test, X_remain]'], {'axis': '(0)'}), '([X_test, X_remain], axis=0)\n', (5704, 5732), True, 'import pandas as pd\n'), ((5806, 5843), 'pandas.concat', 'pd.concat', (['[y_test, y_remain]'], {'axis': '(0)'}), '([y_test, y_remain], axis=0)\n', (5815, 5843), True, 'import pandas as pd\n'), ((5919, 5974), 'sklearn.metrics.classification_report', 'classification_report', (['y_test', 'y_pred'], {'output_dict': '(True)'}), '(y_test, y_pred, output_dict=True)\n', (5940, 5974), False, 'from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report\n'), ((6917, 6942), 'numpy.array', 'np.array', (['scores[element]'], {}), '(scores[element])\n', (6925, 6942), True, 'import numpy as np\n')] |
# ===========================================================================
# segmentation.py ---------------------------------------------------------
# ===========================================================================
import rsvis.utils.imgtools as imgtools
import cv2
import numpy as np
from skimage import segmentation, color
from skimage.future import graph
from skimage.measure import label
from sklearn.utils import shuffle
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from sklearn import preprocessing
# class -------------------------------------------------------------------
# ---------------------------------------------------------------------------
class ImgSeg:
"""Compute low-level segmentation methods like felzenswalb' efficient graph based segmentation or k-means based image segementation
https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html#sphx-glr-auto-examples-segmentation-plot-segmentations-py
"""
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def __init__(self, **kwargs):
self.set_param(**kwargs)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def set_param(self, **param):
self._mode = param["mode"] if "mode" in param.keys() else "SLIC-0"
self._kind = param["kind"] if "kind" in param.keys() else "avg"
self._boundaries = param["boundaries"] if "boundaries" in param.keys() else "mark"
self._convert2lab = param["convert2lab"] if "convert2lab" in param.keys() else True
self._color = param["color"] if "color" in param.keys() else True
self._position = param["position"] if "position" in param.keys() else False
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def predict(self, img, **kwargs):
self._img = img
if self._mode == "SLIC":
self.segmentation_slic(**kwargs)
elif self._mode == "SLIC-0":
self.segmentation_slic_zero(**kwargs)
elif self._mode == "Felzenswalb":
self.segmentation_felzenswalb(**kwargs)
elif self._mode == "Normalized Cuts":
self.segmentation_normalized_cuts(**kwargs)
elif self._mode == "KMeans":
self.segmentation_kmeans(**kwargs)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_data_from_img(self):
w, h, d = original_shape = tuple(self._img.shape)
factor = 1.0
if self._img.dtype == np.uint8:
factor = 255
img = self._img.copy()
if not self._color:
img = np.expand_dims(imgtools.gray_image(img), axis=2)
d -= 2
self._convert2lab = False
if self._convert2lab == True:
img = color.rgb2lab(img)
if self._position:
img = self.add_position_array(img)
d += 2
return np.reshape(np.array(img, dtype=np.float64) / factor, (w * h, d))
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def add_position_array(self, img):
w, h, _ = original_shape = tuple(self._img.shape)
x = np.linspace(0, 1, h)
y = np.linspace(0, 1, w)
xv, yv = np.meshgrid(x,y)
xv = np.expand_dims(xv, axis=2)
yv = np.expand_dims(yv, axis=2)
return np.concatenate((img, xv, yv), axis=2)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_seg_map_from_data(self, pred):
w, h, _ = original_shape = tuple(self._img.shape)
return np.squeeze(np.reshape(pred, (w, h, 1)).astype(np.int32))
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_seg_map(self):
return self._seg_map
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_num_label(self):
return len(self.get_label())
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_label(self):
return np.unique(self._seg_map)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_seg_map_color(self):
if self._kind=="avg" or self._kind=="overlay":
seg_map_color = color.label2rgb(self._seg_map, self._img, kind=self._kind, bg_label=-1)
elif self._kind == "min" or self._kind == "max":
factor = -1.0 if self._kind == "min" else 1.0
seg_map_color = np.zeros(self._img.shape, dtype=np.uint8)
for label in self.get_label():
values = self._img[self._seg_map==label]
value = np.mean(values, axis=0) + factor*np.std(values, axis=0)
value = np.where(value<0, 0, value)
value = np.where(value>255, 255, value)
seg_map_color[self._seg_map==label] = value
# seg_map_color[self._seg_map==label] = np.std(values, axis=0)
# seg_map_color = imgtools.project_data_to_img(seg_map_color, dtype=np.uint8, factor=255)
return seg_map_color
# print(np.mean(values, axis=0))
# print(np.std(values, axis=0))
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_seg_map_boundaries(self, img=None, mode="inner"):
if not isinstance(img, np.ndarray):
img = self._img
# img = imgtools.stack_image_dim(img)
seg_map_bin = segmentation.find_boundaries(self._seg_map, mode=mode)
if mode=="inner":
img = cv2.resize(img, (seg_map_bin.shape[1],seg_map_bin.shape[0]))
# colored boundaries
# return img*seg_map_bin[:,:,np.newaxis]
img_colorize = np.stack([np.zeros(seg_map_bin.shape, dtype=np.uint8),np.full(seg_map_bin.shape, 255, dtype=np.uint8), np.zeros(seg_map_bin.shape, dtype=np.uint8)], axis=2)
return img*np.invert(seg_map_bin)[:,:,np.newaxis] + img_colorize*seg_map_bin[:,:,np.newaxis]
# if self._boundaries=="mark":
# return segmentation.mark_boundaries(self._img, self._seg_map, mode="subpixel")
# elif self._boundaries=="find":
# return segmentation.find_boundaries(self._seg_map, mode="subpixel")
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_visualization(self):
img_list = [self.get_seg_map_color()]
if self._mode != "KMeans":
img_list.append(self.get_seg_map_boundaries())
return img_list
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def segmentation_kmeans(self, **kwargs):
"""
https://towardsdatascience.com/introduction-to-image-segmentation-with-k-means-clustering-83fd0a9e2fc3
https://towardsdatascience.com/k-means-clustering-with-scikit-learn-6b47a369a83c
"""
data = scale(self.get_data_from_img())
km = KMeans(**kwargs, init="random").fit(data)
pred = km.predict(data)
self._seg_map = self.get_seg_map_from_data(pred)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def segmentation_slic(self, **kwargs):
"""
n_segments = the (approximate) number of labels in the segmented output image.
compactness: balances color proximity and space proximity.
max_iter: maximum number of iterations of k-means.
https://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.slic
"""
self._seg_map = segmentation.slic(self._img, **kwargs, start_label=1)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def segmentation_slic_zero(self, **kwargs):
""" https://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.slic
"""
self.segmentation_slic(slic_zero=True, **kwargs)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def segmentation_felzenswalb(self, **kwargs):
""" https://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.felzenszwalb.
"""
self._seg_map = segmentation.felzenszwalb(self._img, **kwargs)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def segmentation_normalized_cuts(self, **kwargs):
""" https://scikit-image.org/docs/stable/api/skimage.future.graph.html#skimage.future.graph.cut_normalized
https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_ncut.html
"""
self.segmentation_slic_zero(**kwargs)
slic_graph = graph.rag_mean_color(self._img, self._seg_map, mode='similarity') # parameter?
self._seg_map = graph.cut_normalized(self._seg_map, slic_graph)
# # # # function ----------------------------------------------------------------
# # # # ---------------------------------------------------------------------------
# # # def segmentation_felzenswalb(img, boundaries="mark", **kwargs):
# # # # param_str = "felz-{}".format("-".join([str(e) for e in **kwargs]))
# # # seg_map = segmentation.felzenszwalb(img, **kwargs)
# # # seg_map_color = color.label2rgb(seg_map, img, kind='avg', bg_label=-1)
# # # seg_map_color_bound = segementation_get_boundaries(seg_map_color, seg_map, boundaries=boundaries)
# # # # define image list for visualization
# # # return seg_map, seg_map_color, seg_map_color_bound
# # # # function ----------------------------------------------------------------
# # # # ---------------------------------------------------------------------------
# # # def segmentation_slic(img, boundaries="mark", **kwargs):
# # # seg_map = segmentation.slic(img, **kwargs, start_label=1)
# # # seg_map_color = color.label2rgb(seg_map, img, kind='avg', bg_label=-1)
# # # seg_map_color_bound = segementation_get_boundaries(seg_map_color, seg_map, boundaries=boundaries)
# # # # define image list for visualization
# # # return seg_map, seg_map_color, seg_map_color_bound
# # # # function ----------------------------------------------------------------
# # # # ---------------------------------------------------------------------------
# # # def segmentation_norm(img, boundaries="mark", **kwargs):
# # # seg_map = segmentation.slic(img, **kwargs, start_label=1)
# # # g = graph.rag_mean_color(img, seg_map, mode='similarity')
# # # seg_map = graph.cut_normalized(seg_map, g)
# # # seg_map_color = color.label2rgb(seg_map, img, kind='avg', bg_label=-1)
# # # seg_map_color_bound = segementation_get_boundaries(seg_map_color, seg_map, boundaries=boundaries)
# # # # define image list for visualization
# # # return seg_map, seg_map_color, seg_map_color_bound
# # # # function ----------------------------------------------------------------
# # # # ---------------------------------------------------------------------------
# # # def segmentation_kmeans_color(img, boundaries="mark", non_pos=True, lab=True, **kwargs):
# # # """Compute low-level segmentation methods like felzenswalb' efficient graph based segmentation or k-means based image segementation
# # # https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html#sphx-glr-auto-examples-segmentation-plot-segmentations-py
# # # """
# # # # https://towardsdatascience.com/introduction-to-image-segmentation-with-k-means-clustering-83fd0a9e2fc3
# # # # https://towardsdatascience.com/k-means-clustering-with-scikit-learn-6b47a369a83c
# # # if lab:
# # # data_img = color.rgb2lab(img.copy())
# # # w, h, d = original_shape = tuple(data_img.shape)
# # # image_array = np.reshape(np.array(data_img, dtype=np.float64) / 255, (w * h, d))
# # # # Fitting model on a small sub-sample of the data"
# # # # image_array_sample = shuffle(image_array, random_state=0)[:1000]
# # # km = KMeans(**kwargs, init="random").fit(image_array)
# # # pred = km.predict(image_array)
# # # seg_map = np.squeeze(np.reshape(pred, (w, h, 1)).astype(np.int32))
# # # seg_map_color = color.label2rgb(seg_map, img, kind='avg', bg_label=-1)
# # # # seg_map_color = color.lab2rgb(np.reshape(km.cluster_centers_[km.labels_], (w, h, d)))
# # # # print(seg_map.dtype)
# # # # print(seg_map_color.dtype)
# # # return seg_map, seg_map_color
# # # # function ----------------------------------------------------------------
# # # # ---------------------------------------------------------------------------
# # # def segmentation_kmeans_color_pos(img, boundaries="mark", non_pos=True, lab=True, **kwargs):
# # # """Compute low-level segmentation methods like felzenswalb' efficient graph based segmentation or k-means based image segementation
# # # https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html#sphx-glr-auto-examples-segmentation-plot-segmentations-py
# # # """
# # # # https://towardsdatascience.com/introduction-to-image-segmentation-with-k-means-clustering-83fd0a9e2fc3
# # # # https://towardsdatascience.com/k-means-clustering-with-scikit-learn-6b47a369a83c
# # # if non_pos:
# # # if lab:
# # # data_img = color.rgb2lab(img.copy())
# # # else:
# # # data_img = imgtools.gray_image(img)
# # # data_img = np.expand_dims(data_img, axis=2)
# # # w, h, d = original_shape = tuple(data_img.shape)
# # # x = np.linspace(0, 1, h)
# # # y = np.linspace(0, 1, w)
# # # xv, yv = np.meshgrid(x,y)
# # # xv = np.expand_dims(xv, axis=2)
# # # yv = np.expand_dims(yv, axis=2)
# # # img_data = np.array(data_img, dtype=np.float64) / 255
# # # data = np.concatenate((img_data, xv, yv), axis=2)
# # # data_array = np.reshape(data, (w * h, d + 2))
# # # # Fitting model on a small sub-sample of the data"
# # # # image_array_sample = shuffle(image_array, random_state=0)[:1000]
# # # data_array_scaled = preprocessing.scale(data_array)
# # # km = KMeans(**kwargs, init="random").fit(data_array_scaled)
# # # pred = km.predict(data_array_scaled)
# # # seg_map = np.squeeze(np.reshape(pred, (w, h, 1)).astype(np.int32))
# # # seg_map_color = color.label2rgb(seg_map, img, kind='avg', bg_label=-1)
# # # # seg_map_color = np.reshape(km.cluster_centers_[:,:d][km.labels_], (w, h, d))
# # # # print(seg_map.dtype)
# # # # print(seg_map_color.dtype)
# # # return seg_map, seg_map_color
# # # # function ----------------------------------------------------------------
# # # # ---------------------------------------------------------------------------
# # # def segementation_get_boundaries(img, seg_map, boundaries="mark", **kwargs):
# # # if boundaries == "mark":
# # # seg_map_bound = segmentation.mark_boundaries(img, seg_map, mode="subpixel")
# # # elif boundaries == "find":
# # # seg_map_bound = segmentation.find_boundaries(seg_map, mode="subpixel")
# # # return seg_map_bound | [
"numpy.invert",
"numpy.mean",
"skimage.future.graph.rag_mean_color",
"numpy.unique",
"skimage.color.rgb2lab",
"skimage.segmentation.find_boundaries",
"numpy.full",
"numpy.meshgrid",
"numpy.std",
"sklearn.cluster.KMeans",
"numpy.reshape",
"numpy.linspace",
"cv2.resize",
"skimage.future.grap... | [((3664, 3684), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'h'], {}), '(0, 1, h)\n', (3675, 3684), True, 'import numpy as np\n'), ((3697, 3717), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'w'], {}), '(0, 1, w)\n', (3708, 3717), True, 'import numpy as np\n'), ((3735, 3752), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (3746, 3752), True, 'import numpy as np\n'), ((3765, 3791), 'numpy.expand_dims', 'np.expand_dims', (['xv'], {'axis': '(2)'}), '(xv, axis=2)\n', (3779, 3791), True, 'import numpy as np\n'), ((3805, 3831), 'numpy.expand_dims', 'np.expand_dims', (['yv'], {'axis': '(2)'}), '(yv, axis=2)\n', (3819, 3831), True, 'import numpy as np\n'), ((3856, 3893), 'numpy.concatenate', 'np.concatenate', (['(img, xv, yv)'], {'axis': '(2)'}), '((img, xv, yv), axis=2)\n', (3870, 3893), True, 'import numpy as np\n'), ((4862, 4886), 'numpy.unique', 'np.unique', (['self._seg_map'], {}), '(self._seg_map)\n', (4871, 4886), True, 'import numpy as np\n'), ((6467, 6521), 'skimage.segmentation.find_boundaries', 'segmentation.find_boundaries', (['self._seg_map'], {'mode': 'mode'}), '(self._seg_map, mode=mode)\n', (6495, 6521), False, 'from skimage import segmentation, color\n'), ((8810, 8863), 'skimage.segmentation.slic', 'segmentation.slic', (['self._img'], {'start_label': '(1)'}), '(self._img, **kwargs, start_label=1)\n', (8827, 8863), False, 'from skimage import segmentation, color\n'), ((9594, 9640), 'skimage.segmentation.felzenszwalb', 'segmentation.felzenszwalb', (['self._img'], {}), '(self._img, **kwargs)\n', (9619, 9640), False, 'from skimage import segmentation, color\n'), ((10135, 10200), 'skimage.future.graph.rag_mean_color', 'graph.rag_mean_color', (['self._img', 'self._seg_map'], {'mode': '"""similarity"""'}), "(self._img, self._seg_map, mode='similarity')\n", (10155, 10200), False, 'from skimage.future import graph\n'), ((10238, 10285), 'skimage.future.graph.cut_normalized', 'graph.cut_normalized', (['self._seg_map', 'slic_graph'], {}), '(self._seg_map, slic_graph)\n', (10258, 10285), False, 'from skimage.future import graph\n'), ((3203, 3221), 'skimage.color.rgb2lab', 'color.rgb2lab', (['img'], {}), '(img)\n', (3216, 3221), False, 'from skimage import segmentation, color\n'), ((5162, 5233), 'skimage.color.label2rgb', 'color.label2rgb', (['self._seg_map', 'self._img'], {'kind': 'self._kind', 'bg_label': '(-1)'}), '(self._seg_map, self._img, kind=self._kind, bg_label=-1)\n', (5177, 5233), False, 'from skimage import segmentation, color\n'), ((6566, 6627), 'cv2.resize', 'cv2.resize', (['img', '(seg_map_bin.shape[1], seg_map_bin.shape[0])'], {}), '(img, (seg_map_bin.shape[1], seg_map_bin.shape[0]))\n', (6576, 6627), False, 'import cv2\n'), ((3041, 3065), 'rsvis.utils.imgtools.gray_image', 'imgtools.gray_image', (['img'], {}), '(img)\n', (3060, 3065), True, 'import rsvis.utils.imgtools as imgtools\n'), ((3343, 3374), 'numpy.array', 'np.array', (['img'], {'dtype': 'np.float64'}), '(img, dtype=np.float64)\n', (3351, 3374), True, 'import numpy as np\n'), ((5377, 5418), 'numpy.zeros', 'np.zeros', (['self._img.shape'], {'dtype': 'np.uint8'}), '(self._img.shape, dtype=np.uint8)\n', (5385, 5418), True, 'import numpy as np\n'), ((6740, 6783), 'numpy.zeros', 'np.zeros', (['seg_map_bin.shape'], {'dtype': 'np.uint8'}), '(seg_map_bin.shape, dtype=np.uint8)\n', (6748, 6783), True, 'import numpy as np\n'), ((6784, 6831), 'numpy.full', 'np.full', (['seg_map_bin.shape', '(255)'], {'dtype': 'np.uint8'}), '(seg_map_bin.shape, 255, dtype=np.uint8)\n', (6791, 6831), True, 'import numpy as np\n'), ((6833, 6876), 'numpy.zeros', 'np.zeros', (['seg_map_bin.shape'], {'dtype': 'np.uint8'}), '(seg_map_bin.shape, dtype=np.uint8)\n', (6841, 6876), True, 'import numpy as np\n'), ((8094, 8125), 'sklearn.cluster.KMeans', 'KMeans', ([], {'init': '"""random"""'}), "(**kwargs, init='random')\n", (8100, 8125), False, 'from sklearn.cluster import KMeans\n'), ((4179, 4206), 'numpy.reshape', 'np.reshape', (['pred', '(w, h, 1)'], {}), '(pred, (w, h, 1))\n', (4189, 4206), True, 'import numpy as np\n'), ((5640, 5669), 'numpy.where', 'np.where', (['(value < 0)', '(0)', 'value'], {}), '(value < 0, 0, value)\n', (5648, 5669), True, 'import numpy as np\n'), ((5692, 5725), 'numpy.where', 'np.where', (['(value > 255)', '(255)', 'value'], {}), '(value > 255, 255, value)\n', (5700, 5725), True, 'import numpy as np\n'), ((6907, 6929), 'numpy.invert', 'np.invert', (['seg_map_bin'], {}), '(seg_map_bin)\n', (6916, 6929), True, 'import numpy as np\n'), ((5560, 5583), 'numpy.mean', 'np.mean', (['values'], {'axis': '(0)'}), '(values, axis=0)\n', (5567, 5583), True, 'import numpy as np\n'), ((5593, 5615), 'numpy.std', 'np.std', (['values'], {'axis': '(0)'}), '(values, axis=0)\n', (5599, 5615), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from keras.models import load_model
import matplotlib.lines as mlines
def adjust_spines(ax, spines):
for loc, spine in ax.spines.items():
if loc in spines:
spine.set_position(('outward', 10)) # outward by 10 points
else:
spine.set_color('none') # don't draw spine
# turn off ticks where there is no spine
if 'left' in spines:
ax.yaxis.set_ticks_position('left')
else:
# no yaxis ticks
ax.yaxis.set_ticks([])
if 'bottom' in spines:
ax.xaxis.set_ticks_position('bottom')
else:
# no xaxis ticks
ax.xaxis.set_ticks([])
def RG_decimation(config):
#config=config.reshape(config.shape[0] * config.shape[1])
#half_root= int(np.sqrt(config.shape[0]/2))
RG_config = np.zeros([int(config.shape[0]),int(config.shape[1]/2)])
#print(config.shape,RG_config.shape)
for i in range(config.shape[0]):
for j in range(config.shape[1]):
if ((i+j)%2==0): RG_config[int(i),int(j/2)] = config[i,j]
#print("Initial",config)
#print("RG:",RG_config.T)
return RG_config
def RG_decimation_2(config):
#config=config.reshape(config.shape[0] * config.shape[1])
RG_config = np.zeros([int(config.shape[0]/2),int(config.shape[1])])
#print(config.shape,RG_config.shape)
for i in range(config.shape[0]):
for j in range(config.shape[1]):
if ((i)%2==0): RG_config[int(i/2),int(j)] = config[i,j]
#print("Initial",config)
#print("RG:",RG_config.T)
return RG_config
lattice_size=32
in_dim=int(lattice_size*lattice_size)
out_dim=int(in_dim/4)
cmap = colors.ListedColormap(['black','white'])
bounds=[-1.5,0, 1.5]
norm = colors.BoundaryNorm(bounds, cmap.N)
# This is the size of our encoded representations
encoding_dim = out_dim # 32 floats -> compression of factor 24.5, assuming the input is 784 floats
model_name1="Full_Ising_AE_Deci_32x32.h5"
model_name2="Ising_temp32_512_relu.h5"
Auto_encoder = load_model(model_name1)
beta_reg32 = load_model(model_name2)
#RG_encoder.summary()
x_train = np.load("Ising_32_T_1000_60000_1.npz")["Lattice"]
x_train = x_train.astype('float32')
x_train = x_train.reshape(x_train.shape[0],in_dim)
y_train = np.load("Ising_32_T_1000_60000_1.npz")["beta"]
y_train = y_train.astype('float32')
y_train = y_train.reshape(y_train.shape[0],1)
#print("Input shape:",x_train.shape)
#encoded_imgs = RG_encoder.predict(x_train[2000:2999])
beta_lattice, beta_ae, beta_ae1, beta_ae2, beta_frg, beta_hrg = [],[],[],[],[],[]
fig, ax = plt.subplots()
config0=0
j=0
Tc=0.4352
for i in range(config0, x_train.shape[0],5):
#rnd = np.random.randint(x_train.shape[0])
# print("Random Number:",i)
# print(x_train[i].shape)
if (y_train[i] >= 0.1):
config = x_train[i].reshape(1,1024)
beta = y_train[i].reshape(1)
#config_2x = RG_decimation_2(RG_decimation(x_train[i].reshape(32,32)))
AE_img = Auto_encoder.predict(config)
lattice=x_train[i].reshape(lattice_size, lattice_size)
#ae_lattice=AE_img.reshape(int(lattice_size), lattice_size)
#ae_lattice= np.sign(ae_lattice)
#beta_effective = beta_reg32.predict(ae_lattice.reshape(1, 1024)).reshape(1) - beta_reg32.predict(config)
beta_ae.append(beta_reg32.predict(np.sign(AE_img)).reshape(1))
beta_frg.append(3*np.log(np.cosh(4*beta))/8)
#print(beta)
if (j%20==0):
ax.scatter(beta, beta_ae[j], marker='.', color='blue', label="AE predicted'{0}'".format('.'))
#print(beta)
j+=1
print(j)
xspace= np.arange(0.1,0.6, 0.00025)
avg_lat= np.average(beta_lattice)
avg_frg= np.average(beta_frg)
print("Average Beta:",avg_lat)
print("Average FRG Beta:", avg_frg)
print(xspace.shape)
m, b = np.polyfit(xspace, beta_ae, 1)
print("m,b=", m,b)
line3 = mlines.Line2D([0.1, 0.6], [0.1,0.6], color='black')
ax.add_line(line3)
ax.plot(xspace, beta_frg, color='red')
ax.plot(xspace, m*xspace + b, color='blue')
ax.legend(['Intitial β', 'β`~ln(cosh(β))', 'AE predicted β'], loc='lower right')
ax.set_xlim(0.1, 0.6)
ax.set_ylim(0.1, 0.6)
#ax.title.set_text('Change ')
ax.set_xlabel('Initial (β)')
ax.set_ylabel('Predicted (β`)')
#plt.xticks(range(0.5, 1))
#plt.yticks(range(0.5, 1))
#plt.xlim(0.7, 1.1)
#plt.ylim(0.7, 1.1)
#plt.scatter(x, y, s=area2, marker='o', c=c)
# Show the boundary between the regions:
#theta = np.arange(0, np.pi / 2, 0.01)
#plt.plot(r0 * np.cos(theta), r0 * np.sin(theta))
plt.show()
| [
"keras.models.load_model",
"numpy.load",
"numpy.average",
"matplotlib.pyplot.show",
"matplotlib.lines.Line2D",
"numpy.polyfit",
"matplotlib.colors.BoundaryNorm",
"matplotlib.pyplot.subplots",
"numpy.arange",
"numpy.sign",
"numpy.cosh",
"matplotlib.colors.ListedColormap"
] | [((1763, 1804), 'matplotlib.colors.ListedColormap', 'colors.ListedColormap', (["['black', 'white']"], {}), "(['black', 'white'])\n", (1784, 1804), False, 'from matplotlib import colors\n'), ((1834, 1869), 'matplotlib.colors.BoundaryNorm', 'colors.BoundaryNorm', (['bounds', 'cmap.N'], {}), '(bounds, cmap.N)\n', (1853, 1869), False, 'from matplotlib import colors\n'), ((2128, 2151), 'keras.models.load_model', 'load_model', (['model_name1'], {}), '(model_name1)\n', (2138, 2151), False, 'from keras.models import load_model\n'), ((2166, 2189), 'keras.models.load_model', 'load_model', (['model_name2'], {}), '(model_name2)\n', (2176, 2189), False, 'from keras.models import load_model\n'), ((2701, 2715), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2713, 2715), True, 'import matplotlib.pyplot as plt\n'), ((3778, 3806), 'numpy.arange', 'np.arange', (['(0.1)', '(0.6)', '(0.00025)'], {}), '(0.1, 0.6, 0.00025)\n', (3787, 3806), True, 'import numpy as np\n'), ((3816, 3840), 'numpy.average', 'np.average', (['beta_lattice'], {}), '(beta_lattice)\n', (3826, 3840), True, 'import numpy as np\n'), ((3851, 3871), 'numpy.average', 'np.average', (['beta_frg'], {}), '(beta_frg)\n', (3861, 3871), True, 'import numpy as np\n'), ((3976, 4006), 'numpy.polyfit', 'np.polyfit', (['xspace', 'beta_ae', '(1)'], {}), '(xspace, beta_ae, 1)\n', (3986, 4006), True, 'import numpy as np\n'), ((4036, 4088), 'matplotlib.lines.Line2D', 'mlines.Line2D', (['[0.1, 0.6]', '[0.1, 0.6]'], {'color': '"""black"""'}), "([0.1, 0.6], [0.1, 0.6], color='black')\n", (4049, 4088), True, 'import matplotlib.lines as mlines\n'), ((4707, 4717), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4715, 4717), True, 'import matplotlib.pyplot as plt\n'), ((2226, 2264), 'numpy.load', 'np.load', (['"""Ising_32_T_1000_60000_1.npz"""'], {}), "('Ising_32_T_1000_60000_1.npz')\n", (2233, 2264), True, 'import numpy as np\n'), ((2380, 2418), 'numpy.load', 'np.load', (['"""Ising_32_T_1000_60000_1.npz"""'], {}), "('Ising_32_T_1000_60000_1.npz')\n", (2387, 2418), True, 'import numpy as np\n'), ((3478, 3493), 'numpy.sign', 'np.sign', (['AE_img'], {}), '(AE_img)\n', (3485, 3493), True, 'import numpy as np\n'), ((3541, 3558), 'numpy.cosh', 'np.cosh', (['(4 * beta)'], {}), '(4 * beta)\n', (3548, 3558), True, 'import numpy as np\n')] |
####################
# This file consist of different edge enhancement methods.
# It serves as the edge enhancement componenet in our pipeline
import numpy as np
import cv2
import os
import sys
import glob
import logging
from detect import main as detect
IMAGE_PATH = './input/nyc.png'
CARTOON_PATH = './output/shinkai/nyc.png'
EDGES = ['adaptive', 'canny', 'morph', 'original']
# logger
logger = logging.getLogger("Enhancer")
logger.propagate = False
log_lvl = {"debug": logging.DEBUG, "info": logging.INFO,
"warning": logging.WARNING, "error": logging.ERROR,
"critical": logging.CRITICAL}
logger.setLevel( log_lvl['info'] )
formatter = logging.Formatter(
"[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s", "%Y-%m-%d %H:%M:%S")
stdhandler = logging.StreamHandler(sys.stdout)
stdhandler.setFormatter(formatter)
logger.addHandler(stdhandler)
# get canny edges in each of the region of interest
def getCannyEdge( objects, cartoon ):
# pre-process
edges = np.zeros( cartoon.shape[:2], np.uint8 )
grey = cv2.cvtColor( cartoon, cv2.COLOR_BGR2GRAY )
blur = cv2.GaussianBlur( grey, ( 5, 5 ), 0 )
# for each region of interest with score larger than 90%
for score, roi in zip( objects['scores'], objects['rois'] ):
if( score > 0.9 ):
# clip to the region
region = blur[ roi[0] : roi[2], roi[1] : roi[3] ]
# edge detection
highThresh, _ = cv2.threshold( region, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU )
lowThresh = highThresh * 0.75
edge = cv2.Canny( region, lowThresh, highThresh )
# edge refinement
kern = np.ones( ( 3, 3 ), np.uint8 )
dilate = cv2.dilate( edge, kern )
erode = cv2.erode( dilate, kern )
# find contour
cont, hier = cv2.findContours( erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE )
edge = cv2.drawContours( np.zeros( region.shape[:2], np.uint8 ), cont, -1, 255, 1 )
# place regional edge to the whole picture
edges[ roi[0] : roi[2], roi[1] : roi[3] ] = edge
# edges = cv2.rectangle( edges, ( roi[1], roi[0] ), ( roi[3], roi[2] ), 127, 1 )
return edges
# get morphologic edge in each of the region of interest
def getMorphEdge( objects, cartoon ):
# pre-process
edges = np.zeros( cartoon.shape[:2], np.uint8 )
grey = cv2.cvtColor( cartoon, cv2.COLOR_BGR2GRAY )
# for each region of interest with score larger than 90%
for score, roi in zip( objects['scores'], objects['rois'] ):
if( score > 0.9 ):
# clip to the region
region = grey[ roi[0] : roi[2], roi[1] : roi[3] ]
# threshold edges
_, thresh = cv2.threshold( region, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU )
# dilated edges
kern = np.ones( ( 3, 3 ), np.uint8 )
dilate = cv2.dilate( thresh, kern )
# difference between edges to get actual edges
edge = cv2.absdiff( dilate, thresh )
# place regional edge to the whole picture
edges[ roi[0] : roi[2], roi[1] : roi[3] ] = edge
return edges
# get adaptive edge in each of the region of interest
def getAdaptiveEdge( objects, cartoon ):
# pre-process
edges = np.zeros( cartoon.shape[:2], np.uint8 )
grey = cv2.cvtColor( cartoon, cv2.COLOR_BGR2GRAY )
# for each region of interest with score larger than 90%
for score, roi in zip( objects['scores'], objects['rois'] ):
if( score > 0.9 ):
# parameters to be tuned
area = ( roi[2] - roi[0] ) * ( roi[3] - roi[1] )
lineSize = max( round( ( ( area ** 0.5 ) / 61.8 - 1 ) / 2 ) * 2 + 1, 3 ) # has to be odd
blurSize = 5
# clip to the region
region = grey[ roi[0] : roi[2], roi[1] : roi[3] ]
blur = cv2.medianBlur( region, blurSize )
# threshold edges
edge = cv2.adaptiveThreshold( blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, lineSize, blurSize )
edge = 255 - edge
# place regional edge to the whole picture
edges[ roi[0] : roi[2], roi[1] : roi[3] ] = edge
return edges
# get edges and enhanced image base on method
def getEdge( obj, cartoon, method ):
edgeImage, enhancedImage = None, None
if method == EDGES[0]:
edgeImage = getAdaptiveEdge( obj, cartoon )
enhancedImage = cv2.bitwise_and( cartoon, cartoon, mask = 255 - edgeImage )
elif method == EDGES[1]:
edgeImage = getCannyEdge( obj, cartoon )
enhancedImage = cv2.bitwise_and( cartoon, cartoon, mask = 255 - edgeImage )
elif method == EDGES[2]:
edgeImage = getMorphEdge( obj, cartoon )
enhancedImage = cv2.bitwise_and( cartoon, cartoon, mask = 255 - edgeImage )
elif method == EDGES[3]:
edgeImage = np.zeros( cartoon.shape[:2], np.uint8 )
enhancedImage = cartoon
return edgeImage, enhancedImage
# enhance objects in cartoon image
def main( imagePath, outputDir, edges, styles ):
logger.info( f'Retrieving images...' )
# get file name
filename = imagePath.split(os.path.sep)[-1]
# useful directory paths
tempDir = os.path.join( outputDir, '.tmp')
pngDir = os.path.join( tempDir, os.path.splitext( filename )[0] )
logger.info( f'Generating {edges} edges with {styles} styles...' )
for style in styles:
# find cartoon and objects based on image type
if filename.endswith( '.gif' ):
# find cartoons from temporary folder
cartoonPaths = []
cartoonPaths.extend( glob.glob( os.path.join( pngDir, style, f"*.png" ) ) )
cartoonPaths = sorted( cartoonPaths, key=lambda x: int(x.split('/')[-1].replace('.png', '')) )
num_images = len( cartoonPaths )
# find objects from temporary folder
objPaths = []
objPaths.extend( glob.glob( os.path.join( pngDir, "objects", f"*.npy" ) ) )
objPaths = sorted( objPaths, key=lambda x: int(x.split('/')[-1].replace('.npy', '')) )
else:
# find cartoons from cartoon folder
cartoonPaths = [ os.path.join( outputDir, style, filename ) ]
# find objects from temporary folder
objPaths = [ os.path.join( pngDir, "objects", "0.npy" ) ]
# generate edges
for e in edges:
logger.debug( f'Generating {e} edge with {style} style...' )
for i, ( cPath, oPath ) in enumerate( zip( cartoonPaths, objPaths ) ):
# get edges
cartoon = cv2.imread( cPath )
obj = np.load( oPath, allow_pickle = True )[()]
edgeImage, enhancedImage = getEdge( obj, cartoon, e )
# create directory and save edges
edgeDir = os.path.join( pngDir, style, e )
if not os.path.exists( edgeDir ):
os.makedirs( edgeDir )
edgeFilename = f"{i + 1}.png"
cv2.imwrite( os.path.join( edgeDir, edgeFilename ), edgeImage )
# create directory and save enhanced image
if filename.endswith( '.gif' ):
# save image to temporary folder
enhancedDir = os.path.join( pngDir, style, e, 'enhanced' )
if not os.path.exists( enhancedDir ):
os.makedirs( enhancedDir )
enhancedFilename = f"{i + 1}.png"
cv2.imwrite( os.path.join( enhancedDir, enhancedFilename ), enhancedImage )
else:
# save image to directly to desired output folder
enhancedDir = os.path.join( outputDir, style, e )
if not os.path.exists( enhancedDir ):
os.makedirs( enhancedDir )
enhancedFilename = filename
cv2.imwrite( os.path.join( enhancedDir, enhancedFilename ), enhancedImage )
return
| [
"cv2.GaussianBlur",
"numpy.load",
"cv2.bitwise_and",
"cv2.medianBlur",
"numpy.ones",
"cv2.adaptiveThreshold",
"logging.getLogger",
"logging.Formatter",
"cv2.absdiff",
"cv2.erode",
"os.path.join",
"cv2.dilate",
"cv2.cvtColor",
"os.path.exists",
"cv2.Canny",
"logging.StreamHandler",
"o... | [((403, 432), 'logging.getLogger', 'logging.getLogger', (['"""Enhancer"""'], {}), "('Enhancer')\n", (420, 432), False, 'import logging\n'), ((666, 764), 'logging.Formatter', 'logging.Formatter', (['"""[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s"""', '"""%Y-%m-%d %H:%M:%S"""'], {}), "('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',\n '%Y-%m-%d %H:%M:%S')\n", (683, 764), False, 'import logging\n'), ((779, 812), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (800, 812), False, 'import logging\n'), ((1000, 1037), 'numpy.zeros', 'np.zeros', (['cartoon.shape[:2]', 'np.uint8'], {}), '(cartoon.shape[:2], np.uint8)\n', (1008, 1037), True, 'import numpy as np\n'), ((1051, 1092), 'cv2.cvtColor', 'cv2.cvtColor', (['cartoon', 'cv2.COLOR_BGR2GRAY'], {}), '(cartoon, cv2.COLOR_BGR2GRAY)\n', (1063, 1092), False, 'import cv2\n'), ((1106, 1139), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['grey', '(5, 5)', '(0)'], {}), '(grey, (5, 5), 0)\n', (1122, 1139), False, 'import cv2\n'), ((2368, 2405), 'numpy.zeros', 'np.zeros', (['cartoon.shape[:2]', 'np.uint8'], {}), '(cartoon.shape[:2], np.uint8)\n', (2376, 2405), True, 'import numpy as np\n'), ((2419, 2460), 'cv2.cvtColor', 'cv2.cvtColor', (['cartoon', 'cv2.COLOR_BGR2GRAY'], {}), '(cartoon, cv2.COLOR_BGR2GRAY)\n', (2431, 2460), False, 'import cv2\n'), ((3345, 3382), 'numpy.zeros', 'np.zeros', (['cartoon.shape[:2]', 'np.uint8'], {}), '(cartoon.shape[:2], np.uint8)\n', (3353, 3382), True, 'import numpy as np\n'), ((3396, 3437), 'cv2.cvtColor', 'cv2.cvtColor', (['cartoon', 'cv2.COLOR_BGR2GRAY'], {}), '(cartoon, cv2.COLOR_BGR2GRAY)\n', (3408, 3437), False, 'import cv2\n'), ((5319, 5350), 'os.path.join', 'os.path.join', (['outputDir', '""".tmp"""'], {}), "(outputDir, '.tmp')\n", (5331, 5350), False, 'import os\n'), ((4532, 4587), 'cv2.bitwise_and', 'cv2.bitwise_and', (['cartoon', 'cartoon'], {'mask': '(255 - edgeImage)'}), '(cartoon, cartoon, mask=255 - edgeImage)\n', (4547, 4587), False, 'import cv2\n'), ((1451, 1517), 'cv2.threshold', 'cv2.threshold', (['region', '(0)', '(255)', '(cv2.THRESH_BINARY + cv2.THRESH_OTSU)'], {}), '(region, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n', (1464, 1517), False, 'import cv2\n'), ((1581, 1621), 'cv2.Canny', 'cv2.Canny', (['region', 'lowThresh', 'highThresh'], {}), '(region, lowThresh, highThresh)\n', (1590, 1621), False, 'import cv2\n'), ((1674, 1699), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.uint8'], {}), '((3, 3), np.uint8)\n', (1681, 1699), True, 'import numpy as np\n'), ((1725, 1747), 'cv2.dilate', 'cv2.dilate', (['edge', 'kern'], {}), '(edge, kern)\n', (1735, 1747), False, 'import cv2\n'), ((1770, 1793), 'cv2.erode', 'cv2.erode', (['dilate', 'kern'], {}), '(dilate, kern)\n', (1779, 1793), False, 'import cv2\n'), ((1849, 1914), 'cv2.findContours', 'cv2.findContours', (['erode', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_NONE'], {}), '(erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n', (1865, 1914), False, 'import cv2\n'), ((2767, 2833), 'cv2.threshold', 'cv2.threshold', (['region', '(0)', '(255)', '(cv2.THRESH_BINARY + cv2.THRESH_OTSU)'], {}), '(region, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n', (2780, 2833), False, 'import cv2\n'), ((2884, 2909), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.uint8'], {}), '((3, 3), np.uint8)\n', (2891, 2909), True, 'import numpy as np\n'), ((2935, 2959), 'cv2.dilate', 'cv2.dilate', (['thresh', 'kern'], {}), '(thresh, kern)\n', (2945, 2959), False, 'import cv2\n'), ((3041, 3068), 'cv2.absdiff', 'cv2.absdiff', (['dilate', 'thresh'], {}), '(dilate, thresh)\n', (3052, 3068), False, 'import cv2\n'), ((3937, 3969), 'cv2.medianBlur', 'cv2.medianBlur', (['region', 'blurSize'], {}), '(region, blurSize)\n', (3951, 3969), False, 'import cv2\n'), ((4022, 4126), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['blur', '(255)', 'cv2.ADAPTIVE_THRESH_MEAN_C', 'cv2.THRESH_BINARY', 'lineSize', 'blurSize'], {}), '(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.\n THRESH_BINARY, lineSize, blurSize)\n', (4043, 4126), False, 'import cv2\n'), ((4695, 4750), 'cv2.bitwise_and', 'cv2.bitwise_and', (['cartoon', 'cartoon'], {'mask': '(255 - edgeImage)'}), '(cartoon, cartoon, mask=255 - edgeImage)\n', (4710, 4750), False, 'import cv2\n'), ((5388, 5414), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (5404, 5414), False, 'import os\n'), ((1954, 1990), 'numpy.zeros', 'np.zeros', (['region.shape[:2]', 'np.uint8'], {}), '(region.shape[:2], np.uint8)\n', (1962, 1990), True, 'import numpy as np\n'), ((4858, 4913), 'cv2.bitwise_and', 'cv2.bitwise_and', (['cartoon', 'cartoon'], {'mask': '(255 - edgeImage)'}), '(cartoon, cartoon, mask=255 - edgeImage)\n', (4873, 4913), False, 'import cv2\n'), ((6288, 6328), 'os.path.join', 'os.path.join', (['outputDir', 'style', 'filename'], {}), '(outputDir, style, filename)\n', (6300, 6328), False, 'import os\n'), ((6408, 6448), 'os.path.join', 'os.path.join', (['pngDir', '"""objects"""', '"""0.npy"""'], {}), "(pngDir, 'objects', '0.npy')\n", (6420, 6448), False, 'import os\n'), ((6714, 6731), 'cv2.imread', 'cv2.imread', (['cPath'], {}), '(cPath)\n', (6724, 6731), False, 'import cv2\n'), ((6945, 6975), 'os.path.join', 'os.path.join', (['pngDir', 'style', 'e'], {}), '(pngDir, style, e)\n', (6957, 6975), False, 'import os\n'), ((4968, 5005), 'numpy.zeros', 'np.zeros', (['cartoon.shape[:2]', 'np.uint8'], {}), '(cartoon.shape[:2], np.uint8)\n', (4976, 5005), True, 'import numpy as np\n'), ((5738, 5775), 'os.path.join', 'os.path.join', (['pngDir', 'style', 'f"""*.png"""'], {}), "(pngDir, style, f'*.png')\n", (5750, 5775), False, 'import os\n'), ((6050, 6091), 'os.path.join', 'os.path.join', (['pngDir', '"""objects"""', 'f"""*.npy"""'], {}), "(pngDir, 'objects', f'*.npy')\n", (6062, 6091), False, 'import os\n'), ((6756, 6789), 'numpy.load', 'np.load', (['oPath'], {'allow_pickle': '(True)'}), '(oPath, allow_pickle=True)\n', (6763, 6789), True, 'import numpy as np\n'), ((7001, 7024), 'os.path.exists', 'os.path.exists', (['edgeDir'], {}), '(edgeDir)\n', (7015, 7024), False, 'import os\n'), ((7048, 7068), 'os.makedirs', 'os.makedirs', (['edgeDir'], {}), '(edgeDir)\n', (7059, 7068), False, 'import os\n'), ((7146, 7181), 'os.path.join', 'os.path.join', (['edgeDir', 'edgeFilename'], {}), '(edgeDir, edgeFilename)\n', (7158, 7181), False, 'import os\n'), ((7393, 7435), 'os.path.join', 'os.path.join', (['pngDir', 'style', 'e', '"""enhanced"""'], {}), "(pngDir, style, e, 'enhanced')\n", (7405, 7435), False, 'import os\n'), ((7823, 7856), 'os.path.join', 'os.path.join', (['outputDir', 'style', 'e'], {}), '(outputDir, style, e)\n', (7835, 7856), False, 'import os\n'), ((7465, 7492), 'os.path.exists', 'os.path.exists', (['enhancedDir'], {}), '(enhancedDir)\n', (7479, 7492), False, 'import os\n'), ((7520, 7544), 'os.makedirs', 'os.makedirs', (['enhancedDir'], {}), '(enhancedDir)\n', (7531, 7544), False, 'import os\n'), ((7634, 7677), 'os.path.join', 'os.path.join', (['enhancedDir', 'enhancedFilename'], {}), '(enhancedDir, enhancedFilename)\n', (7646, 7677), False, 'import os\n'), ((7886, 7913), 'os.path.exists', 'os.path.exists', (['enhancedDir'], {}), '(enhancedDir)\n', (7900, 7913), False, 'import os\n'), ((7941, 7965), 'os.makedirs', 'os.makedirs', (['enhancedDir'], {}), '(enhancedDir)\n', (7952, 7965), False, 'import os\n'), ((8049, 8092), 'os.path.join', 'os.path.join', (['enhancedDir', 'enhancedFilename'], {}), '(enhancedDir, enhancedFilename)\n', (8061, 8092), False, 'import os\n')] |
import numpy as np
np.set_printoptions(edgeitems=30, linewidth=100000, formatter=dict(float=lambda x: "\t%5.3g" % x))
import pdb
class MatrixHandler:
def transform_H_to_G_indentity(self, H_orig, info_bits_position):
H = H_orig.copy()
n_rows = H.shape[0]
n_cols = H.shape[1]
K = n_cols - n_rows
assert K > 0, ("invalid dimension (n_cols=%d, n_rows=%d)" % (n_cols, n_rows))
# step 1: move to triangle way on the right side
for i in range(0, n_rows):
anchor = None
# anchor_row = 0
for j in range(i, n_rows):
if H[j, i + K] == 1:
# swap row with i
if anchor is None:
anchor = H[j, :].copy()
H[j, :] = H[i, :]
H[i, :] = anchor
# anchor_row = i
else:
# subtract current row
H[j, :] = anchor ^ H[j, :]
# step 2: make identity matrix on the right side
for j in range(n_rows-1, -1, -1): # start from last col and go left
for i in range(0, j): # for every row up
if H[i, j + K] == 1:
# eliminate using j-th row
H[i, :] = H[i, :] ^ H[j, :]
# step3: build G
G = np.zeros((K, n_cols), dtype=type(H[0, 0]))
temp = H[:, 0:n_rows]
G[0:K, 0:K] = np.diag(np.ones(K))
G[0:K, K:n_cols] = temp.transpose()
return G
def transform_H_to_G_decomp_LU(self, H, info_bits_position):
pass
| [
"numpy.ones"
] | [((1508, 1518), 'numpy.ones', 'np.ones', (['K'], {}), '(K)\n', (1515, 1518), True, 'import numpy as np\n')] |
import gym
import gym_panda
from gym_panda.wrapper_env.VAE import VAE
import torch
import tensorflow as tf
import numpy as np
import copy
import pickle
import gym_panda
from gym_panda.wrapper_env.wrapper import *
import pdb
import argparse
from itertools import count
import scipy.optimize
from models import *
from replay_memory import Memory
from running_state import ZFilter
from torch.autograd import Variable
from trpo import trpo_step
from utils import *
#from gen_dem import demo
import pickle
import random
import torch.nn as nn
import torch
from SAIL.utils.math import *
from torch.distributions import Normal
from SAIL.models.sac_models import weights_init_
from torch.distributions.categorical import Categorical
from SAIL.models.ppo_models import Value, Policy, DiscretePolicy
import pybullet as p
class imitationExpert(object):
"""Expert to across a block from one side to another side."""
def __init__(self):
self.kp = 0.3
self.kd = 0
self.ierror = np.zeros(3)
self.obj_len = 0.15
def get_next_states(self, state):
#print("State is:",state)
target_point = np.array([0.55, 0, 0.5])
target_point2 = np.array([0, 0, 2.0])
dpos = target_point - state
if state[2] >= 0.5:
#print("Switch to target 2!")
target_point = target_point2
dpos = target_point - state
next_pos = self.kp * dpos + self.kd * self.ierror
self.ierror += dpos
return next_pos
class ralExpert(object):
"""Expert to across a block from one side to another side."""
def __init__(self):
self.kp = 0.5
self.kd = 0
self.ierror = np.zeros(3)
self.obj_len = 0.15
def get_next_states(self, state):
#print("State is:",state)
target_point = np.array([0.1, 0, 0.1])
dpos = target_point - state
next_pos = self.kp * dpos + self.kd * self.ierror
self.ierror += dpos
return next_pos
class sailExpert(object):
"""Expert to across a block from one side to another side."""
def __init__(self):
self.kp = 1.0
self.kd = 0
self.ierror = np.zeros(3)
self.obj_len = 0.15
def get_next_states(self, state):
#print("State is:",state)
target_point = np.array([0.55, 0, 0.5])
target_point2 = np.array([0, 0, 2.0])
dpos = target_point - state
if state[2] >= 0.5:
#print("Switch to target 2!")
target_point = target_point2
dpos = target_point - state
next_pos = self.kp * dpos + self.kd * self.ierror
self.ierror += dpos
return next_pos
class ourExpert(object):
"""Expert to across a block from one side to another side."""
def __init__(self):
self.kp = 0.8
self.kd = 0
self.ierror = np.zeros(3)
self.obj_len = 0.15
def get_next_states(self, state):
#print("State is:",state)
target_point = np.array([0.42, 0, 0.4])
target_point2 = np.array([0.68, 0, 0.4])
target_point3 = np.array([1.0, 0, 0.0])
dpos = target_point - state
#self.kp = 1.3
#pdb.set_trace()
if state[0] >= 0.42:
#print("Switch to target 2!")
target_point = target_point2
dpos = target_point - state
if state[0] >= 0.68:
#print("Switch to target 3!")
target_point = target_point3
dpos = target_point - state
next_pos = self.kp * dpos + self.kd * self.ierror
#pdb.set_trace()
self.ierror += dpos
return next_pos
env = gym.make("realpanda-v0")
state = env.reset()
'''pdb.set_trace()
expert = ourExpert() #imitationExpert ralExpert sailExpert ourExpert
done = False
while not done:
pos = expert.get_next_states(state['ee_position'])
state, r, done, info = env.step(pos)
print(state['ee_position'])
print(r)
'''
for i in range(100):
p.addUserDebugLine([i*0.1,0,0.1], [(i+1)*0.1,0,0.1], [1, 0, 0], lineWidth=3., lifeTime=0)
| [
"numpy.zeros",
"pybullet.addUserDebugLine",
"gym.make",
"numpy.array"
] | [((3346, 3370), 'gym.make', 'gym.make', (['"""realpanda-v0"""'], {}), "('realpanda-v0')\n", (3354, 3370), False, 'import gym\n'), ((3674, 3778), 'pybullet.addUserDebugLine', 'p.addUserDebugLine', (['[i * 0.1, 0, 0.1]', '[(i + 1) * 0.1, 0, 0.1]', '[1, 0, 0]'], {'lineWidth': '(3.0)', 'lifeTime': '(0)'}), '([i * 0.1, 0, 0.1], [(i + 1) * 0.1, 0, 0.1], [1, 0, 0],\n lineWidth=3.0, lifeTime=0)\n', (3692, 3778), True, 'import pybullet as p\n'), ((982, 993), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (990, 993), True, 'import numpy as np\n'), ((1104, 1128), 'numpy.array', 'np.array', (['[0.55, 0, 0.5]'], {}), '([0.55, 0, 0.5])\n', (1112, 1128), True, 'import numpy as np\n'), ((1149, 1170), 'numpy.array', 'np.array', (['[0, 0, 2.0]'], {}), '([0, 0, 2.0])\n', (1157, 1170), True, 'import numpy as np\n'), ((1595, 1606), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1603, 1606), True, 'import numpy as np\n'), ((1717, 1740), 'numpy.array', 'np.array', (['[0.1, 0, 0.1]'], {}), '([0.1, 0, 0.1])\n', (1725, 1740), True, 'import numpy as np\n'), ((2037, 2048), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (2045, 2048), True, 'import numpy as np\n'), ((2159, 2183), 'numpy.array', 'np.array', (['[0.55, 0, 0.5]'], {}), '([0.55, 0, 0.5])\n', (2167, 2183), True, 'import numpy as np\n'), ((2204, 2225), 'numpy.array', 'np.array', (['[0, 0, 2.0]'], {}), '([0, 0, 2.0])\n', (2212, 2225), True, 'import numpy as np\n'), ((2650, 2661), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (2658, 2661), True, 'import numpy as np\n'), ((2772, 2796), 'numpy.array', 'np.array', (['[0.42, 0, 0.4]'], {}), '([0.42, 0, 0.4])\n', (2780, 2796), True, 'import numpy as np\n'), ((2817, 2841), 'numpy.array', 'np.array', (['[0.68, 0, 0.4]'], {}), '([0.68, 0, 0.4])\n', (2825, 2841), True, 'import numpy as np\n'), ((2862, 2885), 'numpy.array', 'np.array', (['[1.0, 0, 0.0]'], {}), '([1.0, 0, 0.0])\n', (2870, 2885), True, 'import numpy as np\n')] |
import typing as tp
import numpy as np
import core
# Units and constants
# Astronomical unit
AU = 1.495978707e11
# Gravitational constant
G = 6.67430e-11
# Time
YEAR_IN_D = 365.25
YEAR_IN_S = 31557600
# Scaling
M_SUN = 1.9885e30
M_EARTH = 5.97234e24
ORBIT_R_EARTH = 149598023e3
V_EARTH = 29.78e3
class Celestial:
def __init__(
self,
x: tp.Union[np.ndarray, float],
v: tp.Union[np.ndarray, float],
m: float,
radius: float,
color: tp.Tuple[int, int, int],
reference: "Celestial" = None,
period: float = None,
x_min: float = None,
x_max: float = None,
texture_low: str = None,
texture_high: str = None,
):
"""
A celestial object
:param x: position (m)
:param v: velocity (m/s)
:param m: mass (kg)
:param radius: (m)
:param color: RGB color tuple
:param reference: reference object for the position and velocity
:param period: orbital period (years)
"""
if isinstance(x, (int, float)):
self.x = np.array([x, 0, 0])
else:
self.x = x
if isinstance(v, (int, float)):
self.v = np.array([0, v, 0])
else:
self.v = v
if reference is not None:
self.x += reference.x
self.v += reference.v
self.reference = reference
self.m = m
self.radius = radius
self.color = color
self.texture_low = texture_low
self.texture_high = texture_high
class Simulation:
def __init__(self, celestials: tp.List[Celestial], dt: float, g: float = 1, fix_scale: bool = False):
self.celestials = celestials
self.g = g
self.dt = dt
self.fix_scale = fix_scale
self.x = np.asfortranarray(np.array([cel.x for cel in celestials]).T)
self.v = np.asfortranarray(np.array([cel.v for cel in celestials]).T)
self.m = np.array([cel.m for cel in celestials], order="F")
self.a = np.zeros_like(self.x)
# The simulation did not work with the astrophysical values,
# probably due to some floating-point errors, so this conversion was added as a fix.
if self.fix_scale:
self.dt /= YEAR_IN_S
self.x /= AU
self.v *= YEAR_IN_S / AU
self.m /= M_EARTH
# This is an ugly hack but I'm in a hurry and for some reason
# cannot figure out how to convert the gravitational
# constant properly. (It should be trivial.)
# self.g = 1.195e-4
self.g = M_EARTH / M_SUN * (V_EARTH * YEAR_IN_S / AU)**2
# print("Periods in years")
# print(2*np.pi*self.x[0, :] / self.v[1, :])
self.min_dist = 1e-4*np.min(np.abs(self.x))
self.x_hist = []
# print("SIMULATION LOAD")
# print("dt", self.dt)
# print("g", self.g)
# print("x")
# print(self.x.T)
# print("v")
# print(self.v.T)
# print("a")
# print(self.a.T)
# print("m")
# print(self.m.T)
# print("LOAD DEBUG PRINT END")
def run(self, steps: int, save_interval: int):
if steps % save_interval != 0:
raise ValueError("Steps must be a multiple of the save interval")
start_x = self.x.copy()
if self.fix_scale:
start_x *= AU
self.x_hist.append(start_x)
batches = steps // save_interval
self.print()
for i in range(batches):
print("Batch", i, "of", batches)
core.core.iterate(
self.x, self.v, self.a, self.m, self.dt,
n_steps=save_interval,
g=self.g,
min_dist=self.min_dist)
new_x = self.x.copy()
if self.fix_scale:
new_x *= AU
self.x_hist.append(new_x)
def print(self):
print("Start:")
print("x")
print(self.x_hist[0].T)
print("Now:")
print("x")
print(self.x.T)
print("v")
print(self.v.T)
print("a")
print(self.a.T)
| [
"numpy.abs",
"core.core.iterate",
"numpy.zeros_like",
"numpy.array"
] | [((2027, 2077), 'numpy.array', 'np.array', (['[cel.m for cel in celestials]'], {'order': '"""F"""'}), "([cel.m for cel in celestials], order='F')\n", (2035, 2077), True, 'import numpy as np\n'), ((2095, 2116), 'numpy.zeros_like', 'np.zeros_like', (['self.x'], {}), '(self.x)\n', (2108, 2116), True, 'import numpy as np\n'), ((1148, 1167), 'numpy.array', 'np.array', (['[x, 0, 0]'], {}), '([x, 0, 0])\n', (1156, 1167), True, 'import numpy as np\n'), ((1266, 1285), 'numpy.array', 'np.array', (['[0, v, 0]'], {}), '([0, v, 0])\n', (1274, 1285), True, 'import numpy as np\n'), ((3672, 3792), 'core.core.iterate', 'core.core.iterate', (['self.x', 'self.v', 'self.a', 'self.m', 'self.dt'], {'n_steps': 'save_interval', 'g': 'self.g', 'min_dist': 'self.min_dist'}), '(self.x, self.v, self.a, self.m, self.dt, n_steps=\n save_interval, g=self.g, min_dist=self.min_dist)\n', (3689, 3792), False, 'import core\n'), ((1889, 1928), 'numpy.array', 'np.array', (['[cel.x for cel in celestials]'], {}), '([cel.x for cel in celestials])\n', (1897, 1928), True, 'import numpy as np\n'), ((1967, 2006), 'numpy.array', 'np.array', (['[cel.v for cel in celestials]'], {}), '([cel.v for cel in celestials])\n', (1975, 2006), True, 'import numpy as np\n'), ((2865, 2879), 'numpy.abs', 'np.abs', (['self.x'], {}), '(self.x)\n', (2871, 2879), True, 'import numpy as np\n')] |
# ParseDM3File reads in a DM3 file and translates it into a dictionary
# this module treats that dictionary as an image-file and extracts the
# appropriate image data as numpy arrays.
# It also tries to create files from numpy arrays that DM can read.
#
# Some notes:
# Only complex64 and complex128 types are converted to structarrays,
# ie they're arrays of structs. Everything else, (including RGB) are
# standard arrays.
# There is a seperate DatatType and PixelDepth stored for images different
# from the tag file datatype. I think these are used more than the tag
# datratypes in describing the data.
# from .parse_dm3 import *
import copy
import datetime
import pprint
import numpy
import typing
from nion.data import Calibration
from nion.data import DataAndMetadata
from . import parse_dm3
def str_to_utf16_bytes(s):
return s.encode('utf-16')
def get_datetime_from_timestamp_str(timestamp_str):
if len(timestamp_str) in (23, 26):
return datetime.datetime.strptime(timestamp_str, "%Y-%m-%dT%H:%M:%S.%f")
elif len(timestamp_str) == 19:
return datetime.datetime.strptime(timestamp_str, "%Y-%m-%dT%H:%M:%S")
return None
structarray_to_np_map = {
('d', 'd'): numpy.complex128,
('f', 'f'): numpy.complex64}
np_to_structarray_map = {v: k for k, v in iter(structarray_to_np_map.items())}
# we want to amp any image type to a single np array type
# but a sinlge np array type could map to more than one dm type.
# For the moment, we won't be strict about, eg, discriminating
# int8 from bool, or even unit32 from RGB. In the future we could
# convert np bool type eg to DM bool and treat y,x,3 int8 images
# as RGB.
# note uint8 here returns the same data type as int8 0 could be that the
# only way they're differentiated is via this type, not the raw type
# in the tag file? And 8 is missing!
dm_image_dtypes = {
1: ("int16", numpy.int16),
2: ("float32", numpy.float32),
3: ("Complex64", numpy.complex64),
6: ("uint8", numpy.int8),
7: ("int32", numpy.int32),
9: ("int8", numpy.int8),
10: ("uint16", numpy.uint16),
11: ("uint32", numpy.uint32),
12: ("float64", numpy.float64),
13: ("Complex128", numpy.complex128),
14: ("Bool", numpy.int8),
23: ("RGB", numpy.int32)
}
def imagedatadict_to_ndarray(imdict):
"""
Converts the ImageData dictionary, imdict, to an nd image.
"""
arr = imdict['Data']
im = None
if isinstance(arr, parse_dm3.array.array):
im = numpy.asarray(arr, dtype=arr.typecode)
elif isinstance(arr, parse_dm3.structarray):
t = tuple(arr.typecodes)
im = numpy.frombuffer(
arr.raw_data,
dtype=structarray_to_np_map[t])
# print "Image has dmimagetype", imdict["DataType"], "numpy type is", im.dtype
assert dm_image_dtypes[imdict["DataType"]][1] == im.dtype
assert imdict['PixelDepth'] == im.dtype.itemsize
im = im.reshape(imdict['Dimensions'][::-1])
if imdict["DataType"] == 23: # RGB
im = im.view(numpy.uint8).reshape(im.shape + (-1, ))[..., :-1] # strip A
# NOTE: RGB -> BGR would be [:, :, ::-1]
return im
def platform_independent_char(dtype):
# windows and linux/macos treat dtype.char differently.
# on linux/macos where 'l' has size 8, ints of size 4 are reported as 'i'
# on windows where 'l' has size 4, ints of size 4 are reported as 'l'
# this function fixes that issue.
if numpy.dtype('int').itemsize == numpy.dtype('int32').itemsize and dtype.char == 'l': return 'i'
if numpy.dtype('uint').itemsize == numpy.dtype('uint32').itemsize and dtype.char == 'L': return 'I'
return dtype.char
def ndarray_to_imagedatadict(nparr):
"""
Convert the numpy array nparr into a suitable ImageList entry dictionary.
Returns a dictionary with the appropriate Data, DataType, PixelDepth
to be inserted into a dm3 tag dictionary and written to a file.
"""
ret = {}
dm_type = None
for k, v in iter(dm_image_dtypes.items()):
if v[1] == nparr.dtype.type:
dm_type = k
break
if dm_type is None and nparr.dtype == numpy.uint8 and nparr.shape[-1] in (3, 4):
ret["DataType"] = 23
ret["PixelDepth"] = 4
if nparr.shape[2] == 4:
rgb_view = nparr.view(numpy.int32).reshape(nparr.shape[:-1]) # squash the color into uint32
else:
assert nparr.shape[2] == 3
rgba_image = numpy.empty(nparr.shape[:-1] + (4,), numpy.uint8)
rgba_image[:,:,0:3] = nparr
rgba_image[:,:,3] = 255
rgb_view = rgba_image.view(numpy.int32).reshape(rgba_image.shape[:-1]) # squash the color into uint32
ret["Dimensions"] = list(rgb_view.shape[::-1])
ret["Data"] = parse_dm3.array.array(platform_independent_char(rgb_view.dtype), rgb_view.flatten())
else:
ret["DataType"] = dm_type
ret["PixelDepth"] = nparr.dtype.itemsize
ret["Dimensions"] = list(nparr.shape[::-1])
if nparr.dtype.type in np_to_structarray_map:
types = np_to_structarray_map[nparr.dtype.type]
ret["Data"] = parse_dm3.structarray(types)
ret["Data"].raw_data = bytes(numpy.array(nparr, copy=False).data)
else:
ret["Data"] = parse_dm3.array.array(platform_independent_char(nparr.dtype), numpy.array(nparr, copy=False).flatten())
return ret
def display_keys(tag: typing.Dict) -> None:
tag_copy = copy.deepcopy(tag)
for image_data in tag_copy.get("ImageList", list()):
image_data.get("ImageData", dict()).pop("Data", None)
tag_copy.pop("Page Behavior", None)
tag_copy.pop("PageSetup", None)
pprint.pprint(tag_copy)
def fix_strings(d):
if isinstance(d, dict):
r = dict()
for k, v in d.items():
if k != "Data":
r[k] = fix_strings(v)
else:
r[k] = v
return r
elif isinstance(d, list):
l = list()
for v in d:
l.append(fix_strings(v))
return l
elif isinstance(d, parse_dm3.array.array):
if d.typecode == 'H':
return d.tobytes().decode("utf-16")
else:
return d.tolist()
else:
return d
def load_image(file) -> DataAndMetadata.DataAndMetadata:
"""
Loads the image from the file-like object or string file.
If file is a string, the file is opened and then read.
Returns a numpy ndarray of our best guess for the most important image
in the file.
"""
if isinstance(file, str) or isinstance(file, str):
with open(file, "rb") as f:
return load_image(f)
dmtag = parse_dm3.parse_dm_header(file)
dmtag = fix_strings(dmtag)
# display_keys(dmtag)
img_index = -1
image_tags = dmtag['ImageList'][img_index]
data = imagedatadict_to_ndarray(image_tags['ImageData'])
calibrations = []
calibration_tags = image_tags['ImageData'].get('Calibrations', dict())
for dimension in calibration_tags.get('Dimension', list()):
origin, scale, units = dimension.get('Origin', 0.0), dimension.get('Scale', 1.0), dimension.get('Units', str())
calibrations.append((-origin * scale, scale, units))
calibrations = tuple(reversed(calibrations))
if len(data.shape) == 3 and data.dtype != numpy.uint8:
if image_tags['ImageTags'].get('Meta Data', dict()).get("Format", str()).lower() in ("spectrum", "spectrum image"):
if data.shape[1] == 1:
data = numpy.squeeze(data, 1)
data = numpy.moveaxis(data, 0, 1)
data_descriptor = DataAndMetadata.DataDescriptor(False, 1, 1)
calibrations = (calibrations[2], calibrations[0])
else:
data = numpy.moveaxis(data, 0, 2)
data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 1)
calibrations = tuple(calibrations[1:]) + (calibrations[0],)
else:
data_descriptor = DataAndMetadata.DataDescriptor(False, 1, 2)
elif len(data.shape) == 4 and data.dtype != numpy.uint8:
# data = numpy.moveaxis(data, 0, 2)
data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 2)
elif data.dtype == numpy.uint8:
data_descriptor = DataAndMetadata.DataDescriptor(False, 0, len(data.shape[:-1]))
else:
data_descriptor = DataAndMetadata.DataDescriptor(False, 0, len(data.shape))
brightness = calibration_tags.get('Brightness', dict())
origin, scale, units = brightness.get('Origin', 0.0), brightness.get('Scale', 1.0), brightness.get('Units', str())
intensity = -origin * scale, scale, units
timestamp = None
timezone = None
timezone_offset = None
title = image_tags.get('Name')
properties = dict()
if 'ImageTags' in image_tags:
voltage = image_tags['ImageTags'].get('ImageScanned', dict()).get('EHT', dict())
if voltage:
properties.setdefault("hardware_source", dict())["autostem"] = { "high_tension_v": float(voltage) }
dm_metadata_signal = image_tags['ImageTags'].get('Meta Data', dict()).get('Signal')
if dm_metadata_signal and dm_metadata_signal.lower() == "eels":
properties.setdefault("hardware_source", dict())["signal_type"] = dm_metadata_signal
if image_tags['ImageTags'].get('Meta Data', dict()).get("Format", str()).lower() in ("spectrum", "spectrum image"):
data_descriptor.collection_dimension_count += data_descriptor.datum_dimension_count - 1
data_descriptor.datum_dimension_count = 1
if image_tags['ImageTags'].get('Meta Data', dict()).get("IsSequence", False) and data_descriptor.collection_dimension_count > 0:
data_descriptor.is_sequence = True
data_descriptor.collection_dimension_count -= 1
timestamp_str = image_tags['ImageTags'].get("Timestamp")
if timestamp_str:
timestamp = get_datetime_from_timestamp_str(timestamp_str)
timezone = image_tags['ImageTags'].get("Timezone")
timezone_offset = image_tags['ImageTags'].get("TimezoneOffset")
# to avoid having duplicate copies in Swift, get rid of these tags
image_tags['ImageTags'].pop("Timestamp", None)
image_tags['ImageTags'].pop("Timezone", None)
image_tags['ImageTags'].pop("TimezoneOffset", None)
# put the image tags into properties
properties.update(image_tags['ImageTags'])
dimensional_calibrations = [Calibration.Calibration(c[0], c[1], c[2]) for c in calibrations]
while len(dimensional_calibrations) < data_descriptor.expected_dimension_count:
dimensional_calibrations.append(Calibration.Calibration())
intensity_calibration = Calibration.Calibration(intensity[0], intensity[1], intensity[2])
return DataAndMetadata.new_data_and_metadata(data,
data_descriptor=data_descriptor,
dimensional_calibrations=dimensional_calibrations,
intensity_calibration=intensity_calibration,
metadata=properties,
timestamp=timestamp,
timezone=timezone,
timezone_offset=timezone_offset)
def save_image(xdata: DataAndMetadata.DataAndMetadata, file):
"""
Saves the nparray data to the file-like object (or string) file.
"""
# we need to create a basic DM tree suitable for an image
# we'll try the minimum: just an data list
# doesn't work. Do we need a ImageSourceList too?
# and a DocumentObjectList?
data = xdata.data
data_descriptor = xdata.data_descriptor
dimensional_calibrations = xdata.dimensional_calibrations
intensity_calibration = xdata.intensity_calibration
metadata = xdata.metadata
modified = xdata.timestamp
timezone = xdata.timezone
timezone_offset = xdata.timezone_offset
needs_slice = False
is_sequence = False
if len(data.shape) == 3 and data.dtype != numpy.uint8 and data_descriptor.datum_dimension_count == 1:
data = numpy.moveaxis(data, 2, 0)
dimensional_calibrations = (dimensional_calibrations[2],) + tuple(dimensional_calibrations[0:2])
if len(data.shape) == 2 and data.dtype != numpy.uint8 and data_descriptor.datum_dimension_count == 1:
is_sequence = data_descriptor.is_sequence
data = numpy.moveaxis(data, 1, 0)
data = numpy.expand_dims(data, axis=1)
dimensional_calibrations = (dimensional_calibrations[1], Calibration.Calibration(), dimensional_calibrations[0])
data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 1)
needs_slice = True
data_dict = ndarray_to_imagedatadict(data)
ret = {}
ret["ImageList"] = [{"ImageData": data_dict}]
if dimensional_calibrations and len(dimensional_calibrations) == len(data.shape):
dimension_list = data_dict.setdefault("Calibrations", dict()).setdefault("Dimension", list())
for dimensional_calibration in reversed(dimensional_calibrations):
dimension = dict()
if dimensional_calibration.scale != 0.0:
origin = -dimensional_calibration.offset / dimensional_calibration.scale
else:
origin = 0.0
dimension['Origin'] = origin
dimension['Scale'] = dimensional_calibration.scale
dimension['Units'] = dimensional_calibration.units
dimension_list.append(dimension)
if intensity_calibration:
if intensity_calibration.scale != 0.0:
origin = -intensity_calibration.offset / intensity_calibration.scale
else:
origin = 0.0
brightness = data_dict.setdefault("Calibrations", dict()).setdefault("Brightness", dict())
brightness['Origin'] = origin
brightness['Scale'] = intensity_calibration.scale
brightness['Units'] = intensity_calibration.units
if modified:
timezone_str = None
if timezone_str is None and timezone:
try:
import pytz
tz = pytz.timezone(timezone)
timezone_str = tz.tzname(modified)
except:
pass
if timezone_str is None and timezone_offset:
timezone_str = timezone_offset
timezone_str = " " + timezone_str if timezone_str is not None else ""
date_str = modified.strftime("%x")
time_str = modified.strftime("%X") + timezone_str
ret["DataBar"] = {"Acquisition Date": date_str, "Acquisition Time": time_str}
# I think ImageSource list creates a mapping between ImageSourceIds and Images
ret["ImageSourceList"] = [{"ClassName": "ImageSource:Simple", "Id": [0], "ImageRef": 0}]
# I think this lists the sources for the DocumentObjectlist. The source number is not
# the indxe in the imagelist but is either the index in the ImageSourceList or the Id
# from that list. We also need to set the annotation type to identify it as an data
ret["DocumentObjectList"] = [{"ImageSource": 0, "AnnotationType": 20}]
# finally some display options
ret["Image Behavior"] = {"ViewDisplayID": 8}
dm_metadata = copy.deepcopy(metadata)
if metadata.get("hardware_source", dict()).get("signal_type", "").lower() == "eels":
if len(data.shape) == 1 or (len(data.shape) == 2 and data.shape[0] == 1):
dm_metadata.setdefault("Meta Data", dict())["Format"] = "Spectrum"
dm_metadata.setdefault("Meta Data", dict())["Signal"] = "EELS"
elif data_descriptor.collection_dimension_count == 2 and data_descriptor.datum_dimension_count == 1:
dm_metadata.setdefault("Meta Data", dict())["Format"] = "Spectrum image"
dm_metadata.setdefault("Meta Data", dict())["Signal"] = "EELS"
elif data_descriptor.datum_dimension_count == 1:
dm_metadata.setdefault("Meta Data", dict())["Format"] = "Spectrum"
if (1 if data_descriptor.is_sequence else 0) + data_descriptor.collection_dimension_count == 1 or needs_slice:
if data_descriptor.is_sequence or is_sequence:
dm_metadata.setdefault("Meta Data", dict())["IsSequence"] = True
ret["ImageSourceList"] = [{"ClassName": "ImageSource:Summed", "Do Sum": True, "Id": [0], "ImageRef": 0, "LayerEnd": 0, "LayerStart": 0, "Summed Dimension": len(data.shape) - 1}]
if needs_slice:
ret["DocumentObjectList"][0]["AnnotationGroupList"] = [{"AnnotationType": 23, "Name": "SICursor", "Rectangle": (0, 0, 1, 1)}]
ret["DocumentObjectList"][0]["ImageDisplayType"] = 1 # display as an image
if modified:
dm_metadata["Timestamp"] = modified.isoformat()
if timezone:
dm_metadata["Timezone"] = timezone
if timezone_offset:
dm_metadata["TimezoneOffset"] = timezone_offset
ret["ImageList"][0]["ImageTags"] = dm_metadata
ret["InImageMode"] = True
parse_dm3.parse_dm_header(file, ret)
# logging.debug(image_tags['ImageData']['Calibrations'])
# {u'DisplayCalibratedUnits': True, u'Dimension': [{u'Origin': -0.0, u'Units': u'nm', u'Scale': 0.01171875}, {u'Origin': -0.0, u'Units': u'nm', u'Scale': 0.01171875}, {u'Origin': 0.0, u'Units': u'', u'Scale': 0.01149425096809864}], u'Brightness': {u'Origin': 0.0, u'Units': u'', u'Scale': 1.0}}
| [
"copy.deepcopy",
"numpy.moveaxis",
"numpy.frombuffer",
"numpy.asarray",
"numpy.empty",
"nion.data.DataAndMetadata.new_data_and_metadata",
"numpy.expand_dims",
"numpy.dtype",
"datetime.datetime.strptime",
"numpy.array",
"pprint.pprint",
"nion.data.Calibration.Calibration",
"nion.data.DataAndM... | [((5463, 5481), 'copy.deepcopy', 'copy.deepcopy', (['tag'], {}), '(tag)\n', (5476, 5481), False, 'import copy\n'), ((5681, 5704), 'pprint.pprint', 'pprint.pprint', (['tag_copy'], {}), '(tag_copy)\n', (5694, 5704), False, 'import pprint\n'), ((10741, 10806), 'nion.data.Calibration.Calibration', 'Calibration.Calibration', (['intensity[0]', 'intensity[1]', 'intensity[2]'], {}), '(intensity[0], intensity[1], intensity[2])\n', (10764, 10806), False, 'from nion.data import Calibration\n'), ((10818, 11096), 'nion.data.DataAndMetadata.new_data_and_metadata', 'DataAndMetadata.new_data_and_metadata', (['data'], {'data_descriptor': 'data_descriptor', 'dimensional_calibrations': 'dimensional_calibrations', 'intensity_calibration': 'intensity_calibration', 'metadata': 'properties', 'timestamp': 'timestamp', 'timezone': 'timezone', 'timezone_offset': 'timezone_offset'}), '(data, data_descriptor=data_descriptor,\n dimensional_calibrations=dimensional_calibrations,\n intensity_calibration=intensity_calibration, metadata=properties,\n timestamp=timestamp, timezone=timezone, timezone_offset=timezone_offset)\n', (10855, 11096), False, 'from nion.data import DataAndMetadata\n'), ((15367, 15390), 'copy.deepcopy', 'copy.deepcopy', (['metadata'], {}), '(metadata)\n', (15380, 15390), False, 'import copy\n'), ((969, 1034), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['timestamp_str', '"""%Y-%m-%dT%H:%M:%S.%f"""'], {}), "(timestamp_str, '%Y-%m-%dT%H:%M:%S.%f')\n", (995, 1034), False, 'import datetime\n'), ((2486, 2524), 'numpy.asarray', 'numpy.asarray', (['arr'], {'dtype': 'arr.typecode'}), '(arr, dtype=arr.typecode)\n', (2499, 2524), False, 'import numpy\n'), ((10497, 10538), 'nion.data.Calibration.Calibration', 'Calibration.Calibration', (['c[0]', 'c[1]', 'c[2]'], {}), '(c[0], c[1], c[2])\n', (10520, 10538), False, 'from nion.data import Calibration\n'), ((12262, 12288), 'numpy.moveaxis', 'numpy.moveaxis', (['data', '(2)', '(0)'], {}), '(data, 2, 0)\n', (12276, 12288), False, 'import numpy\n'), ((12565, 12591), 'numpy.moveaxis', 'numpy.moveaxis', (['data', '(1)', '(0)'], {}), '(data, 1, 0)\n', (12579, 12591), False, 'import numpy\n'), ((12607, 12638), 'numpy.expand_dims', 'numpy.expand_dims', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (12624, 12638), False, 'import numpy\n'), ((12786, 12829), 'nion.data.DataAndMetadata.DataDescriptor', 'DataAndMetadata.DataDescriptor', (['(False)', '(2)', '(1)'], {}), '(False, 2, 1)\n', (12816, 12829), False, 'from nion.data import DataAndMetadata\n'), ((1085, 1147), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['timestamp_str', '"""%Y-%m-%dT%H:%M:%S"""'], {}), "(timestamp_str, '%Y-%m-%dT%H:%M:%S')\n", (1111, 1147), False, 'import datetime\n'), ((2620, 2682), 'numpy.frombuffer', 'numpy.frombuffer', (['arr.raw_data'], {'dtype': 'structarray_to_np_map[t]'}), '(arr.raw_data, dtype=structarray_to_np_map[t])\n', (2636, 2682), False, 'import numpy\n'), ((4448, 4497), 'numpy.empty', 'numpy.empty', (['(nparr.shape[:-1] + (4,))', 'numpy.uint8'], {}), '(nparr.shape[:-1] + (4,), numpy.uint8)\n', (4459, 4497), False, 'import numpy\n'), ((8004, 8047), 'nion.data.DataAndMetadata.DataDescriptor', 'DataAndMetadata.DataDescriptor', (['(False)', '(1)', '(2)'], {}), '(False, 1, 2)\n', (8034, 8047), False, 'from nion.data import DataAndMetadata\n'), ((8179, 8222), 'nion.data.DataAndMetadata.DataDescriptor', 'DataAndMetadata.DataDescriptor', (['(False)', '(2)', '(2)'], {}), '(False, 2, 2)\n', (8209, 8222), False, 'from nion.data import DataAndMetadata\n'), ((10686, 10711), 'nion.data.Calibration.Calibration', 'Calibration.Calibration', ([], {}), '()\n', (10709, 10711), False, 'from nion.data import Calibration\n'), ((12704, 12729), 'nion.data.Calibration.Calibration', 'Calibration.Calibration', ([], {}), '()\n', (12727, 12729), False, 'from nion.data import Calibration\n'), ((3436, 3454), 'numpy.dtype', 'numpy.dtype', (['"""int"""'], {}), "('int')\n", (3447, 3454), False, 'import numpy\n'), ((3467, 3487), 'numpy.dtype', 'numpy.dtype', (['"""int32"""'], {}), "('int32')\n", (3478, 3487), False, 'import numpy\n'), ((3538, 3557), 'numpy.dtype', 'numpy.dtype', (['"""uint"""'], {}), "('uint')\n", (3549, 3557), False, 'import numpy\n'), ((3570, 3591), 'numpy.dtype', 'numpy.dtype', (['"""uint32"""'], {}), "('uint32')\n", (3581, 3591), False, 'import numpy\n'), ((7521, 7543), 'numpy.squeeze', 'numpy.squeeze', (['data', '(1)'], {}), '(data, 1)\n', (7534, 7543), False, 'import numpy\n'), ((7567, 7593), 'numpy.moveaxis', 'numpy.moveaxis', (['data', '(0)', '(1)'], {}), '(data, 0, 1)\n', (7581, 7593), False, 'import numpy\n'), ((7628, 7671), 'nion.data.DataAndMetadata.DataDescriptor', 'DataAndMetadata.DataDescriptor', (['(False)', '(1)', '(1)'], {}), '(False, 1, 1)\n', (7658, 7671), False, 'from nion.data import DataAndMetadata\n'), ((7779, 7805), 'numpy.moveaxis', 'numpy.moveaxis', (['data', '(0)', '(2)'], {}), '(data, 0, 2)\n', (7793, 7805), False, 'import numpy\n'), ((7840, 7883), 'nion.data.DataAndMetadata.DataDescriptor', 'DataAndMetadata.DataDescriptor', (['(False)', '(2)', '(1)'], {}), '(False, 2, 1)\n', (7870, 7883), False, 'from nion.data import DataAndMetadata\n'), ((14269, 14292), 'pytz.timezone', 'pytz.timezone', (['timezone'], {}), '(timezone)\n', (14282, 14292), False, 'import pytz\n'), ((5206, 5236), 'numpy.array', 'numpy.array', (['nparr'], {'copy': '(False)'}), '(nparr, copy=False)\n', (5217, 5236), False, 'import numpy\n'), ((5345, 5375), 'numpy.array', 'numpy.array', (['nparr'], {'copy': '(False)'}), '(nparr, copy=False)\n', (5356, 5375), False, 'import numpy\n')] |
from collections import Counter
import numpy as np
class FeatureDictionary:
"""
A simple feature dictionary that can convert features (ids) to
their textual representation and vice-versa.
"""
def __init__(self, add_unk=True):
self.next_id = 0
self.token_to_id = {}
self.id_to_token = {}
if add_unk:
self.add_or_get_id(self.get_unk())
def add_or_get_id(self, token: str) -> int:
if token in self.token_to_id:
return self.token_to_id[token]
this_id = self.next_id
self.next_id += 1
self.token_to_id[token] = this_id
self.id_to_token[this_id] = token
return this_id
def is_unk(self, token: str) -> bool:
return token not in self.token_to_id
def get_id_or_unk(self, token: str) -> int:
if token in self.token_to_id:
return self.token_to_id[token]
else:
return self.token_to_id[self.get_unk()]
def get_id_or_none(self, token: str):
if token in self.token_to_id:
return self.token_to_id[token]
else:
return None
def get_name_for_id(self, token_id: int) -> str:
return self.id_to_token[token_id]
def __len__(self) -> int:
return len(self.token_to_id)
def __str__(self):
return str(self.token_to_id)
def get_all_names(self) -> frozenset:
return frozenset(self.token_to_id.keys())
@staticmethod
def get_unk() -> str:
return "%UNK%"
@staticmethod
def get_feature_dictionary_for(tokens, count_threshold=5):
token_counter = Counter(tokens)
feature_dict = FeatureDictionary(add_unk=count_threshold > 0)
for token, count in token_counter.items():
if count >= count_threshold:
feature_dict.add_or_get_id(token)
return feature_dict
def get_empirical_distribution(element_dict: FeatureDictionary, elements, dirichlet_alpha=10.):
"""
Retrieve empirical distribution of a seqence of elements
:param element_dict: a dictionary that can convert the elements to their respective ids.
:param elements: an iterable of all the elements
:return:
"""
targets = np.array([element_dict.get_id_or_unk(t) for t in elements])
empirical_distribution = np.bincount(targets, minlength=len(element_dict)).astype(float)
empirical_distribution += dirichlet_alpha / len(empirical_distribution)
return empirical_distribution / (np.sum(empirical_distribution) + dirichlet_alpha)
| [
"collections.Counter",
"numpy.sum"
] | [((1636, 1651), 'collections.Counter', 'Counter', (['tokens'], {}), '(tokens)\n', (1643, 1651), False, 'from collections import Counter\n'), ((2506, 2536), 'numpy.sum', 'np.sum', (['empirical_distribution'], {}), '(empirical_distribution)\n', (2512, 2536), True, 'import numpy as np\n')] |
'''
This sample creates a sample signal and uses this package to create a periodogram power spectral density plot.
This example requires certain Python packages. To check for and install if needed,
open the Script Window (Shift+Alt+3), type the following and press Enter:
pip -chk scipy numpy
'''
import numpy as np
from scipy import signal
import originpro as op
# periodogram power spectral density
fs = 10e3
N = 1e5
amp = 2*np.sqrt(2)
freq = 1234.0
noise_power = 0.001 * fs / 2
time = np.arange(N) / fs
x = amp*np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
f, Pxx_den = signal.periodogram(x, fs)
# put the data into worksheet
wks = op.new_sheet(type='w', lname='Periodogram Power Spectral')
wks.from_list(0, f, lname='Freq', units='Hz')
wks.from_list(1, Pxx_den, lname='PSD', units='V\+(2)/Hz')
graph = op.new_graph(template='line')
#log scale
graph[0].yscale = 2
graph[0].set_xlim(begin=0, end=5000, step=1000)
#step=2 in log
graph[0].set_ylim(1e-7, 1e2, 2)
graph[0].label('legend').remove()
#page.aa in LT, anti-alias -> On
graph.set_int('aa', 1)
# plot the data into the graph
plot = graph[0].add_plot(wks, coly=1, colx=0, type='line')
plot.color = '#167BB2' | [
"originpro.new_sheet",
"originpro.new_graph",
"numpy.sin",
"numpy.arange",
"scipy.signal.periodogram",
"numpy.sqrt"
] | [((626, 651), 'scipy.signal.periodogram', 'signal.periodogram', (['x', 'fs'], {}), '(x, fs)\n', (644, 651), False, 'from scipy import signal\n'), ((689, 747), 'originpro.new_sheet', 'op.new_sheet', ([], {'type': '"""w"""', 'lname': '"""Periodogram Power Spectral"""'}), "(type='w', lname='Periodogram Power Spectral')\n", (701, 747), True, 'import originpro as op\n'), ((861, 890), 'originpro.new_graph', 'op.new_graph', ([], {'template': '"""line"""'}), "(template='line')\n", (873, 890), True, 'import originpro as op\n'), ((433, 443), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (440, 443), True, 'import numpy as np\n'), ((494, 506), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (503, 506), True, 'import numpy as np\n'), ((520, 551), 'numpy.sin', 'np.sin', (['(2 * np.pi * freq * time)'], {}), '(2 * np.pi * freq * time)\n', (526, 551), True, 'import numpy as np\n'), ((574, 594), 'numpy.sqrt', 'np.sqrt', (['noise_power'], {}), '(noise_power)\n', (581, 594), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# @Author: Ruban
# @License: Apache Licence
# @File: inference_util.py
import cv2
import math
import numpy as np
def getDetBoxes_core(text_map, link_map, text_threshold, link_threshold, low_text):
# prepare data
link_map = link_map.copy()
text_map = text_map.copy()
img_h, img_w = text_map.shape
""" labeling method """
ret, text_score = cv2.threshold(text_map, low_text, 1, 0)
ret, link_score = cv2.threshold(link_map, link_threshold, 1, 0)
text_score_comb = np.clip(text_score + link_score, 0, 1)
label_n, labels, stats, centroids = cv2.connectedComponentsWithStats(text_score_comb.astype(np.uint8),
connectivity=4)
det = []
mapper = []
for k in range(1, label_n):
# size filtering
size = stats[k, cv2.CC_STAT_AREA]
if size < 10:
continue
# thresholding
if np.max(text_map[labels == k]) < text_threshold:
continue
x, y = stats[k, cv2.CC_STAT_LEFT], stats[k, cv2.CC_STAT_TOP]
w, h = stats[k, cv2.CC_STAT_WIDTH], stats[k, cv2.CC_STAT_HEIGHT]
niter = int(math.sqrt(size * min(w, h) / (w * h)) * 2)
sx, ex, sy, ey = x - niter, x + w + niter + 1, y - niter, y + h + niter + 1
# boundary check
if sx < 0:
sx = 0
if sy < 0:
sy = 0
if ex >= img_w:
ex = img_w
if ey >= img_h:
ey = img_h
tmp_text_map = text_map[sy:ey, sx:ex]
tmp_labels = labels[sy:ey, sx:ex]
tmp_link_score = link_score[sy:ey, sx:ex]
tmp_text_score = text_score[sy:ey, sx:ex]
# make segmentation map
segmap = np.zeros(tmp_text_map.shape, dtype=np.uint8)
segmap[tmp_labels == k] = 255
segmap[np.logical_and(tmp_link_score == 1, tmp_text_score == 0)] = 0 # remove link area
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1 + niter, 1 + niter))
segmap = cv2.dilate(segmap, kernel)
# make box
np_contours = np.roll(np.array(np.where(segmap != 0)), 1, axis=0).transpose().reshape(-1, 2)
rectangle = cv2.minAreaRect(np_contours)
box = cv2.boxPoints(rectangle)
# align diamond-shape
w, h = np.linalg.norm(box[0] - box[1]), np.linalg.norm(box[1] - box[2])
box_ratio = max(w, h) / (min(w, h) + 1e-5)
if abs(1 - box_ratio) <= 0.1:
l, r = min(np_contours[:, 0]), max(np_contours[:, 0])
t, b = min(np_contours[:, 1]), max(np_contours[:, 1])
box = np.array([[l, t], [r, t], [r, b], [l, b]], dtype=np.float32)
# make clock-wise order
start_idx = box.sum(axis=1).argmin()
box = np.roll(box, 4 - start_idx, 0)
box = np.array(box)
box += (sx, sy)
det.append(box)
mapper.append(k)
return det, labels, mapper
def getDetBoxes(text_map, link_map, text_threshold, link_threshold, low_text):
boxes, labels, mapper = getDetBoxes_core(text_map, link_map, text_threshold, link_threshold, low_text)
return boxes
def adjustResultCoordinates(polys, ratio_w, ratio_h, ratio_net=2):
if len(polys) > 0:
polys = np.array(polys)
polys *= (ratio_w * ratio_net, ratio_h * ratio_net)
# for k in range(len(polys)):
# if polys[k] is not None:
# polys[k] *= (ratio_w * ratio_net, ratio_h * ratio_net)
return polys
| [
"numpy.logical_and",
"cv2.dilate",
"numpy.roll",
"cv2.getStructuringElement",
"cv2.threshold",
"numpy.zeros",
"numpy.clip",
"cv2.boxPoints",
"numpy.max",
"numpy.array",
"numpy.linalg.norm",
"numpy.where",
"cv2.minAreaRect"
] | [((407, 446), 'cv2.threshold', 'cv2.threshold', (['text_map', 'low_text', '(1)', '(0)'], {}), '(text_map, low_text, 1, 0)\n', (420, 446), False, 'import cv2\n'), ((470, 515), 'cv2.threshold', 'cv2.threshold', (['link_map', 'link_threshold', '(1)', '(0)'], {}), '(link_map, link_threshold, 1, 0)\n', (483, 515), False, 'import cv2\n'), ((541, 579), 'numpy.clip', 'np.clip', (['(text_score + link_score)', '(0)', '(1)'], {}), '(text_score + link_score, 0, 1)\n', (548, 579), True, 'import numpy as np\n'), ((1814, 1858), 'numpy.zeros', 'np.zeros', (['tmp_text_map.shape'], {'dtype': 'np.uint8'}), '(tmp_text_map.shape, dtype=np.uint8)\n', (1822, 1858), True, 'import numpy as np\n'), ((2016, 2081), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(1 + niter, 1 + niter)'], {}), '(cv2.MORPH_RECT, (1 + niter, 1 + niter))\n', (2041, 2081), False, 'import cv2\n'), ((2100, 2126), 'cv2.dilate', 'cv2.dilate', (['segmap', 'kernel'], {}), '(segmap, kernel)\n', (2110, 2126), False, 'import cv2\n'), ((2272, 2300), 'cv2.minAreaRect', 'cv2.minAreaRect', (['np_contours'], {}), '(np_contours)\n', (2287, 2300), False, 'import cv2\n'), ((2316, 2340), 'cv2.boxPoints', 'cv2.boxPoints', (['rectangle'], {}), '(rectangle)\n', (2329, 2340), False, 'import cv2\n'), ((2856, 2886), 'numpy.roll', 'np.roll', (['box', '(4 - start_idx)', '(0)'], {}), '(box, 4 - start_idx, 0)\n', (2863, 2886), True, 'import numpy as np\n'), ((2902, 2915), 'numpy.array', 'np.array', (['box'], {}), '(box)\n', (2910, 2915), True, 'import numpy as np\n'), ((3353, 3368), 'numpy.array', 'np.array', (['polys'], {}), '(polys)\n', (3361, 3368), True, 'import numpy as np\n'), ((996, 1025), 'numpy.max', 'np.max', (['text_map[labels == k]'], {}), '(text_map[labels == k])\n', (1002, 1025), True, 'import numpy as np\n'), ((1914, 1970), 'numpy.logical_and', 'np.logical_and', (['(tmp_link_score == 1)', '(tmp_text_score == 0)'], {}), '(tmp_link_score == 1, tmp_text_score == 0)\n', (1928, 1970), True, 'import numpy as np\n'), ((2390, 2421), 'numpy.linalg.norm', 'np.linalg.norm', (['(box[0] - box[1])'], {}), '(box[0] - box[1])\n', (2404, 2421), True, 'import numpy as np\n'), ((2423, 2454), 'numpy.linalg.norm', 'np.linalg.norm', (['(box[1] - box[2])'], {}), '(box[1] - box[2])\n', (2437, 2454), True, 'import numpy as np\n'), ((2699, 2759), 'numpy.array', 'np.array', (['[[l, t], [r, t], [r, b], [l, b]]'], {'dtype': 'np.float32'}), '([[l, t], [r, t], [r, b], [l, b]], dtype=np.float32)\n', (2707, 2759), True, 'import numpy as np\n'), ((2189, 2210), 'numpy.where', 'np.where', (['(segmap != 0)'], {}), '(segmap != 0)\n', (2197, 2210), True, 'import numpy as np\n')] |
from itertools import product
import numpy as np
import torch
from alphazero.game import Game
class TicTacToe(Game):
"""Squares are numbered 0-8 from top-left corner to bottom right corner."""
NUM_ACTIONS = 9
WINNING_POSITIONS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
@property
def terminal(self):
if len(self.history) < 5:
return False
elif len(self.history) == 9:
return True
elif self.winner is not None:
return True
return False
@property
def winner(self):
if len(self.history) < 5:
return None
for player, pos in product((0, 1), TicTacToe.WINNING_POSITIONS):
if len(set(self.history[player::2]) & set(pos)) == 3:
return player
if len(self.history) == 9:
return -1
return None
@property
def valid_actions(self):
return sorted(set(range(9)) - set(self.history))
def render(self, turn=None):
if turn is None:
history = self.history
else:
assert turn <= len(self.history)
assert turn >= 0
history = self.history[:turn]
img = np.zeros((2, 9), dtype=np.float32)
next_player_actions = history[self.next_player::2]
prev_player_actions = history[self.prev_player::2]
img[0, next_player_actions] = 1
img[1, prev_player_actions] = 1
return img.reshape(2, 3, 3)
def __str__(self):
h = self.history
tui = [' ' if i not in h else 'X' if h.index(i) % 2 == 0 else 'O' for i in range(9)]
s = ' ' + ' | '.join(tui[0:3]) + '\n'
s += '-' * 11 + '\n'
s += ' ' + ' | '.join(tui[3:6]) + '\n'
s += '-' * 11 + '\n'
s += ' ' + ' | '.join(tui[6:9])
return s
def solve(self):
BOOK = {
(): (0, [ 0, 0, 0, 0, 0, 0, 0, 0, 0]),
(0,): (0, [ -2, -2, -2, 0, -2, -2, -2, -2]),
(1,): (0, [ 0, 0, -2, 0, -2, -2, 0, -2]),
(2,): (0, [-2, -2, -2, 0, -2, -2, -2, -2]),
(3,): (0, [ 0, -2, -2, 0, 0, 0, -2, -2]),
(4,): (0, [ 0, -2, 0, -2, -2, 0, -2, 0]),
(5,): (0, [-2, -2, 0, 0, 0, -2, -2, 0]),
(6,): (0, [-2, -2, -2, -2, 0, -2, -2, -2]),
(7,): (0, [-2, 0, -2, -2, 0, -2, 0, 0]),
(8,): (0, [-2, -2, -2, -2, 0, -2, -2, -2 ]),
}
def minimax(game, root_depth=None, book={}):
if root_depth is None:
root_depth = len(game)
if tuple(game.history) in book:
return book[tuple(game.history)]
root_player = root_depth % 2
cur_player = len(game) % 2
if game.terminal:
nmoves = 5 - len(game) // 2
outcome = game.terminal_value(root_player)
return nmoves * outcome, []
scores = []
for a in game.valid_actions:
sub_game = game.clone()
sub_game.take_action(a)
s, _ = minimax(sub_game, root_depth, book)
scores.append(s)
if cur_player == root_player:
s = max(scores)
else:
s = min(scores)
return s, scores
s, scores = minimax(self, book=BOOK)
v = 1 if s > 0 else -1 if s < 0 else 0
return scores, v
| [
"numpy.zeros",
"itertools.product"
] | [((770, 814), 'itertools.product', 'product', (['(0, 1)', 'TicTacToe.WINNING_POSITIONS'], {}), '((0, 1), TicTacToe.WINNING_POSITIONS)\n', (777, 814), False, 'from itertools import product\n'), ((1328, 1362), 'numpy.zeros', 'np.zeros', (['(2, 9)'], {'dtype': 'np.float32'}), '((2, 9), dtype=np.float32)\n', (1336, 1362), True, 'import numpy as np\n')] |
#!/usr/bin/python3
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import sys
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import posthoc_learn.banalg as banalg
from posthoc_learn.config import posthoc_config as config
from posthoc_learn.conban_dataset import ConBanDataset
#=================
# Plot Cumulative Regret
#=================
def plot(title, regret, labels):
"""
@param title: graph title
@param regret: T+1 x len(bandits) cumulative regret
@param labels: label[i] for bandits[i]
Plots regret curve.
"""
plt.title(title)
t = np.arange(regret.shape[0])
for i, l in enumerate(labels):
plt.plot(t, regret[:, i], label=l)
T = (regret.shape[0] - 1)
plt.xlim(0, T)
plt.xlabel("Attempts")
plt.ylabel("Cumulative Regret")
plt.legend()
plt.show()
#=================
# General Bandit Alg
#=================
def run(bandits, contexts, posthocs, loss, noise=0):
"""
@param bandits: list of initialized bandit algorithms
@param contexts: T x dF
@param posthocs: T x dG
@param loss: len(K)
"""
# Define constants
T = contexts.shape[0]
regrets = np.zeros((T + 1, len(bandits)))
print("Running for {0} rounds!".format(T))
for t in range(T):
print("Round: %d" % t)
# Choose arm for each bandit
I_t = []
for bandit in bandits:
ret, _ = bandit.choice(t, contexts[t, :])
I_t.append(ret)
# Update bandits
for i, bandit in enumerate(bandits):
regrets[t+1, i] = loss[t, I_t[i]] - np.amin(loss[t, :])
bandit.update(contexts[t, :], I_t[i], loss[t, I_t[i]] + np.random.normal(0, noise), posthocs[t, :])
# Finished, return error array
print("Finished T=%d rounds!" % T)
cum_regrets = np.cumsum(regrets, axis=0)
return cum_regrets
def gen_data(T, K, dF, dG):
# Generate a random invertible matrix (dG x K)
# Generate random matrix
A = np.random.rand(K, dG)
# Make sure it inverts
Ainv = np.linalg.inv(A.T @ A) @ A.T
assert Ainv.shape == (dG, K)
contexts = np.random.rand(T, dF)
assert contexts.shape == (T, dF)
posthocs = contexts[:, :dG]
assert posthocs.shape == (T, dG)
losses = posthocs @ Ainv
assert losses.shape == (T, K)
return contexts, posthocs, losses
def main(T, K, dF, dG):
# Load Dataset
print("Loading Dataset...")
contexts, posthocs, losses = gen_data(T, K, dF, dG)
# Constants
fLambda = 1E-7
gLambda = 1E-7
# Define bandits
bandits = []
# Vanilla Greedy
bandits.append(banalg.EpsilonGreedy(K, dF, dG, fLambda, 0, 0.1))
# Vanilla TS
#bandits.append(banalg.Thompson(K, dF, dG, fLambda, 0, var))
# Post Hoc Greedy
bandits.append(banalg.EpsilonGreedy(K, dF, dG, fLambda, gLambda, 0.1))
# Post Hoc Only
#bandits.append(banalg.Thompson(K, dF, dG, 0, gLambda, 0.01))
# Run experiment
print("Running Experiment...")
regrets = run(bandits, contexts, posthocs, losses)
# Plot Cumulative Regret
labels = []
for bandit in bandits:
labels.append(bandit.label)
title = "Augmented Contextual Bandit Regret"
#plot(title, regrets, labels)
# Save Regret Data
np.savez("toy_{0}_{1}_{2}_{3}.npz".format(T, K, dF, dG),
regrets = regrets)
if __name__ == '__main__':
if len(sys.argv) != 5:
print("Usage: main.py <T> <K> <dF> <dG>")
sys.exit(-1)
main(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"numpy.amin",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.cumsum",
"posthoc_learn.banalg.EpsilonGreedy",
"numpy.arange",
"numpy.linalg.inv",
"numpy.random.normal",
"numpy.random.rand",
"matplotlib... | [((640, 656), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (649, 656), True, 'import matplotlib.pyplot as plt\n'), ((665, 691), 'numpy.arange', 'np.arange', (['regret.shape[0]'], {}), '(regret.shape[0])\n', (674, 691), True, 'import numpy as np\n'), ((805, 819), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', 'T'], {}), '(0, T)\n', (813, 819), True, 'import matplotlib.pyplot as plt\n'), ((824, 846), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Attempts"""'], {}), "('Attempts')\n", (834, 846), True, 'import matplotlib.pyplot as plt\n'), ((851, 882), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cumulative Regret"""'], {}), "('Cumulative Regret')\n", (861, 882), True, 'import matplotlib.pyplot as plt\n'), ((887, 899), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (897, 899), True, 'import matplotlib.pyplot as plt\n'), ((904, 914), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (912, 914), True, 'import matplotlib.pyplot as plt\n'), ((1893, 1919), 'numpy.cumsum', 'np.cumsum', (['regrets'], {'axis': '(0)'}), '(regrets, axis=0)\n', (1902, 1919), True, 'import numpy as np\n'), ((2062, 2083), 'numpy.random.rand', 'np.random.rand', (['K', 'dG'], {}), '(K, dG)\n', (2076, 2083), True, 'import numpy as np\n'), ((2201, 2222), 'numpy.random.rand', 'np.random.rand', (['T', 'dF'], {}), '(T, dF)\n', (2215, 2222), True, 'import numpy as np\n'), ((735, 769), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'regret[:, i]'], {'label': 'l'}), '(t, regret[:, i], label=l)\n', (743, 769), True, 'import matplotlib.pyplot as plt\n'), ((2123, 2145), 'numpy.linalg.inv', 'np.linalg.inv', (['(A.T @ A)'], {}), '(A.T @ A)\n', (2136, 2145), True, 'import numpy as np\n'), ((2701, 2749), 'posthoc_learn.banalg.EpsilonGreedy', 'banalg.EpsilonGreedy', (['K', 'dF', 'dG', 'fLambda', '(0)', '(0.1)'], {}), '(K, dF, dG, fLambda, 0, 0.1)\n', (2721, 2749), True, 'import posthoc_learn.banalg as banalg\n'), ((2875, 2929), 'posthoc_learn.banalg.EpsilonGreedy', 'banalg.EpsilonGreedy', (['K', 'dF', 'dG', 'fLambda', 'gLambda', '(0.1)'], {}), '(K, dF, dG, fLambda, gLambda, 0.1)\n', (2895, 2929), True, 'import posthoc_learn.banalg as banalg\n'), ((3549, 3561), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (3557, 3561), False, 'import sys\n'), ((1668, 1687), 'numpy.amin', 'np.amin', (['loss[t, :]'], {}), '(loss[t, :])\n', (1675, 1687), True, 'import numpy as np\n'), ((1756, 1782), 'numpy.random.normal', 'np.random.normal', (['(0)', 'noise'], {}), '(0, noise)\n', (1772, 1782), True, 'import numpy as np\n')] |
import numpy as np
import os
import tensorflow as tf
from lsct.utils.frame_features_video_folders import CalculateFrameQualityFeatures
from lsct.ablations.frame_features_video_folders_resnet50 import CalculateFrameQualityFeaturesResnet50
FFMPEG = r'..\\ffmpeg\ffmpeg.exe'
FFPROBE = r'..\\ffmpeg\ffprobe.exe'
"""
This script shows how to calculate PHIQNet features on all video frames, FFMPEG and FFProbe are required
"""
def video_frame_features_PHIQNet(phinqnet_weights_path, video_path, reture_clip_features=False):
frame_features_extractor = CalculateFrameQualityFeatures(phinqnet_weights_path, FFPROBE, FFMPEG)
features = frame_features_extractor.__ffmpeg_frames_features__(video_path, flip=False)
features = np.squeeze(np.array(features), axis=2)
features = np.reshape(features, (features.shape[0], features.shape[1] * features.shape[2]))
if reture_clip_features:
clip_features = []
clip_length = 16
for j in range(features.shape[0] // clip_length):
clip_features.append(features[j * clip_length: (j + 1) * clip_length, :])
clip_features = np.array(clip_features)
return clip_features
return np.array(features)
def video_frame_features_ResNet50(resnet50_weights_path, video_path, reture_clip_features=False):
frame_features_extractor = CalculateFrameQualityFeaturesResnet50(resnet50_weights_path, FFPROBE, FFMPEG)
features = frame_features_extractor.__ffmpeg_frames_features__(video_path, flip=False)
features = np.squeeze(np.array(features), axis=1)
if reture_clip_features:
clip_features = []
clip_length = 16
for j in range(features.shape[0] // clip_length):
clip_features.append(features[j * clip_length: (j + 1) * clip_length, :])
clip_features = np.array(clip_features)
return clip_features
return np.array(features, np.float16)
def video_frame_features_ResNet50_folder(resnet50_weights_path, video_folder, target_folder):
frame_features_extractor = CalculateFrameQualityFeaturesResnet50(resnet50_weights_path, FFPROBE, FFMPEG)
video_types = ('.mp4', '.mpg')
video_paths = [f for f in os.listdir(video_folder) if f.endswith(video_types)]
video_paths = video_paths[:70000]
numb_videos = len(video_paths)
for i, video_path in enumerate(video_paths):
ext = os.path.splitext(video_path)
np_file = os.path.join(target_folder, '{}.npy'.format(ext[0]))
if not os.path.exists(np_file):
features = frame_features_extractor.__ffmpeg_frames_features__(os.path.join(video_folder, video_path), flip=False)
features = np.squeeze(np.array(features), axis=1)
features = np.array(features, dtype=np.float16)
np.save(np_file, features)
print('{} out of {}, {} done'.format(i, numb_videos, video_path))
else:
print('{} out of {}, {} already exists'.format(i, numb_videos, video_path))
if __name__ == '__main__':
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
# phiqnet_weights_path = r'..\\model_weights\PHIQNet.h5'
# video_path = r'.\\sample_data\example_video (mos=3.24).mp4'
video_folder = r'K:\Faglitteratur\VQA\k150ka'
# features = video_frame_features_PHIQNet(phiqnet_weights_path, video_path)
# Use None that ResNet50 will download ImageNet Pretrained weights or specify the weight path
resnet50_imagenet_weights = r'C:\pretrained_weights_files\resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'
# features_resnet50 = video_frame_features_ResNet50(resnet50_imagenet_weights, video_path)
target_folder = r'F:\k150k_features'
video_frame_features_ResNet50_folder(resnet50_imagenet_weights, video_folder, target_folder)
t = 0 | [
"numpy.save",
"os.path.join",
"tensorflow.config.experimental.set_visible_devices",
"lsct.utils.frame_features_video_folders.CalculateFrameQualityFeatures",
"os.path.exists",
"lsct.ablations.frame_features_video_folders_resnet50.CalculateFrameQualityFeaturesResnet50",
"numpy.array",
"numpy.reshape",
... | [((554, 623), 'lsct.utils.frame_features_video_folders.CalculateFrameQualityFeatures', 'CalculateFrameQualityFeatures', (['phinqnet_weights_path', 'FFPROBE', 'FFMPEG'], {}), '(phinqnet_weights_path, FFPROBE, FFMPEG)\n', (583, 623), False, 'from lsct.utils.frame_features_video_folders import CalculateFrameQualityFeatures\n'), ((784, 869), 'numpy.reshape', 'np.reshape', (['features', '(features.shape[0], features.shape[1] * features.shape[2])'], {}), '(features, (features.shape[0], features.shape[1] * features.shape[2])\n )\n', (794, 869), True, 'import numpy as np\n'), ((1180, 1198), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (1188, 1198), True, 'import numpy as np\n'), ((1330, 1407), 'lsct.ablations.frame_features_video_folders_resnet50.CalculateFrameQualityFeaturesResnet50', 'CalculateFrameQualityFeaturesResnet50', (['resnet50_weights_path', 'FFPROBE', 'FFMPEG'], {}), '(resnet50_weights_path, FFPROBE, FFMPEG)\n', (1367, 1407), False, 'from lsct.ablations.frame_features_video_folders_resnet50 import CalculateFrameQualityFeaturesResnet50\n'), ((1868, 1898), 'numpy.array', 'np.array', (['features', 'np.float16'], {}), '(features, np.float16)\n', (1876, 1898), True, 'import numpy as np\n'), ((2026, 2103), 'lsct.ablations.frame_features_video_folders_resnet50.CalculateFrameQualityFeaturesResnet50', 'CalculateFrameQualityFeaturesResnet50', (['resnet50_weights_path', 'FFPROBE', 'FFMPEG'], {}), '(resnet50_weights_path, FFPROBE, FFMPEG)\n', (2063, 2103), False, 'from lsct.ablations.frame_features_video_folders_resnet50 import CalculateFrameQualityFeaturesResnet50\n'), ((3008, 3059), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (3052, 3059), True, 'import tensorflow as tf\n'), ((3064, 3122), 'tensorflow.config.experimental.set_visible_devices', 'tf.config.experimental.set_visible_devices', (['gpus[0]', '"""GPU"""'], {}), "(gpus[0], 'GPU')\n", (3106, 3122), True, 'import tensorflow as tf\n'), ((741, 759), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (749, 759), True, 'import numpy as np\n'), ((1115, 1138), 'numpy.array', 'np.array', (['clip_features'], {}), '(clip_features)\n', (1123, 1138), True, 'import numpy as np\n'), ((1525, 1543), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (1533, 1543), True, 'import numpy as np\n'), ((1803, 1826), 'numpy.array', 'np.array', (['clip_features'], {}), '(clip_features)\n', (1811, 1826), True, 'import numpy as np\n'), ((2360, 2388), 'os.path.splitext', 'os.path.splitext', (['video_path'], {}), '(video_path)\n', (2376, 2388), False, 'import os\n'), ((2170, 2194), 'os.listdir', 'os.listdir', (['video_folder'], {}), '(video_folder)\n', (2180, 2194), False, 'import os\n'), ((2475, 2498), 'os.path.exists', 'os.path.exists', (['np_file'], {}), '(np_file)\n', (2489, 2498), False, 'import os\n'), ((2712, 2748), 'numpy.array', 'np.array', (['features'], {'dtype': 'np.float16'}), '(features, dtype=np.float16)\n', (2720, 2748), True, 'import numpy as np\n'), ((2761, 2787), 'numpy.save', 'np.save', (['np_file', 'features'], {}), '(np_file, features)\n', (2768, 2787), True, 'import numpy as np\n'), ((2575, 2613), 'os.path.join', 'os.path.join', (['video_folder', 'video_path'], {}), '(video_folder, video_path)\n', (2587, 2613), False, 'import os\n'), ((2661, 2679), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (2669, 2679), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Point
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Odometry,OccupancyGrid
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
import tf.transformations
import tf
#import laser cast part
from Laser import Laser, Map
import math
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
from copy import copy
import numpy as np
import os
from keras.models import model_from_json
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam
optim=Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
#Network parameters
data_dim =362
output_size=3
batch_size=128
epoch=1
def normalize_angle(theta):
#Normalize phi to be between -pi and pi
while theta> math.pi:
theta = theta - 2*math.pi
while theta<-math.pi:
theta = theta + 2*math.pi
return theta
def calculateScans(train_pose,delta_odom,laser):
global data_laser_simul
data_laser_simul=[]
train_pose.pop()
for i in range(len(train_pose)):
update=train_pose[i]+delta_odom[i]
predicted_laser=getLaserCast( update[0],update[1],update[2],laser)
data_laser_simul.append(predicted_laser)
def mapWrapper(occ_map, width,height):
#print("occ_map",occ_map)
occ_map=np.array(occ_map)
for i in range(occ_map.shape[0]):
if occ_map[i] >= 0:
occ_map[i] = 1.0-(occ_map[i]/100.0)
else:
occ_map[i] = 1
occ_map.resize(height, width)
occ_map = occ_map.T
return occ_map
def initCaster(wrappedMap,mapInfo):
offset_x =mapInfo.origin.position.x
offset_y =mapInfo.origin.position.y
resolution = mapInfo.resolution
#Parameters of the laser
max_range = 50.0
no_of_beams = 181
min_angle = -math.pi/2.0
resolution_angle = math.pi/(no_of_beams-1)
noise_variance = 0.0#perfect
map_obj = Map(mapInfo.height, mapInfo.width, offset_x, offset_y, resolution, wrappedMap)
laser = Laser(max_range, min_angle, resolution_angle, no_of_beams, noise_variance, map_obj)
return laser
def getLaserCast(robot_pos_x,robot_pos_y,robot_theta, laser):
#relative position of the laser scanner to the center of the robot
laser_pos_x = 1.2
laser_pos_y = 0.0
laser_angle = 0.0 * (math.pi/180.0)
sin_theta = math.sin(robot_theta)
cos_theta = math.cos(robot_theta)
x = robot_pos_x + laser_pos_x * cos_theta - laser_pos_y*sin_theta
y = robot_pos_y + laser_pos_x * sin_theta + laser_pos_y*cos_theta
theta = robot_theta + laser_angle
theta=normalize_angle(theta)
ranges = laser.scan(x,y,theta)
return ranges
gridMap=OccupancyGrid()
callback_front_laser=[]
callback_pose_new=PoseStamped()
odom=Odometry()
#training data
data_pose=[]
data_laser=[]
data_laser_simul=[]
data_odom=[]
def get_data():
global callback_front_laser
global callback_pose_new
global data_pose
global data_laser
global odom
global data_odom
# get pose
temp=[None]*3
temp[0]=copy(callback_pose_new.pose.position.x)
temp[1]=copy(callback_pose_new.pose.position.y)
quaternion = (
callback_pose_new.pose.orientation.x,
callback_pose_new.pose.orientation.y,
callback_pose_new.pose.orientation.z,
callback_pose_new.pose.orientation.w)
euler = tf.transformations.euler_from_quaternion(quaternion)
temp[2]=copy(euler[2])
data_pose.append(copy(temp))
#get laser front
data_laser.append(copy(callback_front_laser))
#odom update
odom_current=[None]*3
quaternion = (
odom.pose.pose.orientation.x,
odom.pose.pose.orientation.y,
odom.pose.pose.orientation.z,
odom.pose.pose.orientation.w)
euler = tf.transformations.euler_from_quaternion(quaternion)
odom_current[0] =copy(odom.pose.pose.position.x)
odom_current[1]=copy(odom.pose.pose.position.y)
odom_current[2]=euler[2]
data_odom.append(odom_current)
def callback_map(data):
global gridMap
gridMap=data
def callback_front(data):
global callback_front_laser
callback_front_laser=data.ranges
def callback_pose(data):
global callback_pose_new
callback_pose_new=data
def callback_odom(data):
global odom
odom=data
def both():
global data_laser
global data_laser_simul
global data_pose
global odom
global gridMap
rospy.init_node('correction_net_train', anonymous=True)
#subscribe
rospy.Subscriber('scan_front', LaserScan, callback_front)
rospy.Subscriber('true_pose', PoseStamped, callback_pose)
rospy.Subscriber('odom', Odometry, callback_odom)
rospy.Subscriber('/map', OccupancyGrid, callback_map)
rate = rospy.Rate(10) # 10hz
rospy.sleep(2.)
time_last_update = rospy.Time.now()
update_weights_freq= rospy.Duration(10).to_sec()
wrappedMap= mapWrapper(gridMap.data,gridMap.info.width, gridMap.info.height)
laser=initCaster(wrappedMap, gridMap.info)
while not rospy.is_shutdown():
rate.sleep()
diff_time=rospy.Time.now()-time_last_update# frequency of update
get_data()
if(diff_time.to_sec()>=update_weights_freq):
time_last_update=rospy.Time.now()
train_front=copy(data_laser)
train_pose=copy(data_pose)
train_odom=copy(data_odom)
#generate laser scans from odom position
delta_odom=np.diff(train_odom,axis=0)
delta_pose=np.diff(train_pose,axis=0)
print("delta_odom",delta_odom.shape)
print("delta_pose",delta_pose.shape)
train_front.pop(0)
calculateScans(train_pose,delta_odom,laser)
delta=delta_pose-delta_odom
print("train_front", len(train_front))
print("train_simul", len(data_laser_simul))
data=np.hstack((data_laser_simul,train_front))
X_train=np.reshape(data, (data.shape[0],1,1, data_dim))
print('X_train',X_train.shape)
y_train=np.array( delta)
print('y_train',y_train.shape)
netname="CorrectionNet"
if not os.path.isfile(netname+'.h5') or not os.path.isfile(netname+'.json'):
print('NO NETWORK')
else:
print('Loading existing network')
model = model_from_json(open(netname+'.json').read())
model.load_weights(netname+'.h5')
#compile loaded model
model.compile(loss='mse',optimizer=optim)
print('Start learning...')
model.fit(X_train, y_train, nb_epoch=epoch,batch_size=batch_size)
model.save_weights(netname+'.h5', overwrite=True)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
print('Start retraining')
both()
| [
"Laser.Laser",
"rospy.Subscriber",
"os.path.isfile",
"rospy.Duration",
"geometry_msgs.msg.PoseStamped",
"rospy.Time.now",
"Laser.Map",
"rospy.Rate",
"rospy.is_shutdown",
"math.cos",
"rospy.init_node",
"numpy.reshape",
"nav_msgs.msg.Odometry",
"nav_msgs.msg.OccupancyGrid",
"keras.optimize... | [((745, 800), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(1e-05)', 'beta_1': '(0.9)', 'beta_2': '(0.999)', 'epsilon': '(1e-08)'}), '(lr=1e-05, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n', (749, 800), False, 'from keras.optimizers import Adam\n'), ((2925, 2940), 'nav_msgs.msg.OccupancyGrid', 'OccupancyGrid', ([], {}), '()\n', (2938, 2940), False, 'from nav_msgs.msg import Odometry, OccupancyGrid\n'), ((2985, 2998), 'geometry_msgs.msg.PoseStamped', 'PoseStamped', ([], {}), '()\n', (2996, 2998), False, 'from geometry_msgs.msg import PoseStamped\n'), ((3005, 3015), 'nav_msgs.msg.Odometry', 'Odometry', ([], {}), '()\n', (3013, 3015), False, 'from nav_msgs.msg import Odometry, OccupancyGrid\n'), ((1518, 1535), 'numpy.array', 'np.array', (['occ_map'], {}), '(occ_map)\n', (1526, 1535), True, 'import numpy as np\n'), ((2138, 2216), 'Laser.Map', 'Map', (['mapInfo.height', 'mapInfo.width', 'offset_x', 'offset_y', 'resolution', 'wrappedMap'], {}), '(mapInfo.height, mapInfo.width, offset_x, offset_y, resolution, wrappedMap)\n', (2141, 2216), False, 'from Laser import Laser, Map\n'), ((2230, 2317), 'Laser.Laser', 'Laser', (['max_range', 'min_angle', 'resolution_angle', 'no_of_beams', 'noise_variance', 'map_obj'], {}), '(max_range, min_angle, resolution_angle, no_of_beams, noise_variance,\n map_obj)\n', (2235, 2317), False, 'from Laser import Laser, Map\n'), ((2575, 2596), 'math.sin', 'math.sin', (['robot_theta'], {}), '(robot_theta)\n', (2583, 2596), False, 'import math\n'), ((2614, 2635), 'math.cos', 'math.cos', (['robot_theta'], {}), '(robot_theta)\n', (2622, 2635), False, 'import math\n'), ((3312, 3351), 'copy.copy', 'copy', (['callback_pose_new.pose.position.x'], {}), '(callback_pose_new.pose.position.x)\n', (3316, 3351), False, 'from copy import copy\n'), ((3365, 3404), 'copy.copy', 'copy', (['callback_pose_new.pose.position.y'], {}), '(callback_pose_new.pose.position.y)\n', (3369, 3404), False, 'from copy import copy\n'), ((3612, 3664), 'tf.transformations.euler_from_quaternion', 'tf.transformations.euler_from_quaternion', (['quaternion'], {}), '(quaternion)\n', (3652, 3664), False, 'import tf\n'), ((3678, 3692), 'copy.copy', 'copy', (['euler[2]'], {}), '(euler[2])\n', (3682, 3692), False, 'from copy import copy\n'), ((4022, 4074), 'tf.transformations.euler_from_quaternion', 'tf.transformations.euler_from_quaternion', (['quaternion'], {}), '(quaternion)\n', (4062, 4074), False, 'import tf\n'), ((4097, 4128), 'copy.copy', 'copy', (['odom.pose.pose.position.x'], {}), '(odom.pose.pose.position.x)\n', (4101, 4128), False, 'from copy import copy\n'), ((4150, 4181), 'copy.copy', 'copy', (['odom.pose.pose.position.y'], {}), '(odom.pose.pose.position.y)\n', (4154, 4181), False, 'from copy import copy\n'), ((4718, 4773), 'rospy.init_node', 'rospy.init_node', (['"""correction_net_train"""'], {'anonymous': '(True)'}), "('correction_net_train', anonymous=True)\n", (4733, 4773), False, 'import rospy\n'), ((4795, 4852), 'rospy.Subscriber', 'rospy.Subscriber', (['"""scan_front"""', 'LaserScan', 'callback_front'], {}), "('scan_front', LaserScan, callback_front)\n", (4811, 4852), False, 'import rospy\n'), ((4858, 4915), 'rospy.Subscriber', 'rospy.Subscriber', (['"""true_pose"""', 'PoseStamped', 'callback_pose'], {}), "('true_pose', PoseStamped, callback_pose)\n", (4874, 4915), False, 'import rospy\n'), ((4921, 4970), 'rospy.Subscriber', 'rospy.Subscriber', (['"""odom"""', 'Odometry', 'callback_odom'], {}), "('odom', Odometry, callback_odom)\n", (4937, 4970), False, 'import rospy\n'), ((4976, 5029), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/map"""', 'OccupancyGrid', 'callback_map'], {}), "('/map', OccupancyGrid, callback_map)\n", (4992, 5029), False, 'import rospy\n'), ((5042, 5056), 'rospy.Rate', 'rospy.Rate', (['(10)'], {}), '(10)\n', (5052, 5056), False, 'import rospy\n'), ((5069, 5085), 'rospy.sleep', 'rospy.sleep', (['(2.0)'], {}), '(2.0)\n', (5080, 5085), False, 'import rospy\n'), ((5121, 5137), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (5135, 5137), False, 'import rospy\n'), ((7198, 7210), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (7208, 7210), False, 'import rospy\n'), ((3715, 3725), 'copy.copy', 'copy', (['temp'], {}), '(temp)\n', (3719, 3725), False, 'from copy import copy\n'), ((3772, 3798), 'copy.copy', 'copy', (['callback_front_laser'], {}), '(callback_front_laser)\n', (3776, 3798), False, 'from copy import copy\n'), ((5339, 5358), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (5356, 5358), False, 'import rospy\n'), ((5164, 5182), 'rospy.Duration', 'rospy.Duration', (['(10)'], {}), '(10)\n', (5178, 5182), False, 'import rospy\n'), ((5401, 5417), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (5415, 5417), False, 'import rospy\n'), ((5560, 5576), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (5574, 5576), False, 'import rospy\n'), ((5602, 5618), 'copy.copy', 'copy', (['data_laser'], {}), '(data_laser)\n', (5606, 5618), False, 'from copy import copy\n'), ((5643, 5658), 'copy.copy', 'copy', (['data_pose'], {}), '(data_pose)\n', (5647, 5658), False, 'from copy import copy\n'), ((5683, 5698), 'copy.copy', 'copy', (['data_odom'], {}), '(data_odom)\n', (5687, 5698), False, 'from copy import copy\n'), ((5791, 5818), 'numpy.diff', 'np.diff', (['train_odom'], {'axis': '(0)'}), '(train_odom, axis=0)\n', (5798, 5818), True, 'import numpy as np\n'), ((5842, 5869), 'numpy.diff', 'np.diff', (['train_pose'], {'axis': '(0)'}), '(train_pose, axis=0)\n', (5849, 5869), True, 'import numpy as np\n'), ((6232, 6274), 'numpy.hstack', 'np.hstack', (['(data_laser_simul, train_front)'], {}), '((data_laser_simul, train_front))\n', (6241, 6274), True, 'import numpy as np\n'), ((6295, 6344), 'numpy.reshape', 'np.reshape', (['data', '(data.shape[0], 1, 1, data_dim)'], {}), '(data, (data.shape[0], 1, 1, data_dim))\n', (6305, 6344), True, 'import numpy as np\n'), ((6408, 6423), 'numpy.array', 'np.array', (['delta'], {}), '(delta)\n', (6416, 6423), True, 'import numpy as np\n'), ((6526, 6557), 'os.path.isfile', 'os.path.isfile', (["(netname + '.h5')"], {}), "(netname + '.h5')\n", (6540, 6557), False, 'import os\n'), ((6563, 6596), 'os.path.isfile', 'os.path.isfile', (["(netname + '.json')"], {}), "(netname + '.json')\n", (6577, 6596), False, 'import os\n')] |
import matplotlib.pyplot as plt
import numpy as np
import pytest
import torch
from src import datamodules
from src.augmentations.seg_aug import get_composed_augmentations
from src.datamodules.cityscapes import Cityscapes
from src.datamodules.dadatamodule import DADataModule
from src.datamodules.gta5 import GTA5
from src.datamodules.synthia import Synthia
aug = {
"rcrop": [768, 768],
"brightness": 0.5,
"contrast": 0.5,
"saturation": 0.5,
"hflip": 0.5,
}
def template_test(data_class, name, **kwargs):
augmentations = get_composed_augmentations(aug)
dst = data_class(augmentations=augmentations, **kwargs)
bs = 4
trainloader = torch.utils.data.DataLoader(dst, batch_size=bs, num_workers=0)
imgs, labels, ind = next(iter(trainloader))
imgs = imgs.numpy()[:, ::-1, :, :]
imgs = np.transpose(imgs, [0, 2, 3, 1])
f, axarr = plt.subplots(bs, 2)
for j in range(bs):
axarr[j][0].set_axis_off()
axarr[j][1].set_axis_off()
axarr[j][0].imshow(imgs[j])
axarr[j][1].imshow(dst.decode_segmap(labels.numpy()[j]))
plt.savefig(f"{name}_test.png")
def test_Cityscapes():
return template_test(
Cityscapes,
"cityscapes",
rootpath="./data/cityscapes",
split="train",
n_classes=19,
img_cols=2048,
img_rows=1024,
norm=False,
)
def test_GTA5():
return template_test(
GTA5,
"gta5",
rootpath="./data/GTA5",
n_classes=19,
img_cols=1914,
img_rows=1052,
norm=False,
)
def test_synthia():
return
return template_test(
Synthia,
"synthia",
rootpath="./data/SYNTHIA",
img_cols=1914,
img_rows=1052,
n_classes=13,
is_transform=True,
norm=False,
)
def test_dadatamodule():
loader = DADataModule(augmentations=aug)
loader.setup()
assert not loader.is_da_task
it = loader.train_dataloader()["src"]
ret = next(iter(it))
_, _, _ = ret
it = loader.val_dataloader()
ret = next(iter(it))
_, _, _ = ret
| [
"src.augmentations.seg_aug.get_composed_augmentations",
"torch.utils.data.DataLoader",
"numpy.transpose",
"src.datamodules.dadatamodule.DADataModule",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((548, 579), 'src.augmentations.seg_aug.get_composed_augmentations', 'get_composed_augmentations', (['aug'], {}), '(aug)\n', (574, 579), False, 'from src.augmentations.seg_aug import get_composed_augmentations\n'), ((670, 732), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dst'], {'batch_size': 'bs', 'num_workers': '(0)'}), '(dst, batch_size=bs, num_workers=0)\n', (697, 732), False, 'import torch\n'), ((832, 864), 'numpy.transpose', 'np.transpose', (['imgs', '[0, 2, 3, 1]'], {}), '(imgs, [0, 2, 3, 1])\n', (844, 864), True, 'import numpy as np\n'), ((880, 899), 'matplotlib.pyplot.subplots', 'plt.subplots', (['bs', '(2)'], {}), '(bs, 2)\n', (892, 899), True, 'import matplotlib.pyplot as plt\n'), ((1099, 1130), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{name}_test.png"""'], {}), "(f'{name}_test.png')\n", (1110, 1130), True, 'import matplotlib.pyplot as plt\n'), ((1871, 1902), 'src.datamodules.dadatamodule.DADataModule', 'DADataModule', ([], {'augmentations': 'aug'}), '(augmentations=aug)\n', (1883, 1902), False, 'from src.datamodules.dadatamodule import DADataModule\n')] |
import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
import numpy as np
from torch.autograd.variable import Variable
from src.Models.loss import losses_joint
from src.Models.models import Encoder
from src.Models.models import ImitateJoint, ParseModelOutput
from src.utils import read_config
from src.utils.generators.mixed_len_generator import MixedGenerateData
from src.utils.generators.wake_sleep_gen import WakeSleepGen
from src.utils.learn_utils import LearningRate
from src.utils.train_utils import prepare_input_op, cosine_similarity, chamfer, beams_parser, validity, image_from_expressions, stack_from_expressions
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from src.utils.refine import optimize_expression
import os
import json
import sys
from src.utils.generators.shapenet_generater import Generator
from ws_infer import infer_programs
from globals import device
inference_train_size = 10000
inference_test_size = 3000
# inference_train_size = 500
# inference_test_size = 100
vocab_size = 400
max_len = 13
"""
Trains CSGNet to convergence on samples from generator network
TODO: train to convergence and not number of epochs
"""
def train_inference(inference_net, iter):
config = read_config.Config("config_synthetic.yml")
generator = WakeSleepGen(f"wake_sleep_data/inference/{iter}/labels/labels.pt",
f"wake_sleep_data/inference/{iter}/labels/val/labels.pt",
batch_size=config.batch_size,
train_size=inference_train_size,
test_size=inference_test_size,
canvas_shape=config.canvas_shape,
max_len=max_len)
train_gen = generator.get_train_data()
test_gen = generator.get_test_data()
encoder_net, imitate_net = inference_net
optimizer = optim.Adam(
[para for para in imitate_net.parameters() if para.requires_grad],
weight_decay=config.weight_decay,
lr=config.lr)
reduce_plat = LearningRate(
optimizer,
init_lr=config.lr,
lr_dacay_fact=0.2,
patience=config.patience)
best_test_loss = 1e20
best_imitate_dict = imitate_net.state_dict()
prev_test_cd = 1e20
prev_test_iou = 0
patience = 5
num_worse = 0
for epoch in range(50):
train_loss = 0
Accuracies = []
imitate_net.train()
for batch_idx in range(inference_train_size //
(config.batch_size * config.num_traj)):
optimizer.zero_grad()
loss = Variable(torch.zeros(1)).to(device).data
for _ in range(config.num_traj):
batch_data, batch_labels = next(train_gen)
batch_data = batch_data.to(device)
batch_labels = batch_labels.to(device)
batch_data = batch_data[:, :, 0:1, :, :]
one_hot_labels = prepare_input_op(batch_labels, vocab_size)
one_hot_labels = Variable(
torch.from_numpy(one_hot_labels)).to(device)
outputs = imitate_net([batch_data, one_hot_labels, max_len])
loss_k = (losses_joint(outputs, batch_labels, time_steps=max_len + 1) / (
max_len + 1)) / config.num_traj
loss_k.backward()
loss += loss_k.data
del loss_k
optimizer.step()
train_loss += loss
print(f"batch {batch_idx} train loss: {loss.cpu().numpy()}")
mean_train_loss = train_loss / (inference_train_size // (config.batch_size))
print(f"epoch {epoch} mean train loss: {mean_train_loss.cpu().numpy()}")
imitate_net.eval()
loss = Variable(torch.zeros(1)).to(device)
metrics = {"cos": 0, "iou": 0, "cd": 0}
IOU = 0
COS = 0
CD = 0
for batch_idx in range(inference_test_size // config.batch_size):
with torch.no_grad():
batch_data, batch_labels = next(test_gen)
batch_data = batch_data.to(device)
batch_labels = batch_labels.to(device)
one_hot_labels = prepare_input_op(batch_labels, vocab_size)
one_hot_labels = Variable(
torch.from_numpy(one_hot_labels)).to(device)
test_outputs = imitate_net([batch_data, one_hot_labels, max_len])
loss += (losses_joint(test_outputs, batch_labels, time_steps=max_len + 1) / (
max_len + 1))
test_output = imitate_net.test([batch_data, one_hot_labels, max_len])
pred_images, correct_prog, pred_prog = generator.parser.get_final_canvas(
test_output, if_just_expressions=False, if_pred_images=True)
target_images = batch_data.cpu().numpy()[-1, :, 0, :, :].astype(dtype=bool)
iou = np.sum(np.logical_and(target_images, pred_images),
(1, 2)) / \
np.sum(np.logical_or(target_images, pred_images),
(1, 2))
cos = cosine_similarity(target_images, pred_images)
CD += np.sum(chamfer(target_images, pred_images))
IOU += np.sum(iou)
COS += np.sum(cos)
metrics["iou"] = IOU / inference_test_size
metrics["cos"] = COS / inference_test_size
metrics["cd"] = CD / inference_test_size
test_losses = loss.data
test_loss = test_losses.cpu().numpy() / (inference_test_size //
(config.batch_size))
if test_loss >= best_test_loss:
num_worse += 1
else:
num_worse = 0
best_test_loss = test_loss
best_imitate_dict = imitate_net.state_dict()
if num_worse >= patience:
# load the best model and stop training
imitate_net.load_state_dict(best_imitate_dict)
break
reduce_plat.reduce_on_plateu(metrics["cd"])
print("Epoch {}/{}=> train_loss: {}, iou: {}, cd: {}, test_mse: {}".format(epoch, config.epochs,
mean_train_loss.cpu().numpy(),
metrics["iou"], metrics["cd"], test_loss,))
print(f"CORRECT PROGRAMS: {len(generator.correct_programs)}")
del test_losses, test_outputs
"""
Get initial pretrained CSGNet inference network
"""
def get_csgnet():
config = read_config.Config("config_synthetic.yml")
# Encoder
encoder_net = Encoder(config.encoder_drop)
encoder_net = encoder_net.to(device)
# Load the terminals symbols of the grammar
with open("terminals.txt", "r") as file:
unique_draw = file.readlines()
for index, e in enumerate(unique_draw):
unique_draw[index] = e[0:-1]
imitate_net = ImitateJoint(
hd_sz=config.hidden_size,
input_size=config.input_size,
encoder=encoder_net,
mode=config.mode,
num_draws=len(unique_draw),
canvas_shape=config.canvas_shape)
imitate_net = imitate_net.to(device)
print("pre loading model")
pretrained_dict = torch.load(config.pretrain_modelpath, map_location=device)
imitate_net_dict = imitate_net.state_dict()
imitate_pretrained_dict = {
k: v
for k, v in pretrained_dict.items() if k in imitate_net_dict
}
imitate_net_dict.update(imitate_pretrained_dict)
imitate_net.load_state_dict(imitate_net_dict)
for param in imitate_net.parameters():
param.requires_grad = True
for param in encoder_net.parameters():
param.requires_grad = True
return (encoder_net, imitate_net)
"""
Runs the wake-sleep algorithm
"""
def wake_sleep(iterations):
encoder_net, imitate_net = get_csgnet()
# print("pre loading model")
# pretrained_dict = torch.load("trained_models/imitate-17.pth", map_location=device)
# imitate_net_dict = imitate_net.state_dict()
# imitate_pretrained_dict = {
# k: v
# for k, v in pretrained_dict.items() if k in imitate_net_dict
# }
# imitate_net_dict.update(imitate_pretrained_dict)
# imitate_net.load_state_dict(imitate_net_dict)
for i in range(iterations):
print(f"WAKE SLEEP ITERATION {i}")
if not i == 0: # already inferred initial cad programs using pretrained model
infer_programs((encoder_net, imitate_net), i)
train_inference((encoder_net, imitate_net), i)
torch.save(imitate_net.state_dict(), f"trained_models/imitate-{i}.pth")
wake_sleep(50)
| [
"src.utils.learn_utils.LearningRate",
"src.utils.read_config.Config",
"src.utils.train_utils.chamfer",
"torch.from_numpy",
"numpy.sum",
"numpy.logical_and",
"ws_infer.infer_programs",
"src.utils.train_utils.prepare_input_op",
"torch.load",
"src.Models.loss.losses_joint",
"matplotlib.use",
"num... | [((774, 795), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (788, 795), False, 'import matplotlib\n'), ((1358, 1400), 'src.utils.read_config.Config', 'read_config.Config', (['"""config_synthetic.yml"""'], {}), "('config_synthetic.yml')\n", (1376, 1400), False, 'from src.utils import read_config\n'), ((1418, 1701), 'src.utils.generators.wake_sleep_gen.WakeSleepGen', 'WakeSleepGen', (['f"""wake_sleep_data/inference/{iter}/labels/labels.pt"""', 'f"""wake_sleep_data/inference/{iter}/labels/val/labels.pt"""'], {'batch_size': 'config.batch_size', 'train_size': 'inference_train_size', 'test_size': 'inference_test_size', 'canvas_shape': 'config.canvas_shape', 'max_len': 'max_len'}), "(f'wake_sleep_data/inference/{iter}/labels/labels.pt',\n f'wake_sleep_data/inference/{iter}/labels/val/labels.pt', batch_size=\n config.batch_size, train_size=inference_train_size, test_size=\n inference_test_size, canvas_shape=config.canvas_shape, max_len=max_len)\n", (1430, 1701), False, 'from src.utils.generators.wake_sleep_gen import WakeSleepGen\n'), ((2180, 2272), 'src.utils.learn_utils.LearningRate', 'LearningRate', (['optimizer'], {'init_lr': 'config.lr', 'lr_dacay_fact': '(0.2)', 'patience': 'config.patience'}), '(optimizer, init_lr=config.lr, lr_dacay_fact=0.2, patience=\n config.patience)\n', (2192, 2272), False, 'from src.utils.learn_utils import LearningRate\n'), ((6679, 6721), 'src.utils.read_config.Config', 'read_config.Config', (['"""config_synthetic.yml"""'], {}), "('config_synthetic.yml')\n", (6697, 6721), False, 'from src.utils import read_config\n'), ((6755, 6783), 'src.Models.models.Encoder', 'Encoder', (['config.encoder_drop'], {}), '(config.encoder_drop)\n', (6762, 6783), False, 'from src.Models.models import Encoder\n'), ((7372, 7430), 'torch.load', 'torch.load', (['config.pretrain_modelpath'], {'map_location': 'device'}), '(config.pretrain_modelpath, map_location=device)\n', (7382, 7430), False, 'import torch\n'), ((8592, 8637), 'ws_infer.infer_programs', 'infer_programs', (['(encoder_net, imitate_net)', 'i'], {}), '((encoder_net, imitate_net), i)\n', (8606, 8637), False, 'from ws_infer import infer_programs\n'), ((3084, 3126), 'src.utils.train_utils.prepare_input_op', 'prepare_input_op', (['batch_labels', 'vocab_size'], {}), '(batch_labels, vocab_size)\n', (3100, 3126), False, 'from src.utils.train_utils import prepare_input_op, cosine_similarity, chamfer, beams_parser, validity, image_from_expressions, stack_from_expressions\n'), ((4117, 4132), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4130, 4132), False, 'import torch\n'), ((4331, 4373), 'src.utils.train_utils.prepare_input_op', 'prepare_input_op', (['batch_labels', 'vocab_size'], {}), '(batch_labels, vocab_size)\n', (4347, 4373), False, 'from src.utils.train_utils import prepare_input_op, cosine_similarity, chamfer, beams_parser, validity, image_from_expressions, stack_from_expressions\n'), ((5286, 5331), 'src.utils.train_utils.cosine_similarity', 'cosine_similarity', (['target_images', 'pred_images'], {}), '(target_images, pred_images)\n', (5303, 5331), False, 'from src.utils.train_utils import prepare_input_op, cosine_similarity, chamfer, beams_parser, validity, image_from_expressions, stack_from_expressions\n'), ((5421, 5432), 'numpy.sum', 'np.sum', (['iou'], {}), '(iou)\n', (5427, 5432), True, 'import numpy as np\n'), ((5456, 5467), 'numpy.sum', 'np.sum', (['cos'], {}), '(cos)\n', (5462, 5467), True, 'import numpy as np\n'), ((3904, 3918), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (3915, 3918), False, 'import torch\n'), ((4589, 4653), 'src.Models.loss.losses_joint', 'losses_joint', (['test_outputs', 'batch_labels'], {'time_steps': '(max_len + 1)'}), '(test_outputs, batch_labels, time_steps=max_len + 1)\n', (4601, 4653), False, 'from src.Models.loss import losses_joint\n'), ((5361, 5396), 'src.utils.train_utils.chamfer', 'chamfer', (['target_images', 'pred_images'], {}), '(target_images, pred_images)\n', (5368, 5396), False, 'from src.utils.train_utils import prepare_input_op, cosine_similarity, chamfer, beams_parser, validity, image_from_expressions, stack_from_expressions\n'), ((3339, 3398), 'src.Models.loss.losses_joint', 'losses_joint', (['outputs', 'batch_labels'], {'time_steps': '(max_len + 1)'}), '(outputs, batch_labels, time_steps=max_len + 1)\n', (3351, 3398), False, 'from src.Models.loss import losses_joint\n'), ((5070, 5112), 'numpy.logical_and', 'np.logical_and', (['target_images', 'pred_images'], {}), '(target_images, pred_images)\n', (5084, 5112), True, 'import numpy as np\n'), ((5184, 5225), 'numpy.logical_or', 'np.logical_or', (['target_images', 'pred_images'], {}), '(target_images, pred_images)\n', (5197, 5225), True, 'import numpy as np\n'), ((2752, 2766), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (2763, 2766), False, 'import torch\n'), ((3190, 3222), 'torch.from_numpy', 'torch.from_numpy', (['one_hot_labels'], {}), '(one_hot_labels)\n', (3206, 3222), False, 'import torch\n'), ((4437, 4469), 'torch.from_numpy', 'torch.from_numpy', (['one_hot_labels'], {}), '(one_hot_labels)\n', (4453, 4469), False, 'import torch\n')] |
# python peripherals
import numpy
# torch
import torch
# Taken from https://github.com/vsitzmann/siren
class Sine(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
# See paper sec. 3.2, final paragraph, and supplement Sec. 1.5 for discussion of factor 30
return torch.sin(input)
# Taken from https://github.com/vsitzmann/siren
def sine_init(m):
with torch.no_grad():
if hasattr(m, 'weight'):
num_input = m.weight.size(-1)
# See supplement Sec. 1.5 for discussion of factor 30
m.weight.uniform_(-numpy.sqrt(6 / num_input) / 30, numpy.sqrt(6 / num_input) / 30)
# Taken from https://github.com/vsitzmann/siren
def first_layer_sine_init(m):
with torch.no_grad():
if hasattr(m, 'weight'):
num_input = m.weight.size(-1)
# See paper sec. 3.2, final paragraph, and supplement Sec. 1.5 for discussion of factor 30
m.weight.uniform_(-1 / num_input, 1 / num_input)
class DeepSignatureCurvatureNet(torch.nn.Module):
def __init__(self, sample_points):
super(DeepSignatureCurvatureNet, self).__init__()
self._regressor = DeepSignatureCurvatureNet._create_regressor(in_features=2 * sample_points)
def forward(self, input):
features = input.reshape([input.shape[0] * input.shape[1], input.shape[2] * input.shape[3]])
output = self._regressor(features).reshape([input.shape[0], input.shape[1], 1])
return output
@staticmethod
def _create_regressor(in_features):
linear_modules = []
in_features = in_features
out_features = 100
p = None
while out_features > 10:
linear_modules.extend(DeepSignatureCurvatureNet._create_hidden_layer(in_features=in_features, out_features=out_features, p=p, use_batch_norm=True, weights_init=None))
linear_modules.extend(DeepSignatureCurvatureNet._create_hidden_layer(in_features=out_features, out_features=out_features, p=p, use_batch_norm=True, weights_init=None))
in_features = out_features
out_features = int(out_features / 2)
linear_modules.append(torch.nn.Linear(in_features=in_features, out_features=1))
return torch.nn.Sequential(*linear_modules)
@staticmethod
def _create_hidden_layer(in_features, out_features, p=None, use_batch_norm=False, weights_init=None):
linear_modules = []
linear_module = torch.nn.Linear(in_features=in_features, out_features=out_features)
linear_modules.append(linear_module)
if use_batch_norm:
linear_modules.append(torch.nn.BatchNorm1d(out_features))
linear_modules.append(Sine())
if p is not None:
linear_modules.append(torch.nn.Dropout(p))
return linear_modules
class DeepSignatureArcLengthNet(torch.nn.Module):
def __init__(self, sample_points, transformation_group_type):
super(DeepSignatureArcLengthNet, self).__init__()
self._regressor = DeepSignatureArcLengthNet._create_regressor(in_features=2 * sample_points, transformation_group_type=transformation_group_type)
def forward(self, input):
features = input.reshape([input.shape[0] * input.shape[1], input.shape[2] * input.shape[3]])
output = self._regressor(features).reshape([input.shape[0], input.shape[1], 1])
return output.abs()
@staticmethod
def _create_regressor(in_features, transformation_group_type):
linear_modules = []
in_features = in_features
if transformation_group_type == 'affine':
out_features = 60
else:
out_features = 100
p = None
while out_features > 10:
linear_modules.extend(DeepSignatureArcLengthNet._create_hidden_layer(in_features=in_features, out_features=out_features, p=p, use_batch_norm=True))
linear_modules.extend(DeepSignatureArcLengthNet._create_hidden_layer(in_features=out_features, out_features=out_features, p=p, use_batch_norm=True))
if transformation_group_type == 'affine':
linear_modules.extend(DeepSignatureArcLengthNet._create_hidden_layer(in_features=out_features, out_features=out_features, p=p, use_batch_norm=True))
in_features = out_features
out_features = int(out_features / 2)
linear_modules.append(torch.nn.Linear(in_features=in_features, out_features=1))
return torch.nn.Sequential(*linear_modules)
@staticmethod
def _create_hidden_layer(in_features, out_features, p=None, use_batch_norm=False):
linear_modules = []
linear_modules.append(torch.nn.Linear(in_features=in_features, out_features=out_features))
if use_batch_norm:
linear_modules.append(torch.nn.BatchNorm1d(out_features))
# linear_modules.append(torch.nn.PReLU())
# linear_modules.append(torch.nn.LeakyReLU())
# linear_modules.append(torch.nn.ReLU())
linear_modules.append(torch.nn.GELU())
# linear_modules.append(Sine())
if p is not None:
linear_modules.append(torch.nn.Dropout(p))
return linear_modules
| [
"torch.nn.Dropout",
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"torch.nn.GELU",
"torch.nn.Linear",
"torch.no_grad",
"torch.sin",
"numpy.sqrt"
] | [((331, 347), 'torch.sin', 'torch.sin', (['input'], {}), '(input)\n', (340, 347), False, 'import torch\n'), ((425, 440), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (438, 440), False, 'import torch\n'), ((767, 782), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (780, 782), False, 'import torch\n'), ((2265, 2301), 'torch.nn.Sequential', 'torch.nn.Sequential', (['*linear_modules'], {}), '(*linear_modules)\n', (2284, 2301), False, 'import torch\n'), ((2479, 2546), 'torch.nn.Linear', 'torch.nn.Linear', ([], {'in_features': 'in_features', 'out_features': 'out_features'}), '(in_features=in_features, out_features=out_features)\n', (2494, 2546), False, 'import torch\n'), ((4478, 4514), 'torch.nn.Sequential', 'torch.nn.Sequential', (['*linear_modules'], {}), '(*linear_modules)\n', (4497, 4514), False, 'import torch\n'), ((2191, 2247), 'torch.nn.Linear', 'torch.nn.Linear', ([], {'in_features': 'in_features', 'out_features': '(1)'}), '(in_features=in_features, out_features=1)\n', (2206, 2247), False, 'import torch\n'), ((4405, 4461), 'torch.nn.Linear', 'torch.nn.Linear', ([], {'in_features': 'in_features', 'out_features': '(1)'}), '(in_features=in_features, out_features=1)\n', (4420, 4461), False, 'import torch\n'), ((4679, 4746), 'torch.nn.Linear', 'torch.nn.Linear', ([], {'in_features': 'in_features', 'out_features': 'out_features'}), '(in_features=in_features, out_features=out_features)\n', (4694, 4746), False, 'import torch\n'), ((5029, 5044), 'torch.nn.GELU', 'torch.nn.GELU', ([], {}), '()\n', (5042, 5044), False, 'import torch\n'), ((2655, 2689), 'torch.nn.BatchNorm1d', 'torch.nn.BatchNorm1d', (['out_features'], {}), '(out_features)\n', (2675, 2689), False, 'import torch\n'), ((2791, 2810), 'torch.nn.Dropout', 'torch.nn.Dropout', (['p'], {}), '(p)\n', (2807, 2810), False, 'import torch\n'), ((4809, 4843), 'torch.nn.BatchNorm1d', 'torch.nn.BatchNorm1d', (['out_features'], {}), '(out_features)\n', (4829, 4843), False, 'import torch\n'), ((5147, 5166), 'torch.nn.Dropout', 'torch.nn.Dropout', (['p'], {}), '(p)\n', (5163, 5166), False, 'import torch\n'), ((646, 671), 'numpy.sqrt', 'numpy.sqrt', (['(6 / num_input)'], {}), '(6 / num_input)\n', (656, 671), False, 'import numpy\n'), ((614, 639), 'numpy.sqrt', 'numpy.sqrt', (['(6 / num_input)'], {}), '(6 / num_input)\n', (624, 639), False, 'import numpy\n')] |
from PIL import Image
import cv2
import numpy as np
import sys
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassifier
import pickle
WIDTH = 310/2
HEIGHT = 568/2
size = (int(WIDTH), int(HEIGHT))
def resize_and_save(img_name):
#try:
main_image = Image.open("images/Fractured Bone/{}".format(img_name))
#except IOError:
#sys.stderr.write("ERROR: Could not open file {}\n".format(img_name))
#return
#exit(1)
#main_image.thumbnail(size, Image.ANTIALIAS)
x= main_image.resize(size, Image.NEAREST)
x.save("images/resized/{}".format(img_name))
def _reshape_img(arr):
#reshape a numpy image and returns a 1-D array
flat_arr=[]
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
for k in range(arr.shape[2]):
flat_arr.append(arr[i][j][k])
return flat_arr
def _create_data(train_img_list, label_list):
inp_arr=[]
for img in train_img_list:
img= cv2.imread(img)
inp_arr.append(_reshape_img(img))
inp_arr= np.array(inp_arr)
return inp_arr,np.array(label_list)
def train_and_save(train_img_list, label_list, model_name):
try:
with open(model_name,"rb") as file:
model= pickle.load(file)
except FileNotFoundError:
in_arr, out_arr= _create_data(train_img_list, label_list)
#model= LogisticRegression(random_state=43,tol=1e-5,max_iter=5000,verbose=1).fit(in_arr,out_arr)
#model = RandomForestClassifier(n_estimators=10, random_state=42).fit(in_arr, out_arr)
model= Ridge(alpha=0.01,tol=0.000001,max_iter=5000,random_state=43).fit(in_arr,out_arr)
with open(model_name,"wb") as file:
pickle.dump(model,file)
return model
def get_model(model_name):
try:
with open(model_name,"rb") as file:
model= pickle.load(file)
return model
except FileNotFoundError:
print("{} doesn't exist. Train and save a model first".format(model_name))
sys.exit(0)
if __name__=="__main__":
for each in range(1,101):
try:
resize_and_save("F{}.JPG".format(each))
except IOError:
try:
resize_and_save("F{}.jpg".format(each))
except IOError:
resize_and_save("F{}.jpeg".format(each))
from train_label import train_label, test_label
train_img_list=[]
train_label_list=[]
for key in train_label.keys():
train_img_list.append("images/resized/"+key+".jpg")
train_label_list.append(train_label[key])
test_img_list=[]
test_label_list=[]
for key in test_label.keys():
test_img_list.append("images/resized/"+key+".jpg")
test_label_list.append(test_label[key])
#in_arr, out_arr= _create_data(train_img_list,label_list)
#print(in_arr.shape)
print("Training started...")
svm_model=train_and_save(train_img_list,train_label_list, "ridge_model")
print("Training finished...")
train_in_arr, train_out_arr= _create_data(train_img_list,train_label_list)
test_in_arr, test_out_arr= _create_data(test_img_list,test_label_list)
print("Training set score: {:.2f}".format(svm_model.score(train_in_arr, train_out_arr)))
print("Test set score: {:.2f}".format(svm_model.score(test_in_arr, test_out_arr)))
| [
"pickle.dump",
"sklearn.linear_model.Ridge",
"train_label.train_label.keys",
"cv2.imread",
"pickle.load",
"numpy.array",
"train_label.test_label.keys",
"sys.exit"
] | [((1211, 1228), 'numpy.array', 'np.array', (['inp_arr'], {}), '(inp_arr)\n', (1219, 1228), True, 'import numpy as np\n'), ((2626, 2644), 'train_label.train_label.keys', 'train_label.keys', ([], {}), '()\n', (2642, 2644), False, 'from train_label import train_label, test_label\n'), ((2820, 2837), 'train_label.test_label.keys', 'test_label.keys', ([], {}), '()\n', (2835, 2837), False, 'from train_label import train_label, test_label\n'), ((1135, 1150), 'cv2.imread', 'cv2.imread', (['img'], {}), '(img)\n', (1145, 1150), False, 'import cv2\n'), ((1249, 1269), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (1257, 1269), True, 'import numpy as np\n'), ((1404, 1421), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (1415, 1421), False, 'import pickle\n'), ((2026, 2043), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (2037, 2043), False, 'import pickle\n'), ((2190, 2201), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2198, 2201), False, 'import sys\n'), ((1880, 1904), 'pickle.dump', 'pickle.dump', (['model', 'file'], {}), '(model, file)\n', (1891, 1904), False, 'import pickle\n'), ((1742, 1802), 'sklearn.linear_model.Ridge', 'Ridge', ([], {'alpha': '(0.01)', 'tol': '(1e-06)', 'max_iter': '(5000)', 'random_state': '(43)'}), '(alpha=0.01, tol=1e-06, max_iter=5000, random_state=43)\n', (1747, 1802), False, 'from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge\n')] |
# Copyright (c) 2020, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of FINN nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
from onnx import helper as oh
import warnings
from finn.core.datatype import DataType
import finn.core.data_layout as DataLayout
from finn.transformation.base import Transformation
from finn.util.basic import get_by_name
from finn.custom_op.registry import getCustomOp
from finn.transformation.infer_shapes import InferShapes
from finn.transformation.infer_datatypes import InferDataTypes
class AbsorbSignBiasIntoMultiThreshold(Transformation):
"""Absorb scalar bias originating from signed int export back into
MultiThreshold and re-evaluate the output datatype."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
# search for (MultiThreshold, Add) pair
node_ind += 1
if (
n.op_type == "MultiThreshold"
and not model.is_fork_node(n)
and not model.is_join_node(n)
):
consumer = model.find_consumer(n.output[0])
if consumer is not None and consumer.op_type == "Add":
mt_node = n
add_node = consumer
threshold_name = mt_node.input[1]
add_weight_name = add_node.input[1]
T = model.get_initializer(threshold_name)
A = model.get_initializer(add_weight_name)
if (A is None) or (T is None):
warnings.warn("Threshold or add bias not constant, skipping")
continue
end_name = add_node.output[0]
# we can only absorb scalar adds
is_scalar = A.ndim == 0 or all(x == 1 for x in A.shape)
if not is_scalar:
continue
bias = A.flatten()[0]
# set MultiThreshold bias property
mt_inst = getCustomOp(mt_node)
bias += mt_inst.get_nodeattr("out_bias")
mt_inst.set_nodeattr("out_bias", bias)
graph_modified = True
# compute new DataType for MultiThreshold output
steps = T.shape[-1]
new_min = bias
new_max = steps + bias
odt = DataType.get_smallest_possible(steps).name.replace(
"UINT", "INT"
)
odt = DataType[odt]
assert odt.allowed(new_max) and odt.allowed(
new_min
), """Could
not compute new MultiThreshold DataType (min = %d max = %d)""" % (
new_min,
new_max,
)
mt_inst.set_nodeattr("out_dtype", odt.name)
# remove Add node, rewire MultiThreshold
graph.node.remove(add_node)
mt_node.output[0] = end_name
# set datatype
model.set_tensor_datatype(end_name, odt)
if graph_modified:
model = model.transform(InferDataTypes())
return (model, graph_modified)
class AbsorbAddIntoMultiThreshold(Transformation):
"""Absorb preceding Add ops into MultiThreshold by updating the threshold
values. Only scalar/1D add vectors can be absorbed."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
node_ind += 1
if (
n.op_type == "Add"
and not model.is_fork_node(n)
and not model.is_join_node(n)
):
consumer = model.find_consumer(n.output[0])
if consumer is not None and consumer.op_type == "MultiThreshold":
add_weight_name = n.input[1]
threshold_name = consumer.input[1]
A = model.get_initializer(add_weight_name)
T = model.get_initializer(threshold_name)
assert A is not None, "Initializer for add weights is not set."
assert T is not None, "Initializer for thresholds is not set."
start_name = n.input[0]
# we can only absorb 0d or 1d adds
is_scalar = A.ndim == 0 or all(x == 1 for x in A.shape)
actual_ndims = len(tuple(filter(lambda x: x > 1, A.shape)))
is_1d = actual_ndims == 1
if is_scalar or is_1d:
Tnew = T - A.reshape(-1, 1)
# Tnew = T - A.reshape(-1, T.shape[1])
# compute new thresholds and set initializer
model.set_initializer(threshold_name, Tnew)
# wire add input directly to MultiThreshold
consumer.input[0] = start_name
# remove the add node
graph.node.remove(n)
graph_modified = True
return (model, graph_modified)
class AbsorbMulIntoMultiThreshold(Transformation):
"""Absorb preceding Mul ops into MultiThreshold by updating the threshold
values. Only *positive* scalar/1D mul vectors can be absorbed."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
node_ind += 1
if (
n.op_type == "Mul"
and not model.is_fork_node(n)
and not model.is_join_node(n)
):
mul_weight_name = n.input[1]
A = model.get_initializer(mul_weight_name)
assert A is not None, "Initializer for mul weights is not set."
is_signed = (A < 0).any()
is_scalar = A.ndim == 0 or all(x == 1 for x in A.shape)
actual_ndims = len(tuple(filter(lambda x: x > 1, A.shape)))
is_1d = actual_ndims == 1
consumer = model.find_consumer(n.output[0])
if consumer is not None and consumer.op_type == "MultiThreshold":
if not is_signed and (is_1d or is_scalar):
threshold_name = consumer.input[1]
T = model.get_initializer(threshold_name)
assert T is not None, "Initializer for thresholds is not set."
start_name = n.input[0]
# compute new thresholds and set initializer
Tnew = T / A.reshape(-1, 1)
# TODO: need to handle negative A values correctly; produce
# mul sign mask and merge into preceding matmul?
model.set_initializer(threshold_name, Tnew)
# wire add input directly to MultiThreshold
consumer.input[0] = start_name
# remove the mul node
graph.node.remove(n)
graph_modified = True
return (model, graph_modified)
class FactorOutMulSignMagnitude(Transformation):
"""Split multiply-by-constant nodes into two multiply-by-constant nodes,
where the first node is a bipolar vector (of signs) and the second is a
vector of magnitudes."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
node_ind += 1
if n.op_type == "Mul":
mul_weight_name = n.input[1]
A = model.get_initializer(mul_weight_name)
assert A is not None, "Initializer for mul weights is not set."
is_scalar = np.prod(A.shape) == 1
actual_ndims = len(tuple(filter(lambda x: x > 1, A.shape)))
is_1d = actual_ndims == 1
is_not_bipolar = (
model.get_tensor_datatype(mul_weight_name) != DataType.BIPOLAR
)
is_signed = (A < 0).any()
if is_signed and (is_scalar or is_1d) and is_not_bipolar:
start_name = n.input[0]
in_shape = model.get_tensor_shape(start_name)
middle_name = model.make_new_valueinfo_name()
model.set_tensor_shape(middle_name, in_shape)
sign_mul_param_name = model.make_new_valueinfo_name()
# create new mul node with sign(A) as the operand
sgn = np.sign(A)
model.set_initializer(sign_mul_param_name, sgn)
model.set_tensor_datatype(sign_mul_param_name, DataType.BIPOLAR)
# replace original mul weight by magnitudes
model.set_initializer(mul_weight_name, np.abs(A))
new_mul = oh.make_node(
"Mul", [start_name, sign_mul_param_name], [middle_name]
)
n.input[0] = middle_name
graph.node.insert(node_ind - 1, new_mul)
graph_modified = True
return (model, graph_modified)
class Absorb1BitMulIntoMatMul(Transformation):
"""Absorb bipolar or binary multiplications into the preciding matrix
multiply."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
node_ind += 1
if n.op_type == "MatMul":
matmul_weight_name = n.input[1]
W = model.get_initializer(matmul_weight_name)
Wdt = model.get_tensor_datatype(matmul_weight_name)
assert W is not None, "Initializer for matmul weights is not set."
consumer = model.find_consumer(n.output[0])
if consumer is not None and consumer.op_type == "Mul":
mul_weight_name = consumer.input[1]
A = model.get_initializer(mul_weight_name)
assert A is not None, "Initializer for mul weights is not set."
is_1bit = model.get_tensor_datatype(mul_weight_name).bitwidth() == 1
if is_1bit:
Wnew = A * W
assert (
Wnew.shape == W.shape
), """Shape of new weights is not
the same as the shape of the weight matrix before."""
check_fxn = np.vectorize(lambda x: Wdt.allowed(x))
# only absorb if permitted by W datatype
if check_fxn(Wnew).all():
model.set_initializer(matmul_weight_name, Wnew)
n.output[0] = consumer.output[0]
graph.node.remove(consumer)
graph_modified = True
return (model, graph_modified)
class Absorb1BitMulIntoConv(Transformation):
"""Absorb bipolar or binary multiplications into the preciding convolution."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
node_ind += 1
if n.op_type == "Conv":
conv_weight_name = n.input[1]
W = model.get_initializer(conv_weight_name)
Wdt = model.get_tensor_datatype(conv_weight_name)
assert W is not None, "Initializer for conv weights is not set."
consumer = model.find_consumer(n.output[0])
if consumer is not None and consumer.op_type == "Mul":
mul_weight_name = consumer.input[1]
A = model.get_initializer(mul_weight_name)
assert A is not None, "Initializer for mul weights is not set."
is_1bit = model.get_tensor_datatype(mul_weight_name).bitwidth() == 1
is_scalar = np.prod(A.shape) == 1
actual_ndims = len(tuple(filter(lambda x: x > 1, A.shape)))
is_1d = actual_ndims == 1
if is_1bit and (is_1d or is_scalar):
# move the mul to the OFM position, since the mul is
# applied on the outputs channelwise or as scalar
Wnew = A.reshape(-1, 1, 1, 1) * W
assert (
Wnew.shape == W.shape
), """Shape of new weights is not
the same as the shape of the conv weights before."""
check_fxn = np.vectorize(lambda x: Wdt.allowed(x))
# only absorb if permitted by W datatype
if check_fxn(Wnew).all():
model.set_initializer(conv_weight_name, Wnew)
n.output[0] = consumer.output[0]
graph.node.remove(consumer)
graph_modified = True
return (model, graph_modified)
class AbsorbTransposeIntoMultiThreshold(Transformation):
"""Change (NHWCTranpose -> MultiThreshold -> NCHWTranspose) to (MultiThreshold)
with NHWC mode."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
node_ind += 1
if n.op_type == "Transpose" and not model.is_fork_node(n):
perms = list(get_by_name(n.attribute, "perm").ints)
if perms == [0, 3, 1, 2]:
mt_cand = model.find_consumer(n.output[0])
if mt_cand.op_type == "MultiThreshold" and not model.is_fork_node(
mt_cand
):
final_t_cand = model.find_consumer(mt_cand.output[0])
if final_t_cand.op_type == "Transpose":
perms = list(
get_by_name(final_t_cand.attribute, "perm").ints
)
if perms == [0, 2, 3, 1]:
mt = getCustomOp(mt_cand)
mt.set_nodeattr("data_layout", "NHWC")
# get rid of tranpose nodes, wire MT directly
mt_cand.input[0] = n.input[0]
mt_cand.output[0] = final_t_cand.output[0]
graph.node.remove(n)
graph.node.remove(final_t_cand)
graph_modified = True
elif final_t_cand.op_type == "Reshape":
oshape = model.get_tensor_shape(final_t_cand.output[0])
if len(oshape) == 2:
# transition to FC part, can still use NHWC
mt = getCustomOp(mt_cand)
mt.set_nodeattr("data_layout", "NHWC")
# get rid of first tranpose node
mt_cand.input[0] = n.input[0]
# fix output shape for MultiThreshold
mt_ishape = model.get_tensor_shape(mt_cand.input[0])
(b, h, w, c) = mt_ishape
assert (
h == 1 and w == 1
), """Untested spatial dim
in conv->fc transition, proceed with caution!"""
model.set_tensor_shape(mt_cand.output[0], mt_ishape)
graph.node.remove(n)
graph_modified = True
if graph_modified:
model = model.transform(InferDataTypes())
return (model, graph_modified)
class AbsorbTransposeIntoFlatten(Transformation):
"""Absorb transpose node into succeeding flatten node, if H=W=1 and the first
dimension stays the same. Can also be applied if flatten is implemented implicitly
by a reshape node with shape [1, -1] and the first input dimension is 1"""
def apply(self, model):
graph = model.graph
graph_modified = False
node_ind = 0
for n in graph.node:
node_ind += 1
if (
n.op_type == "Reshape"
and (model.get_initializer(n.input[1]) == [1, -1]).all()
) or n.op_type == "Flatten":
prod = model.find_producer(n.input[0])
if (
prod is not None
and prod.op_type == "Transpose"
# we ensure that the first dimension is not changed from the
# transpose operation
and get_by_name(prod.attribute, "perm").ints[0] == 0
):
data_layout = model.get_tensor_layout(prod.input[0])
# check for the data layout to interpret input shape correctly
if data_layout is None:
warnings.warn(
"""Data layout for input tensor of Transpose node is not set.
To use AbsorbTransposeIntoFlatten transformation
please set tensor data layout."""
)
continue
elif data_layout == DataLayout.NCHW:
(b, c, h, w) = model.get_tensor_shape(prod.input[0])
# if h=w=1 the transposition can be absorbed, otherwise
# the absorption would lead to an error in the behavior
if h != 1 or w != 1:
continue
# the flatten node from onnx keeps by default the first
# dim and flattens the rest, that is why this transformation
# can only work with b != 1 if the model contains already a
# flatten node and not a reshape node with shape = [1, -1].
# If the first dim of the input tensor is not 1, flatten and
# reshape (with shape = [1, -1]) would lead to different results
if n.op_type == "Reshape" and b != 1:
continue
elif data_layout == DataLayout.NHWC:
(b, h, w, c) = model.get_tensor_shape(prod.input[0])
if h != 1 or w != 1:
continue
if n.op_type == "Reshape" and b != 1:
continue
# create single flatten node and remove obsolete nodes
node = oh.make_node("Flatten", [prod.input[0]], [n.output[0]])
graph.node.remove(n)
graph.node.remove(prod)
graph.node.insert(node_ind, node)
graph_modified = True
if graph_modified:
model = model.transform(InferDataTypes())
return (model, graph_modified)
class AbsorbScalarMulAddIntoTopK(Transformation):
"""Remove mul/add node prior to topk node if the op is scalar. Note that
the TopK output probabilities will change, but the indices won't."""
def apply(self, model):
graph = model.graph
node_ind = 0
graph_modified = False
for n in graph.node:
node_ind += 1
if n.op_type == "TopK":
prod = model.find_producer(n.input[0])
if prod is not None and (prod.op_type in ["Mul", "Add"]):
prod_input = prod.input[0]
param_name = prod.input[1]
A = model.get_initializer(param_name)
if A is None:
warnings.warn("Param is not constant, skipping")
continue
is_scalar = all(x == 1 for x in A.shape)
is_scalar_pos_mul = is_scalar and (prod.op_type == "Mul") and A > 0
is_scalar_add = is_scalar and (prod.op_type == "Add")
if is_scalar_pos_mul or is_scalar_add:
# if the mul is scalar and positive, we can just delete the
# mul node and rewire the top k node. Because the top k node
# works with probabilities and their relation to each other
# the relation doesn't change if every value is multiplied
# with a scalar
graph.node.remove(prod)
n.input[0] = prod_input
# to avoid error the dataype is set to float32
model.set_tensor_datatype(n.input[0], DataType.FLOAT32)
graph_modified = True
if graph_modified:
model = model.transform(InferShapes())
model = model.transform(InferDataTypes())
return (model, graph_modified)
class AbsorbConsecutiveTransposes(Transformation):
"""Remove (Transpose -> Transpose) patterns when the input and output
of the pattern have the same layout."""
def Are_opposite_permutations(self, perms1, perms2):
if len(perms1) != len(perms2):
return False
assert 0 <= max(perms2) < len(perms2), "invalid permutation"
assert 0 <= max(perms1) < len(perms1), "invalid permutation"
for i, p in enumerate(perms2):
if perms1[p] != i:
return False
return True
def apply(self, model):
graph = model.graph
graph_modified = False
for n in graph.node:
if n.op_type == "Transpose":
if model.is_fork_node(n):
next_nodes = model.find_direct_successors(n)
perms1 = list(get_by_name(n.attribute, "perm").ints)
# check if all nodes after fork are opposite transposes
all_opposite_transposes = True
for next_node in next_nodes:
if next_node is not None and next_node.op_type == "Transpose":
perms2 = list(get_by_name(next_node.attribute, "perm").ints)
if not self.Are_opposite_permutations(perms1, perms2):
all_opposite_transposes = False
break
else:
all_opposite_transposes = False
break
if not all_opposite_transposes:
continue
prod = model.find_producer(n.input[0])
for next_node in next_nodes:
# connect next_node's consumer input to n's producer output
# TODO implement this to allow for forks as producers and
# joins as consumers
cons = model.find_consumer(next_node.output[0])
cons.input[0] = prod.output[0]
# remove consumer transpose
graph.node.remove(next_node)
# remove producer transpose
graph.node.remove(n)
graph_modified = True
else:
next_node = model.find_consumer(n.output[0])
if next_node is not None and next_node.op_type == "Transpose":
perms1 = list(get_by_name(n.attribute, "perm").ints)
perms2 = list(get_by_name(next_node.attribute, "perm").ints)
if self.Are_opposite_permutations(perms1, perms2):
# connect next_node's consumer input to n's producer output
# TODO implement this to allow for forks as producers
consumers = model.find_direct_successors(next_node)
prod = model.find_producer(n.input[0])
for cons in consumers:
for cons_in in cons.input:
if cons_in == next_node.output[0]:
prod.output[0] = cons_in
break
# remove both transposes
graph.node.remove(n)
graph.node.remove(next_node)
graph_modified = True
if graph_modified:
model = model.transform(InferDataTypes())
return (model, graph_modified)
| [
"finn.custom_op.registry.getCustomOp",
"onnx.helper.make_node",
"numpy.abs",
"finn.transformation.infer_shapes.InferShapes",
"finn.transformation.infer_datatypes.InferDataTypes",
"numpy.sign",
"finn.util.basic.get_by_name",
"warnings.warn",
"finn.core.datatype.DataType.get_smallest_possible",
"num... | [((4719, 4735), 'finn.transformation.infer_datatypes.InferDataTypes', 'InferDataTypes', ([], {}), '()\n', (4733, 4735), False, 'from finn.transformation.infer_datatypes import InferDataTypes\n'), ((17588, 17604), 'finn.transformation.infer_datatypes.InferDataTypes', 'InferDataTypes', ([], {}), '()\n', (17602, 17604), False, 'from finn.transformation.infer_datatypes import InferDataTypes\n'), ((20894, 20910), 'finn.transformation.infer_datatypes.InferDataTypes', 'InferDataTypes', ([], {}), '()\n', (20908, 20910), False, 'from finn.transformation.infer_datatypes import InferDataTypes\n'), ((22788, 22801), 'finn.transformation.infer_shapes.InferShapes', 'InferShapes', ([], {}), '()\n', (22799, 22801), False, 'from finn.transformation.infer_shapes import InferShapes\n'), ((22839, 22855), 'finn.transformation.infer_datatypes.InferDataTypes', 'InferDataTypes', ([], {}), '()\n', (22853, 22855), False, 'from finn.transformation.infer_datatypes import InferDataTypes\n'), ((26510, 26526), 'finn.transformation.infer_datatypes.InferDataTypes', 'InferDataTypes', ([], {}), '()\n', (26524, 26526), False, 'from finn.transformation.infer_datatypes import InferDataTypes\n'), ((3486, 3506), 'finn.custom_op.registry.getCustomOp', 'getCustomOp', (['mt_node'], {}), '(mt_node)\n', (3497, 3506), False, 'from finn.custom_op.registry import getCustomOp\n'), ((9416, 9432), 'numpy.prod', 'np.prod', (['A.shape'], {}), '(A.shape)\n', (9423, 9432), True, 'import numpy as np\n'), ((10220, 10230), 'numpy.sign', 'np.sign', (['A'], {}), '(A)\n', (10227, 10230), True, 'import numpy as np\n'), ((10548, 10617), 'onnx.helper.make_node', 'oh.make_node', (['"""Mul"""', '[start_name, sign_mul_param_name]', '[middle_name]'], {}), "('Mul', [start_name, sign_mul_param_name], [middle_name])\n", (10560, 10617), True, 'from onnx import helper as oh\n'), ((20594, 20649), 'onnx.helper.make_node', 'oh.make_node', (['"""Flatten"""', '[prod.input[0]]', '[n.output[0]]'], {}), "('Flatten', [prod.input[0]], [n.output[0]])\n", (20606, 20649), True, 'from onnx import helper as oh\n'), ((3014, 3075), 'warnings.warn', 'warnings.warn', (['"""Threshold or add bias not constant, skipping"""'], {}), "('Threshold or add bias not constant, skipping')\n", (3027, 3075), False, 'import warnings\n'), ((10507, 10516), 'numpy.abs', 'np.abs', (['A'], {}), '(A)\n', (10513, 10516), True, 'import numpy as np\n'), ((13675, 13691), 'numpy.prod', 'np.prod', (['A.shape'], {}), '(A.shape)\n', (13682, 13691), True, 'import numpy as np\n'), ((15207, 15239), 'finn.util.basic.get_by_name', 'get_by_name', (['n.attribute', '"""perm"""'], {}), "(n.attribute, 'perm')\n", (15218, 15239), False, 'from finn.util.basic import get_by_name\n'), ((18883, 19116), 'warnings.warn', 'warnings.warn', (['"""Data layout for input tensor of Transpose node is not set.\n To use AbsorbTransposeIntoFlatten transformation\n please set tensor data layout."""'], {}), '(\n """Data layout for input tensor of Transpose node is not set.\n To use AbsorbTransposeIntoFlatten transformation\n please set tensor data layout."""\n )\n', (18896, 19116), False, 'import warnings\n'), ((21692, 21740), 'warnings.warn', 'warnings.warn', (['"""Param is not constant, skipping"""'], {}), "('Param is not constant, skipping')\n", (21705, 21740), False, 'import warnings\n'), ((23747, 23779), 'finn.util.basic.get_by_name', 'get_by_name', (['n.attribute', '"""perm"""'], {}), "(n.attribute, 'perm')\n", (23758, 23779), False, 'from finn.util.basic import get_by_name\n'), ((3882, 3919), 'finn.core.datatype.DataType.get_smallest_possible', 'DataType.get_smallest_possible', (['steps'], {}), '(steps)\n', (3912, 3919), False, 'from finn.core.datatype import DataType\n'), ((15879, 15899), 'finn.custom_op.registry.getCustomOp', 'getCustomOp', (['mt_cand'], {}), '(mt_cand)\n', (15890, 15899), False, 'from finn.custom_op.registry import getCustomOp\n'), ((18591, 18626), 'finn.util.basic.get_by_name', 'get_by_name', (['prod.attribute', '"""perm"""'], {}), "(prod.attribute, 'perm')\n", (18602, 18626), False, 'from finn.util.basic import get_by_name\n'), ((25428, 25460), 'finn.util.basic.get_by_name', 'get_by_name', (['n.attribute', '"""perm"""'], {}), "(n.attribute, 'perm')\n", (25439, 25460), False, 'from finn.util.basic import get_by_name\n'), ((25505, 25545), 'finn.util.basic.get_by_name', 'get_by_name', (['next_node.attribute', '"""perm"""'], {}), "(next_node.attribute, 'perm')\n", (25516, 25545), False, 'from finn.util.basic import get_by_name\n'), ((15709, 15752), 'finn.util.basic.get_by_name', 'get_by_name', (['final_t_cand.attribute', '"""perm"""'], {}), "(final_t_cand.attribute, 'perm')\n", (15720, 15752), False, 'from finn.util.basic import get_by_name\n'), ((16667, 16687), 'finn.custom_op.registry.getCustomOp', 'getCustomOp', (['mt_cand'], {}), '(mt_cand)\n', (16678, 16687), False, 'from finn.custom_op.registry import getCustomOp\n'), ((24092, 24132), 'finn.util.basic.get_by_name', 'get_by_name', (['next_node.attribute', '"""perm"""'], {}), "(next_node.attribute, 'perm')\n", (24103, 24132), False, 'from finn.util.basic import get_by_name\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 5 15:33:27 2019
@author: gptshubham595
"""
import cv2
import matplotlib.pyplot as plot
import numpy as np
import time
def main():
imgp1="C:\\opencv learn machin\\misc\\4.2.01.tiff"
imgp2="C:\\opencv learn machin\\misc\\4.2.05.tiff"
#1-by preserving same colour default
#0-grayscale
img1=cv2.imread(imgp1,1)
img2=cv2.imread(imgp2,1)
#img1=cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)
#img2=cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)
add=img1 + img2
z=0
#50->Intervals
for i in np.linspace(0,1,50):
x=i
y=1-x
output=cv2.addWeighted(img1,x,img2,y,z)
cv2.imshow('Transition',output)
time.sleep(0.1)
if cv2.waitKey(1)==27:
break
#x+y+z=1 for good
#(img1*x +img2*y+z}/(x+y+z)
cv2.destroyAllWindows()
if __name__=="__main__":
main() | [
"cv2.waitKey",
"cv2.imshow",
"cv2.addWeighted",
"time.sleep",
"cv2.imread",
"numpy.linspace",
"cv2.destroyAllWindows"
] | [((369, 389), 'cv2.imread', 'cv2.imread', (['imgp1', '(1)'], {}), '(imgp1, 1)\n', (379, 389), False, 'import cv2\n'), ((398, 418), 'cv2.imread', 'cv2.imread', (['imgp2', '(1)'], {}), '(imgp2, 1)\n', (408, 418), False, 'import cv2\n'), ((597, 618), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(50)'], {}), '(0, 1, 50)\n', (608, 618), True, 'import numpy as np\n'), ((874, 897), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (895, 897), False, 'import cv2\n'), ((659, 695), 'cv2.addWeighted', 'cv2.addWeighted', (['img1', 'x', 'img2', 'y', 'z'], {}), '(img1, x, img2, y, z)\n', (674, 695), False, 'import cv2\n'), ((700, 732), 'cv2.imshow', 'cv2.imshow', (['"""Transition"""', 'output'], {}), "('Transition', output)\n", (710, 732), False, 'import cv2\n'), ((740, 755), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (750, 755), False, 'import time\n'), ((767, 781), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (778, 781), False, 'import cv2\n')] |
import random
import numpy as np
from service import stats
def test_get_values_stats():
"""stats - get values stats"""
random.seed(42)
values = [random.uniform(0,10) for _ in range(105)]
median, mad, q1, q3 = stats.get_values_stats(values)
assert median == np.median(values)
assert 1 < mad < 4
assert q1 == np.percentile(values, 25, interpolation='midpoint')
assert q3 == np.percentile(values, 75, interpolation='midpoint')
np.percentile(np.asarray(range(1, 101)), 25)
def test_get_values_stats_few_values():
"""stats - get values stats few values"""
random.seed(42)
values = [random.uniform(0,10) for _ in range(1)]
median, mad, q1, q3 = stats.get_values_stats(values)
assert median == np.median(values)
assert mad is None
assert q1 is None
assert q3 is None
values = [random.uniform(0, 10) for _ in range(5)]
median, mad, q1, q3 = stats.get_values_stats(values)
assert median == np.median(values)
assert 1 < mad < 4
assert q1 is None
assert q3 is None
| [
"random.uniform",
"numpy.median",
"numpy.percentile",
"random.seed",
"service.stats.get_values_stats"
] | [((129, 144), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (140, 144), False, 'import random\n'), ((227, 257), 'service.stats.get_values_stats', 'stats.get_values_stats', (['values'], {}), '(values)\n', (249, 257), False, 'from service import stats\n'), ((599, 614), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (610, 614), False, 'import random\n'), ((695, 725), 'service.stats.get_values_stats', 'stats.get_values_stats', (['values'], {}), '(values)\n', (717, 725), False, 'from service import stats\n'), ((913, 943), 'service.stats.get_values_stats', 'stats.get_values_stats', (['values'], {}), '(values)\n', (935, 943), False, 'from service import stats\n'), ((159, 180), 'random.uniform', 'random.uniform', (['(0)', '(10)'], {}), '(0, 10)\n', (173, 180), False, 'import random\n'), ((279, 296), 'numpy.median', 'np.median', (['values'], {}), '(values)\n', (288, 296), True, 'import numpy as np\n'), ((337, 388), 'numpy.percentile', 'np.percentile', (['values', '(25)'], {'interpolation': '"""midpoint"""'}), "(values, 25, interpolation='midpoint')\n", (350, 388), True, 'import numpy as np\n'), ((406, 457), 'numpy.percentile', 'np.percentile', (['values', '(75)'], {'interpolation': '"""midpoint"""'}), "(values, 75, interpolation='midpoint')\n", (419, 457), True, 'import numpy as np\n'), ((629, 650), 'random.uniform', 'random.uniform', (['(0)', '(10)'], {}), '(0, 10)\n', (643, 650), False, 'import random\n'), ((747, 764), 'numpy.median', 'np.median', (['values'], {}), '(values)\n', (756, 764), True, 'import numpy as np\n'), ((846, 867), 'random.uniform', 'random.uniform', (['(0)', '(10)'], {}), '(0, 10)\n', (860, 867), False, 'import random\n'), ((965, 982), 'numpy.median', 'np.median', (['values'], {}), '(values)\n', (974, 982), True, 'import numpy as np\n')] |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Datasets imported
#dataset_train for training
#dataset_test for testing
dataset_train = pd.read_csv(path_train)
dataset_test = pd.read_csv(path_test)
#X consists of 3 features
#Y consists of a single output feature
#creates X dataframe for training
dataset_train_x = dataset_train.drop(['y'], axis=1)
#creates Y dataframe for training
dataset_train_y = dataset_train[['y']]
dataset_train.head() #shows first lines of data in the dataset
dataset_test.head()
#asserting additional information on training and test sets
dataset_train.info()
dataset_test.info()
#evaluate general statistical parameters
dataset_train.describe()
dataset_test.describe()
#input plots
#x1 - same approach for other variables
array = np.array(dataset_train.x1.values)
n, histo, pat = plt.hist(array,100,normed=1)
mu = np.mean(array)
sigma = np.std(array)
plt.plot(histo, mlab.normpdf(histo,mu,sigma))
plt.title('Fig.1. Histogram of variable x1 - Train')
plt.show()
#plotting the probability distribution function of input variables allows the better understanding of the variable behavior
#input space
#3d plot of two chosen input variables and output
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(dataset_train.x1, dataset_train.x2, dataset_train.y, '.')
plt.title('Fig.2. Input variables space')
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"pandas.read_csv",
"numpy.std",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array"
] | [((168, 191), 'pandas.read_csv', 'pd.read_csv', (['path_train'], {}), '(path_train)\n', (179, 191), True, 'import pandas as pd\n'), ((208, 230), 'pandas.read_csv', 'pd.read_csv', (['path_test'], {}), '(path_test)\n', (219, 230), True, 'import pandas as pd\n'), ((822, 855), 'numpy.array', 'np.array', (['dataset_train.x1.values'], {}), '(dataset_train.x1.values)\n', (830, 855), True, 'import numpy as np\n'), ((873, 903), 'matplotlib.pyplot.hist', 'plt.hist', (['array', '(100)'], {'normed': '(1)'}), '(array, 100, normed=1)\n', (881, 903), True, 'import matplotlib.pyplot as plt\n'), ((908, 922), 'numpy.mean', 'np.mean', (['array'], {}), '(array)\n', (915, 922), True, 'import numpy as np\n'), ((932, 945), 'numpy.std', 'np.std', (['array'], {}), '(array)\n', (938, 945), True, 'import numpy as np\n'), ((996, 1048), 'matplotlib.pyplot.title', 'plt.title', (['"""Fig.1. Histogram of variable x1 - Train"""'], {}), "('Fig.1. Histogram of variable x1 - Train')\n", (1005, 1048), True, 'import matplotlib.pyplot as plt\n'), ((1050, 1060), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1058, 1060), True, 'import matplotlib.pyplot as plt\n'), ((1262, 1274), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1272, 1274), True, 'import matplotlib.pyplot as plt\n'), ((1377, 1418), 'matplotlib.pyplot.title', 'plt.title', (['"""Fig.2. Input variables space"""'], {}), "('Fig.2. Input variables space')\n", (1386, 1418), True, 'import matplotlib.pyplot as plt\n')] |
# Standard library
import os, abc
import pickle
import numpy as np
from copy import deepcopy
# Third-party
from scipy.integrate import quad
from scipy.interpolate import interp1d
from astropy.table import Table
from astropy import units as u
# Project
from .. import MIST_PATH
from ..util import check_random_state, check_units
from ..log import logger
from ..filters import *
from .imf import sample_imf, build_galaxy, imf_dict, IMFIntegrator
from .isochrones import MISTIsochrone
__all__ = ['SSP', 'MISTSSP', 'constant_sb_stars_per_pix']
class StellarPopulation(metaclass=abc.ABCMeta):
"""
Stellar population base class.
Parameters
----------
distance : float or `~astropy.units.Quantity`, optional
Distance to source. If float is given, the units are assumed
to be `~astropy.units.Mpc`. Default distance is 10 `~astropy.units.pc`
(i.e., the mags are in absolute units).
imf : str, optional
The initial stellar mass function. Default is `'kroupa'`.
"""
def __init__(self, distance=10.0 * u.pc, imf='kroupa', imf_kw={}):
self.imf = imf
self.imf_kw = imf_kw
self.distance = check_units(distance, 'Mpc')
def build_pop(self, num_stars=None, **kwargs):
"""Build stellar population."""
return NotImplementedError()
@property
def dist_mod(self):
"""The distance modulus."""
return 5 * np.log10(self.distance.to('pc').value) - 5
@property
def num_pops(self):
"""
The number of simple stellar populations that composes this pop.
"""
return 1 if type(self.isochrone) != list else len(self.isochrone)
@property
def total_initial_live_mass(self):
"""Total initial stellar mass in solar units."""
return self.initial_masses.sum() * u.M_sun
@property
def num_stars(self):
"""Number stars in population."""
return len(self.star_masses)
@property
def abs_mag_table(self):
"""Absolute magnitudes in a `~astropy.table.Table` object."""
return Table(self.abs_mags)
@property
def mag_table(self):
"""Apparent magnitudes in a `~astropy.table.Table` object."""
_mags = {}
for filt in self.filters:
_mags[filt] = self.star_mags(filt)
return Table(_mags)
def to_pickle(self, file_name):
"""Pickle stellar population object."""
pkl_file = open(file_name, 'wb')
pickle.dump(self, pkl_file)
pkl_file.close()
@staticmethod
def from_pickle(file_name):
"""Load pickle of stellar population object."""
pkl_file = open(file_name, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data
def _remnants_factor(self, **kwargs):
"""
Correction factor to account for stellar remnants in the final mass.
The mass in luminous stars is given by M_total * factor.
"""
m_without_remnants = self.isochrone.ssp_surviving_mass(
self.imf, add_remnants=False, **kwargs)
m_with_remnants = self.isochrone.ssp_surviving_mass(
self.imf, add_remnants=True, **kwargs)
factor = m_without_remnants / m_with_remnants
return factor
def copy(self):
return deepcopy(self)
def set_distance(self, distance):
"""
Change the distance to the stellar population.
Parameters
----------
distance : float or `~astropy.units.Quantity`
Distance to source. If float is given, the units are assumed
to be `~astropy.units.Mpc`.
"""
self.distance = check_units(distance, 'Mpc')
def star_mags(self, bandpass, select=None):
"""
Get the stellar apparent magnitudes.
Parameters
----------
bandpass : str
Filter of observation. Must be a filter in the given
photometric system(s).
select : `~numpy.ndarray`, optional
Boolean mask for selecting stars (True for stars to include).
Returns
-------
mags : `~numpy.ndarray`
The stellar apparent magnitudes in the given bandpass.
"""
mags = self.abs_mags[bandpass] + self.dist_mod
if select is not None:
mags = mags[select]
return mags
def mag_integrated_component(self, bandpass):
"""
Get the magnitude of the integrated component of the population if
it exists.
Parameters
----------
bandpass : str
Filter of observation. Must be a filter in the given
photometric system(s).
Returns
-------
mag : float
The integrated magnitude if it exists. Otherwise None is returned.
"""
if hasattr(self, 'integrated_abs_mags'):
mag = self.integrated_abs_mags[bandpass] + self.dist_mod
else:
mag = None
return mag
def sbf_mag(self, bandpass):
"""
Calculate the apparent SBF magnitude of the stellar population.
Parameters
----------
bandpass : str
Filter of observation. Must be a filter in the given
photometric system(s).
Returns
-------
mbar : float
The apparent SBF magnitude of the stellar population in the given
bandpass.
"""
integrated = self.mag_integrated_component(bandpass)
if integrated is not None:
f_int = 10**(-0.4*integrated)
log_dddd = 4 * np.log10(self.distance.to('cm').value)
ff_int = 10**(self._integrated_log_lumlum[bandpass] - log_dddd)
else:
f_int = 0.0
ff_int = 0.0
f_i = 10**(-0.4 * (self.star_mags(bandpass)))
ff = np.sum(f_i**2) + ff_int
f = np.sum(f_i) + f_int
mbar = -2.5 * np.log10(ff / f)
return mbar
def integrated_color(self, blue, red, select=None):
"""
Calculate the population's integrated color.
Parameters
----------
blue : str
The blue bandpass. Must be a filter in the
given photometric system(s).
red : str
The red bandpass. Must be a filter in the
given photometric system(s).
select : `~numpy.ndarray`, optional
Boolean mask for selecting stars (True for stars to include).
Returns
-------
color : float
The integrated color.
"""
blue_int = self.mag_integrated_component(blue)
if select is None and blue_int is not None:
f_blue_int = 10**(-0.4*blue_int)
f_red_int = 10**(-0.4*self.mag_integrated_component(red))
else:
f_blue_int = 0.0
f_red_int = 0.0
blue_mag = self.star_mags(blue, select)
F_blue = np.sum(10**(-0.4 * blue_mag)) + f_blue_int
red_mag = self.star_mags(red, select)
F_red = np.sum(10**(-0.4 * red_mag)) + f_red_int
color = -2.5 * np.log10(F_blue / F_red)
return color
def mean_mag(self, bandpass, select=None):
"""
Calculate the population's mean magnitude.
Parameters
----------
bandpass : str
Filter of observation. Must be a filter in the given
photometric system(s).
select : `~numpy.ndarray`, optional
Boolean mask for selecting stars (True for stars to include).
Returns
-------
mag : float
The mean magnitude in the given bandpass.
"""
integrated = self.mag_integrated_component(bandpass)
if select is None and integrated is not None:
f_int = 10**(-0.4*integrated)
n_int = self.num_stars_integrated
else:
f_int = 0.0
n_int = 0.0
mags = self.star_mags(bandpass, select)
mean_flux = ((10**(-0.4*mags)).sum() + f_int) / (len(mags) + n_int)
mag = -2.5 * np.log10(mean_flux)
return mag
def total_mag(self, bandpass, select=None):
"""
Calculate the population's total magnitude.
Parameters
----------
bandpass : str
Filter of observation. Must be a filter in the given
photometric system(s).
select : `~numpy.ndarray`, optional
Boolean mask for selecting stars (True for stars to include).
Returns
-------
mag : float
The total magnitude in the given bandpass.
"""
integrated = self.mag_integrated_component(bandpass)
if select is None and integrated is not None:
f_int = 10**(-0.4*integrated)
else:
f_int = 0.0
mags = self.star_mags(bandpass, select)
total_flux = (10**(-0.4*mags)).sum() + f_int
mag = -2.5 * np.log10(total_flux)
return mag
class SSP(StellarPopulation):
"""
Generic Simple Stellar Population (SSP).
.. note::
You must give `total_mass` *or* `num_stars`.
Parameters
----------
isochrone : `~artpop.stars.Isochrone`
Isochrone object.
num_stars : int or `None`
Number of stars in source. If `None`, then must give `total_mass`.
total_mass : float or `~astropy.units.Quantity` or `None`
Stellar mass of the source. If `None`, then must give `num_stars`. This
mass accounts for stellar remnants when ``add_remnants = True``, which
means the actual sampled mass will be less than the given value. If
float is given, the units are assumed to be solar masses.
distance : float or `~astropy.units.Quantity`, optional
Distance to source. If float is given, the units are assumed
to be `~astropy.units.Mpc`. Default distance is 10 `~astropy.units.pc`.
mag_limit : float, optional
Only sample individual stars that are brighter than this magnitude. All
fainter stars will be combined into an integrated component. Otherwise,
all stars in the population will be sampled. You must also give the
`mag_limit_band` if you use this parameter.
mag_limit_band : str, optional
Bandpass of the limiting magnitude. You must give this parameter if
you use the `mag_limit` parameter.
imf : str, optional
The initial stellar mass function. Default is `'kroupa'`.
imf_kw : dict, optional
Optional keyword arguments for sampling the stellar mass function.
mass_tolerance : float, optional
Tolerance in the fractional difference between the input mass and the
final mass of the population. The parameter is only used when
`total_mass` is given.
add_remnants : bool, optional
If True (default), apply scaling factor to total mass to account for
stellar remnants in the form of white dwarfs, neutron stars,
and black holes.
random_state : `None`, int, list of ints, or `~numpy.random.RandomState`
If `None`, return the `~numpy.random.RandomState` singleton used by
``numpy.random``. If `int`, return a new `~numpy.random.RandomState`
instance seeded with the `int`. If `~numpy.random.RandomState`,
return it. Otherwise raise ``ValueError``.
"""
def __init__(self, isochrone, num_stars=None, total_mass=None,
distance=10*u.pc, mag_limit=None, mag_limit_band=None,
imf='kroupa', imf_kw={}, mass_tolerance=0.01,
add_remnants=True, random_state=None):
super(SSP, self).__init__(distance=distance, imf=imf, imf_kw=imf_kw)
self.isochrone = isochrone
self.filters = isochrone.filters
self.mag_limit = mag_limit
self.mag_limit_band = mag_limit_band
self.rng = check_random_state(random_state)
self.build_pop(num_stars, total_mass, mass_tolerance, add_remnants)
self._r = {'M_star': f'{self.total_mass.value:.2e} M_sun'}
def build_pop(self, num_stars=None, total_mass=None, mass_tolerance=0.01,
add_remnants=True):
"""
Build the stellar population. You must give `total_mass`
*or* `num_stars` as an argument.
Parameters
----------
num_stars : int or `None`
Number of stars in source. If `None`, then must give `total_mass`.
total_mass : float or `~astropy.units.Quantity` or `None`
Stellar mass of the source. If `None`, then must give `num_stars`.
This mass accounts for stellar remnants when ``add_remnants = True``
which means the actual sampled mass will be less than the given
value. If float is given, the units are assumed to be solar masses.
mass_tolerance : float, optional
Tolerance in the fractional difference between the input mass and
the final mass of the population. The parameter is only used when
`total_mass` is given.
add_remnants : bool, optional
If True (default), apply scaling factor to total mass to account
for stellar remnants in the form of white dwarfs, neutron stars,
and black holes.
"""
# get isochrone object and info
m_min, m_max = self.isochrone.m_min, self.isochrone.m_max
imf_kw = self.imf_kw.copy()
iso = self.isochrone
imfint = IMFIntegrator(self.imf, m_min=m_min, m_max=m_max)
remnants_factor = self._remnants_factor() if add_remnants else 1.0
# calculate the fraction of stars we will sample
m_lim, f_num_sampled, f_mass_sampled = self.sample_fraction(
self.mag_limit,
self.mag_limit_band
)
# the limiting mass is min mass if 100% of stars will be sampled
self.has_integrated_component = m_lim != m_min
m_min = m_lim
self.sampled_mass_lower_limit = m_lim
self.frac_num_sampled = f_num_sampled
self.frac_mass_sampled = f_mass_sampled
if num_stars is not None:
# sample imf
num_stars_sample = int(num_stars * f_num_sampled)
self.initial_masses = sample_imf(
num_stars_sample, m_min=m_min, m_max=m_max, imf=self.imf,
random_state=self.rng, imf_kw=imf_kw)
# star masses are interpolated from "actual" mass
self.star_masses = iso.interpolate('mact', self.initial_masses)
# will be < num_stars if f_num_sampled < 1.0.
self.num_stars_integrated = int(num_stars - len(self.star_masses))
self.sampled_mass = self.star_masses.sum()
elif total_mass is not None:
total_mass = check_units(total_mass, 'Msun').to('Msun').value
# calculate fraction of mass that remains after mass loss
mass_loss = iso.ssp_surviving_mass(
imf=self.imf, m_min=iso.m_min, m_max=iso.m_max,
add_remnants=False)
# we sample less mass than total_mass to account for
# stellar remnants and the sample fraction
sampled_mass = total_mass * remnants_factor * f_mass_sampled
# we increase the sampled mass to account for mass loss
sampled_mass /= mass_loss
# sample initial masses
mean_mass = imfint.m_integrate(m_min, m_max)
mean_mass /= imfint.integrate(m_min, m_max)
num_stars_iter = int(mass_tolerance * sampled_mass / mean_mass)
self.initial_masses = build_galaxy(
sampled_mass, m_min=m_min, m_max=m_max, imf=self.imf,
random_state=self.rng, num_stars_iter=num_stars_iter, **imf_kw)
# star masses are interpolated from "actual" mass
self.star_masses = iso.interpolate('mact', self.initial_masses)
self.sampled_mass = self.star_masses.sum()
# calculate approximate number of stars in integrated component
factor = (1 - f_num_sampled) / f_num_sampled
self.num_stars_integrated = int(self.num_stars * factor)
else:
raise Exception('you must give total mass *or* number of stars')
self.abs_mags = {}
for filt in self.filters:
self.abs_mags[filt] = iso.interpolate(filt, self.initial_masses)
# update masses and mags if there is an integrated component
if self.has_integrated_component:
# find evolved stars that are fainter than mag_limit
sampled_mags = self.abs_mags[self.mag_limit_band] + self.dist_mod
evolved_faint = sampled_mags > self.mag_limit
evolved_mags = {}
for filt in self.filters:
evolved_mags[filt] = self.abs_mags[filt][evolved_faint]
self.abs_mags[filt] = self.abs_mags[filt][~evolved_faint]
# calculate evolved mass and update integrated star count
evolved_mass = self.star_masses[evolved_faint].sum()
self.num_stars_integrated += evolved_faint.sum()
# update initial and sampled masses
self.initial_masses = self.initial_masses[~evolved_faint]
self.star_masses = self.star_masses[~evolved_faint]
self.sampled_mass = self.star_masses.sum()
# calculate normalized IMF weights
w = iso.imf_weights(self.imf, m_max_norm=m_max, norm_type='number')
_, arg = iso.nearest_mini(m_lim)
# update total mass
num_stars = self.num_stars_integrated + self.num_stars
_mass = num_stars * np.sum(iso.mact[:arg] * w[:arg])
_mass += evolved_mass
self.total_mass = (self.sampled_mass + _mass) / remnants_factor
# updated integrated absolute magnitudes and luminosity variances
self.integrated_abs_mags = {}
self._integrated_log_lumlum = {}
for filt in iso.filters:
mag = iso.mag_table[filt]
flux = num_stars * np.sum(10**(-0.4 * mag[: arg]) * w[: arg])
flux += np.sum(10**(-0.4 * evolved_mags[filt]))
self.integrated_abs_mags[filt] = -2.5 * np.log10(flux)
ff = num_stars * np.sum(10**(-0.8 * mag[: arg]) * w[: arg])
ff += np.sum(10**(-0.8 * evolved_mags[filt]))
log_dddd = 4 * np.log10((10 * u.pc).to('cm').value)
self._integrated_log_lumlum[filt] = np.log10(ff) + log_dddd
else:
# calculate total_mass with stellar remnants
self.total_mass = self.sampled_mass / remnants_factor
self.live_star_mass = self.total_mass * remnants_factor
self.ssp_labels = np.ones(len(self.star_masses), dtype=int)
self.total_mass *= u.Msun
self.sampled_mass *= u.Msun
self.live_star_mass *= u.Msun
for attr in ['eep', 'log_L', 'log_Teff']:
if hasattr(iso, attr):
if getattr(iso, attr) is not None:
vals_interp = iso.interpolate(attr, self.initial_masses)
setattr(self, attr, vals_interp)
def sample_fraction(self, mag_limit, mag_limit_band):
"""
Calculate the fraction of stars by mass and number that will be
sampled with the give limiting magnitude.
Parameters
----------
mag_limit : float, optional
Only sample individual stars that are brighter than this magnitude.
mag_limit_band : str, optional
Bandpass of the limiting magnitude.
Returns
-------
m_lim : float
Initial stellar mass associated with `mag_limit`.
f_num_sampled : float
Fraction of stars that will be sampled by number.
f_mass_sampled : float
Fraction of stars that will be sampled by mass.
"""
iso = self.isochrone
imfint = IMFIntegrator(self.imf, iso.m_min, iso.m_max)
m_lim = iso.m_min
f_num_sampled = 1.0
f_mass_sampled = 1.0
if mag_limit is not None:
if mag_limit_band is None:
raise Exception('Must give bandpass of limiting magnitude.')
mags = iso.mag_table[mag_limit_band] + self.dist_mod
if mag_limit < mags.max() and mag_limit > mags.min():
m_lim = iso.mag_to_mass(
mag_limit - self.dist_mod, mag_limit_band).min()
f_num_sampled = imfint.integrate(m_lim, iso.m_max, True)
f_mass_sampled = imfint.m_integrate(m_lim, iso.m_max, True)
else:
logger.warning(f'mag_lim = {mag_limit} is outside mag range.')
return m_lim, f_num_sampled, f_mass_sampled
def __add__(self, ssp):
assert StellarPopulation in ssp.__class__.__mro__, 'invalid type(s)'
assert self.filters == ssp.filters, 'must have same filters'
assert self.distance == ssp.distance, 'SSPs must have same distance'
new = deepcopy(self)
if type(new.isochrone) != list:
new.isochrone = [new.isochrone]
if type(ssp.isochrone) != list:
new.isochrone.append(ssp.isochrone)
else:
new.isochrone.extend(ssp.isochrone)
if not hasattr(new, 'ssp_total_masses'):
new.ssp_total_masses = [new.total_mass]
if not hasattr(ssp, 'ssp_total_masses'):
ssp.ssp_total_masses = [ssp.total_mass]
new.ssp_total_masses.extend(ssp.ssp_total_masses)
if not hasattr(new, 'ssp_total_num_stars'):
_n = new.num_stars + new.num_stars_integrated
new.ssp_total_num_stars = [_n]
if not hasattr(ssp, 'ssp_total_num_stars'):
_n = ssp.num_stars + ssp.num_stars_integrated
ssp.ssp_total_num_stars = [_n]
new.ssp_total_num_stars.extend(ssp.ssp_total_num_stars)
new.total_mass = new.total_mass + ssp.total_mass
new.sampled_mass = new.sampled_mass + ssp.sampled_mass
new.live_star_mass = new.live_star_mass + ssp.live_star_mass
new.frac_mass_sampled = new.sampled_mass / new.live_star_mass
new_num_stars_total = new.num_stars + new.num_stars_integrated
ssp_num_stars_total = ssp.num_stars + ssp.num_stars_integrated
total_num_stars = new_num_stars_total + ssp_num_stars_total
new.num_stars_integrated += ssp.num_stars_integrated
new.initial_masses = np.concatenate(
[new.initial_masses, ssp.initial_masses])
new.star_masses = np.concatenate([new.star_masses, ssp.star_masses])
new.frac_num_sampled = new.num_stars / total_num_stars
new.ssp_num_fracs = []
new.ssp_mass_fracs = []
for n, m in zip(new.ssp_total_num_stars, new.ssp_total_masses):
new.ssp_num_fracs.append(n / total_num_stars)
new.ssp_mass_fracs.append(m / new.total_mass)
# Loop over optional attributes.
# Both SSPs must have the arrtibute to add them.
for attr in ['eep', 'log_L', 'log_Teff']:
if hasattr(new, attr) and hasattr(ssp, attr):
new_attr = getattr(new, attr)
ssp_attr = getattr(ssp, attr)
setattr(new, attr, np.concatenate([new_attr, ssp_attr]))
new_label = np.ones(len(ssp.star_masses), dtype=int)
new_label *= len(new.isochrone)
new.ssp_labels = np.concatenate([new.ssp_labels, new_label])
if hasattr(new, 'log_age'):
if type(new.log_age) != list:
new.log_age = [new.log_age]
new.log_age.append(ssp.log_age)
if hasattr(new, 'feh'):
if type(new.feh) != list:
new.feh = [new.feh]
new.feh.append(ssp.feh)
for filt in new.filters:
_mags = [new.abs_mags[filt], ssp.abs_mags[filt]]
new.abs_mags[filt] = np.concatenate(_mags)
if new.has_integrated_component and ssp.has_integrated_component:
new_flux = 10**(-0.4 * new.integrated_abs_mags[filt])
ssp_flux = 10**(-0.4 * ssp.integrated_abs_mags[filt])
flux = new_flux + ssp_flux
new.integrated_abs_mags[filt] = -2.5 * np.log10(flux)
new_lumlum = 10**new._integrated_log_lumlum[filt]
ssp_lumlum = 10**ssp._integrated_log_lumlum[filt]
log_lumlum = np.log10(new_lumlum + ssp_lumlum)
new._integrated_log_lumlum[filt] = log_lumlum
elif ssp.has_integrated_component:
new.integrated_abs_magw[filt] = ssp.integrated_abs_mags[filt]
log_lumlum = ssp._integrated_log_lumlum[filt]
new._integrated_log_lumlum[filt] = log_lumlum
return CompositePopulation(new)
def __repr__(self):
r = [f'{k} = {v}' for k, v in self._r.items()]
t = 'Simple Stellar Population\n-------------------------\n'
return t + '\n'.join(r)
class MISTSSP(SSP):
"""
MIST Simple Stellar Population.
.. note::
You must give `total_mass` *or* `num_stars`.
Parameters
----------
log_age : float
Log (base 10) of the simple stellar population age in years.
feh : float
Metallicity [Fe/H] of the simple stellar population.
phot_system : str or list-like
Name of the photometric system(s).
num_stars : int or `None`
Number of stars in source. If `None`, then must give `total_mass`.
total_mass : float or `~astropy.units.Quantity` or `None`
Stellar mass of the source. If `None`, then must give `num_stars`. This
mass accounts for stellar remnants when ``add_remnants = True``, which
means the actual sampled mass will be less than the given value. If
float is given, the units are assumed to be solar masses.
distance : float or `~astropy.units.Quantity`, optional
Distance to source. If float is given, the units are assumed
to be `~astropy.units.Mpc`. Default distance is 10 `~astropy.units.pc`.
mag_limit : float, optional
Only sample individual stars that are brighter than this magnitude. All
fainter stars will be combined into an integrated component. Otherwise,
all stars in the population will be sampled. You must also give the
`mag_limit_band` if you use this parameter.
mag_limit_band : str, optional
Bandpass of the limiting magnitude. You must give this parameter if
you use the `mag_limit` parameter.
imf : str, optional
The initial stellar mass function. Default is `'kroupa'`.
mist_path : str, optional
Path to MIST isochrone grids. Use this if you want to use a different
path from the `MIST_PATH` environment variable.
imf_kw : dict, optional
Optional keyword arguments for sampling the stellar mass function.
mass_tolerance : float, optional
Tolerance in the fractional difference between the input mass and the
final mass of the population. The parameter is only used when
`total_mass` is given.
add_remnants : bool, optional
If True (default), apply scaling factor to total mass to account for
stellar remnants in the form of white dwarfs, neutron stars,
and black holes.
random_state : `None`, int, list of ints, or `~numpy.random.RandomState`
If `None`, return the `~numpy.random.RandomState` singleton used by
``numpy.random``. If `int`, return a new `~numpy.random.RandomState`
instance seeded with the `int`. If `~numpy.random.RandomState`,
return it. Otherwise raise ``ValueError``.
"""
phases = ['PMS', 'MS', 'giants', 'RGB', 'CHeB', 'AGB',
'EAGB', 'TPAGB', 'postAGB', 'WDCS']
def __init__(self, log_age, feh, phot_system, num_stars=None,
total_mass=None, distance=10*u.pc, mag_limit=None,
mag_limit_band=None, imf='kroupa', mist_path=MIST_PATH,
imf_kw={}, mass_tolerance=0.05, add_remnants=True,
random_state=None, **kwargs):
self.feh = feh
self.log_age = log_age
self.phot_system = phot_system
self.mist_path = mist_path
_iso = MISTIsochrone(log_age, feh, phot_system, mist_path, **kwargs)
super(MISTSSP, self).__init__(
isochrone=_iso,
num_stars=num_stars,
total_mass=total_mass,
distance=distance,
mag_limit=mag_limit,
mag_limit_band=mag_limit_band,
imf=imf,
imf_kw=imf_kw,
mass_tolerance=mass_tolerance,
add_remnants=add_remnants,
random_state=random_state
)
self._r.update({'log(age/yr)': self.log_age,
'[Fe/H]': self.feh,
'photometric system': self.phot_system})
def select_phase(self, phase):
"""
Generate stellar evolutionary phase mask. The mask will be `True` for
sources that are in the give phase according to the MIST EEPs.
Parameters
----------
phase : str
Evolutionary phase to select. Options are 'all', 'MS', 'giants',
'RGB', 'CHeB', 'AGB', 'EAGB', 'TPAGB', 'postAGB', or 'WDCS'.
Returns
-------
mask : `~numpy.ndarray`
Mask that is `True` for stars in input phase and `False` otherwise.
Notes
-----
The MIST EEP phases were taken from Table II: Primary Equivalent
Evolutionary Points (EEPs):
http://waps.cfa.harvard.edu/MIST/README_tables.pdf
"""
if phase == 'all':
mask = np.ones_like(self.eep, dtype=bool)
elif phase == 'PMS':
mask = self.eep < 202
elif phase == 'MS':
mask = (self.eep >= 202) & (self.eep < 454)
elif phase == 'giants':
mask = (self.eep >= 454) & (self.eep < 1409)
elif phase == 'RGB':
mask = (self.eep >= 454) & (self.eep <= 605)
elif phase == 'CHeB':
mask = (self.eep > 605) & (self.eep < 707)
elif phase == 'AGB':
mask = (self.eep >= 707) & (self.eep < 1409)
elif phase == 'EAGB':
mask = (self.eep >= 707) & (self.eep < 808)
elif phase == 'TPAGB':
mask = (self.eep >= 808) & (self.eep < 1409)
elif phase == 'postAGB':
mask = (self.eep >= 1409) & (self.eep <= 1710)
elif phase == 'WDCS':
mask = self.eep > 1710
else:
raise Exception('Uh, what phase u want?')
return mask
def get_star_phases(self):
"""Returns the stellar phases (as defined by the MIST EEPs)."""
phase_list = ['PMS', 'MS', 'RGB', 'CHeB', 'EAGB',
'TPAGB', 'postAGB', 'WDCS']
star_phases = np.array([''] * self.num_stars, dtype='<U8')
for phase in phase_list:
star_phases[self.select_phase(phase)] = phase
return star_phases
class CompositePopulation(SSP):
"""
Composite stellar populations.
"""
def __init__(self, pop):
for name, attr in pop.__dict__.items():
setattr(self, name, attr)
def __repr__(self):
num_fracs = self.ssp_num_fracs
mass_fracs = self.ssp_mass_fracs
r = {'N_pops': self.num_pops,
'M_star': f'{self.total_mass.value:.2e} M_sun',
'number fractions': [f'{p * 100:.2f}%' for p in num_fracs],
'mass fractions': [f'{p * 100:.2f}%' for p in mass_fracs]}
if hasattr(self, 'log_age'):
r['log(age/yr)'] = self.log_age
if hasattr(self, 'feh'):
r['[Fe/H]'] = self.feh
if hasattr(self, 'phot_system'):
r['photometric system'] = self.phot_system
r = [f'{k} = {v}' for k, v in r.items()]
t = 'Composite Population\n--------------------\n'
return t + '\n'.join(r)
def constant_sb_stars_per_pix(sb, mean_mag, distance=10*u.pc, pixel_scale=0.2):
"""
Calculate the number of stars per pixel for a uniform
distribution (i.e., constant surface brightness) of stars.
Parameters
----------
sb : float
Surface brightness of stellar population.
mean_mag : float
Mean stellar magnitude of the stellar population.
distance : float or `~astropy.units.Quantity`
Distance to source. If float is given, the units are assumed
to be `~astropy.units.Mpc`.
pixel_scale : float or `~astropy.units.Quantity`, optional
The pixel scale of the mock image. If a float is given, the units will
be assumed to be `~astropy.units.arcsec` per `~astropy.units.pixels`.
Returns
-------
num_stars_per_pix : float
The number of stars per pixel.
"""
distance = check_units(distance, 'Mpc').to('pc').value
pixel_scale = check_units(pixel_scale, u.arcsec / u.pixel).value
dist_mod = 5 * np.log10(distance) - 5
num_stars_per_arsec_sq = 10**(0.4 * (mean_mag + dist_mod - sb))
num_stars_per_pix = num_stars_per_arsec_sq * pixel_scale**2
return num_stars_per_pix
| [
"copy.deepcopy",
"pickle.dump",
"astropy.table.Table",
"numpy.sum",
"numpy.ones_like",
"pickle.load",
"numpy.array",
"numpy.log10",
"numpy.concatenate"
] | [((2085, 2105), 'astropy.table.Table', 'Table', (['self.abs_mags'], {}), '(self.abs_mags)\n', (2090, 2105), False, 'from astropy.table import Table\n'), ((2331, 2343), 'astropy.table.Table', 'Table', (['_mags'], {}), '(_mags)\n', (2336, 2343), False, 'from astropy.table import Table\n'), ((2478, 2505), 'pickle.dump', 'pickle.dump', (['self', 'pkl_file'], {}), '(self, pkl_file)\n', (2489, 2505), False, 'import pickle\n'), ((2694, 2715), 'pickle.load', 'pickle.load', (['pkl_file'], {}), '(pkl_file)\n', (2705, 2715), False, 'import pickle\n'), ((3310, 3324), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (3318, 3324), False, 'from copy import deepcopy\n'), ((21084, 21098), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (21092, 21098), False, 'from copy import deepcopy\n'), ((22527, 22583), 'numpy.concatenate', 'np.concatenate', (['[new.initial_masses, ssp.initial_masses]'], {}), '([new.initial_masses, ssp.initial_masses])\n', (22541, 22583), True, 'import numpy as np\n'), ((22623, 22673), 'numpy.concatenate', 'np.concatenate', (['[new.star_masses, ssp.star_masses]'], {}), '([new.star_masses, ssp.star_masses])\n', (22637, 22673), True, 'import numpy as np\n'), ((23488, 23531), 'numpy.concatenate', 'np.concatenate', (['[new.ssp_labels, new_label]'], {}), '([new.ssp_labels, new_label])\n', (23502, 23531), True, 'import numpy as np\n'), ((30963, 31007), 'numpy.array', 'np.array', (["([''] * self.num_stars)"], {'dtype': '"""<U8"""'}), "([''] * self.num_stars, dtype='<U8')\n", (30971, 31007), True, 'import numpy as np\n'), ((5863, 5879), 'numpy.sum', 'np.sum', (['(f_i ** 2)'], {}), '(f_i ** 2)\n', (5869, 5879), True, 'import numpy as np\n'), ((5899, 5910), 'numpy.sum', 'np.sum', (['f_i'], {}), '(f_i)\n', (5905, 5910), True, 'import numpy as np\n'), ((5941, 5957), 'numpy.log10', 'np.log10', (['(ff / f)'], {}), '(ff / f)\n', (5949, 5957), True, 'import numpy as np\n'), ((6944, 6975), 'numpy.sum', 'np.sum', (['(10 ** (-0.4 * blue_mag))'], {}), '(10 ** (-0.4 * blue_mag))\n', (6950, 6975), True, 'import numpy as np\n'), ((7049, 7079), 'numpy.sum', 'np.sum', (['(10 ** (-0.4 * red_mag))'], {}), '(10 ** (-0.4 * red_mag))\n', (7055, 7079), True, 'import numpy as np\n'), ((7113, 7137), 'numpy.log10', 'np.log10', (['(F_blue / F_red)'], {}), '(F_blue / F_red)\n', (7121, 7137), True, 'import numpy as np\n'), ((8079, 8098), 'numpy.log10', 'np.log10', (['mean_flux'], {}), '(mean_flux)\n', (8087, 8098), True, 'import numpy as np\n'), ((8948, 8968), 'numpy.log10', 'np.log10', (['total_flux'], {}), '(total_flux)\n', (8956, 8968), True, 'import numpy as np\n'), ((23969, 23990), 'numpy.concatenate', 'np.concatenate', (['_mags'], {}), '(_mags)\n', (23983, 23990), True, 'import numpy as np\n'), ((29781, 29815), 'numpy.ones_like', 'np.ones_like', (['self.eep'], {'dtype': 'bool'}), '(self.eep, dtype=bool)\n', (29793, 29815), True, 'import numpy as np\n'), ((33072, 33090), 'numpy.log10', 'np.log10', (['distance'], {}), '(distance)\n', (33080, 33090), True, 'import numpy as np\n'), ((17675, 17707), 'numpy.sum', 'np.sum', (['(iso.mact[:arg] * w[:arg])'], {}), '(iso.mact[:arg] * w[:arg])\n', (17681, 17707), True, 'import numpy as np\n'), ((18166, 18207), 'numpy.sum', 'np.sum', (['(10 ** (-0.4 * evolved_mags[filt]))'], {}), '(10 ** (-0.4 * evolved_mags[filt]))\n', (18172, 18207), True, 'import numpy as np\n'), ((18375, 18416), 'numpy.sum', 'np.sum', (['(10 ** (-0.8 * evolved_mags[filt]))'], {}), '(10 ** (-0.8 * evolved_mags[filt]))\n', (18381, 18416), True, 'import numpy as np\n'), ((24483, 24516), 'numpy.log10', 'np.log10', (['(new_lumlum + ssp_lumlum)'], {}), '(new_lumlum + ssp_lumlum)\n', (24491, 24516), True, 'import numpy as np\n'), ((18099, 18141), 'numpy.sum', 'np.sum', (['(10 ** (-0.4 * mag[:arg]) * w[:arg])'], {}), '(10 ** (-0.4 * mag[:arg]) * w[:arg])\n', (18105, 18141), True, 'import numpy as np\n'), ((18262, 18276), 'numpy.log10', 'np.log10', (['flux'], {}), '(flux)\n', (18270, 18276), True, 'import numpy as np\n'), ((18310, 18352), 'numpy.sum', 'np.sum', (['(10 ** (-0.8 * mag[:arg]) * w[:arg])'], {}), '(10 ** (-0.8 * mag[:arg]) * w[:arg])\n', (18316, 18352), True, 'import numpy as np\n'), ((18535, 18547), 'numpy.log10', 'np.log10', (['ff'], {}), '(ff)\n', (18543, 18547), True, 'import numpy as np\n'), ((23323, 23359), 'numpy.concatenate', 'np.concatenate', (['[new_attr, ssp_attr]'], {}), '([new_attr, ssp_attr])\n', (23337, 23359), True, 'import numpy as np\n'), ((24307, 24321), 'numpy.log10', 'np.log10', (['flux'], {}), '(flux)\n', (24315, 24321), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 19:26:41 2018
@author: damodara
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 12:31:33 2018
@author: damodara
"""
import numpy as np
import utilstransport
import importlib
importlib.reload(utilstransport)
import pylab as pl
import matplotlib.pyplot as plt
import dnn
from scipy.spatial.distance import cdist
import ot
seed=1985
np.random.seed(seed)
#%% data generation
n =10000
ntest=30000
nz=.3
d=2
p=3
theta=0.8
dataset='3gauss'
X,y=utilstransport.get_dataset(dataset,n,nz)
Xtest,ytest=utilstransport.get_dataset(dataset,ntest,nz)
rindex = np.random.permutation(np.shape(Xtest)[0])
Xtest = Xtest[rindex,:]
ytest = ytest[rindex]
rindex = np.random.permutation(np.shape(X)[0])
X = X[rindex,:]
y = y[rindex]
print('Angle='+str(theta*180./np.pi))
rotation = np.array([[np.cos(theta),np.sin(theta)],
[-np.sin(theta),np.cos(theta)]])
Xtest=np.dot(Xtest,rotation.T)
nbnoise=0
if nbnoise:
X=np.hstack((X,np.random.randn(n,nbnoise)))
Xtest=np.hstack((Xtest,np.random.randn(ntest,nbnoise)))
vals=np.unique(y)
nbclass=len(vals)
Y=np.zeros((len(y),len(vals)))
Y0=np.zeros((len(y),len(vals)))
YT=np.zeros((len(ytest),len(vals)))
YT0=np.zeros((len(ytest),len(vals)))
for i,val in enumerate(vals):
Y[:,i]=2*((y==val)-.5)
Y0[:,i]=(y==val)
YT[:,i]=2*((ytest==val)-.5)
YT0[:,i]=(ytest==val)
#%% visu dataset
if 1:
i1=0
i2=1;
pl.figure(1)
pl.clf()
# plot 3D relations
#t1=pl.plot(X[y==1,i1],X[y==1,i2] , 'b+') #s=WiniScaled[0:N1],
#t2=pl.plot(X[y==-1,i1], X[y==-1,i2], 'rx')
pl.subplot(2,2,1)
pl.scatter(X[:,i1],X[:,i2],c=y)
pl.title('Source data')
pl.subplot(2,2,2)
pl.scatter(Xtest[:,i1],Xtest[:,i2],c=ytest)
pl.title('Target data')
#%%
source_traindata, source_trainlabel_cat = X, Y0
target_traindata, target_trainlabel_cat = Xtest, YT0
#%%
n_class = nbclass
n_dim = np.shape(source_traindata)
optim = dnn.keras.optimizers.SGD(lr=0.01)
#%%
def feat_ext(main_input, l2_weight=0.0):
net = dnn.Dense(500, activation='relu', name='fe')(main_input)
net = dnn.Dense(100, activation='relu', name='feat_ext')(net)
return net
def classifier(model_input, nclass, l2_weight=0.0):
net = dnn.Dense(100, activation='relu', name='cl')(model_input)
net = dnn.Dense(nclass, activation='softmax', name='cl_output')(net)
return net
#%%
def make_trainable(net, val):
net.trainable = val
for l in net.layers:
l.trainable = val
#%% Feature extraction model
main_input = dnn.Input(shape=(n_dim[1],))
fe = feat_ext(main_input)
fe_size=fe.get_shape().as_list()[1]
fe_model = dnn.Model(main_input, fe, name= 'fe_model')
# Classifier model
cl_input = dnn.Input(shape =(fe.get_shape().as_list()[1],))
net = classifier(cl_input , n_class)
cl_model = dnn.Model(cl_input, net, name ='classifier')
#%% source model
ms = dnn.Input(shape=(n_dim[1],))
fes = feat_ext(ms)
nets = classifier(fes,n_class)
source_model = dnn.Model(ms, nets)
source_model.compile(optimizer=optim, loss='categorical_crossentropy', metrics=['accuracy'])
source_model.fit(source_traindata, source_trainlabel_cat, batch_size=128, epochs=10)
source_acc = source_model.evaluate(source_traindata, source_trainlabel_cat)
target_acc = source_model.evaluate(target_traindata, target_trainlabel_cat)
print("source acc", source_acc)
print("target acc", target_acc)
#%% Target model
main_input = dnn.Input(shape=(n_dim[1],))
ffe=fe_model(main_input)
net = cl_model(ffe)
#con_cat = dnn.concatenate([net, ffe ], axis=1)
model = dnn.Model(inputs=main_input, outputs=[net, ffe])
model.set_weights(source_model.get_weights())
#%% Target model loss and fit function
optim = dnn.keras.optimizers.SGD(lr=0.001,momentum=0.9, decay=0.0001, nesterov=True)
class jdot_align(object):
def __init__(self, model, batch_size, n_class, optim, allign_loss=1.0, tar_cl_loss=1.0, verbose=1):
self.model = model
self.batch_size = batch_size
self.n_class= n_class
self.optimizer= optim
self.gamma=dnn.K.zeros(shape=(self.batch_size, self.batch_size))
self.train_cl =dnn.K.variable(tar_cl_loss)
self.train_algn=dnn.K.variable(allign_loss)
self.source_m = dnn.K.variable(1.)
self.verbose = verbose
# target classification L2 loss
def classifier_l2_loss(y_true, y_pred):
'''
update the classifier based on L2 loss in the target domain
1:batch_size - is source samples
batch_size:end - is target samples
self.gamma - is the optimal transport plan
'''
# source true labels
ys = y_true[:batch_size,:]
# target prediction
ypred_t = y_pred[batch_size:,:]
# L2 distance
dist = dnn.K.reshape(dnn.K.sum(dnn.K.square(ys),1), (-1,1))
dist += dnn.K.reshape(dnn.K.sum(dnn.K.square(ypred_t),1), (1,-1))
dist -= 2.0*dnn.K.dot(ys, dnn.K.transpose(ypred_t))
# JDOT classification loss
loss = dnn.K.sum(self.gamma*dist)
return self.train_cl*loss
self.classifier_l2_loss = classifier_l2_loss
def classifier_cat_loss(y_true, y_pred):
'''
classifier loss based on categorical cross entropy in the target domain
1:batch_size - is source samples
batch_size:end - is target samples
self.gamma - is the optimal transport plan
'''
# source true labels
ys = y_true[:batch_size,:]
# target prediction
ypred_t = y_pred[batch_size:,:]
# source_ypred = y_pred[:batch_size,:]
# source_loss = dnn.K.sum(dnn.K.categorical_crossentropy(ys, source_ypred))
# categorical cross entropy loss
ypred_t = dnn.K.log(ypred_t)
# loss calculation based on double sum (sum_ij (ys^i, ypred_t^j))
loss = -dnn.K.dot(ys, dnn.K.transpose(ypred_t))
# return self.train_cl*(dnn.K.sum(self.gamma * loss)+ source_loss)
return self.train_cl*(dnn.K.sum(self.gamma * loss))
self.classifier_cat_loss = classifier_cat_loss
def L2_dist(x,y):
'''
compute the squared L2 distance between two matrics
'''
dist = dnn.K.reshape(dnn.K.sum(dnn.K.square(x),1), (-1,1))
dist += dnn.K.reshape(dnn.K.sum(dnn.K.square(y),1), (1,-1))
dist -= 2.0*dnn.K.dot(x, dnn.K.transpose(y))
return dist
def align_loss(y_true, y_pred):
'''
source and target alignment loss in the intermediate layers of the target model
allignment is performed in the target model (both source and target features are from targte model)
y-true - is dummy value( that is full of zeros)
y-pred - is the value of intermediate layers in the target model
1:batch_size - is source samples
batch_size:end - is target samples
'''
# source domain features
gs = y_pred[:batch_size,:]
# target domain features
gt = y_pred[batch_size:,:]
gdist = L2_dist(gs,gt)
# loss = dnn.K.sum(self.gamma*(gdist+fdist))
loss = dnn.K.sum(self.gamma*(gdist))
return self.train_algn*loss
self.align_loss= align_loss
def fit(self, source_traindata, ys_label, target_traindata, n_iter=1000):
'''
ys_label - source data true labels
'''
n_iter = 1000
ns = source_traindata.shape[0]
nt= target_traindata.shape[0]
method='sinkhorn' # for optimal transport
reg =0.01 # for sinkhorn
alpha=0.00001
self.model.compile(optimizer= optim, loss =[self.classifier_cat_loss, self.align_loss])
for i in range(500):
# p = float(i) / 500.0
# lr = 0.01 / (1. + 10 * p)**0.75
# dnn.K.set_value(self.model.optimizer.lr, lr)
# fixing f and g, and computing optimal transport plan (gamma)
s_ind = np.random.choice(ns, self.batch_size)
t_ind = np.random.choice(nt,self.batch_size)
xs_batch, ys = source_traindata[s_ind], ys_label[s_ind]
xt_batch = target_traindata[t_ind]
l_dummy = np.zeros_like(ys)
g_dummy = np.zeros((2*batch_size, fe_size))
s = xs_batch.shape
# concat of source and target samples and prediction
modelpred = self.model.predict(np.vstack((xs_batch, xt_batch)))
# intermediate features
gs_batch = modelpred[1][:batch_size, :]
gt_batch = modelpred[1][batch_size:, :]
# softmax prediction of target samples
ft_pred = modelpred[0][batch_size:,:]
C0 = cdist(gs_batch, gt_batch, metric='sqeuclidean')
C1 = cdist(ys, ft_pred, metric='sqeuclidean')
C= alpha*C0+C1
# transportation metric
if method == 'emd':
gamma=ot.emd(ot.unif(gs_batch.shape[0]),ot.unif(gt_batch.shape[0]),C)
elif method =='sinkhorn':
gamma=ot.sinkhorn(ot.unif(gs_batch.shape[0]),ot.unif(gt_batch.shape[0]),C,reg)
# update the computed gamma
dnn.K.set_value(self.gamma, gamma)
# activate the classifier loss
# dnn.K.set_value(self.train_cl,1.0)
# dnn.K.set_value(self.source_m,0.0)
# dnn.K.set_value(self.train_algn,1.0)
data = np.vstack((xs_batch, xt_batch))
hist= self.model.train_on_batch([data], [np.vstack((ys,l_dummy)), g_dummy])
if self.verbose:
print ('cl_loss ={:f}, fe_loss ={:f}'.format(hist[1], hist[2]))
def predict(self, data):
ypred = self.model.predict(data)
return ypred
def evaluate(self, data, label):
ypred = self.model.predict(data)
score = np.mean(np.argmax(label,1)==np.argmax(ypred[0],1))
return score
#%% target model training
batch_size=500
al_model = jdot_align(model, batch_size, n_class, optim)
al_model.fit(source_traindata, source_trainlabel_cat, target_traindata)
#%% accuracy assesment
acc = al_model.evaluate(target_traindata, target_trainlabel_cat)
tarmodel_sacc = al_model.evaluate(source_traindata, source_trainlabel_cat)
print("target domain acc", acc)
print("trained on target, source acc", tarmodel_sacc)
#%% feature ext
def feature_extraction(model, data, out_layer_num=-2, out_layer_name=None):
'''
extract the features from the pre-trained model
inp_layer_num - input layer
out_layer_num -- from which layer to extract the features
out_layer_name -- name of the layer to extract the features
'''
if out_layer_name is None:
intermediate_layer_model = dnn.Model(inputs=model.layers[0].input,
outputs=model.layers[out_layer_num].output)
intermediate_output = intermediate_layer_model.predict(data)
else:
intermediate_layer_model = dnn.Model(inputs=model.layers[0].input,
outputs=model.get_layer(out_layer_name).output)
intermediate_output = intermediate_layer_model.predict(data)
return intermediate_output
#%%
smodel_source_feat = feature_extraction(source_model, source_traindata[:1000,],
out_layer_name='feat_ext')
smodel_target_feat = feature_extraction(source_model, target_traindata[:1000,],
out_layer_name='feat_ext')
#%% intermediate layers of source and target domain for TSNE plot of target model
subset = 1000
al_sourcedata = model.predict(source_traindata[:subset,])[1]
al_targetdata = model.predict(target_traindata[:subset,])[1]
#%%
def tsne_plot(xs, xt, xs_label, xt_label, subset=True, title=None, pname=None):
num_test=1000
if subset:
combined_imgs = np.vstack([xs[0:num_test, :], xt[0:num_test, :]])
combined_labels = np.vstack([xs_label[0:num_test, :],xt_label[0:num_test, :]])
combined_labels = combined_labels.astype('int')
combined_domain = np.vstack([np.zeros((num_test,1)),np.ones((num_test,1))])
from sklearn.manifold import TSNE
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=3000)
source_only_tsne = tsne.fit_transform(combined_imgs)
plt.figure()
plt.scatter(source_only_tsne[:num_test,0], source_only_tsne[:num_test,1], c=combined_labels[:num_test].argmax(1), marker='o', label='source')
plt.scatter(source_only_tsne[num_test:,0], source_only_tsne[num_test:,1], c=combined_labels[num_test:].argmax(1),marker='+',label='target')
plt.legend(loc='best')
plt.title(title)
#%%
title = 'tsne plot of source and target data with source model'
tsne_plot(smodel_source_feat, smodel_target_feat, source_trainlabel_cat, target_trainlabel_cat, title=title)
title = 'tsne plot of source and target data with target model'
tsne_plot(al_sourcedata, al_targetdata, source_trainlabel_cat, target_trainlabel_cat, title=title)
#plt.figure(num=7)
#plt.scatter(al_sourcedata[:,0], al_sourcedata[:,1], c=y, alpha=0.9)
#plt.scatter(al_targetdata[:,0], al_targetdata[:,1], c=ytest, cmap='cool', alpha=0.4)
| [
"matplotlib.pyplot.title",
"dnn.K.set_value",
"numpy.random.seed",
"dnn.K.sum",
"numpy.argmax",
"numpy.ones",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.sin",
"pylab.figure",
"dnn.K.square",
"dnn.K.transpose",
"utilstransport.get_dataset",
"numpy.unique",
"pylab.title",
"numpy.z... | [((249, 281), 'importlib.reload', 'importlib.reload', (['utilstransport'], {}), '(utilstransport)\n', (265, 281), False, 'import importlib\n'), ((416, 436), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (430, 436), True, 'import numpy as np\n'), ((538, 580), 'utilstransport.get_dataset', 'utilstransport.get_dataset', (['dataset', 'n', 'nz'], {}), '(dataset, n, nz)\n', (564, 580), False, 'import utilstransport\n'), ((594, 640), 'utilstransport.get_dataset', 'utilstransport.get_dataset', (['dataset', 'ntest', 'nz'], {}), '(dataset, ntest, nz)\n', (620, 640), False, 'import utilstransport\n'), ((991, 1016), 'numpy.dot', 'np.dot', (['Xtest', 'rotation.T'], {}), '(Xtest, rotation.T)\n', (997, 1016), True, 'import numpy as np\n'), ((1163, 1175), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (1172, 1175), True, 'import numpy as np\n'), ((2043, 2069), 'numpy.shape', 'np.shape', (['source_traindata'], {}), '(source_traindata)\n', (2051, 2069), True, 'import numpy as np\n'), ((2079, 2112), 'dnn.keras.optimizers.SGD', 'dnn.keras.optimizers.SGD', ([], {'lr': '(0.01)'}), '(lr=0.01)\n', (2103, 2112), False, 'import dnn\n'), ((2698, 2726), 'dnn.Input', 'dnn.Input', ([], {'shape': '(n_dim[1],)'}), '(shape=(n_dim[1],))\n', (2707, 2726), False, 'import dnn\n'), ((2803, 2845), 'dnn.Model', 'dnn.Model', (['main_input', 'fe'], {'name': '"""fe_model"""'}), "(main_input, fe, name='fe_model')\n", (2812, 2845), False, 'import dnn\n'), ((2978, 3021), 'dnn.Model', 'dnn.Model', (['cl_input', 'net'], {'name': '"""classifier"""'}), "(cl_input, net, name='classifier')\n", (2987, 3021), False, 'import dnn\n'), ((3047, 3075), 'dnn.Input', 'dnn.Input', ([], {'shape': '(n_dim[1],)'}), '(shape=(n_dim[1],))\n', (3056, 3075), False, 'import dnn\n'), ((3144, 3163), 'dnn.Model', 'dnn.Model', (['ms', 'nets'], {}), '(ms, nets)\n', (3153, 3163), False, 'import dnn\n'), ((3598, 3626), 'dnn.Input', 'dnn.Input', ([], {'shape': '(n_dim[1],)'}), '(shape=(n_dim[1],))\n', (3607, 3626), False, 'import dnn\n'), ((3732, 3780), 'dnn.Model', 'dnn.Model', ([], {'inputs': 'main_input', 'outputs': '[net, ffe]'}), '(inputs=main_input, outputs=[net, ffe])\n', (3741, 3780), False, 'import dnn\n'), ((3877, 3954), 'dnn.keras.optimizers.SGD', 'dnn.keras.optimizers.SGD', ([], {'lr': '(0.001)', 'momentum': '(0.9)', 'decay': '(0.0001)', 'nesterov': '(True)'}), '(lr=0.001, momentum=0.9, decay=0.0001, nesterov=True)\n', (3901, 3954), False, 'import dnn\n'), ((1537, 1549), 'pylab.figure', 'pl.figure', (['(1)'], {}), '(1)\n', (1546, 1549), True, 'import pylab as pl\n'), ((1555, 1563), 'pylab.clf', 'pl.clf', ([], {}), '()\n', (1561, 1563), True, 'import pylab as pl\n'), ((1711, 1730), 'pylab.subplot', 'pl.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (1721, 1730), True, 'import pylab as pl\n'), ((1734, 1769), 'pylab.scatter', 'pl.scatter', (['X[:, i1]', 'X[:, i2]'], {'c': 'y'}), '(X[:, i1], X[:, i2], c=y)\n', (1744, 1769), True, 'import pylab as pl\n'), ((1771, 1794), 'pylab.title', 'pl.title', (['"""Source data"""'], {}), "('Source data')\n", (1779, 1794), True, 'import pylab as pl\n'), ((1802, 1821), 'pylab.subplot', 'pl.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (1812, 1821), True, 'import pylab as pl\n'), ((1825, 1872), 'pylab.scatter', 'pl.scatter', (['Xtest[:, i1]', 'Xtest[:, i2]'], {'c': 'ytest'}), '(Xtest[:, i1], Xtest[:, i2], c=ytest)\n', (1835, 1872), True, 'import pylab as pl\n'), ((1874, 1897), 'pylab.title', 'pl.title', (['"""Target data"""'], {}), "('Target data')\n", (1882, 1897), True, 'import pylab as pl\n'), ((13026, 13086), 'sklearn.manifold.TSNE', 'TSNE', ([], {'perplexity': '(30)', 'n_components': '(2)', 'init': '"""pca"""', 'n_iter': '(3000)'}), "(perplexity=30, n_components=2, init='pca', n_iter=3000)\n", (13030, 13086), False, 'from sklearn.manifold import TSNE\n'), ((13150, 13162), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13160, 13162), True, 'import matplotlib.pyplot as plt\n'), ((13460, 13482), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (13470, 13482), True, 'import matplotlib.pyplot as plt\n'), ((13488, 13504), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (13497, 13504), True, 'import matplotlib.pyplot as plt\n'), ((673, 688), 'numpy.shape', 'np.shape', (['Xtest'], {}), '(Xtest)\n', (681, 688), True, 'import numpy as np\n'), ((775, 786), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (783, 786), True, 'import numpy as np\n'), ((2175, 2219), 'dnn.Dense', 'dnn.Dense', (['(500)'], {'activation': '"""relu"""', 'name': '"""fe"""'}), "(500, activation='relu', name='fe')\n", (2184, 2219), False, 'import dnn\n'), ((2243, 2293), 'dnn.Dense', 'dnn.Dense', (['(100)'], {'activation': '"""relu"""', 'name': '"""feat_ext"""'}), "(100, activation='relu', name='feat_ext')\n", (2252, 2293), False, 'import dnn\n'), ((2385, 2429), 'dnn.Dense', 'dnn.Dense', (['(100)'], {'activation': '"""relu"""', 'name': '"""cl"""'}), "(100, activation='relu', name='cl')\n", (2394, 2429), False, 'import dnn\n'), ((2454, 2511), 'dnn.Dense', 'dnn.Dense', (['nclass'], {'activation': '"""softmax"""', 'name': '"""cl_output"""'}), "(nclass, activation='softmax', name='cl_output')\n", (2463, 2511), False, 'import dnn\n'), ((4236, 4289), 'dnn.K.zeros', 'dnn.K.zeros', ([], {'shape': '(self.batch_size, self.batch_size)'}), '(shape=(self.batch_size, self.batch_size))\n', (4247, 4289), False, 'import dnn\n'), ((4314, 4341), 'dnn.K.variable', 'dnn.K.variable', (['tar_cl_loss'], {}), '(tar_cl_loss)\n', (4328, 4341), False, 'import dnn\n'), ((4367, 4394), 'dnn.K.variable', 'dnn.K.variable', (['allign_loss'], {}), '(allign_loss)\n', (4381, 4394), False, 'import dnn\n'), ((4420, 4439), 'dnn.K.variable', 'dnn.K.variable', (['(1.0)'], {}), '(1.0)\n', (4434, 4439), False, 'import dnn\n'), ((11540, 11628), 'dnn.Model', 'dnn.Model', ([], {'inputs': 'model.layers[0].input', 'outputs': 'model.layers[out_layer_num].output'}), '(inputs=model.layers[0].input, outputs=model.layers[out_layer_num]\n .output)\n', (11549, 11628), False, 'import dnn\n'), ((12689, 12738), 'numpy.vstack', 'np.vstack', (['[xs[0:num_test, :], xt[0:num_test, :]]'], {}), '([xs[0:num_test, :], xt[0:num_test, :]])\n', (12698, 12738), True, 'import numpy as np\n'), ((12766, 12827), 'numpy.vstack', 'np.vstack', (['[xs_label[0:num_test, :], xt_label[0:num_test, :]]'], {}), '([xs_label[0:num_test, :], xt_label[0:num_test, :]])\n', (12775, 12827), True, 'import numpy as np\n'), ((891, 904), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (897, 904), True, 'import numpy as np\n'), ((905, 918), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (911, 918), True, 'import numpy as np\n'), ((964, 977), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (970, 977), True, 'import numpy as np\n'), ((1065, 1092), 'numpy.random.randn', 'np.random.randn', (['n', 'nbnoise'], {}), '(n, nbnoise)\n', (1080, 1092), True, 'import numpy as np\n'), ((1122, 1153), 'numpy.random.randn', 'np.random.randn', (['ntest', 'nbnoise'], {}), '(ntest, nbnoise)\n', (1137, 1153), True, 'import numpy as np\n'), ((5284, 5312), 'dnn.K.sum', 'dnn.K.sum', (['(self.gamma * dist)'], {}), '(self.gamma * dist)\n', (5293, 5312), False, 'import dnn\n'), ((6119, 6137), 'dnn.K.log', 'dnn.K.log', (['ypred_t'], {}), '(ypred_t)\n', (6128, 6137), False, 'import dnn\n'), ((7670, 7699), 'dnn.K.sum', 'dnn.K.sum', (['(self.gamma * gdist)'], {}), '(self.gamma * gdist)\n', (7679, 7699), False, 'import dnn\n'), ((8525, 8562), 'numpy.random.choice', 'np.random.choice', (['ns', 'self.batch_size'], {}), '(ns, self.batch_size)\n', (8541, 8562), True, 'import numpy as np\n'), ((8584, 8621), 'numpy.random.choice', 'np.random.choice', (['nt', 'self.batch_size'], {}), '(nt, self.batch_size)\n', (8600, 8621), True, 'import numpy as np\n'), ((8790, 8807), 'numpy.zeros_like', 'np.zeros_like', (['ys'], {}), '(ys)\n', (8803, 8807), True, 'import numpy as np\n'), ((8831, 8866), 'numpy.zeros', 'np.zeros', (['(2 * batch_size, fe_size)'], {}), '((2 * batch_size, fe_size))\n', (8839, 8866), True, 'import numpy as np\n'), ((9332, 9379), 'scipy.spatial.distance.cdist', 'cdist', (['gs_batch', 'gt_batch'], {'metric': '"""sqeuclidean"""'}), "(gs_batch, gt_batch, metric='sqeuclidean')\n", (9337, 9379), False, 'from scipy.spatial.distance import cdist\n'), ((9412, 9452), 'scipy.spatial.distance.cdist', 'cdist', (['ys', 'ft_pred'], {'metric': '"""sqeuclidean"""'}), "(ys, ft_pred, metric='sqeuclidean')\n", (9417, 9452), False, 'from scipy.spatial.distance import cdist\n'), ((9910, 9944), 'dnn.K.set_value', 'dnn.K.set_value', (['self.gamma', 'gamma'], {}), '(self.gamma, gamma)\n', (9925, 9944), False, 'import dnn\n'), ((10175, 10206), 'numpy.vstack', 'np.vstack', (['(xs_batch, xt_batch)'], {}), '((xs_batch, xt_batch))\n', (10184, 10206), True, 'import numpy as np\n'), ((950, 963), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (956, 963), True, 'import numpy as np\n'), ((6392, 6420), 'dnn.K.sum', 'dnn.K.sum', (['(self.gamma * loss)'], {}), '(self.gamma * loss)\n', (6401, 6420), False, 'import dnn\n'), ((9021, 9052), 'numpy.vstack', 'np.vstack', (['(xs_batch, xt_batch)'], {}), '((xs_batch, xt_batch))\n', (9030, 9052), True, 'import numpy as np\n'), ((10637, 10656), 'numpy.argmax', 'np.argmax', (['label', '(1)'], {}), '(label, 1)\n', (10646, 10656), True, 'import numpy as np\n'), ((10657, 10679), 'numpy.argmax', 'np.argmax', (['ypred[0]', '(1)'], {}), '(ypred[0], 1)\n', (10666, 10679), True, 'import numpy as np\n'), ((12922, 12945), 'numpy.zeros', 'np.zeros', (['(num_test, 1)'], {}), '((num_test, 1))\n', (12930, 12945), True, 'import numpy as np\n'), ((12945, 12967), 'numpy.ones', 'np.ones', (['(num_test, 1)'], {}), '((num_test, 1))\n', (12952, 12967), True, 'import numpy as np\n'), ((5051, 5067), 'dnn.K.square', 'dnn.K.square', (['ys'], {}), '(ys)\n', (5063, 5067), False, 'import dnn\n'), ((5125, 5146), 'dnn.K.square', 'dnn.K.square', (['ypred_t'], {}), '(ypred_t)\n', (5137, 5146), False, 'import dnn\n'), ((5198, 5222), 'dnn.K.transpose', 'dnn.K.transpose', (['ypred_t'], {}), '(ypred_t)\n', (5213, 5222), False, 'import dnn\n'), ((6252, 6276), 'dnn.K.transpose', 'dnn.K.transpose', (['ypred_t'], {}), '(ypred_t)\n', (6267, 6276), False, 'import dnn\n'), ((6658, 6673), 'dnn.K.square', 'dnn.K.square', (['x'], {}), '(x)\n', (6670, 6673), False, 'import dnn\n'), ((6731, 6746), 'dnn.K.square', 'dnn.K.square', (['y'], {}), '(y)\n', (6743, 6746), False, 'import dnn\n'), ((6797, 6815), 'dnn.K.transpose', 'dnn.K.transpose', (['y'], {}), '(y)\n', (6812, 6815), False, 'import dnn\n'), ((9641, 9667), 'ot.unif', 'ot.unif', (['gs_batch.shape[0]'], {}), '(gs_batch.shape[0])\n', (9648, 9667), False, 'import ot\n'), ((9668, 9694), 'ot.unif', 'ot.unif', (['gt_batch.shape[0]'], {}), '(gt_batch.shape[0])\n', (9675, 9694), False, 'import ot\n'), ((10265, 10289), 'numpy.vstack', 'np.vstack', (['(ys, l_dummy)'], {}), '((ys, l_dummy))\n', (10274, 10289), True, 'import numpy as np\n'), ((9773, 9799), 'ot.unif', 'ot.unif', (['gs_batch.shape[0]'], {}), '(gs_batch.shape[0])\n', (9780, 9799), False, 'import ot\n'), ((9800, 9826), 'ot.unif', 'ot.unif', (['gt_batch.shape[0]'], {}), '(gt_batch.shape[0])\n', (9807, 9826), False, 'import ot\n')] |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
from unittest import TestCase, main
from collections import Counter, defaultdict, OrderedDict
try:
from StringIO import StringIO
except ImportError: # python3 system
from io import StringIO
import tempfile
import numpy as np
from scipy.spatial.distance import hamming
from skbio import (Sequence, DNA, RNA,
DistanceMatrix, Alignment, SequenceCollection)
from skbio.alignment import (StockholmAlignment, SequenceCollectionError,
StockholmParseError, AlignmentError)
class SequenceCollectionTests(TestCase):
def setUp(self):
self.d1 = DNA('GATTACA', metadata={'id': "d1"})
self.d2 = DNA('TTG', metadata={'id': "d2"})
self.d3 = DNA('GTATACA', metadata={'id': "d3"})
self.r1 = RNA('GAUUACA', metadata={'id': "r1"})
self.r2 = RNA('UUG', metadata={'id': "r2"})
self.r3 = RNA('U-----UGCC--', metadata={'id': "r3"})
self.seqs1 = [self.d1, self.d2]
self.seqs2 = [self.r1, self.r2, self.r3]
self.seqs3 = self.seqs1 + self.seqs2
self.seqs4 = [self.d1, self.d3]
self.s1 = SequenceCollection(self.seqs1)
self.s2 = SequenceCollection(self.seqs2)
self.s3 = SequenceCollection(self.seqs3)
self.s4 = SequenceCollection(self.seqs4)
self.empty = SequenceCollection([])
def test_init(self):
SequenceCollection(self.seqs1)
SequenceCollection(self.seqs2)
SequenceCollection(self.seqs3)
SequenceCollection([])
def test_init_fail(self):
# sequences with overlapping ids
s1 = [self.d1, self.d1]
self.assertRaises(SequenceCollectionError, SequenceCollection, s1)
def test_init_fail_no_id(self):
seq = Sequence('ACGTACGT')
with self.assertRaisesRegexp(SequenceCollectionError,
"'id' must be included in the sequence "
"metadata"):
SequenceCollection([seq])
def test_contains(self):
self.assertTrue('d1' in self.s1)
self.assertTrue('r2' in self.s2)
self.assertFalse('r2' in self.s1)
def test_eq(self):
self.assertTrue(self.s1 == self.s1)
self.assertFalse(self.s1 == self.s2)
# different objects can be equal
self.assertTrue(self.s1 == SequenceCollection([self.d1, self.d2]))
self.assertTrue(SequenceCollection([self.d1, self.d2]) == self.s1)
# SequenceCollections with different number of sequences are not equal
self.assertFalse(self.s1 == SequenceCollection([self.d1]))
class FakeSequenceCollection(SequenceCollection):
pass
# SequenceCollections of different types are not equal
self.assertFalse(self.s4 == FakeSequenceCollection([self.d1, self.d3]))
self.assertFalse(self.s4 == Alignment([self.d1, self.d3]))
# SequenceCollections with different sequences are not equal
self.assertFalse(self.s1 == SequenceCollection([self.d1, self.r1]))
def test_getitem(self):
self.assertEqual(self.s1[0], self.d1)
self.assertEqual(self.s1[1], self.d2)
self.assertEqual(self.s2[0], self.r1)
self.assertEqual(self.s2[1], self.r2)
self.assertRaises(IndexError, self.empty.__getitem__, 0)
self.assertRaises(KeyError, self.empty.__getitem__, '0')
def test_iter(self):
s1_iter = iter(self.s1)
count = 0
for actual, expected in zip(s1_iter, self.seqs1):
count += 1
self.assertEqual(actual, expected)
self.assertEqual(count, len(self.seqs1))
self.assertRaises(StopIteration, lambda: next(s1_iter))
def test_len(self):
self.assertEqual(len(self.s1), 2)
self.assertEqual(len(self.s2), 3)
self.assertEqual(len(self.s3), 5)
self.assertEqual(len(self.empty), 0)
def test_ne(self):
self.assertFalse(self.s1 != self.s1)
self.assertTrue(self.s1 != self.s2)
# SequenceCollections with different number of sequences are not equal
self.assertTrue(self.s1 != SequenceCollection([self.d1]))
class FakeSequenceCollection(SequenceCollection):
pass
# SequenceCollections of different types are not equal
self.assertTrue(self.s4 != FakeSequenceCollection([self.d1, self.d3]))
self.assertTrue(self.s4 != Alignment([self.d1, self.d3]))
# SequenceCollections with different sequences are not equal
self.assertTrue(self.s1 !=
SequenceCollection([self.d1, self.r1]))
def test_repr(self):
self.assertEqual(repr(self.s1),
"<SequenceCollection: n=2; "
"mean +/- std length=5.00 +/- 2.00>")
self.assertEqual(repr(self.s2),
"<SequenceCollection: n=3; "
"mean +/- std length=7.33 +/- 3.68>")
self.assertEqual(repr(self.s3),
"<SequenceCollection: n=5; "
"mean +/- std length=6.40 +/- 3.32>")
self.assertEqual(repr(self.empty),
"<SequenceCollection: n=0; "
"mean +/- std length=0.00 +/- 0.00>")
def test_reversed(self):
s1_iter = reversed(self.s1)
count = 0
for actual, expected in zip(s1_iter, self.seqs1[::-1]):
count += 1
self.assertEqual(actual, expected)
self.assertEqual(count, len(self.seqs1))
self.assertRaises(StopIteration, lambda: next(s1_iter))
def test_kmer_frequencies(self):
expected1 = Counter({'GAT': 1, 'TAC': 1})
expected2 = Counter({'TTG': 1})
self.assertEqual(
self.s1.kmer_frequencies(k=3, overlap=False, relative=False),
[expected1, expected2])
expected1 = defaultdict(float)
expected1['A'] = 3 / 7.
expected1['C'] = 1 / 7.
expected1['G'] = 1 / 7.
expected1['T'] = 2 / 7.
expected2 = defaultdict(float)
expected2['G'] = 1 / 3.
expected2['T'] = 2 / 3.
self.assertEqual(self.s1.kmer_frequencies(k=1, relative=True),
[expected1, expected2])
expected1 = defaultdict(float)
expected1['GAT'] = 1 / 2.
expected1['TAC'] = 1 / 2.
expected2 = defaultdict(float)
expected2['TTG'] = 1 / 1.
self.assertEqual(
self.s1.kmer_frequencies(k=3, overlap=False, relative=True),
[expected1, expected2])
self.assertEqual(self.empty.kmer_frequencies(k=1, relative=True), [])
# Test to ensure floating point precision bug isn't present. See the
# tests for Sequence.kmer_frequencies for more details.
sc = SequenceCollection([RNA('C' * 10, metadata={'id': 's1'}),
RNA('G' * 10, metadata={'id': 's2'})])
self.assertEqual(sc.kmer_frequencies(1, relative=True),
[defaultdict(float, {'C': 1.0}),
defaultdict(float, {'G': 1.0})])
def test_str(self):
exp1 = ">d1\nGATTACA\n>d2\nTTG\n"
self.assertEqual(str(self.s1), exp1)
exp2 = ">r1\nGAUUACA\n>r2\nUUG\n>r3\nU-----UGCC--\n"
self.assertEqual(str(self.s2), exp2)
exp4 = ""
self.assertEqual(str(self.empty), exp4)
def test_distances(self):
s1 = SequenceCollection([DNA("ACGT", metadata={'id': "d1"}),
DNA("ACGG", metadata={'id': "d2"})])
expected = [[0, 0.25],
[0.25, 0]]
expected = DistanceMatrix(expected, ['d1', 'd2'])
actual = s1.distances(hamming)
self.assertEqual(actual, expected)
# alt distance function provided
def dumb_distance(s1, s2):
return 42.
expected = [[0, 42.],
[42., 0]]
expected = DistanceMatrix(expected, ['d1', 'd2'])
actual = s1.distances(dumb_distance)
self.assertEqual(actual, expected)
def test_distribution_stats(self):
actual1 = self.s1.distribution_stats()
self.assertEqual(actual1[0], 2)
self.assertAlmostEqual(actual1[1], 5.0, 3)
self.assertAlmostEqual(actual1[2], 2.0, 3)
actual2 = self.s2.distribution_stats()
self.assertEqual(actual2[0], 3)
self.assertAlmostEqual(actual2[1], 7.333, 3)
self.assertAlmostEqual(actual2[2], 3.682, 3)
actual3 = self.s3.distribution_stats()
self.assertEqual(actual3[0], 5)
self.assertAlmostEqual(actual3[1], 6.400, 3)
self.assertAlmostEqual(actual3[2], 3.323, 3)
actual4 = self.empty.distribution_stats()
self.assertEqual(actual4[0], 0)
self.assertEqual(actual4[1], 0.0)
self.assertEqual(actual4[2], 0.0)
def test_degap(self):
expected = SequenceCollection([
RNA('GAUUACA', metadata={'id': "r1"}),
RNA('UUG', metadata={'id': "r2"}),
RNA('UUGCC', metadata={'id': "r3"})])
actual = self.s2.degap()
self.assertEqual(actual, expected)
def test_get_seq(self):
self.assertEqual(self.s1.get_seq('d1'), self.d1)
self.assertEqual(self.s1.get_seq('d2'), self.d2)
def test_ids(self):
self.assertEqual(self.s1.ids(), ['d1', 'd2'])
self.assertEqual(self.s2.ids(), ['r1', 'r2', 'r3'])
self.assertEqual(self.s3.ids(),
['d1', 'd2', 'r1', 'r2', 'r3'])
self.assertEqual(self.empty.ids(), [])
def test_update_ids_default_behavior(self):
# 3 seqs
exp_sc = SequenceCollection([
RNA('GAUUACA', metadata={'id': "1"}),
RNA('UUG', metadata={'id': "2"}),
RNA('U-----UGCC--', metadata={'id': "3"})
])
exp_id_map = {'1': 'r1', '2': 'r2', '3': 'r3'}
obs_sc, obs_id_map = self.s2.update_ids()
self.assertEqual(obs_sc, exp_sc)
self.assertEqual(obs_id_map, exp_id_map)
# empty
obs_sc, obs_id_map = self.empty.update_ids()
self.assertEqual(obs_sc, self.empty)
self.assertEqual(obs_id_map, {})
def test_update_ids_prefix(self):
# 3 seqs
exp_sc = SequenceCollection([
RNA('GAUUACA', metadata={'id': "abc1"}),
RNA('UUG', metadata={'id': "abc2"}),
RNA('U-----UGCC--', metadata={'id': "abc3"})
])
exp_id_map = {'abc1': 'r1', 'abc2': 'r2', 'abc3': 'r3'}
obs_sc, obs_id_map = self.s2.update_ids(prefix='abc')
self.assertEqual(obs_sc, exp_sc)
self.assertEqual(obs_id_map, exp_id_map)
# empty
obs_sc, obs_id_map = self.empty.update_ids(prefix='abc')
self.assertEqual(obs_sc, self.empty)
self.assertEqual(obs_id_map, {})
def test_update_ids_func_parameter(self):
def append_42(ids):
return [id_ + '-42' for id_ in ids]
# 3 seqs
exp_sc = SequenceCollection([
RNA('GAUUACA', metadata={'id': "r1-42"}),
RNA('UUG', metadata={'id': "r2-42"}),
RNA('U-----UGCC--', metadata={'id': "r3-42"})
])
exp_id_map = {'r1-42': 'r1', 'r2-42': 'r2', 'r3-42': 'r3'}
obs_sc, obs_id_map = self.s2.update_ids(func=append_42)
self.assertEqual(obs_sc, exp_sc)
self.assertEqual(obs_id_map, exp_id_map)
# empty
obs_sc, obs_id_map = self.empty.update_ids(func=append_42)
self.assertEqual(obs_sc, self.empty)
self.assertEqual(obs_id_map, {})
def test_update_ids_ids_parameter(self):
# 3 seqs
exp_sc = SequenceCollection([
RNA('GAUUACA', metadata={'id': "abc"}),
RNA('UUG', metadata={'id': "def"}),
RNA('U-----UGCC--', metadata={'id': "ghi"})
])
exp_id_map = {'abc': 'r1', 'def': 'r2', 'ghi': 'r3'}
obs_sc, obs_id_map = self.s2.update_ids(ids=('abc', 'def', 'ghi'))
self.assertEqual(obs_sc, exp_sc)
self.assertEqual(obs_id_map, exp_id_map)
# empty
obs_sc, obs_id_map = self.empty.update_ids(ids=[])
self.assertEqual(obs_sc, self.empty)
self.assertEqual(obs_id_map, {})
def test_update_ids_sequence_attributes_propagated(self):
# 1 seq
exp_sc = Alignment([
DNA('ACGT', metadata={'id': "abc", 'description': 'desc'},
positional_metadata={'quality': range(4)})
])
exp_id_map = {'abc': 'seq1'}
obj = Alignment([
DNA('ACGT', metadata={'id': "seq1", 'description': 'desc'},
positional_metadata={'quality': range(4)})
])
obs_sc, obs_id_map = obj.update_ids(ids=('abc',))
self.assertEqual(obs_sc, exp_sc)
self.assertEqual(obs_id_map, exp_id_map)
# 2 seqs
exp_sc = Alignment([
DNA('ACGT', metadata={'id': "abc", 'description': 'desc1'},
positional_metadata={'quality': range(4)}),
DNA('TGCA', metadata={'id': "def", 'description': 'desc2'},
positional_metadata={'quality': range(4)[::-1]})
])
exp_id_map = {'abc': 'seq1', 'def': 'seq2'}
obj = Alignment([
DNA('ACGT', metadata={'id': "seq1", 'description': 'desc1'},
positional_metadata={'quality': (0, 1, 2, 3)}),
DNA('TGCA', metadata={'id': "seq2", 'description': 'desc2'},
positional_metadata={'quality': (3, 2, 1, 0)})
])
obs_sc, obs_id_map = obj.update_ids(ids=('abc', 'def'))
self.assertEqual(obs_sc, exp_sc)
self.assertEqual(obs_id_map, exp_id_map)
def test_update_ids_invalid_parameter_combos(self):
with self.assertRaisesRegexp(SequenceCollectionError, 'ids and func'):
self.s1.update_ids(func=lambda e: e, ids=['foo', 'bar'])
with self.assertRaisesRegexp(SequenceCollectionError, 'prefix'):
self.s1.update_ids(ids=['foo', 'bar'], prefix='abc')
with self.assertRaisesRegexp(SequenceCollectionError, 'prefix'):
self.s1.update_ids(func=lambda e: e, prefix='abc')
def test_update_ids_invalid_ids(self):
# incorrect number of new ids
with self.assertRaisesRegexp(SequenceCollectionError, '3 != 2'):
self.s1.update_ids(ids=['foo', 'bar', 'baz'])
with self.assertRaisesRegexp(SequenceCollectionError, '4 != 2'):
self.s1.update_ids(func=lambda e: ['foo', 'bar', 'baz', 'abc'])
# duplicates
with self.assertRaisesRegexp(SequenceCollectionError, 'foo'):
self.s2.update_ids(ids=['foo', 'bar', 'foo'])
with self.assertRaisesRegexp(SequenceCollectionError, 'bar'):
self.s2.update_ids(func=lambda e: ['foo', 'bar', 'bar'])
def test_is_empty(self):
self.assertFalse(self.s1.is_empty())
self.assertFalse(self.s2.is_empty())
self.assertFalse(self.s3.is_empty())
self.assertTrue(self.empty.is_empty())
def test_iteritems(self):
self.assertEqual(list(self.s1.iteritems()),
[(s.metadata['id'], s) for s in self.s1])
def test_sequence_count(self):
self.assertEqual(self.s1.sequence_count(), 2)
self.assertEqual(self.s2.sequence_count(), 3)
self.assertEqual(self.s3.sequence_count(), 5)
self.assertEqual(self.empty.sequence_count(), 0)
def test_sequence_lengths(self):
self.assertEqual(self.s1.sequence_lengths(), [7, 3])
self.assertEqual(self.s2.sequence_lengths(), [7, 3, 12])
self.assertEqual(self.s3.sequence_lengths(), [7, 3, 7, 3, 12])
self.assertEqual(self.empty.sequence_lengths(), [])
class AlignmentTests(TestCase):
def setUp(self):
self.d1 = DNA('..ACC-GTTGG..', metadata={'id': "d1"})
self.d2 = DNA('TTACCGGT-GGCC', metadata={'id': "d2"})
self.d3 = DNA('.-ACC-GTTGC--', metadata={'id': "d3"})
self.r1 = RNA('UUAU-', metadata={'id': "r1"})
self.r2 = RNA('ACGUU', metadata={'id': "r2"})
self.seqs1 = [self.d1, self.d2, self.d3]
self.seqs2 = [self.r1, self.r2]
self.a1 = Alignment(self.seqs1)
self.a2 = Alignment(self.seqs2)
self.a3 = Alignment(self.seqs2, score=42.0,
start_end_positions=[(0, 3), (5, 9)])
self.a4 = Alignment(self.seqs2, score=-42.0,
start_end_positions=[(1, 4), (6, 10)])
# no sequences
self.empty = Alignment([])
# sequences, but no positions
self.no_positions = Alignment([RNA('', metadata={'id': 'a'}),
RNA('', metadata={'id': 'b'})])
def test_degap(self):
expected = SequenceCollection([
DNA('ACCGTTGG', metadata={'id': "d1"}),
DNA('TTACCGGTGGCC', metadata={'id': "d2"}),
DNA('ACCGTTGC', metadata={'id': "d3"})])
actual = self.a1.degap()
self.assertEqual(actual, expected)
expected = SequenceCollection([
RNA('UUAU', metadata={'id': "r1"}),
RNA('ACGUU', metadata={'id': "r2"})])
actual = self.a2.degap()
self.assertEqual(actual, expected)
def test_distances(self):
expected = [[0, 6. / 13, 4. / 13],
[6. / 13, 0, 7. / 13],
[4. / 13, 7. / 13, 0]]
expected = DistanceMatrix(expected, ['d1', 'd2', 'd3'])
actual = self.a1.distances()
self.assertEqual(actual, expected)
# alt distance function provided
def dumb_distance(s1, s2):
return 42.
expected = [[0, 42., 42.],
[42., 0, 42.],
[42., 42., 0]]
expected = DistanceMatrix(expected, ['d1', 'd2', 'd3'])
actual = self.a1.distances(dumb_distance)
self.assertEqual(actual, expected)
def test_score(self):
self.assertEqual(self.a3.score(), 42.0)
self.assertEqual(self.a4.score(), -42.0)
def test_start_end_positions(self):
self.assertEqual(self.a3.start_end_positions(), [(0, 3), (5, 9)])
self.assertEqual(self.a4.start_end_positions(), [(1, 4), (6, 10)])
def test_subalignment(self):
# keep seqs by ids
actual = self.a1.subalignment(seqs_to_keep=['d1', 'd3'])
expected = Alignment([self.d1, self.d3])
self.assertEqual(actual, expected)
# keep seqs by indices
actual = self.a1.subalignment(seqs_to_keep=[0, 2])
expected = Alignment([self.d1, self.d3])
self.assertEqual(actual, expected)
# keep seqs by ids (invert)
actual = self.a1.subalignment(seqs_to_keep=['d1', 'd3'],
invert_seqs_to_keep=True)
expected = Alignment([self.d2])
self.assertEqual(actual, expected)
# keep seqs by indices (invert)
actual = self.a1.subalignment(seqs_to_keep=[0, 2],
invert_seqs_to_keep=True)
expected = Alignment([self.d2])
self.assertEqual(actual, expected)
# keep positions
actual = self.a1.subalignment(positions_to_keep=[0, 2, 3])
d1 = DNA('.AC', metadata={'id': "d1"})
d2 = DNA('TAC', metadata={'id': "d2"})
d3 = DNA('.AC', metadata={'id': "d3"})
expected = Alignment([d1, d2, d3])
self.assertEqual(actual, expected)
# keep positions (invert)
actual = self.a1.subalignment(positions_to_keep=[0, 2, 3],
invert_positions_to_keep=True)
d1 = DNA('.C-GTTGG..', metadata={'id': "d1"})
d2 = DNA('TCGGT-GGCC', metadata={'id': "d2"})
d3 = DNA('-C-GTTGC--', metadata={'id': "d3"})
expected = Alignment([d1, d2, d3])
self.assertEqual(actual, expected)
# keep seqs and positions
actual = self.a1.subalignment(seqs_to_keep=[0, 2],
positions_to_keep=[0, 2, 3])
d1 = DNA('.AC', metadata={'id': "d1"})
d3 = DNA('.AC', metadata={'id': "d3"})
expected = Alignment([d1, d3])
self.assertEqual(actual, expected)
# keep seqs and positions (invert)
actual = self.a1.subalignment(seqs_to_keep=[0, 2],
positions_to_keep=[0, 2, 3],
invert_seqs_to_keep=True,
invert_positions_to_keep=True)
d2 = DNA('TCGGT-GGCC', metadata={'id': "d2"})
expected = Alignment([d2])
self.assertEqual(actual, expected)
def test_subalignment_filter_out_everything(self):
exp = Alignment([])
# no sequences
obs = self.a1.subalignment(seqs_to_keep=None, invert_seqs_to_keep=True)
self.assertEqual(obs, exp)
# no positions
obs = self.a1.subalignment(positions_to_keep=None,
invert_positions_to_keep=True)
self.assertEqual(obs, exp)
def test_init_not_equal_lengths(self):
invalid_seqs = [self.d1, self.d2, self.d3,
DNA('.-ACC-GTGC--', metadata={'id': "i2"})]
self.assertRaises(AlignmentError, Alignment,
invalid_seqs)
def test_init_equal_lengths(self):
seqs = [self.d1, self.d2, self.d3]
Alignment(seqs)
def test_iter_positions(self):
actual = list(self.a2.iter_positions())
expected = [
[RNA('U', metadata={'id': 'r1'}), RNA('A', metadata={'id': 'r2'})],
[RNA('U', metadata={'id': 'r1'}), RNA('C', metadata={'id': 'r2'})],
[RNA('A', metadata={'id': 'r1'}), RNA('G', metadata={'id': 'r2'})],
[RNA('U', metadata={'id': 'r1'}), RNA('U', metadata={'id': 'r2'})],
[RNA('-', metadata={'id': 'r1'}), RNA('U', metadata={'id': 'r2'})]
]
self.assertEqual(actual, expected)
actual = list(self.a2.iter_positions(constructor=str))
expected = [list('UA'),
list('UC'),
list('AG'),
list('UU'),
list('-U')]
self.assertEqual(actual, expected)
def test_majority_consensus(self):
# empty cases
self.assertEqual(
self.empty.majority_consensus(), Sequence(''))
self.assertEqual(
self.no_positions.majority_consensus(), RNA(''))
# alignment where all sequences are the same
aln = Alignment([DNA('AG', metadata={'id': 'a'}),
DNA('AG', metadata={'id': 'b'})])
self.assertEqual(aln.majority_consensus(), DNA('AG'))
# no ties
d1 = DNA('TTT', metadata={'id': "d1"})
d2 = DNA('TT-', metadata={'id': "d2"})
d3 = DNA('TC-', metadata={'id': "d3"})
a1 = Alignment([d1, d2, d3])
self.assertEqual(a1.majority_consensus(), DNA('TT-'))
# ties
d1 = DNA('T', metadata={'id': "d1"})
d2 = DNA('A', metadata={'id': "d2"})
a1 = Alignment([d1, d2])
self.assertTrue(a1.majority_consensus() in
[DNA('T'), DNA('A')])
def test_omit_gap_positions(self):
expected = self.a2
self.assertEqual(self.a2.omit_gap_positions(1.0), expected)
self.assertEqual(self.a2.omit_gap_positions(0.51), expected)
r1 = RNA('UUAU', metadata={'id': "r1"})
r2 = RNA('ACGU', metadata={'id': "r2"})
expected = Alignment([r1, r2])
self.assertEqual(self.a2.omit_gap_positions(0.49), expected)
r1 = RNA('UUAU', metadata={'id': "r1"})
r2 = RNA('ACGU', metadata={'id': "r2"})
expected = Alignment([r1, r2])
self.assertEqual(self.a2.omit_gap_positions(0.0), expected)
self.assertEqual(self.empty.omit_gap_positions(0.0), self.empty)
self.assertEqual(self.empty.omit_gap_positions(0.49), self.empty)
self.assertEqual(self.empty.omit_gap_positions(1.0), self.empty)
# Test to ensure floating point precision bug isn't present. See the
# tests for Alignment.position_frequencies for more details.
seqs = []
for i in range(33):
seqs.append(DNA('-.', metadata={'id': str(i)}))
aln = Alignment(seqs)
self.assertEqual(aln.omit_gap_positions(1 - np.finfo(float).eps),
Alignment([DNA('', metadata={'id': str(i)})
for i in range(33)]))
def test_omit_gap_sequences(self):
expected = self.a2
self.assertEqual(self.a2.omit_gap_sequences(1.0), expected)
self.assertEqual(self.a2.omit_gap_sequences(0.20), expected)
expected = Alignment([self.r2])
self.assertEqual(self.a2.omit_gap_sequences(0.19), expected)
self.assertEqual(self.empty.omit_gap_sequences(0.0), self.empty)
self.assertEqual(self.empty.omit_gap_sequences(0.2), self.empty)
self.assertEqual(self.empty.omit_gap_sequences(1.0), self.empty)
# Test to ensure floating point precision bug isn't present. See the
# tests for Alignment.position_frequencies for more details.
aln = Alignment([DNA('.' * 33, metadata={'id': 'abc'}),
DNA('-' * 33, metadata={'id': 'def'})])
self.assertEqual(aln.omit_gap_sequences(1 - np.finfo(float).eps),
Alignment([]))
def test_position_counters(self):
self.assertEqual(self.empty.position_counters(), [])
self.assertEqual(self.no_positions.position_counters(), [])
expected = [Counter({'U': 1, 'A': 1}),
Counter({'U': 1, 'C': 1}),
Counter({'A': 1, 'G': 1}),
Counter({'U': 2}),
Counter({'-': 1, 'U': 1})]
self.assertEqual(self.a2.position_counters(), expected)
def test_position_frequencies(self):
self.assertEqual(self.empty.position_frequencies(), [])
self.assertEqual(self.no_positions.position_frequencies(), [])
expected = [defaultdict(float, {'U': 0.5, 'A': 0.5}),
defaultdict(float, {'U': 0.5, 'C': 0.5}),
defaultdict(float, {'A': 0.5, 'G': 0.5}),
defaultdict(float, {'U': 1.0}),
defaultdict(float, {'-': 0.5, 'U': 0.5})]
self.assertEqual(self.a2.position_frequencies(), expected)
def test_position_frequencies_floating_point_precision(self):
# Test that a position with no variation yields a frequency of exactly
# 1.0. Note that it is important to use self.assertEqual here instead
# of self.assertAlmostEqual because we want to test for exactly 1.0. A
# previous implementation of Alignment.position_frequencies added
# (1 / sequence_count) for each occurrence of a character in a position
# to compute the frequencies (see
# https://github.com/biocore/scikit-bio/issues/801). In certain cases,
# this yielded a frequency slightly less than 1.0 due to roundoff
# error. The test case here uses an alignment of 10 sequences with no
# variation at a position. This test case exposes the roundoff error
# present in the previous implementation because 1/10 added 10 times
# yields a number slightly less than 1.0. This occurs because 1/10
# cannot be represented exactly as a floating point number.
seqs = []
for i in range(10):
seqs.append(DNA('A', metadata={'id': str(i)}))
aln = Alignment(seqs)
self.assertEqual(aln.position_frequencies(),
[defaultdict(float, {'A': 1.0})])
def test_position_entropies(self):
# tested by calculating values as described in this post:
# http://stackoverflow.com/a/15476958/3424666
expected = [0.69314, 0.69314, 0.69314, 0.0, np.nan]
np.testing.assert_almost_equal(self.a2.position_entropies(),
expected, 5)
expected = [1.0, 1.0, 1.0, 0.0, np.nan]
np.testing.assert_almost_equal(self.a2.position_entropies(base=2),
expected, 5)
np.testing.assert_almost_equal(self.empty.position_entropies(base=2),
[])
def test_kmer_frequencies(self):
expected = [defaultdict(float, {'U': 3 / 5, 'A': 1 / 5, '-': 1 / 5}),
defaultdict(float, {'A': 1 / 5, 'C': 1 / 5, 'G': 1 / 5,
'U': 2 / 5})]
actual = self.a2.kmer_frequencies(k=1, relative=True)
for a, e in zip(actual, expected):
self.assertEqual(sorted(a), sorted(e), 5)
np.testing.assert_almost_equal(sorted(a.values()),
sorted(e.values()), 5)
def test_sequence_length(self):
self.assertEqual(self.a1.sequence_length(), 13)
self.assertEqual(self.a2.sequence_length(), 5)
self.assertEqual(self.empty.sequence_length(), 0)
def test_validate_lengths(self):
self.assertTrue(self.a1._validate_lengths())
self.assertTrue(self.a2._validate_lengths())
self.assertTrue(self.empty._validate_lengths())
self.assertTrue(Alignment([
DNA('TTT', metadata={'id': "d1"})])._validate_lengths())
class StockholmAlignmentTests(TestCase):
def setUp(self):
self.seqs = [DNA("ACC-G-GGTA", metadata={'id': "seq1"}),
DNA("TCC-G-GGCA", metadata={'id': "seq2"})]
self.GF = OrderedDict([
("AC", "RF00360"),
("BM", ["cmbuild -F CM SEED",
"cmsearch -Z 274931 -E 1000000"]),
("SQ", "9"),
("RT", ["TITLE1", "TITLE2"]),
("RN", ["[1]", "[2]"]),
("RA", ["Auth1;", "Auth2;"]),
("RL", ["J Mol Biol", "Cell"]),
("RM", ["11469857", "12007400"]),
('RN', ['[1]', '[2]'])
])
self.GS = {"AC": OrderedDict([("seq1", "111"), ("seq2", "222")])}
self.GR = {"SS": OrderedDict([("seq1", "1110101111"),
("seq2", "0110101110")])}
self.GC = {"SS_cons": "(((....)))"}
self.st = StockholmAlignment(self.seqs, gc=self.GC, gf=self.GF,
gs=self.GS, gr=self.GR)
def test_retrieve_metadata(self):
self.assertEqual(self.st.gc, self.GC)
self.assertEqual(self.st.gf, self.GF)
self.assertEqual(self.st.gs, self.GS)
self.assertEqual(self.st.gr, self.GR)
def test_from_file_alignment(self):
# test that a basic stockholm file with interleaved alignment can be
# parsed
sto = StringIO("# STOCKHOLM 1.0\n"
"seq1 ACC-G\n"
"seq2 TCC-G\n\n"
"seq1 -GGTA\n"
"seq2 -GGCA\n//")
obs_sto = next(StockholmAlignment.from_file(sto, DNA))
exp_sto = StockholmAlignment(self.seqs)
self.assertEqual(obs_sto, exp_sto)
def test_from_file_GF(self):
# remove rn line to make sure auto-added
self.GF.pop("RN")
sto = StringIO("# STOCKHOLM 1.0\n#=GF RN [1]\n#=GF RM 11469857\n"
"#=GF RT TITLE1\n#=GF RA Auth1;\n#=GF RL J Mol Biol\n"
"#=GF RN [2]\n#=GF RM 12007400\n#=GF RT TITLE2\n"
"#=GF RA Auth2;\n#=GF RL Cell\n#=GF AC RF00360\n"
"#=GF BM cmbuild -F CM SEED\n"
"#=GF BM cmsearch -Z 274931 -E 1000000\n#=GF SQ 9\n"
"seq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n//")
obs_sto = next(StockholmAlignment.from_file(sto, DNA))
exp_sto = StockholmAlignment(self.seqs, self.GF, {}, {}, {})
self.assertEqual(obs_sto, exp_sto)
def test_from_file_GC(self):
sto = StringIO("# STOCKHOLM 1.0\n"
"seq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n"
"#=GC SS_cons (((....)))\n//")
obs_sto = next(StockholmAlignment.from_file(sto, DNA))
exp_sto = StockholmAlignment(self.seqs, {}, {}, {}, self.GC)
self.assertEqual(obs_sto, exp_sto)
def test_from_file_GS(self):
sto = StringIO("# STOCKHOLM 1.0\n#=GS seq2 AC 222\n#=GS seq1 AC 111\n"
"seq1 ACC-G-GGTA\n"
"seq2 TCC-G-GGCA\n//")
obs_sto = next(StockholmAlignment.from_file(sto, DNA))
exp_sto = StockholmAlignment(self.seqs, {}, self.GS, {}, {})
self.assertEqual(obs_sto, exp_sto)
def test_from_file_GR(self):
sto = StringIO("# STOCKHOLM 1.0\nseq1 ACC-G\n"
"#=GR seq1 SS 11101\nseq2 TCC-G\n"
"#=GR seq2 SS 01101\n\nseq1 -GGTA\n"
"#=GR seq1 SS 01111\nseq2 -GGCA\n"
"#=GR seq2 SS 01110\n//")
obs_sto = next(StockholmAlignment.from_file(sto, DNA))
exp_sto = StockholmAlignment(self.seqs, {}, {}, self.GR, {})
self.assertEqual(obs_sto, exp_sto)
def test_from_file_multi(self):
sto = StringIO("# STOCKHOLM 1.0\n#=GS seq2 AC 222\n#=GS seq1 AC 111\n"
"seq1 ACC-G-GGTA\n"
"seq2 TCC-G-GGCA\n//\n"
"# STOCKHOLM 1.0\nseq1 ACC-G-GGTA\n"
"#=GR seq1 SS 1110101111\nseq2 TCC-G-GGCA\n"
"#=GR seq2 SS 0110101110\n//")
obs_sto = StockholmAlignment.from_file(sto, DNA)
count = 0
for obs in obs_sto:
if count == 0:
exp_sto = StockholmAlignment(self.seqs, {}, self.GS, {}, {})
self.assertEqual(obs, exp_sto)
elif count == 1:
exp_sto = StockholmAlignment(self.seqs, {}, {}, self.GR, {})
self.assertEqual(obs, exp_sto)
else:
raise AssertionError("More than 2 sto alignments parsed!")
count += 1
def test_parse_gf_multiline_nh(self):
sto = ["#=GF TN MULTILINE TREE",
"#=GF NH THIS IS FIRST", "#=GF NH THIS IS SECOND",
"#=GF AC 1283394"]
exp = {'TN': 'MULTILINE TREE',
'NH': 'THIS IS FIRST THIS IS SECOND',
'AC': '1283394'}
self.assertEqual(self.st._parse_gf_info(sto), exp)
def test_parse_gf_multiline_cc(self):
sto = ["#=GF CC THIS IS FIRST", "#=GF CC THIS IS SECOND"]
exp = {'CC': 'THIS IS FIRST THIS IS SECOND'}
self.assertEqual(self.st._parse_gf_info(sto), exp)
def test_parse_gf_info_nongf(self):
sto = ["#=GF AC BLAAAAAAAHHH", "#=GC HUH THIS SHOULD NOT BE HERE"]
with self.assertRaises(StockholmParseError):
self.st._parse_gf_info(sto)
def test_parse_gf_info_malformed(self):
# too short of a line
sto = ["#=GF AC", "#=GF"]
with self.assertRaises(StockholmParseError):
self.st._parse_gf_info(sto)
def test_parse_gc_info_nongf(self):
sto = ["#=GC AC BLAAAAAAAHHH", "#=GF HUH THIS SHOULD NOT BE HERE"]
with self.assertRaises(StockholmParseError):
self.st._parse_gf_info(sto)
def test_parse_gc_info_strict_len(self):
sto = ["#=GC SS_cons (((..)))"]
with self.assertRaises(StockholmParseError):
self.st._parse_gc_info(sto, seqlen=20, strict=True)
def test_parse_gc_info_strict_duplicate(self):
sto = ["#=GC SS_cons (((..)))", "#=GC SS_cons (((..)))"]
with self.assertRaises(StockholmParseError):
self.st._parse_gc_info(sto, seqlen=8, strict=True)
def test_parse_gc_info_malformed(self):
# too short of a line
sto = ["#=GC AC BLAAAAAAAHHH", "#=GC"]
with self.assertRaises(StockholmParseError):
self.st._parse_gc_info(sto)
def test_parse_gs_gr_info_mixed(self):
sto = ["#=GS seq1 AC BLAAA", "#=GR seq2 HUH THIS SHOULD NOT BE HERE"]
with self.assertRaises(StockholmParseError):
self.st._parse_gs_gr_info(sto)
def test_parse_gs_gr_info_malformed(self):
# too short of a line
sto = ["#=GS AC BLAAAAAAAHHH", "#=GS"]
with self.assertRaises(StockholmParseError):
self.st._parse_gs_gr_info(sto)
def test_parse_gs_gr_info_strict(self):
sto = ["#=GR seq1 SS 10101111", "#=GR seq2 SS 01101"]
with self.assertRaises(StockholmParseError):
self.st._parse_gs_gr_info(sto, seqlen=20, strict=True)
def test_str(self):
st = StockholmAlignment(self.seqs, gc=self.GC, gf=self.GF, gs=self.GS,
gr=self.GR)
obs = str(st)
exp = ('# STOCKHOLM 1.0\n'
'#=GF AC RF00360\n'
'#=GF BM cmbuild -F CM SEED\n'
'#=GF BM cmsearch -Z 274931 -E 1000000\n'
'#=GF SQ 9\n'
'#=GF RN [1]\n'
'#=GF RM 11469857\n'
'#=GF RT TITLE1\n'
'#=GF RA Auth1;\n'
'#=GF RL J Mol Biol\n'
'#=GF RN [2]\n'
'#=GF RM 12007400\n'
'#=GF RT TITLE2\n'
'#=GF RA Auth2;\n'
'#=GF RL Cell\n'
'#=GS seq1 AC 111\n'
'#=GS seq2 AC 222\n'
'seq1 ACC-G-GGTA\n'
'#=GR seq1 SS 1110101111\n'
'seq2 TCC-G-GGCA\n'
'#=GR seq2 SS 0110101110\n'
'#=GC SS_cons (((....)))\n//')
self.assertEqual(obs, exp)
def test_to_file(self):
st = StockholmAlignment(self.seqs, gc=self.GC, gf=self.GF, gs=self.GS,
gr=self.GR)
with tempfile.NamedTemporaryFile('r+') as temp_file:
st.to_file(temp_file)
temp_file.flush()
temp_file.seek(0)
obs = temp_file.read()
exp = ('# STOCKHOLM 1.0\n'
'#=GF AC RF00360\n'
'#=GF BM cmbuild -F CM SEED\n'
'#=GF BM cmsearch -Z 274931 -E 1000000\n'
'#=GF SQ 9\n'
'#=GF RN [1]\n'
'#=GF RM 11469857\n'
'#=GF RT TITLE1\n'
'#=GF RA Auth1;\n'
'#=GF RL J Mol Biol\n'
'#=GF RN [2]\n'
'#=GF RM 12007400\n'
'#=GF RT TITLE2\n'
'#=GF RA Auth2;\n'
'#=GF RL Cell\n'
'#=GS seq1 AC 111\n'
'#=GS seq2 AC 222\n'
'seq1 ACC-G-GGTA\n'
'#=GR seq1 SS 1110101111\n'
'seq2 TCC-G-GGCA\n'
'#=GR seq2 SS 0110101110\n'
'#=GC SS_cons (((....)))\n//')
self.assertEqual(obs, exp)
def test_str_gc(self):
st = StockholmAlignment(self.seqs, gc=self.GC, gf=None, gs=None,
gr=None)
obs = str(st)
exp = ("# STOCKHOLM 1.0\nseq1 ACC-G-GGTA\n"
"seq2 TCC-G-GGCA\n"
"#=GC SS_cons (((....)))\n//")
self.assertEqual(obs, exp)
def test_str_gf(self):
st = StockholmAlignment(self.seqs, gc=None, gf=self.GF, gs=None,
gr=None)
obs = str(st)
exp = ('# STOCKHOLM 1.0\n'
'#=GF AC RF00360\n'
'#=GF BM cmbuild -F CM SEED\n'
'#=GF BM cmsearch -Z 274931 -E 1000000\n'
'#=GF SQ 9\n'
'#=GF RN [1]\n'
'#=GF RM 11469857\n'
'#=GF RT TITLE1\n'
'#=GF RA Auth1;\n'
'#=GF RL J Mol Biol\n'
'#=GF RN [2]\n'
'#=GF RM 12007400\n'
'#=GF RT TITLE2\n'
'#=GF RA Auth2;\n'
'#=GF RL Cell\n'
'seq1 ACC-G-GGTA\n'
'seq2 TCC-G-GGCA\n//')
self.assertEqual(obs, exp)
def test_str_gs(self):
st = StockholmAlignment(self.seqs, gc=None, gf=None, gs=self.GS,
gr=None)
obs = str(st)
exp = ('# STOCKHOLM 1.0\n'
'#=GS seq1 AC 111\n'
'#=GS seq2 AC 222\n'
'seq1 ACC-G-GGTA\n'
'seq2 TCC-G-GGCA\n//')
self.assertEqual(obs, exp)
def test_str_gr(self):
st = StockholmAlignment(self.seqs, gc=None, gf=None, gs=None,
gr=self.GR)
obs = str(st)
exp = ("# STOCKHOLM 1.0\nseq1 ACC-G-GGTA\n"
"#=GR seq1 SS 1110101111\nseq2 TCC-G-GGCA\n"
"#=GR seq2 SS 0110101110\n//")
self.assertEqual(obs, exp)
def test_str_trees(self):
GF = OrderedDict({"NH": ["IMATREE", "IMATREETOO"],
"TN": ["Tree2", "Tree1"]})
st = StockholmAlignment(self.seqs, gc=None, gf=GF, gs=None,
gr=None)
obs = str(st)
exp = ("# STOCKHOLM 1.0\n#=GF TN Tree2\n#=GF NH IMATREE\n#=GF TN Tree1"
"\n#=GF NH IMATREETOO\nseq1 ACC-G-GGTA\n"
"seq2 TCC-G-GGCA\n//")
self.assertEqual(obs, exp)
if __name__ == "__main__":
main()
| [
"unittest.main",
"tempfile.NamedTemporaryFile",
"io.StringIO",
"skbio.SequenceCollection",
"collections.defaultdict",
"skbio.DNA",
"skbio.Alignment",
"skbio.alignment.StockholmAlignment",
"numpy.finfo",
"collections.OrderedDict",
"collections.Counter",
"skbio.alignment.StockholmAlignment.from_... | [((41986, 41992), 'unittest.main', 'main', ([], {}), '()\n', (41990, 41992), False, 'from unittest import TestCase, main\n'), ((1026, 1063), 'skbio.DNA', 'DNA', (['"""GATTACA"""'], {'metadata': "{'id': 'd1'}"}), "('GATTACA', metadata={'id': 'd1'})\n", (1029, 1063), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1082, 1115), 'skbio.DNA', 'DNA', (['"""TTG"""'], {'metadata': "{'id': 'd2'}"}), "('TTG', metadata={'id': 'd2'})\n", (1085, 1115), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1134, 1171), 'skbio.DNA', 'DNA', (['"""GTATACA"""'], {'metadata': "{'id': 'd3'}"}), "('GTATACA', metadata={'id': 'd3'})\n", (1137, 1171), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1190, 1227), 'skbio.RNA', 'RNA', (['"""GAUUACA"""'], {'metadata': "{'id': 'r1'}"}), "('GAUUACA', metadata={'id': 'r1'})\n", (1193, 1227), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1246, 1279), 'skbio.RNA', 'RNA', (['"""UUG"""'], {'metadata': "{'id': 'r2'}"}), "('UUG', metadata={'id': 'r2'})\n", (1249, 1279), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1298, 1340), 'skbio.RNA', 'RNA', (['"""U-----UGCC--"""'], {'metadata': "{'id': 'r3'}"}), "('U-----UGCC--', metadata={'id': 'r3'})\n", (1301, 1340), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1535, 1565), 'skbio.SequenceCollection', 'SequenceCollection', (['self.seqs1'], {}), '(self.seqs1)\n', (1553, 1565), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1584, 1614), 'skbio.SequenceCollection', 'SequenceCollection', (['self.seqs2'], {}), '(self.seqs2)\n', (1602, 1614), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1633, 1663), 'skbio.SequenceCollection', 'SequenceCollection', (['self.seqs3'], {}), '(self.seqs3)\n', (1651, 1663), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1682, 1712), 'skbio.SequenceCollection', 'SequenceCollection', (['self.seqs4'], {}), '(self.seqs4)\n', (1700, 1712), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1734, 1756), 'skbio.SequenceCollection', 'SequenceCollection', (['[]'], {}), '([])\n', (1752, 1756), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1791, 1821), 'skbio.SequenceCollection', 'SequenceCollection', (['self.seqs1'], {}), '(self.seqs1)\n', (1809, 1821), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1830, 1860), 'skbio.SequenceCollection', 'SequenceCollection', (['self.seqs2'], {}), '(self.seqs2)\n', (1848, 1860), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1869, 1899), 'skbio.SequenceCollection', 'SequenceCollection', (['self.seqs3'], {}), '(self.seqs3)\n', (1887, 1899), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((1908, 1930), 'skbio.SequenceCollection', 'SequenceCollection', (['[]'], {}), '([])\n', (1926, 1930), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((2161, 2181), 'skbio.Sequence', 'Sequence', (['"""ACGTACGT"""'], {}), "('ACGTACGT')\n", (2169, 2181), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((6063, 6092), 'collections.Counter', 'Counter', (["{'GAT': 1, 'TAC': 1}"], {}), "({'GAT': 1, 'TAC': 1})\n", (6070, 6092), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((6113, 6132), 'collections.Counter', 'Counter', (["{'TTG': 1}"], {}), "({'TTG': 1})\n", (6120, 6132), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((6290, 6308), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (6301, 6308), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((6457, 6475), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (6468, 6475), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((6681, 6699), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (6692, 6699), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((6788, 6806), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (6799, 6806), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((8056, 8094), 'skbio.DistanceMatrix', 'DistanceMatrix', (['expected', "['d1', 'd2']"], {}), "(expected, ['d1', 'd2'])\n", (8070, 8094), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((8356, 8394), 'skbio.DistanceMatrix', 'DistanceMatrix', (['expected', "['d1', 'd2']"], {}), "(expected, ['d1', 'd2'])\n", (8370, 8394), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16223, 16266), 'skbio.DNA', 'DNA', (['"""..ACC-GTTGG.."""'], {'metadata': "{'id': 'd1'}"}), "('..ACC-GTTGG..', metadata={'id': 'd1'})\n", (16226, 16266), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16285, 16328), 'skbio.DNA', 'DNA', (['"""TTACCGGT-GGCC"""'], {'metadata': "{'id': 'd2'}"}), "('TTACCGGT-GGCC', metadata={'id': 'd2'})\n", (16288, 16328), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16347, 16390), 'skbio.DNA', 'DNA', (['""".-ACC-GTTGC--"""'], {'metadata': "{'id': 'd3'}"}), "('.-ACC-GTTGC--', metadata={'id': 'd3'})\n", (16350, 16390), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16410, 16445), 'skbio.RNA', 'RNA', (['"""UUAU-"""'], {'metadata': "{'id': 'r1'}"}), "('UUAU-', metadata={'id': 'r1'})\n", (16413, 16445), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16464, 16499), 'skbio.RNA', 'RNA', (['"""ACGUU"""'], {'metadata': "{'id': 'r2'}"}), "('ACGUU', metadata={'id': 'r2'})\n", (16467, 16499), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16609, 16630), 'skbio.Alignment', 'Alignment', (['self.seqs1'], {}), '(self.seqs1)\n', (16618, 16630), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16649, 16670), 'skbio.Alignment', 'Alignment', (['self.seqs2'], {}), '(self.seqs2)\n', (16658, 16670), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16689, 16760), 'skbio.Alignment', 'Alignment', (['self.seqs2'], {'score': '(42.0)', 'start_end_positions': '[(0, 3), (5, 9)]'}), '(self.seqs2, score=42.0, start_end_positions=[(0, 3), (5, 9)])\n', (16698, 16760), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16807, 16880), 'skbio.Alignment', 'Alignment', (['self.seqs2'], {'score': '(-42.0)', 'start_end_positions': '[(1, 4), (6, 10)]'}), '(self.seqs2, score=-42.0, start_end_positions=[(1, 4), (6, 10)])\n', (16816, 16880), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((16954, 16967), 'skbio.Alignment', 'Alignment', (['[]'], {}), '([])\n', (16963, 16967), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17846, 17890), 'skbio.DistanceMatrix', 'DistanceMatrix', (['expected', "['d1', 'd2', 'd3']"], {}), "(expected, ['d1', 'd2', 'd3'])\n", (17860, 17890), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((18195, 18239), 'skbio.DistanceMatrix', 'DistanceMatrix', (['expected', "['d1', 'd2', 'd3']"], {}), "(expected, ['d1', 'd2', 'd3'])\n", (18209, 18239), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((18792, 18821), 'skbio.Alignment', 'Alignment', (['[self.d1, self.d3]'], {}), '([self.d1, self.d3])\n', (18801, 18821), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((18975, 19004), 'skbio.Alignment', 'Alignment', (['[self.d1, self.d3]'], {}), '([self.d1, self.d3])\n', (18984, 19004), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((19233, 19253), 'skbio.Alignment', 'Alignment', (['[self.d2]'], {}), '([self.d2])\n', (19242, 19253), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((19480, 19500), 'skbio.Alignment', 'Alignment', (['[self.d2]'], {}), '([self.d2])\n', (19489, 19500), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((19650, 19683), 'skbio.DNA', 'DNA', (['""".AC"""'], {'metadata': "{'id': 'd1'}"}), "('.AC', metadata={'id': 'd1'})\n", (19653, 19683), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((19697, 19730), 'skbio.DNA', 'DNA', (['"""TAC"""'], {'metadata': "{'id': 'd2'}"}), "('TAC', metadata={'id': 'd2'})\n", (19700, 19730), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((19744, 19777), 'skbio.DNA', 'DNA', (['""".AC"""'], {'metadata': "{'id': 'd3'}"}), "('.AC', metadata={'id': 'd3'})\n", (19747, 19777), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((19797, 19820), 'skbio.Alignment', 'Alignment', (['[d1, d2, d3]'], {}), '([d1, d2, d3])\n', (19806, 19820), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20048, 20088), 'skbio.DNA', 'DNA', (['""".C-GTTGG.."""'], {'metadata': "{'id': 'd1'}"}), "('.C-GTTGG..', metadata={'id': 'd1'})\n", (20051, 20088), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20102, 20142), 'skbio.DNA', 'DNA', (['"""TCGGT-GGCC"""'], {'metadata': "{'id': 'd2'}"}), "('TCGGT-GGCC', metadata={'id': 'd2'})\n", (20105, 20142), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20156, 20196), 'skbio.DNA', 'DNA', (['"""-C-GTTGC--"""'], {'metadata': "{'id': 'd3'}"}), "('-C-GTTGC--', metadata={'id': 'd3'})\n", (20159, 20196), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20216, 20239), 'skbio.Alignment', 'Alignment', (['[d1, d2, d3]'], {}), '([d1, d2, d3])\n', (20225, 20239), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20457, 20490), 'skbio.DNA', 'DNA', (['""".AC"""'], {'metadata': "{'id': 'd1'}"}), "('.AC', metadata={'id': 'd1'})\n", (20460, 20490), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20504, 20537), 'skbio.DNA', 'DNA', (['""".AC"""'], {'metadata': "{'id': 'd3'}"}), "('.AC', metadata={'id': 'd3'})\n", (20507, 20537), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20557, 20576), 'skbio.Alignment', 'Alignment', (['[d1, d3]'], {}), '([d1, d3])\n', (20566, 20576), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20936, 20976), 'skbio.DNA', 'DNA', (['"""TCGGT-GGCC"""'], {'metadata': "{'id': 'd2'}"}), "('TCGGT-GGCC', metadata={'id': 'd2'})\n", (20939, 20976), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((20996, 21011), 'skbio.Alignment', 'Alignment', (['[d2]'], {}), '([d2])\n', (21005, 21011), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((21125, 21138), 'skbio.Alignment', 'Alignment', (['[]'], {}), '([])\n', (21134, 21138), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((21809, 21824), 'skbio.Alignment', 'Alignment', (['seqs'], {}), '(seqs)\n', (21818, 21824), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23148, 23181), 'skbio.DNA', 'DNA', (['"""TTT"""'], {'metadata': "{'id': 'd1'}"}), "('TTT', metadata={'id': 'd1'})\n", (23151, 23181), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23195, 23228), 'skbio.DNA', 'DNA', (['"""TT-"""'], {'metadata': "{'id': 'd2'}"}), "('TT-', metadata={'id': 'd2'})\n", (23198, 23228), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23242, 23275), 'skbio.DNA', 'DNA', (['"""TC-"""'], {'metadata': "{'id': 'd3'}"}), "('TC-', metadata={'id': 'd3'})\n", (23245, 23275), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23289, 23312), 'skbio.Alignment', 'Alignment', (['[d1, d2, d3]'], {}), '([d1, d2, d3])\n', (23298, 23312), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23404, 23435), 'skbio.DNA', 'DNA', (['"""T"""'], {'metadata': "{'id': 'd1'}"}), "('T', metadata={'id': 'd1'})\n", (23407, 23435), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23449, 23480), 'skbio.DNA', 'DNA', (['"""A"""'], {'metadata': "{'id': 'd2'}"}), "('A', metadata={'id': 'd2'})\n", (23452, 23480), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23494, 23513), 'skbio.Alignment', 'Alignment', (['[d1, d2]'], {}), '([d1, d2])\n', (23503, 23513), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23829, 23863), 'skbio.RNA', 'RNA', (['"""UUAU"""'], {'metadata': "{'id': 'r1'}"}), "('UUAU', metadata={'id': 'r1'})\n", (23832, 23863), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23877, 23911), 'skbio.RNA', 'RNA', (['"""ACGU"""'], {'metadata': "{'id': 'r2'}"}), "('ACGU', metadata={'id': 'r2'})\n", (23880, 23911), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23931, 23950), 'skbio.Alignment', 'Alignment', (['[r1, r2]'], {}), '([r1, r2])\n', (23940, 23950), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((24034, 24068), 'skbio.RNA', 'RNA', (['"""UUAU"""'], {'metadata': "{'id': 'r1'}"}), "('UUAU', metadata={'id': 'r1'})\n", (24037, 24068), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((24082, 24116), 'skbio.RNA', 'RNA', (['"""ACGU"""'], {'metadata': "{'id': 'r2'}"}), "('ACGU', metadata={'id': 'r2'})\n", (24085, 24116), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((24136, 24155), 'skbio.Alignment', 'Alignment', (['[r1, r2]'], {}), '([r1, r2])\n', (24145, 24155), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((24712, 24727), 'skbio.Alignment', 'Alignment', (['seqs'], {}), '(seqs)\n', (24721, 24727), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((25153, 25173), 'skbio.Alignment', 'Alignment', (['[self.r2]'], {}), '([self.r2])\n', (25162, 25173), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((28006, 28021), 'skbio.Alignment', 'Alignment', (['seqs'], {}), '(seqs)\n', (28015, 28021), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((30032, 30335), 'collections.OrderedDict', 'OrderedDict', (["[('AC', 'RF00360'), ('BM', ['cmbuild -F CM SEED',\n 'cmsearch -Z 274931 -E 1000000']), ('SQ', '9'), ('RT', ['TITLE1',\n 'TITLE2']), ('RN', ['[1]', '[2]']), ('RA', ['Auth1;', 'Auth2;']), ('RL',\n ['J Mol Biol', 'Cell']), ('RM', ['11469857', '12007400']), ('RN', [\n '[1]', '[2]'])]"], {}), "([('AC', 'RF00360'), ('BM', ['cmbuild -F CM SEED',\n 'cmsearch -Z 274931 -E 1000000']), ('SQ', '9'), ('RT', ['TITLE1',\n 'TITLE2']), ('RN', ['[1]', '[2]']), ('RA', ['Auth1;', 'Auth2;']), ('RL',\n ['J Mol Biol', 'Cell']), ('RM', ['11469857', '12007400']), ('RN', [\n '[1]', '[2]'])])\n", (30043, 30335), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((30720, 30797), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'self.GC', 'gf': 'self.GF', 'gs': 'self.GS', 'gr': 'self.GR'}), '(self.seqs, gc=self.GC, gf=self.GF, gs=self.GS, gr=self.GR)\n', (30738, 30797), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((31207, 31316), 'io.StringIO', 'StringIO', (['"""# STOCKHOLM 1.0\nseq1 ACC-G\nseq2 TCC-G\n\nseq1 -GGTA\nseq2 -GGCA\n//"""'], {}), '(\n """# STOCKHOLM 1.0\nseq1 ACC-G\nseq2 TCC-G\n\nseq1 -GGTA\nseq2 -GGCA\n//"""\n )\n', (31215, 31316), False, 'from io import StringIO\n'), ((31494, 31523), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {}), '(self.seqs)\n', (31512, 31523), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((31690, 32025), 'io.StringIO', 'StringIO', (['"""# STOCKHOLM 1.0\n#=GF RN [1]\n#=GF RM 11469857\n#=GF RT TITLE1\n#=GF RA Auth1;\n#=GF RL J Mol Biol\n#=GF RN [2]\n#=GF RM 12007400\n#=GF RT TITLE2\n#=GF RA Auth2;\n#=GF RL Cell\n#=GF AC RF00360\n#=GF BM cmbuild -F CM SEED\n#=GF BM cmsearch -Z 274931 -E 1000000\n#=GF SQ 9\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n//"""'], {}), '(\n """# STOCKHOLM 1.0\n#=GF RN [1]\n#=GF RM 11469857\n#=GF RT TITLE1\n#=GF RA Auth1;\n#=GF RL J Mol Biol\n#=GF RN [2]\n#=GF RM 12007400\n#=GF RT TITLE2\n#=GF RA Auth2;\n#=GF RL Cell\n#=GF AC RF00360\n#=GF BM cmbuild -F CM SEED\n#=GF BM cmsearch -Z 274931 -E 1000000\n#=GF SQ 9\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n//"""\n )\n', (31698, 32025), False, 'from io import StringIO\n'), ((32266, 32316), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs', 'self.GF', '{}', '{}', '{}'], {}), '(self.seqs, self.GF, {}, {}, {})\n', (32284, 32316), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((32408, 32524), 'io.StringIO', 'StringIO', (['"""# STOCKHOLM 1.0\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n#=GC SS_cons (((....)))\n//"""'], {}), '(\n """# STOCKHOLM 1.0\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n#=GC SS_cons (((....)))\n//"""\n )\n', (32416, 32524), False, 'from io import StringIO\n'), ((32648, 32698), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs', '{}', '{}', '{}', 'self.GC'], {}), '(self.seqs, {}, {}, {}, self.GC)\n', (32666, 32698), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((32790, 32918), 'io.StringIO', 'StringIO', (['"""# STOCKHOLM 1.0\n#=GS seq2 AC 222\n#=GS seq1 AC 111\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n//"""'], {}), '(\n """# STOCKHOLM 1.0\n#=GS seq2 AC 222\n#=GS seq1 AC 111\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n//"""\n )\n', (32798, 32918), False, 'from io import StringIO\n'), ((33043, 33093), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs', '{}', 'self.GS', '{}', '{}'], {}), '(self.seqs, {}, self.GS, {}, {})\n', (33061, 33093), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((33185, 33390), 'io.StringIO', 'StringIO', (['"""# STOCKHOLM 1.0\nseq1 ACC-G\n#=GR seq1 SS 11101\nseq2 TCC-G\n#=GR seq2 SS 01101\n\nseq1 -GGTA\n#=GR seq1 SS 01111\nseq2 -GGCA\n#=GR seq2 SS 01110\n//"""'], {}), '(\n """# STOCKHOLM 1.0\nseq1 ACC-G\n#=GR seq1 SS 11101\nseq2 TCC-G\n#=GR seq2 SS 01101\n\nseq1 -GGTA\n#=GR seq1 SS 01111\nseq2 -GGCA\n#=GR seq2 SS 01110\n//"""\n )\n', (33193, 33390), False, 'from io import StringIO\n'), ((33572, 33622), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs', '{}', '{}', 'self.GR', '{}'], {}), '(self.seqs, {}, {}, self.GR, {})\n', (33590, 33622), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((33717, 33964), 'io.StringIO', 'StringIO', (['"""# STOCKHOLM 1.0\n#=GS seq2 AC 222\n#=GS seq1 AC 111\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n//\n# STOCKHOLM 1.0\nseq1 ACC-G-GGTA\n#=GR seq1 SS 1110101111\nseq2 TCC-G-GGCA\n#=GR seq2 SS 0110101110\n//"""'], {}), '(\n """# STOCKHOLM 1.0\n#=GS seq2 AC 222\n#=GS seq1 AC 111\nseq1 ACC-G-GGTA\nseq2 TCC-G-GGCA\n//\n# STOCKHOLM 1.0\nseq1 ACC-G-GGTA\n#=GR seq1 SS 1110101111\nseq2 TCC-G-GGCA\n#=GR seq2 SS 0110101110\n//"""\n )\n', (33725, 33964), False, 'from io import StringIO\n'), ((34110, 34148), 'skbio.alignment.StockholmAlignment.from_file', 'StockholmAlignment.from_file', (['sto', 'DNA'], {}), '(sto, DNA)\n', (34138, 34148), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((37180, 37257), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'self.GC', 'gf': 'self.GF', 'gs': 'self.GS', 'gr': 'self.GR'}), '(self.seqs, gc=self.GC, gf=self.GF, gs=self.GS, gr=self.GR)\n', (37198, 37257), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((38228, 38305), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'self.GC', 'gf': 'self.GF', 'gs': 'self.GS', 'gr': 'self.GR'}), '(self.seqs, gc=self.GC, gf=self.GF, gs=self.GS, gr=self.GR)\n', (38246, 38305), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((39532, 39600), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'self.GC', 'gf': 'None', 'gs': 'None', 'gr': 'None'}), '(self.seqs, gc=self.GC, gf=None, gs=None, gr=None)\n', (39550, 39600), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((39883, 39951), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'None', 'gf': 'self.GF', 'gs': 'None', 'gr': 'None'}), '(self.seqs, gc=None, gf=self.GF, gs=None, gr=None)\n', (39901, 39951), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((40717, 40785), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'None', 'gf': 'None', 'gs': 'self.GS', 'gr': 'None'}), '(self.seqs, gc=None, gf=None, gs=self.GS, gr=None)\n', (40735, 40785), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((41114, 41182), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'None', 'gf': 'None', 'gs': 'None', 'gr': 'self.GR'}), '(self.seqs, gc=None, gf=None, gs=None, gr=self.GR)\n', (41132, 41182), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((41494, 41566), 'collections.OrderedDict', 'OrderedDict', (["{'NH': ['IMATREE', 'IMATREETOO'], 'TN': ['Tree2', 'Tree1']}"], {}), "({'NH': ['IMATREE', 'IMATREETOO'], 'TN': ['Tree2', 'Tree1']})\n", (41505, 41566), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((41606, 41669), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs'], {'gc': 'None', 'gf': 'GF', 'gs': 'None', 'gr': 'None'}), '(self.seqs, gc=None, gf=GF, gs=None, gr=None)\n', (41624, 41669), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((2384, 2409), 'skbio.SequenceCollection', 'SequenceCollection', (['[seq]'], {}), '([seq])\n', (2402, 2409), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((21581, 21623), 'skbio.DNA', 'DNA', (['""".-ACC-GTGC--"""'], {'metadata': "{'id': 'i2'}"}), "('.-ACC-GTGC--', metadata={'id': 'i2'})\n", (21584, 21623), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22782, 22794), 'skbio.Sequence', 'Sequence', (['""""""'], {}), "('')\n", (22790, 22794), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22874, 22881), 'skbio.RNA', 'RNA', (['""""""'], {}), "('')\n", (22877, 22881), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23105, 23114), 'skbio.DNA', 'DNA', (['"""AG"""'], {}), "('AG')\n", (23108, 23114), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23363, 23373), 'skbio.DNA', 'DNA', (['"""TT-"""'], {}), "('TT-')\n", (23366, 23373), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((25838, 25851), 'skbio.Alignment', 'Alignment', (['[]'], {}), '([])\n', (25847, 25851), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((26043, 26068), 'collections.Counter', 'Counter', (["{'U': 1, 'A': 1}"], {}), "({'U': 1, 'A': 1})\n", (26050, 26068), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26090, 26115), 'collections.Counter', 'Counter', (["{'U': 1, 'C': 1}"], {}), "({'U': 1, 'C': 1})\n", (26097, 26115), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26137, 26162), 'collections.Counter', 'Counter', (["{'A': 1, 'G': 1}"], {}), "({'A': 1, 'G': 1})\n", (26144, 26162), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26184, 26201), 'collections.Counter', 'Counter', (["{'U': 2}"], {}), "({'U': 2})\n", (26191, 26201), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26223, 26248), 'collections.Counter', 'Counter', (["{'-': 1, 'U': 1}"], {}), "({'-': 1, 'U': 1})\n", (26230, 26248), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26513, 26553), 'collections.defaultdict', 'defaultdict', (['float', "{'U': 0.5, 'A': 0.5}"], {}), "(float, {'U': 0.5, 'A': 0.5})\n", (26524, 26553), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26575, 26615), 'collections.defaultdict', 'defaultdict', (['float', "{'U': 0.5, 'C': 0.5}"], {}), "(float, {'U': 0.5, 'C': 0.5})\n", (26586, 26615), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26637, 26677), 'collections.defaultdict', 'defaultdict', (['float', "{'A': 0.5, 'G': 0.5}"], {}), "(float, {'A': 0.5, 'G': 0.5})\n", (26648, 26677), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26699, 26729), 'collections.defaultdict', 'defaultdict', (['float', "{'U': 1.0}"], {}), "(float, {'U': 1.0})\n", (26710, 26729), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((26751, 26791), 'collections.defaultdict', 'defaultdict', (['float', "{'-': 0.5, 'U': 0.5}"], {}), "(float, {'-': 0.5, 'U': 0.5})\n", (26762, 26791), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((28832, 28888), 'collections.defaultdict', 'defaultdict', (['float', "{'U': 3 / 5, 'A': 1 / 5, '-': 1 / 5}"], {}), "(float, {'U': 3 / 5, 'A': 1 / 5, '-': 1 / 5})\n", (28843, 28888), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((28910, 28978), 'collections.defaultdict', 'defaultdict', (['float', "{'A': 1 / 5, 'C': 1 / 5, 'G': 1 / 5, 'U': 2 / 5}"], {}), "(float, {'A': 1 / 5, 'C': 1 / 5, 'G': 1 / 5, 'U': 2 / 5})\n", (28921, 28978), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((29905, 29947), 'skbio.DNA', 'DNA', (['"""ACC-G-GGTA"""'], {'metadata': "{'id': 'seq1'}"}), "('ACC-G-GGTA', metadata={'id': 'seq1'})\n", (29908, 29947), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((29970, 30012), 'skbio.DNA', 'DNA', (['"""TCC-G-GGCA"""'], {'metadata': "{'id': 'seq2'}"}), "('TCC-G-GGCA', metadata={'id': 'seq2'})\n", (29973, 30012), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((30483, 30530), 'collections.OrderedDict', 'OrderedDict', (["[('seq1', '111'), ('seq2', '222')]"], {}), "([('seq1', '111'), ('seq2', '222')])\n", (30494, 30530), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((30557, 30618), 'collections.OrderedDict', 'OrderedDict', (["[('seq1', '1110101111'), ('seq2', '0110101110')]"], {}), "([('seq1', '1110101111'), ('seq2', '0110101110')])\n", (30568, 30618), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((31436, 31474), 'skbio.alignment.StockholmAlignment.from_file', 'StockholmAlignment.from_file', (['sto', 'DNA'], {}), '(sto, DNA)\n', (31464, 31474), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((32208, 32246), 'skbio.alignment.StockholmAlignment.from_file', 'StockholmAlignment.from_file', (['sto', 'DNA'], {}), '(sto, DNA)\n', (32236, 32246), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((32590, 32628), 'skbio.alignment.StockholmAlignment.from_file', 'StockholmAlignment.from_file', (['sto', 'DNA'], {}), '(sto, DNA)\n', (32618, 32628), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((32985, 33023), 'skbio.alignment.StockholmAlignment.from_file', 'StockholmAlignment.from_file', (['sto', 'DNA'], {}), '(sto, DNA)\n', (33013, 33023), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((33514, 33552), 'skbio.alignment.StockholmAlignment.from_file', 'StockholmAlignment.from_file', (['sto', 'DNA'], {}), '(sto, DNA)\n', (33542, 33552), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((38352, 38385), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', (['"""r+"""'], {}), "('r+')\n", (38379, 38385), False, 'import tempfile\n'), ((2754, 2792), 'skbio.SequenceCollection', 'SequenceCollection', (['[self.d1, self.d2]'], {}), '([self.d1, self.d2])\n', (2772, 2792), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((2818, 2856), 'skbio.SequenceCollection', 'SequenceCollection', (['[self.d1, self.d2]'], {}), '([self.d1, self.d2])\n', (2836, 2856), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((2985, 3014), 'skbio.SequenceCollection', 'SequenceCollection', (['[self.d1]'], {}), '([self.d1])\n', (3003, 3014), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((3271, 3300), 'skbio.Alignment', 'Alignment', (['[self.d1, self.d3]'], {}), '([self.d1, self.d3])\n', (3280, 3300), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((3408, 3446), 'skbio.SequenceCollection', 'SequenceCollection', (['[self.d1, self.r1]'], {}), '([self.d1, self.r1])\n', (3426, 3446), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((4533, 4562), 'skbio.SequenceCollection', 'SequenceCollection', (['[self.d1]'], {}), '([self.d1])\n', (4551, 4562), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((4817, 4846), 'skbio.Alignment', 'Alignment', (['[self.d1, self.d3]'], {}), '([self.d1, self.d3])\n', (4826, 4846), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((4977, 5015), 'skbio.SequenceCollection', 'SequenceCollection', (['[self.d1, self.r1]'], {}), '([self.d1, self.r1])\n', (4995, 5015), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((7230, 7266), 'skbio.RNA', 'RNA', (["('C' * 10)"], {'metadata': "{'id': 's1'}"}), "('C' * 10, metadata={'id': 's1'})\n", (7233, 7266), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((7301, 7337), 'skbio.RNA', 'RNA', (["('G' * 10)"], {'metadata': "{'id': 's2'}"}), "('G' * 10, metadata={'id': 's2'})\n", (7304, 7337), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((7430, 7460), 'collections.defaultdict', 'defaultdict', (['float', "{'C': 1.0}"], {}), "(float, {'C': 1.0})\n", (7441, 7460), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((7488, 7518), 'collections.defaultdict', 'defaultdict', (['float', "{'G': 1.0}"], {}), "(float, {'G': 1.0})\n", (7499, 7518), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((7869, 7903), 'skbio.DNA', 'DNA', (['"""ACGT"""'], {'metadata': "{'id': 'd1'}"}), "('ACGT', metadata={'id': 'd1'})\n", (7872, 7903), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((7938, 7972), 'skbio.DNA', 'DNA', (['"""ACGG"""'], {'metadata': "{'id': 'd2'}"}), "('ACGG', metadata={'id': 'd2'})\n", (7941, 7972), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((9354, 9391), 'skbio.RNA', 'RNA', (['"""GAUUACA"""'], {'metadata': "{'id': 'r1'}"}), "('GAUUACA', metadata={'id': 'r1'})\n", (9357, 9391), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((9405, 9438), 'skbio.RNA', 'RNA', (['"""UUG"""'], {'metadata': "{'id': 'r2'}"}), "('UUG', metadata={'id': 'r2'})\n", (9408, 9438), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((9452, 9487), 'skbio.RNA', 'RNA', (['"""UUGCC"""'], {'metadata': "{'id': 'r3'}"}), "('UUGCC', metadata={'id': 'r3'})\n", (9455, 9487), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((10108, 10144), 'skbio.RNA', 'RNA', (['"""GAUUACA"""'], {'metadata': "{'id': '1'}"}), "('GAUUACA', metadata={'id': '1'})\n", (10111, 10144), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((10158, 10190), 'skbio.RNA', 'RNA', (['"""UUG"""'], {'metadata': "{'id': '2'}"}), "('UUG', metadata={'id': '2'})\n", (10161, 10190), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((10204, 10245), 'skbio.RNA', 'RNA', (['"""U-----UGCC--"""'], {'metadata': "{'id': '3'}"}), "('U-----UGCC--', metadata={'id': '3'})\n", (10207, 10245), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((10714, 10753), 'skbio.RNA', 'RNA', (['"""GAUUACA"""'], {'metadata': "{'id': 'abc1'}"}), "('GAUUACA', metadata={'id': 'abc1'})\n", (10717, 10753), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((10767, 10802), 'skbio.RNA', 'RNA', (['"""UUG"""'], {'metadata': "{'id': 'abc2'}"}), "('UUG', metadata={'id': 'abc2'})\n", (10770, 10802), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((10816, 10860), 'skbio.RNA', 'RNA', (['"""U-----UGCC--"""'], {'metadata': "{'id': 'abc3'}"}), "('U-----UGCC--', metadata={'id': 'abc3'})\n", (10819, 10860), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((11447, 11487), 'skbio.RNA', 'RNA', (['"""GAUUACA"""'], {'metadata': "{'id': 'r1-42'}"}), "('GAUUACA', metadata={'id': 'r1-42'})\n", (11450, 11487), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((11501, 11537), 'skbio.RNA', 'RNA', (['"""UUG"""'], {'metadata': "{'id': 'r2-42'}"}), "('UUG', metadata={'id': 'r2-42'})\n", (11504, 11537), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((11551, 11596), 'skbio.RNA', 'RNA', (['"""U-----UGCC--"""'], {'metadata': "{'id': 'r3-42'}"}), "('U-----UGCC--', metadata={'id': 'r3-42'})\n", (11554, 11596), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((12112, 12150), 'skbio.RNA', 'RNA', (['"""GAUUACA"""'], {'metadata': "{'id': 'abc'}"}), "('GAUUACA', metadata={'id': 'abc'})\n", (12115, 12150), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((12164, 12198), 'skbio.RNA', 'RNA', (['"""UUG"""'], {'metadata': "{'id': 'def'}"}), "('UUG', metadata={'id': 'def'})\n", (12167, 12198), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((12212, 12255), 'skbio.RNA', 'RNA', (['"""U-----UGCC--"""'], {'metadata': "{'id': 'ghi'}"}), "('U-----UGCC--', metadata={'id': 'ghi'})\n", (12215, 12255), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((13677, 13788), 'skbio.DNA', 'DNA', (['"""ACGT"""'], {'metadata': "{'id': 'seq1', 'description': 'desc1'}", 'positional_metadata': "{'quality': (0, 1, 2, 3)}"}), "('ACGT', metadata={'id': 'seq1', 'description': 'desc1'},\n positional_metadata={'quality': (0, 1, 2, 3)})\n", (13680, 13788), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((13814, 13925), 'skbio.DNA', 'DNA', (['"""TGCA"""'], {'metadata': "{'id': 'seq2', 'description': 'desc2'}", 'positional_metadata': "{'quality': (3, 2, 1, 0)}"}), "('TGCA', metadata={'id': 'seq2', 'description': 'desc2'},\n positional_metadata={'quality': (3, 2, 1, 0)})\n", (13817, 13925), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17046, 17075), 'skbio.RNA', 'RNA', (['""""""'], {'metadata': "{'id': 'a'}"}), "('', metadata={'id': 'a'})\n", (17049, 17075), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17116, 17145), 'skbio.RNA', 'RNA', (['""""""'], {'metadata': "{'id': 'b'}"}), "('', metadata={'id': 'b'})\n", (17119, 17145), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17227, 17265), 'skbio.DNA', 'DNA', (['"""ACCGTTGG"""'], {'metadata': "{'id': 'd1'}"}), "('ACCGTTGG', metadata={'id': 'd1'})\n", (17230, 17265), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17279, 17321), 'skbio.DNA', 'DNA', (['"""TTACCGGTGGCC"""'], {'metadata': "{'id': 'd2'}"}), "('TTACCGGTGGCC', metadata={'id': 'd2'})\n", (17282, 17321), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17335, 17373), 'skbio.DNA', 'DNA', (['"""ACCGTTGC"""'], {'metadata': "{'id': 'd3'}"}), "('ACCGTTGC', metadata={'id': 'd3'})\n", (17338, 17373), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17505, 17539), 'skbio.RNA', 'RNA', (['"""UUAU"""'], {'metadata': "{'id': 'r1'}"}), "('UUAU', metadata={'id': 'r1'})\n", (17508, 17539), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((17553, 17588), 'skbio.RNA', 'RNA', (['"""ACGUU"""'], {'metadata': "{'id': 'r2'}"}), "('ACGUU', metadata={'id': 'r2'})\n", (17556, 17588), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((21943, 21974), 'skbio.RNA', 'RNA', (['"""U"""'], {'metadata': "{'id': 'r1'}"}), "('U', metadata={'id': 'r1'})\n", (21946, 21974), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((21976, 22007), 'skbio.RNA', 'RNA', (['"""A"""'], {'metadata': "{'id': 'r2'}"}), "('A', metadata={'id': 'r2'})\n", (21979, 22007), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22023, 22054), 'skbio.RNA', 'RNA', (['"""U"""'], {'metadata': "{'id': 'r1'}"}), "('U', metadata={'id': 'r1'})\n", (22026, 22054), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22056, 22087), 'skbio.RNA', 'RNA', (['"""C"""'], {'metadata': "{'id': 'r2'}"}), "('C', metadata={'id': 'r2'})\n", (22059, 22087), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22103, 22134), 'skbio.RNA', 'RNA', (['"""A"""'], {'metadata': "{'id': 'r1'}"}), "('A', metadata={'id': 'r1'})\n", (22106, 22134), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22136, 22167), 'skbio.RNA', 'RNA', (['"""G"""'], {'metadata': "{'id': 'r2'}"}), "('G', metadata={'id': 'r2'})\n", (22139, 22167), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22183, 22214), 'skbio.RNA', 'RNA', (['"""U"""'], {'metadata': "{'id': 'r1'}"}), "('U', metadata={'id': 'r1'})\n", (22186, 22214), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22216, 22247), 'skbio.RNA', 'RNA', (['"""U"""'], {'metadata': "{'id': 'r2'}"}), "('U', metadata={'id': 'r2'})\n", (22219, 22247), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22263, 22294), 'skbio.RNA', 'RNA', (['"""-"""'], {'metadata': "{'id': 'r1'}"}), "('-', metadata={'id': 'r1'})\n", (22266, 22294), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22296, 22327), 'skbio.RNA', 'RNA', (['"""U"""'], {'metadata': "{'id': 'r2'}"}), "('U', metadata={'id': 'r2'})\n", (22299, 22327), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((22962, 22993), 'skbio.DNA', 'DNA', (['"""AG"""'], {'metadata': "{'id': 'a'}"}), "('AG', metadata={'id': 'a'})\n", (22965, 22993), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23020, 23051), 'skbio.DNA', 'DNA', (['"""AG"""'], {'metadata': "{'id': 'b'}"}), "('AG', metadata={'id': 'b'})\n", (23023, 23051), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((25635, 25672), 'skbio.DNA', 'DNA', (["('.' * 33)"], {'metadata': "{'id': 'abc'}"}), "('.' * 33, metadata={'id': 'abc'})\n", (25638, 25672), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((25699, 25736), 'skbio.DNA', 'DNA', (["('-' * 33)"], {'metadata': "{'id': 'def'}"}), "('-' * 33, metadata={'id': 'def'})\n", (25702, 25736), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((28101, 28131), 'collections.defaultdict', 'defaultdict', (['float', "{'A': 1.0}"], {}), "(float, {'A': 1.0})\n", (28112, 28131), False, 'from collections import Counter, defaultdict, OrderedDict\n'), ((34248, 34298), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs', '{}', 'self.GS', '{}', '{}'], {}), '(self.seqs, {}, self.GS, {}, {})\n', (34266, 34298), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((23590, 23598), 'skbio.DNA', 'DNA', (['"""T"""'], {}), "('T')\n", (23593, 23598), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((23600, 23608), 'skbio.DNA', 'DNA', (['"""A"""'], {}), "('A')\n", (23603, 23608), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n'), ((34401, 34451), 'skbio.alignment.StockholmAlignment', 'StockholmAlignment', (['self.seqs', '{}', '{}', 'self.GR', '{}'], {}), '(self.seqs, {}, {}, self.GR, {})\n', (34419, 34451), False, 'from skbio.alignment import StockholmAlignment, SequenceCollectionError, StockholmParseError, AlignmentError\n'), ((24780, 24795), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (24788, 24795), True, 'import numpy as np\n'), ((25791, 25806), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (25799, 25806), True, 'import numpy as np\n'), ((29763, 29796), 'skbio.DNA', 'DNA', (['"""TTT"""'], {'metadata': "{'id': 'd1'}"}), "('TTT', metadata={'id': 'd1'})\n", (29766, 29796), False, 'from skbio import Sequence, DNA, RNA, DistanceMatrix, Alignment, SequenceCollection\n')] |
#!/usr/bin/python
'''Takes a database file as an argument, compares localfiles and esgffiles,
and creates a table "failed_dl" that contains files that did not show
up in the local storage tree.'''
import sys
import apsw
import numpy as np
#dbname = sys.argv[1]
def connect(dbname):
conn = apsw.Connection(dbname)
c = conn.cursor()
return((conn, c))
def read_chksums(c, table):
selstring = 'SELECT checksum, checksum_type FROM esgffiles' \
if table == 'esgffiles' \
else 'SELECT md5, sha256 FROM localfiles'
chk_esgf = c.execute(selstring).fetchall()
return(chk_esgf)
def mk_failed_table(c):
c.execute('''DROP TABLE IF EXISTS failed''')
c.execute(''' CREATE TABLE failed AS
SELECT * FROM esgffiles WHERE 1=2''')
allfields = c.execute("PRAGMA table_info(failed)").fetchall()
allfields = [x[1] for x in allfields]
for idx_col in allfields:
c.execute("CREATE INDEX IF NOT EXISTS {0} ON {2} ({1})".
format("idx_failed_"+idx_col, idx_col, "failed"))
def get_failed(c, resloc, resesgf):
setloc = np.array([max(x) for x in resloc])
setesgf = np.array([x[0] for x in resesgf])
failedidx = np.logical_not(np.in1d(setesgf, setloc))
failedfiles = setesgf[failedidx]
ffstring = "('"+"','".join(failedfiles) + "')"
c.execute('''INSERT OR REPLACE INTO failed
SELECT * FROM esgffiles
WHERE checksum IN {0}'''.format(ffstring))
if __name__ == "__main__":
conn, c = connect(dbname)
resloc = read_chksums(c, 'localfiles')
resesgf = read_chksums(c, 'esgffiles')
print("Files in esgf: {0},\n Files in local: {1}"
.format(len(resesgf), len(resloc)))
mk_failed_table(c)
get_failed(c, resloc, resesgf)
c.close()
| [
"apsw.Connection",
"numpy.array",
"numpy.in1d"
] | [((299, 322), 'apsw.Connection', 'apsw.Connection', (['dbname'], {}), '(dbname)\n', (314, 322), False, 'import apsw\n'), ((1174, 1207), 'numpy.array', 'np.array', (['[x[0] for x in resesgf]'], {}), '([x[0] for x in resesgf])\n', (1182, 1207), True, 'import numpy as np\n'), ((1239, 1263), 'numpy.in1d', 'np.in1d', (['setesgf', 'setloc'], {}), '(setesgf, setloc)\n', (1246, 1263), True, 'import numpy as np\n')] |
from __future__ import annotations
import copy
import attr
import torch
import numpy as np
import typing
from evocraft_ga.nn.linear import Linear
from evocraft_ga.nn.cppn import CPPN
model_dict = {"linear": Linear, "cppn": CPPN}
@attr.s
class Genome:
noise_dims: int = attr.ib()
cube_dims: int = attr.ib()
seeds: typing.List[int] = attr.ib(default=[])
noise_stdev: float = attr.ib(default=1.0)
num_classes: int = attr.ib(default=1)
model_class: str = attr.ib(default="linear")
# set later
_model_class = attr.ib(init=False)
model = attr.ib(init=False)
def __attrs_post_init__(self):
self._verify_seeds(self.seeds)
self._model_class = model_dict.get(self.model_class, model_dict["linear"])
self.model = self._model_class(
self.noise_dims,
self.cube_dims,
self.cube_dims,
self.cube_dims,
num_classes=self.num_classes,
)
self.initialize_weights()
def _verify_seeds(self, seeds):
if len(seeds) == 0:
seeds = [np.random.randint(1, high=2 ** 31 - 1)]
self.seeds = seeds.copy()
def initialize_weights(self) -> None:
num_seeds = len(self.seeds)
rs = np.random.RandomState(self.seeds[0])
for n, W in self.model.named_parameters():
if any(x in n for x in ["weight", "bias"]):
weights = rs.normal(loc=0.0, scale=self.noise_stdev, size=W.size())
W.data = torch.from_numpy(weights).float()
for seed_num in range(1, num_seeds):
rs = np.random.RandomState(self.seeds[seed_num])
for name, W in self.model.named_parameters():
if any(x in name for x in ["weight", "bias"]):
weights = (
rs.normal(loc=0.0, scale=1.0, size=W.size()) * self.noise_stdev
)
W.data = W.data + torch.from_numpy(weights).float()
def mutate(self):
new_seed = np.random.randint(1, high=2 ** 31 - 1)
self.seeds.append(new_seed)
self.initialize_weights()
def generate(self, to_numpy=False, squeeze=False, seed=None):
return self.model.generate(to_numpy=to_numpy, squeeze=squeeze, seed=seed)
def copy_parameters(self, genome: Genome):
self.seeds = copy.deepcopy(genome.seeds)
| [
"copy.deepcopy",
"attr.ib",
"numpy.random.RandomState",
"numpy.random.randint",
"torch.from_numpy"
] | [((277, 286), 'attr.ib', 'attr.ib', ([], {}), '()\n', (284, 286), False, 'import attr\n'), ((308, 317), 'attr.ib', 'attr.ib', ([], {}), '()\n', (315, 317), False, 'import attr\n'), ((348, 367), 'attr.ib', 'attr.ib', ([], {'default': '[]'}), '(default=[])\n', (355, 367), False, 'import attr\n'), ((393, 413), 'attr.ib', 'attr.ib', ([], {'default': '(1.0)'}), '(default=1.0)\n', (400, 413), False, 'import attr\n'), ((437, 455), 'attr.ib', 'attr.ib', ([], {'default': '(1)'}), '(default=1)\n', (444, 455), False, 'import attr\n'), ((479, 504), 'attr.ib', 'attr.ib', ([], {'default': '"""linear"""'}), "(default='linear')\n", (486, 504), False, 'import attr\n'), ((540, 559), 'attr.ib', 'attr.ib', ([], {'init': '(False)'}), '(init=False)\n', (547, 559), False, 'import attr\n'), ((572, 591), 'attr.ib', 'attr.ib', ([], {'init': '(False)'}), '(init=False)\n', (579, 591), False, 'import attr\n'), ((1242, 1278), 'numpy.random.RandomState', 'np.random.RandomState', (['self.seeds[0]'], {}), '(self.seeds[0])\n', (1263, 1278), True, 'import numpy as np\n'), ((2013, 2051), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(2 ** 31 - 1)'}), '(1, high=2 ** 31 - 1)\n', (2030, 2051), True, 'import numpy as np\n'), ((2340, 2367), 'copy.deepcopy', 'copy.deepcopy', (['genome.seeds'], {}), '(genome.seeds)\n', (2353, 2367), False, 'import copy\n'), ((1592, 1635), 'numpy.random.RandomState', 'np.random.RandomState', (['self.seeds[seed_num]'], {}), '(self.seeds[seed_num])\n', (1613, 1635), True, 'import numpy as np\n'), ((1075, 1113), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(2 ** 31 - 1)'}), '(1, high=2 ** 31 - 1)\n', (1092, 1113), True, 'import numpy as np\n'), ((1495, 1520), 'torch.from_numpy', 'torch.from_numpy', (['weights'], {}), '(weights)\n', (1511, 1520), False, 'import torch\n'), ((1937, 1962), 'torch.from_numpy', 'torch.from_numpy', (['weights'], {}), '(weights)\n', (1953, 1962), False, 'import torch\n')] |
"""
University of Minnesota
Aerospace Engineering and Mechanics - UAV Lab
Copyright 2019 Regents of the University of Minnesota
See: LICENSE.md for complete license details
Author: <NAME>
Analysis for Huginn (mAEWing2) FLT 03-06
"""
#%%
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
# Hack to allow loading the Core package
if __name__ == "__main__" and __package__ is None:
from sys import path, argv
from os.path import dirname, abspath, join
path.insert(0, abspath(join(dirname(argv[0]), "..")))
path.insert(0, abspath(join(dirname(argv[0]), "..", 'Core')))
del path, argv, dirname, abspath, join
from Core import Loader
from Core import OpenData
# Constants
hz2rps = 2 * np.pi
rps2hz = 1 / hz2rps
#%% File Lists
import os.path as path
pathBase = path.join('/home', 'rega0051', 'FlightArchive', 'Huginn')
#pathBase = path.join('G:', 'Shared drives', 'UAVLab', 'Flight Data', 'Huginn')
#pathBase = path.join('D:/', 'Huginn')
fileList = {}
flt = 'FLT03'
fileList[flt] = {}
fileList[flt]['log'] = path.join(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')
fileList[flt]['config'] = path.join(pathBase, 'Huginn' + flt, 'huginn.json')
fileList[flt]['def'] = path.join(pathBase, 'Huginn' + flt, 'huginn_def.json')
flt = 'FLT04'
fileList[flt] = {}
fileList[flt]['log'] = path.join(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')
fileList[flt]['config'] = path.join(pathBase, 'Huginn' + flt, 'huginn.json')
fileList[flt]['def'] = path.join(pathBase, 'Huginn' + flt, 'huginn_def.json')
flt = 'FLT05'
fileList[flt] = {}
fileList[flt]['log'] = path.join(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')
fileList[flt]['config'] = path.join(pathBase, 'Huginn' + flt, 'huginn.json')
fileList[flt]['def'] = path.join(pathBase, 'Huginn' + flt, 'huginn_def.json')
flt = 'FLT06'
fileList[flt] = {}
fileList[flt]['log'] = path.join(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')
fileList[flt]['config'] = path.join(pathBase, 'Huginn' + flt, 'huginn.json')
fileList[flt]['def'] = path.join(pathBase, 'Huginn' + flt, 'huginn_def.json')
#%%
from Core import FreqTrans
rtsmSegList = [
{'flt': 'FLT03', 'seg': ('time_us', [693458513 , 705458513], 'FLT03 - 23 m/s'), 'fmt': 'k'}, # 23 m/s
{'flt': 'FLT03', 'seg': ('time_us', [865877709 , 877877709], 'FLT03 - 20 m/s'), 'fmt': 'k'}, # 20 m/s
{'flt': 'FLT04', 'seg': ('time_us', [884683583, 896683583], 'FLT04 - 26 m/s'), 'fmt': 'k'}, # 26 m/s
{'flt': 'FLT04', 'seg': ('time_us', [998733748, 1010733748], 'FLT04 - 20 m/s'), 'fmt': 'k'}, # 20 m/s
{'flt': 'FLT06', 'seg': ('time_us', [1122539650, 1134539650], 'FLT06 - 23 m/s'), 'fmt': 'k'}, # 23 m/s
{'flt': 'FLT05', 'seg': ('time_us', [582408497, 594408497], 'FLT05 - 26 m/s'), 'fmt': 'b'}, # 26 m/s
{'flt': 'FLT05', 'seg': ('time_us', [799488311, 811488311], 'FLT05 - 29 m/s'), 'fmt': 'g'}, # 29 m/s
{'flt': 'FLT06', 'seg': ('time_us', [955822061, 967822061], 'FLT06 - 32 m/s'), 'fmt': 'm'}, # 32 m/s
]
oDataSegs = []
for rtsmSeg in rtsmSegList:
fltNum = rtsmSeg['flt']
fileLog = fileList[fltNum]['log']
fileConfig = fileList[fltNum]['config']
# Load
h5Data = Loader.Load_h5(fileLog) # RAPTRS log data as hdf5
sysConfig = Loader.JsonRead(fileConfig)
oData = Loader.OpenData_RAPTRS(h5Data, sysConfig)
# Create Signal for Bending Measurement
aZ = np.array([
oData['aCenterFwdIMU_IMU_mps2'][2] - oData['aCenterFwdIMU_IMU_mps2'][2][0],
oData['aCenterAftIMU_IMU_mps2'][2] - oData['aCenterAftIMU_IMU_mps2'][2][0],
oData['aLeftMidIMU_IMU_mps2'][2] - oData['aLeftMidIMU_IMU_mps2'][2][0],
oData['aLeftFwdIMU_IMU_mps2'][2] - oData['aLeftFwdIMU_IMU_mps2'][2][0],
oData['aLeftAftIMU_IMU_mps2'][2] - oData['aLeftAftIMU_IMU_mps2'][2][0],
oData['aRightMidIMU_IMU_mps2'][2] - oData['aRightMidIMU_IMU_mps2'][2][0],
oData['aRightFwdIMU_IMU_mps2'][2] - oData['aRightFwdIMU_IMU_mps2'][2][0],
oData['aRightAftIMU_IMU_mps2'][2] - oData['aRightAftIMU_IMU_mps2'][2][0]
])
aCoefEta1 = np.array([456.1, -565.1, -289.9, 605.4, 472.4, -292, 605.6, 472.2]) * 0.3048
measEta1 = aCoefEta1 @ (aZ - np.mean(aZ, axis = 0)) * 1/50 * 1e-3
aCoefEta1dt = np.array([2.956, -2.998, -1.141, 5.974, 5.349, -1.149, 5.974, 5.348]) * 0.3048
measEta1dt = aCoefEta1dt @ (aZ - np.mean(aZ, axis = 0)) * 1e-3
# Added signals
oData['cmdRoll_FF'] = h5Data['Control']['cmdRoll_PID_rpsFF']
oData['cmdRoll_FB'] = h5Data['Control']['cmdRoll_PID_rpsFB']
oData['cmdPitch_FF'] = h5Data['Control']['cmdPitch_PID_rpsFF']
oData['cmdPitch_FB'] = h5Data['Control']['cmdPitch_PID_rpsFB']
oData['cmdBend_FF'] = h5Data['Control']['refBend_nd'] # h5Data['Excitation']['Bend']['cmdBend_nd']
oData['cmdBendDt_FB'] = measEta1dt
oData['cmdBend_FB'] = measEta1
# Segments
seg = OpenData.Segment(oData, rtsmSeg['seg'])
oDataSegs.append(seg)
# plt.plot(seg['time_s'], seg['Control']['cmdBend_nd'], seg['time_s'], seg['cmdBendDt_FB'], seg['time_s'], seg['cmdBend_FB'])
#%%
sigExcList = ['cmdRoll_rps', 'cmdPitch_rps', 'cmdBend_nd']
sigFbList = ['cmdRoll_FB', 'cmdPitch_FB', 'cmdBend_FB']
sigFfList = ['cmdRoll_FF', 'cmdPitch_FF', 'cmdBend_FF']
freqExc_rps = []
freqExc_rps.append( np.array(sysConfig['Excitation']['OMS_RTSM_1']['Frequency']))
freqExc_rps.append( np.array(sysConfig['Excitation']['OMS_RTSM_2']['Frequency']))
freqExc_rps.append( np.array(sysConfig['Excitation']['OMS_RTSM_3']['Frequency']))
vCmdList = []
vExcList = []
vFbList = []
vFfList = []
for iSeg, seg in enumerate(oDataSegs):
vCmd = np.zeros((len(sigExcList), len(seg['time_s'])))
vExc = np.zeros((len(sigExcList), len(seg['time_s'])))
vFb = np.zeros((len(sigExcList), len(seg['time_s'])))
vFf = np.zeros((len(sigExcList), len(seg['time_s'])))
for iSig, sigExc in enumerate(sigExcList):
sigFb = sigFbList[iSig]
sigFf = sigFfList[iSig]
vCmd[iSig] = seg['Control'][sigExc]
vExc[iSig] = seg['Excitation'][sigExc]
vFb[iSig][1:-1] = seg[sigFb][0:-2] # Shift the time of the output into next frame
vFf[iSig] = seg[sigFf]
vCmdList.append(vCmd)
vExcList.append(vExc)
vFbList.append(vFb)
vFfList.append(vFf)
plt.plot(oDataSegs[iSeg]['time_s'], oDataSegs[iSeg]['vIas_mps'])
# plt.plot(oDataSegs[iSeg]['time_s'], vExcList[iSeg][0])
# plt.plot(oDataSegs[iSeg]['time_s'], vExcList[iSeg][1])
# plt.plot(oDataSegs[iSeg]['time_s'], vExcList[iSeg][2])
# plt.plot(oDataSegs[iSeg]['time_s'], vFbList[iSeg][0])
# plt.plot(oDataSegs[iSeg]['time_s'], vFbList[iSeg][1])
# plt.plot(oDataSegs[iSeg]['time_s'], vFbList[iSeg][2])
#%% Estimate the frequency response function
# Define the excitation frequencies
freqRate_hz = 50
freqRate_rps = freqRate_hz * hz2rps
optSpec = FreqTrans.OptSpect(dftType = 'czt', freqRate = freqRate_rps, smooth = ('box', 3), winType = ('tukey', 0.2), detrendType = 'Linear')
# Excited Frequencies per input channel
optSpec.freq = np.asarray(freqExc_rps)
optSpec.freqInterp = np.sort(optSpec.freq.flatten())
# Null Frequencies
freqGap_rps = optSpec.freq.flatten()[0:-1] + 0.5 * np.diff(optSpec.freq.flatten())
optSpec.freqNull = freqGap_rps
optSpec.freqNullInterp = True
# FRF Estimate
T = []
TUnc = []
C = []
for iSeg, seg in enumerate(oDataSegs):
freq_rps, Teb, Ceb, Pee, Pbb, Peb, TebUnc, Pee_N, Pbb_N = FreqTrans.FreqRespFuncEstNoise(vExcList[iSeg], vFbList[iSeg], optSpec)
_ , Tev, Cev, _ , Pvv, Pev, TevUnc, _ , Pvv_N = FreqTrans.FreqRespFuncEstNoise(vExcList[iSeg], vCmdList[iSeg], optSpec)
freq_hz = freq_rps * rps2hz
# Form the Frequency Response
T_seg = np.empty_like(Tev)
TUnc_seg = np.empty_like(Tev)
for i in range(T_seg.shape[-1]):
T_seg[...,i] = Teb[...,i] @ np.linalg.inv(Tev[...,i])
TUnc_seg[...,i] = TebUnc[...,i] @ np.linalg.inv(Tev[...,i])
T.append( T_seg )
TUnc.append( np.abs(TUnc_seg) )
# C.append(Cev)
C.append(Ceb)
T_InputNames = sigExcList
T_OutputNames = sigFbList
# Compute Gain, Phase, Crit Distance
gain_mag = []
gainUnc_mag = []
phase_deg = []
rCritNom_mag = []
rCritUnc_mag = []
rCrit_mag = []
sNom = []
sUnc = []
for iSeg in range(0, len(oDataSegs)):
gainElem_mag, gainElemUnc_mag, gainElemDiff_mag = FreqTrans.DistCritCirc(T[iSeg], TUnc[iSeg], pCrit = 0+0j, typeNorm = 'RSS')
gain_mag.append(gainElem_mag)
gainUnc_mag.append(gainElemUnc_mag)
phase_deg.append(FreqTrans.Phase(T[iSeg], phaseUnit = 'deg', unwrap = True))
nom_mag, unc_mag, diff_mag = FreqTrans.DistCritCirc(T[iSeg], TUnc[iSeg], pCrit = -1+0j, typeNorm = 'RSS')
rCritNom_mag.append(nom_mag)
rCritUnc_mag.append(unc_mag)
rCrit_mag.append(diff_mag)
sNom_seg, sUnc_seg = FreqTrans.Sigma(T[iSeg], TUnc[iSeg]) # Singular Value Decomp, U @ S @ Vh == T[...,i]
sNom.append(sNom_seg)
sUnc.append(sUnc_seg)
#%% Spectrograms
if False:
#%%
iSgnlExc = 0
iSgnlOut = 0
freqRate_rps = 50 * hz2rps
optSpec = FreqTrans.OptSpect(dftType = 'dftmat', freq = freqExc_rps[iSgnlExc], freqRate = freqRate_rps, smooth = ('box', 3), winType = ('tukey', 0.0), detrendType = 'Linear')
optSpecN = FreqTrans.OptSpect(dftType = 'dftmat', freq = freqGap_rps, freqRate = freqRate_rps, smooth = ('box', 3), winType = ('tukey', 0.0), detrendType = 'Linear')
for iSeg in range(0, len(oDataSegs)):
t = oDataSegs[iSeg]['time_s']
x = vExcList[iSeg][iSgnlExc]
y = vFbList[iSeg][iSgnlOut]
# Number of time segments and length of overlap, units of samples
#lenSeg = 2**6 - 1
lenSeg = int(1.0 * optSpec.freqRate * rps2hz)
lenOverlap = 1
# Compute Spectrum over time
tSpecY_s, freqSpecY_rps, P_Y_mag = FreqTrans.SpectTime(t, y, lenSeg, lenOverlap, optSpec)
tSpecN_s, freqSpecN_rps, P_N_mag = FreqTrans.SpectTime(t, y, lenSeg, lenOverlap, optSpecN)
# Plot the Spectrogram
fig = FreqTrans.Spectogram(tSpecY_s, freqSpecY_rps * rps2hz, 20 * np.log10(P_Y_mag))
fig.suptitle(oDataSegs[iSeg]['Desc'] + ': Spectrogram - ' + sigFbList[iSgnlOut])
fig = FreqTrans.Spectogram(tSpecN_s, freqSpecN_rps * rps2hz, 20 * np.log10(P_N_mag))
fig.suptitle(oDataSegs[iSeg]['Desc'] + ': Spectrogram Null - ' + sigFbList[iSgnlOut])
#%% Sigma Plot
fig = None
for iSeg in range(0, len(oDataSegs)):
Cmin = np.min(np.min(C[iSeg], axis = 0), axis = 0)
sNomMin = np.min(sNom[iSeg], axis=0)
sCritMin = np.min(sUnc[iSeg], axis=0)
sNomMinErr = sNomMin - sCritMin
fig = FreqTrans.PlotSigma(freq_hz[0], sNomMin, err = sNomMinErr, coher_nd = Cmin, fig = fig, fmt = rtsmSegList[iSeg]['fmt'] + '*-', label = oDataSegs[iSeg]['Desc'])
fig = FreqTrans.PlotSigma(freq_hz[0], 0.4 * np.ones_like(freq_hz[0]), fmt = '--r', fig = fig)
ax = fig.get_axes()
ax[0].set_xlim(0, 10)
ax[0].set_ylim(0, 1)
#%% Disk Margin Plots
inPlot = sigExcList # Elements of sigExcList
outPlot = sigFbList # Elements of sigFbList
if False:
#%%
for iOut, outName in enumerate(outPlot):
for iIn, inName in enumerate(inPlot):
fig = None
for iSeg in range(0, len(oDataSegs)):
fig = FreqTrans.PlotSigma(freq_hz[0], rCritNom_mag[iSeg][iOut, iIn], err = rCritUnc_mag[iSeg][iOut, iIn], coher_nd = C[iSeg][iOut, iIn], fig = fig, fmt = rtsmSegList[iSeg]['fmt'] + '*-', label = oDataSegs[iSeg]['Desc'])
fig = FreqTrans.PlotSigma(freq_hz[0], 0.4 * np.ones_like(freq_hz[0]), fig = fig, fmt = 'r--', label = 'Critical Limit')
fig.suptitle(inName + ' to ' + outName, size=20)
ax = fig.get_axes()
ax[0].set_ylim(0, 2)
#%% Nyquist Plots
if False:
#%%
for iOut, outName in enumerate(outPlot):
for iIn, inName in enumerate(inPlot):
fig = None
for iSeg in range(0, len(oDataSegs)):
fig = FreqTrans.PlotNyquist(T[iSeg][iOut, iIn], TUnc[iSeg][iOut, iIn], fig = fig, fmt = rtsmSegList[iSeg]['fmt'] + '*', label = oDataSegs[iSeg]['Desc'])
fig = FreqTrans.PlotNyquist(np.asarray([-1+ 0j]), TUnc = np.asarray([0.4 + 0.4j]), fig = fig, fmt = '*r', label = 'Critical Region')
fig.suptitle(inName + ' to ' + outName, size=20)
ax = fig.get_axes()
ax[0].set_xlim(-3, 1)
ax[0].set_ylim(-2, 2)
#%% Bode Plots
if False:
#%%
for iOut, outName in enumerate(outPlot):
for iIn, inName in enumerate(inPlot):
fig = None
for iSeg in range(0, len(oDataSegs)):
# fig = FreqTrans.PlotBode(freq_hz[0], gain_mag[iSeg][iOut, iIn], phase_deg[iSeg][iOut, iIn], C[iSeg][iOut, iIn], gainUnc_mag = gainUnc_mag[iSeg][iOut, iIn], fig = fig, fmt = rtsmSegList[iSeg]['fmt'] + '*-', label = oDataSegs[iSeg]['Desc'])
fig = FreqTrans.PlotBode(freq_hz[0], gain_mag[iSeg][iOut, iIn], phase_deg[iSeg][iOut, iIn], C[iSeg][iOut, iIn], fig = fig, fmt = rtsmSegList[iSeg]['fmt'] + '*-', label = oDataSegs[iSeg]['Desc'])
fig.suptitle(inName + ' to ' + outName, size=20)
| [
"numpy.abs",
"numpy.mean",
"os.path.dirname",
"Core.FreqTrans.OptSpect",
"Core.FreqTrans.FreqRespFuncEstNoise",
"numpy.empty_like",
"Core.FreqTrans.DistCritCirc",
"Core.OpenData.Segment",
"Core.FreqTrans.Sigma",
"numpy.log10",
"Core.FreqTrans.PlotBode",
"numpy.ones_like",
"Core.FreqTrans.Plo... | [((806, 863), 'sys.path.join', 'path.join', (['"""/home"""', '"""rega0051"""', '"""FlightArchive"""', '"""Huginn"""'], {}), "('/home', 'rega0051', 'FlightArchive', 'Huginn')\n", (815, 863), False, 'from sys import path, argv\n'), ((1054, 1113), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", "('Huginn' + flt + '.h5')"], {}), "(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')\n", (1063, 1113), False, 'from sys import path, argv\n'), ((1140, 1190), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn.json')\n", (1149, 1190), False, 'from sys import path, argv\n'), ((1214, 1268), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn_def.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn_def.json')\n", (1223, 1268), False, 'from sys import path, argv\n'), ((1326, 1385), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", "('Huginn' + flt + '.h5')"], {}), "(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')\n", (1335, 1385), False, 'from sys import path, argv\n'), ((1412, 1462), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn.json')\n", (1421, 1462), False, 'from sys import path, argv\n'), ((1486, 1540), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn_def.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn_def.json')\n", (1495, 1540), False, 'from sys import path, argv\n'), ((1598, 1657), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", "('Huginn' + flt + '.h5')"], {}), "(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')\n", (1607, 1657), False, 'from sys import path, argv\n'), ((1684, 1734), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn.json')\n", (1693, 1734), False, 'from sys import path, argv\n'), ((1758, 1812), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn_def.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn_def.json')\n", (1767, 1812), False, 'from sys import path, argv\n'), ((1870, 1929), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", "('Huginn' + flt + '.h5')"], {}), "(pathBase, 'Huginn' + flt, 'Huginn' + flt + '.h5')\n", (1879, 1929), False, 'from sys import path, argv\n'), ((1956, 2006), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn.json')\n", (1965, 2006), False, 'from sys import path, argv\n'), ((2030, 2084), 'sys.path.join', 'path.join', (['pathBase', "('Huginn' + flt)", '"""huginn_def.json"""'], {}), "(pathBase, 'Huginn' + flt, 'huginn_def.json')\n", (2039, 2084), False, 'from sys import path, argv\n'), ((6868, 6993), 'Core.FreqTrans.OptSpect', 'FreqTrans.OptSpect', ([], {'dftType': '"""czt"""', 'freqRate': 'freqRate_rps', 'smooth': "('box', 3)", 'winType': "('tukey', 0.2)", 'detrendType': '"""Linear"""'}), "(dftType='czt', freqRate=freqRate_rps, smooth=('box', 3),\n winType=('tukey', 0.2), detrendType='Linear')\n", (6886, 6993), False, 'from Core import FreqTrans\n'), ((7056, 7079), 'numpy.asarray', 'np.asarray', (['freqExc_rps'], {}), '(freqExc_rps)\n', (7066, 7079), True, 'import numpy as np\n'), ((3171, 3194), 'Core.Loader.Load_h5', 'Loader.Load_h5', (['fileLog'], {}), '(fileLog)\n', (3185, 3194), False, 'from Core import Loader\n'), ((3237, 3264), 'Core.Loader.JsonRead', 'Loader.JsonRead', (['fileConfig'], {}), '(fileConfig)\n', (3252, 3264), False, 'from Core import Loader\n'), ((3277, 3318), 'Core.Loader.OpenData_RAPTRS', 'Loader.OpenData_RAPTRS', (['h5Data', 'sysConfig'], {}), '(h5Data, sysConfig)\n', (3299, 3318), False, 'from Core import Loader\n'), ((3373, 4006), 'numpy.array', 'np.array', (["[oData['aCenterFwdIMU_IMU_mps2'][2] - oData['aCenterFwdIMU_IMU_mps2'][2][0],\n oData['aCenterAftIMU_IMU_mps2'][2] - oData['aCenterAftIMU_IMU_mps2'][2]\n [0], oData['aLeftMidIMU_IMU_mps2'][2] - oData['aLeftMidIMU_IMU_mps2'][2\n ][0], oData['aLeftFwdIMU_IMU_mps2'][2] - oData['aLeftFwdIMU_IMU_mps2'][\n 2][0], oData['aLeftAftIMU_IMU_mps2'][2] - oData['aLeftAftIMU_IMU_mps2']\n [2][0], oData['aRightMidIMU_IMU_mps2'][2] - oData[\n 'aRightMidIMU_IMU_mps2'][2][0], oData['aRightFwdIMU_IMU_mps2'][2] -\n oData['aRightFwdIMU_IMU_mps2'][2][0], oData['aRightAftIMU_IMU_mps2'][2] -\n oData['aRightAftIMU_IMU_mps2'][2][0]]"], {}), "([oData['aCenterFwdIMU_IMU_mps2'][2] - oData[\n 'aCenterFwdIMU_IMU_mps2'][2][0], oData['aCenterAftIMU_IMU_mps2'][2] -\n oData['aCenterAftIMU_IMU_mps2'][2][0], oData['aLeftMidIMU_IMU_mps2'][2] -\n oData['aLeftMidIMU_IMU_mps2'][2][0], oData['aLeftFwdIMU_IMU_mps2'][2] -\n oData['aLeftFwdIMU_IMU_mps2'][2][0], oData['aLeftAftIMU_IMU_mps2'][2] -\n oData['aLeftAftIMU_IMU_mps2'][2][0], oData['aRightMidIMU_IMU_mps2'][2] -\n oData['aRightMidIMU_IMU_mps2'][2][0], oData['aRightFwdIMU_IMU_mps2'][2] -\n oData['aRightFwdIMU_IMU_mps2'][2][0], oData['aRightAftIMU_IMU_mps2'][2] -\n oData['aRightAftIMU_IMU_mps2'][2][0]])\n", (3381, 4006), True, 'import numpy as np\n'), ((4902, 4941), 'Core.OpenData.Segment', 'OpenData.Segment', (['oData', "rtsmSeg['seg']"], {}), "(oData, rtsmSeg['seg'])\n", (4918, 4941), False, 'from Core import OpenData\n'), ((5314, 5374), 'numpy.array', 'np.array', (["sysConfig['Excitation']['OMS_RTSM_1']['Frequency']"], {}), "(sysConfig['Excitation']['OMS_RTSM_1']['Frequency'])\n", (5322, 5374), True, 'import numpy as np\n'), ((5396, 5456), 'numpy.array', 'np.array', (["sysConfig['Excitation']['OMS_RTSM_2']['Frequency']"], {}), "(sysConfig['Excitation']['OMS_RTSM_2']['Frequency'])\n", (5404, 5456), True, 'import numpy as np\n'), ((5478, 5538), 'numpy.array', 'np.array', (["sysConfig['Excitation']['OMS_RTSM_3']['Frequency']"], {}), "(sysConfig['Excitation']['OMS_RTSM_3']['Frequency'])\n", (5486, 5538), True, 'import numpy as np\n'), ((6299, 6363), 'matplotlib.pyplot.plot', 'plt.plot', (["oDataSegs[iSeg]['time_s']", "oDataSegs[iSeg]['vIas_mps']"], {}), "(oDataSegs[iSeg]['time_s'], oDataSegs[iSeg]['vIas_mps'])\n", (6307, 6363), True, 'import matplotlib.pyplot as plt\n'), ((7439, 7509), 'Core.FreqTrans.FreqRespFuncEstNoise', 'FreqTrans.FreqRespFuncEstNoise', (['vExcList[iSeg]', 'vFbList[iSeg]', 'optSpec'], {}), '(vExcList[iSeg], vFbList[iSeg], optSpec)\n', (7469, 7509), False, 'from Core import FreqTrans\n'), ((7572, 7643), 'Core.FreqTrans.FreqRespFuncEstNoise', 'FreqTrans.FreqRespFuncEstNoise', (['vExcList[iSeg]', 'vCmdList[iSeg]', 'optSpec'], {}), '(vExcList[iSeg], vCmdList[iSeg], optSpec)\n', (7602, 7643), False, 'from Core import FreqTrans\n'), ((7724, 7742), 'numpy.empty_like', 'np.empty_like', (['Tev'], {}), '(Tev)\n', (7737, 7742), True, 'import numpy as np\n'), ((7758, 7776), 'numpy.empty_like', 'np.empty_like', (['Tev'], {}), '(Tev)\n', (7771, 7776), True, 'import numpy as np\n'), ((8345, 8420), 'Core.FreqTrans.DistCritCirc', 'FreqTrans.DistCritCirc', (['T[iSeg]', 'TUnc[iSeg]'], {'pCrit': '(0 + 0.0j)', 'typeNorm': '"""RSS"""'}), "(T[iSeg], TUnc[iSeg], pCrit=0 + 0.0j, typeNorm='RSS')\n", (8367, 8420), False, 'from Core import FreqTrans\n'), ((8612, 8688), 'Core.FreqTrans.DistCritCirc', 'FreqTrans.DistCritCirc', (['T[iSeg]', 'TUnc[iSeg]'], {'pCrit': '(-1 + 0.0j)', 'typeNorm': '"""RSS"""'}), "(T[iSeg], TUnc[iSeg], pCrit=-1 + 0.0j, typeNorm='RSS')\n", (8634, 8688), False, 'from Core import FreqTrans\n'), ((8813, 8849), 'Core.FreqTrans.Sigma', 'FreqTrans.Sigma', (['T[iSeg]', 'TUnc[iSeg]'], {}), '(T[iSeg], TUnc[iSeg])\n', (8828, 8849), False, 'from Core import FreqTrans\n'), ((9063, 9225), 'Core.FreqTrans.OptSpect', 'FreqTrans.OptSpect', ([], {'dftType': '"""dftmat"""', 'freq': 'freqExc_rps[iSgnlExc]', 'freqRate': 'freqRate_rps', 'smooth': "('box', 3)", 'winType': "('tukey', 0.0)", 'detrendType': '"""Linear"""'}), "(dftType='dftmat', freq=freqExc_rps[iSgnlExc], freqRate=\n freqRate_rps, smooth=('box', 3), winType=('tukey', 0.0), detrendType=\n 'Linear')\n", (9081, 9225), False, 'from Core import FreqTrans\n'), ((9243, 9395), 'Core.FreqTrans.OptSpect', 'FreqTrans.OptSpect', ([], {'dftType': '"""dftmat"""', 'freq': 'freqGap_rps', 'freqRate': 'freqRate_rps', 'smooth': "('box', 3)", 'winType': "('tukey', 0.0)", 'detrendType': '"""Linear"""'}), "(dftType='dftmat', freq=freqGap_rps, freqRate=\n freqRate_rps, smooth=('box', 3), winType=('tukey', 0.0), detrendType=\n 'Linear')\n", (9261, 9395), False, 'from Core import FreqTrans\n'), ((10504, 10530), 'numpy.min', 'np.min', (['sNom[iSeg]'], {'axis': '(0)'}), '(sNom[iSeg], axis=0)\n', (10510, 10530), True, 'import numpy as np\n'), ((10546, 10572), 'numpy.min', 'np.min', (['sUnc[iSeg]'], {'axis': '(0)'}), '(sUnc[iSeg], axis=0)\n', (10552, 10572), True, 'import numpy as np\n'), ((10620, 10773), 'Core.FreqTrans.PlotSigma', 'FreqTrans.PlotSigma', (['freq_hz[0]', 'sNomMin'], {'err': 'sNomMinErr', 'coher_nd': 'Cmin', 'fig': 'fig', 'fmt': "(rtsmSegList[iSeg]['fmt'] + '*-')", 'label': "oDataSegs[iSeg]['Desc']"}), "(freq_hz[0], sNomMin, err=sNomMinErr, coher_nd=Cmin, fig\n =fig, fmt=rtsmSegList[iSeg]['fmt'] + '*-', label=oDataSegs[iSeg]['Desc'])\n", (10639, 10773), False, 'from Core import FreqTrans\n'), ((4101, 4168), 'numpy.array', 'np.array', (['[456.1, -565.1, -289.9, 605.4, 472.4, -292, 605.6, 472.2]'], {}), '([456.1, -565.1, -289.9, 605.4, 472.4, -292, 605.6, 472.2])\n', (4109, 4168), True, 'import numpy as np\n'), ((4268, 4337), 'numpy.array', 'np.array', (['[2.956, -2.998, -1.141, 5.974, 5.349, -1.149, 5.974, 5.348]'], {}), '([2.956, -2.998, -1.141, 5.974, 5.349, -1.149, 5.974, 5.348])\n', (4276, 4337), True, 'import numpy as np\n'), ((7986, 8002), 'numpy.abs', 'np.abs', (['TUnc_seg'], {}), '(TUnc_seg)\n', (7992, 8002), True, 'import numpy as np\n'), ((8518, 8572), 'Core.FreqTrans.Phase', 'FreqTrans.Phase', (['T[iSeg]'], {'phaseUnit': '"""deg"""', 'unwrap': '(True)'}), "(T[iSeg], phaseUnit='deg', unwrap=True)\n", (8533, 8572), False, 'from Core import FreqTrans\n'), ((9813, 9867), 'Core.FreqTrans.SpectTime', 'FreqTrans.SpectTime', (['t', 'y', 'lenSeg', 'lenOverlap', 'optSpec'], {}), '(t, y, lenSeg, lenOverlap, optSpec)\n', (9832, 9867), False, 'from Core import FreqTrans\n'), ((9911, 9966), 'Core.FreqTrans.SpectTime', 'FreqTrans.SpectTime', (['t', 'y', 'lenSeg', 'lenOverlap', 'optSpecN'], {}), '(t, y, lenSeg, lenOverlap, optSpecN)\n', (9930, 9966), False, 'from Core import FreqTrans\n'), ((10453, 10476), 'numpy.min', 'np.min', (['C[iSeg]'], {'axis': '(0)'}), '(C[iSeg], axis=0)\n', (10459, 10476), True, 'import numpy as np\n'), ((10824, 10848), 'numpy.ones_like', 'np.ones_like', (['freq_hz[0]'], {}), '(freq_hz[0])\n', (10836, 10848), True, 'import numpy as np\n'), ((7851, 7877), 'numpy.linalg.inv', 'np.linalg.inv', (['Tev[..., i]'], {}), '(Tev[..., i])\n', (7864, 7877), True, 'import numpy as np\n'), ((7919, 7945), 'numpy.linalg.inv', 'np.linalg.inv', (['Tev[..., i]'], {}), '(Tev[..., i])\n', (7932, 7945), True, 'import numpy as np\n'), ((514, 530), 'os.path.dirname', 'dirname', (['argv[0]'], {}), '(argv[0])\n', (521, 530), False, 'from os.path import dirname, abspath, join\n'), ((572, 588), 'os.path.dirname', 'dirname', (['argv[0]'], {}), '(argv[0])\n', (579, 588), False, 'from os.path import dirname, abspath, join\n'), ((4384, 4403), 'numpy.mean', 'np.mean', (['aZ'], {'axis': '(0)'}), '(aZ, axis=0)\n', (4391, 4403), True, 'import numpy as np\n'), ((10073, 10090), 'numpy.log10', 'np.log10', (['P_Y_mag'], {}), '(P_Y_mag)\n', (10081, 10090), True, 'import numpy as np\n'), ((10256, 10273), 'numpy.log10', 'np.log10', (['P_N_mag'], {}), '(P_N_mag)\n', (10264, 10273), True, 'import numpy as np\n'), ((11257, 11469), 'Core.FreqTrans.PlotSigma', 'FreqTrans.PlotSigma', (['freq_hz[0]', 'rCritNom_mag[iSeg][iOut, iIn]'], {'err': 'rCritUnc_mag[iSeg][iOut, iIn]', 'coher_nd': 'C[iSeg][iOut, iIn]', 'fig': 'fig', 'fmt': "(rtsmSegList[iSeg]['fmt'] + '*-')", 'label': "oDataSegs[iSeg]['Desc']"}), "(freq_hz[0], rCritNom_mag[iSeg][iOut, iIn], err=\n rCritUnc_mag[iSeg][iOut, iIn], coher_nd=C[iSeg][iOut, iIn], fig=fig,\n fmt=rtsmSegList[iSeg]['fmt'] + '*-', label=oDataSegs[iSeg]['Desc'])\n", (11276, 11469), False, 'from Core import FreqTrans\n'), ((11956, 12100), 'Core.FreqTrans.PlotNyquist', 'FreqTrans.PlotNyquist', (['T[iSeg][iOut, iIn]', 'TUnc[iSeg][iOut, iIn]'], {'fig': 'fig', 'fmt': "(rtsmSegList[iSeg]['fmt'] + '*')", 'label': "oDataSegs[iSeg]['Desc']"}), "(T[iSeg][iOut, iIn], TUnc[iSeg][iOut, iIn], fig=fig,\n fmt=rtsmSegList[iSeg]['fmt'] + '*', label=oDataSegs[iSeg]['Desc'])\n", (11977, 12100), False, 'from Core import FreqTrans\n'), ((12144, 12167), 'numpy.asarray', 'np.asarray', (['[-1 + 0.0j]'], {}), '([-1 + 0.0j])\n', (12154, 12167), True, 'import numpy as np\n'), ((12889, 13080), 'Core.FreqTrans.PlotBode', 'FreqTrans.PlotBode', (['freq_hz[0]', 'gain_mag[iSeg][iOut, iIn]', 'phase_deg[iSeg][iOut, iIn]', 'C[iSeg][iOut, iIn]'], {'fig': 'fig', 'fmt': "(rtsmSegList[iSeg]['fmt'] + '*-')", 'label': "oDataSegs[iSeg]['Desc']"}), "(freq_hz[0], gain_mag[iSeg][iOut, iIn], phase_deg[iSeg][\n iOut, iIn], C[iSeg][iOut, iIn], fig=fig, fmt=rtsmSegList[iSeg]['fmt'] +\n '*-', label=oDataSegs[iSeg]['Desc'])\n", (12907, 13080), False, 'from Core import FreqTrans\n'), ((11528, 11552), 'numpy.ones_like', 'np.ones_like', (['freq_hz[0]'], {}), '(freq_hz[0])\n', (11540, 11552), True, 'import numpy as np\n'), ((12173, 12197), 'numpy.asarray', 'np.asarray', (['[0.4 + 0.4j]'], {}), '([0.4 + 0.4j])\n', (12183, 12197), True, 'import numpy as np\n'), ((4211, 4230), 'numpy.mean', 'np.mean', (['aZ'], {'axis': '(0)'}), '(aZ, axis=0)\n', (4218, 4230), True, 'import numpy as np\n')] |
import numpy as np
def iou(box, clusters):
"""
Calculates the Intersection over Union (IoU) between a box and k clusters.
:param box: tuple or array, shifted to the origin (i. e. width and height)
:param clusters: numpy array of shape (k, 2) where k is the number of clusters
:return: numpy array of shape (k, 0) where k is the number of clusters
"""
x = np.minimum(clusters[:, 0], box[0])
y = np.minimum(clusters[:, 1], box[1])
if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:
raise ValueError("Box has no area")
intersection = x * y
box_area = box[0] * box[1]
cluster_area = clusters[:, 0] * clusters[:, 1]
iou_ = intersection / (box_area + cluster_area - intersection)
return iou_
def avg_iou(boxes, clusters):
"""
Calculates the average Intersection over Union (IoU) between a numpy array of boxes and k clusters.
:param boxes: numpy array of shape (r, 2), where r is the number of rows
:param clusters: numpy array of shape (k, 2) where k is the number of clusters
:return: average IoU as a single float
"""
return np.mean([np.max(iou(boxes[i], clusters)) for i in range(boxes.shape[0])])
def translate_boxes(boxes):
"""
Translates all the boxes to the origin.
:param boxes: numpy array of shape (r, 4)
:return: numpy array of shape (r, 2)
"""
new_boxes = boxes.copy()
for row in range(new_boxes.shape[0]):
new_boxes[row][2] = np.abs(new_boxes[row][2] - new_boxes[row][0])
new_boxes[row][3] = np.abs(new_boxes[row][3] - new_boxes[row][1])
return np.delete(new_boxes, [0, 1], axis=1)
def kmeans(boxes, k, dist=np.median):
"""
Calculates k-means clustering with the Intersection over Union (IoU) metric.
:param boxes: numpy array of shape (r, 2), where r is the number of rows
:param k: number of clusters
:param dist: distance function
:return: numpy array of shape (k, 2)
"""
rows = boxes.shape[0]
distances = np.empty((rows, k))
last_clusters = np.zeros((rows,))
np.random.seed()
# the Forgy method will fail if the whole array contains the same rows
clusters = boxes[np.random.choice(rows, k, replace=False)]
while True:
for row in range(rows):
distances[row] = 1 - iou(boxes[row], clusters)
nearest_clusters = np.argmin(distances, axis=1)
if (last_clusters == nearest_clusters).all():
break
for cluster in range(k):
clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0)
print(clusters)
last_clusters = nearest_clusters
return clusters
class AnchorKmeans(object):
"""
K-means clustering on bounding boxes to generate anchors
"""
def __init__(self, k, max_iter=300, random_seed=None):
self.k = k
self.max_iter = max_iter
self.random_seed = random_seed
self.n_iter = 0
self.anchors_ = None
self.labels_ = None
self.ious_ = None
def fit(self, boxes):
"""
Run K-means cluster on input boxes.
:param boxes: 2-d array, shape(n, 2), form as (w, h)
:return: None
"""
assert self.k < len(boxes), "K must be less than the number of data."
# If the current number of iterations is greater than 0, then reset
if self.n_iter > 0:
self.n_iter = 0
np.random.seed(self.random_seed)
n = boxes.shape[0]
# Initialize K cluster centers (i.e., K anchors)
self.anchors_ = boxes[np.random.choice(n, self.k, replace=True)]
self.labels_ = np.zeros((n,))
while True:
self.n_iter += 1
# If the current number of iterations is greater than max number of iterations , then break
if self.n_iter > self.max_iter:
break
self.ious_ = self.iou(boxes, self.anchors_)
distances = 1 - self.ious_
cur_labels = np.argmin(distances, axis=1)
# If anchors not change any more, then break
if (cur_labels == self.labels_).all():
break
# Update K anchors
for i in range(self.k):
self.anchors_[i] = np.mean(boxes[cur_labels == i], axis=0)
self.labels_ = cur_labels
@staticmethod
def iou(boxes, anchors):
"""
Calculate the IOU between boxes and anchors.
:param boxes: 2-d array, shape(n, 2)
:param anchors: 2-d array, shape(k, 2)
:return: 2-d array, shape(n, k)
"""
# Calculate the intersection,
# the new dimension are added to construct shape (n, 1) and shape (1, k),
# so we can get (n, k) shape result by numpy broadcast
w_min = np.minimum(boxes[:, 0, np.newaxis], anchors[np.newaxis, :, 0])
h_min = np.minimum(boxes[:, 1, np.newaxis], anchors[np.newaxis, :, 1])
inter = w_min * h_min
# Calculate the union
box_area = boxes[:, 0] * boxes[:, 1]
anchor_area = anchors[:, 0] * anchors[:, 1]
union = box_area[:, np.newaxis] + anchor_area[np.newaxis]
return inter / (union - inter)
def avg_iou(self):
"""
Calculate the average IOU with closest anchor.
:return: None
"""
return np.mean(self.ious_[np.arange(len(self.labels_)), self.labels_]) | [
"numpy.minimum",
"numpy.random.seed",
"numpy.abs",
"numpy.count_nonzero",
"numpy.empty",
"numpy.zeros",
"numpy.argmin",
"numpy.mean",
"numpy.random.choice",
"numpy.delete"
] | [((385, 419), 'numpy.minimum', 'np.minimum', (['clusters[:, 0]', 'box[0]'], {}), '(clusters[:, 0], box[0])\n', (395, 419), True, 'import numpy as np\n'), ((428, 462), 'numpy.minimum', 'np.minimum', (['clusters[:, 1]', 'box[1]'], {}), '(clusters[:, 1], box[1])\n', (438, 462), True, 'import numpy as np\n'), ((1616, 1652), 'numpy.delete', 'np.delete', (['new_boxes', '[0, 1]'], {'axis': '(1)'}), '(new_boxes, [0, 1], axis=1)\n', (1625, 1652), True, 'import numpy as np\n'), ((2019, 2038), 'numpy.empty', 'np.empty', (['(rows, k)'], {}), '((rows, k))\n', (2027, 2038), True, 'import numpy as np\n'), ((2059, 2076), 'numpy.zeros', 'np.zeros', (['(rows,)'], {}), '((rows,))\n', (2067, 2076), True, 'import numpy as np\n'), ((2082, 2098), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (2096, 2098), True, 'import numpy as np\n'), ((1485, 1530), 'numpy.abs', 'np.abs', (['(new_boxes[row][2] - new_boxes[row][0])'], {}), '(new_boxes[row][2] - new_boxes[row][0])\n', (1491, 1530), True, 'import numpy as np\n'), ((1559, 1604), 'numpy.abs', 'np.abs', (['(new_boxes[row][3] - new_boxes[row][1])'], {}), '(new_boxes[row][3] - new_boxes[row][1])\n', (1565, 1604), True, 'import numpy as np\n'), ((2196, 2236), 'numpy.random.choice', 'np.random.choice', (['rows', 'k'], {'replace': '(False)'}), '(rows, k, replace=False)\n', (2212, 2236), True, 'import numpy as np\n'), ((2373, 2401), 'numpy.argmin', 'np.argmin', (['distances'], {'axis': '(1)'}), '(distances, axis=1)\n', (2382, 2401), True, 'import numpy as np\n'), ((3439, 3471), 'numpy.random.seed', 'np.random.seed', (['self.random_seed'], {}), '(self.random_seed)\n', (3453, 3471), True, 'import numpy as np\n'), ((3654, 3668), 'numpy.zeros', 'np.zeros', (['(n,)'], {}), '((n,))\n', (3662, 3668), True, 'import numpy as np\n'), ((4809, 4871), 'numpy.minimum', 'np.minimum', (['boxes[:, 0, np.newaxis]', 'anchors[np.newaxis, :, 0]'], {}), '(boxes[:, 0, np.newaxis], anchors[np.newaxis, :, 0])\n', (4819, 4871), True, 'import numpy as np\n'), ((4888, 4950), 'numpy.minimum', 'np.minimum', (['boxes[:, 1, np.newaxis]', 'anchors[np.newaxis, :, 1]'], {}), '(boxes[:, 1, np.newaxis], anchors[np.newaxis, :, 1])\n', (4898, 4950), True, 'import numpy as np\n'), ((470, 494), 'numpy.count_nonzero', 'np.count_nonzero', (['(x == 0)'], {}), '(x == 0)\n', (486, 494), True, 'import numpy as np\n'), ((502, 526), 'numpy.count_nonzero', 'np.count_nonzero', (['(y == 0)'], {}), '(y == 0)\n', (518, 526), True, 'import numpy as np\n'), ((3587, 3628), 'numpy.random.choice', 'np.random.choice', (['n', 'self.k'], {'replace': '(True)'}), '(n, self.k, replace=True)\n', (3603, 3628), True, 'import numpy as np\n'), ((4011, 4039), 'numpy.argmin', 'np.argmin', (['distances'], {'axis': '(1)'}), '(distances, axis=1)\n', (4020, 4039), True, 'import numpy as np\n'), ((4274, 4313), 'numpy.mean', 'np.mean', (['boxes[cur_labels == i]'], {'axis': '(0)'}), '(boxes[cur_labels == i], axis=0)\n', (4281, 4313), True, 'import numpy as np\n')] |
import functools
import flowws
from flowws import Argument as Arg
import numpy as np
@flowws.add_stage_arguments
class EvaluateEmbedding(flowws.Stage):
"""Evaluate the embedding model on all input data"""
ARGS = [
Arg('batch_size', '-b', int, 32, help='Batch size of calculations'),
Arg(
'average_bonds',
'-a',
bool,
False,
help='If True, average per-bond embeddings to be per-particle',
),
]
def run(self, scope, storage):
self.scope = scope
scope.update(self.value_dict)
if scope.get('per_cloud', False):
pass
elif self.arguments['average_bonds']:
x = scope['embedding']
s = scope['neighbor_segments']
N = np.clip(scope['neighbor_counts'][:, None], 1, 1e8)
scope['embedding'] = np.add.reduceat(x, s) / N
else:
scope['embedding_contexts'] = np.repeat(
scope['embedding_contexts'], scope['neighbor_counts']
)
@functools.cached_property
def value_dict(self):
model = self.scope['embedding_model']
if 'data_generator' in self.scope:
return self.evaluate_generator(model, self.scope)
else:
return self.evaluate(model, self.scope)
def evaluate_generator(self, model, scope):
result = {}
xs = []
counts = []
ctxs = []
neighbor_count = 1
for (x, y, ctx) in scope['data_generator']:
pred = model.predict_on_batch(x)
ndim = pred.shape[-1]
if not scope.get('per_cloud', False):
filt = np.any(x[0] != 0, axis=-1)
neighbor_count = np.sum(filt, axis=-1)
pred = pred[filt]
xs.append(pred)
counts.append(neighbor_count)
ctxs.extend(ctx)
result['embedding'] = np.concatenate(xs, axis=0)
result['embedding_contexts'] = ctxs
if not scope.get('per_cloud', False):
result['neighbor_counts'] = np.concatenate(counts)
result['neighbor_segments'] = np.cumsum(
np.insert(result['neighbor_counts'], 0, 0)
)[:-1]
return result
def evaluate(self, model, scope):
result = {}
pred = model.predict(scope['x_train'], batch_size=self.arguments['batch_size'])
if not scope.get('per_cloud', False):
filt = np.any(scope['x_train'][0] != 0, axis=-1)
pred = pred[filt]
neighbor_count = np.sum(filt, axis=-1)
result['neighbor_counts'] = neighbor_count
result['neighbor_segments'] = np.cumsum(
np.insert(result['neighbor_counts'], 0, 0)
)[:-1]
result['embedding'] = pred
result['embedding_contexts'] = scope['x_contexts']
return result
| [
"flowws.Argument",
"numpy.sum",
"numpy.add.reduceat",
"numpy.clip",
"numpy.insert",
"numpy.any",
"numpy.concatenate",
"numpy.repeat"
] | [((234, 301), 'flowws.Argument', 'Arg', (['"""batch_size"""', '"""-b"""', 'int', '(32)'], {'help': '"""Batch size of calculations"""'}), "('batch_size', '-b', int, 32, help='Batch size of calculations')\n", (237, 301), True, 'from flowws import Argument as Arg\n'), ((311, 419), 'flowws.Argument', 'Arg', (['"""average_bonds"""', '"""-a"""', 'bool', '(False)'], {'help': '"""If True, average per-bond embeddings to be per-particle"""'}), "('average_bonds', '-a', bool, False, help=\n 'If True, average per-bond embeddings to be per-particle')\n", (314, 419), True, 'from flowws import Argument as Arg\n'), ((1930, 1956), 'numpy.concatenate', 'np.concatenate', (['xs'], {'axis': '(0)'}), '(xs, axis=0)\n', (1944, 1956), True, 'import numpy as np\n'), ((2087, 2109), 'numpy.concatenate', 'np.concatenate', (['counts'], {}), '(counts)\n', (2101, 2109), True, 'import numpy as np\n'), ((2475, 2516), 'numpy.any', 'np.any', (["(scope['x_train'][0] != 0)"], {'axis': '(-1)'}), "(scope['x_train'][0] != 0, axis=-1)\n", (2481, 2516), True, 'import numpy as np\n'), ((2576, 2597), 'numpy.sum', 'np.sum', (['filt'], {'axis': '(-1)'}), '(filt, axis=-1)\n', (2582, 2597), True, 'import numpy as np\n'), ((794, 852), 'numpy.clip', 'np.clip', (["scope['neighbor_counts'][:, None]", '(1)', '(100000000.0)'], {}), "(scope['neighbor_counts'][:, None], 1, 100000000.0)\n", (801, 852), True, 'import numpy as np\n'), ((960, 1024), 'numpy.repeat', 'np.repeat', (["scope['embedding_contexts']", "scope['neighbor_counts']"], {}), "(scope['embedding_contexts'], scope['neighbor_counts'])\n", (969, 1024), True, 'import numpy as np\n'), ((1684, 1710), 'numpy.any', 'np.any', (['(x[0] != 0)'], {'axis': '(-1)'}), '(x[0] != 0, axis=-1)\n', (1690, 1710), True, 'import numpy as np\n'), ((1744, 1765), 'numpy.sum', 'np.sum', (['filt'], {'axis': '(-1)'}), '(filt, axis=-1)\n', (1750, 1765), True, 'import numpy as np\n'), ((878, 899), 'numpy.add.reduceat', 'np.add.reduceat', (['x', 's'], {}), '(x, s)\n', (893, 899), True, 'import numpy as np\n'), ((2179, 2221), 'numpy.insert', 'np.insert', (["result['neighbor_counts']", '(0)', '(0)'], {}), "(result['neighbor_counts'], 0, 0)\n", (2188, 2221), True, 'import numpy as np\n'), ((2722, 2764), 'numpy.insert', 'np.insert', (["result['neighbor_counts']", '(0)', '(0)'], {}), "(result['neighbor_counts'], 0, 0)\n", (2731, 2764), True, 'import numpy as np\n')] |
# coding: utf-8
"""
Name: train_with_constrain.py
Desc: This script contains the training and testing code of Unwrap Film.
Notations:
||rgb
Mean: The original render image in color space.
Shape: [batch_size, 3, 256, 256]
Range: 0 ~ 255 -----> -1 ~ 1
||threeD_map :
Mean: Three coordinate map as ground truth.
Shape: [batch_size, 3, 256, 256]
Range: 0.1 ~ 1 -----> -1 ~ 1
||nor_map:
Mean: Normal map as ground truth.
Shape: [batch_size, 3, 256, 256]
Range: 0 ~ 1 -----> -1 ~ 1
||dep_map:
Mean: Depth map as ground truth.
Shape: [batch_size, 1, 256, 256]
Range: 0.1 ~ 1 -----> -1 ~ 1
||uv_map:
Mean: UV map as ground truth.
Shape: [batch_size, 2, 256, 256]
Range: 0 ~ 1 ------> -1 ~ 1
||mask_map:
Mean: Background mask as ground truth.
Shape: [batch_size, 1, 256, 256]
Range: 0 or 1
||alb_map:
Mean: Albedo map as ground truth.
Shape: [batch_size, 1, 256, 256]
Range: 0 ~ 255 -----> -1 ~ 1
||bcward_map:
Mean: Backward map as ground truth.
Shape: [batch_size, 2, 256, 256]
Range: 0 ~ 1
For any notations, we use original signature X as direct predict and X_gt as corresponding ground truth.
X_from_source eg. dep_from3d dep_from_nor means transfer
Constrain Path:
1st path: 3D ---> Normal
3D ---> Depth
Normal ---> Depth
Depth ---> Normal
If need
2nd path: 3D ---> Normal ---> Depth
3D ---> Depth ----> Normal
"""
import torch
import torch.nn as nn
import models
import train_configs
from torch.utils.data import Dataset, DataLoader
from load_data_npy import filmDataset
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from cal_times import CallingCounter
import time
import os
# import metrics
import numpy as np
from write_image import *
from tensorboardX import SummaryWriter
import models2
import models3
from tutils import *
import load_data_npy
from dataloader.load_data_2 import filmDataset_old
from dataloader.uv2bw import uv2bmap_in_tensor
from dataloader.print_img import print_img_with_reprocess
from config import *
from dataloader.data_process import reprocess_auto_batch
from dataloader.uv2bw import uv2backward_batch
from evaluater.eval_ones import cal_PSNR, cal_MSE
from evaluater.eval_batches import uvbw_loss_np_batch
from dataloader.print_img import print_img_auto
from dataloader.bw_mapping import bw_mapping_batch_2, bw_mapping_batch_3
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "5, 0, 1, 2"
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return float(param_group['lr'])
# def train(args, model, device, train_loader, optimizer, criterion, epoch, writer, output_dir, isWriteImage, isVal=False,
# test_loader=None):
# return lr
def test2(*args):
### Cancel the test Func
pass
@tfuncname
def test(args, model, test_loader, optimizer, criterion, \
epoch, writer, output_dir, isWriteImage, isVal=False):
model.eval()
acc = 0
device = "cuda"
count = 0
mse1, mse2, mse3, mse4 = 0, 0, 0, 0
mae1, mae2, mae3, mae4 = 0, 0, 0, 0
cc1, cc2, cc3, cc4 = 0, 0, 0, 0
psnr1, psnr2, psnr3, psnr4 = 0, 0, 0, 0
ssim1, ssim2, ssim3, ssim4 = 0, 0, 0, 0
m1, m2, s1, s2 = 0,0,0,0
for batch_idx, data in enumerate(test_loader):
if batch_idx >= 100:
break
threeD_map_gt = data[0]
uv_map_gt = data[1]
bw_map_gt = data[2]
mask_map_gt = data[3]
ori_map_gt = data[4]
uv_map_gt, threeD_map_gt, bw_map_gt, mask_map_gt = uv_map_gt.to(device), threeD_map_gt.to(device), bw_map_gt.to(device), mask_map_gt.to(device)
uv_pred_t, bw_pred_t= model(threeD_map_gt)
uv_pred_t = torch.where(mask_map_gt>0, uv_pred_t, mask_map_gt)
# loss_uv = criterion(uv_pred_t, uv_map_gt).float()
# loss_bw = criterion(bw_pred_t, bw_map_gt).float()
uv_np = reprocess_auto_batch(uv_pred_t, "uv")
uv_gt_np = reprocess_auto_batch(uv_map_gt, "uv")
bw_np = reprocess_auto_batch(bw_pred_t, "bw")
bw_gt_np = reprocess_auto_batch(bw_map_gt, "bw")
mask_np = reprocess_auto_batch(mask_map_gt, "background")
bw_uv = uv2backward_batch(uv_np, mask_np)
ori = reprocess_auto_batch(ori_map_gt, "ori")
count += uv_np.shape[0]*1.0
# ---------- MSE -------------------
# total_uv_bw_loss, total_bw_loss, total_ori_uv_loss, total_ori_bw_loss
l1, l2, l3, l4 = uvbw_loss_np_batch(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix="mse")
mse1 += l1
mse2 += l2
mse3 += l3
mse4 += l4
writer.add_scalar('mse_one/uv_bw_loss' , l1, global_step=batch_idx)
writer.add_scalar('mse_one/bw_loss', l2, global_step=batch_idx)
writer.add_scalar('mse_one/ori_uv_loss', l3, global_step=batch_idx)
writer.add_scalar('mse_one/ori_bw_loss', l4, global_step=batch_idx)
# --------------------------
l1, l2, l3, l4 = uvbw_loss_np_batch(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix="mae")
mae1 += l1
mae2 += l2
mae3 += l3
mae4 += l4
writer.add_scalar('mae_one/uv_bw_loss' , l1, global_step=batch_idx)
writer.add_scalar('mae_one/bw_loss', l2, global_step=batch_idx)
writer.add_scalar('mae_one/ori_uv_loss', l3, global_step=batch_idx)
writer.add_scalar('mae_one/ori_bw_loss', l4, global_step=batch_idx)
# ---------- CC -------------------
l1, l2, l3, l4 = uvbw_loss_np_batch(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix="cc")
cc1 += l1
cc2 += l2
cc3 += l3
cc4 += l4
writer.add_scalar('cc_one/uv_bw_loss' , l1, global_step=batch_idx)
writer.add_scalar('cc_one/bw_loss', l2, global_step=batch_idx)
writer.add_scalar('cc_one/ori_uv_loss', l3, global_step=batch_idx)
writer.add_scalar('cc_one/ori_bw_loss', l4, global_step=batch_idx)
# ---------- PSNR -------------------
l1, l2, l3, l4 = uvbw_loss_np_batch(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix="psnr")
psnr1 += l1
psnr2 += l2
psnr3 += l3
psnr4 += l4
writer.add_scalar('psnr_one/uv_bw_loss' , l1, global_step=batch_idx)
writer.add_scalar('psnr_one/bw_loss', l2, global_step=batch_idx)
writer.add_scalar('psnr_one/ori_uv_loss', l3, global_step=batch_idx)
writer.add_scalar('psnr_one/ori_bw_loss', l4, global_step=batch_idx)
# ---------- SSIM -------------------
# l1, l2, l3, l4 = uvbw_loss_np_batch(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix="ssim")
# ssim1 += l1
# ssim2 += l2
# ssim3 += l3
# ssim4 += l4
writer.add_scalar('ssim_one/uv_bw_loss' , l1, global_step=batch_idx)
writer.add_scalar('ssim_one/bw_loss', l2, global_step=batch_idx)
writer.add_scalar('ssim_one/ori_uv_loss', l3, global_step=batch_idx)
writer.add_scalar('ssim_one/ori_bw_loss', l4, global_step=batch_idx)
print("Batch-idx {}, total_bw_loss {}".format(batch_idx, cc1))
print("outputdir", output_dir)
writer.add_scalar('mse/uv_bw_loss' , mse1/count, global_step=batch_idx)
writer.add_scalar('mse/bw_loss', mse2/count, global_step=batch_idx)
writer.add_scalar('mse/ori_uv_loss', mse3/count, global_step=batch_idx)
writer.add_scalar('mse/ori_bw_loss', mse4/count, global_step=batch_idx)
writer.add_scalar('mae/uv_bw_loss' , mae1/count, global_step=batch_idx)
writer.add_scalar('mae/bw_loss', mae2/count, global_step=batch_idx)
writer.add_scalar('mae/ori_uv_loss', mae3/count, global_step=batch_idx)
writer.add_scalar('mae/ori_bw_loss', mae4/count, global_step=batch_idx)
writer.add_scalar('cc/uv_bw_loss' , cc1/count, global_step=batch_idx)
writer.add_scalar('cc/bw_loss', cc2/count, global_step=batch_idx)
writer.add_scalar('cc/ori_uv_loss', cc3/count, global_step=batch_idx)
writer.add_scalar('cc/ori_bw_loss', cc4/count, global_step=batch_idx)
writer.add_scalar('psnr/uv_bw_loss' , psnr1/count, global_step=batch_idx)
writer.add_scalar('psnr/bw_loss', psnr2/count, global_step=batch_idx)
writer.add_scalar('psnr/ori_uv_loss', psnr3/count, global_step=batch_idx)
writer.add_scalar('psnr/ori_bw_loss', psnr4/count, global_step=batch_idx)
writer.add_scalar('ssim/uv_bw_loss' , ssim1/count, global_step=batch_idx)
writer.add_scalar('ssim/bw_loss', ssim2/count, global_step=batch_idx)
writer.add_scalar('ssim/ori_uv_loss', ssim3/count, global_step=batch_idx)
writer.add_scalar('ssim/ori_bw_loss', ssim4/count, global_step=batch_idx)
# ------------ Write Imgs --------------------
dewarp_ori_bw = bw_mapping_batch_3(ori, bw_np, device="cuda")
dewarp_ori_uv = bw_mapping_batch_3(ori, bw_uv, device="cuda")
dewarp_ori_gt = bw_mapping_batch_3(ori, bw_gt_np, device="cuda")
fname_bw = tfilename(output_dir, "test_uvbw/batch_{}/ori_bw.jpg".format(batch_idx))
fname_uv = tfilename(output_dir, "test_uvbw/batch_{}/ori_uv.jpg".format(batch_idx))
fname_origt = tfilename(output_dir, "test_uvbw/batch_{}/ori_dewarp_gt.jpg".format(batch_idx))
print_img_auto(dewarp_ori_bw[0,:,:,:], img_type="ori", is_gt=False, fname=fname_bw)
print_img_auto(dewarp_ori_uv[0,:,:,:], img_type="ori", is_gt=False, fname=fname_uv)
print_img_auto(dewarp_ori_gt[0,:,:,:], img_type="ori", is_gt=False, fname=fname_origt)
print_img_auto(uv_np[0,:,:,:], "uv", is_gt=False, fname=tfilename(output_dir, "test_uvbw/batch_{}/uv_pred.jpg".format(batch_idx)))
print_img_auto(uv_gt_np[0,:,:,:], "uv", is_gt=False, fname=tfilename(output_dir, "test_uvbw/batch_{}/uv_gt.jpg".format(batch_idx)))
print_img_auto(bw_np[0,:,:,:], "bw", is_gt=False, fname=tfilename(output_dir, "test_uvbw/batch_{}/bw_pred.jpg".format(batch_idx)))
print_img_auto(bw_gt_np[0,:,:,:], "bw", is_gt=False, fname=tfilename(output_dir, "test_uvbw/batch_{}/bw_gt.jpg".format(batch_idx)))
print_img_auto(bw_uv[0,:,:,:], "bw", is_gt=False, fname=tfilename(output_dir, "test_uvbw/batch_{}/bw_uv_pred.jpg".format(batch_idx)))
print_img_auto(mask_np[0,:,:,:], "background", is_gt=False, fname=tfilename(output_dir, "test_uvbw/batch_{}/bg_gt.jpg".format(batch_idx)))
print_img_auto(ori[0,:,:,:], "ori", is_gt=False, fname=tfilename(output_dir, "test_uvbw/batch_{}/ori_gt.jpg".format(batch_idx)))
# Write bw diffs
diff1 = bw_gt_np[0,:,:,:] - bw_np[0,:,:,:]
diff2 = bw_gt_np[0,:,:,:] - bw_uv[0,:,:,:]
max1 = np.max(diff1)
max2 = np.max(diff2)
min1 = np.min(diff1)
min2 = np.min(diff2)
max_both = np.max([max1, max2])
min_both = np.min([min1, min2])
diff_p1 = (diff1 - min_both) / (max_both - min_both) * 255
diff_p2 = (diff2 - min_both) / (max_both - min_both) * 255
mean1_1 = np.average(diff1[0,:,:,0])
mean1_2 = np.average(diff1[0,:,:,1])
mean2_1 = np.average(diff2[0,:,:,0])
mean2_2 = np.average(diff2[0,:,:,1])
# mean2 = np.average(diff2)
std1 = np.std(diff1)
std2 = np.std(diff2)
m1_1 += np.abs(mean1_1)
m1_2 += np.abs(mean1_2)
m2_1 += np.abs(mean2_1)
m2_2 += np.abs(mean2_2)
s1 += std1
s2 += std2
diff1[0,:,:,0] = diff1[0,:,:,0] - mean1_1
diff1[0,:,:,1] = diff1[0,:,:,1] - mean1_2
diff2[0,:,:,0] = diff2[0,:,:,0] - mean2_1
diff2[0,:,:,1] = diff2[0,:,:,1] - mean2_2
writer.add_scalar("bw_all_single/mean1_1", mean1_1, global_step=batch_idx)
writer.add_scalar("bw_all_single/mean1_2", mean1_2, global_step=batch_idx)
writer.add_scalar("bw_all_single/mean2_1", mean2_1, global_step=batch_idx)
writer.add_scalar("bw_all_single/mean2_2", mean2_2, global_step=batch_idx)
writer.add_scalar("bw_all_single/std_1", std1, global_step=batch_idx)
writer.add_scalar("bw_all_single/std_2", std2, global_step=batch_idx)
writer.add_scalar("bw_all_total/m1_1", m1_1, global_step=batch_idx)
writer.add_scalar("bw_all_total/m1_2", m1_2, global_step=batch_idx)
writer.add_scalar("bw_all_total/m2_1", m2_1, global_step=batch_idx)
writer.add_scalar("bw_all_total/m2_2", m2_2, global_step=batch_idx)
writer.add_scalar("bw_all_total/mean2", m2, global_step=batch_idx)
writer.add_scalar("bw_all_total/std_1", s1, global_step=batch_idx)
writer.add_scalar("bw_all_total/std_2", s2, global_step=batch_idx)
print_img_auto(diff_p1, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_bw.jpg".format(batch_idx)))
print_img_auto(diff_p2, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_bwuv.jpg".format(batch_idx)))
print_img_auto(diff_m1, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_m_bw.jpg".format(batch_idx)))
print_img_auto(diff_m2, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_m_bwuv.jpg".format(batch_idx)))
# Write diffs Ori
# diff1 = np.abs(dewarp_ori_bw[0,:,:,:] - dewarp_ori_gt[0,:,:,:])
# diff2 = np.abs(dewarp_ori_uv[0,:,:,:] - dewarp_ori_gt[0,:,:,:])
# max1 = np.max(diff1)
# max2 = np.max(diff2)
# max_both = np.max([max1, max2])
# diff1 = diff1 / max_both * 255
# diff2 = diff2 / max_both * 255
# mean1 = np.average(diff1)
# mean2 = np.average(diff2)
# std1 = np.std(diff2)
# std2 = np.std(diff2)
# diff_m1 = diff1 - mean1
# diff_m2 = diff2 - mean2
# print_img_auto(diff1, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_bw.jpg".format(batch_idx)))
# print_img_auto(diff2, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_bwuv.jpg".format(batch_idx)))
# print_img_auto(diff_m1, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_m_bw.jpg".format(batch_idx)))
# print_img_auto(diff_m2, "bw", fname=tfilename(output_dir, "test_uvbw/batch_{}/diff_m_bwuv.jpg".format(batch_idx)))
# print_img_auto(diffo1, "ori", fname=)
# print_img_auto(bw_gt_np[0,:,:,:], "deform", fname=tfilename(output_dir, "test_uvbw/batch_{}/deform_gt.jpg".format(batch_idx)))
# print_img_auto(bw_np[0,:,:,:], "deform", fname=tfilename(output_dir, "test_uvbw/batch_{}/deform_bw.jpg".format(batch_idx)))
# print_img_auto(bw_uv[0,:,:,:], "deform", fname=tfilename(output_dir, "test_uvbw/batch_{}/deform_bwuv.jpg".format(batch_idx)))
# print("Loss:")
# print("mse: {} {}".format(mse_bw/count, mse_ori/count))
# print("cc: {} {}".format(cc_bw/count, cc_ori/count))
# print("psnr: {} {}".format(psnr_bw/count, psnr_ori/count))
# print("ssim: {} {}".format(ssim_bw/count, ssim_ori/count))
return
def main():
# Model Build
model = models3.UnwarpNet()
model2 = models3.Conf_Discriminator()
args = train_configs.args
use_cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
if use_cuda:
print(" [*] Set cuda: True")
model = torch.nn.DataParallel(model.cuda())
model2 = torch.nn.DataParallel(model2.cuda())
else:
print(" [*] Set cuda: False")
# Load Dataset
kwargs = {'num_workers': 8, 'pin_memory': True} if use_cuda else {}
dataset_test = filmDataset_old(npy_dir=args.test_path, load_mod='test_uvbw_mapping')
dataset_test_loader = DataLoader(dataset_test,
batch_size=1,
shuffle=True,
**kwargs)
if UVBW_TRAIN:
dataset_train = filmDataset_old(npy_dir=args.train_path, load_mod='uvbw')
dataset_train_loader = DataLoader(dataset_train, batch_size=args.batch_size,
shuffle=True, **kwargs)
start_epoch = 1
learning_rate = args.lr
# Load Parameters
#if args.pretrained:
if DEFORM_TEST:
# pre_model = "/home1/quanquan/film_code/test_output2/20201018-070501z0alvFmodels/uvbw/tv_constrain_35.pkl"
pre_model = "/home1/quanquan/film_code/test_output2/20201021-094607K3qzNUmodels/uvbw/tv_constrain_69.pkl"
pretrained_dict = torch.load(pre_model, map_location=None)
model.load_state_dict(pretrained_dict['model_state'])
start_lr = pretrained_dict['lr']
start_epoch = pretrained_dict['epoch']
print("Start_lr: {} , Start_epoch {}".format(start_lr, start_epoch))
# Add Optimizer
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Output dir setting
output_dir = tdir(args.output_dir, generate_name())
print("Saving Dir: ", output_dir)
if args.use_mse:
criterion = torch.nn.MSELoss()
else:
criterion = torch.nn.L1Loss()
if args.write_summary:
writer_dir = tdir(output_dir, 'summary/' + args.model_name + '_start_epoch{}'.format(start_epoch))
print("Using TensorboardX !")
writer = SummaryWriter(logdir=writer_dir)
# print(args.model_name)
else:
writer = 0
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
#start_lr = args.lr
for epoch in range(start_epoch, args.epochs + 1):
if UVBW_TRAIN:
model.train()
correct = 0
for batch_idx, data in enumerate(dataset_train_loader):
ori_map_gt = data[0].to(device)
ab_map_gt = data[1].to(device)
depth_map_gt = data[2].to(device)
normal_map_gt = data[3].to(device)
cmap_gt = data[4].to(device)
uv_map_gt = data[5].to(device)
df_map_gt = data[6].to(device)
bg_map_gt = data[7].to(device)
optimizer.zero_grad()
uv_pred, cmap_pred, nor_pred, alb_pred, dep_pred, mask_map, \
nor_from_threeD, dep_from_threeD, nor_from_dep, dep_from_nor, df_map = model(ori_map_gt)
# TODO: 这里需不需要改成这样
uv = torch.where(mask_map>0.5, uv_pred, 0)
loss_uv = criterion(uv_pred, uv_map_gt).float()
loss_uv.backward()
optimizer.step()
lr = get_lr(optimizer)
# Start using Confident
if epoch > 30:
loss_conf, loss_total = model2(dewarp_ori_pred, ori_map_gt)
if batch_idx % args.log_intervals == 0:
print('\r Epoch:{} batch index:{}/{}||lr:{:.8f}||loss_uv:{:.6f}||loss_bw:{:.6f}'.format(epoch, batch_idx + 1,
len(dataset_train_loader.dataset) // args.batch_size,
lr, loss_uv.item(), loss_bw.item()), end=" ")
if args.write_summary:
writer.add_scalar('summary/train_uv_loss', loss_uv.item(),
global_step=epoch * len(dataset_train_loader) + batch_idx + 1)
# writer.add_scalar('summary/backward_loss', loss_bw.item(),
# global_step=epoch * len(train_loader) + batch_idx + 1)
writer.add_scalar('summary/lrate', lr, global_step=epoch * len(dataset_train_loader) + batch_idx + 1)
if True: # Draw Image
if batch_idx == (len(dataset_train_loader.dataset) // args.batch_size)-1:
print('writing image')
for k in range(2):
uv_pred = uv_map[k, :, :, :]
uv_gt = uv_map_gt[k, :, :, :]
mask_gt = mask_map_gt[k, :, :, :]
bw_gt = df_map_gt[k, :, :, :]
bw_pred = bw_map[k, :, :, :]
cmap_gt = threeD_map_gt[k, :, :, :]
output_dir1 = tdir(output_dir + '/uvbw_train/', 'epoch_{}_batch_{}/'.format(epoch, batch_idx))
"""pred"""
print_img_with_reprocess(uv_pred, img_type="uv", fname=tfilename(output_dir1 + 'train/epoch_{}/pred_uv_ind_{}'.format(epoch, k) + '.jpg'))
# print_img_with_reprocess(bw_from_uv, img_type="bw", fname=tfilename(output_dir1 + 'train/epoch_{}/bw_f_uv_ind_{}'.format(epoch, k) + '.jpg'))
print_img_with_reprocess(bw_pred, img_type="bw", fname=tfilename(output_dir1 + 'train/epoch_{}/pred_bw_ind_{}'.format(epoch, k) + '.jpg'))
"""gt"""
print_img_with_reprocess(cmap_gt, img_type="cmap", fname=tfilename(output_dir1 + 'train/epoch_{}/gt_3D_ind_{}'.format(epoch, k) + '.jpg')) # Problem
print_img_with_reprocess(uv_gt, img_type="uv", fname=tfilename(output_dir1 + 'train/epoch_{}/gt_uv_ind_{}'.format(epoch, k) + '.jpg'))
print_img_with_reprocess(bw_gt, img_type="bw", fname=tfilename(output_dir1 + 'train/epoch_{}/gt_bw_ind_{}'.format(epoch, k) + '.jpg')) # Problem
print_img_with_reprocess(mask_gt, img_type="background", fname=tfilename(output_dir1 + 'train/epoch_{}/gt_back_ind_{}'.format(epoch, k) + '.jpg'))
else:
test(args, model, dataset_test_loader, optimizer, criterion, epoch, \
writer, output_dir, args.write_image_test)
print("#"*22)
break
scheduler.step()
if UVBW_TRAIN and args.save_model:
state = {'epoch': epoch + 1,
'lr': lr,
'model_state': model.state_dict(),
'optimizer_state': optimizer.state_dict()
}
torch.save(state, tfilename(output_dir, "models/uvbw/{}_{}.pkl".format(args.model_name, epoch)))
def exist_or_make(path):
if not os.path.exists(path):
os.mkdir(path)
if __name__ == '__main__':
main()
| [
"os.mkdir",
"torch.optim.lr_scheduler.StepLR",
"numpy.abs",
"evaluater.eval_batches.uvbw_loss_np_batch",
"dataloader.load_data_2.filmDataset_old",
"torch.device",
"torch.nn.MSELoss",
"torch.utils.data.DataLoader",
"numpy.std",
"torch.load",
"os.path.exists",
"numpy.max",
"numpy.average",
"... | [((15276, 15295), 'models3.UnwarpNet', 'models3.UnwarpNet', ([], {}), '()\n', (15293, 15295), False, 'import models3\n'), ((15309, 15337), 'models3.Conf_Discriminator', 'models3.Conf_Discriminator', ([], {}), '()\n', (15335, 15337), False, 'import models3\n'), ((15448, 15491), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (15460, 15491), False, 'import torch\n'), ((15810, 15879), 'dataloader.load_data_2.filmDataset_old', 'filmDataset_old', ([], {'npy_dir': 'args.test_path', 'load_mod': '"""test_uvbw_mapping"""'}), "(npy_dir=args.test_path, load_mod='test_uvbw_mapping')\n", (15825, 15879), False, 'from dataloader.load_data_2 import filmDataset_old\n'), ((15906, 15968), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_test'], {'batch_size': '(1)', 'shuffle': '(True)'}), '(dataset_test, batch_size=1, shuffle=True, **kwargs)\n', (15916, 15968), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((17583, 17631), 'torch.optim.lr_scheduler.StepLR', 'StepLR', (['optimizer'], {'step_size': '(1)', 'gamma': 'args.gamma'}), '(optimizer, step_size=1, gamma=args.gamma)\n', (17589, 17631), False, 'from torch.optim.lr_scheduler import StepLR\n'), ((3918, 3970), 'torch.where', 'torch.where', (['(mask_map_gt > 0)', 'uv_pred_t', 'mask_map_gt'], {}), '(mask_map_gt > 0, uv_pred_t, mask_map_gt)\n', (3929, 3970), False, 'import torch\n'), ((4106, 4143), 'dataloader.data_process.reprocess_auto_batch', 'reprocess_auto_batch', (['uv_pred_t', '"""uv"""'], {}), "(uv_pred_t, 'uv')\n", (4126, 4143), False, 'from dataloader.data_process import reprocess_auto_batch\n'), ((4163, 4200), 'dataloader.data_process.reprocess_auto_batch', 'reprocess_auto_batch', (['uv_map_gt', '"""uv"""'], {}), "(uv_map_gt, 'uv')\n", (4183, 4200), False, 'from dataloader.data_process import reprocess_auto_batch\n'), ((4217, 4254), 'dataloader.data_process.reprocess_auto_batch', 'reprocess_auto_batch', (['bw_pred_t', '"""bw"""'], {}), "(bw_pred_t, 'bw')\n", (4237, 4254), False, 'from dataloader.data_process import reprocess_auto_batch\n'), ((4274, 4311), 'dataloader.data_process.reprocess_auto_batch', 'reprocess_auto_batch', (['bw_map_gt', '"""bw"""'], {}), "(bw_map_gt, 'bw')\n", (4294, 4311), False, 'from dataloader.data_process import reprocess_auto_batch\n'), ((4330, 4377), 'dataloader.data_process.reprocess_auto_batch', 'reprocess_auto_batch', (['mask_map_gt', '"""background"""'], {}), "(mask_map_gt, 'background')\n", (4350, 4377), False, 'from dataloader.data_process import reprocess_auto_batch\n'), ((4394, 4427), 'dataloader.uv2bw.uv2backward_batch', 'uv2backward_batch', (['uv_np', 'mask_np'], {}), '(uv_np, mask_np)\n', (4411, 4427), False, 'from dataloader.uv2bw import uv2backward_batch\n'), ((4442, 4481), 'dataloader.data_process.reprocess_auto_batch', 'reprocess_auto_batch', (['ori_map_gt', '"""ori"""'], {}), "(ori_map_gt, 'ori')\n", (4462, 4481), False, 'from dataloader.data_process import reprocess_auto_batch\n'), ((4671, 4741), 'evaluater.eval_batches.uvbw_loss_np_batch', 'uvbw_loss_np_batch', (['uv_np', 'bw_np', 'bw_gt_np', 'mask_np', 'ori'], {'metrix': '"""mse"""'}), "(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix='mse')\n", (4689, 4741), False, 'from evaluater.eval_batches import uvbw_loss_np_batch\n'), ((5186, 5256), 'evaluater.eval_batches.uvbw_loss_np_batch', 'uvbw_loss_np_batch', (['uv_np', 'bw_np', 'bw_gt_np', 'mask_np', 'ori'], {'metrix': '"""mae"""'}), "(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix='mae')\n", (5204, 5256), False, 'from evaluater.eval_batches import uvbw_loss_np_batch\n'), ((5710, 5779), 'evaluater.eval_batches.uvbw_loss_np_batch', 'uvbw_loss_np_batch', (['uv_np', 'bw_np', 'bw_gt_np', 'mask_np', 'ori'], {'metrix': '"""cc"""'}), "(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix='cc')\n", (5728, 5779), False, 'from evaluater.eval_batches import uvbw_loss_np_batch\n'), ((6227, 6298), 'evaluater.eval_batches.uvbw_loss_np_batch', 'uvbw_loss_np_batch', (['uv_np', 'bw_np', 'bw_gt_np', 'mask_np', 'ori'], {'metrix': '"""psnr"""'}), "(uv_np, bw_np, bw_gt_np, mask_np, ori, metrix='psnr')\n", (6245, 6298), False, 'from evaluater.eval_batches import uvbw_loss_np_batch\n'), ((9052, 9097), 'dataloader.bw_mapping.bw_mapping_batch_3', 'bw_mapping_batch_3', (['ori', 'bw_np'], {'device': '"""cuda"""'}), "(ori, bw_np, device='cuda')\n", (9070, 9097), False, 'from dataloader.bw_mapping import bw_mapping_batch_2, bw_mapping_batch_3\n'), ((9122, 9167), 'dataloader.bw_mapping.bw_mapping_batch_3', 'bw_mapping_batch_3', (['ori', 'bw_uv'], {'device': '"""cuda"""'}), "(ori, bw_uv, device='cuda')\n", (9140, 9167), False, 'from dataloader.bw_mapping import bw_mapping_batch_2, bw_mapping_batch_3\n'), ((9192, 9240), 'dataloader.bw_mapping.bw_mapping_batch_3', 'bw_mapping_batch_3', (['ori', 'bw_gt_np'], {'device': '"""cuda"""'}), "(ori, bw_gt_np, device='cuda')\n", (9210, 9240), False, 'from dataloader.bw_mapping import bw_mapping_batch_2, bw_mapping_batch_3\n'), ((9535, 9625), 'dataloader.print_img.print_img_auto', 'print_img_auto', (['dewarp_ori_bw[0, :, :, :]'], {'img_type': '"""ori"""', 'is_gt': '(False)', 'fname': 'fname_bw'}), "(dewarp_ori_bw[0, :, :, :], img_type='ori', is_gt=False,\n fname=fname_bw)\n", (9549, 9625), False, 'from dataloader.print_img import print_img_auto\n'), ((9627, 9717), 'dataloader.print_img.print_img_auto', 'print_img_auto', (['dewarp_ori_uv[0, :, :, :]'], {'img_type': '"""ori"""', 'is_gt': '(False)', 'fname': 'fname_uv'}), "(dewarp_ori_uv[0, :, :, :], img_type='ori', is_gt=False,\n fname=fname_uv)\n", (9641, 9717), False, 'from dataloader.print_img import print_img_auto\n'), ((9719, 9812), 'dataloader.print_img.print_img_auto', 'print_img_auto', (['dewarp_ori_gt[0, :, :, :]'], {'img_type': '"""ori"""', 'is_gt': '(False)', 'fname': 'fname_origt'}), "(dewarp_ori_gt[0, :, :, :], img_type='ori', is_gt=False,\n fname=fname_origt)\n", (9733, 9812), False, 'from dataloader.print_img import print_img_auto\n'), ((10948, 10961), 'numpy.max', 'np.max', (['diff1'], {}), '(diff1)\n', (10954, 10961), True, 'import numpy as np\n'), ((10977, 10990), 'numpy.max', 'np.max', (['diff2'], {}), '(diff2)\n', (10983, 10990), True, 'import numpy as np\n'), ((11006, 11019), 'numpy.min', 'np.min', (['diff1'], {}), '(diff1)\n', (11012, 11019), True, 'import numpy as np\n'), ((11035, 11048), 'numpy.min', 'np.min', (['diff2'], {}), '(diff2)\n', (11041, 11048), True, 'import numpy as np\n'), ((11068, 11088), 'numpy.max', 'np.max', (['[max1, max2]'], {}), '([max1, max2])\n', (11074, 11088), True, 'import numpy as np\n'), ((11108, 11128), 'numpy.min', 'np.min', (['[min1, min2]'], {}), '([min1, min2])\n', (11114, 11128), True, 'import numpy as np\n'), ((11281, 11310), 'numpy.average', 'np.average', (['diff1[0, :, :, 0]'], {}), '(diff1[0, :, :, 0])\n', (11291, 11310), True, 'import numpy as np\n'), ((11326, 11355), 'numpy.average', 'np.average', (['diff1[0, :, :, 1]'], {}), '(diff1[0, :, :, 1])\n', (11336, 11355), True, 'import numpy as np\n'), ((11371, 11400), 'numpy.average', 'np.average', (['diff2[0, :, :, 0]'], {}), '(diff2[0, :, :, 0])\n', (11381, 11400), True, 'import numpy as np\n'), ((11416, 11445), 'numpy.average', 'np.average', (['diff2[0, :, :, 1]'], {}), '(diff2[0, :, :, 1])\n', (11426, 11445), True, 'import numpy as np\n'), ((11494, 11507), 'numpy.std', 'np.std', (['diff1'], {}), '(diff1)\n', (11500, 11507), True, 'import numpy as np\n'), ((11523, 11536), 'numpy.std', 'np.std', (['diff2'], {}), '(diff2)\n', (11529, 11536), True, 'import numpy as np\n'), ((11553, 11568), 'numpy.abs', 'np.abs', (['mean1_1'], {}), '(mean1_1)\n', (11559, 11568), True, 'import numpy as np\n'), ((11585, 11600), 'numpy.abs', 'np.abs', (['mean1_2'], {}), '(mean1_2)\n', (11591, 11600), True, 'import numpy as np\n'), ((11617, 11632), 'numpy.abs', 'np.abs', (['mean2_1'], {}), '(mean2_1)\n', (11623, 11632), True, 'import numpy as np\n'), ((11649, 11664), 'numpy.abs', 'np.abs', (['mean2_2'], {}), '(mean2_2)\n', (11655, 11664), True, 'import numpy as np\n'), ((15409, 15434), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (15432, 15434), False, 'import torch\n'), ((16123, 16180), 'dataloader.load_data_2.filmDataset_old', 'filmDataset_old', ([], {'npy_dir': 'args.train_path', 'load_mod': '"""uvbw"""'}), "(npy_dir=args.train_path, load_mod='uvbw')\n", (16138, 16180), False, 'from dataloader.load_data_2 import filmDataset_old\n'), ((16212, 16289), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_train'], {'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(dataset_train, batch_size=args.batch_size, shuffle=True, **kwargs)\n', (16222, 16289), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((16701, 16741), 'torch.load', 'torch.load', (['pre_model'], {'map_location': 'None'}), '(pre_model, map_location=None)\n', (16711, 16741), False, 'import torch\n'), ((17216, 17234), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (17232, 17234), False, 'import torch\n'), ((17265, 17282), 'torch.nn.L1Loss', 'torch.nn.L1Loss', ([], {}), '()\n', (17280, 17282), False, 'import torch\n'), ((17472, 17504), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {'logdir': 'writer_dir'}), '(logdir=writer_dir)\n', (17485, 17504), False, 'from tensorboardX import SummaryWriter\n'), ((22494, 22514), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (22508, 22514), False, 'import os\n'), ((22524, 22538), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (22532, 22538), False, 'import os\n'), ((18529, 18568), 'torch.where', 'torch.where', (['(mask_map > 0.5)', 'uv_pred', '(0)'], {}), '(mask_map > 0.5, uv_pred, 0)\n', (18540, 18568), False, 'import torch\n')] |
# Linear Regression using Tensorflow
# Code from https://www.geeksforgeeks.org/linear-regression-using-tensorflow/
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
np.random.seed(101)
tf.set_random_seed(101)
# Genrating random linear data
# There will be 50 data points ranging from 0 to 50
x = np.linspace(0, 50, 50)
y = np.linspace(0, 50, 50)
# Adding noise to the random linear data
x += np.random.uniform(-4, 4, 50)
y += np.random.uniform(-4, 4, 50)
n = len(x) # Number of data points
# Plot of Training Data
# plt.scatter(x, y)
# plt.xlabel('x')
# plt.xlabel('y')
# plt.title("Training Data")
# plt.show()
X = tf.placeholder("float")
Y = tf.placeholder("float")
W = tf.Variable(np.random.randn(), name = "W")
b = tf.Variable(np.random.randn(), name = "b")
learning_rate = 0.01
training_epochs = 1000
# Hypothesis
y_pred = tf.add(tf.multiply(X, W), b)
# Mean Squared Error Cost Function
cost = tf.reduce_sum(tf.pow(y_pred-Y, 2)) / (2 * n)
# Gradient Descent Optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Global Variables Initializer
init = tf.global_variables_initializer()
# Starting the Tensorflow Session
with tf.Session() as sess:
# Initializing the Variables
sess.run(init)
# Iterating through all the epochs
for epoch in range(training_epochs):
# Feeding each data point into the optimizer using Feed Dictionary
for (_x, _y) in zip(x, y):
sess.run(optimizer, feed_dict = {X : _x, Y : _y})
# Displaying the result after every 50 epochs
if (epoch + 1) % 50 == 0:
# Calculating the cost a every epoch
c = sess.run(cost, feed_dict = {X : x, Y : y})
print("Epoch", (epoch + 1), ": cost =", c, "W =", sess.run(W), "b =", sess.run(b))
# Storing necessary values to be used outside the Session
training_cost = sess.run(cost, feed_dict ={X: x, Y: y})
weight = sess.run(W)
bias = sess.run(b)
# Calculating the predictions
predictions = weight * x + bias
print("Training cost =", training_cost, "Weight =", weight, "bias =", bias, '\n')
# Plotting the Results
plt.plot(x, y, 'ro', label ='Original data')
plt.plot(x, predictions, label ='Fitted line')
plt.title('Linear Regression Result')
plt.legend()
plt.savefig('results.png')
plt.show()
| [
"matplotlib.pyplot.title",
"numpy.random.uniform",
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"tensorflow.global_variables_initializer",
"matplotlib.pyplot.legend",
"tensorflow.Session",
"tensorflow.pow",
"tensorflow.set_random_seed",
"tensor... | [((259, 278), 'numpy.random.seed', 'np.random.seed', (['(101)'], {}), '(101)\n', (273, 278), True, 'import numpy as np\n'), ((281, 304), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(101)'], {}), '(101)\n', (299, 304), True, 'import tensorflow as tf\n'), ((400, 422), 'numpy.linspace', 'np.linspace', (['(0)', '(50)', '(50)'], {}), '(0, 50, 50)\n', (411, 422), True, 'import numpy as np\n'), ((429, 451), 'numpy.linspace', 'np.linspace', (['(0)', '(50)', '(50)'], {}), '(0, 50, 50)\n', (440, 451), True, 'import numpy as np\n'), ((504, 532), 'numpy.random.uniform', 'np.random.uniform', (['(-4)', '(4)', '(50)'], {}), '(-4, 4, 50)\n', (521, 532), True, 'import numpy as np\n'), ((540, 568), 'numpy.random.uniform', 'np.random.uniform', (['(-4)', '(4)', '(50)'], {}), '(-4, 4, 50)\n', (557, 568), True, 'import numpy as np\n'), ((751, 774), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (765, 774), True, 'import tensorflow as tf\n'), ((781, 804), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (795, 804), True, 'import tensorflow as tf\n'), ((1260, 1293), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1291, 1293), True, 'import tensorflow as tf\n'), ((2275, 2318), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""ro"""'], {'label': '"""Original data"""'}), "(x, y, 'ro', label='Original data')\n", (2283, 2318), True, 'import matplotlib.pyplot as plt\n'), ((2322, 2367), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'predictions'], {'label': '"""Fitted line"""'}), "(x, predictions, label='Fitted line')\n", (2330, 2367), True, 'import matplotlib.pyplot as plt\n'), ((2371, 2408), 'matplotlib.pyplot.title', 'plt.title', (['"""Linear Regression Result"""'], {}), "('Linear Regression Result')\n", (2380, 2408), True, 'import matplotlib.pyplot as plt\n'), ((2411, 2423), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2421, 2423), True, 'import matplotlib.pyplot as plt\n'), ((2425, 2451), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""results.png"""'], {}), "('results.png')\n", (2436, 2451), True, 'import matplotlib.pyplot as plt\n'), ((2453, 2463), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2461, 2463), True, 'import matplotlib.pyplot as plt\n'), ((825, 842), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (840, 842), True, 'import numpy as np\n'), ((874, 891), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (889, 891), True, 'import numpy as np\n'), ((990, 1007), 'tensorflow.multiply', 'tf.multiply', (['X', 'W'], {}), '(X, W)\n', (1001, 1007), True, 'import tensorflow as tf\n'), ((1338, 1350), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1348, 1350), True, 'import tensorflow as tf\n'), ((1074, 1095), 'tensorflow.pow', 'tf.pow', (['(y_pred - Y)', '(2)'], {}), '(y_pred - Y, 2)\n', (1080, 1095), True, 'import tensorflow as tf\n'), ((1152, 1200), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (1185, 1200), True, 'import tensorflow as tf\n')] |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
import IMLearn.metrics
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression
from sklearn.linear_model import Lasso, Ridge
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def select_polynomial_degree(n_samples: int = 100, noise: float = 5):
"""
Simulate data from a polynomial model and use cross-validation to select the best fitting degree
Parameters
----------
n_samples: int, default=100
Number of samples to generate
noise: float, default = 5
Noise level to simulate in responses
"""
# Question 1 - Generate dataset for model f(x)=(x+3)(x+2)(x+1)(x-1)(x-2) + eps for eps Gaussian noise
# and split into training- and testing portions
response = lambda x: (x+3)*(x+2)*(x+1)*(x-1)*(x-2)
X = np.linspace(-1.2, 2, n_samples)
y_ = response(X)
y = y_ + np.random.normal(scale=noise, size=len(y_))
train_x, train_y, test_x, test_y = split_train_test(pd.DataFrame(X), pd.Series(y), 2/3)
train_x, train_y, test_x, test_y = train_x.to_numpy().flatten(), train_y.to_numpy().flatten(), test_x.to_numpy().flatten(), test_y.to_numpy().flatten()
fig1 = go.Figure(data=[go.Scatter(x=X, y=y_, mode="markers", name="Real Points", marker=dict(color="black", opacity=.7)),
go.Scatter(x=train_x, y=train_y, mode="markers", name="Observed Training Points", marker=dict(color="red", opacity=.7)),
go.Scatter(x=test_x, y=test_y, mode="markers", name="Observed Test Points", marker=dict(color="blue", opacity=.7))],
layout=go.Layout(title_text=rf"$\text{{Scatter Plot Of True Values vs. Test & Train Values}}\mathcal{{N}}\ left(0,5\right)$",
xaxis={"title": r"$x$"},
yaxis={"title": r"$y$"}))
# fig1.show()
# Question 2 - Perform CV for polynomial fitting with degrees 0,1,...,10
train_err = []
validate_err = []
for k in range(11):
train_err_k, validate_err_k = cross_validate(PolynomialFitting(k), train_x, train_y, mean_square_error, 5)
train_err.append(train_err_k)
validate_err.append(validate_err_k)
x_k = [k for k in range(11)]
fig2 = go.Figure(data=[go.Scatter(x=x_k, y=train_err, mode="markers", name="Train Error per Polynomial Degree", marker=dict(color="black", opacity=.7)),
go.Scatter(x=x_k, y=validate_err, mode="markers", name="Validation Error per Polynomial Degree", marker=dict(color="red", opacity=.7))],
layout=go.Layout(title_text=rf"$\text{{5-Fold Validation Error per Polynomial Degree}}$",
xaxis={"title": r"$Polynomial Degree$"},
yaxis={"title": r"$Error$"}))
# fig2.show()
# Question 3 - Using best value of k, fit a k-degree polynomial model and report test error
k_star = np.argmin(np.array(validate_err))
print(f'The best validation error is {validate_err[k_star].round(2)} \n')
model = PolynomialFitting(k_star).fit(train_x, train_y)
print(f'The loss on the test set is {mean_square_error(test_y, model.predict(test_x)).round(2)} and the optimal polynomial degree is {k_star}')
def select_regularization_parameter(n_samples: int = 50, n_evaluations: int = 500):
"""
Using sklearn's diabetes dataset use cross-validation to select the best fitting regularization parameter
values for Ridge and Lasso regressions
Parameters
----------
n_samples: int, default=50
Number of samples to generate
n_evaluations: int, default = 500
Number of regularization parameter values to evaluate for each of the algorithms
"""
# Question 6 - Load diabetes dataset and split into training and testing portions
X, y = datasets.load_diabetes(return_X_y=True, as_frame=True)
train_X = X[:50]
train_y = y[:50]
test_X = X[51:]
test_y = y[51:]
train_X, train_y, test_X, test_y = train_X.to_numpy(), train_y.to_numpy(), test_X.to_numpy(), test_y.to_numpy()
# Question 7 - Perform CV for different values of the regularization parameter for Ridge and Lasso regressions
lambdas = np.linspace(0, 3)
ridge_train_err = []
ridge_val_err = []
lasso_train_err = []
lasso_val_err = []
for lam in lambdas:
ridge_train_lam_err, ridge_val_lam_err = cross_validate(RidgeRegression(lam), train_X, train_y, mean_square_error, 5)
lasso_train_lam_err, lasso_val_lam_err = cross_validate(Lasso(alpha=lam), train_X, train_y, mean_square_error, 5)
ridge_train_err.append(ridge_train_lam_err)
ridge_val_err.append(ridge_val_lam_err)
lasso_train_err.append(lasso_train_lam_err)
lasso_val_err.append(lasso_val_lam_err)
fig3 = go.Figure(data=[go.Scatter(x=lambdas, y=ridge_train_err, mode="markers+lines", name="Train Error per Lambda in Ridge", marker=dict(color="black", opacity=.7)),
go.Scatter(x=lambdas, y=ridge_val_err, mode="markers+lines", name="Validation Error per Lambda in Ridge", marker=dict(color="red", opacity=.7)),
go.Scatter(x=lambdas, y=lasso_train_err, mode="markers+lines", name="Train Error per Lambda in Lasso", marker=dict(color="blue", opacity=.7)),
go.Scatter(x=lambdas, y=lasso_val_err, mode="markers+lines", name="Validation Error per Lambda in Lasso", marker=dict(color="green", opacity=.7))],
layout=go.Layout(title_text=rf"$\text{{5-Fold Train and Validation Error per Regularization Lambda of Ridge and Lasso}}$",
xaxis={"title": r"$Lambda$"},
yaxis={"title": r"$Error$"}))
# fig3.show()
# Question 8 - Compare best Ridge model, best Lasso model and Least Squares model
lambda_star_ridge = lambdas[np.argmin(np.array(ridge_val_err))]
lambda_star_lasso = lambdas[np.argmin(np.array(lasso_val_err))]
ridge_model = RidgeRegression(lambda_star_ridge).fit(train_X, train_y)
lasso_model = Lasso(alpha=lambda_star_lasso).fit(train_X, train_y)
least_squares_model = LinearRegression().fit(train_X, train_y)
print(f'The loss on the test set for ridge is {mean_square_error(test_y, ridge_model.predict(test_X)).round(2)} and the optimal lambda is {lambda_star_ridge.round(2)}')
print(f'The loss on the test set for lasso is {mean_square_error(test_y, lasso_model.predict(test_X)).round(2)} and the optimal lambda is {lambda_star_lasso.round(2)}')
print(f'The loss on the test set for least squares is {mean_square_error(test_y, least_squares_model.predict(test_X)).round(2)}')
if __name__ == '__main__':
np.random.seed(0)
select_polynomial_degree()
select_polynomial_degree(noise=0)
select_polynomial_degree(1500, noise=10)
select_regularization_parameter()
| [
"pandas.DataFrame",
"numpy.random.seed",
"IMLearn.learners.regressors.RidgeRegression",
"sklearn.datasets.load_diabetes",
"IMLearn.learners.regressors.PolynomialFitting",
"numpy.array",
"pandas.Series",
"numpy.linspace",
"plotly.graph_objects.Layout",
"IMLearn.learners.regressors.LinearRegression"... | [((1091, 1122), 'numpy.linspace', 'np.linspace', (['(-1.2)', '(2)', 'n_samples'], {}), '(-1.2, 2, n_samples)\n', (1102, 1122), True, 'import numpy as np\n'), ((4086, 4140), 'sklearn.datasets.load_diabetes', 'datasets.load_diabetes', ([], {'return_X_y': '(True)', 'as_frame': '(True)'}), '(return_X_y=True, as_frame=True)\n', (4108, 4140), False, 'from sklearn import datasets\n'), ((4469, 4486), 'numpy.linspace', 'np.linspace', (['(0)', '(3)'], {}), '(0, 3)\n', (4480, 4486), True, 'import numpy as np\n'), ((6993, 7010), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (7007, 7010), True, 'import numpy as np\n'), ((1257, 1272), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (1269, 1272), True, 'import pandas as pd\n'), ((1274, 1286), 'pandas.Series', 'pd.Series', (['y'], {}), '(y)\n', (1283, 1286), True, 'import pandas as pd\n'), ((3194, 3216), 'numpy.array', 'np.array', (['validate_err'], {}), '(validate_err)\n', (3202, 3216), True, 'import numpy as np\n'), ((1847, 2026), 'plotly.graph_objects.Layout', 'go.Layout', ([], {'title_text': 'f"""$\\\\text{{Scatter Plot Of True Values vs. Test & Train Values}}\\\\mathcal{{N}}\\\\ left(0,5\\\\right)$"""', 'xaxis': "{'title': '$x$'}", 'yaxis': "{'title': '$y$'}"}), "(title_text=\n f'$\\\\text{{Scatter Plot Of True Values vs. Test & Train Values}}\\\\mathcal{{N}}\\\\ left(0,5\\\\right)$'\n , xaxis={'title': '$x$'}, yaxis={'title': '$y$'})\n", (1856, 2026), True, 'import plotly.graph_objects as go\n'), ((2280, 2300), 'IMLearn.learners.regressors.PolynomialFitting', 'PolynomialFitting', (['k'], {}), '(k)\n', (2297, 2300), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((2818, 2978), 'plotly.graph_objects.Layout', 'go.Layout', ([], {'title_text': 'f"""$\\\\text{{5-Fold Validation Error per Polynomial Degree}}$"""', 'xaxis': "{'title': '$Polynomial Degree$'}", 'yaxis': "{'title': '$Error$'}"}), "(title_text=\n f'$\\\\text{{5-Fold Validation Error per Polynomial Degree}}$', xaxis={\n 'title': '$Polynomial Degree$'}, yaxis={'title': '$Error$'})\n", (2827, 2978), True, 'import plotly.graph_objects as go\n'), ((3308, 3333), 'IMLearn.learners.regressors.PolynomialFitting', 'PolynomialFitting', (['k_star'], {}), '(k_star)\n', (3325, 3333), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((4671, 4691), 'IMLearn.learners.regressors.RidgeRegression', 'RidgeRegression', (['lam'], {}), '(lam)\n', (4686, 4691), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((4797, 4813), 'sklearn.linear_model.Lasso', 'Lasso', ([], {'alpha': 'lam'}), '(alpha=lam)\n', (4802, 4813), False, 'from sklearn.linear_model import Lasso, Ridge\n'), ((5776, 5958), 'plotly.graph_objects.Layout', 'go.Layout', ([], {'title_text': 'f"""$\\\\text{{5-Fold Train and Validation Error per Regularization Lambda of Ridge and Lasso}}$"""', 'xaxis': "{'title': '$Lambda$'}", 'yaxis': "{'title': '$Error$'}"}), "(title_text=\n f'$\\\\text{{5-Fold Train and Validation Error per Regularization Lambda of Ridge and Lasso}}$'\n , xaxis={'title': '$Lambda$'}, yaxis={'title': '$Error$'})\n", (5785, 5958), True, 'import plotly.graph_objects as go\n'), ((6174, 6197), 'numpy.array', 'np.array', (['ridge_val_err'], {}), '(ridge_val_err)\n', (6182, 6197), True, 'import numpy as np\n'), ((6242, 6265), 'numpy.array', 'np.array', (['lasso_val_err'], {}), '(lasso_val_err)\n', (6250, 6265), True, 'import numpy as np\n'), ((6286, 6320), 'IMLearn.learners.regressors.RidgeRegression', 'RidgeRegression', (['lambda_star_ridge'], {}), '(lambda_star_ridge)\n', (6301, 6320), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((6361, 6391), 'sklearn.linear_model.Lasso', 'Lasso', ([], {'alpha': 'lambda_star_lasso'}), '(alpha=lambda_star_lasso)\n', (6366, 6391), False, 'from sklearn.linear_model import Lasso, Ridge\n'), ((6440, 6458), 'IMLearn.learners.regressors.LinearRegression', 'LinearRegression', ([], {}), '()\n', (6456, 6458), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n')] |
import cv2 as cv
import numpy as np
titleWindow = 'Introduction_to_svm.py'
print("Takes a moment to compute resulting image...")
# Set up training data
## [setup1]
labels = np.array([1, -1, -1, -1])
trainingData = np.matrix([[501, 10], [255, 10], [501, 255], [10, 501]], dtype=np.float32)
## [setup1]
# Train the SVM
## [init]
svm = cv.ml.SVM_create()
svm.setType(cv.ml.SVM_C_SVC)
svm.setKernel(cv.ml.SVM_LINEAR)
svm.setTermCriteria((cv.TERM_CRITERIA_MAX_ITER, 100, 1e-6))
## [init]
## [train]
svm.train(trainingData, cv.ml.ROW_SAMPLE, labels)
## [train]
# Data for visual representation
width = 512
height = 512
image = np.zeros((height, width, 3), dtype=np.uint8)
# Show the decision regions given by the SVM
## [show]
green = (0,255,0)
blue = (255,0,0)
for i in range(image.shape[0]):
for j in range(image.shape[1]):
sampleMat = np.matrix([[j,i]], dtype=np.float32)
response = svm.predict(sampleMat)[1]
if response == 1:
image[i,j] = green
elif response == -1:
image[i,j] = blue
## [show]
# Show the training data
## [show_data]
thickness = -1
cv.circle(image, (501, 10), 5, ( 0, 0, 0), thickness)
cv.circle(image, (255, 10), 5, (255, 255, 255), thickness)
cv.circle(image, (501, 255), 5, (255, 255, 255), thickness)
cv.circle(image, ( 10, 501), 5, (255, 255, 255), thickness)
## [show_data]
# Show support vectors
## [show_vectors]
thickness = 2
sv = svm.getUncompressedSupportVectors()
for i in range(sv.shape[0]):
cv.circle(image, (sv[i,0], sv[i,1]), 6, (128, 128, 128), thickness)
## [show_vectors]
#cv.imwrite('result.png', image) # save the image
cv.imshow('SVM Simple Example', image) # show it to the user
cv.waitKey()
| [
"numpy.matrix",
"cv2.circle",
"cv2.waitKey",
"numpy.zeros",
"cv2.ml.SVM_create",
"numpy.array",
"cv2.imshow"
] | [((173, 198), 'numpy.array', 'np.array', (['[1, -1, -1, -1]'], {}), '([1, -1, -1, -1])\n', (181, 198), True, 'import numpy as np\n'), ((214, 288), 'numpy.matrix', 'np.matrix', (['[[501, 10], [255, 10], [501, 255], [10, 501]]'], {'dtype': 'np.float32'}), '([[501, 10], [255, 10], [501, 255], [10, 501]], dtype=np.float32)\n', (223, 288), True, 'import numpy as np\n'), ((334, 352), 'cv2.ml.SVM_create', 'cv.ml.SVM_create', ([], {}), '()\n', (350, 352), True, 'import cv2 as cv\n'), ((623, 667), 'numpy.zeros', 'np.zeros', (['(height, width, 3)'], {'dtype': 'np.uint8'}), '((height, width, 3), dtype=np.uint8)\n', (631, 667), True, 'import numpy as np\n'), ((1112, 1164), 'cv2.circle', 'cv.circle', (['image', '(501, 10)', '(5)', '(0, 0, 0)', 'thickness'], {}), '(image, (501, 10), 5, (0, 0, 0), thickness)\n', (1121, 1164), True, 'import cv2 as cv\n'), ((1172, 1230), 'cv2.circle', 'cv.circle', (['image', '(255, 10)', '(5)', '(255, 255, 255)', 'thickness'], {}), '(image, (255, 10), 5, (255, 255, 255), thickness)\n', (1181, 1230), True, 'import cv2 as cv\n'), ((1232, 1291), 'cv2.circle', 'cv.circle', (['image', '(501, 255)', '(5)', '(255, 255, 255)', 'thickness'], {}), '(image, (501, 255), 5, (255, 255, 255), thickness)\n', (1241, 1291), True, 'import cv2 as cv\n'), ((1292, 1350), 'cv2.circle', 'cv.circle', (['image', '(10, 501)', '(5)', '(255, 255, 255)', 'thickness'], {}), '(image, (10, 501), 5, (255, 255, 255), thickness)\n', (1301, 1350), True, 'import cv2 as cv\n'), ((1636, 1674), 'cv2.imshow', 'cv.imshow', (['"""SVM Simple Example"""', 'image'], {}), "('SVM Simple Example', image)\n", (1645, 1674), True, 'import cv2 as cv\n'), ((1697, 1709), 'cv2.waitKey', 'cv.waitKey', ([], {}), '()\n', (1707, 1709), True, 'import cv2 as cv\n'), ((1498, 1567), 'cv2.circle', 'cv.circle', (['image', '(sv[i, 0], sv[i, 1])', '(6)', '(128, 128, 128)', 'thickness'], {}), '(image, (sv[i, 0], sv[i, 1]), 6, (128, 128, 128), thickness)\n', (1507, 1567), True, 'import cv2 as cv\n'), ((847, 884), 'numpy.matrix', 'np.matrix', (['[[j, i]]'], {'dtype': 'np.float32'}), '([[j, i]], dtype=np.float32)\n', (856, 884), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.