code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import math
import random
import logging
import pickle
import numpy as np
import sklearn
from data import FaceImageIter
import mxnet as mx
from mxnet import ndarray as nd
import argparse
import mxnet.optimizer as optimizer
sys.path.append(os.path.join(os.path.dirname(__file__), 'common'))
#import face_image
import fresnet
import fmobilenet
logger = logging.getLogger()
logger.setLevel(logging.INFO)
AGE=100
args = None
class AccMetric(mx.metric.EvalMetric):
def __init__(self):
self.axis = 1
super(AccMetric, self).__init__(
'acc', axis=self.axis,
output_names=None, label_names=None)
self.losses = []
self.count = 0
def update(self, labels, preds):
self.count+=1
label = labels[0].asnumpy()[:,0:1]
pred_label = preds[-1].asnumpy()[:,0:2]
pred_label = np.argmax(pred_label, axis=self.axis)
pred_label = pred_label.astype('int32').flatten()
label = label.astype('int32').flatten()
assert label.shape==pred_label.shape
self.sum_metric += (pred_label.flat == label.flat).sum()
self.num_inst += len(pred_label.flat)
class LossValueMetric(mx.metric.EvalMetric):
def __init__(self):
self.axis = 1
super(LossValueMetric, self).__init__(
'lossvalue', axis=self.axis,
output_names=None, label_names=None)
self.losses = []
def update(self, labels, preds):
loss = preds[-1].asnumpy()[0]
self.sum_metric += loss
self.num_inst += 1.0
gt_label = preds[-2].asnumpy()
#print(gt_label)
class MAEMetric(mx.metric.EvalMetric):
def __init__(self):
self.axis = 1
super(MAEMetric, self).__init__(
'MAE', axis=self.axis,
output_names=None, label_names=None)
self.losses = []
self.count = 0
def update(self, labels, preds):
self.count+=1
label = labels[0].asnumpy()
label_age = np.count_nonzero(label[:,1:], axis=1)
pred_age = np.zeros( label_age.shape, dtype=np.int)
#pred_age = np.zeros( label_age.shape, dtype=np.float32)
pred = preds[-1].asnumpy()
for i in range(AGE):
_pred = pred[:,2+i*2:4+i*2]
_pred = np.argmax(_pred, axis=1)
#pred = pred[:,1]
pred_age += _pred
#pred_age = pred_age.astype(np.int)
mae = np.mean(np.abs(label_age - pred_age))
self.sum_metric += mae
self.num_inst += 1.0
class CUMMetric(mx.metric.EvalMetric):
def __init__(self, n=5):
self.axis = 1
self.n = n
super(CUMMetric, self).__init__(
'CUM_%d'%n, axis=self.axis,
output_names=None, label_names=None)
self.losses = []
self.count = 0
def update(self, labels, preds):
self.count+=1
label = labels[0].asnumpy()
label_age = np.count_nonzero(label[:,1:], axis=1)
pred_age = np.zeros( label_age.shape, dtype=np.int)
pred = preds[-1].asnumpy()
for i in range(AGE):
_pred = pred[:,2+i*2:4+i*2]
_pred = np.argmax(_pred, axis=1)
#pred = pred[:,1]
pred_age += _pred
diff = np.abs(label_age - pred_age)
cum = np.sum( (diff<self.n) )
self.sum_metric += cum
self.num_inst += len(label_age)
def parse_args():
parser = argparse.ArgumentParser(description='Train face network')
# general
parser.add_argument('--data-dir', default='', help='training set directory')
parser.add_argument('--prefix', default='../model/model', help='directory to save model.')
parser.add_argument('--pretrained', default='', help='pretrained model to load')
parser.add_argument('--ckpt', type=int, default=1, help='checkpoint saving option. 0: discard saving. 1: save when necessary. 2: always save')
parser.add_argument('--loss-type', type=int, default=4, help='loss type')
parser.add_argument('--verbose', type=int, default=2000, help='do verification testing and model saving every verbose batches')
parser.add_argument('--max-steps', type=int, default=0, help='max training batches')
parser.add_argument('--end-epoch', type=int, default=100000, help='training epoch size.')
parser.add_argument('--network', default='r50', help='specify network')
parser.add_argument('--image-size', default='112,112', help='specify input image height and width')
parser.add_argument('--version-input', type=int, default=1, help='network input config')
parser.add_argument('--version-output', type=str, default='GAP', help='network embedding output config')
parser.add_argument('--version-act', type=str, default='prelu', help='network activation config')
parser.add_argument('--multiplier', type=float, default=1.0, help='')
parser.add_argument('--lr', type=float, default=0.1, help='start learning rate')
parser.add_argument('--lr-steps', type=str, default='', help='steps of lr changing')
parser.add_argument('--wd', type=float, default=0.0005, help='weight decay')
parser.add_argument('--bn-mom', type=float, default=0.9, help='bn mom')
parser.add_argument('--mom', type=float, default=0.9, help='momentum')
parser.add_argument('--per-batch-size', type=int, default=128, help='batch size in each context')
parser.add_argument('--rand-mirror', type=int, default=1, help='if do random mirror in training')
parser.add_argument('--cutoff', type=int, default=0, help='cut off aug')
parser.add_argument('--color', type=int, default=0, help='color jittering aug')
parser.add_argument('--ce-loss', default=False, action='store_true', help='if output ce loss')
args = parser.parse_args()
return args
def get_symbol(args, arg_params, aux_params):
data_shape = (args.image_channel,args.image_h,args.image_w)
image_shape = ",".join([str(x) for x in data_shape])
margin_symbols = []
if args.network[0]=='m':
fc1 = fmobilenet.get_symbol(AGE*2+2,
multiplier = args.multiplier,
version_input=args.version_input,
version_output=args.version_output)
else:
fc1 = fresnet.get_symbol(AGE*2+2, args.num_layers,
version_input=args.version_input,
version_output=args.version_output)
label = mx.symbol.Variable('softmax_label')
gender_label = mx.symbol.slice_axis(data = label, axis=1, begin=0, end=1)
gender_label = mx.symbol.reshape(gender_label, shape=(args.per_batch_size,))
gender_fc1 = mx.symbol.slice_axis(data = fc1, axis=1, begin=0, end=2)
#gender_fc7 = mx.sym.FullyConnected(data=gender_fc1, num_hidden=2, name='gender_fc7')
gender_softmax = mx.symbol.SoftmaxOutput(data=gender_fc1, label = gender_label, name='gender_softmax', normalization='valid', use_ignore=True, ignore_label = 9999)
outs = [gender_softmax]
for i in range(AGE):
age_label = mx.symbol.slice_axis(data = label, axis=1, begin=i+1, end=i+2)
age_label = mx.symbol.reshape(age_label, shape=(args.per_batch_size,))
age_fc1 = mx.symbol.slice_axis(data = fc1, axis=1, begin=2+i*2, end=4+i*2)
#age_fc7 = mx.sym.FullyConnected(data=age_fc1, num_hidden=2, name='age_fc7_%i'%i)
age_softmax = mx.symbol.SoftmaxOutput(data=age_fc1, label = age_label, name='age_softmax_%d'%i, normalization='valid', grad_scale=1)
outs.append(age_softmax)
outs.append(mx.sym.BlockGrad(fc1))
out = mx.symbol.Group(outs)
return (out, arg_params, aux_params)
def train_net(args):
ctx = []
cvd = os.environ['CUDA_VISIBLE_DEVICES'].strip()
if len(cvd)>0:
for i in range(len(cvd.split(','))):
ctx.append(mx.gpu(i))
if len(ctx)==0:
ctx = [mx.cpu()]
print('use cpu')
else:
print('gpu num:', len(ctx))
prefix = args.prefix
prefix_dir = os.path.dirname(prefix)
if not os.path.exists(prefix_dir):
os.makedirs(prefix_dir)
end_epoch = args.end_epoch
args.ctx_num = len(ctx)
args.num_layers = int(args.network[1:])
print('num_layers', args.num_layers)
if args.per_batch_size==0:
args.per_batch_size = 128
args.batch_size = args.per_batch_size*args.ctx_num
args.rescale_threshold = 0
args.image_channel = 3
data_dir_list = args.data_dir.split(',')
assert len(data_dir_list)==1
data_dir = data_dir_list[0]
path_imgrec = None
path_imglist = None
image_size = [int(x) for x in args.image_size.split(',')]
assert len(image_size)==2
assert image_size[0]==image_size[1]
args.image_h = image_size[0]
args.image_w = image_size[1]
print('image_size', image_size)
path_imgrec = os.path.join(data_dir, "train.rec")
path_imgrec_val = os.path.join(data_dir, "val.rec")
print('Called with argument:', args)
data_shape = (args.image_channel,image_size[0],image_size[1])
mean = None
begin_epoch = 0
base_lr = args.lr
base_wd = args.wd
base_mom = args.mom
if len(args.pretrained)==0:
arg_params = None
aux_params = None
sym, arg_params, aux_params = get_symbol(args, arg_params, aux_params)
else:
vec = args.pretrained.split(',')
print('loading', vec)
_, arg_params, aux_params = mx.model.load_checkpoint(vec[0], int(vec[1]))
sym, arg_params, aux_params = get_symbol(args, arg_params, aux_params)
#label_name = 'softmax_label'
#label_shape = (args.batch_size,)
model = mx.mod.Module(
context = ctx,
symbol = sym,
)
val_dataiter = None
train_dataiter = FaceImageIter(
batch_size = args.batch_size,
data_shape = data_shape,
path_imgrec = path_imgrec,
shuffle = True,
rand_mirror = args.rand_mirror,
mean = mean,
cutoff = args.cutoff,
color_jittering = args.color,
)
val_dataiter = FaceImageIter(
batch_size = args.batch_size,
data_shape = data_shape,
path_imgrec = path_imgrec_val,
shuffle = False,
rand_mirror = False,
mean = mean,
)
metric = mx.metric.CompositeEvalMetric([AccMetric(), MAEMetric(), CUMMetric()])
if args.network[0]=='r' or args.network[0]=='y':
initializer = mx.init.Xavier(rnd_type='gaussian', factor_type="out", magnitude=2) #resnet style
elif args.network[0]=='i' or args.network[0]=='x':
initializer = mx.init.Xavier(rnd_type='gaussian', factor_type="in", magnitude=2) #inception
else:
initializer = mx.init.Xavier(rnd_type='uniform', factor_type="in", magnitude=2)
_rescale = 1.0/args.ctx_num
opt = optimizer.SGD(learning_rate=base_lr, momentum=base_mom, wd=base_wd, rescale_grad=_rescale)
#opt = optimizer.Nadam(learning_rate=base_lr, wd=base_wd, rescale_grad=_rescale)
som = 20
_cb = mx.callback.Speedometer(args.batch_size, som)
lr_steps = [int(x) for x in args.lr_steps.split(',')]
global_step = [0]
def _batch_callback(param):
_cb(param)
global_step[0]+=1
mbatch = global_step[0]
for _lr in lr_steps:
if mbatch==_lr:
opt.lr *= 0.1
print('lr change to', opt.lr)
break
if mbatch%1000==0:
print('lr-batch-epoch:',opt.lr,param.nbatch,param.epoch)
if mbatch==lr_steps[-1]:
arg, aux = model.get_params()
all_layers = model.symbol.get_internals()
_sym = all_layers['fc1_output']
mx.model.save_checkpoint(args.prefix, 0, _sym, arg, aux)
sys.exit(0)
epoch_cb = None
train_dataiter = mx.io.PrefetchingIter(train_dataiter)
print('start fitting')
model.fit(train_dataiter,
begin_epoch = begin_epoch,
num_epoch = end_epoch,
eval_data = val_dataiter,
eval_metric = metric,
kvstore = 'device',
optimizer = opt,
#optimizer_params = optimizer_params,
initializer = initializer,
arg_params = arg_params,
aux_params = aux_params,
allow_missing = True,
batch_end_callback = _batch_callback,
epoch_end_callback = epoch_cb )
def main():
#time.sleep(3600*6.5)
global args
args = parse_args()
train_net(args)
if __name__ == '__main__':
main()
|
[
"numpy.abs",
"argparse.ArgumentParser",
"numpy.sum",
"numpy.argmax",
"fresnet.get_symbol",
"fmobilenet.get_symbol",
"mxnet.io.PrefetchingIter",
"mxnet.optimizer.SGD",
"os.path.join",
"mxnet.sym.BlockGrad",
"mxnet.callback.Speedometer",
"os.path.dirname",
"os.path.exists",
"mxnet.gpu",
"mxnet.symbol.SoftmaxOutput",
"mxnet.init.Xavier",
"mxnet.symbol.Group",
"mxnet.cpu",
"sys.exit",
"numpy.count_nonzero",
"os.makedirs",
"mxnet.model.save_checkpoint",
"mxnet.mod.Module",
"data.FaceImageIter",
"numpy.zeros",
"mxnet.symbol.Variable",
"mxnet.symbol.reshape",
"mxnet.symbol.slice_axis",
"logging.getLogger"
] |
[((484, 503), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (501, 503), False, 'import logging\n'), ((3241, 3298), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train face network"""'}), "(description='Train face network')\n", (3264, 3298), False, 'import argparse\n'), ((6073, 6108), 'mxnet.symbol.Variable', 'mx.symbol.Variable', (['"""softmax_label"""'], {}), "('softmax_label')\n", (6091, 6108), True, 'import mxnet as mx\n'), ((6126, 6182), 'mxnet.symbol.slice_axis', 'mx.symbol.slice_axis', ([], {'data': 'label', 'axis': '(1)', 'begin': '(0)', 'end': '(1)'}), '(data=label, axis=1, begin=0, end=1)\n', (6146, 6182), True, 'import mxnet as mx\n'), ((6202, 6263), 'mxnet.symbol.reshape', 'mx.symbol.reshape', (['gender_label'], {'shape': '(args.per_batch_size,)'}), '(gender_label, shape=(args.per_batch_size,))\n', (6219, 6263), True, 'import mxnet as mx\n'), ((6279, 6333), 'mxnet.symbol.slice_axis', 'mx.symbol.slice_axis', ([], {'data': 'fc1', 'axis': '(1)', 'begin': '(0)', 'end': '(2)'}), '(data=fc1, axis=1, begin=0, end=2)\n', (6299, 6333), True, 'import mxnet as mx\n'), ((6443, 6595), 'mxnet.symbol.SoftmaxOutput', 'mx.symbol.SoftmaxOutput', ([], {'data': 'gender_fc1', 'label': 'gender_label', 'name': '"""gender_softmax"""', 'normalization': '"""valid"""', 'use_ignore': '(True)', 'ignore_label': '(9999)'}), "(data=gender_fc1, label=gender_label, name=\n 'gender_softmax', normalization='valid', use_ignore=True, ignore_label=9999\n )\n", (6466, 6595), True, 'import mxnet as mx\n'), ((7170, 7191), 'mxnet.symbol.Group', 'mx.symbol.Group', (['outs'], {}), '(outs)\n', (7185, 7191), True, 'import mxnet as mx\n'), ((7563, 7586), 'os.path.dirname', 'os.path.dirname', (['prefix'], {}), '(prefix)\n', (7578, 7586), False, 'import os\n'), ((8386, 8421), 'os.path.join', 'os.path.join', (['data_dir', '"""train.rec"""'], {}), "(data_dir, 'train.rec')\n", (8398, 8421), False, 'import os\n'), ((8444, 8477), 'os.path.join', 'os.path.join', (['data_dir', '"""val.rec"""'], {}), "(data_dir, 'val.rec')\n", (8456, 8477), False, 'import os\n'), ((9168, 9206), 'mxnet.mod.Module', 'mx.mod.Module', ([], {'context': 'ctx', 'symbol': 'sym'}), '(context=ctx, symbol=sym)\n', (9181, 9206), True, 'import mxnet as mx\n'), ((9293, 9493), 'data.FaceImageIter', 'FaceImageIter', ([], {'batch_size': 'args.batch_size', 'data_shape': 'data_shape', 'path_imgrec': 'path_imgrec', 'shuffle': '(True)', 'rand_mirror': 'args.rand_mirror', 'mean': 'mean', 'cutoff': 'args.cutoff', 'color_jittering': 'args.color'}), '(batch_size=args.batch_size, data_shape=data_shape,\n path_imgrec=path_imgrec, shuffle=True, rand_mirror=args.rand_mirror,\n mean=mean, cutoff=args.cutoff, color_jittering=args.color)\n', (9306, 9493), False, 'from data import FaceImageIter\n'), ((9678, 9820), 'data.FaceImageIter', 'FaceImageIter', ([], {'batch_size': 'args.batch_size', 'data_shape': 'data_shape', 'path_imgrec': 'path_imgrec_val', 'shuffle': '(False)', 'rand_mirror': '(False)', 'mean': 'mean'}), '(batch_size=args.batch_size, data_shape=data_shape,\n path_imgrec=path_imgrec_val, shuffle=False, rand_mirror=False, mean=mean)\n', (9691, 9820), False, 'from data import FaceImageIter\n'), ((10483, 10577), 'mxnet.optimizer.SGD', 'optimizer.SGD', ([], {'learning_rate': 'base_lr', 'momentum': 'base_mom', 'wd': 'base_wd', 'rescale_grad': '_rescale'}), '(learning_rate=base_lr, momentum=base_mom, wd=base_wd,\n rescale_grad=_rescale)\n', (10496, 10577), True, 'import mxnet.optimizer as optimizer\n'), ((10682, 10727), 'mxnet.callback.Speedometer', 'mx.callback.Speedometer', (['args.batch_size', 'som'], {}), '(args.batch_size, som)\n', (10705, 10727), True, 'import mxnet as mx\n'), ((11419, 11456), 'mxnet.io.PrefetchingIter', 'mx.io.PrefetchingIter', (['train_dataiter'], {}), '(train_dataiter)\n', (11440, 11456), True, 'import mxnet as mx\n'), ((383, 408), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (398, 408), False, 'import os\n'), ((945, 982), 'numpy.argmax', 'np.argmax', (['pred_label'], {'axis': 'self.axis'}), '(pred_label, axis=self.axis)\n', (954, 982), True, 'import numpy as np\n'), ((1971, 2009), 'numpy.count_nonzero', 'np.count_nonzero', (['label[:, 1:]'], {'axis': '(1)'}), '(label[:, 1:], axis=1)\n', (1987, 2009), True, 'import numpy as np\n'), ((2024, 2063), 'numpy.zeros', 'np.zeros', (['label_age.shape'], {'dtype': 'np.int'}), '(label_age.shape, dtype=np.int)\n', (2032, 2063), True, 'import numpy as np\n'), ((2803, 2841), 'numpy.count_nonzero', 'np.count_nonzero', (['label[:, 1:]'], {'axis': '(1)'}), '(label[:, 1:], axis=1)\n', (2819, 2841), True, 'import numpy as np\n'), ((2856, 2895), 'numpy.zeros', 'np.zeros', (['label_age.shape'], {'dtype': 'np.int'}), '(label_age.shape, dtype=np.int)\n', (2864, 2895), True, 'import numpy as np\n'), ((3085, 3113), 'numpy.abs', 'np.abs', (['(label_age - pred_age)'], {}), '(label_age - pred_age)\n', (3091, 3113), True, 'import numpy as np\n'), ((3124, 3145), 'numpy.sum', 'np.sum', (['(diff < self.n)'], {}), '(diff < self.n)\n', (3130, 3145), True, 'import numpy as np\n'), ((5759, 5895), 'fmobilenet.get_symbol', 'fmobilenet.get_symbol', (['(AGE * 2 + 2)'], {'multiplier': 'args.multiplier', 'version_input': 'args.version_input', 'version_output': 'args.version_output'}), '(AGE * 2 + 2, multiplier=args.multiplier,\n version_input=args.version_input, version_output=args.version_output)\n', (5780, 5895), False, 'import fmobilenet\n'), ((5932, 6055), 'fresnet.get_symbol', 'fresnet.get_symbol', (['(AGE * 2 + 2)', 'args.num_layers'], {'version_input': 'args.version_input', 'version_output': 'args.version_output'}), '(AGE * 2 + 2, args.num_layers, version_input=args.\n version_input, version_output=args.version_output)\n', (5950, 6055), False, 'import fresnet\n'), ((6655, 6719), 'mxnet.symbol.slice_axis', 'mx.symbol.slice_axis', ([], {'data': 'label', 'axis': '(1)', 'begin': '(i + 1)', 'end': '(i + 2)'}), '(data=label, axis=1, begin=i + 1, end=i + 2)\n', (6675, 6719), True, 'import mxnet as mx\n'), ((6734, 6792), 'mxnet.symbol.reshape', 'mx.symbol.reshape', (['age_label'], {'shape': '(args.per_batch_size,)'}), '(age_label, shape=(args.per_batch_size,))\n', (6751, 6792), True, 'import mxnet as mx\n'), ((6807, 6877), 'mxnet.symbol.slice_axis', 'mx.symbol.slice_axis', ([], {'data': 'fc1', 'axis': '(1)', 'begin': '(2 + i * 2)', 'end': '(4 + i * 2)'}), '(data=fc1, axis=1, begin=2 + i * 2, end=4 + i * 2)\n', (6827, 6877), True, 'import mxnet as mx\n'), ((6976, 7099), 'mxnet.symbol.SoftmaxOutput', 'mx.symbol.SoftmaxOutput', ([], {'data': 'age_fc1', 'label': 'age_label', 'name': "('age_softmax_%d' % i)", 'normalization': '"""valid"""', 'grad_scale': '(1)'}), "(data=age_fc1, label=age_label, name=\n 'age_softmax_%d' % i, normalization='valid', grad_scale=1)\n", (6999, 7099), True, 'import mxnet as mx\n'), ((7138, 7159), 'mxnet.sym.BlockGrad', 'mx.sym.BlockGrad', (['fc1'], {}), '(fc1)\n', (7154, 7159), True, 'import mxnet as mx\n'), ((7598, 7624), 'os.path.exists', 'os.path.exists', (['prefix_dir'], {}), '(prefix_dir)\n', (7612, 7624), False, 'import os\n'), ((7632, 7655), 'os.makedirs', 'os.makedirs', (['prefix_dir'], {}), '(prefix_dir)\n', (7643, 7655), False, 'import os\n'), ((10110, 10177), 'mxnet.init.Xavier', 'mx.init.Xavier', ([], {'rnd_type': '"""gaussian"""', 'factor_type': '"""out"""', 'magnitude': '(2)'}), "(rnd_type='gaussian', factor_type='out', magnitude=2)\n", (10124, 10177), True, 'import mxnet as mx\n'), ((2230, 2254), 'numpy.argmax', 'np.argmax', (['_pred'], {'axis': '(1)'}), '(_pred, axis=1)\n', (2239, 2254), True, 'import numpy as np\n'), ((2361, 2389), 'numpy.abs', 'np.abs', (['(label_age - pred_age)'], {}), '(label_age - pred_age)\n', (2367, 2389), True, 'import numpy as np\n'), ((3001, 3025), 'numpy.argmax', 'np.argmax', (['_pred'], {'axis': '(1)'}), '(_pred, axis=1)\n', (3010, 3025), True, 'import numpy as np\n'), ((7444, 7452), 'mxnet.cpu', 'mx.cpu', ([], {}), '()\n', (7450, 7452), True, 'import mxnet as mx\n'), ((10267, 10333), 'mxnet.init.Xavier', 'mx.init.Xavier', ([], {'rnd_type': '"""gaussian"""', 'factor_type': '"""in"""', 'magnitude': '(2)'}), "(rnd_type='gaussian', factor_type='in', magnitude=2)\n", (10281, 10333), True, 'import mxnet as mx\n'), ((10375, 10440), 'mxnet.init.Xavier', 'mx.init.Xavier', ([], {'rnd_type': '"""uniform"""', 'factor_type': '"""in"""', 'magnitude': '(2)'}), "(rnd_type='uniform', factor_type='in', magnitude=2)\n", (10389, 10440), True, 'import mxnet as mx\n'), ((11300, 11356), 'mxnet.model.save_checkpoint', 'mx.model.save_checkpoint', (['args.prefix', '(0)', '_sym', 'arg', 'aux'], {}), '(args.prefix, 0, _sym, arg, aux)\n', (11324, 11356), True, 'import mxnet as mx\n'), ((11365, 11376), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (11373, 11376), False, 'import sys\n'), ((7400, 7409), 'mxnet.gpu', 'mx.gpu', (['i'], {}), '(i)\n', (7406, 7409), True, 'import mxnet as mx\n')]
|
#
from __future__ import division
import timeit
import time
from math import sqrt
from numpy import concatenate
import matplotlib.pyplot as plt
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.metrics import mean_squared_error
from sklearn import preprocessing
import numpy as np
import pandas as pd
import multiprocessing
import matplotlib
from IOHMM import UnSupervisedIOHMM
from IOHMM import OLS, DiscreteMNL, CrossEntropyMNL
from IOHMM import forward_backward
from scipy.special import logsumexp
import pickle
from copy import deepcopy
import random
from sklearn.decomposition import PCA
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import os
import keras
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, LSTM
from keras.utils import to_categorical
from keras import backend as K
from tensorflow.keras import regularizers
# with open ('data/individual_ID_list', 'rb') as fp:
# individual_ID_list = pickle.load(fp)
# num_of_test_samples=500
# individual_ID_list_test = [ day_list[i] for i in sorted(random.sample(range(len(day_list)), num_of_test_samples)) ]
Accurate_duration = []
# filename1='data/activity_index_test.txt'
# file1=open(filename1,'r')
# activity_index_test=eval(file1.read())
activity_index_test = {}
def process_data(data, test_proportion,Card_ID, test_last):
#data['duration'] = np.log(data['duration']) # log for better modeling
data.loc[data['duration_last'] == -1, 'duration_last'] = 0 # first activity, assign to 0
column_list = list(data.columns.values)
location_list = []
hour_list = []
for ele in column_list:
if 'location' in ele:
location_list.append(ele)
if 'hour' in ele:
hour_list.append(ele)
location_list.remove('location_o')
location_list.remove('location')
hour_list.remove('hour')
# set covariates to this OLS model
weather_list=['rain','heavy_rain','sun','cloud','Avrg_Temp','fengli']
Weekday_list=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
holiday_list=['National_holiday','Observance']
last_activity=['duration_last','duration_trip']
previous_trips = ['Last_trip_time_yesterday','N_days_withtrip_past20',
'N_consec_days_no_trips','N_trips_yesterday']
Ut_list=weather_list + hour_list + Weekday_list+ location_list + holiday_list +last_activity + previous_trips
# U1_list=Weekday_list+weather_list + holiday_list
x_array = np.array(data.loc[:,Ut_list])
min_max_scaler = preprocessing.MinMaxScaler()
x_array_minmax = min_max_scaler.fit_transform(x_array)
print(x_array_minmax.shape)
weather_list=['rain','heavy_rain','sun','cloud','Avrg_Temp','fengli']
Weekday_list=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
holiday_list=['National_holiday','Observance']
last_activity=['duration_last','duration_trip']
previous_trips = ['Last_trip_time_yesterday','N_days_withtrip_past20',
'N_consec_days_no_trips','N_trips_yesterday']
Ut_list = weather_list + hour_list + Weekday_list + location_list + holiday_list + last_activity + previous_trips
# U1_list=Weekday_list+weather_list + holiday_list
data_array = np.array(data.loc[:, Ut_list])
min_max_scaler = preprocessing.MinMaxScaler()
array_minmax = min_max_scaler.fit_transform(data_array)
data.loc[:, Ut_list] = array_minmax
total_days = data['seq_ID'].max()
train_days = int(total_days - round(total_days*test_proportion))
# drop last
#data = data.loc[data['if_last']!=1]
if test_last:
# last 30 days
data_train = data.loc[data['seq_ID']<=train_days]
data_test = data.loc[data['seq_ID']>train_days]
else:
random.seed(Card_ID)
test_seq = random.sample(list(range(1,total_days+1)), total_days - train_days)
data_train = data.loc[~data['seq_ID'].isin(test_seq)]
data_test = data.loc[data['seq_ID'].isin(test_seq)]
return min_max_scaler, data, data_train, data_test, Ut_list
def gen_sequence(id_df, seq_length, seq_cols):
'''
padding with zero
'''
# for one id I put all the rows in a single matrix
data_matrix = id_df[seq_cols].values
num_elements = data_matrix.shape[0]
# Iterate over two lists in parallel.
# For example id1 have 192 rows and sequence_length is equal to 50
# so zip iterate over two following list of numbers (0,112),(50,192)
# 0 50 -> from row 0 to row 50
# 1 51 -> from row 1 to row 51
# 2 52 -> from row 2 to row 52
# ...
# 111 191 -> from row 111 to 191
for start, stop in zip(range(-seq_length+1, num_elements), range(1, num_elements+1)):
if start<0: # padding with zero
padding = np.zeros([-start, data_matrix.shape[1]])
used_data = data_matrix[0:stop, :]
yield np.vstack([padding, used_data])
else:
yield data_matrix[start:stop, :]
def gen_labels(id_df, seq_length, label):
# For one id I put all the labels in a single matrix.
# For example:
# [[1]
# [4]
# [1]
# [5]
# [9]
# ...
# [200]]
data_matrix = id_df[label].values
num_elements = data_matrix.shape[0]
# I have to remove the first seq_length labels
# because for one id the first sequence of seq_length size have as target
# the last label (the previus ones are discarded).
# All the next id's sequences will have associated step by step one label as target.
return data_matrix[0:num_elements, :]
def pre_process_to_LSTM(data_train, data_test, Ut_list, depend_var, sequence_length):
# test = list(gen_sequence(data_train[data_train['seq_ID'] == 59], sequence_length, Ut_list))
seq_gen_train = (list(gen_sequence(data_train[data_train['seq_ID'] == idx], sequence_length, Ut_list))
for idx in data_train['seq_ID'].unique())
seq_gen_test = (list(gen_sequence(data_test[data_test['seq_ID'] == idx], sequence_length, Ut_list))
for idx in data_test['seq_ID'].unique())
seq_array_train = np.concatenate(list(seq_gen_train)).astype(np.float32)
seq_array_test = np.concatenate(list(seq_gen_test)).astype(np.float32)
# generate labels
# val_label = gen_labels(data_train[data_train['seq_ID']==59], sequence_length, depend_var)
data = data_train.append(data_test)
# label_gen_train = [gen_labels(data_train[data_train['seq_ID']==idx], sequence_length, depend_var)
# for idx in data_train['seq_ID'].unique()]
# label_gen_test = [gen_labels(data_test[data_test['seq_ID']==idx], sequence_length, depend_var)
# for idx in data_test['seq_ID'].unique()]
dict_label = sorted(list(pd.unique(data.loc[:,depend_var[0]])))
dict_label2 = {}
idx = 0
for key in dict_label:
dict_label2[key] = idx
idx += 1
data['new_dep'] = data[depend_var[0]].apply(lambda x: dict_label2[x])
label_gen = [gen_labels(data[data['seq_ID']==idx], sequence_length, ['new_dep'])
for idx in data['seq_ID'].unique()]
label_gen = np.concatenate(label_gen).astype(np.int32)
label_gen = to_categorical(label_gen, num_classes=len(dict_label))
# label_array_train = np.concatenate(label_gen_train).astype(np.int32)
# label_array_test = np.concatenate(label_gen_test).astype(np.int32)
label_array_train = label_gen[0:len(data_train),:]
label_array_test = label_gen[len(data_train):,:]
return seq_array_train, seq_array_test, label_array_train, label_array_test, dict_label
def Model(Card_ID, RE_RUN):
file_name_test_results = data_path + 'results/result_Location_LSTM' + str(Card_ID) + 'test.csv'
model_path = 'output/LSTM/' + 'model_Location_' + str(Card_ID) + '.h5'
if not RE_RUN:
if os.path.exists(file_name_test_results):
print('Finish model', Card_ID)
return
# if Card_ID in activity_index_test:
# print ('Running model', Card_ID)
# return
file_name_train = data_path + 'samples/sample_' + str(Card_ID) + '_201407_201408_all.csv'
data = pd.read_csv(file_name_train)
data = data.loc[data['if_last']==0,:] # drop the last one, it will distract the training (because it is manually added)
test_proportion = 0.2
#========================= #data_preprocessing
test_last = False
scaler, data, data_train, data_test, Ut_list = process_data(data, test_proportion,Card_ID, test_last)
data_train['duration_hour'] = round(data['duration'] / 3600).astype('int') # classification
data_test['duration_hour'] = round(data['duration'] / 3600).astype('int') # classification
depend_var = ['Next_tapin_station']
sequence_length = 2 # look back period, use 2 because most people only has 2 trips.
seq_array_train, seq_array_test, label_array_train, label_array_test, dict_label = pre_process_to_LSTM(data_train, data_test, Ut_list, depend_var, sequence_length)
# print(seq_array_train.shape, seq_array_test.shape, label_array_train.shape, label_array_test.shape)
nb_features = seq_array_train.shape[2]
nb_out = label_array_train.shape[1]
#===========================
# design network
model = Sequential()
model.add(LSTM(
input_shape=(sequence_length, nb_features),
units=50,
return_sequences=False,
)) #
model.add(Dropout(0.05))
# model.add(Dense(units=50, activation='relu'))
# model.add(LSTM(
# units=50,
# return_sequences=False))
# model.add(Dropout(0.05))
# opt = keras.optimizers.SGD(lr=1e-2)
model.add(Dense(units=nb_out, activation='sigmoid',name='output_rank'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# print(model.summary())
# fit the network
history = model.fit(seq_array_train, label_array_train, epochs=200, batch_size=30, verbose=0,
validation_data=(seq_array_test, label_array_test),
callbacks=[
keras.callbacks.EarlyStopping(monitor='val_acc', min_delta=0, patience=50, verbose=0,
mode='max'),
keras.callbacks.ModelCheckpoint(model_path, monitor='val_acc', save_best_only=True,
mode='max', verbose=0)]
)
# history = model.fit(seq_array_train, label_array_train, epochs=200, batch_size=30, verbose=2,
# validation_data=(seq_array_test, label_array_test)
# )
#####################################plot history
# fig_acc = plt.figure(figsize=(10, 10))
# plt.plot(history.history['acc'])
# plt.plot(history.history['val_acc'])
# plt.title('model accuracy')
# plt.ylabel('accuracy')
# plt.xlabel('epoch')
# plt.legend(['train', 'test'], loc='upper left')
# plt.show()
# #
# # summarize history for Loss
# fig_loss = plt.figure(figsize=(10, 10))
# plt.plot(history.history['loss'])
# plt.plot(history.history['val_loss'])
# plt.title('model loss')
# plt.ylabel('loss')
# plt.xlabel('epoch')
# plt.legend(['train', 'test'], loc='upper left')
# plt.show()
#
#########################
# test
if os.path.isfile(model_path):
estimator = load_model(model_path)
get_last_layer_output = K.function([estimator.layers[0].input],
[estimator.get_layer('output_rank').output])
layer_output = get_last_layer_output([seq_array_test])[0]
top_N = np.min([20, nb_out])
idx_top_N = np.argsort(-layer_output, axis = 1) # use negative because from small to large
idx_top_N = idx_top_N[:,0:top_N]
results = data_test.loc[:,['ID',depend_var[0],'act_ID']]
results['Card_ID'] = Card_ID
results = results.reset_index(drop=True)
predict_topN = [np.array(dict_label)[row_index.astype('int')] for row_index in idx_top_N]
pred_col = ['Predict' + str(i + 1) for i in range(top_N)]
results_predict = pd.DataFrame(predict_topN, columns= pred_col)
results = pd.concat([results, results_predict],axis=1)
results = results.rename(columns = {depend_var[0]:'Ground_truth','act_ID':'activity_index'})
results['Correct'] = 0
results.loc[results['Predict1'] == results['Ground_truth'],'Correct'] = 1
test_acc = sum(results['Correct'])/len(results)
if top_N < 20:
for k in range(top_N+1,20+1):
results['Predict'+str(k)] = -1
file_name_test_results = data_path + 'results/result_Location_LSTM' + str(Card_ID) + 'test.csv'
results.to_csv(file_name_test_results, columns=['ID','Card_ID'] + ['Predict' + str(i + 1) for i in range(20)] + ['Ground_truth', 'Correct', 'activity_index'],index=False)
# train
get_last_layer_output = K.function([model.layers[0].input],
[model.get_layer('output_rank').output])
layer_output = get_last_layer_output([seq_array_train])[0]
idx_top_N = np.argsort(-layer_output, axis = 1) # use negative because from small to large
idx_top_N = idx_top_N[:,0:top_N]
results = data_train.loc[:,['ID',depend_var[0],'act_ID']]
results['Card_ID'] = Card_ID
results = results.reset_index(drop=True)
predict_topN = [np.array(dict_label)[row_index.astype('int')] for row_index in idx_top_N]
pred_col = ['Predict' + str(i + 1) for i in range(top_N)]
results_predict = pd.DataFrame(predict_topN, columns= pred_col)
results = pd.concat([results, results_predict],axis=1)
results = results.rename(columns = {depend_var[0]:'Ground_truth','act_ID':'activity_index'})
results['Correct'] = 0
results.loc[results['Predict1'] == results['Ground_truth'],'Correct'] = 1
train_acc = sum(results['Correct']) / len(results)
print('Train accuracy', train_acc)
if top_N < 20:
for k in range(top_N+1,20+1):
results['Predict'+str(k)] = -1
file_name_train_results = data_path + 'results/result_Location_LSTM' + str(Card_ID) + 'train.csv'
results.to_csv(file_name_train_results,columns=['ID','Card_ID'] + ['Predict' + str(i + 1) for i in range(20)] + ['Ground_truth', 'Correct', 'activity_index'],index=False)
return test_acc
def calculate_accuracy(result_df):
N_first = result_df['Correct'].loc[result_df['activity_index']==0].count()
Accuracy_first = result_df['Correct'].loc[(result_df['Correct']==1)&
(result_df['activity_index']==0)].count()/N_first
N_middle = result_df['Correct'].loc[result_df['activity_index']!=0].count()
Accuracy_middle = result_df['Correct'].loc[(result_df['Correct']==1)&
(result_df['activity_index']!=0)].count()/N_middle
N_all = result_df['Correct'].count()
Accuracy_all = result_df['Correct'].loc[result_df['Correct']==1].count()/N_all
return Accuracy_first, Accuracy_middle, Accuracy_all, N_first, N_middle, N_all
if __name__ == '__main__':
# card_ID = 954394568
# individual_ID_list_test = [958999238]
data_path = '../data/'
# with open(data_path + 'individual_ID_list_test', 'rb') as fp:
# individual_ID_list_test = pickle.load(fp)
SHOW_BASELINE = False
SKIP_RUNNED_MODEL = True
num_ind = 1000
with open(data_path + 'individual_ID_list_test_' + str(num_ind) + '.pickle', 'rb') as fp:
individual_ID_list_test = pickle.load(fp)
individual_ID_list_test = individual_ID_list_test[0:500]
count = 0
RE_RUN = True
tic = time.time()
for Card_ID in individual_ID_list_test:
count+=1
print('Current Card ID',Card_ID,'count',count, 'total',len(individual_ID_list_test))
file_name_test_ = data_path + 'results/result_Location_LSTM' + str(Card_ID) + 'test.csv'
if SKIP_RUNNED_MODEL:
if os.path.exists(file_name_test_):
print ('Finish model', Card_ID)
continue
test_acc = Model(Card_ID,RE_RUN)
if test_acc is None:
result_df = pd.read_csv(data_path + 'results/result_Location_LSTM' + str(Card_ID) + 'test.csv')
_, _, test_acc, _, _, _ = calculate_accuracy(result_df)
if SHOW_BASELINE:
result_df_MC = pd.read_csv(data_path + 'results/result_Location_MC' + str(Card_ID) + '.csv')
_, _, Accuracy_MC, _, _, _ = calculate_accuracy(result_df_MC)
result_df_IOHMM = pd.read_csv(data_path + 'results/result_Location_' + str(Card_ID) + 'test.csv')
_, _, Accuracy_IOHMM, _, _, _ = calculate_accuracy(result_df_IOHMM)
else:
Accuracy_MC = -1
Accuracy_IOHMM = -1
print ('Num_people_processed', count)
print(Card_ID, 'Total Testing Accuracy:', test_acc)
print(Card_ID, 'Base Total Testing Accuracy:', Accuracy_MC)
print(Card_ID, 'IOHMM Total Testing Accuracy:', Accuracy_IOHMM)
print('Elapsed time', time.time() - tic)
print('------****------')
# pool = multiprocessing.Pool(processes=3)
print('Total time', time.time() - tic)
# pool.map(Model, individual_ID_list_test)
# pool.close()
# print ('Accurate_duration',sum(Accurate_duration)/len(Accurate_duration))
# filename1='data/activity_index_test.txt'
# file1=open(filename1,'r')
# activity_index_test=eval(file1.read())
|
[
"keras.models.load_model",
"pandas.read_csv",
"sklearn.preprocessing.MinMaxScaler",
"numpy.argsort",
"os.path.isfile",
"pickle.load",
"pandas.DataFrame",
"os.path.exists",
"random.seed",
"pandas.concat",
"keras.callbacks.ModelCheckpoint",
"keras.layers.Dropout",
"numpy.min",
"numpy.concatenate",
"numpy.vstack",
"keras.layers.LSTM",
"numpy.zeros",
"pandas.unique",
"time.time",
"keras.layers.Dense",
"numpy.array",
"keras.callbacks.EarlyStopping",
"keras.models.Sequential"
] |
[((2622, 2652), 'numpy.array', 'np.array', (['data.loc[:, Ut_list]'], {}), '(data.loc[:, Ut_list])\n', (2630, 2652), True, 'import numpy as np\n'), ((2673, 2701), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', ([], {}), '()\n', (2699, 2701), False, 'from sklearn import preprocessing\n'), ((3394, 3424), 'numpy.array', 'np.array', (['data.loc[:, Ut_list]'], {}), '(data.loc[:, Ut_list])\n', (3402, 3424), True, 'import numpy as np\n'), ((3446, 3474), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', ([], {}), '()\n', (3472, 3474), False, 'from sklearn import preprocessing\n'), ((8264, 8292), 'pandas.read_csv', 'pd.read_csv', (['file_name_train'], {}), '(file_name_train)\n', (8275, 8292), True, 'import pandas as pd\n'), ((9373, 9385), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (9383, 9385), False, 'from keras.models import Sequential, load_model\n'), ((11517, 11543), 'os.path.isfile', 'os.path.isfile', (['model_path'], {}), '(model_path)\n', (11531, 11543), False, 'import os\n'), ((11813, 11833), 'numpy.min', 'np.min', (['[20, nb_out]'], {}), '([20, nb_out])\n', (11819, 11833), True, 'import numpy as np\n'), ((11851, 11884), 'numpy.argsort', 'np.argsort', (['(-layer_output)'], {'axis': '(1)'}), '(-layer_output, axis=1)\n', (11861, 11884), True, 'import numpy as np\n'), ((12284, 12328), 'pandas.DataFrame', 'pd.DataFrame', (['predict_topN'], {'columns': 'pred_col'}), '(predict_topN, columns=pred_col)\n', (12296, 12328), True, 'import pandas as pd\n'), ((12344, 12389), 'pandas.concat', 'pd.concat', (['[results, results_predict]'], {'axis': '(1)'}), '([results, results_predict], axis=1)\n', (12353, 12389), True, 'import pandas as pd\n'), ((13256, 13289), 'numpy.argsort', 'np.argsort', (['(-layer_output)'], {'axis': '(1)'}), '(-layer_output, axis=1)\n', (13266, 13289), True, 'import numpy as np\n'), ((13690, 13734), 'pandas.DataFrame', 'pd.DataFrame', (['predict_topN'], {'columns': 'pred_col'}), '(predict_topN, columns=pred_col)\n', (13702, 13734), True, 'import pandas as pd\n'), ((13750, 13795), 'pandas.concat', 'pd.concat', (['[results, results_predict]'], {'axis': '(1)'}), '([results, results_predict], axis=1)\n', (13759, 13795), True, 'import pandas as pd\n'), ((15743, 15754), 'time.time', 'time.time', ([], {}), '()\n', (15752, 15754), False, 'import time\n'), ((3913, 3933), 'random.seed', 'random.seed', (['Card_ID'], {}), '(Card_ID)\n', (3924, 3933), False, 'import random\n'), ((7964, 8002), 'os.path.exists', 'os.path.exists', (['file_name_test_results'], {}), '(file_name_test_results)\n', (7978, 8002), False, 'import os\n'), ((9400, 9487), 'keras.layers.LSTM', 'LSTM', ([], {'input_shape': '(sequence_length, nb_features)', 'units': '(50)', 'return_sequences': '(False)'}), '(input_shape=(sequence_length, nb_features), units=50, return_sequences\n =False)\n', (9404, 9487), False, 'from keras.layers import Dense, Dropout, LSTM\n'), ((9535, 9548), 'keras.layers.Dropout', 'Dropout', (['(0.05)'], {}), '(0.05)\n', (9542, 9548), False, 'from keras.layers import Dense, Dropout, LSTM\n'), ((9766, 9827), 'keras.layers.Dense', 'Dense', ([], {'units': 'nb_out', 'activation': '"""sigmoid"""', 'name': '"""output_rank"""'}), "(units=nb_out, activation='sigmoid', name='output_rank')\n", (9771, 9827), False, 'from keras.layers import Dense, Dropout, LSTM\n'), ((11565, 11587), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (11575, 11587), False, 'from keras.models import Sequential, load_model\n'), ((15623, 15638), 'pickle.load', 'pickle.load', (['fp'], {}), '(fp)\n', (15634, 15638), False, 'import pickle\n'), ((4923, 4963), 'numpy.zeros', 'np.zeros', (['[-start, data_matrix.shape[1]]'], {}), '([-start, data_matrix.shape[1]])\n', (4931, 4963), True, 'import numpy as np\n'), ((6886, 6923), 'pandas.unique', 'pd.unique', (['data.loc[:, depend_var[0]]'], {}), '(data.loc[:, depend_var[0]])\n', (6895, 6923), True, 'import pandas as pd\n'), ((7261, 7286), 'numpy.concatenate', 'np.concatenate', (['label_gen'], {}), '(label_gen)\n', (7275, 7286), True, 'import numpy as np\n'), ((12126, 12146), 'numpy.array', 'np.array', (['dict_label'], {}), '(dict_label)\n', (12134, 12146), True, 'import numpy as np\n'), ((13532, 13552), 'numpy.array', 'np.array', (['dict_label'], {}), '(dict_label)\n', (13540, 13552), True, 'import numpy as np\n'), ((16051, 16082), 'os.path.exists', 'os.path.exists', (['file_name_test_'], {}), '(file_name_test_)\n', (16065, 16082), False, 'import os\n'), ((17279, 17290), 'time.time', 'time.time', ([], {}), '()\n', (17288, 17290), False, 'import time\n'), ((5029, 5060), 'numpy.vstack', 'np.vstack', (['[padding, used_data]'], {}), '([padding, used_data])\n', (5038, 5060), True, 'import numpy as np\n'), ((10209, 10310), 'keras.callbacks.EarlyStopping', 'keras.callbacks.EarlyStopping', ([], {'monitor': '"""val_acc"""', 'min_delta': '(0)', 'patience': '(50)', 'verbose': '(0)', 'mode': '"""max"""'}), "(monitor='val_acc', min_delta=0, patience=50,\n verbose=0, mode='max')\n", (10238, 10310), False, 'import keras\n'), ((10394, 10504), 'keras.callbacks.ModelCheckpoint', 'keras.callbacks.ModelCheckpoint', (['model_path'], {'monitor': '"""val_acc"""', 'save_best_only': '(True)', 'mode': '"""max"""', 'verbose': '(0)'}), "(model_path, monitor='val_acc',\n save_best_only=True, mode='max', verbose=0)\n", (10425, 10504), False, 'import keras\n'), ((17151, 17162), 'time.time', 'time.time', ([], {}), '()\n', (17160, 17162), False, 'import time\n')]
|
# This code is written at BigVision LLC. It is based on the OpenCV project. It is subject to the license terms in the LICENSE file found in this distribution and at http://opencv.org/license.html
# Usage example: python3 object_detection_yolo.py --video=run.mp4 --device 'cpu'
# python3 object_detection_yolo.py --video=run.mp4 --device 'gpu'
# python3 object_detection_yolo.py --image=office.jpg --device 'cpu'
# python3 object_detection_yolo.py --image=bird.jpg --device 'gpu'
import cv2 as cv
import argparse
import sys
import numpy as np
import os.path
import telebot
import datetime
import random
import bisect
import threading
import requests
import requests
import sqlite3
import sys
import MySQLdb
import psycopg2
import pyautogui
import win32gui
import time
from ftplib import FTP
import os
import calendar
print(calendar.day_abbr[datetime.date(2019, 2, 2).weekday()])
d_day_to_cat = {'Fri':'20211112', 'Sat':'20211113', 'Sun':'20211114', 'Mon': '20211115', 'Tue': '20211116', 'Wed': '20211117', 'Thu': '20211118'}
# Initialize the parameters
not_worked_time = 0
time0 = '0:0'
time1 = '0:0'
time0_flag = 0
time1_flag = 0
worked_time_v2 = 0
fl_newtime = 0
bot = telebot.TeleBot('2002045567:AAFBWxp3Fpxf9OdhRFm8HxCUMvAhuZVLwq4')
ch_id = ''
api_token = '2002045567:AAFBWxp3Fpxf9OdhRFm8HxCUMv<PASSWORD>'
flag_of_sent_msg = 0
global ft
time_a = 0
time_t = 0
ftp = FTP('172.16.58.3', user='taxiuser', passwd='<PASSWORD>')
def send_telegram(text, tpe):
token = '<KEY>'
url = "https://api.telegram.org/bot"
channel_id = "-1001668840613"
url += token
method = url + "/sendMessage"
if tpe == 1:
tx = 'Рабочее время: ' + str(text[0]) + ' часов, ' + str(text[1]) + ' минут.'
elif tpe == 2:
tx = 'Работал 1 человек' + str(text[0]) + ' часов, ' + str(text[1]) + ' минут.'
else:
tx = 'Работало более 1 человека' + str(text[0]) + ' часов, ' + str(text[1]) + ' минут.'
r = requests.post(method, data={
"chat_id": channel_id,
"text": tx
})
if r.status_code != 200:
raise Exception("post_text error")
def screenshot(window_title='InternetExplorer'):
if window_title:
hwnd = win32gui.FindWindow(None, window_title)
if hwnd:
win32gui.SetForegroundWindow(hwnd)
x, y, x1, y1 = win32gui.GetClientRect(hwnd)
x, y = win32gui.ClientToScreen(hwnd, (x, y))
x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y))
im = pyautogui.screenshot(region=(x, y, x1, y1))
return im
else:
print('Window not found!')
else:
im = pyautogui.screenshot()
return im
def gettime1(time):
global time1
global time1_flag
global time0_flag
global worked_time_v2
time1 = time
time1_flag = 1
time0_flag = 0
worked_time_v2 += 2
print(worked_time_v2)
def gettime0(time):
global time0
global time1
global time1_flag
global time0_flag
global not_worked_time
if time0_flag == 0:
time0 = time
time0_flag = 1
time1_flag = 0
print(time0, time1)
time_ms_1 = [int(i) for i in str(time1).split(':')[:2]]
time_ms_0 = [int(i) for i in str(time0).split(':')[:2]]
sum_time1 = (time_ms_1[0] * 60) + time_ms_1[1]
sum_time0 = (time_ms_0[0] * 60) + time_ms_0[1]
not_worked_time += sum_time0 - sum_time1
print(str(time0).split(':'), str(time1).split(':'), not_worked_time)
def new_time_counter():
global fl_newtime
global worked_time_v2
if fl_newtime == 0:
worked_time_v2 += 2
fl_newtime = 1
def time_alone():
global time_a
time_a += 2
def time_two():
global time_t
time_t += 2
def image_analis():
confThreshold = 0.5 #Confidence threshold
nmsThreshold = 0.4 #Non-maximum suppression threshold
inpWidth = 416 #Width of network's input image
inpHeight = 416 #Height of network's input image
ms_label_list = []
parser = argparse.ArgumentParser(description='Object Detection using YOLO in OPENCV')
parser.add_argument('--device', default='cpu', help="Device to perform inference on 'cpu' or 'gpu'.")
parser.add_argument('--image', help='office.jpg')
parser.add_argument('--video', help='Path to video file.')
args = parser.parse_args()
# Load names of classes
classesFile = "coco.names"
classes = None
with open(classesFile, 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# Give the configuration and weight files for the model and load the network using them.
modelConfiguration = "yolov3.cfg"
modelWeights = "yolov3.weights"
net = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
if(args.device == 'cpu'):
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)
print('Using CPU device.')
elif(args.device == 'gpu'):
net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)
print('Using GPU device.')
# Get the names of the output layers
def getOutputsNames(net):
# Get the names of all the layers in the network
layersNames = net.getLayerNames()
# Get the names of the output layers, i.e. the layers with unconnected outputs
return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Draw the predicted bounding box
def drawPred(classId, conf, left, top, right, bottom):
# Draw a bounding box.
cv.rectangle(frame, (left, top), (right, bottom), (255, 178, 50), 3)
label = '%.2f' % conf
# Get the label for the class name and its confidence
if classes:
assert(classId < len(classes))
label = '%s:%s' % (classes[classId], label)
ms_label_list.append(label.split(':')[0])
#Display the label at the top of the bounding box
labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
top = max(top, labelSize[1])
cv.rectangle(frame, (left, top - round(1.5*labelSize[1])), (left + round(1.5*labelSize[0]), top + baseLine), (255, 255, 255), cv.FILLED)
cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0,0,0), 1)
# Remove the bounding boxes with low confidence using non-maxima suppression
def postprocess(frame, outs):
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
# Scan through all the bounding boxes output from the network and keep only the
# ones with high confidence scores. Assign the box's class label as the class with the highest score.
classIds = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
classId = np.argmax(scores)
confidence = scores[classId]
if confidence > confThreshold:
center_x = int(detection[0] * frameWidth)
center_y = int(detection[1] * frameHeight)
width = int(detection[2] * frameWidth)
height = int(detection[3] * frameHeight)
left = int(center_x - width / 2)
top = int(center_y - height / 2)
classIds.append(classId)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# Perform non maximum suppression to eliminate redundant overlapping boxes with
# lower confidences.
indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
for i in indices:
i = i[0]
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
drawPred(classIds[i], confidences[i], left, top, left + width, top + height)
# Process inputs
winName = 'Deep learning object detection in OpenCV'
cv.namedWindow(winName, cv.WINDOW_NORMAL)
outputFile = "yolo_out_py.avi"
if (True):
# Open the image file
if not os.path.isfile('office.jpg'):
print("Input image file ", args.image, " doesn't exist")
sys.exit(1)
cap = cv.VideoCapture('office.jpg')
outputFile = 'off' + '_yolo_out_py.jpg'
"""elif (args.video):
# Open the video file
if not os.path.isfile(args.video):
print("Input video file ", args.video, " doesn't exist")
sys.exit(1)
cap = cv.VideoCapture(args.video)
outputFile = args.video[:-4]+'_yolo_out_py.avi'
else:
# Webcam input
cap = cv.VideoCapture(0)"""
# Get the video writer initialized to save the output video
#if (not args.image):
# vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M','J','P','G'), 30, (round(cap.get(cv.CAP_PROP_FRAME_WIDTH)),round(cap.get(cv.CAP_PROP_FRAME_HEIGHT))))
while cv.waitKey(1) < 0:
# get frame from the video
hasFrame, frame = cap.read()
# Stop the program if reached end of video
if not hasFrame:
print("Done processing !!!")
print("Output file is stored as ", outputFile)
cv.waitKey(3000)
# Release device
cap.release()
break
# Create a 4D blob from a frame.
blob = cv.dnn.blobFromImage(frame, 1/255, (inpWidth, inpHeight), [0,0,0], 1, crop=False)
# Sets the input to the network
net.setInput(blob)
# Runs the forward pass to get output of the output layers
outs = net.forward(getOutputsNames(net))
# Remove the bounding boxes with low confidence
postprocess(frame, outs)
# Put efficiency information. The function getPerfProfile returns the overall time for inference(t) and the timings for each of the layers(in layersTimes)
t, _ = net.getPerfProfile()
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))
# Write the frame with the detection boxes
if (True):
cv.imwrite(outputFile, frame.astype(np.uint8))
else:
vid_writer.write(frame.astype(np.uint8))
cv.imshow(winName, frame)
print(ms_label_list)
is_two = (ms_label_list.count('person') >= 2)
is_one = (1 == ms_label_list.count('person'))
if is_one:
return 1
elif is_two:
return 2
return 0
image_analis()
b_time_sender = []
lst = ftp.nlst('20211114')
print('llll', len(lst))
while True:
dt_now = datetime.datetime.now()
m_d = str(dt_now).split(' ')[0].split('-')
if ''.join(str(datetime.datetime.now().time()).split(':')[:2]) == '0801':
flag_of_sent_msg = 0
if ''.join(str(datetime.datetime.now().time()).split(':')[:2]) == '0800':
print('вход')
worked_time = 1440 - not_worked_time
actual_time_hours = str(worked_time_v2 // 60)
actual_time_minutes = str(worked_time_v2 % 60)
time_a_hours = str(time_a // 60)
time_a_minutes = str(time_a % 60)
time_t_hours = str(time_t // 60)
time_t_minutes = str(time_t % 60)
b_time_sender = [actual_time_hours, actual_time_minutes]
b_time_sender_a = [time_a_hours, time_a_minutes]
b_time_sender_t = [time_t_hours, time_t_minutes]
b_dop_time_sender = []
if flag_of_sent_msg == 0:
send_telegram(b_time_sender, 1)
send_telegram(b_time_sender_a, 2)
send_telegram(b_time_sender_t, 3)
flag_of_sent_msg = 1
not_worked_time = 0
time0 = '0:0'
time1 = '0:0'
time0_flag = '0:0'
time1_flag = '0:0'
worked_time_v2 = 0
if int(''.join(str(datetime.datetime.now().time()).split(':')[1])) % 2 == 1:
fl_newtime = 0
if int(''.join(str(datetime.datetime.now().time()).split(':')[1])) % 2 == 0:
print(worked_time_v2)
out = 'office.jpg'
print("получил изображение")
lst = ftp.nlst(d_day_to_cat[calendar.day_abbr[datetime.date(int(m_d[0]), int(m_d[1]), int(m_d[2])).weekday()]])
print(lst[-1], d_day_to_cat[calendar.day_abbr[datetime.date(int(m_d[0]), int(m_d[1]), int(m_d[2])).weekday()]])
with open(out, 'wb') as f:
ftp.retrbinary('RETR ' + f'{lst[-1]}', f.write)
result = image_analis()
if result != 0:
if result == 1:
time_alone()
if result == 2:
time_two()
print("попало в 1")
new_time_counter()
elif result == 0:
print('прошло в 0')
gettime0(datetime.datetime.now().time())
|
[
"win32gui.ClientToScreen",
"argparse.ArgumentParser",
"cv2.dnn.NMSBoxes",
"numpy.argmax",
"pyautogui.screenshot",
"os.path.isfile",
"cv2.rectangle",
"win32gui.SetForegroundWindow",
"requests.post",
"cv2.imshow",
"telebot.TeleBot",
"cv2.getTickFrequency",
"cv2.dnn.blobFromImage",
"datetime.datetime.now",
"cv2.waitKey",
"datetime.date",
"cv2.dnn.readNetFromDarknet",
"sys.exit",
"cv2.putText",
"cv2.getTextSize",
"win32gui.GetClientRect",
"win32gui.FindWindow",
"cv2.VideoCapture",
"ftplib.FTP",
"cv2.namedWindow"
] |
[((1220, 1285), 'telebot.TeleBot', 'telebot.TeleBot', (['"""2002045567:AAFBWxp3Fpxf9OdhRFm8HxCUMvAhuZVLwq4"""'], {}), "('2002045567:AAFBWxp3Fpxf9OdhRFm8HxCUMvAhuZVLwq4')\n", (1235, 1285), False, 'import telebot\n'), ((1418, 1474), 'ftplib.FTP', 'FTP', (['"""172.16.58.3"""'], {'user': '"""taxiuser"""', 'passwd': '"""<PASSWORD>"""'}), "('172.16.58.3', user='taxiuser', passwd='<PASSWORD>')\n", (1421, 1474), False, 'from ftplib import FTP\n'), ((1977, 2040), 'requests.post', 'requests.post', (['method'], {'data': "{'chat_id': channel_id, 'text': tx}"}), "(method, data={'chat_id': channel_id, 'text': tx})\n", (1990, 2040), False, 'import requests\n'), ((4072, 4148), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Object Detection using YOLO in OPENCV"""'}), "(description='Object Detection using YOLO in OPENCV')\n", (4095, 4148), False, 'import argparse\n'), ((4751, 4810), 'cv2.dnn.readNetFromDarknet', 'cv.dnn.readNetFromDarknet', (['modelConfiguration', 'modelWeights'], {}), '(modelConfiguration, modelWeights)\n', (4776, 4810), True, 'import cv2 as cv\n'), ((8150, 8191), 'cv2.namedWindow', 'cv.namedWindow', (['winName', 'cv.WINDOW_NORMAL'], {}), '(winName, cv.WINDOW_NORMAL)\n', (8164, 8191), True, 'import cv2 as cv\n'), ((10839, 10862), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10860, 10862), False, 'import datetime\n'), ((2231, 2270), 'win32gui.FindWindow', 'win32gui.FindWindow', (['None', 'window_title'], {}), '(None, window_title)\n', (2250, 2270), False, 'import win32gui\n'), ((2676, 2698), 'pyautogui.screenshot', 'pyautogui.screenshot', ([], {}), '()\n', (2696, 2698), False, 'import pyautogui\n'), ((5646, 5714), 'cv2.rectangle', 'cv.rectangle', (['frame', '(left, top)', '(right, bottom)', '(255, 178, 50)', '(3)'], {}), '(frame, (left, top), (right, bottom), (255, 178, 50), 3)\n', (5658, 5714), True, 'import cv2 as cv\n'), ((6068, 6122), 'cv2.getTextSize', 'cv.getTextSize', (['label', 'cv.FONT_HERSHEY_SIMPLEX', '(0.5)', '(1)'], {}), '(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n', (6082, 6122), True, 'import cv2 as cv\n'), ((6313, 6399), 'cv2.putText', 'cv.putText', (['frame', 'label', '(left, top)', 'cv.FONT_HERSHEY_SIMPLEX', '(0.75)', '(0, 0, 0)', '(1)'], {}), '(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0,\n 0), 1)\n', (6323, 6399), True, 'import cv2 as cv\n'), ((7733, 7797), 'cv2.dnn.NMSBoxes', 'cv.dnn.NMSBoxes', (['boxes', 'confidences', 'confThreshold', 'nmsThreshold'], {}), '(boxes, confidences, confThreshold, nmsThreshold)\n', (7748, 7797), True, 'import cv2 as cv\n'), ((8425, 8454), 'cv2.VideoCapture', 'cv.VideoCapture', (['"""office.jpg"""'], {}), "('office.jpg')\n", (8440, 8454), True, 'import cv2 as cv\n'), ((9141, 9154), 'cv2.waitKey', 'cv.waitKey', (['(1)'], {}), '(1)\n', (9151, 9154), True, 'import cv2 as cv\n'), ((9569, 9658), 'cv2.dnn.blobFromImage', 'cv.dnn.blobFromImage', (['frame', '(1 / 255)', '(inpWidth, inpHeight)', '[0, 0, 0]', '(1)'], {'crop': '(False)'}), '(frame, 1 / 255, (inpWidth, inpHeight), [0, 0, 0], 1,\n crop=False)\n', (9589, 9658), True, 'import cv2 as cv\n'), ((10215, 10291), 'cv2.putText', 'cv.putText', (['frame', 'label', '(0, 15)', 'cv.FONT_HERSHEY_SIMPLEX', '(0.5)', '(0, 0, 255)'], {}), '(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))\n', (10225, 10291), True, 'import cv2 as cv\n'), ((10498, 10523), 'cv2.imshow', 'cv.imshow', (['winName', 'frame'], {}), '(winName, frame)\n', (10507, 10523), True, 'import cv2 as cv\n'), ((2300, 2334), 'win32gui.SetForegroundWindow', 'win32gui.SetForegroundWindow', (['hwnd'], {}), '(hwnd)\n', (2328, 2334), False, 'import win32gui\n'), ((2362, 2390), 'win32gui.GetClientRect', 'win32gui.GetClientRect', (['hwnd'], {}), '(hwnd)\n', (2384, 2390), False, 'import win32gui\n'), ((2410, 2447), 'win32gui.ClientToScreen', 'win32gui.ClientToScreen', (['hwnd', '(x, y)'], {}), '(hwnd, (x, y))\n', (2433, 2447), False, 'import win32gui\n'), ((2469, 2516), 'win32gui.ClientToScreen', 'win32gui.ClientToScreen', (['hwnd', '(x1 - x, y1 - y)'], {}), '(hwnd, (x1 - x, y1 - y))\n', (2492, 2516), False, 'import win32gui\n'), ((2534, 2577), 'pyautogui.screenshot', 'pyautogui.screenshot', ([], {'region': '(x, y, x1, y1)'}), '(region=(x, y, x1, y1))\n', (2554, 2577), False, 'import pyautogui\n'), ((8288, 8316), 'os.path.isfile', 'os.path.isfile', (['"""office.jpg"""'], {}), "('office.jpg')\n", (8302, 8316), False, 'import os\n'), ((8399, 8410), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (8407, 8410), False, 'import sys\n'), ((9422, 9438), 'cv2.waitKey', 'cv.waitKey', (['(3000)'], {}), '(3000)\n', (9432, 9438), True, 'import cv2 as cv\n'), ((890, 915), 'datetime.date', 'datetime.date', (['(2019)', '(2)', '(2)'], {}), '(2019, 2, 2)\n', (903, 915), False, 'import datetime\n'), ((6972, 6989), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (6981, 6989), True, 'import numpy as np\n'), ((10184, 10205), 'cv2.getTickFrequency', 'cv.getTickFrequency', ([], {}), '()\n', (10203, 10205), True, 'import cv2 as cv\n'), ((12923, 12946), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (12944, 12946), False, 'import datetime\n'), ((10929, 10952), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10950, 10952), False, 'import datetime\n'), ((11036, 11059), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (11057, 11059), False, 'import datetime\n'), ((12022, 12045), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (12043, 12045), False, 'import datetime\n'), ((12126, 12149), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (12147, 12149), False, 'import datetime\n')]
|
import netCDF4
import bisect
import warnings
from collections import OrderedDict
import numpy as np
from kid_readout.roach.tools import ntone_power_correction
import kid_readout.analysis.timeseries.fftfilt
from kid_readout.measurement.io.data_block import lpf
import kid_readout.roach.tools
class TimestreamGroup(object):
def __init__(self,ncgroup, parent=None):
self.parent = parent
keys = ncgroup.variables.keys()
keys.remove('data')
keys.remove('dt')
keys.remove('fs')
keys.remove('tone')
keys.remove('nsamp')
for key in keys:
setattr(self,key,ncgroup.variables[key][:])
required_keys = ['wavenorm', 'sweep_index']
for key in required_keys:
if key not in keys:
setattr(self,key,None)
# self.epoch = ncgroup.variables['epoch'][:]
self.tonebin = ncgroup.variables['tone'][:]
self.tone_nsamp = ncgroup.variables['nsamp'][:]
# self.fftbin = ncgroup.variables['fftbin'][:]
# self.nfft = ncgroup.variables['nfft'][:]
# self.dt = ncgroup.variables['dt'][:] # the dt property is actually misleading at this point, so leaving it out
self.adc_sampling_freq = ncgroup.variables['fs'][:]
self.baseband_measurement_freq = self.adc_sampling_freq*self.tonebin/(1.0*self.tone_nsamp)
if self.parent.heterodyne:
self.baseband_measurement_freq = np.where(self.baseband_measurement_freq>=self.adc_sampling_freq/2,
self.baseband_measurement_freq-self.adc_sampling_freq,
self.baseband_measurement_freq)
self.measurement_freq = self.lo + self.baseband_measurement_freq
self.sample_rate = self.adc_sampling_freq*1e6/(self.nfft)
else:
self.measurement_freq = self.baseband_measurement_freq
self.sample_rate = self.adc_sampling_freq*1e6/(2*self.nfft)
# if ncgroup.variables.has_key('wavenorm'):
# self.wavenorm = ncgroup.variables['wavenorm'][:]
# else:
# self.wavenorm = None
# if ncgroup.variables.has_key('sweep_index'):
# self.sweep_index = ncgroup.variables['sweep_index'][:]
# else:
# self.sweep_index = None
if self.parent is not None:
self.modulation_duty_cycle = np.zeros_like(self.epoch)
self.modulation_phase = np.zeros_like(self.epoch)
self.modulation_freq = np.zeros_like(self.epoch)
self.modulation_period_samples = np.zeros_like(self.epoch)
for index in range(len(self.epoch)):
out, rate = self.parent.get_modulation_state_at(self.epoch[index])
if out == 2:
self.modulation_duty_cycle[index] = 0.5
self.modulation_freq[index] = self.sample_rate[index]/2.**rate
self.modulation_period_samples[index] = 2.**rate
else:
self.modulation_duty_cycle[index] = out
self.modulation_freq[index] = 0.0
self.modulation_period_samples[index] = 0.0
self._data = ncgroup.variables['data']
self.num_data_samples = self._data.shape[1]
self.data_len_seconds = self.num_data_samples/self.sample_rate
self._datacache = None
@property
def data(self):
if self._datacache is None:
if self.wavenorm is None:
wavenorm = 1.0
warnings.warn("wave normalization not found, time series will not match sweep")
else:
wavenorm = self.wavenorm[:,None]
self._datacache = self._data[:].view(self._data.datatype.name)*wavenorm
return self._datacache
def get_data_index(self,index):
if self._datacache is None:
if self.wavenorm is None:
wavenorm = 1.0
warnings.warn("wave normalization not found, time series will not match sweep")
else:
wavenorm = self.wavenorm[index]
return self._data[index].view(self._data.datatype.name)*wavenorm
else:
return self._datacache[index]
class SweepGroup(object):
def __init__(self,ncgroup, parent=None):
self.parent = parent
self.frequency = ncgroup.variables['frequency'][:]
self.s21 = ncgroup.variables['s21'][:].view(ncgroup.variables['s21'].datatype.name)
self.index = ncgroup.variables['index'][:]
self.timestream_group = TimestreamGroup(ncgroup.groups['datablocks'], parent=parent)
self.start_epoch = self.timestream_group.epoch.min()
self.end_epoch = self.timestream_group.epoch.max()
@property
def errors(self):
return self._get_errors()
def _get_errors(self,mask = None):
if self.timestream_group.wavenorm is None:
wavenorm = 1
else:
wavenorm = self.timestream_group.wavenorm[0]
if mask is None:
indexes_to_calculate = np.arange(self.timestream_group.data.shape[0],dtype='int')
else:
indexes_to_calculate = np.flatnonzero(mask)
errors = np.zeros(indexes_to_calculate.shape[0], dtype='complex')
for output_index,input_index in enumerate(indexes_to_calculate):
filtered = kid_readout.analysis.timeseries.fftfilt.fftfilt(lpf, self.timestream_group.data[input_index,
:])[len(lpf):]
# the standard deviation is scaled by the number of independent samples
# to compute the error on the mean.
error_scaling = np.sqrt(float(len(filtered))/len(lpf))
real_error = filtered.real.std()/error_scaling
imag_error = filtered.imag.std()/error_scaling
errors[output_index] = real_error + 1j*imag_error
return errors
def select_by_index(self,index):
mask = self.index == index
freq,s21,errors = self.frequency[mask], self.s21[mask], self._get_errors(mask)
order = freq.argsort()
return freq[order], s21[order], errors[order]
def select_by_frequency(self,freq):
findex = np.argmin(abs(self.frequency - freq))
index = self.index[findex]
return self.select_by_index(index)
class ReadoutNetCDF(object):
def __init__(self,filename):
self.filename = filename
self.ncroot = netCDF4.Dataset(filename,mode='r')
hwgroup = self.ncroot.groups['hw_state']
self.hardware_state_epoch = hwgroup.variables['epoch'][:]
self.adc_atten = hwgroup.variables['adc_atten'][:]
self.dac_atten = hwgroup.variables['dac_atten'][:]
try:
self.heterodyne = bool(self.ncroot.heterodyne)
except AttributeError:
self.heterodyne = False
if 'ntones' in hwgroup.variables:
self.num_tones = hwgroup.variables['ntones'][:]
else:
self.num_tones = None
for key in ['modulation_rate', 'modulation_output']:
if key in hwgroup.variables:
self.__setattr__(key,hwgroup.variables[key][:])
else:
self.__setattr__(key,None)
try:
self.gitinfo = self.ncroot.gitinfo
except AttributeError:
self.gitinfo = ''
try:
self.boffile = self.ncroot.boffile
except AttributeError:
self.boffile = ''
try:
self.mmw_atten_turns = self.ncroot.mmw_atten_turns
except AttributeError:
self.mmw_atten_turns = (np.nan,np.nan)
self.sweeps_dict = OrderedDict()
self.timestreams_dict = OrderedDict()
for name,group in self.ncroot.groups['sweeps'].groups.items():
self.sweeps_dict[name] = SweepGroup(group, parent=self)
self.__setattr__(name,self.sweeps_dict[name])
self.sweeps = self.sweeps_dict.values()
for name,group in self.ncroot.groups['timestreams'].groups.items():
self.timestreams_dict[name] = TimestreamGroup(group, parent=self)
self.__setattr__(name,self.timestreams_dict[name])
self.timestreams = self.timestreams_dict.values()
def close(self):
self.ncroot.close()
def get_delay_estimate(self):
if self.boffile == '':
try:
nfft = self.sweeps[0].timestream_group.nfft[0]
except IndexError:
raise Exception("could not find any means to estimate the delay for %s" % self.filename)
return kid_readout.roach.tools.get_delay_estimate_for_nfft(nfft)
else:
return kid_readout.roach.tools.get_delay_estimate_for_boffile(self.boffile)
def _get_hwstate_index_at(self,epoch):
"""
Find the index of the hardware state arrays corresponding to the hardware state at a given epoch
:param epoch: unix timestamp
:return:
"""
index = bisect.bisect_left(self.hardware_state_epoch, epoch) # find the index of the epoch immediately preceding the desired epoch
index = index - 1
if index < 0:
index = 0
return index
def get_effective_dac_atten_at(self,epoch):
"""
Get the dac attenuator value and total signal attenuation at a given time
:param epoch: unix timestamp
:return: dac attenuator in dB, total attenuation in dB
"""
index = self._get_hwstate_index_at(epoch)
dac_atten = self.dac_atten[index]
if self.num_tones is not None:
ntones = self.num_tones[index]
else:
ntones = 1
warnings.warn("ntones parameter not found in data file %s, assuming 1. The effective power level may be wrong" % self.filename)
total = dac_atten + ntone_power_correction(ntones)
return dac_atten, total
def get_modulation_state_at(self,epoch):
"""
Get the source modulation TTL output state at a given time
:param epoch: unix timestamp
:return: modulation output state: 0 -> low, 1 -> high, 2 -> modulated
modulation rate parameter: FIXME
"""
if self.modulation_rate is None:
return 0,0
index = self._get_hwstate_index_at(epoch)
modulation_rate = self.modulation_rate[index]
modulation_output = self.modulation_output[index]
return modulation_output, modulation_rate
|
[
"netCDF4.Dataset",
"numpy.zeros_like",
"numpy.flatnonzero",
"numpy.zeros",
"kid_readout.roach.tools.ntone_power_correction",
"numpy.where",
"numpy.arange",
"collections.OrderedDict",
"warnings.warn",
"bisect.bisect_left"
] |
[((5280, 5336), 'numpy.zeros', 'np.zeros', (['indexes_to_calculate.shape[0]'], {'dtype': '"""complex"""'}), "(indexes_to_calculate.shape[0], dtype='complex')\n", (5288, 5336), True, 'import numpy as np\n'), ((6564, 6599), 'netCDF4.Dataset', 'netCDF4.Dataset', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (6579, 6599), False, 'import netCDF4\n'), ((7792, 7805), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (7803, 7805), False, 'from collections import OrderedDict\n'), ((7838, 7851), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (7849, 7851), False, 'from collections import OrderedDict\n'), ((9125, 9177), 'bisect.bisect_left', 'bisect.bisect_left', (['self.hardware_state_epoch', 'epoch'], {}), '(self.hardware_state_epoch, epoch)\n', (9143, 9177), False, 'import bisect\n'), ((1438, 1607), 'numpy.where', 'np.where', (['(self.baseband_measurement_freq >= self.adc_sampling_freq / 2)', '(self.baseband_measurement_freq - self.adc_sampling_freq)', 'self.baseband_measurement_freq'], {}), '(self.baseband_measurement_freq >= self.adc_sampling_freq / 2, self\n .baseband_measurement_freq - self.adc_sampling_freq, self.\n baseband_measurement_freq)\n', (1446, 1607), True, 'import numpy as np\n'), ((2414, 2439), 'numpy.zeros_like', 'np.zeros_like', (['self.epoch'], {}), '(self.epoch)\n', (2427, 2439), True, 'import numpy as np\n'), ((2476, 2501), 'numpy.zeros_like', 'np.zeros_like', (['self.epoch'], {}), '(self.epoch)\n', (2489, 2501), True, 'import numpy as np\n'), ((2537, 2562), 'numpy.zeros_like', 'np.zeros_like', (['self.epoch'], {}), '(self.epoch)\n', (2550, 2562), True, 'import numpy as np\n'), ((2608, 2633), 'numpy.zeros_like', 'np.zeros_like', (['self.epoch'], {}), '(self.epoch)\n', (2621, 2633), True, 'import numpy as np\n'), ((5134, 5193), 'numpy.arange', 'np.arange', (['self.timestream_group.data.shape[0]'], {'dtype': '"""int"""'}), "(self.timestream_group.data.shape[0], dtype='int')\n", (5143, 5193), True, 'import numpy as np\n'), ((5242, 5262), 'numpy.flatnonzero', 'np.flatnonzero', (['mask'], {}), '(mask)\n', (5256, 5262), True, 'import numpy as np\n'), ((9817, 9954), 'warnings.warn', 'warnings.warn', (["('ntones parameter not found in data file %s, assuming 1. The effective power level may be wrong'\n % self.filename)"], {}), "(\n 'ntones parameter not found in data file %s, assuming 1. The effective power level may be wrong'\n % self.filename)\n", (9830, 9954), False, 'import warnings\n'), ((9973, 10003), 'kid_readout.roach.tools.ntone_power_correction', 'ntone_power_correction', (['ntones'], {}), '(ntones)\n', (9995, 10003), False, 'from kid_readout.roach.tools import ntone_power_correction\n'), ((3573, 3652), 'warnings.warn', 'warnings.warn', (['"""wave normalization not found, time series will not match sweep"""'], {}), "('wave normalization not found, time series will not match sweep')\n", (3586, 3652), False, 'import warnings\n'), ((3997, 4076), 'warnings.warn', 'warnings.warn', (['"""wave normalization not found, time series will not match sweep"""'], {}), "('wave normalization not found, time series will not match sweep')\n", (4010, 4076), False, 'import warnings\n')]
|
import os
import csv
from PIL import Image
import numpy as np
import torch
import torch.utils.data as data
from torchvision import datasets, transforms
import params
class COVID19_Dataset(Dataset):
"""
COVID-19 image data collection
Dataset: https://github.com/ieee8023/covid-chestxray-dataset
Paper: https://arxiv.org/abs/2003.11597
"""
def __init__(self,
imgpath=os.path.join(thispath, "covid-chestxray-dataset", "images"),
csvpath=os.path.join(thispath, "covid-chestxray-dataset", "metadata.csv"),
views=["PA", "AP"],
transform=None,
data_aug=None,
nrows=None,
seed=0,
pure_labels=False,
unique_patients=True):
super(COVID19_Dataset, self).__init__()
np.random.seed(seed) # Reset the seed so all runs are the same.
self.imgpath = imgpath
self.transform = transform
self.data_aug = data_aug
self.views = views
# defined here to make the code easier to read
pneumonias = ["COVID-19", "SARS", "MERS", "ARDS", "Streptococcus", "Pneumocystis", "Klebsiella", "Chlamydophila", "Legionella", "Influenza", "Mycoplasma", "Varicella", "Viral", "Bacterial", "Fungal", "Lipoid","E.Coli"]
self.pathologies = ["Pneumonia","No Finding"] + pneumonias
self.pathologies = sorted(self.pathologies)
mapping = dict()
mapping["Pneumonia"] = pneumonias
mapping["Viral"] = ["COVID-19", "SARS", "MERS", "Influenza", "Varicella"]
mapping["Bacterial"] = ["Streptococcus", "Klebsiella", "Chlamydophila", "Legionella", "Mycoplasma","E.Coli"]
mapping["Fungal"] = ["Pneumocystis"]
# Load data
self.csvpath = csvpath
self.csv = pd.read_csv(self.csvpath, nrows=nrows)
self.MAXVAL = 255 # Range [0 255]
# Keep only the frontal views.
#idx_pa = self.csv["view"].isin(["PA", "AP", "AP Supine"])
idx_pa = self.csv["view"].isin(self.views)
self.csv = self.csv[idx_pa]
self.labels = []
for pathology in self.pathologies:
mask = self.csv["finding"].str.contains(pathology)
if pathology in mapping:
for syn in mapping[pathology]:
#print("mapping", syn)
mask |= self.csv["finding"].str.contains(syn)
self.labels.append(mask.values)
self.labels = np.asarray(self.labels).T
self.labels = self.labels.astype(np.float32)
def __repr__(self):
pprint.pprint(self.totals())
return self.__class__.__name__ + " num_samples={} views={}".format(len(self), self.views)
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
imgid = self.csv['filename'].iloc[idx]
img_path = os.path.join(self.imgpath, imgid)
#print(img_path)
img = imread(img_path)
img = normalize(img, self.MAXVAL)
# Check that images are 2D arrays
if len(img.shape) > 2:
img = img[:, :, 0]
if len(img.shape) < 2:
print("error, dimension lower than 2 for image")
# Add color channel
img = img[None, :, :]
if self.transform is not None:
img = self.transform(img)
if self.data_aug is not None:
img = self.data_aug(img)
return {"img":img, "lab":self.labels[idx], "idx":idx}
|
[
"numpy.random.seed",
"numpy.asarray",
"os.path.join"
] |
[((422, 481), 'os.path.join', 'os.path.join', (['thispath', '"""covid-chestxray-dataset"""', '"""images"""'], {}), "(thispath, 'covid-chestxray-dataset', 'images')\n", (434, 481), False, 'import os\n'), ((509, 574), 'os.path.join', 'os.path.join', (['thispath', '"""covid-chestxray-dataset"""', '"""metadata.csv"""'], {}), "(thispath, 'covid-chestxray-dataset', 'metadata.csv')\n", (521, 574), False, 'import os\n'), ((870, 890), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (884, 890), True, 'import numpy as np\n'), ((2944, 2977), 'os.path.join', 'os.path.join', (['self.imgpath', 'imgid'], {}), '(self.imgpath, imgid)\n', (2956, 2977), False, 'import os\n'), ((2546, 2569), 'numpy.asarray', 'np.asarray', (['self.labels'], {}), '(self.labels)\n', (2556, 2569), True, 'import numpy as np\n')]
|
'''
Created on Mar 13, 2012
.. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
'''
import unittest
import numpy as np
import pandas as pd
from ema_workbench.analysis import prim
from ema_workbench.analysis.prim import PrimBox
from test import utilities
from ema_workbench.analysis.scenario_discovery_util import RuleInductionType
def flu_classify(data):
#get the output for deceased population
result = data['deceased population region 1']
#make an empty array of length equal to number of cases
classes = np.zeros(result.shape[0])
#if deceased population is higher then 1.000.000 people, classify as 1
classes[result[:, -1] > 1000000] = 1
return classes
def scarcity_classify(outcomes):
outcome = outcomes['relative market price']
change = np.abs(outcome[:, 1::]-outcome[:, 0:-1])
neg_change = np.min(change, axis=1)
pos_change = np.max(change, axis=1)
logical = (neg_change > -0.6) & (pos_change > 0.6)
classes = np.zeros(outcome.shape[0])
classes[logical] = 1
return classes
class PrimBoxTestCase(unittest.TestCase):
def test_init(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = {'y':np.array([0,1,2])}
results = (x,y)
prim_obj = prim.setup_prim(results, 'y', threshold=0.8)
box = PrimBox(prim_obj, prim_obj.box_init, prim_obj.yi)
self.assertEqual(box.peeling_trajectory.shape, (1,6))
def test_select(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = {'y':np.array([1,1,0])}
results = (x,y)
prim_obj = prim.setup_prim(results, 'y', threshold=0.8)
box = PrimBox(prim_obj, prim_obj.box_init, prim_obj.yi)
new_box_lim = pd.DataFrame([(0,1,1),
(2,5,6)],
columns=['a', 'b', 'c'])
indices = np.array([0,1], dtype=np.int)
box.update(new_box_lim, indices)
box.select(0)
self.assertTrue(np.all(box.yi==prim_obj.yi))
def test_inspect(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = np.array([1,1,0])
prim_obj = prim.Prim(x, y, threshold=0.8)
box = PrimBox(prim_obj, prim_obj.box_init, prim_obj.yi)
new_box_lim = pd.DataFrame([(0,1,1),
(2,5,6)],
columns=['a', 'b', 'c'])
indices = np.array([0,1], dtype=np.int)
box.update(new_box_lim, indices)
box.inspect(1)
box.inspect()
box.inspect(style='graph')
with self.assertRaises(ValueError):
box.inspect(style='some unknown style')
def test_show_ppt(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = np.array([1,1,0])
prim_obj = prim.Prim(x, y, threshold=0.8)
box = PrimBox(prim_obj, prim_obj.box_init, prim_obj.yi)
cols = ['mean', 'mass', 'coverage', 'density', 'res_dim']
data = np.zeros((100, 5))
data[:, 0:4] = np.random.rand(100, 4)
data[:, 4] = np.random.randint(0, 5, size=(100, ))
box.peeling_trajectory = pd.DataFrame(data, columns=cols)
box.show_ppt()
def test_show_tradeoff(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = np.array([1,1,0])
prim_obj = prim.Prim(x, y, threshold=0.8)
box = PrimBox(prim_obj, prim_obj.box_init, prim_obj.yi)
cols = ['mean', 'mass', 'coverage', 'density', 'res_dim']
data = np.zeros((100, 5))
data[:, 0:4] = np.random.rand(100, 4)
data[:, 4] = np.random.randint(0, 5, size=(100, ))
box.peeling_trajectory = pd.DataFrame(data, columns=cols)
box.show_tradeoff()
def test_update(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = {'y':np.array([1,1,0])}
results = (x,y)
prim_obj = prim.setup_prim(results, 'y', threshold=0.8)
box = PrimBox(prim_obj, prim_obj.box_init, prim_obj.yi)
new_box_lim = pd.DataFrame([(0,1,1),
(2,5,6)],
columns=['a', 'b', 'c'])
indices = np.array([0,1], dtype=np.int)
box.update(new_box_lim, indices)
self.assertEqual(box.peeling_trajectory['mean'][1], 1)
self.assertEqual(box.peeling_trajectory['coverage'][1], 1)
self.assertEqual(box.peeling_trajectory['density'][1], 1)
self.assertEqual(box.peeling_trajectory['res_dim'][1], 1)
self.assertEqual(box.peeling_trajectory['mass'][1], 2/3)
def test_drop_restriction(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = {'y':np.array([1,1,0])}
results = (x,y)
prim_obj = prim.setup_prim(results, 'y', threshold=0.8)
box = PrimBox(prim_obj, prim_obj.box_init, prim_obj.yi)
new_box_lim = pd.DataFrame([(0,1,1),
(2,2,6)],
columns=['a', 'b', 'c'])
indices = np.array([0,1], dtype=np.int)
box.update(new_box_lim, indices)
box.drop_restriction('b')
correct_box_lims = pd.DataFrame([(0,1,1),
(2,5,6)],
columns=['a', 'b', 'c'])
box_lims = box.box_lims[-1]
names = box_lims.columns
for entry in names:
lim_correct = correct_box_lims[entry]
lim_box = box_lims[entry]
for i in range(len(lim_correct)):
self.assertEqual(lim_correct[i], lim_box[i])
self.assertEqual(box.peeling_trajectory['mean'][2], 1)
self.assertEqual(box.peeling_trajectory['coverage'][2], 1)
self.assertEqual(box.peeling_trajectory['density'][2], 1)
self.assertEqual(box.peeling_trajectory['res_dim'][2], 1)
self.assertEqual(box.peeling_trajectory['mass'][2], 2/3)
def test_calculate_quasi_p(self):
pass
class PrimTestCase(unittest.TestCase):
def test_setup_prim(self):
self.results = utilities.load_flu_data()
self.classify = flu_classify
experiments, outcomes = self.results
# test initialization, including t_coi calculation in case of searching
# for results equal to or higher than the threshold
outcomes['death toll'] = outcomes['deceased population region 1'][:, -1]
results = experiments, outcomes
threshold = 10000
prim_obj = prim.setup_prim(results, classify='death toll',
threshold_type=prim.ABOVE, threshold=threshold)
value = np.ones((experiments.shape[0],))
value = value[outcomes['death toll'] >= threshold].shape[0]
self.assertTrue(prim_obj.t_coi==value)
# test initialization, including t_coi calculation in case of searching
# for results equal to or lower than the threshold
threshold = 1000
prim_obj = prim.setup_prim(results, classify='death toll',
threshold_type=prim.BELOW,
threshold=threshold)
value = np.ones((experiments.shape[0],))
value = value[outcomes['death toll'] <= threshold].shape[0]
self.assertTrue(prim_obj.t_coi==value)
prim.setup_prim(self.results, self.classify, threshold=prim.ABOVE)
def test_boxes(self):
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,1)],
columns=['a', 'b', 'c'])
y = {'y':np.array([0,1,2])}
results = (x,y)
prim_obj = prim.setup_prim(results, 'y', threshold=0.8)
boxes = prim_obj.boxes
self.assertEqual(len(boxes), 1, 'box length not correct')
# real data test case
prim_obj = prim.setup_prim(utilities.load_flu_data(), flu_classify,
threshold=0.8)
prim_obj.find_box()
boxes = prim_obj.boxes
self.assertEqual(len(boxes), 1, 'box length not correct')
def test_prim_init_select(self):
self.results = utilities.load_flu_data()
self.classify = flu_classify
experiments, outcomes = self.results
unc = experiments.columns.values.tolist()
# test initialization, including t_coi calculation in case of searching
# for results equal to or higher than the threshold
outcomes['death toll'] = outcomes['deceased population region 1'][:, -1]
results = experiments, outcomes
threshold = 10000
prim_obj = prim.setup_prim(results, classify='death toll',
threshold_type=prim.ABOVE, threshold=threshold,
incl_unc=unc)
value = np.ones((experiments.shape[0],))
value = value[outcomes['death toll'] >= threshold].shape[0]
self.assertTrue(prim_obj.t_coi==value)
# test initialization, including t_coi calculation in case of searching
# for results equal to or lower than the threshold
threshold = 1000
prim_obj = prim.setup_prim(results, classify='death toll',
threshold_type=prim.BELOW,
threshold=threshold)
value = np.ones((experiments.shape[0],))
value = value[outcomes['death toll'] <= threshold].shape[0]
self.assertTrue(prim_obj.t_coi==value)
prim.setup_prim(self.results, self.classify, threshold=prim.ABOVE)
def test_quantile(self):
data = pd.Series(np.arange(10))
self.assertTrue(prim.get_quantile(data, 0.9)==8.5)
self.assertTrue(prim.get_quantile(data, 0.95)==8.5)
self.assertTrue(prim.get_quantile(data, 0.1)==0.5)
self.assertTrue(prim.get_quantile(data, 0.05)==0.5)
data = pd.Series(1)
self.assertTrue(prim.get_quantile(data, 0.9)==1)
self.assertTrue(prim.get_quantile(data, 0.95)==1)
self.assertTrue(prim.get_quantile(data, 0.1)==1)
self.assertTrue(prim.get_quantile(data, 0.05)==1)
data = pd.Series([1,1,2,3,4,5,6,7,8,9,9])
self.assertTrue(prim.get_quantile(data, 0.9)==8.5)
self.assertTrue(prim.get_quantile(data, 0.95)==8.5)
self.assertTrue(prim.get_quantile(data, 0.1)==1.5)
self.assertTrue(prim.get_quantile(data, 0.05)==1.5)
def test_box_init(self):
# test init box without NANS
x = pd.DataFrame([(0,1,2),
(2,5,6),
(3,2,7)],
columns=['a', 'b', 'c'])
y = np.array([0,1,2])
prim_obj = prim.Prim(x,y, threshold=0.5,
mode=RuleInductionType.REGRESSION)
box_init = prim_obj.box_init
# some test on the box
self.assertTrue(box_init.loc[0, 'a']==0)
self.assertTrue(box_init.loc[1, 'a']==3)
self.assertTrue(box_init.loc[0, 'b']==1)
self.assertTrue(box_init.loc[1, 'b']==5)
self.assertTrue(box_init.loc[0, 'c']==2)
self.assertTrue(box_init.loc[1, 'c']==7)
# heterogenous without NAN
x = pd.DataFrame([[0.1, 0, 'a'],
[0.2, 1, 'b'],
[0.3, 2, 'a'],
[0.4, 3, 'b'],
[0.5, 4, 'a'],
[0.6, 5, 'a'],
[0.7, 6, 'b'],
[0.8, 7, 'a'],
[0.9, 8, 'b'],
[1.0, 9, 'a']],
columns=['a', 'b', 'c'])
y = np.arange(0, x.shape[0])
prim_obj = prim.Prim(x,y, threshold=0.5,
mode=RuleInductionType.REGRESSION)
box_init = prim_obj.box_init
# some test on the box
self.assertTrue(box_init['a'][0]==0.1)
self.assertTrue(box_init['a'][1]==1.0)
self.assertTrue(box_init['b'][0]==0)
self.assertTrue(box_init['b'][1]==9)
self.assertTrue(box_init['c'][0]==set(['a','b']))
self.assertTrue(box_init['c'][1]==set(['a','b']))
def test_prim_exceptions(self):
results = utilities.load_flu_data()
x, outcomes = results
y = outcomes['deceased population region 1']
self.assertRaises(prim.PrimException, prim.Prim,
x, y, threshold=0.8,
mode=RuleInductionType.REGRESSION)
def test_find_box(self):
results = utilities.load_flu_data()
classify = flu_classify
prim_obj = prim.setup_prim(results, classify,
threshold=0.8)
box_1 = prim_obj.find_box()
prim_obj._update_yi_remaining(prim_obj)
after_find = box_1.yi.shape[0] + prim_obj.yi_remaining.shape[0]
self.assertEqual(after_find, prim_obj.y.shape[0])
box_2 = prim_obj.find_box()
prim_obj._update_yi_remaining(prim_obj)
after_find = box_1.yi.shape[0] +\
box_2.yi.shape[0] +\
prim_obj.yi_remaining.shape[0]
self.assertEqual(after_find, prim_obj.y.shape[0])
def test_discrete_peel(self):
x = pd.DataFrame(np.random.randint(0, 10, size=(100,), dtype=np.int),
columns=['a'])
y = np.zeros(100,)
y[x.a > 5] = 1
primalg = prim.Prim(x, y, threshold=0.8)
boxlims = primalg.box_init
box = prim.PrimBox(primalg, boxlims, primalg.yi)
peels = primalg._discrete_peel(box, 'a', 0, primalg.x_int)
self.assertEqual(len(peels), 2)
for peel in peels:
self.assertEqual(len(peel), 2)
indices, tempbox = peel
self.assertTrue(isinstance(indices, np.ndarray))
self.assertTrue(isinstance(tempbox, pd.DataFrame))
# have modified boxlims as starting point
primalg = prim.Prim(x, y, threshold=0.8)
boxlims = primalg.box_init
boxlims.a = [1,8]
box = prim.PrimBox(primalg, boxlims, primalg.yi)
peels = primalg._discrete_peel(box, 'a', 0, primalg.x_int)
self.assertEqual(len(peels), 2)
for peel in peels:
self.assertEqual(len(peel), 2)
indices, tempbox = peel
self.assertTrue(isinstance(indices, np.ndarray))
self.assertTrue(isinstance(tempbox, pd.DataFrame))
# have modified boxlims as starting point
x.a[x.a>5] = 5
primalg = prim.Prim(x, y, threshold=0.8)
boxlims = primalg.box_init
boxlims.a = [5,8]
box = prim.PrimBox(primalg, boxlims, primalg.yi)
peels = primalg._discrete_peel(box, 'a', 0, primalg.x_int)
self.assertEqual(len(peels), 2)
x.a[x.a<5] = 5
primalg = prim.Prim(x, y, threshold=0.8)
boxlims = primalg.box_init
boxlims.a = [5,8]
box = prim.PrimBox(primalg, boxlims, primalg.yi)
peels = primalg._discrete_peel(box, 'a', 0, primalg.x_int)
self.assertEqual(len(peels), 2)
def test_categorical_peel(self):
x = pd.DataFrame(list(zip(np.random.rand(10,),
['a','b','a','b','a','a','b','a','b','a', ])),
columns=['a', 'b'])
y = np.random.randint(0,2, (10,))
y = y.astype(np.int)
y = {'y':y}
results = x, y
classify = 'y'
prim_obj = prim.setup_prim(results, classify, threshold=0.8)
box_lims = pd.DataFrame([(0, set(['a','b'])),
(1, set(['a','b']))],
columns=['a', 'b'] )
box = prim.PrimBox(prim_obj, box_lims, prim_obj.yi)
u = 'b'
x = x.select_dtypes(exclude=np.number).values
j = 0
peels = prim_obj._categorical_peel(box, u, j, x)
self.assertEqual(len(peels), 2)
for peel in peels:
pl = peel[1][u]
self.assertEqual(len(pl[0]), 1)
self.assertEqual(len(pl[1]), 1)
a = ('a',)
b = ('b',)
x = pd.DataFrame(list(zip(np.random.rand(10,),
[a, b, a, b, a,
a, b, a, b, a])),
columns=['a', 'b'])
y = np.random.randint(0,2, (10,))
y = y.astype(np.int)
y = {'y':y}
results = x, y
classify = 'y'
prim_obj = prim.setup_prim(results, classify, threshold=0.8)
box_lims = prim_obj.box_init
box = prim.PrimBox(prim_obj, box_lims, prim_obj.yi)
u = 'b'
x = x.select_dtypes(exclude=np.number).values
j = 0
peels = prim_obj._categorical_peel(box, u, j, x)
self.assertEqual(len(peels), 2)
for peel in peels:
pl = peel[1][u]
self.assertEqual(len(pl[0]), 1)
self.assertEqual(len(pl[1]), 1)
def test_categorical_paste(self):
a = np.random.rand(10,)
b = ['a','b','a','b','a','a','b','a','b','a', ]
x = pd.DataFrame(list(zip(a,b)), columns=['a', 'b'])
x['b'] = x['b'].astype('category')
y = np.random.randint(0,2, (10,))
y = y.astype(np.int)
y = {'y':y}
results = x,y
classify = 'y'
prim_obj = prim.setup_prim(results, classify, threshold=0.8)
box_lims = pd.DataFrame([(0, set(['a',])),
(1, set(['a',]))], columns=x.columns)
yi = np.where(x.loc[:,'b']=='a')
box = prim.PrimBox(prim_obj, box_lims, yi)
u = 'b'
pastes = prim_obj._categorical_paste(box, u, x, ['b'])
self.assertEqual(len(pastes), 1)
for paste in pastes:
indices, box_lims = paste
self.assertEqual(indices.shape[0], 10)
self.assertEqual(box_lims[u][0], set(['a','b']))
if __name__ == '__main__':
# ema_logging.log_to_stderr(ema_logging.INFO)
unittest.main()
# suite = unittest.TestSuite()
# suite.addTest(PrimTestCase("test_write_boxes_to_stdout"))
# unittest.TextTestRunner().run(suite)
|
[
"test.utilities.load_flu_data",
"numpy.abs",
"numpy.ones",
"ema_workbench.analysis.prim.PrimBox",
"numpy.random.randint",
"numpy.arange",
"unittest.main",
"pandas.DataFrame",
"ema_workbench.analysis.prim.Prim",
"numpy.max",
"ema_workbench.analysis.prim.setup_prim",
"numpy.min",
"pandas.Series",
"numpy.all",
"numpy.zeros",
"numpy.where",
"numpy.array",
"ema_workbench.analysis.prim.get_quantile",
"numpy.random.rand"
] |
[((546, 571), 'numpy.zeros', 'np.zeros', (['result.shape[0]'], {}), '(result.shape[0])\n', (554, 571), True, 'import numpy as np\n'), ((813, 854), 'numpy.abs', 'np.abs', (['(outcome[:, 1:] - outcome[:, 0:-1])'], {}), '(outcome[:, 1:] - outcome[:, 0:-1])\n', (819, 854), True, 'import numpy as np\n'), ((876, 898), 'numpy.min', 'np.min', (['change'], {'axis': '(1)'}), '(change, axis=1)\n', (882, 898), True, 'import numpy as np\n'), ((916, 938), 'numpy.max', 'np.max', (['change'], {'axis': '(1)'}), '(change, axis=1)\n', (922, 938), True, 'import numpy as np\n'), ((1018, 1044), 'numpy.zeros', 'np.zeros', (['outcome.shape[0]'], {}), '(outcome.shape[0])\n', (1026, 1044), True, 'import numpy as np\n'), ((19557, 19572), 'unittest.main', 'unittest.main', ([], {}), '()\n', (19570, 19572), False, 'import unittest\n'), ((1175, 1247), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (1187, 1247), True, 'import pandas as pd\n'), ((1409, 1453), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', '"""y"""'], {'threshold': '(0.8)'}), "(results, 'y', threshold=0.8)\n", (1424, 1453), False, 'from ema_workbench.analysis import prim\n'), ((1468, 1517), 'ema_workbench.analysis.prim.PrimBox', 'PrimBox', (['prim_obj', 'prim_obj.box_init', 'prim_obj.yi'], {}), '(prim_obj, prim_obj.box_init, prim_obj.yi)\n', (1475, 1517), False, 'from ema_workbench.analysis.prim import PrimBox\n'), ((1625, 1697), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (1637, 1697), True, 'import pandas as pd\n'), ((1859, 1903), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', '"""y"""'], {'threshold': '(0.8)'}), "(results, 'y', threshold=0.8)\n", (1874, 1903), False, 'from ema_workbench.analysis import prim\n'), ((1918, 1967), 'ema_workbench.analysis.prim.PrimBox', 'PrimBox', (['prim_obj', 'prim_obj.box_init', 'prim_obj.yi'], {}), '(prim_obj, prim_obj.box_init, prim_obj.yi)\n', (1925, 1967), False, 'from ema_workbench.analysis.prim import PrimBox\n'), ((1991, 2052), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 1), (2, 5, 6)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 1), (2, 5, 6)], columns=['a', 'b', 'c'])\n", (2003, 2052), True, 'import pandas as pd\n'), ((2140, 2170), 'numpy.array', 'np.array', (['[0, 1]'], {'dtype': 'np.int'}), '([0, 1], dtype=np.int)\n', (2148, 2170), True, 'import numpy as np\n'), ((2340, 2412), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (2352, 2412), True, 'import pandas as pd\n'), ((2498, 2517), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (2506, 2517), True, 'import numpy as np\n'), ((2544, 2574), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.8)'}), '(x, y, threshold=0.8)\n', (2553, 2574), False, 'from ema_workbench.analysis import prim\n'), ((2589, 2638), 'ema_workbench.analysis.prim.PrimBox', 'PrimBox', (['prim_obj', 'prim_obj.box_init', 'prim_obj.yi'], {}), '(prim_obj, prim_obj.box_init, prim_obj.yi)\n', (2596, 2638), False, 'from ema_workbench.analysis.prim import PrimBox\n'), ((2662, 2723), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 1), (2, 5, 6)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 1), (2, 5, 6)], columns=['a', 'b', 'c'])\n", (2674, 2723), True, 'import pandas as pd\n'), ((2811, 2841), 'numpy.array', 'np.array', (['[0, 1]'], {'dtype': 'np.int'}), '([0, 1], dtype=np.int)\n', (2819, 2841), True, 'import numpy as np\n'), ((3122, 3194), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (3134, 3194), True, 'import pandas as pd\n'), ((3280, 3299), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (3288, 3299), True, 'import numpy as np\n'), ((3326, 3356), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.8)'}), '(x, y, threshold=0.8)\n', (3335, 3356), False, 'from ema_workbench.analysis import prim\n'), ((3371, 3420), 'ema_workbench.analysis.prim.PrimBox', 'PrimBox', (['prim_obj', 'prim_obj.box_init', 'prim_obj.yi'], {}), '(prim_obj, prim_obj.box_init, prim_obj.yi)\n', (3378, 3420), False, 'from ema_workbench.analysis.prim import PrimBox\n'), ((3520, 3538), 'numpy.zeros', 'np.zeros', (['(100, 5)'], {}), '((100, 5))\n', (3528, 3538), True, 'import numpy as np\n'), ((3562, 3584), 'numpy.random.rand', 'np.random.rand', (['(100)', '(4)'], {}), '(100, 4)\n', (3576, 3584), True, 'import numpy as np\n'), ((3606, 3642), 'numpy.random.randint', 'np.random.randint', (['(0)', '(5)'], {'size': '(100,)'}), '(0, 5, size=(100,))\n', (3623, 3642), True, 'import numpy as np\n'), ((3677, 3709), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'cols'}), '(data, columns=cols)\n', (3689, 3709), True, 'import pandas as pd\n'), ((3801, 3873), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (3813, 3873), True, 'import pandas as pd\n'), ((3959, 3978), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (3967, 3978), True, 'import numpy as np\n'), ((4005, 4035), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.8)'}), '(x, y, threshold=0.8)\n', (4014, 4035), False, 'from ema_workbench.analysis import prim\n'), ((4050, 4099), 'ema_workbench.analysis.prim.PrimBox', 'PrimBox', (['prim_obj', 'prim_obj.box_init', 'prim_obj.yi'], {}), '(prim_obj, prim_obj.box_init, prim_obj.yi)\n', (4057, 4099), False, 'from ema_workbench.analysis.prim import PrimBox\n'), ((4199, 4217), 'numpy.zeros', 'np.zeros', (['(100, 5)'], {}), '((100, 5))\n', (4207, 4217), True, 'import numpy as np\n'), ((4241, 4263), 'numpy.random.rand', 'np.random.rand', (['(100)', '(4)'], {}), '(100, 4)\n', (4255, 4263), True, 'import numpy as np\n'), ((4285, 4321), 'numpy.random.randint', 'np.random.randint', (['(0)', '(5)'], {'size': '(100,)'}), '(0, 5, size=(100,))\n', (4302, 4321), True, 'import numpy as np\n'), ((4356, 4388), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'cols'}), '(data, columns=cols)\n', (4368, 4388), True, 'import pandas as pd\n'), ((4474, 4546), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (4486, 4546), True, 'import pandas as pd\n'), ((4708, 4752), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', '"""y"""'], {'threshold': '(0.8)'}), "(results, 'y', threshold=0.8)\n", (4723, 4752), False, 'from ema_workbench.analysis import prim\n'), ((4767, 4816), 'ema_workbench.analysis.prim.PrimBox', 'PrimBox', (['prim_obj', 'prim_obj.box_init', 'prim_obj.yi'], {}), '(prim_obj, prim_obj.box_init, prim_obj.yi)\n', (4774, 4816), False, 'from ema_workbench.analysis.prim import PrimBox\n'), ((4840, 4901), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 1), (2, 5, 6)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 1), (2, 5, 6)], columns=['a', 'b', 'c'])\n", (4852, 4901), True, 'import pandas as pd\n'), ((4989, 5019), 'numpy.array', 'np.array', (['[0, 1]'], {'dtype': 'np.int'}), '([0, 1], dtype=np.int)\n', (4997, 5019), True, 'import numpy as np\n'), ((5450, 5522), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (5462, 5522), True, 'import pandas as pd\n'), ((5684, 5728), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', '"""y"""'], {'threshold': '(0.8)'}), "(results, 'y', threshold=0.8)\n", (5699, 5728), False, 'from ema_workbench.analysis import prim\n'), ((5743, 5792), 'ema_workbench.analysis.prim.PrimBox', 'PrimBox', (['prim_obj', 'prim_obj.box_init', 'prim_obj.yi'], {}), '(prim_obj, prim_obj.box_init, prim_obj.yi)\n', (5750, 5792), False, 'from ema_workbench.analysis.prim import PrimBox\n'), ((5816, 5877), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 1), (2, 2, 6)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 1), (2, 2, 6)], columns=['a', 'b', 'c'])\n", (5828, 5877), True, 'import pandas as pd\n'), ((5965, 5995), 'numpy.array', 'np.array', (['[0, 1]'], {'dtype': 'np.int'}), '([0, 1], dtype=np.int)\n', (5973, 5995), True, 'import numpy as np\n'), ((6115, 6176), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 1), (2, 5, 6)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 1), (2, 5, 6)], columns=['a', 'b', 'c'])\n", (6127, 6176), True, 'import pandas as pd\n'), ((7052, 7077), 'test.utilities.load_flu_data', 'utilities.load_flu_data', ([], {}), '()\n', (7075, 7077), False, 'from test import utilities\n'), ((7492, 7591), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results'], {'classify': '"""death toll"""', 'threshold_type': 'prim.ABOVE', 'threshold': 'threshold'}), "(results, classify='death toll', threshold_type=prim.ABOVE,\n threshold=threshold)\n", (7507, 7591), False, 'from ema_workbench.analysis import prim\n'), ((7643, 7675), 'numpy.ones', 'np.ones', (['(experiments.shape[0],)'], {}), '((experiments.shape[0],))\n', (7650, 7675), True, 'import numpy as np\n'), ((7992, 8091), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results'], {'classify': '"""death toll"""', 'threshold_type': 'prim.BELOW', 'threshold': 'threshold'}), "(results, classify='death toll', threshold_type=prim.BELOW,\n threshold=threshold)\n", (8007, 8091), False, 'from ema_workbench.analysis import prim\n'), ((8173, 8205), 'numpy.ones', 'np.ones', (['(experiments.shape[0],)'], {}), '((experiments.shape[0],))\n', (8180, 8205), True, 'import numpy as np\n'), ((8338, 8404), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['self.results', 'self.classify'], {'threshold': 'prim.ABOVE'}), '(self.results, self.classify, threshold=prim.ABOVE)\n', (8353, 8404), False, 'from ema_workbench.analysis import prim\n'), ((8448, 8520), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 1)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 1)], columns=['a', 'b', 'c'])\n", (8460, 8520), True, 'import pandas as pd\n'), ((8681, 8725), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', '"""y"""'], {'threshold': '(0.8)'}), "(results, 'y', threshold=0.8)\n", (8696, 8725), False, 'from ema_workbench.analysis import prim\n'), ((9193, 9218), 'test.utilities.load_flu_data', 'utilities.load_flu_data', ([], {}), '()\n', (9216, 9218), False, 'from test import utilities\n'), ((9692, 9805), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results'], {'classify': '"""death toll"""', 'threshold_type': 'prim.ABOVE', 'threshold': 'threshold', 'incl_unc': 'unc'}), "(results, classify='death toll', threshold_type=prim.ABOVE,\n threshold=threshold, incl_unc=unc)\n", (9707, 9805), False, 'from ema_workbench.analysis import prim\n'), ((9886, 9918), 'numpy.ones', 'np.ones', (['(experiments.shape[0],)'], {}), '((experiments.shape[0],))\n', (9893, 9918), True, 'import numpy as np\n'), ((10235, 10334), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results'], {'classify': '"""death toll"""', 'threshold_type': 'prim.BELOW', 'threshold': 'threshold'}), "(results, classify='death toll', threshold_type=prim.BELOW,\n threshold=threshold)\n", (10250, 10334), False, 'from ema_workbench.analysis import prim\n'), ((10416, 10448), 'numpy.ones', 'np.ones', (['(experiments.shape[0],)'], {}), '((experiments.shape[0],))\n', (10423, 10448), True, 'import numpy as np\n'), ((10581, 10647), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['self.results', 'self.classify'], {'threshold': 'prim.ABOVE'}), '(self.results, self.classify, threshold=prim.ABOVE)\n', (10596, 10647), False, 'from ema_workbench.analysis import prim\n'), ((10980, 10992), 'pandas.Series', 'pd.Series', (['(1)'], {}), '(1)\n', (10989, 10992), True, 'import pandas as pd\n'), ((11247, 11291), 'pandas.Series', 'pd.Series', (['[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9]'], {}), '([1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9])\n', (11256, 11291), True, 'import pandas as pd\n'), ((11627, 11699), 'pandas.DataFrame', 'pd.DataFrame', (['[(0, 1, 2), (2, 5, 6), (3, 2, 7)]'], {'columns': "['a', 'b', 'c']"}), "([(0, 1, 2), (2, 5, 6), (3, 2, 7)], columns=['a', 'b', 'c'])\n", (11639, 11699), True, 'import pandas as pd\n'), ((11784, 11803), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (11792, 11803), True, 'import numpy as np\n'), ((11830, 11895), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.5)', 'mode': 'RuleInductionType.REGRESSION'}), '(x, y, threshold=0.5, mode=RuleInductionType.REGRESSION)\n', (11839, 11895), False, 'from ema_workbench.analysis import prim\n'), ((12346, 12545), 'pandas.DataFrame', 'pd.DataFrame', (["[[0.1, 0, 'a'], [0.2, 1, 'b'], [0.3, 2, 'a'], [0.4, 3, 'b'], [0.5, 4, 'a'],\n [0.6, 5, 'a'], [0.7, 6, 'b'], [0.8, 7, 'a'], [0.9, 8, 'b'], [1.0, 9, 'a']]"], {'columns': "['a', 'b', 'c']"}), "([[0.1, 0, 'a'], [0.2, 1, 'b'], [0.3, 2, 'a'], [0.4, 3, 'b'], [\n 0.5, 4, 'a'], [0.6, 5, 'a'], [0.7, 6, 'b'], [0.8, 7, 'a'], [0.9, 8, 'b'\n ], [1.0, 9, 'a']], columns=['a', 'b', 'c'])\n", (12358, 12545), True, 'import pandas as pd\n'), ((12809, 12833), 'numpy.arange', 'np.arange', (['(0)', 'x.shape[0]'], {}), '(0, x.shape[0])\n', (12818, 12833), True, 'import numpy as np\n'), ((12854, 12919), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.5)', 'mode': 'RuleInductionType.REGRESSION'}), '(x, y, threshold=0.5, mode=RuleInductionType.REGRESSION)\n', (12863, 12919), False, 'from ema_workbench.analysis import prim\n'), ((13385, 13410), 'test.utilities.load_flu_data', 'utilities.load_flu_data', ([], {}), '()\n', (13408, 13410), False, 'from test import utilities\n'), ((13716, 13741), 'test.utilities.load_flu_data', 'utilities.load_flu_data', ([], {}), '()\n', (13739, 13741), False, 'from test import utilities\n'), ((13802, 13851), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', 'classify'], {'threshold': '(0.8)'}), '(results, classify, threshold=0.8)\n', (13817, 13851), False, 'from ema_workbench.analysis import prim\n'), ((14581, 14594), 'numpy.zeros', 'np.zeros', (['(100)'], {}), '(100)\n', (14589, 14594), True, 'import numpy as np\n'), ((14646, 14676), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.8)'}), '(x, y, threshold=0.8)\n', (14655, 14676), False, 'from ema_workbench.analysis import prim\n'), ((14726, 14768), 'ema_workbench.analysis.prim.PrimBox', 'prim.PrimBox', (['primalg', 'boxlims', 'primalg.yi'], {}), '(primalg, boxlims, primalg.yi)\n', (14738, 14768), False, 'from ema_workbench.analysis import prim\n'), ((15236, 15266), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.8)'}), '(x, y, threshold=0.8)\n', (15245, 15266), False, 'from ema_workbench.analysis import prim\n'), ((15342, 15384), 'ema_workbench.analysis.prim.PrimBox', 'prim.PrimBox', (['primalg', 'boxlims', 'primalg.yi'], {}), '(primalg, boxlims, primalg.yi)\n', (15354, 15384), False, 'from ema_workbench.analysis import prim\n'), ((15875, 15905), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.8)'}), '(x, y, threshold=0.8)\n', (15884, 15905), False, 'from ema_workbench.analysis import prim\n'), ((15981, 16023), 'ema_workbench.analysis.prim.PrimBox', 'prim.PrimBox', (['primalg', 'boxlims', 'primalg.yi'], {}), '(primalg, boxlims, primalg.yi)\n', (15993, 16023), False, 'from ema_workbench.analysis import prim\n'), ((16187, 16217), 'ema_workbench.analysis.prim.Prim', 'prim.Prim', (['x', 'y'], {'threshold': '(0.8)'}), '(x, y, threshold=0.8)\n', (16196, 16217), False, 'from ema_workbench.analysis import prim\n'), ((16293, 16335), 'ema_workbench.analysis.prim.PrimBox', 'prim.PrimBox', (['primalg', 'boxlims', 'primalg.yi'], {}), '(primalg, boxlims, primalg.yi)\n', (16305, 16335), False, 'from ema_workbench.analysis import prim\n'), ((16715, 16745), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', '(10,)'], {}), '(0, 2, (10,))\n', (16732, 16745), True, 'import numpy as np\n'), ((16869, 16918), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', 'classify'], {'threshold': '(0.8)'}), '(results, classify, threshold=0.8)\n', (16884, 16918), False, 'from ema_workbench.analysis import prim\n'), ((17096, 17141), 'ema_workbench.analysis.prim.PrimBox', 'prim.PrimBox', (['prim_obj', 'box_lims', 'prim_obj.yi'], {}), '(prim_obj, box_lims, prim_obj.yi)\n', (17108, 17141), False, 'from ema_workbench.analysis import prim\n'), ((17782, 17812), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', '(10,)'], {}), '(0, 2, (10,))\n', (17799, 17812), True, 'import numpy as np\n'), ((17936, 17985), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', 'classify'], {'threshold': '(0.8)'}), '(results, classify, threshold=0.8)\n', (17951, 17985), False, 'from ema_workbench.analysis import prim\n'), ((18037, 18082), 'ema_workbench.analysis.prim.PrimBox', 'prim.PrimBox', (['prim_obj', 'box_lims', 'prim_obj.yi'], {}), '(prim_obj, box_lims, prim_obj.yi)\n', (18049, 18082), False, 'from ema_workbench.analysis import prim\n'), ((18495, 18513), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (18509, 18513), True, 'import numpy as np\n'), ((18696, 18726), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', '(10,)'], {}), '(0, 2, (10,))\n', (18713, 18726), True, 'import numpy as np\n'), ((18849, 18898), 'ema_workbench.analysis.prim.setup_prim', 'prim.setup_prim', (['results', 'classify'], {'threshold': '(0.8)'}), '(results, classify, threshold=0.8)\n', (18864, 18898), False, 'from ema_workbench.analysis import prim\n'), ((19043, 19073), 'numpy.where', 'np.where', (["(x.loc[:, 'b'] == 'a')"], {}), "(x.loc[:, 'b'] == 'a')\n", (19051, 19073), True, 'import numpy as np\n'), ((19094, 19130), 'ema_workbench.analysis.prim.PrimBox', 'prim.PrimBox', (['prim_obj', 'box_lims', 'yi'], {}), '(prim_obj, box_lims, yi)\n', (19106, 19130), False, 'from ema_workbench.analysis import prim\n'), ((1338, 1357), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (1346, 1357), True, 'import numpy as np\n'), ((1788, 1807), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (1796, 1807), True, 'import numpy as np\n'), ((2266, 2295), 'numpy.all', 'np.all', (['(box.yi == prim_obj.yi)'], {}), '(box.yi == prim_obj.yi)\n', (2272, 2295), True, 'import numpy as np\n'), ((4637, 4656), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (4645, 4656), True, 'import numpy as np\n'), ((5613, 5632), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (5621, 5632), True, 'import numpy as np\n'), ((8610, 8629), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (8618, 8629), True, 'import numpy as np\n'), ((8914, 8939), 'test.utilities.load_flu_data', 'utilities.load_flu_data', ([], {}), '()\n', (8937, 8939), False, 'from test import utilities\n'), ((10703, 10716), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (10712, 10716), True, 'import numpy as np\n'), ((14475, 14526), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)'], {'size': '(100,)', 'dtype': 'np.int'}), '(0, 10, size=(100,), dtype=np.int)\n', (14492, 14526), True, 'import numpy as np\n'), ((10742, 10770), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.9)'], {}), '(data, 0.9)\n', (10759, 10770), False, 'from ema_workbench.analysis import prim\n'), ((10801, 10830), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.95)'], {}), '(data, 0.95)\n', (10818, 10830), False, 'from ema_workbench.analysis import prim\n'), ((10861, 10889), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.1)'], {}), '(data, 0.1)\n', (10878, 10889), False, 'from ema_workbench.analysis import prim\n'), ((10920, 10949), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.05)'], {}), '(data, 0.05)\n', (10937, 10949), False, 'from ema_workbench.analysis import prim\n'), ((11017, 11045), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.9)'], {}), '(data, 0.9)\n', (11034, 11045), False, 'from ema_workbench.analysis import prim\n'), ((11074, 11103), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.95)'], {}), '(data, 0.95)\n', (11091, 11103), False, 'from ema_workbench.analysis import prim\n'), ((11132, 11160), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.1)'], {}), '(data, 0.1)\n', (11149, 11160), False, 'from ema_workbench.analysis import prim\n'), ((11189, 11218), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.05)'], {}), '(data, 0.05)\n', (11206, 11218), False, 'from ema_workbench.analysis import prim\n'), ((11306, 11334), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.9)'], {}), '(data, 0.9)\n', (11323, 11334), False, 'from ema_workbench.analysis import prim\n'), ((11365, 11394), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.95)'], {}), '(data, 0.95)\n', (11382, 11394), False, 'from ema_workbench.analysis import prim\n'), ((11425, 11453), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.1)'], {}), '(data, 0.1)\n', (11442, 11453), False, 'from ema_workbench.analysis import prim\n'), ((11484, 11513), 'ema_workbench.analysis.prim.get_quantile', 'prim.get_quantile', (['data', '(0.05)'], {}), '(data, 0.05)\n', (11501, 11513), False, 'from ema_workbench.analysis import prim\n'), ((16546, 16564), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (16560, 16564), True, 'import numpy as np\n'), ((17592, 17610), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (17606, 17610), True, 'import numpy as np\n')]
|
import sys, os, glob
import pandas as pd, numpy as np
import ujson
import datetime
from ast import literal_eval
from get_workflow_info import get_workflow_info, get_class_cols, translate_non_alphanumerics, get_short_slug
################################################################################
# Jailbreak question annotations from their JSON
# (will partially jailbreak markings etc, but not fully)
################################################################################
def breakout_anno_q(row, workflow_info):
# if you're doing this by iterating yourself and feeding it a row it needs
# to be row[1]['anno_json'] because row[0] is the row index
# but if you're calling this by a .apply(lambda ) it doesn't have that
# because obviously why would you want them to have the same syntax why why why
annotations = row['anno_json']
# I was trying this with numpy in hopes of saving time but that can lead to ordering problems
# just saving it here in case I ever change my mind
#
# theclass = np.empty(len(d_cols), dtype=object)
# the_cols = np.empty(len(d_cols), dtype=object)
#
# for thistask in annotations:
#
# the_cols[d_cols[workflow_info[thistask['task']+'_shorttext']]] = workflow_info[thistask['task']+'_shorttext']
#
# try:
# theclass[d_cols[workflow_info[thistask['task']+'_shorttext']]] = thistask['value']
# except:
# # in case numpy doesn't want to accept a dict for the drawing task?
# theclass[d_cols[workflow_info[thistask['task']+'_shorttext']]] = str(thistask['value'])
theclass = {}
for task in annotations:
try:
theclass[workflow_info[task['task']+'_shorttext']] = task['value']
except:
theclass[workflow_info[task['task']+'_shorttext']] = str(task['value'])
# if things are going very badly, uncomment these and pipe the output to a logfile
# print("------------------------------------------------------------")
# print(row)
# print(theclass)
# print(pd.Series(theclass))
# print("------------------------------------------------------------")
return pd.Series(theclass)
################################################################################
# Jailbreak survey annotations from their JSON
################################################################################
def breakout_anno_survey(row, workflow_info, fp, classcols, thecols):
annotations = row['anno_json']
#classcols = "classification_id created_at user_name user_id user_ip".split()
printcols = classcols + thecols
n_marks = 0
theclass = {}
# fill the row with the basic classification information
# theclass['classification_id'] = row.index
# for col in "created_at user_name user_id user_ip".split():
# theclass[col] = row[col]
# actually, let's assume we haven't set classification_id to be the index
for col in classcols:
theclass[col] = row[col]
# create all the other relevant columns
for col in thecols:
theclass[col] = ''
#print(workflow_info)
for task in annotations:
taskname = task['task']
tasktype = workflow_info[taskname]['type']
# for a survey we expect a survey task and a "shortcut" for e.g.
# "Nothing Here", and they require different approaches
# either way we'll write 1 row per mark to the file
if tasktype == "survey":
marks = task['value']
for mark in marks:
n_marks += 1
# empty the dict of marks
for col in thecols:
theclass[col] = ''
# fill in the dict
theclass[taskname.lower()+'_choice'] = mark['choice']
for ans in mark['answers'].keys():
thelabel = workflow_info[taskname]['questions'][ans]['label_slug']
#thelabel = get_short_slug(ans)
theclass[taskname.lower()+'_'+thelabel] = mark['answers'][ans]
# not currently doing anything with "filters"
# print the mark
write_class_row(fp, theclass, printcols)
elif tasktype == "shortcut":
n_marks += 1
# empty the dict of marks
for col in thecols:
theclass[col] = ''
# populate a default value for all the relevant columns
for ans in workflow_info[taskname]['answers']:
theclass[ans['label_slug']] = False
# now populate the ones we have actual info for
for ans_orig in task['value']:
# get the index in the workflow answer map so we can fetch
# the correct column label
i_a = workflow_info[taskname]['answer_map'][ans_orig]
ans = workflow_info[taskname]['answers'][i_a]['label_slug']
#ans = get_short_slug(ans_orig.lower())
theclass[ans] = True
# now write the row to the file
write_class_row(fp, theclass, printcols)
return n_marks
################################################################################
# Write a dictionary to a csv using columns and order in thecols
################################################################################
def write_class_row(fp, theclass, thecols):
# print the row
for i in range(len(thecols)):
entry = theclass[thecols[i]]
if not i == 0:
fp.write(",")
try:
if isinstance(entry, (list, tuple)):
fp.write('"%s"' % str(entry))
else:
fp.write(str(entry))
except:
pass
fp.write("\n")
return
################################################################################
# Compute a vote fraction
################################################################################
def getfrac(row, colname, colcount):
try:
return float(row[colname])/float(row[colcount])
except:
return 0.0
################################################################################
# Aggregate question vote fractions based on a dictionary of tasks
################################################################################
def aggregate_questions(classifications, theqdict, verbose=True):
by_subj = classifications.groupby(['subject_ids'])
subj_ans = by_subj['count'].aggregate('sum')
subj_ans.name = 'n_class_total'
# this should set up with the index==subject_ids and the column name we've just specified
class_counts = pd.DataFrame(subj_ans)
# .items() is python 3, .iteritems() is python 2
for t, q in theqdict.iteritems():
if verbose:
print("Aggregating task %s (%s)... %s" % (t, q, datetime.datetime.now().strftime('%H:%M:%S')))
colstem = t.lower()+'_'+q+'_'
answers = classifications[q].unique()
by_q_subj = classifications.groupby(['subject_ids', q])
q_subj_ans = by_q_subj['count'].aggregate('sum')
subj_anscounts_df = pd.DataFrame(q_subj_ans).unstack().fillna(0.0)
# the above ends up with multi-level column names, so let's fix that
newcolnames = []
fraccolnames = []
for namepair in subj_anscounts_df.columns:
# [0] should be 'count' because that's the column we summmed on
# [1] is the text of each answer
# let's make it label-friendly
thisans = (translate_non_alphanumerics(namepair[1], translate_to=u'')).replace('\n', '_').replace(' ', '_').replace('__', '_').replace('__', '_').lower()
# e.g. 't1_spiral_arms_attached_yes_count'
thisnewcol = colstem + thisans + '_count'
thisnewfrac = colstem + thisans + '_frac'
newcolnames.append(thisnewcol)
fraccolnames.append(thisnewfrac)
class_counts[thisnewcol] = np.zeros_like(class_counts.n_class_total)
subj_anscounts_df.columns = newcolnames
class_counts[newcolnames] = subj_anscounts_df
class_counts[colstem+'count'] = class_counts[newcolnames].apply(lambda row: sum(row), axis=1)
for i, thecol in enumerate(newcolnames):
thefraccol = fraccolnames[i]
class_counts[thefraccol] = class_counts.apply(lambda row: getfrac(row, thecol, colstem+'count'), axis=1)
# just some cleanup (replace NaNs with 0.0)
class_counts.fillna(0.0, inplace=True)
return class_counts
################################################################################
# Aggregate survey classifications based on a workflow definition dict
################################################################################
def aggregate_survey(grp, workflow_info):
#workflow_info = wf_info
# groupby() --> df because indexing etc is slightly different
subj = pd.DataFrame(grp)
# get the columns we'll be using based on the workflow info
class_cols = get_class_cols(workflow_info)
# initialize the dict that will hold the counts
theclass = {}
for col in class_cols:
theclass[col] = 0.0
# count the number of classifications for this subject
theclass['class_count'] = len(subj.classification_id.unique())
# now loop through tasks
for task in workflow_info['tasknames']:
# we will do something slightly different for the survey itself
# versus the "unlinked" task(s) e.g. "Nothing Here"
task_low = task.lower()
if workflow_info[task]['type'] == "survey":
# only deal with the choices we actually need for this subject
choicecol = "%s_choice" % task_low
choices = (subj[choicecol].unique()).tolist()
# ignore if there are empties, which read here as NaN
try:
choices.remove(np.nan)
except ValueError:
# if there aren't any NaNs in the list, carry on
pass
# make sure this task isn't empty
if (len(choices) > 0):
# get the questions we're working with
qcol = []
qmult = []
for i_q in range(len(workflow_info[task]['questionsOrder'])):
q = workflow_info[task]['questionsOrder'][i_q]
#qcol[i_q] = "%s_%s" % (task_low, workflow_info[task]['questions'][q]['label_slug'])
qcol.append(workflow_info[task]['questions'][q]['label_slug'])
qmult.append(workflow_info[task]['questions'][q]['multiple'])
for choice in choices:
# choice_slug will have the taskname prepended
choice_slug = workflow_info[task]['choices'][choice]['label_slug']
# only deal with the annotations that indicated this choice
this_choice = subj[subj[choicecol] == choice]
# count 'em up
choice_count = float(len(this_choice))
theclass["%s_count" % choice_slug] = choice_count
# now deal with the questions for each choice
for i_q in range(len(qcol)):
q = workflow_info[task]['questionsOrder'][i_q]
# the column we're saving to
class_slug = "%s_%s" % (choice_slug, qcol[i_q])
# the column we're reading from
col_slug = "%s_%s" % (task_low, workflow_info[task]['questions'][q]['label_slug'])
# if this question requires a single answer, this is relatively easy
if not qmult[i_q]:
theclass["%s_count" % class_slug] = float(len(this_choice[col_slug]))
by_ans = this_choice.groupby(col_slug)
theans = this_choice[col_slug].unique()
ans_count = by_ans['count'].aggregate('sum')
for a in ans_count.index:
a_str = a
if not isinstance(a, basestring):
a_str = str(int(a))
a_slug = workflow_info[task]['questions'][q]['answers'][a_str]['label_slug']
colname = "%s_%s_count" % (choice_slug, a_slug)
theclass[colname] = ans_count[a]
else:
# we need to deal with questions that can have multiple answers
# we stored them as a list, but stringified
try:
ans_list = [literal_eval(t) for t in this_choice[col_slug].values]
list_all = [item for sublist in ans_list for item in sublist]
except:
ans_list = [t for t in this_choice[col_slug].values]
list_all = ans_list
# this will flatten the list of lists
adf = pd.DataFrame(list_all)
adf.columns = ['ans']
adf['count'] = np.ones_like(list_all, dtype=int)
by_ans = adf.groupby('ans')
ans_count = by_ans['count'].aggregate('sum')
for a in ans_count.index:
a_str = a
if not isinstance(a, basestring):
a_str = str(int(a))
a_slug = workflow_info[task]['questions'][q]['answers'][a_str]['label_slug']
colname = "%s_%s_count" % (choice_slug, a_slug)
theclass[colname] = ans_count[a]
elif workflow_info[task]['type'] == "shortcut":
# what columns and possible answers are we working with here?
#answers = []
#anno_cols = []
for q in workflow_info[task]['answers']:
# the actual answer text
#answers.append(q['label'])
# the column name in the jailbroken annotations file
#anno_cols.append(q['label_slug'])
thecol = q['label_slug']
# the True values are already in there
x = subj[thecol].fillna(False)
thecount = float(sum(x))
theclass["%s_count" % thecol] = thecount
theclass["%s_frac" % thecol] = thecount/theclass['class_count']
return pd.Series(theclass)
#end
|
[
"pandas.DataFrame",
"numpy.zeros_like",
"get_workflow_info.get_class_cols",
"numpy.ones_like",
"get_workflow_info.translate_non_alphanumerics",
"pandas.Series",
"ast.literal_eval",
"datetime.datetime.now"
] |
[((2197, 2216), 'pandas.Series', 'pd.Series', (['theclass'], {}), '(theclass)\n', (2206, 2216), True, 'import pandas as pd, numpy as np\n'), ((6722, 6744), 'pandas.DataFrame', 'pd.DataFrame', (['subj_ans'], {}), '(subj_ans)\n', (6734, 6744), True, 'import pandas as pd, numpy as np\n'), ((9013, 9030), 'pandas.DataFrame', 'pd.DataFrame', (['grp'], {}), '(grp)\n', (9025, 9030), True, 'import pandas as pd, numpy as np\n'), ((9113, 9142), 'get_workflow_info.get_class_cols', 'get_class_cols', (['workflow_info'], {}), '(workflow_info)\n', (9127, 9142), False, 'from get_workflow_info import get_workflow_info, get_class_cols, translate_non_alphanumerics, get_short_slug\n'), ((14838, 14857), 'pandas.Series', 'pd.Series', (['theclass'], {}), '(theclass)\n', (14847, 14857), True, 'import pandas as pd, numpy as np\n'), ((8049, 8090), 'numpy.zeros_like', 'np.zeros_like', (['class_counts.n_class_total'], {}), '(class_counts.n_class_total)\n', (8062, 8090), True, 'import pandas as pd, numpy as np\n'), ((7199, 7223), 'pandas.DataFrame', 'pd.DataFrame', (['q_subj_ans'], {}), '(q_subj_ans)\n', (7211, 7223), True, 'import pandas as pd, numpy as np\n'), ((13304, 13326), 'pandas.DataFrame', 'pd.DataFrame', (['list_all'], {}), '(list_all)\n', (13316, 13326), True, 'import pandas as pd, numpy as np\n'), ((13420, 13453), 'numpy.ones_like', 'np.ones_like', (['list_all'], {'dtype': 'int'}), '(list_all, dtype=int)\n', (13432, 13453), True, 'import pandas as pd, numpy as np\n'), ((6917, 6940), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (6938, 6940), False, 'import datetime\n'), ((12881, 12896), 'ast.literal_eval', 'literal_eval', (['t'], {}), '(t)\n', (12893, 12896), False, 'from ast import literal_eval\n'), ((7613, 7671), 'get_workflow_info.translate_non_alphanumerics', 'translate_non_alphanumerics', (['namepair[1]'], {'translate_to': 'u""""""'}), "(namepair[1], translate_to=u'')\n", (7640, 7671), False, 'from get_workflow_info import get_workflow_info, get_class_cols, translate_non_alphanumerics, get_short_slug\n')]
|
# Copyright 2021 Google LLC
#
# 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.
"""Unitests for automatic variable tracing."""
import unittest
import numpy as np
import jax.numpy as jn
import objax
from objax.zoo.dnnet import DNNet
global_w = objax.TrainVar(jn.zeros(5))
global_b = objax.TrainVar(jn.zeros(1))
global_m = objax.nn.Sequential([objax.nn.Conv2D(2, 4, 3), objax.nn.BatchNorm2D(4)])
class TestTracing(unittest.TestCase):
"""Unit tests for variable tracing using."""
def test_function_global_vars(self):
def loss(x, y):
pred = jn.dot(x, global_w.value) + global_b.value
return 0.5 * ((y - pred) ** 2).mean()
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, {'global_w': global_w, 'global_b': global_b})
def test_function_global_module(self):
def loss(x):
return jn.sum(global_m(x, training=True))
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, global_m.vars(scope='global_m.'))
def test_function_closure_vars(self):
w = objax.TrainVar(jn.zeros(5))
b = objax.TrainVar(jn.zeros(1))
def loss(x, y):
pred = jn.dot(x, w.value) + b.value
return 0.5 * ((y - pred) ** 2).mean()
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, {'w': w, 'b': b})
def test_function_closure_module(self):
m = objax.nn.Sequential([objax.nn.Conv2D(1, 2, 3), objax.nn.BatchNorm2D(2)])
def loss(x):
return jn.sum(m(x, training=True))
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, m.vars(scope='m.'))
def test_lambda_with_closure_vars(self):
w = objax.TrainVar(jn.zeros(5))
b = objax.TrainVar(jn.zeros(1))
loss = lambda x, y: 0.5 * ((y - jn.dot(x, w.value) + b.value) ** 2).mean()
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, {'w': w, 'b': b})
def test_multiline_lambda_with_closure_vars(self):
w = objax.TrainVar(jn.zeros(5))
b = objax.TrainVar(jn.zeros(1))
loss = lambda x, y: (
0.5 * ((y - jn.dot(x, w.value) + b.value) ** 2).mean()
)
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, {'w': w, 'b': b})
def test_closure_overrides_global_vars(self):
# Make sure that global variables are what we expect them to be
np.testing.assert_allclose(global_w.value, np.zeros(5))
np.testing.assert_allclose(global_b.value, np.zeros(1))
def _do_test():
# define local variable with the same name as existing global
global_w = objax.TrainVar(jn.ones(10))
# verify that global_w and global_b are what we expect them to be
np.testing.assert_allclose(global_w.value, np.ones(10))
np.testing.assert_allclose(global_b.value, np.zeros(1))
# loss function which mixes closure vars, global vars and closure var hides global var
def loss(x, y):
pred = jn.dot(x, global_w.value) + global_b.value
return 0.5 * ((y - pred) ** 2).mean()
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, {'global_w': global_w, 'global_b': global_b})
_do_test()
# Make sure that global variables didn't change, in other words
# that _do_test operated on local variables
np.testing.assert_allclose(global_w.value, np.zeros(5))
np.testing.assert_allclose(global_b.value, np.zeros(1))
def test_typical_training_loop(self):
# Define model and optimizer
model = DNNet((32, 10), objax.functional.leaky_relu)
opt = objax.optimizer.Momentum(model.vars(), nesterov=True)
# Predict op
predict_op = lambda x: objax.functional.softmax(model(x, training=False))
self.assertDictEqual(objax.util.find_used_variables(predict_op),
model.vars(scope='model.'))
# Loss function
def loss(x, label):
logit = model(x, training=True)
xe_loss = objax.functional.loss.cross_entropy_logits_sparse(logit, label).mean()
return xe_loss
self.assertDictEqual(objax.util.find_used_variables(loss),
model.vars(scope='model.'))
# Gradients and loss function
loss_gv = objax.GradValues(loss, objax.util.find_used_variables(loss))
def train_op(x, y, learning_rate):
grads, loss = loss_gv(x, y)
opt(learning_rate, grads)
return loss
self.assertDictEqual(objax.util.find_used_variables(train_op),
{**model.vars(scope='loss_gv.model.'), **opt.vars(scope='opt.')})
def test_lambda_inside_function(self):
m = objax.nn.Sequential([objax.nn.Conv2D(1, 2, 3), objax.nn.BatchNorm2D(2)])
def loss(x):
get_logits = lambda inp: m(inp, training=True)
return jn.sum(get_logits(x))
vc = objax.util.find_used_variables(loss)
self.assertDictEqual(vc, m.vars(scope='m.'))
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"jax.numpy.dot",
"objax.zoo.dnnet.DNNet",
"numpy.zeros",
"numpy.ones",
"objax.nn.Conv2D",
"objax.nn.BatchNorm2D",
"jax.numpy.ones",
"jax.numpy.zeros",
"objax.functional.loss.cross_entropy_logits_sparse",
"objax.util.find_used_variables"
] |
[((758, 769), 'jax.numpy.zeros', 'jn.zeros', (['(5)'], {}), '(5)\n', (766, 769), True, 'import jax.numpy as jn\n'), ((797, 808), 'jax.numpy.zeros', 'jn.zeros', (['(1)'], {}), '(1)\n', (805, 808), True, 'import jax.numpy as jn\n'), ((5718, 5733), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5731, 5733), False, 'import unittest\n'), ((843, 867), 'objax.nn.Conv2D', 'objax.nn.Conv2D', (['(2)', '(4)', '(3)'], {}), '(2, 4, 3)\n', (858, 867), False, 'import objax\n'), ((869, 892), 'objax.nn.BatchNorm2D', 'objax.nn.BatchNorm2D', (['(4)'], {}), '(4)\n', (889, 892), False, 'import objax\n'), ((1176, 1212), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (1206, 1212), False, 'import objax\n'), ((1425, 1461), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (1455, 1461), False, 'import objax\n'), ((1789, 1825), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (1819, 1825), False, 'import objax\n'), ((2090, 2126), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (2120, 2126), False, 'import objax\n'), ((2404, 2440), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (2434, 2440), False, 'import objax\n'), ((2750, 2786), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (2780, 2786), False, 'import objax\n'), ((4209, 4253), 'objax.zoo.dnnet.DNNet', 'DNNet', (['(32, 10)', 'objax.functional.leaky_relu'], {}), '((32, 10), objax.functional.leaky_relu)\n', (4214, 4253), False, 'from objax.zoo.dnnet import DNNet\n'), ((5595, 5631), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (5625, 5631), False, 'import objax\n'), ((1599, 1610), 'jax.numpy.zeros', 'jn.zeros', (['(5)'], {}), '(5)\n', (1607, 1610), True, 'import jax.numpy as jn\n'), ((1639, 1650), 'jax.numpy.zeros', 'jn.zeros', (['(1)'], {}), '(1)\n', (1647, 1650), True, 'import jax.numpy as jn\n'), ((2253, 2264), 'jax.numpy.zeros', 'jn.zeros', (['(5)'], {}), '(5)\n', (2261, 2264), True, 'import jax.numpy as jn\n'), ((2293, 2304), 'jax.numpy.zeros', 'jn.zeros', (['(1)'], {}), '(1)\n', (2301, 2304), True, 'import jax.numpy as jn\n'), ((2575, 2586), 'jax.numpy.zeros', 'jn.zeros', (['(5)'], {}), '(5)\n', (2583, 2586), True, 'import jax.numpy as jn\n'), ((2615, 2626), 'jax.numpy.zeros', 'jn.zeros', (['(1)'], {}), '(1)\n', (2623, 2626), True, 'import jax.numpy as jn\n'), ((3012, 3023), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (3020, 3023), True, 'import numpy as np\n'), ((3076, 3087), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (3084, 3087), True, 'import numpy as np\n'), ((3720, 3756), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (3750, 3756), False, 'import objax\n'), ((4036, 4047), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (4044, 4047), True, 'import numpy as np\n'), ((4100, 4111), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (4108, 4111), True, 'import numpy as np\n'), ((4456, 4498), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['predict_op'], {}), '(predict_op)\n', (4486, 4498), False, 'import objax\n'), ((4804, 4840), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (4834, 4840), False, 'import objax\n'), ((4979, 5015), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['loss'], {}), '(loss)\n', (5009, 5015), False, 'import objax\n'), ((5193, 5233), 'objax.util.find_used_variables', 'objax.util.find_used_variables', (['train_op'], {}), '(train_op)\n', (5223, 5233), False, 'import objax\n'), ((1069, 1094), 'jax.numpy.dot', 'jn.dot', (['x', 'global_w.value'], {}), '(x, global_w.value)\n', (1075, 1094), True, 'import jax.numpy as jn\n'), ((1696, 1714), 'jax.numpy.dot', 'jn.dot', (['x', 'w.value'], {}), '(x, w.value)\n', (1702, 1714), True, 'import jax.numpy as jn\n'), ((1955, 1979), 'objax.nn.Conv2D', 'objax.nn.Conv2D', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1970, 1979), False, 'import objax\n'), ((1981, 2004), 'objax.nn.BatchNorm2D', 'objax.nn.BatchNorm2D', (['(2)'], {}), '(2)\n', (2001, 2004), False, 'import objax\n'), ((3226, 3237), 'jax.numpy.ones', 'jn.ones', (['(10)'], {}), '(10)\n', (3233, 3237), True, 'import jax.numpy as jn\n'), ((3373, 3384), 'numpy.ones', 'np.ones', (['(10)'], {}), '(10)\n', (3380, 3384), True, 'import numpy as np\n'), ((3441, 3452), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (3449, 3452), True, 'import numpy as np\n'), ((5407, 5431), 'objax.nn.Conv2D', 'objax.nn.Conv2D', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (5422, 5431), False, 'import objax\n'), ((5433, 5456), 'objax.nn.BatchNorm2D', 'objax.nn.BatchNorm2D', (['(2)'], {}), '(2)\n', (5453, 5456), False, 'import objax\n'), ((3605, 3630), 'jax.numpy.dot', 'jn.dot', (['x', 'global_w.value'], {}), '(x, global_w.value)\n', (3611, 3630), True, 'import jax.numpy as jn\n'), ((4676, 4739), 'objax.functional.loss.cross_entropy_logits_sparse', 'objax.functional.loss.cross_entropy_logits_sparse', (['logit', 'label'], {}), '(logit, label)\n', (4725, 4739), False, 'import objax\n'), ((2347, 2365), 'jax.numpy.dot', 'jn.dot', (['x', 'w.value'], {}), '(x, w.value)\n', (2353, 2365), True, 'import jax.numpy as jn\n'), ((2683, 2701), 'jax.numpy.dot', 'jn.dot', (['x', 'w.value'], {}), '(x, w.value)\n', (2689, 2701), True, 'import jax.numpy as jn\n')]
|
import numpy as np
from ..testing_utils import DummyConverter, DummyLoad, DummyNoise, DummyOdeSolver, DummyVoltageSupply, DummyElectricMotor,\
mock_instantiate, instantiate_dict
from gym_electric_motor.physical_systems import physical_systems as ps, converters as cv, electric_motors as em,\
mechanical_loads as ml, voltage_supplies as vs, solvers as sv
from gym.spaces import Box
import pytest
class TestSCMLSystem:
"""
Base Class to test all PhysicalSystems that derive from SCMLSystem
"""
class_to_test = ps.SCMLSystem
def mock_build_state(self, motor_state, torque, u_in, u_sup):
"""Function to mock an arbitrary build_state function to test the SCMLSystem
"""
self.motor_state = motor_state
self.torque = torque
self.u_in = u_in
self.u_sup = u_sup
return np.concatenate((
self.motor_state[:len(DummyLoad.state_names)], [torque],
self.motor_state[len(DummyLoad.state_names):], [u_sup]
))
@pytest.fixture
def scml_system(self, monkeypatch):
"""
Returns an instantiated SCMLSystem with Dummy Components and mocked abstract functions
"""
monkeypatch.setattr(
self.class_to_test,
'_build_state_names',
lambda _:
DummyLoad.state_names + ['torque'] + DummyElectricMotor.CURRENTS + DummyElectricMotor.VOLTAGES + ['u_sup']
)
monkeypatch.setattr(
self.class_to_test,
'_build_state_space',
lambda _, state_names: Box(
low=np.zeros_like(state_names, dtype=float),
high=np.zeros_like(state_names, dtype=float)
)
)
return self.class_to_test(
converter=DummyConverter(),
motor=DummyElectricMotor(),
load=DummyLoad(),
supply=DummyVoltageSupply(),
ode_solver=DummyOdeSolver(),
noise_generator=DummyNoise()
)
def test_reset(self, scml_system):
"""Test the reset function in the physical system"""
scml_system._t = 12
scml_system._k = 33
state_space = scml_system.state_space
state_positions = scml_system.state_positions
initial_state = scml_system.reset()
target = (np.array([0, 0, 0, 0, 0, 0, 560]) + scml_system._noise_generator.reset()) / scml_system.limits
assert np.all(initial_state == target), 'Initial states of the system are incorrect'
assert scml_system._t == 0, 'Time of the system was not set to zero after reset'
assert scml_system._k == 0, 'Episode step of the system was not set to zero after reset'
assert scml_system.converter.reset_counter == scml_system.electrical_motor.reset_counter \
== scml_system.mechanical_load.reset_counter == scml_system.supply.reset_counter,\
'The reset was not passed to all components of the SCMLSystem'
assert scml_system._ode_solver.t == 0, 'The ode solver was not reset correctly'
assert all(scml_system._ode_solver.y == np.zeros_like(
scml_system.mechanical_load.state_names + scml_system.electrical_motor.CURRENTS, dtype=float
)), ' The ode solver was not reset correctly'
def test_system_equation(self, scml_system):
"""Tests the system equation function"""
state = np.random.rand(4)
currents = state[[2, 3]]
torque = scml_system.electrical_motor.torque(currents)
u_in = np.random.rand(2)
t = np.random.rand()
derivative = scml_system._system_equation(t, state, u_in)
assert all(
derivative == np.array([torque, -torque, currents[0] - u_in[0], currents[1] - u_in[1]])
), 'The system equation return differs from the expected'
assert scml_system.mechanical_load.t == t, 'The time t was not passed through to the mech. load equation'
assert np.all(scml_system.mechanical_load.mechanical_state == state[:2]),\
'The mech. state was not returned correctly'
def test_simulate(self, scml_system):
"""Test the simulation function of the SCMLSystem"""
# Reset the system and take a random action
scml_system.reset()
action = scml_system.action_space.sample()
# Set a defined intitial state
ode_state = np.array([3, 4, 5, 6])
scml_system._ode_solver.set_initial_value(ode_state)
# Perform the action on the system
next_state = scml_system.simulate(action)
solver_state_me = scml_system._ode_solver.y[:len(DummyLoad.state_names)]
solver_state_el = scml_system._ode_solver.y[len(DummyLoad.state_names):]
torque = [scml_system.electrical_motor.torque(solver_state_el)]
u_sup = [scml_system.supply.u_nominal]
u_in = [u * u_sup[0] for u in scml_system.converter.u_in]
# Calculate the next state
desired_next_state = (
np.concatenate((solver_state_me, torque, solver_state_el, u_in, u_sup))
+ scml_system._noise_generator.noise()
) / scml_system.limits
# Assertions for correct simulation
assert all(desired_next_state == next_state), 'The calculated next state differs from the expected one'
assert scml_system.converter.action == action, 'The action was not passed correctly to the converter'
assert scml_system.converter.action_set_time == 0, 'The action start time was passed incorrect to the converter'
assert scml_system.converter.last_i_out == scml_system.electrical_motor.i_in(scml_system._ode_solver.last_y[2:])
def test_system_jacobian(self, scml_system):
"""Tests for the system jacobian function"""
el_jac = np.arange(4).reshape(2, 2)
el_over_omega = np.arange(4, 6)
torque_over_el = np.arange(6, 8)
# Set the el. jacobian returns to specified values
scml_system.electrical_motor.electrical_jac_return = (el_jac, el_over_omega, torque_over_el)
me_jac = np.arange(8, 12).reshape(2, 2)
me_over_torque = np.arange(12, 14)
# Set the mech. jabobian returns to specified values
scml_system.mechanical_load.mechanical_jac_return = me_jac, me_over_torque
sys_jac = scml_system._system_jacobian(0, np.array([0, 1, 2, 3]), [0, -1])
#
assert np.all(sys_jac[-2:, -2:] == el_jac), 'The el. jacobian is false'
assert np.all(sys_jac[:2, :2] == me_jac), 'The mech. jacobian is false'
assert np.all(sys_jac[2:, 0] == el_over_omega), 'the derivative of the el.state over omega is false'
assert np.all(sys_jac[2:, 1] == np.zeros(2))
assert np.all(sys_jac[:-2, 2:] == np.array([[72, 84], [78, 91]])), 'The derivative of the mech.state ' \
'over the currents is false'
|
[
"numpy.zeros_like",
"numpy.concatenate",
"numpy.zeros",
"numpy.array",
"numpy.arange",
"numpy.random.rand",
"numpy.all"
] |
[((2433, 2464), 'numpy.all', 'np.all', (['(initial_state == target)'], {}), '(initial_state == target)\n', (2439, 2464), True, 'import numpy as np\n'), ((3391, 3408), 'numpy.random.rand', 'np.random.rand', (['(4)'], {}), '(4)\n', (3405, 3408), True, 'import numpy as np\n'), ((3520, 3537), 'numpy.random.rand', 'np.random.rand', (['(2)'], {}), '(2)\n', (3534, 3537), True, 'import numpy as np\n'), ((3550, 3566), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3564, 3566), True, 'import numpy as np\n'), ((3948, 4013), 'numpy.all', 'np.all', (['(scml_system.mechanical_load.mechanical_state == state[:2])'], {}), '(scml_system.mechanical_load.mechanical_state == state[:2])\n', (3954, 4013), True, 'import numpy as np\n'), ((4368, 4390), 'numpy.array', 'np.array', (['[3, 4, 5, 6]'], {}), '([3, 4, 5, 6])\n', (4376, 4390), True, 'import numpy as np\n'), ((5805, 5820), 'numpy.arange', 'np.arange', (['(4)', '(6)'], {}), '(4, 6)\n', (5814, 5820), True, 'import numpy as np\n'), ((5846, 5861), 'numpy.arange', 'np.arange', (['(6)', '(8)'], {}), '(6, 8)\n', (5855, 5861), True, 'import numpy as np\n'), ((6095, 6112), 'numpy.arange', 'np.arange', (['(12)', '(14)'], {}), '(12, 14)\n', (6104, 6112), True, 'import numpy as np\n'), ((6366, 6401), 'numpy.all', 'np.all', (['(sys_jac[-2:, -2:] == el_jac)'], {}), '(sys_jac[-2:, -2:] == el_jac)\n', (6372, 6401), True, 'import numpy as np\n'), ((6446, 6479), 'numpy.all', 'np.all', (['(sys_jac[:2, :2] == me_jac)'], {}), '(sys_jac[:2, :2] == me_jac)\n', (6452, 6479), True, 'import numpy as np\n'), ((6526, 6565), 'numpy.all', 'np.all', (['(sys_jac[2:, 0] == el_over_omega)'], {}), '(sys_jac[2:, 0] == el_over_omega)\n', (6532, 6565), True, 'import numpy as np\n'), ((6307, 6329), 'numpy.array', 'np.array', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (6315, 6329), True, 'import numpy as np\n'), ((2323, 2356), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0, 560]'], {}), '([0, 0, 0, 0, 0, 0, 560])\n', (2331, 2356), True, 'import numpy as np\n'), ((3102, 3214), 'numpy.zeros_like', 'np.zeros_like', (['(scml_system.mechanical_load.state_names + scml_system.electrical_motor.\n CURRENTS)'], {'dtype': 'float'}), '(scml_system.mechanical_load.state_names + scml_system.\n electrical_motor.CURRENTS, dtype=float)\n', (3115, 3214), True, 'import numpy as np\n'), ((3679, 3752), 'numpy.array', 'np.array', (['[torque, -torque, currents[0] - u_in[0], currents[1] - u_in[1]]'], {}), '([torque, -torque, currents[0] - u_in[0], currents[1] - u_in[1]])\n', (3687, 3752), True, 'import numpy as np\n'), ((4970, 5041), 'numpy.concatenate', 'np.concatenate', (['(solver_state_me, torque, solver_state_el, u_in, u_sup)'], {}), '((solver_state_me, torque, solver_state_el, u_in, u_sup))\n', (4984, 5041), True, 'import numpy as np\n'), ((5754, 5766), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (5763, 5766), True, 'import numpy as np\n'), ((6039, 6055), 'numpy.arange', 'np.arange', (['(8)', '(12)'], {}), '(8, 12)\n', (6048, 6055), True, 'import numpy as np\n'), ((6660, 6671), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (6668, 6671), True, 'import numpy as np\n'), ((6715, 6745), 'numpy.array', 'np.array', (['[[72, 84], [78, 91]]'], {}), '([[72, 84], [78, 91]])\n', (6723, 6745), True, 'import numpy as np\n'), ((1600, 1639), 'numpy.zeros_like', 'np.zeros_like', (['state_names'], {'dtype': 'float'}), '(state_names, dtype=float)\n', (1613, 1639), True, 'import numpy as np\n'), ((1662, 1701), 'numpy.zeros_like', 'np.zeros_like', (['state_names'], {'dtype': 'float'}), '(state_names, dtype=float)\n', (1675, 1701), True, 'import numpy as np\n')]
|
#coding=utf-8
'''
Created on 2016年9月27日
@author: dengdan
'''
import numpy as np
import time
import random
rng = np.random.RandomState(int(time.time()))
rand = np.random.rand
"""
Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)
"""
def normal(shape, mu = 0, sigma_square = 1, dtype = np.float32):
tensor = rng.normal(mu, np.sqrt(sigma_square), shape)
return np.array(tensor, dtype = dtype)
def randint(low = 2 ** 30, high = None, shape = None):
"""
low: the higher bound except when high is not None.
high: when it is not none, low must be smaller than it
shape: if not provided, a scalar will be returned
"""
return rng.randint(low = low, high = high, size = shape)
def shuffle(lst):
random.shuffle(lst)
def sample(lst, n):
return random.sample(lst, n)
def prob(allow_zero = True):
"""
Generate a random value as probability
"""
return rand_val(low = 0, high = 1.0, allow_zero = allow_zero)
def rand_val(low = 0, high = 1.0, allow_zero = True, range = None):
if range is not None:
low = range[0]
high = range[1]
val = rng.uniform(low = low, high = high)
if not allow_zero:
while not val:
val = rng.uniform(low = low, high = high)
return val
|
[
"random.sample",
"random.shuffle",
"time.time",
"numpy.array",
"numpy.sqrt"
] |
[((433, 462), 'numpy.array', 'np.array', (['tensor'], {'dtype': 'dtype'}), '(tensor, dtype=dtype)\n', (441, 462), True, 'import numpy as np\n'), ((799, 818), 'random.shuffle', 'random.shuffle', (['lst'], {}), '(lst)\n', (813, 818), False, 'import random\n'), ((851, 872), 'random.sample', 'random.sample', (['lst', 'n'], {}), '(lst, n)\n', (864, 872), False, 'import random\n'), ((140, 151), 'time.time', 'time.time', ([], {}), '()\n', (149, 151), False, 'import time\n'), ((392, 413), 'numpy.sqrt', 'np.sqrt', (['sigma_square'], {}), '(sigma_square)\n', (399, 413), True, 'import numpy as np\n')]
|
# Import the libraries we need for this lab
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from torch.utils.data import Dataset, DataLoader
# Plot the data
def plot_decision_regions_2class(model,data_set):
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#00AAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#00AAFF'])
X = data_set.x.numpy()
y = data_set.y.numpy()
h = .02
x_min, x_max = X[:, 0].min() - 0.1 , X[:, 0].max() + 0.1
y_min, y_max = X[:, 1].min() - 0.1 , X[:, 1].max() + 0.1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),np.arange(y_min, y_max, h))
XX = torch.Tensor(np.c_[xx.ravel(), yy.ravel()])
yhat = np.logical_not((model(XX)[:, 0] > 0.5).numpy()).reshape(xx.shape)
plt.pcolormesh(xx, yy, yhat, cmap=cmap_light)
plt.plot(X[y[:, 0] == 0, 0], X[y[:, 0] == 0, 1], 'o', label='y=0')
plt.plot(X[y[:, 0] == 1, 0], X[y[:, 0] == 1, 1], 'ro', label='y=1')
plt.title("decision region")
plt.legend()
# Calculate the accuracy
def accuracy(model, data_set):
return np.mean(data_set.y.view(-1).numpy() == (model(data_set.x)[:, 0] > 0.5).numpy())
# Define the class Net with one hidden layer
class Net(nn.Module):
# Constructor
def __init__(self, D_in, H, D_out):
super(Net, self).__init__()
# hidden layer
self.linear1 = nn.Linear(D_in, H)
# output layer
self.linear2 = nn.Linear(H, D_out)
# Prediction
def forward(self, x):
x = torch.sigmoid(self.linear1(x))
x = torch.sigmoid(self.linear2(x))
return x
# Define the train model
def train(data_set, model, criterion, train_loader, optimizer, epochs=5):
COST = []
ACC = []
for epoch in range(epochs):
total = 0
for x, y in train_loader:
optimizer.zero_grad()
yhat = model(x)
loss = criterion(yhat, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# cumulative loss
total += loss.item()
ACC.append(accuracy(model, data_set))
COST.append(total)
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.plot(COST, color=color)
ax1.set_xlabel('epoch', color=color)
ax1.set_ylabel('total loss', color=color)
ax1.tick_params(axis='y', color=color)
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('accuracy', color=color) # we already handled the x-label with ax1
ax2.plot(ACC, color=color)
ax2.tick_params(axis='y', color=color)
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.show()
return COST
# Define the class XOR_Data
class XOR_Data(Dataset):
# Constructor
def __init__(self, N_s=100):
self.x = torch.zeros((N_s, 2))
self.y = torch.zeros((N_s, 1))
for i in range(N_s // 4):
self.x[i, :] = torch.Tensor([0.0, 0.0])
self.y[i, 0] = torch.Tensor([0.0])
self.x[i + N_s // 4, :] = torch.Tensor([0.0, 1.0])
self.y[i + N_s // 4, 0] = torch.Tensor([1.0])
self.x[i + N_s // 2, :] = torch.Tensor([1.0, 0.0])
self.y[i + N_s // 2, 0] = torch.Tensor([1.0])
self.x[i + 3 * N_s // 4, :] = torch.Tensor([1.0, 1.0])
self.y[i + 3 * N_s // 4, 0] = torch.Tensor([0.0])
self.x = self.x + 0.01 * torch.randn((N_s, 2))
self.len = N_s
# Getter
def __getitem__(self, index):
return self.x[index], self.y[index]
# Get Length
def __len__(self):
return self.len
# Plot the data
def plot_stuff(self):
plt.plot(self.x[self.y[:, 0] == 0, 0].numpy(), self.x[self.y[:, 0] == 0, 1].numpy(), 'o', label="y=0")
plt.plot(self.x[self.y[:, 0] == 1, 0].numpy(), self.x[self.y[:, 0] == 1, 1].numpy(), 'ro', label="y=1")
plt.legend()
# Create dataset object
data_set = XOR_Data()
data_set.plot_stuff()
# Train the model
learning_rate = 0.001
criterion = nn.BCELoss()
#optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
train_loader = DataLoader(dataset=data_set, batch_size=1)
#LOSS12 = train(data_set, model, criterion, train_loader, optimizer, epochs=500)
#plot_decision_regions_2class(model, data_set)
# Train the model
learning_rate = 0.1
criterion = nn.BCELoss()
#optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
train_loader = DataLoader(dataset=data_set, batch_size=1)
#LOSS12 = train(data_set, model, criterion, train_loader, optimizer, epochs=500)
#plot_decision_regions_2class(model, data_set)
# Practice: create a model with two neuron
model = Net(2, 4, 1)
# Type your code here
# Train the model
learning_rate = 0.1
criterion = nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
train_loader = DataLoader(dataset=data_set, batch_size=1)
LOSS12 = train(data_set, model, criterion, train_loader, optimizer, epochs=500)
plot_decision_regions_2class(model, data_set)
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"torch.nn.BCELoss",
"matplotlib.pyplot.plot",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.legend",
"torch.randn",
"matplotlib.pyplot.subplots",
"torch.Tensor",
"numpy.arange",
"matplotlib.pyplot.pcolormesh",
"torch.nn.Linear",
"torch.zeros",
"matplotlib.colors.ListedColormap"
] |
[((4111, 4123), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (4121, 4123), True, 'import torch.nn as nn\n'), ((4206, 4248), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'data_set', 'batch_size': '(1)'}), '(dataset=data_set, batch_size=1)\n', (4216, 4248), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4429, 4441), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (4439, 4441), True, 'import torch.nn as nn\n'), ((4524, 4566), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'data_set', 'batch_size': '(1)'}), '(dataset=data_set, batch_size=1)\n', (4534, 4566), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4834, 4846), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (4844, 4846), True, 'import torch.nn as nn\n'), ((4928, 4970), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'data_set', 'batch_size': '(1)'}), '(dataset=data_set, batch_size=1)\n', (4938, 4970), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((344, 393), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["['#FFAAAA', '#AAFFAA', '#00AAFF']"], {}), "(['#FFAAAA', '#AAFFAA', '#00AAFF'])\n", (358, 393), False, 'from matplotlib.colors import ListedColormap\n'), ((410, 459), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["['#FF0000', '#00FF00', '#00AAFF']"], {}), "(['#FF0000', '#00FF00', '#00AAFF'])\n", (424, 459), False, 'from matplotlib.colors import ListedColormap\n'), ((863, 908), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['xx', 'yy', 'yhat'], {'cmap': 'cmap_light'}), '(xx, yy, yhat, cmap=cmap_light)\n', (877, 908), True, 'import matplotlib.pyplot as plt\n'), ((913, 979), 'matplotlib.pyplot.plot', 'plt.plot', (['X[y[:, 0] == 0, 0]', 'X[y[:, 0] == 0, 1]', '"""o"""'], {'label': '"""y=0"""'}), "(X[y[:, 0] == 0, 0], X[y[:, 0] == 0, 1], 'o', label='y=0')\n", (921, 979), True, 'import matplotlib.pyplot as plt\n'), ((984, 1051), 'matplotlib.pyplot.plot', 'plt.plot', (['X[y[:, 0] == 1, 0]', 'X[y[:, 0] == 1, 1]', '"""ro"""'], {'label': '"""y=1"""'}), "(X[y[:, 0] == 1, 0], X[y[:, 0] == 1, 1], 'ro', label='y=1')\n", (992, 1051), True, 'import matplotlib.pyplot as plt\n'), ((1056, 1084), 'matplotlib.pyplot.title', 'plt.title', (['"""decision region"""'], {}), "('decision region')\n", (1065, 1084), True, 'import matplotlib.pyplot as plt\n'), ((1089, 1101), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1099, 1101), True, 'import matplotlib.pyplot as plt\n'), ((2250, 2264), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2262, 2264), True, 'import matplotlib.pyplot as plt\n'), ((2735, 2745), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2743, 2745), True, 'import matplotlib.pyplot as plt\n'), ((673, 699), 'numpy.arange', 'np.arange', (['x_min', 'x_max', 'h'], {}), '(x_min, x_max, h)\n', (682, 699), True, 'import numpy as np\n'), ((700, 726), 'numpy.arange', 'np.arange', (['y_min', 'y_max', 'h'], {}), '(y_min, y_max, h)\n', (709, 726), True, 'import numpy as np\n'), ((1462, 1480), 'torch.nn.Linear', 'nn.Linear', (['D_in', 'H'], {}), '(D_in, H)\n', (1471, 1480), True, 'import torch.nn as nn\n'), ((1527, 1546), 'torch.nn.Linear', 'nn.Linear', (['H', 'D_out'], {}), '(H, D_out)\n', (1536, 1546), True, 'import torch.nn as nn\n'), ((2888, 2909), 'torch.zeros', 'torch.zeros', (['(N_s, 2)'], {}), '((N_s, 2))\n', (2899, 2909), False, 'import torch\n'), ((2927, 2948), 'torch.zeros', 'torch.zeros', (['(N_s, 1)'], {}), '((N_s, 1))\n', (2938, 2948), False, 'import torch\n'), ((3974, 3986), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3984, 3986), True, 'import matplotlib.pyplot as plt\n'), ((3010, 3034), 'torch.Tensor', 'torch.Tensor', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (3022, 3034), False, 'import torch\n'), ((3062, 3081), 'torch.Tensor', 'torch.Tensor', (['[0.0]'], {}), '([0.0])\n', (3074, 3081), False, 'import torch\n'), ((3121, 3145), 'torch.Tensor', 'torch.Tensor', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (3133, 3145), False, 'import torch\n'), ((3184, 3203), 'torch.Tensor', 'torch.Tensor', (['[1.0]'], {}), '([1.0])\n', (3196, 3203), False, 'import torch\n'), ((3243, 3267), 'torch.Tensor', 'torch.Tensor', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (3255, 3267), False, 'import torch\n'), ((3306, 3325), 'torch.Tensor', 'torch.Tensor', (['[1.0]'], {}), '([1.0])\n', (3318, 3325), False, 'import torch\n'), ((3369, 3393), 'torch.Tensor', 'torch.Tensor', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (3381, 3393), False, 'import torch\n'), ((3436, 3455), 'torch.Tensor', 'torch.Tensor', (['[0.0]'], {}), '([0.0])\n', (3448, 3455), False, 'import torch\n'), ((3494, 3515), 'torch.randn', 'torch.randn', (['(N_s, 2)'], {}), '((N_s, 2))\n', (3505, 3515), False, 'import torch\n')]
|
import os
import sys
os.environ["OMP_NUM_THREADS"] = "1"
import tensorflow as tf
import numpy as np
import time
n = 8192
dtype = tf.float32
with tf.device("/gpu:0"):
matrix1 = tf.Variable(tf.ones((n, n), dtype=dtype))
matrix2 = tf.Variable(tf.ones((n, n), dtype=dtype))
product = tf.matmul(matrix1, matrix2)
# avoid optimizing away redundant nodes
config = tf.ConfigProto(graph_options=tf.GraphOptions(optimizer_options=tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)))
sess = tf.Session(config=config)
sess.run(tf.global_variables_initializer())
iters = 10
# pre-warming
sess.run(product.op)
start = time.time()
for i in range(iters):
sess.run(product.op)
end = time.time()
ops = n**3 + (n-1)*n**2 # n^2*(n-1) additions, n^3 multiplications
elapsed = (end - start)
rate = iters*ops/elapsed/10**9
print('\nGPU: %d x %d matmul took: %.2f sec, %.2f G ops/sec' % (n, n, elapsed/iters,rate,))
matrix1 = np.ones((n,n))
matrix2 = np.ones((n,n))
start = time.time()
for i in range(iters):
np.matmul(matrix1,matrix2)
end = time.time()
ops = n**3 + (n-1)*n**2 # n^2*(n-1) additions, n^3 multiplications
elapsed = (end - start)
rate = iters*ops/elapsed/10**9
print('\nCPU: %d x %d matmul took: %.2f sec, %.2f G ops/sec' % (n, n, elapsed/iters,rate,))
|
[
"tensorflow.ones",
"tensorflow.global_variables_initializer",
"tensorflow.device",
"tensorflow.Session",
"numpy.ones",
"tensorflow.OptimizerOptions",
"time.time",
"tensorflow.matmul",
"numpy.matmul"
] |
[((500, 525), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (510, 525), True, 'import tensorflow as tf\n'), ((626, 637), 'time.time', 'time.time', ([], {}), '()\n', (635, 637), False, 'import time\n'), ((690, 701), 'time.time', 'time.time', ([], {}), '()\n', (699, 701), False, 'import time\n'), ((928, 943), 'numpy.ones', 'np.ones', (['(n, n)'], {}), '((n, n))\n', (935, 943), True, 'import numpy as np\n'), ((953, 968), 'numpy.ones', 'np.ones', (['(n, n)'], {}), '((n, n))\n', (960, 968), True, 'import numpy as np\n'), ((977, 988), 'time.time', 'time.time', ([], {}), '()\n', (986, 988), False, 'import time\n'), ((1047, 1058), 'time.time', 'time.time', ([], {}), '()\n', (1056, 1058), False, 'import time\n'), ((148, 167), 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (157, 167), True, 'import tensorflow as tf\n'), ((295, 322), 'tensorflow.matmul', 'tf.matmul', (['matrix1', 'matrix2'], {}), '(matrix1, matrix2)\n', (304, 322), True, 'import tensorflow as tf\n'), ((536, 569), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (567, 569), True, 'import tensorflow as tf\n'), ((1014, 1041), 'numpy.matmul', 'np.matmul', (['matrix1', 'matrix2'], {}), '(matrix1, matrix2)\n', (1023, 1041), True, 'import numpy as np\n'), ((195, 223), 'tensorflow.ones', 'tf.ones', (['(n, n)'], {'dtype': 'dtype'}), '((n, n), dtype=dtype)\n', (202, 223), True, 'import tensorflow as tf\n'), ((251, 279), 'tensorflow.ones', 'tf.ones', (['(n, n)'], {'dtype': 'dtype'}), '((n, n), dtype=dtype)\n', (258, 279), True, 'import tensorflow as tf\n'), ((437, 490), 'tensorflow.OptimizerOptions', 'tf.OptimizerOptions', ([], {'opt_level': 'tf.OptimizerOptions.L0'}), '(opt_level=tf.OptimizerOptions.L0)\n', (456, 490), True, 'import tensorflow as tf\n')]
|
# Modulos
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
np.set_printoptions(suppress=True)
# Declaracion de clases
class Adeline:
def __init__(self, r, landa, training_type, iter):
self.iter = iter
self.training_type = training_type
self.landa = landa
self.r = r
def function_transfer(self,x):
return 1/ (1 + np.exp(-x))
def show(self, iter, x, y, up):
print('ITERACION ACTUAL: {}\n'.format(iter))
print('Patron | __________ Salida __________\n')
print('No | Deseada Calculada Error Abs\n')
for i in range(0,self.p):
if i < 12 or i >= self.p - 8:
print('{} | {:.2f} {:.2f} {:.2f}'.format(i, y[i],up[i],abs(y[i]-up[i])))
elif i == 12:
print('...')
print('\n')
def solve(self, x, y):
self.p = x.shape[0]
self.inputs = x.shape[1]
self.W = np.random.uniform(low=-0.3, high=0.3,size=(1,self.inputs))
vectorjfw = []
jfwprev = 0
# self.W = np.zeros((1,self.inputs))
it = 0
while(it < self.iter):
# for i in range(0,self.r):
if self.training_type == "Lotes":
deltaw = np.zeros((self.inputs, 1))
up = self.evaluation(x)
vectorjfw.append(mean_squared_error(y,up))
print('Error promedio: {:.6f}'.format(sum(vectorjfw) / len(vectorjfw)))
jw = (y - up) * (up) * (1 - up)
self.show(it, x, y, up)
for j in range(0,self.p):
wri = self.landa*(jw[j])*np.transpose(x[j])
self.W = self.W + wri
it = it + 1
def evaluation(self,x):
up = sum(np.transpose(self.W*x) - 0.5)
up = self.function_transfer(up)
return up
# Declaracion de operaciones
def main():
''' Cuerpo principal '''
x0 = np.random.uniform(0, 1)
xn = []
xn.append(x0)
for i in range(1,600):
xn.append(4*xn[i-1]*(1-xn[i-1]))
vcr = []
vcry = []
xn = xn[-100:]
for i in range(0,len(xn[-100:])-2):
vcr.append([xn[i],xn[i+1],xn[i]*xn[i],xn[i]*xn[i+1],xn[i+1]*xn[i+1]])
vcry.append(xn[i+2])
x = np.array(vcr)
y = np.array(vcry)
X_train, X_test, y_train, y_test = train_test_split( x, y, test_size=0.33, random_state=42)
p = Adeline(1, 0.8,"PP",1000)
print('Tipo de aprendizaje: Patron a patron\nFactor de aprendizaje: {}\nCantidad de iteraciones utilizadas: {}'.format(p.landa, p.iter))
p.solve(X_train,y_train)
if __name__ == '__main__':
main()
|
[
"numpy.random.uniform",
"numpy.set_printoptions",
"sklearn.model_selection.train_test_split",
"numpy.zeros",
"numpy.transpose",
"numpy.array",
"numpy.exp",
"sklearn.metrics.mean_squared_error"
] |
[((129, 163), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (148, 163), True, 'import numpy as np\n'), ((1979, 2002), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (1996, 2002), True, 'import numpy as np\n'), ((2304, 2317), 'numpy.array', 'np.array', (['vcr'], {}), '(vcr)\n', (2312, 2317), True, 'import numpy as np\n'), ((2326, 2340), 'numpy.array', 'np.array', (['vcry'], {}), '(vcry)\n', (2334, 2340), True, 'import numpy as np\n'), ((2380, 2435), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.33)', 'random_state': '(42)'}), '(x, y, test_size=0.33, random_state=42)\n', (2396, 2435), False, 'from sklearn.model_selection import train_test_split\n'), ((1014, 1074), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.3)', 'high': '(0.3)', 'size': '(1, self.inputs)'}), '(low=-0.3, high=0.3, size=(1, self.inputs))\n', (1031, 1074), True, 'import numpy as np\n'), ((434, 444), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (440, 444), True, 'import numpy as np\n'), ((1319, 1345), 'numpy.zeros', 'np.zeros', (['(self.inputs, 1)'], {}), '((self.inputs, 1))\n', (1327, 1345), True, 'import numpy as np\n'), ((1411, 1436), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y', 'up'], {}), '(y, up)\n', (1429, 1436), False, 'from sklearn.metrics import mean_squared_error\n'), ((1810, 1834), 'numpy.transpose', 'np.transpose', (['(self.W * x)'], {}), '(self.W * x)\n', (1822, 1834), True, 'import numpy as np\n'), ((1682, 1700), 'numpy.transpose', 'np.transpose', (['x[j]'], {}), '(x[j])\n', (1694, 1700), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
import pandas as pd
# Read in track metadata with genre labels
tracks = pd.read_csv('datasets/fma-rock-vs-hiphop.csv')
# Read in track metrics with the features
echonest_metrics = pd.read_json('datasets/echonest-metrics.json', precise_float=True)
# Merge the relevant columns of tracks and echonest_metrics
echo_tracks = echonest_metrics.merge(tracks[['genre_top', 'track_id']], on='track_id')
# Inspect the resultant dataframe
echo_tracks.info()
# Create a correlation matrix
corr_metrics = echo_tracks.corr()
corr_metrics.style.background_gradient()
# Define features
features = echo_tracks.drop(['genre_top', 'track_id'], axis=1)
# Define labels
labels = echo_tracks['genre_top']
# Import the StandardScaler
from sklearn.preprocessing import StandardScaler
# Scale the features and set the values to a new variable
scaler = StandardScaler()
scaled_train_features = scaler.fit_transform(features)
# Import plotting module, and PCA class
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# Get explained variance ratios from PCA using all features
pca = PCA()
pca.fit(scaled_train_features)
exp_variance = pca.explained_variance_ratio_
# plot the explained variance using a barplot
fig, ax = plt.subplots()
print(pca.explained_variance_ratio_)
print(pca.n_components_)
ax.bar(range(pca.n_components_), exp_variance)
ax.set_xlabel('Principal Component #')
# Import numpy
import numpy as np
# Calculate the cumulative explained variance
cum_exp_variance = np.cumsum(exp_variance)
# Plot the cumulative explained variance and draw a dashed line at 0.85.
fig, ax = plt.subplots()
ax.plot(cum_exp_variance)
ax.axhline(y=0.85, linestyle='--')
# choose the n_components where about 85% of our variance can be explained
n_components = 6
# Perform PCA with the chosen number of components and project data onto components
pca = PCA(n_components, random_state=10)
pca.fit(scaled_train_features)
pca_projection = pca.transform(scaled_train_features)
# Import train_test_split function and Decision tree classifier
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# Split data
train_features, test_features, train_labels, test_labels = train_test_split(pca_projection, labels, random_state=10)
# Train decision tree
tree = DecisionTreeClassifier(random_state=10)
tree.fit(train_features, train_labels)
# Predict the labels for the test data
pred_labels_tree = tree.predict(test_features)
# Import LogisticRegression
from sklearn.linear_model import LogisticRegression
# Train logistic regression and predict labels for the test set
logreg = LogisticRegression(random_state=10)
logreg.fit(train_features, train_labels)
pred_labels_logit = logreg.predict(test_features)
# Create the classification report for both models
from sklearn.metrics import classification_report
class_rep_tree = classification_report(test_labels, pred_labels_tree)
class_rep_log = classification_report(test_labels, pred_labels_logit)
print("Decision Tree: \n", class_rep_tree)
print("Logistic Regression: \n", class_rep_log)
# Balance data for greater performance
# Subset only the hip-hop tracks, and then only the rock tracks
hop_only = echo_tracks.loc[echo_tracks['genre_top'] == 'Hip-Hop']
rock_only = echo_tracks.loc[echo_tracks['genre_top'] == 'Rock']
# sample the rocks songs to be the same number as there are hip-hop songs
rock_only = rock_only.sample(hop_only.shape[0], random_state=10)
# concatenate the dataframes rock_only and hop_only
rock_hop_bal = pd.concat([rock_only, hop_only])
# The features, labels, and pca projection are created for the balanced dataframe
features = rock_hop_bal.drop(['genre_top', 'track_id'], axis=1)
labels = rock_hop_bal['genre_top']
pca_projection = pca.fit_transform(scaler.fit_transform(features))
# Redefine the train and test set with the pca_projection from the balanced data
train_features, test_features, train_labels, test_labels = train_test_split(pca_projection, labels, random_state=10)
# Train decision tree on the balanced data
tree = DecisionTreeClassifier(random_state=10)
tree.fit(train_features, train_labels)
pred_labels_tree = tree.predict(test_features)
# Train logistic regression on the balanced data
logreg = LogisticRegression(random_state=10)
logreg.fit(train_features, train_labels)
pred_labels_logit = logreg.predict(test_features)
# Compare the models
print("Decision Tree: \n", classification_report(test_labels, pred_labels_tree))
print("Logistic Regression: \n", classification_report(test_labels, pred_labels_logit))
# Using cross-validation to evaluate our models
from sklearn.model_selection import KFold, cross_val_score
# Set up K-fold cross-validation
kf = KFold(n_splits=10)
tree = DecisionTreeClassifier(random_state=10)
logreg = LogisticRegression(random_state=10)
# Train models using KFold cv
tree_score = cross_val_score(tree, pca_projection, labels, cv = kf )
logit_score = cross_val_score(logreg, pca_projection, labels, cv = kf)
# Print the mean of each array of scores
print("Decision Tree:", np.mean(tree_score), "Logistic Regression:", np.mean(logit_score))
|
[
"sklearn.preprocessing.StandardScaler",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.model_selection.cross_val_score",
"pandas.read_json",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.metrics.classification_report",
"numpy.cumsum",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.KFold",
"sklearn.decomposition.PCA",
"numpy.mean",
"matplotlib.pyplot.subplots",
"pandas.concat"
] |
[((98, 144), 'pandas.read_csv', 'pd.read_csv', (['"""datasets/fma-rock-vs-hiphop.csv"""'], {}), "('datasets/fma-rock-vs-hiphop.csv')\n", (109, 144), True, 'import pandas as pd\n'), ((207, 273), 'pandas.read_json', 'pd.read_json', (['"""datasets/echonest-metrics.json"""'], {'precise_float': '(True)'}), "('datasets/echonest-metrics.json', precise_float=True)\n", (219, 273), True, 'import pandas as pd\n'), ((864, 880), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (878, 880), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1116, 1121), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (1119, 1121), False, 'from sklearn.decomposition import PCA\n'), ((1255, 1269), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1267, 1269), True, 'import matplotlib.pyplot as plt\n'), ((1519, 1542), 'numpy.cumsum', 'np.cumsum', (['exp_variance'], {}), '(exp_variance)\n', (1528, 1542), True, 'import numpy as np\n'), ((1627, 1641), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1639, 1641), True, 'import matplotlib.pyplot as plt\n'), ((1887, 1921), 'sklearn.decomposition.PCA', 'PCA', (['n_components'], {'random_state': '(10)'}), '(n_components, random_state=10)\n', (1890, 1921), False, 'from sklearn.decomposition import PCA\n'), ((2248, 2305), 'sklearn.model_selection.train_test_split', 'train_test_split', (['pca_projection', 'labels'], {'random_state': '(10)'}), '(pca_projection, labels, random_state=10)\n', (2264, 2305), False, 'from sklearn.model_selection import train_test_split\n'), ((2337, 2376), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'random_state': '(10)'}), '(random_state=10)\n', (2359, 2376), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((2660, 2695), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'random_state': '(10)'}), '(random_state=10)\n', (2678, 2695), False, 'from sklearn.linear_model import LogisticRegression\n'), ((2906, 2958), 'sklearn.metrics.classification_report', 'classification_report', (['test_labels', 'pred_labels_tree'], {}), '(test_labels, pred_labels_tree)\n', (2927, 2958), False, 'from sklearn.metrics import classification_report\n'), ((2975, 3028), 'sklearn.metrics.classification_report', 'classification_report', (['test_labels', 'pred_labels_logit'], {}), '(test_labels, pred_labels_logit)\n', (2996, 3028), False, 'from sklearn.metrics import classification_report\n'), ((3565, 3597), 'pandas.concat', 'pd.concat', (['[rock_only, hop_only]'], {}), '([rock_only, hop_only])\n', (3574, 3597), True, 'import pandas as pd\n'), ((3988, 4045), 'sklearn.model_selection.train_test_split', 'train_test_split', (['pca_projection', 'labels'], {'random_state': '(10)'}), '(pca_projection, labels, random_state=10)\n', (4004, 4045), False, 'from sklearn.model_selection import train_test_split\n'), ((4098, 4137), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'random_state': '(10)'}), '(random_state=10)\n', (4120, 4137), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((4283, 4318), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'random_state': '(10)'}), '(random_state=10)\n', (4301, 4318), False, 'from sklearn.linear_model import LogisticRegression\n'), ((4751, 4769), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(10)'}), '(n_splits=10)\n', (4756, 4769), False, 'from sklearn.model_selection import KFold, cross_val_score\n'), ((4778, 4817), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'random_state': '(10)'}), '(random_state=10)\n', (4800, 4817), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((4827, 4862), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'random_state': '(10)'}), '(random_state=10)\n', (4845, 4862), False, 'from sklearn.linear_model import LogisticRegression\n'), ((4908, 4960), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['tree', 'pca_projection', 'labels'], {'cv': 'kf'}), '(tree, pca_projection, labels, cv=kf)\n', (4923, 4960), False, 'from sklearn.model_selection import KFold, cross_val_score\n'), ((4978, 5032), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['logreg', 'pca_projection', 'labels'], {'cv': 'kf'}), '(logreg, pca_projection, labels, cv=kf)\n', (4993, 5032), False, 'from sklearn.model_selection import KFold, cross_val_score\n'), ((4459, 4511), 'sklearn.metrics.classification_report', 'classification_report', (['test_labels', 'pred_labels_tree'], {}), '(test_labels, pred_labels_tree)\n', (4480, 4511), False, 'from sklearn.metrics import classification_report\n'), ((4546, 4599), 'sklearn.metrics.classification_report', 'classification_report', (['test_labels', 'pred_labels_logit'], {}), '(test_labels, pred_labels_logit)\n', (4567, 4599), False, 'from sklearn.metrics import classification_report\n'), ((5101, 5120), 'numpy.mean', 'np.mean', (['tree_score'], {}), '(tree_score)\n', (5108, 5120), True, 'import numpy as np\n'), ((5147, 5167), 'numpy.mean', 'np.mean', (['logit_score'], {}), '(logit_score)\n', (5154, 5167), True, 'import numpy as np\n')]
|
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from data_worker.data_worker import combine_batches, split_into_batches, \
unpickle, unpack_data, display_img
from torch_lib.Interface import Interface
from torch_lib.Nets import MediumNet
from torch_lib.data_worker import suit4pytorch
batches_names = [
'data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4',
'data_batch_5']
if __name__ == '__main__':
print('running main')
saved_weights_file = 'saved_nets/saved_torch/version1.pth'
data_batches = [
unpickle(f'datasets/cifar-10-batches-py/{batch_name}') for batch_name
in batches_names]
unpacked_batches = [
(unpack_data(data_batch)) for data_batch
in data_batches]
print(unpacked_batches[0][0].shape)
X, Y = combine_batches(unpacked_batches)
print(X.shape, Y.shape)
batches = split_into_batches(X, Y, 3)
torch_batches = [(suit4pytorch(X, Y)) for X, Y in batches]
X_torch = torch_batches[0][0]
Y_torch = torch_batches[0][1]
net = MediumNet()
net_interface = Interface(net)
net_interface.train_net(torch_batches, 1, verbose=False, batch_size=None)
net_interface.save_weights(saved_weights_file)
preds = net_interface.predict_net(X_torch)
preds = preds.detach().numpy()
print(preds)
print(np.argmax(preds, axis=1), Y_torch)
|
[
"data_worker.data_worker.unpack_data",
"numpy.argmax",
"data_worker.data_worker.unpickle",
"data_worker.data_worker.combine_batches",
"torch_lib.Interface.Interface",
"torch_lib.data_worker.suit4pytorch",
"torch_lib.Nets.MediumNet",
"data_worker.data_worker.split_into_batches"
] |
[((833, 866), 'data_worker.data_worker.combine_batches', 'combine_batches', (['unpacked_batches'], {}), '(unpacked_batches)\n', (848, 866), False, 'from data_worker.data_worker import combine_batches, split_into_batches, unpickle, unpack_data, display_img\n'), ((911, 938), 'data_worker.data_worker.split_into_batches', 'split_into_batches', (['X', 'Y', '(3)'], {}), '(X, Y, 3)\n', (929, 938), False, 'from data_worker.data_worker import combine_batches, split_into_batches, unpickle, unpack_data, display_img\n'), ((1083, 1094), 'torch_lib.Nets.MediumNet', 'MediumNet', ([], {}), '()\n', (1092, 1094), False, 'from torch_lib.Nets import MediumNet\n'), ((1115, 1129), 'torch_lib.Interface.Interface', 'Interface', (['net'], {}), '(net)\n', (1124, 1129), False, 'from torch_lib.Interface import Interface\n'), ((584, 638), 'data_worker.data_worker.unpickle', 'unpickle', (['f"""datasets/cifar-10-batches-py/{batch_name}"""'], {}), "(f'datasets/cifar-10-batches-py/{batch_name}')\n", (592, 638), False, 'from data_worker.data_worker import combine_batches, split_into_batches, unpickle, unpack_data, display_img\n'), ((715, 738), 'data_worker.data_worker.unpack_data', 'unpack_data', (['data_batch'], {}), '(data_batch)\n', (726, 738), False, 'from data_worker.data_worker import combine_batches, split_into_batches, unpickle, unpack_data, display_img\n'), ((962, 980), 'torch_lib.data_worker.suit4pytorch', 'suit4pytorch', (['X', 'Y'], {}), '(X, Y)\n', (974, 980), False, 'from torch_lib.data_worker import suit4pytorch\n'), ((1369, 1393), 'numpy.argmax', 'np.argmax', (['preds'], {'axis': '(1)'}), '(preds, axis=1)\n', (1378, 1393), True, 'import numpy as np\n')]
|
'''
<NAME> 2012-2013
<<EMAIL>>
'''
import numpy as np
import scipy.io as sio
def create_icosahedron(height=1.,payloadR=0.3):
'''
Creates a tensegrity icosahedron
'''
#create points
points = np.zeros((3,2*6+2))
phi = (1+np.sqrt(5))*0.5
offest = 0.792
points[:,0] = (-phi,0,1*offest)
points[:,1] = (phi,0,1*offest)
points[:,2] = (-phi,0,-1*offest)
points[:,3] = (phi,0,-1*offest)
points[:,4] = (1*offest,-phi,0)
points[:,5] = (1*offest,phi,0)
points[:,6] = (-1*offest,-phi,0)
points[:,7] = (-1*offest,phi,0)
points[:,8] = (0,1*offest,-phi)
points[:,9] = (0,1*offest,phi)
points[:,10] = (0,-1*offest,-phi)
points[:,11] = (0,-1*offest,phi)
points[:,12] = (0,0,(payloadR/(height*0.62*0.5)))
points[:,13] = (0,0,(-payloadR/(height*0.62*0.5)))
#theta = -0.36486 #theta=-20.905 degrees
#yRot = np.array([[np.cos(theta),0.,np.sin(theta)],[0.,1.,0.],[-np.sin(theta),0.,np.cos(theta)]])
#testPoints = np.dot(yRot,points)
#print points
#print testPoints
#points = testPoints
points *= (height*0.62)*0.5
#scale the tensegrity and center it
#create bars
bars = np.zeros((6+1,6*2+2))
bars[:,::2] = np.eye(6+1)
bars[:,1::2] = -np.eye(6+1)
#create springs
springs = np.zeros((6*6,2*6+2))
springs[0,(0,6)] = (1,-1)
springs[1,(0,7)] = (1,-1)
springs[2,(0,9)] = (1,-1)
springs[3,(0,11)] = (1,-1)
springs[4,(1,4)] = (1,-1)
springs[5,(1,5)] = (1,-1)
springs[6,(1,9)] = (1,-1)
springs[7,(1,11)] = (1,-1)
springs[8,(2,6)] = (1,-1)
springs[9,(2,7)] = (1,-1)
springs[10,(2,8)] = (1,-1)
springs[11,(2,10)] = (1,-1)
springs[12,(3,4)] = (1,-1)
springs[13,(3,5)] = (1,-1)
springs[14,(3,8)] = (1,-1)
springs[15,(3,10)] = (1,-1)
springs[16,(4,10)] = (1,-1)
springs[17,(4,11)] = (1,-1)
springs[18,(5,8)] = (1,-1)
springs[19,(5,9)] = (1,-1)
springs[20,(6,10)] = (1,-1)
springs[21,(6,11)] = (1,-1)
springs[22,(7,8)] = (1,-1)
springs[23,(7,9)] = (1,-1)
springs[24,(0,12)] = (1,-1)
springs[25,(1,12)] = (1,-1)
springs[26,(2,13)] = (1,-1)
springs[27,(3,13)] = (1,-1)
springs[28,(6,13)] = (1,-1)
springs[29,(5,13)] = (1,-1)
springs[30,(4,12)] = (1,-1)
springs[31,(7,12)] = (1,-1)
springs[32,(8,13)] = (1,-1)
springs[33,(9,12)] = (1,-1)
springs[34,(10,13)] = (1,-1)
springs[35,(11,12)] = (1,-1)
# springs[:num_struts,:num_struts] = -np.eye(num_struts)+np.roll(np.eye(num_struts),1,1) #ground layer
# springs[num_struts:2*num_struts,num_struts:] = -np.eye(num_struts)+np.roll(np.eye(num_struts),1,1) #top layer
# springs[2*num_struts:,:num_struts] = -np.eye(num_struts) #connections between layers
# springs[2*num_struts:,num_struts:] = np.roll(np.eye(num_struts),1,1)
return points,bars,springs
|
[
"numpy.eye",
"numpy.zeros",
"numpy.sqrt"
] |
[((214, 238), 'numpy.zeros', 'np.zeros', (['(3, 2 * 6 + 2)'], {}), '((3, 2 * 6 + 2))\n', (222, 238), True, 'import numpy as np\n'), ((1188, 1216), 'numpy.zeros', 'np.zeros', (['(6 + 1, 6 * 2 + 2)'], {}), '((6 + 1, 6 * 2 + 2))\n', (1196, 1216), True, 'import numpy as np\n'), ((1228, 1241), 'numpy.eye', 'np.eye', (['(6 + 1)'], {}), '(6 + 1)\n', (1234, 1241), True, 'import numpy as np\n'), ((1307, 1335), 'numpy.zeros', 'np.zeros', (['(6 * 6, 2 * 6 + 2)'], {}), '((6 * 6, 2 * 6 + 2))\n', (1315, 1335), True, 'import numpy as np\n'), ((1260, 1273), 'numpy.eye', 'np.eye', (['(6 + 1)'], {}), '(6 + 1)\n', (1266, 1273), True, 'import numpy as np\n'), ((247, 257), 'numpy.sqrt', 'np.sqrt', (['(5)'], {}), '(5)\n', (254, 257), True, 'import numpy as np\n')]
|
import numpy as np
import pandas as pd
def Preprc(raw_data: object, flag: object = 0) -> object:
"""
Function to compute the decoded values in motionsense HRV sensors and
interploate the timestamps given the decoded sequence numbers
:param raw_data:
:param flag:
:return:
"""
# process recieved arrays (data_arr1=data, data_arr2=time,seq)
if not list(raw_data):
return []
data_arr1, data_arr2, err_pkts = process_raw_PPG(raw_data)
seq = np.copy(data_arr2[:, 1])
# make Sq no. ordered
d = np.diff(seq)
idx1 = np.where(d < -(1023 - 50))[0]
idx1 = np.append(idx1, len(seq) - 1)
for i in range(len(idx1) - 1):
seq[idx1[i] + 1:idx1[i + 1] + 1] = seq[idx1[i] + 1:idx1[i + 1] + 1] - (i + 1) * d[idx1[i]]
seq = (seq - seq[0]).astype(int).reshape((len(seq)))
# print(seq)
seq_max = max(seq) # just some heuristic to make ECG seq value 4 times
arr1 = np.concatenate([seq.reshape((len(seq), 1)), data_arr1], axis=1)
if raw_data.all != None:
df1 = pd.DataFrame(arr1, columns=['Seq', 'AccX', 'AccY', 'AccZ', 'GyroX',
'GyroY', 'GyroZ', 'LED1', 'LED2', 'LED3'])
else:
return []
df1.drop_duplicates(subset=['Seq'], inplace=True)
df2 = pd.DataFrame(np.array(range(seq_max + 1)), columns=['Seq'])
itime = data_arr2[0, 0];
ftime = data_arr2[-1, 0]
df3 = df2.merge(df1, how='left', on=['Seq'])
df3['time'] = pd.to_datetime(np.linspace(itime, ftime, len(df2)), unit='ms')
df3.set_index('time', inplace=True)
df3.interpolate(method='time', axis=0, inplace=True) # filling missing data
df3.dropna(inplace=True)
df3['time_stamps'] = np.linspace(itime, ftime, len(df2))
return df3
def process_raw_PPG(raw_data: object) -> object:
"""
function to decode the values from raw byte arrays
:rtype: object
:param raw_data:
:return:
"""
data = raw_data
Vals = data[:, 2:]
num_samples = Vals.shape[0]
ts = data[:, 0]
Accx = np.zeros((num_samples));
Accy = np.zeros((num_samples))
Accz = np.zeros((num_samples));
Gyrox = np.zeros((num_samples))
Gyroy = np.zeros((num_samples));
Gyroz = np.zeros((num_samples))
led1 = np.zeros((num_samples));
led2 = np.zeros((num_samples))
led3 = np.zeros((num_samples));
seq = np.zeros((num_samples))
time_stamps = np.zeros((num_samples))
n = 0;
i = 0;
s = 0;
mis_pkts = 0
while (n) < (num_samples):
time_stamps[i] = ts[n]
Accx[i] = np.int16((np.uint8(Vals[n, 0]) << 8) | (np.uint8(Vals[n, 1])))
Accy[i] = np.int16((np.uint8(Vals[n, 2]) << 8) | (np.uint8(Vals[n, 3])))
Accz[i] = np.int16((np.uint8(Vals[n, 4]) << 8) | (np.uint8(Vals[n, 5])))
Gyrox[i] = np.int16((np.uint8(Vals[n, 6]) << 8) | (np.uint8(Vals[n, 7])))
Gyroy[i] = np.int16((np.uint8(Vals[n, 8]) << 8) | (np.uint8(Vals[n, 9])))
Gyroz[i] = np.int16((np.uint8(Vals[n, 10]) << 8) | (np.uint8(Vals[n, 11])))
led1[i] = (np.uint8(Vals[n, 12]) << 10) | (np.uint8(Vals[n, 13]) << 2) | \
((np.uint8(Vals[n, 14]) & int('11000000', 2)) >> 6)
led2[i] = ((np.uint8(Vals[n, 14]) & int('00111111', 2)) << 12) | \
(np.uint8(Vals[n, 15]) << 4) | \
((np.uint8(Vals[n, 16]) & int('11110000', 2)) >> 4)
led3[i] = ((np.uint8(Vals[n, 16]) & int('00001111', 2)) << 14) | \
(np.uint8(Vals[n, 17]) << 6) | \
((np.uint8(Vals[n, 18]) & int('11111100', 2)) >> 2)
seq[i] = ((np.uint8(Vals[n, 18]) & int('00000011', 2)) << 8) | \
(np.uint8(Vals[n, 19]))
if i > 0:
difer = int((seq[i] - seq[i - 1]) % 1024)
if difer > 50:
s = s + 1 # keep a record of how many such errors occured
n = n + 1
continue
mis_pkts = mis_pkts + (difer - 1)
n = n + 1;
i = i + 1
# removing any trailing zeros
seq = seq[:i];
time_stamps = time_stamps[:i]
Accx = Accx[:i];
Accy = Accy[:i];
Accz = Accz[:i]
Gyrox = Gyrox[:i];
Gyroy = Gyroy[:i];
Gyroz = Gyroz[:i]
led1 = led1[:i];
led2 = led2[:i];
led3 = led3[:i]
# print('no. of unknown seq errors in PPG= ',s)
# print('no. of missed packets= {}'.format(mis_pkts))
data_arr1 = np.stack((Accx, Accy, Accz, Gyrox, Gyroy, Gyroz, led1, led2, led3), axis=1)
# print(np.shape(data_arr1))
data_arr2 = np.concatenate((time_stamps.reshape(1, -1), seq.reshape(1, -1))).T
return data_arr1, data_arr2, (mis_pkts + s)
|
[
"numpy.stack",
"pandas.DataFrame",
"numpy.uint8",
"numpy.copy",
"numpy.zeros",
"numpy.diff",
"numpy.where"
] |
[((493, 517), 'numpy.copy', 'np.copy', (['data_arr2[:, 1]'], {}), '(data_arr2[:, 1])\n', (500, 517), True, 'import numpy as np\n'), ((552, 564), 'numpy.diff', 'np.diff', (['seq'], {}), '(seq)\n', (559, 564), True, 'import numpy as np\n'), ((2056, 2077), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2064, 2077), True, 'import numpy as np\n'), ((2092, 2113), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2100, 2113), True, 'import numpy as np\n'), ((2127, 2148), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2135, 2148), True, 'import numpy as np\n'), ((2164, 2185), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2172, 2185), True, 'import numpy as np\n'), ((2200, 2221), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2208, 2221), True, 'import numpy as np\n'), ((2237, 2258), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2245, 2258), True, 'import numpy as np\n'), ((2272, 2293), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2280, 2293), True, 'import numpy as np\n'), ((2308, 2329), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2316, 2329), True, 'import numpy as np\n'), ((2343, 2364), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2351, 2364), True, 'import numpy as np\n'), ((2378, 2399), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2386, 2399), True, 'import numpy as np\n'), ((2420, 2441), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2428, 2441), True, 'import numpy as np\n'), ((4419, 4494), 'numpy.stack', 'np.stack', (['(Accx, Accy, Accz, Gyrox, Gyroy, Gyroz, led1, led2, led3)'], {'axis': '(1)'}), '((Accx, Accy, Accz, Gyrox, Gyroy, Gyroz, led1, led2, led3), axis=1)\n', (4427, 4494), True, 'import numpy as np\n'), ((576, 602), 'numpy.where', 'np.where', (['(d < -(1023 - 50))'], {}), '(d < -(1023 - 50))\n', (584, 602), True, 'import numpy as np\n'), ((1052, 1166), 'pandas.DataFrame', 'pd.DataFrame', (['arr1'], {'columns': "['Seq', 'AccX', 'AccY', 'AccZ', 'GyroX', 'GyroY', 'GyroZ', 'LED1', 'LED2',\n 'LED3']"}), "(arr1, columns=['Seq', 'AccX', 'AccY', 'AccZ', 'GyroX', 'GyroY',\n 'GyroZ', 'LED1', 'LED2', 'LED3'])\n", (1064, 1166), True, 'import pandas as pd\n'), ((3683, 3704), 'numpy.uint8', 'np.uint8', (['Vals[n, 19]'], {}), '(Vals[n, 19])\n', (3691, 3704), True, 'import numpy as np\n'), ((2614, 2634), 'numpy.uint8', 'np.uint8', (['Vals[n, 1]'], {}), '(Vals[n, 1])\n', (2622, 2634), True, 'import numpy as np\n'), ((2695, 2715), 'numpy.uint8', 'np.uint8', (['Vals[n, 3]'], {}), '(Vals[n, 3])\n', (2703, 2715), True, 'import numpy as np\n'), ((2776, 2796), 'numpy.uint8', 'np.uint8', (['Vals[n, 5]'], {}), '(Vals[n, 5])\n', (2784, 2796), True, 'import numpy as np\n'), ((2858, 2878), 'numpy.uint8', 'np.uint8', (['Vals[n, 7]'], {}), '(Vals[n, 7])\n', (2866, 2878), True, 'import numpy as np\n'), ((2940, 2960), 'numpy.uint8', 'np.uint8', (['Vals[n, 9]'], {}), '(Vals[n, 9])\n', (2948, 2960), True, 'import numpy as np\n'), ((3023, 3044), 'numpy.uint8', 'np.uint8', (['Vals[n, 11]'], {}), '(Vals[n, 11])\n', (3031, 3044), True, 'import numpy as np\n'), ((2584, 2604), 'numpy.uint8', 'np.uint8', (['Vals[n, 0]'], {}), '(Vals[n, 0])\n', (2592, 2604), True, 'import numpy as np\n'), ((2665, 2685), 'numpy.uint8', 'np.uint8', (['Vals[n, 2]'], {}), '(Vals[n, 2])\n', (2673, 2685), True, 'import numpy as np\n'), ((2746, 2766), 'numpy.uint8', 'np.uint8', (['Vals[n, 4]'], {}), '(Vals[n, 4])\n', (2754, 2766), True, 'import numpy as np\n'), ((2828, 2848), 'numpy.uint8', 'np.uint8', (['Vals[n, 6]'], {}), '(Vals[n, 6])\n', (2836, 2848), True, 'import numpy as np\n'), ((2910, 2930), 'numpy.uint8', 'np.uint8', (['Vals[n, 8]'], {}), '(Vals[n, 8])\n', (2918, 2930), True, 'import numpy as np\n'), ((2992, 3013), 'numpy.uint8', 'np.uint8', (['Vals[n, 10]'], {}), '(Vals[n, 10])\n', (3000, 3013), True, 'import numpy as np\n'), ((3066, 3087), 'numpy.uint8', 'np.uint8', (['Vals[n, 12]'], {}), '(Vals[n, 12])\n', (3074, 3087), True, 'import numpy as np\n'), ((3098, 3119), 'numpy.uint8', 'np.uint8', (['Vals[n, 13]'], {}), '(Vals[n, 13])\n', (3106, 3119), True, 'import numpy as np\n'), ((3150, 3171), 'numpy.uint8', 'np.uint8', (['Vals[n, 14]'], {}), '(Vals[n, 14])\n', (3158, 3171), True, 'import numpy as np\n'), ((3294, 3315), 'numpy.uint8', 'np.uint8', (['Vals[n, 15]'], {}), '(Vals[n, 15])\n', (3302, 3315), True, 'import numpy as np\n'), ((3346, 3367), 'numpy.uint8', 'np.uint8', (['Vals[n, 16]'], {}), '(Vals[n, 16])\n', (3354, 3367), True, 'import numpy as np\n'), ((3490, 3511), 'numpy.uint8', 'np.uint8', (['Vals[n, 17]'], {}), '(Vals[n, 17])\n', (3498, 3511), True, 'import numpy as np\n'), ((3542, 3563), 'numpy.uint8', 'np.uint8', (['Vals[n, 18]'], {}), '(Vals[n, 18])\n', (3550, 3563), True, 'import numpy as np\n'), ((3611, 3632), 'numpy.uint8', 'np.uint8', (['Vals[n, 18]'], {}), '(Vals[n, 18])\n', (3619, 3632), True, 'import numpy as np\n'), ((3220, 3241), 'numpy.uint8', 'np.uint8', (['Vals[n, 14]'], {}), '(Vals[n, 14])\n', (3228, 3241), True, 'import numpy as np\n'), ((3416, 3437), 'numpy.uint8', 'np.uint8', (['Vals[n, 16]'], {}), '(Vals[n, 16])\n', (3424, 3437), True, 'import numpy as np\n')]
|
#/usr/bin/env python3
import numpy as np
# Try importing matplotlib; if it works show a plot of generated data
try:
import matplotlib.pyplot as plt
except ImportError:
MAKE_PLOT = False
else:
MAKE_PLOT = True
FILTERSIZE = 50
def smooth(x, window_len=11, window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window; should be an odd integer
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
t=linspace(-2,2,0.1)
x=sin(t)+randn(len(t))*0.1
y=smooth(x)
see also:
np.hanning, np.hamming, np.bartlett, np.blackman, np.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
"""
if x.ndim != 1:
raise ValueError("smooth only accepts 1 dimension arrays.")
if x.size < window_len:
raise ValueError("Input vector needs to be bigger than window size.")
if window_len<3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
s=np.r_[x[window_len-1:0:-1],x,x[-2:-window_len-1:-1]]
if window == 'flat': #moving average
w=np.ones(window_len,'d')
else:
w=eval('np.'+window+'(window_len)')
y=np.convolve(w/w.sum(),s,mode='valid')
return y
def main():
samples = np.random.rand(360000)
samples_smooth = smooth(samples, FILTERSIZE)
if MAKE_PLOT:
plt.plot(np.arange(len(samples)), samples)
plt.plot(np.arange(len(samples_smooth)), samples_smooth)
plt.xlim(0, len(samples))
plt.show()
for s in samples:
print(s, end=" ")
if __name__ == "__main__":
main()
|
[
"numpy.random.rand",
"matplotlib.pyplot.show",
"numpy.ones"
] |
[((2053, 2075), 'numpy.random.rand', 'np.random.rand', (['(360000)'], {}), '(360000)\n', (2067, 2075), True, 'import numpy as np\n'), ((1890, 1914), 'numpy.ones', 'np.ones', (['window_len', '"""d"""'], {}), "(window_len, 'd')\n", (1897, 1914), True, 'import numpy as np\n'), ((2301, 2311), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2309, 2311), True, 'import matplotlib.pyplot as plt\n')]
|
from __future__ import annotations
from typing import Tuple, NoReturn
from ...base import BaseEstimator
import numpy as np
from itertools import product
class DecisionStump(BaseEstimator):
"""
A decision stump classifier for {-1,1} labels according to the CART algorithm
Attributes
----------
self.threshold_ : float
The threshold by which the data is split
self.j_ : int
The index of the feature by which to split the data
self.sign_: int
The label to predict for samples where the value of the j'th feature is above the threshold
"""
def __init__(self) -> DecisionStump:
"""
Instantiate a Decision stump classifier
"""
super().__init__()
self.threshold_, self.j_, self.sign_ = None, None, None
def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn:
"""
fits a decision stump to the given data
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Input data to fit an estimator for
y : ndarray of shape (n_samples, )
Responses of input data to fit to
"""
min_err = np.inf
for i in range(X.shape[1]):
thr_pos, thr_err_pos = self._find_threshold(X[:, i], y, 1)
thr_neg, thr_err_neg = self._find_threshold(X[:, i], y, -1)
if thr_err_pos < min_err:
min_err = thr_err_pos
self.threshold_ = thr_pos
self.sign_ = 1
self.j_ = i
if thr_err_neg < min_err:
min_err = thr_err_neg
self.threshold_ = thr_neg
self.sign_ = -1
self.j_ = i
def _predict(self, X: np.ndarray) -> np.ndarray:
"""
Predict responses for given samples using fitted estimator
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Input data to predict responses for
Returns
-------
responses : ndarray of shape (n_samples, )
Predicted responses of given samples
Notes
-----
Feature values strictly below threshold are predicted as `-sign` whereas values which equal
to or above the threshold are predicted as `sign`
"""
true_vec = X[:, self.j_] >= self.threshold_
res = np.full(X.shape[0], -1)
res[true_vec] = 1
return res * self.sign_
def _find_threshold(self, values: np.ndarray, labels: np.ndarray, sign: int) -> Tuple[float, float]:
"""
Given a feature vector and labels, find a threshold by which to perform a split
The threshold is found according to the value minimizing the misclassification
error along this feature
Parameters
----------
values: ndarray of shape (n_samples,)
A feature vector to find a splitting threshold for
labels: ndarray of shape (n_samples,)
The labels to compare against
sign: int
Predicted label assigned to values equal to or above threshold
Returns
-------
thr: float
Threshold by which to perform split
thr_err: float between 0 and 1
Misclassificaiton error of returned threshold
Notes
-----
For every tested threshold, values strictly below threshold are predicted as `-sign` whereas values
which equal to or above the threshold are predicted as `sign`
"""
size = labels.size
new_idx = np.argsort(values)
sorted_values = values[new_idx]
sorted_labels = labels[new_idx]
# create matrix of all possabilities
mat = np.full((size, size + 1), -sign)
iu = np.tril_indices(size)
mat[iu] = sign
res = sorted_labels @ mat
max_idx = np.argmax(res)
mis = float(np.sum((np.sign(sorted_labels) != np.sign(mat[:, max_idx])) * np.abs(sorted_labels)))
if max_idx == 0:
return -np.inf, mis
if max_idx == size:
return np.inf, mis
return sorted_values[max_idx], mis
def _loss(self, X: np.ndarray, y: np.ndarray) -> float:
"""
Evaluate performance under misclassification loss function
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Test samples
y : ndarray of shape (n_samples, )
True labels of test samples
Returns
-------
loss : float
Performance under missclassification loss function
"""
return float(np.sum(self.predict(X) != y)) / y.size
|
[
"numpy.full",
"numpy.tril_indices",
"numpy.abs",
"numpy.argmax",
"numpy.argsort",
"numpy.sign"
] |
[((2399, 2422), 'numpy.full', 'np.full', (['X.shape[0]', '(-1)'], {}), '(X.shape[0], -1)\n', (2406, 2422), True, 'import numpy as np\n'), ((3600, 3618), 'numpy.argsort', 'np.argsort', (['values'], {}), '(values)\n', (3610, 3618), True, 'import numpy as np\n'), ((3758, 3790), 'numpy.full', 'np.full', (['(size, size + 1)', '(-sign)'], {}), '((size, size + 1), -sign)\n', (3765, 3790), True, 'import numpy as np\n'), ((3804, 3825), 'numpy.tril_indices', 'np.tril_indices', (['size'], {}), '(size)\n', (3819, 3825), True, 'import numpy as np\n'), ((3902, 3916), 'numpy.argmax', 'np.argmax', (['res'], {}), '(res)\n', (3911, 3916), True, 'import numpy as np\n'), ((4000, 4021), 'numpy.abs', 'np.abs', (['sorted_labels'], {}), '(sorted_labels)\n', (4006, 4021), True, 'import numpy as np\n'), ((3946, 3968), 'numpy.sign', 'np.sign', (['sorted_labels'], {}), '(sorted_labels)\n', (3953, 3968), True, 'import numpy as np\n'), ((3972, 3996), 'numpy.sign', 'np.sign', (['mat[:, max_idx]'], {}), '(mat[:, max_idx])\n', (3979, 3996), True, 'import numpy as np\n')]
|
import torch
import torch.nn as nn
from numpy.random import random_sample
def make_rand_coords(input_size=(256,256,256), patch_size=(64,64,64)):
return [get_dims(input_size[0] - patch_size[0]), \
get_dims(input_size[1] - patch_size[1]), \
get_dims(input_size[2] - patch_size[2])]
def get_dims(upper):
# Random value in the range [0, upper)
return int(upper * random_sample())
def multi_gpu_check(gpu_map, l_name, *args):
"""
Can move computations to other GPUs if specified. The names of the layers and corresponding GPUs can be specified
in GPU map.
:param gpu_map:
:param l_name:
:param args:
:return:
"""
args = list(args)
if l_name in gpu_map.keys():
# print(l_name)
for idx, l in enumerate(args):
args[idx] = l.to(torch.device(gpu_map[l_name]))
# print(args[idx].device, gpu_map[l_name])
if len(args)==1:
return args[0]
return args
class RCVNet(nn.Module):
"""
Random Cropping VNet. Model is designed to extract patches randomly during feedforward pass unless specifically
prevented by setting a random patch coordinate manually. Can also move operations for individual layers to different
GPUs if specified in params
Standard VNet Architecture
"""
def __init__(self, params):
"""
Standard VNet Architecture
"""
super(RCVNet, self).__init__()
self.coords = None
self.input_shape = params['input_shape']
self.patch_size = params['patch_size']
self.gen_random = params['gen_random']
# Choose sub model
if params['sub_model_name'] == 'vnet':
from model.VNet import EncoderBlock, BottleNeck, DecoderBlock
elif params['sub_model_name'] == 'vnet_2d_3d':
from model.VNet_2D_3D import EncoderBlock, BottleNeck, DecoderBlock
elif params['sub_model_name'] == 'vnet_asym':
from model.VNetAsym import EncoderBlock, BottleNeck, DecoderBlock
elif params['sub_model_name'] == 'vnet_sym':
from model.VNetSym import EncoderBlock, BottleNeck, DecoderBlock
elif params['sub_model_name'] == 'vnet_denseadd':
from model.VNetDenseAdd import EncoderBlock, BottleNeck, DecoderBlock
elif params['sub_model_name'] == 'vnet_exclusion':
from model.VNetExclusion import EncoderBlock, BottleNeck, DecoderBlock
elif params['sub_model_name'] == 'vnet_se':
from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock
else:
raise ValueError(f"{params['sub_model_name']} does not exist.")
# Artefact from another file. Unfortunately was not removed and is a dangling layer in many of the saved models
# i.e. registered as a parameter, but never used
self.down_input_lower = nn.Sequential(
nn.Conv3d(in_channels=params['in_channels'], out_channels=4*params['out_channels'],
kernel_size=(4,4,4), padding=0, stride=4),
nn.GroupNorm(num_groups=4, num_channels=4*params['out_channels']),
nn.PReLU()
)
# Start model creation
# in_channels: 16, out_channels: 16
self.encoder_block_1 = EncoderBlock(params)
params['input'] = False
params['create_layer_1'] = True
params['in_channels'] = params['out_channels'] * 2 # 32
params['out_channels'] = params['out_channels'] * 2 # 32
self.encoder_block_2 = EncoderBlock(params)
params['create_layer_2'] = True
params['in_channels'] = params['out_channels'] * 2 # 64
params['out_channels'] = params['out_channels'] * 2 # 64
self.encoder_block_3 = EncoderBlock(params)
params['in_channels'] = params['out_channels'] * 2 # 128
params['out_channels'] = params['out_channels'] * 2 # 128
self.encoder_block_4 = EncoderBlock(params)
params['in_channels'] = params['out_channels'] * 2 # 256
params['out_channels'] = int(params['out_channels'] * 2) # 256
self.bottleneck_block = BottleNeck(params)
enc_channels = 128
params['in_channels'] = params['out_channels'] + enc_channels # 256 + 128
params['out_channels'] = params['out_channels'] # 256
self.decoder_block_4 = DecoderBlock(params)
enc_channels = int(enc_channels/2)
params['in_channels'] = int(params['out_channels']/2) + enc_channels # 128 + 64
params['out_channels'] = int(params['out_channels'] / 2) # 128
self.decoder_block_3 = DecoderBlock(params)
enc_channels = int(enc_channels/2)
params['in_channels'] = int(params['out_channels'] / 2) + enc_channels # 64 + 32
params['out_channels'] = int(params['out_channels'] / 2) # 64
params['create_layer_2'] = False
self.decoder_block_2 = DecoderBlock(params)
enc_channels = int(enc_channels/2)
params['in_channels'] = int(params['out_channels'] / 2) + enc_channels # 32 + 16
params['out_channels'] = int(params['out_channels'] / 2) # 32
params['create_layer_1'] = False
params['out'] = True
self.decoder_block_1 = DecoderBlock(params)
params['out'] = False
self.output_block = nn.Conv3d(in_channels=params['out_channels'], out_channels=params['num_classes'],
kernel_size = (1, 1, 1), stride = 1, padding = 0)
self.gpu_map = params['gpu_map']
def forward(self, x):
if self.training:
return self.train_forward(x)
else:
return self.eval_forward(x)
def train_forward(self, x):
"""
Standard VNet Architecture
"""
# Generate Random Coordinates if needed
if self.gen_random: # For usage by QuadNet
self.coords = make_rand_coords(self.input_shape, self.patch_size)
assert self.coords is not None
# Cropped Patch for the part of encoder
x_upper = x[..., self.coords[0]:self.coords[0] + self.patch_size[0],
self.coords[1]:self.coords[1] + self.patch_size[1],
self.coords[2]:self.coords[2] + self.patch_size[2]]
# Running Encoder side of network
x_upper = multi_gpu_check(self.gpu_map, 'encoder_block_1', x_upper)
x_upper_res_1, x_down_1 = self.encoder_block_1(x_upper)
x_down_1 = multi_gpu_check(self.gpu_map, 'encoder_block_2', x_down_1)
x_upper_res_2, x_down_2 = self.encoder_block_2(x_down_1)
x_down_2 = multi_gpu_check(self.gpu_map, 'encoder_block_3', x_down_2)
x_lower_res_3, x_down_3 = self.encoder_block_3(x_down_2)
x_down_3 = multi_gpu_check(self.gpu_map, 'encoder_block_4', x_down_3)
x_lower_res_4, x_down_4 = self.encoder_block_4(x_down_3)
# Running bottleneck
x_down_4 = multi_gpu_check(self.gpu_map, 'bottleneck_block', x_down_4)
x_bottleneck = self.bottleneck_block(x_down_4)
# Run decoder
x_lower_res_4, x_bottleneck = multi_gpu_check(self.gpu_map, 'decoder_block_4', x_lower_res_4, x_bottleneck)
x_up_4 = self.decoder_block_4(x_lower_res_4, x_bottleneck)
x_lower_res_3, x_up_4 = multi_gpu_check(self.gpu_map, 'decoder_block_3', x_lower_res_3, x_up_4)
x_up_3 = self.decoder_block_3(x_lower_res_3, x_up_4)
x_upper_res_2, x_up_3 = multi_gpu_check(self.gpu_map, 'decoder_block_2', x_upper_res_2, x_up_3)
x_up_2 = self.decoder_block_2(x_upper_res_2, x_up_3)
x_upper_res_1, x_up_2 = multi_gpu_check(self.gpu_map, 'decoder_block_1', x_upper_res_1, x_up_2)
x_last = self.decoder_block_1(x_upper_res_1, x_up_2)
x_last = multi_gpu_check(self.gpu_map, 'output_block', x_last)
out = self.output_block(x_last)
return out
def eval_forward(self, x):
"""
Standard VNet Architecture
"""
# Standard evaluation. No patch extraction
x_upper = multi_gpu_check(self.gpu_map, 'encoder_block_1', x)
x_upper_res_1, x_down_1 = self.encoder_block_1(x_upper)
x_down_1 = multi_gpu_check(self.gpu_map, 'encoder_block_2', x_down_1)
x_upper_res_2, x_down_2 = self.encoder_block_2(x_down_1)
x_down_2 = multi_gpu_check(self.gpu_map, 'encoder_block_3', x_down_2)
x_lower_res_3, x_down_3 = self.encoder_block_3(x_down_2)
x_down_3 = multi_gpu_check(self.gpu_map, 'encoder_block_4', x_down_3)
x_lower_res_4, x_down_4 = self.encoder_block_4(x_down_3)
# Running bottlenext and decoder
x_down_4 = multi_gpu_check(self.gpu_map, 'bottleneck_block', x_down_4)
x_bottleneck = self.bottleneck_block(x_down_4)
x_lower_res_4, x_bottleneck = multi_gpu_check(self.gpu_map, 'decoder_block_4', x_lower_res_4, x_bottleneck)
x_up_4 = self.decoder_block_4(x_lower_res_4, x_bottleneck)
x_lower_res_3, x_up_4 = multi_gpu_check(self.gpu_map, 'decoder_block_3', x_lower_res_3, x_up_4)
x_up_3 = self.decoder_block_3(x_lower_res_3, x_up_4)
x_upper_res_2, x_up_3 = multi_gpu_check(self.gpu_map, 'decoder_block_2', x_upper_res_2, x_up_3)
x_up_2 = self.decoder_block_2(x_upper_res_2, x_up_3)
x_upper_res_1, x_up_2 = multi_gpu_check(self.gpu_map, 'decoder_block_1', x_upper_res_1, x_up_2)
x_last = self.decoder_block_1(x_upper_res_1, x_up_2)
x_last = multi_gpu_check(self.gpu_map, 'output_block', x_last)
out = self.output_block(x_last)
return out
class RCVNetAttention(RCVNet):
def __init__(self, params):
super(RCVNet, self).__init__()
from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, \
DecoderBlock as AttDecoderBlock
self.coords = None
self.input_shape = params['input_shape']
self.patch_size = params['patch_size']
self.gen_random = params['gen_random']
self.down_input_lower = nn.Sequential(
nn.Conv3d(in_channels=params['in_channels'], out_channels=4*params['out_channels'],
kernel_size=(4,4,4), padding=0, stride=4),
nn.GroupNorm(num_groups=4, num_channels=4*params['out_channels']),
nn.PReLU()
)
# in_channels: 16, out_channels: 16
self.encoder_block_1 = AttEncoderBlock(params)
params['input'] = False
params['create_layer_1'] = True
params['in_channels'] = params['out_channels'] * 2 # 32
params['out_channels'] = params['out_channels'] * 2 # 32
self.encoder_block_2 = AttEncoderBlock(params)
params['create_layer_2'] = True
params['in_channels'] = params['out_channels'] * 2 # 64
params['out_channels'] = params['out_channels'] * 2 # 64
self.encoder_block_3 = AttEncoderBlock(params)
params['in_channels'] = params['out_channels'] * 2 # 128
params['out_channels'] = params['out_channels'] * 2 # 128
self.encoder_block_4 = AttEncoderBlock(params)
params['in_channels'] = params['out_channels'] * 2 # 256
params['out_channels'] = int(params['out_channels'] * 2) # 256
self.bottleneck_block = AttBottleNeck(params)
enc_channels = 128
params['in_channels'] = params['out_channels'] + enc_channels # 256 + 128
params['F_g'], params['F_l'], params['F_int'] = (256, 128, 128)
params['out_channels'] = params['out_channels'] # 256
self.decoder_block_4 = AttDecoderBlock(params)
enc_channels = int(enc_channels/2)
params['in_channels'] = int(params['out_channels']/2) + enc_channels # 128 + 64
params['out_channels'] = int(params['out_channels'] / 2) # 128
params['F_g'], params['F_l'], params['F_int'] = (128, 64, 64)
self.decoder_block_3 = AttDecoderBlock(params)
enc_channels = int(enc_channels/2)
params['in_channels'] = int(params['out_channels'] / 2) + enc_channels # 64 + 32
params['out_channels'] = int(params['out_channels'] / 2) # 64
params['F_g'], params['F_l'], params['F_int'] = (64, 32, 32)
params['create_layer_2'] = False
self.decoder_block_2 = AttDecoderBlock(params)
enc_channels = int(enc_channels/2)
params['in_channels'] = int(params['out_channels'] / 2) + enc_channels # 32 + 16
params['out_channels'] = int(params['out_channels'] / 2) # 32
params['F_g'], params['F_l'], params['F_int'] = (32, 16, 16)
params['create_layer_1'] = False
params['out'] = True
self.decoder_block_1 = AttDecoderBlock(params)
params['out'] = False
self.output_block = nn.Conv3d(in_channels=params['out_channels'], out_channels=params['num_classes'],
kernel_size = (1, 1, 1), stride = 1, padding = 0)
if __name__ == "__main__":
# TEST CODE [RUN THIS TO VERIFY MODELS]
params = {'in_channels': 1,
'out_channels': 16,
'create_layer_1': False,
'create_layer_2': False,
'kernel_size': (5, 5, 5),
'input_shape': (64,64,64),
'patch_size': (64,64,64),
'num_classes': 40,
'out': False,
'input': True,
# 'F_g': None,
# 'F_l': None,
# 'F_int': None
'gen_random' : True,
'gpu_map':{}
}
m = RCVNet(params=params).cuda()
# m.eval()
# m = CompetitiveEncoderBlockInput(params=params).cuda()
try:
from torchsummary import summary
# print([l for l in m.named_children()])
summary(m, input_size=(1,64,64,64))
except ImportError:
pass
#
# print([l for l in m.decoder_block_1.parameters()])
# print([l.device() for _, l in m.named_children()])
|
[
"torch.nn.PReLU",
"numpy.random.random_sample",
"torch.nn.Conv3d",
"model.VNetAttention.EncoderBlock",
"model.VNetAttention.BottleNeck",
"torch.nn.GroupNorm",
"model.VNetSE.DecoderBlock",
"torchsummary.summary",
"model.VNetSE.BottleNeck",
"model.VNetSE.EncoderBlock",
"torch.device",
"model.VNetAttention.DecoderBlock"
] |
[((3296, 3316), 'model.VNetSE.EncoderBlock', 'EncoderBlock', (['params'], {}), '(params)\n', (3308, 3316), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((3550, 3570), 'model.VNetSE.EncoderBlock', 'EncoderBlock', (['params'], {}), '(params)\n', (3562, 3570), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((3772, 3792), 'model.VNetSE.EncoderBlock', 'EncoderBlock', (['params'], {}), '(params)\n', (3784, 3792), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((3956, 3976), 'model.VNetSE.EncoderBlock', 'EncoderBlock', (['params'], {}), '(params)\n', (3968, 3976), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((4146, 4164), 'model.VNetSE.BottleNeck', 'BottleNeck', (['params'], {}), '(params)\n', (4156, 4164), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((4368, 4388), 'model.VNetSE.DecoderBlock', 'DecoderBlock', (['params'], {}), '(params)\n', (4380, 4388), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((4624, 4644), 'model.VNetSE.DecoderBlock', 'DecoderBlock', (['params'], {}), '(params)\n', (4636, 4644), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((4921, 4941), 'model.VNetSE.DecoderBlock', 'DecoderBlock', (['params'], {}), '(params)\n', (4933, 4941), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((5246, 5266), 'model.VNetSE.DecoderBlock', 'DecoderBlock', (['params'], {}), '(params)\n', (5258, 5266), False, 'from model.VNetSE import EncoderBlock, BottleNeck, DecoderBlock\n'), ((5326, 5456), 'torch.nn.Conv3d', 'nn.Conv3d', ([], {'in_channels': "params['out_channels']", 'out_channels': "params['num_classes']", 'kernel_size': '(1, 1, 1)', 'stride': '(1)', 'padding': '(0)'}), "(in_channels=params['out_channels'], out_channels=params[\n 'num_classes'], kernel_size=(1, 1, 1), stride=1, padding=0)\n", (5335, 5456), True, 'import torch.nn as nn\n'), ((10418, 10441), 'model.VNetAttention.EncoderBlock', 'AttEncoderBlock', (['params'], {}), '(params)\n', (10433, 10441), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((10675, 10698), 'model.VNetAttention.EncoderBlock', 'AttEncoderBlock', (['params'], {}), '(params)\n', (10690, 10698), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((10900, 10923), 'model.VNetAttention.EncoderBlock', 'AttEncoderBlock', (['params'], {}), '(params)\n', (10915, 10923), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((11087, 11110), 'model.VNetAttention.EncoderBlock', 'AttEncoderBlock', (['params'], {}), '(params)\n', (11102, 11110), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((11280, 11301), 'model.VNetAttention.BottleNeck', 'AttBottleNeck', (['params'], {}), '(params)\n', (11293, 11301), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((11577, 11600), 'model.VNetAttention.DecoderBlock', 'AttDecoderBlock', (['params'], {}), '(params)\n', (11592, 11600), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((11906, 11929), 'model.VNetAttention.DecoderBlock', 'AttDecoderBlock', (['params'], {}), '(params)\n', (11921, 11929), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((12275, 12298), 'model.VNetAttention.DecoderBlock', 'AttDecoderBlock', (['params'], {}), '(params)\n', (12290, 12298), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((12672, 12695), 'model.VNetAttention.DecoderBlock', 'AttDecoderBlock', (['params'], {}), '(params)\n', (12687, 12695), True, 'from model.VNetAttention import EncoderBlock as AttEncoderBlock, BottleNeck as AttBottleNeck, DecoderBlock as AttDecoderBlock\n'), ((12755, 12885), 'torch.nn.Conv3d', 'nn.Conv3d', ([], {'in_channels': "params['out_channels']", 'out_channels': "params['num_classes']", 'kernel_size': '(1, 1, 1)', 'stride': '(1)', 'padding': '(0)'}), "(in_channels=params['out_channels'], out_channels=params[\n 'num_classes'], kernel_size=(1, 1, 1), stride=1, padding=0)\n", (12764, 12885), True, 'import torch.nn as nn\n'), ((13741, 13779), 'torchsummary.summary', 'summary', (['m'], {'input_size': '(1, 64, 64, 64)'}), '(m, input_size=(1, 64, 64, 64))\n', (13748, 13779), False, 'from torchsummary import summary\n'), ((397, 412), 'numpy.random.random_sample', 'random_sample', ([], {}), '()\n', (410, 412), False, 'from numpy.random import random_sample\n'), ((2912, 3046), 'torch.nn.Conv3d', 'nn.Conv3d', ([], {'in_channels': "params['in_channels']", 'out_channels': "(4 * params['out_channels'])", 'kernel_size': '(4, 4, 4)', 'padding': '(0)', 'stride': '(4)'}), "(in_channels=params['in_channels'], out_channels=4 * params[\n 'out_channels'], kernel_size=(4, 4, 4), padding=0, stride=4)\n", (2921, 3046), True, 'import torch.nn as nn\n'), ((3081, 3148), 'torch.nn.GroupNorm', 'nn.GroupNorm', ([], {'num_groups': '(4)', 'num_channels': "(4 * params['out_channels'])"}), "(num_groups=4, num_channels=4 * params['out_channels'])\n", (3093, 3148), True, 'import torch.nn as nn\n'), ((3164, 3174), 'torch.nn.PReLU', 'nn.PReLU', ([], {}), '()\n', (3172, 3174), True, 'import torch.nn as nn\n'), ((10066, 10200), 'torch.nn.Conv3d', 'nn.Conv3d', ([], {'in_channels': "params['in_channels']", 'out_channels': "(4 * params['out_channels'])", 'kernel_size': '(4, 4, 4)', 'padding': '(0)', 'stride': '(4)'}), "(in_channels=params['in_channels'], out_channels=4 * params[\n 'out_channels'], kernel_size=(4, 4, 4), padding=0, stride=4)\n", (10075, 10200), True, 'import torch.nn as nn\n'), ((10235, 10302), 'torch.nn.GroupNorm', 'nn.GroupNorm', ([], {'num_groups': '(4)', 'num_channels': "(4 * params['out_channels'])"}), "(num_groups=4, num_channels=4 * params['out_channels'])\n", (10247, 10302), True, 'import torch.nn as nn\n'), ((10318, 10328), 'torch.nn.PReLU', 'nn.PReLU', ([], {}), '()\n', (10326, 10328), True, 'import torch.nn as nn\n'), ((828, 857), 'torch.device', 'torch.device', (['gpu_map[l_name]'], {}), '(gpu_map[l_name])\n', (840, 857), False, 'import torch\n')]
|
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import pytest
import numpy as np
import scipy.sparse as sparse
import cntk as C
csr = sparse.csr_matrix
from ..core import *
from cntk.tests.test_utils import *
from cntk.ops.tests.ops_test_utils import compare_lists_of_np_arrays, cntk_device
from cntk import *
from cntk.internal import _value_as_sequence_or_array
from cntk import asarray, asvalue
from cntk.tests.test_utils import _to_dense, _to_csr
test_numbers = [4., 5, 6., 7., 8.]
test_array = AA(test_numbers, dtype=np.float32)
def _dense_value_to_ndarray_test(data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes):
shape = (5,)
if num_of_dynamic_axes == 2:
var = sequence.input(shape)
elif num_of_dynamic_axes == 1:
var = input(shape)
else:
var = input(shape, dynamic_axes=[])
# conversion array -> value
val = asvalue(var, data)
assert val.shape == expected_value_shape
# conversion value -> array
dense_result = _value_as_sequence_or_array(val, var)
if isinstance(dense_result, list):
result_shapes = [AA(v).shape for v in dense_result]
else:
result_shapes = dense_result.shape
assert result_shapes == expected_array_shapes
def _sparse_value_to_csr_test(data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes):
shape = (3,)
if num_of_dynamic_axes == 2:
var = sequence.input(shape, is_sparse=True)
elif num_of_dynamic_axes == 1:
var = input(shape, is_sparse=True)
else:
var = input(shape, is_sparse=True, dynamic_axes=[])
# conversion csr array -> value
val = asvalue(var, data)
assert val.shape == expected_value_shape
# conversion value -> csr array
csr_result = val.as_sequences(var)
csr_result_shapes = [v.shape for v in csr_result]
assert csr_result_shapes == expected_csr_shapes
DENSE_CONFIGURATIONS = [
# (dense data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes)
([[test_array],
[test_array, test_array]], 2, (2,2,5), [(1,5),(2,5)]),
([test_array,
test_array], 2, (2, 1, 5), [(1,5), (1,5)]),
([[test_array],
[test_array]], 2, (2, 1, 5), [(1,5), (1,5)]),
(test_array, 2, (5,), [(), (), (), (), ()]),
(AA([test_numbers], dtype=np.float32), 2, (1,5), [(5,)]),
(AA([test_numbers, test_numbers], dtype=np.float32),
2, (2, 5), [(5,), (5,)]),
([test_array,
test_array], 1, (2,1,5), (2,1,5)),
([[test_array],
[test_array]], 1, (2,1,5), (2,1,5)),
(AA([test_numbers, test_numbers], dtype=np.float32), 1, (2,5), (2,5)),
(AA([test_numbers], dtype=np.float32), 1, (1,5), (1,5)),
([test_array,
test_array], 0, (2,5), (2,5)),
(AA([test_numbers, test_numbers], dtype=np.float32), 0, (2,5), (2,5)),
(test_array, 0, (5,), (5,)),
]
@pytest.mark.parametrize("data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes", DENSE_CONFIGURATIONS)
def test_dense_value_to_ndarray(data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes):
_dense_value_to_ndarray_test(
data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes)
SPARSE_ARRAYS = [
# (sparse data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes)
([csr([[1.,0.,2.], [2.,3.,0.]]),
csr([5.,0.,1.])], 2, (2, 2, 3), [(2,3),(1,3)]),
([csr([1,0,2]),
csr([5,0,1])], 2, (2, 1, 3),[(1,3),(1,3)]),
([csr([[1,0,2],[2,3,4]])], 2, (1, 2, 3), [(2,3)]),
([csr([1,0,2]),
csr([5,0,1])], 1, (2, 1, 3), [(1,3),(1,3)]),
([csr([[1,0,2], [2,3,0]]),
csr([[5,0,1], [2,3,0]])], 1, (2, 2, 3), [(2,3),(2,3)]),
([csr([[1,0,2],[2,3,4]])], 1, (1, 2, 3), [(2,3)]),
(csr([1,0,2]), 0, (1, 3), [(1,3)]),
]
@pytest.mark.parametrize("data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes", SPARSE_ARRAYS)
def test_sparse_value_to_csr(data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes):
_sparse_value_to_csr_test(
data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes)
DENSE_FAILING_CONFIGURATIONS = [
# (dense data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes)
([[test_array],
[test_array, test_array]], 0, (2,2,5), [(1,5),(2,5)]),
# TODO: enable once check is implemented
#([[test_array],
# [test_array]], 0, (2, 1, 5), [(1, 5),(1, 5)]),
#([[test_array],
# [test_array, test_array]], 1, (2,2,5), [(1,5),(2,5)]),
]
SPARSE_FAILING_CONFIGURATIONS = [
# (sparse data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes)
# TODO: Following configurations are not meant to fail as expected
#(csr([[1,0,2], [2,3,0]]), 2, (1, 3), [(1,3)]),
#(csr([[1,0,2],[2,3,4]]), 2, (2, 1, 3), [(1,3),(1,3)]),
#(csr([[1,0,2], [2,3,0]]), 1, (1, 3), [(1,3)]),
([csr([[1,0,2],[2,3,4]])], 0, (1, 2, 3), [(2,3)]),
([csr([[1,0,2], [2,3,0]]),
csr([5,0,1])], 0, (2, 2, 3), [(2,3),(1,3)]),
([csr([1,0,2])], 0, (1, 3), [(1,3)]),
# TODO: enable once check is implemented
#([csr([[1,0,2], [2,3,0]]),
# csr([5,0,1])], 1, (2, 2, 3), [(2,3),(1,3)]),
]
@pytest.mark.parametrize("data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes", DENSE_FAILING_CONFIGURATIONS)
def test_dense_failing_value_to_ndarray(data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes):
with pytest.raises(ValueError):
_dense_value_to_ndarray_test(
data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes)
@pytest.mark.parametrize("data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes", SPARSE_FAILING_CONFIGURATIONS)
def test_sparse_failing_value_to_csr(data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes):
with pytest.raises(ValueError):
_sparse_value_to_csr_test(
data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes)
def test_asarray_method():
shape = (3,)
var = sequence.input(shape, is_sparse=True)
data = [csr([[1,0,2], [5,0,1]])]
# conversion array -> value
val = asvalue(var, data)
as_csr = val.as_sequences(var)
for a, d in zip(as_csr, data):
assert (a==d).toarray().all()
var = C.input(shape, is_sparse=True)
data = csr([[1,0,2], [5,0,1]])
# conversion array -> value
val = asvalue(var, data)
for v in [
val, # Value
super(Value, val), # cntk_py.Value
val.data, # NDArrayView
super(NDArrayView, val.data), # cntk_py.NDArrayView
]:
as_csr = v.asarray()
for a, d in zip(as_csr, data):
assert (a==d).toarray().all()
def test_value_properties():
ndav = NDArrayView((1, 2, 3), np.float32, device=C.cpu())
val = Value(batch=ndav)
dev = val.device
assert isinstance(dev, DeviceDescriptor)
assert str(dev) == 'CPU'
assert val.is_read_only == False
assert val.is_sparse == False
assert val.dtype == np.float32
def test_ndarray_properties():
ndav = NDArrayView((2, 3), np.float32, device=C.cpu())
dev = ndav.device
assert isinstance(dev, DeviceDescriptor)
assert str(dev) == 'CPU'
assert ndav.is_read_only == False
assert ndav.is_sparse == False
assert ndav.dtype == np.float32
def test_ndarrayview_from_csr(device_id):
dev = cntk_device(device_id)
data = [[[0, 1, 1], [0, 1, 0]], [[1, 0, 0], [1, 0, 1]]]
csr_data = _to_csr(data)
ndarrayview = NDArrayView.from_csr(csr_data, shape=(2, 2, 3))
assert np.array_equal(_to_dense(ndarrayview), data)
with pytest.raises(ValueError):
ndarrayview = NDArrayView.from_csr(csr_data, shape=(3, 2, 3))
with pytest.raises(ValueError):
ndarrayview = NDArrayView.from_csr(csr_data, shape=(2, 2, 4))
def test_2d_sparse_sequences_value(device_id):
dev = cntk_device(device_id)
seq1_data = [[[0, 1, 1], [0, 1, 0]], [[1, 0, 0], [1, 0, 1]]]
csr_seq1 = _to_csr(seq1_data)
ndarrayview1 = NDArrayView.from_csr(csr_seq1, shape=(2, 2, 3), device=cpu())
seq2_data = [[0, 1, 1], [1, 1, 0]]
csr_seq2 = _to_csr(seq2_data)
ndarrayview2 = NDArrayView.from_csr(csr_seq2, shape=(1, 2, 3), device=cpu())
x = sequence.input((2, 3))
sequence_value = Value.create(x, [ndarrayview1, ndarrayview2], device=dev)
assert np.array_equal(_to_dense(sequence_value.data), [seq1_data, [seq2_data, [[0, 0, 0], [0, 0, 0]]]])
def test_as_shape_to_1d(device_id):
dev = cntk_device(device_id)
x = C.input(1)
w_1d = C.parameter((1), device=dev)
assert np.array_equal(w_1d.value, [0])
op = x * 0.1
value = op.eval({x:np.asarray([[1]], dtype=np.float32)}, as_numpy=False, device=dev)
value = value.data.as_shape(value.data.shape[1:])
w_1d.value = value
assert np.array_equal(w_1d.value, np.asarray([0.1], dtype=np.float32))
def test_is_valid(device_id):
a = C.input((2,), needs_gradient=True)
b = a*a
a0 = np.array([1,2],dtype=np.float32)
g = b.grad({a:a0}, as_numpy=False)
g2 = b.grad({a:a0}, as_numpy=False)
assert (g.is_valid == False)
assert (g2.is_valid == True)
|
[
"cntk.ops.tests.ops_test_utils.cntk_device",
"cntk.input",
"cntk.asvalue",
"cntk.tests.test_utils._to_csr",
"numpy.asarray",
"cntk.cpu",
"cntk.parameter",
"pytest.raises",
"numpy.array",
"cntk.tests.test_utils._to_dense",
"numpy.array_equal",
"pytest.mark.parametrize",
"cntk.internal._value_as_sequence_or_array"
] |
[((3041, 3169), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes"""', 'DENSE_CONFIGURATIONS'], {}), "(\n 'data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes',\n DENSE_CONFIGURATIONS)\n", (3064, 3169), False, 'import pytest\n'), ((3964, 4083), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes"""', 'SPARSE_ARRAYS'], {}), "(\n 'data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes',\n SPARSE_ARRAYS)\n", (3987, 4083), False, 'import pytest\n'), ((5356, 5492), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes"""', 'DENSE_FAILING_CONFIGURATIONS'], {}), "(\n 'data, num_of_dynamic_axes, expected_value_shape, expected_array_shapes',\n DENSE_FAILING_CONFIGURATIONS)\n", (5379, 5492), False, 'import pytest\n'), ((5757, 5892), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes"""', 'SPARSE_FAILING_CONFIGURATIONS'], {}), "(\n 'data, num_of_dynamic_axes, expected_value_shape, expected_csr_shapes',\n SPARSE_FAILING_CONFIGURATIONS)\n", (5780, 5892), False, 'import pytest\n'), ((1078, 1096), 'cntk.asvalue', 'asvalue', (['var', 'data'], {}), '(var, data)\n', (1085, 1096), False, 'from cntk import asarray, asvalue\n'), ((1194, 1231), 'cntk.internal._value_as_sequence_or_array', '_value_as_sequence_or_array', (['val', 'var'], {}), '(val, var)\n', (1221, 1231), False, 'from cntk.internal import _value_as_sequence_or_array\n'), ((1836, 1854), 'cntk.asvalue', 'asvalue', (['var', 'data'], {}), '(var, data)\n', (1843, 1854), False, 'from cntk import asarray, asvalue\n'), ((6319, 6337), 'cntk.asvalue', 'asvalue', (['var', 'data'], {}), '(var, data)\n', (6326, 6337), False, 'from cntk import asarray, asvalue\n'), ((6457, 6487), 'cntk.input', 'C.input', (['shape'], {'is_sparse': '(True)'}), '(shape, is_sparse=True)\n', (6464, 6487), True, 'import cntk as C\n'), ((6566, 6584), 'cntk.asvalue', 'asvalue', (['var', 'data'], {}), '(var, data)\n', (6573, 6584), False, 'from cntk import asarray, asvalue\n'), ((7578, 7600), 'cntk.ops.tests.ops_test_utils.cntk_device', 'cntk_device', (['device_id'], {}), '(device_id)\n', (7589, 7600), False, 'from cntk.ops.tests.ops_test_utils import compare_lists_of_np_arrays, cntk_device\n'), ((7676, 7689), 'cntk.tests.test_utils._to_csr', '_to_csr', (['data'], {}), '(data)\n', (7683, 7689), False, 'from cntk.tests.test_utils import _to_dense, _to_csr\n'), ((8085, 8107), 'cntk.ops.tests.ops_test_utils.cntk_device', 'cntk_device', (['device_id'], {}), '(device_id)\n', (8096, 8107), False, 'from cntk.ops.tests.ops_test_utils import compare_lists_of_np_arrays, cntk_device\n'), ((8188, 8206), 'cntk.tests.test_utils._to_csr', '_to_csr', (['seq1_data'], {}), '(seq1_data)\n', (8195, 8206), False, 'from cntk.tests.test_utils import _to_dense, _to_csr\n'), ((8342, 8360), 'cntk.tests.test_utils._to_csr', '_to_csr', (['seq2_data'], {}), '(seq2_data)\n', (8349, 8360), False, 'from cntk.tests.test_utils import _to_dense, _to_csr\n'), ((8708, 8730), 'cntk.ops.tests.ops_test_utils.cntk_device', 'cntk_device', (['device_id'], {}), '(device_id)\n', (8719, 8730), False, 'from cntk.ops.tests.ops_test_utils import compare_lists_of_np_arrays, cntk_device\n'), ((8739, 8749), 'cntk.input', 'C.input', (['(1)'], {}), '(1)\n', (8746, 8749), True, 'import cntk as C\n'), ((8761, 8787), 'cntk.parameter', 'C.parameter', (['(1)'], {'device': 'dev'}), '(1, device=dev)\n', (8772, 8787), True, 'import cntk as C\n'), ((8801, 8832), 'numpy.array_equal', 'np.array_equal', (['w_1d.value', '[0]'], {}), '(w_1d.value, [0])\n', (8815, 8832), True, 'import numpy as np\n'), ((9132, 9166), 'cntk.input', 'C.input', (['(2,)'], {'needs_gradient': '(True)'}), '((2,), needs_gradient=True)\n', (9139, 9166), True, 'import cntk as C\n'), ((9188, 9222), 'numpy.array', 'np.array', (['[1, 2]'], {'dtype': 'np.float32'}), '([1, 2], dtype=np.float32)\n', (9196, 9222), True, 'import numpy as np\n'), ((5606, 5631), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5619, 5631), False, 'import pytest\n'), ((6001, 6026), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6014, 6026), False, 'import pytest\n'), ((7782, 7804), 'cntk.tests.test_utils._to_dense', '_to_dense', (['ndarrayview'], {}), '(ndarrayview)\n', (7791, 7804), False, 'from cntk.tests.test_utils import _to_dense, _to_csr\n'), ((7822, 7847), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7835, 7847), False, 'import pytest\n'), ((7929, 7954), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7942, 7954), False, 'import pytest\n'), ((8579, 8609), 'cntk.tests.test_utils._to_dense', '_to_dense', (['sequence_value.data'], {}), '(sequence_value.data)\n', (8588, 8609), False, 'from cntk.tests.test_utils import _to_dense, _to_csr\n'), ((9055, 9090), 'numpy.asarray', 'np.asarray', (['[0.1]'], {'dtype': 'np.float32'}), '([0.1], dtype=np.float32)\n', (9065, 9090), True, 'import numpy as np\n'), ((6980, 6987), 'cntk.cpu', 'C.cpu', ([], {}), '()\n', (6985, 6987), True, 'import cntk as C\n'), ((7305, 7312), 'cntk.cpu', 'C.cpu', ([], {}), '()\n', (7310, 7312), True, 'import cntk as C\n'), ((8874, 8909), 'numpy.asarray', 'np.asarray', (['[[1]]'], {'dtype': 'np.float32'}), '([[1]], dtype=np.float32)\n', (8884, 8909), True, 'import numpy as np\n')]
|
# MIT License
#
# Copyright (c) 2019-2021 Tskit Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Test cases for generating genotypes/haplotypes.
"""
import itertools
import random
import textwrap
import msprime
import numpy as np
import pytest
import tests
import tests.test_wright_fisher as wf
import tests.tsutil as tsutil
import tskit
from tests.test_highlevel import get_example_tree_sequences
from tskit import exceptions
# ↑ See https://github.com/tskit-dev/tskit/issues/1804 for when
# we can remove this.
# TODO replace this with a call to
# example_tree_sequences(discrete_genome=True, snps_only=True)
@tests.cached_example
def get_example_discrete_genome_tree_sequences():
ret = []
for ts in get_example_tree_sequences():
if ts.discrete_genome:
snps = all(len(site.ancestral_state) == 1 for site in ts.sites()) and all(
len(mut.derived_state) == 1 for mut in ts.mutations()
)
if snps:
ret.append(ts)
return ret
def naive_get_ancestral_haplotypes(ts):
"""
Simple implementation using tree traversals. Note that this definition
won't work when we have topology that's not reachable from a root,
but this seems more trouble than it's worth dealing with.
"""
A = np.zeros((ts.num_nodes, ts.num_sites), dtype=np.int8)
A[:] = tskit.MISSING_DATA
for t in ts.trees():
for site in t.sites():
alleles = {site.ancestral_state: 0}
for u in t.nodes():
A[u, site.id] = 0
j = 1
for mutation in site.mutations:
if mutation.derived_state not in alleles:
alleles[mutation.derived_state] = j
j += 1
for u in t.nodes(mutation.node):
A[u, site.id] = alleles[mutation.derived_state]
return A
class TestGetAncestralHaplotypes:
"""
Tests for the engine to the actual ancestors from a simulation.
"""
def verify(self, ts):
A = naive_get_ancestral_haplotypes(ts)
# To detect missing data in ancestors we must set all nodes
# to be samples
tables = ts.dump_tables()
nodes = tables.nodes
flags = nodes.flags[:]
flags[:] = 1
nodes.set_columns(time=nodes.time, flags=flags)
ts = tables.tree_sequence()
B = ts.genotype_matrix().T
assert np.array_equal(A, B)
def test_single_tree(self):
ts = msprime.simulate(5, mutation_rate=1, random_seed=234)
self.verify(ts)
def test_many_trees(self):
ts = msprime.simulate(
8, recombination_rate=10, mutation_rate=10, random_seed=234
)
assert ts.num_trees > 1
assert ts.num_sites > 1
self.verify(ts)
def test_single_tree_jukes_cantor(self):
ts = msprime.simulate(6, random_seed=1, mutation_rate=1)
ts = tsutil.jukes_cantor(ts, 20, 1, seed=10)
self.verify(ts)
def test_single_tree_multichar_mutations(self):
ts = msprime.simulate(6, random_seed=1, mutation_rate=1)
ts = tsutil.insert_multichar_mutations(ts)
self.verify(ts)
def test_many_trees_infinite_sites(self):
ts = msprime.simulate(6, recombination_rate=2, mutation_rate=2, random_seed=1)
assert ts.num_sites > 0
assert ts.num_trees > 2
self.verify(ts)
def test_wright_fisher_initial_generation(self):
tables = wf.wf_sim(
6, 5, seed=3, deep_history=True, initial_generation_samples=True, num_loci=2
)
tables.sort()
tables.simplify()
ts = msprime.mutate(tables.tree_sequence(), rate=0.08, random_seed=2)
assert ts.num_sites > 0
self.verify(ts)
def test_wright_fisher_simplified(self):
tables = wf.wf_sim(
9,
10,
seed=1,
deep_history=True,
initial_generation_samples=False,
num_loci=5,
)
tables.sort()
ts = tables.tree_sequence().simplify()
ts = msprime.mutate(ts, rate=0.2, random_seed=1234)
assert ts.num_sites > 0
self.verify(ts)
def test_empty_ts(self):
tables = tskit.TableCollection(1.0)
for _ in range(10):
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
ts = tables.tree_sequence()
self.verify(ts)
def isolated_samples_genotype_matrix(ts):
"""
Returns the genotype matrix for the specified tree sequence
where isolated samples are marked with MISSING_DATA.
"""
G = ts.genotype_matrix()
samples = ts.samples()
sample_index_map = np.zeros(ts.num_nodes, dtype=int) - 1
for index, sample in enumerate(samples):
sample_index_map[sample] = index
for tree in ts.trees():
for site in tree.sites():
for root in tree.roots:
# An isolated sample is any root that has no children.
if tree.left_child(root) == -1:
assert sample_index_map[root] != -1
G[site.id, sample_index_map[root]] = -1
return G
class TestVariantGenerator:
"""
Tests the variants() method to ensure the output is consistent.
"""
def get_tree_sequence(self):
ts = msprime.simulate(
10, length=10, recombination_rate=1, mutation_rate=10, random_seed=3
)
assert ts.get_num_mutations() > 10
return ts
def test_as_bytes(self):
ts = self.get_tree_sequence()
n = ts.get_sample_size()
m = ts.get_num_mutations()
A = np.zeros((m, n), dtype="u1")
B = np.zeros((m, n), dtype="u1")
for variant in ts.variants():
A[variant.index] = variant.genotypes
for variant in ts.variants(as_bytes=True):
assert isinstance(variant.genotypes, bytes)
B[variant.index] = np.frombuffer(variant.genotypes, np.uint8) - ord("0")
assert np.all(A == B)
bytes_variants = list(ts.variants(as_bytes=True))
for j, variant in enumerate(bytes_variants):
assert j == variant.index
row = np.frombuffer(variant.genotypes, np.uint8) - ord("0")
assert np.all(A[j] == row)
def test_as_bytes_fails(self):
ts = tsutil.insert_multichar_mutations(self.get_tree_sequence())
with pytest.raises(ValueError):
list(ts.variants(as_bytes=True))
def test_dtype(self):
ts = self.get_tree_sequence()
for var in ts.variants():
assert var.genotypes.dtype == np.int8
def test_dtype_conversion(self):
# Check if we hit any issues if we assume the variants are uint8
# as they were prior to version 0.2.0
ts = self.get_tree_sequence()
G = ts.genotype_matrix().astype(np.uint8)
assert G.dtype == np.uint8
for var in ts.variants():
assert np.array_equal(G[var.index], var.genotypes)
assert np.all(G[var.index] == var.genotypes)
assert [var.alleles[g] for g in var.genotypes] == [
var.alleles[g] for g in G[var.index]
]
G[var.index, :] = var.genotypes
assert np.array_equal(G[var.index], var.genotypes)
def test_multichar_alleles(self):
ts = tsutil.insert_multichar_mutations(self.get_tree_sequence())
for var in ts.variants():
assert len(var.alleles) == 2
assert var.site.ancestral_state == var.alleles[0]
assert var.site.mutations[0].derived_state == var.alleles[1]
assert all(0 <= var.genotypes)
assert all(var.genotypes <= 1)
def test_many_alleles(self):
ts = self.get_tree_sequence()
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
# This gives us a total of 360 permutations.
alleles = list(map("".join, itertools.permutations("ABCDEF", 4)))
assert len(alleles) > 127
tables.sites.add_row(0, alleles[0])
parent = -1
num_alleles = 1
for allele in alleles[1:]:
ts = tables.tree_sequence()
if num_alleles > 127:
with pytest.raises(exceptions.LibraryError):
next(ts.variants())
else:
var = next(ts.variants())
assert not var.has_missing_data
assert var.num_alleles == num_alleles
assert len(var.alleles) == num_alleles
assert list(var.alleles) == alleles[:num_alleles]
assert var.alleles[var.genotypes[0]] == alleles[num_alleles - 1]
for u in ts.samples():
if u != 0:
assert var.alleles[var.genotypes[u]] == alleles[0]
tables.mutations.add_row(0, 0, allele, parent=parent)
parent += 1
num_alleles += 1
def test_many_alleles_missing_data(self):
ts = self.get_tree_sequence()
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
# Add an isolated sample
tables.nodes.add_row(flags=1, time=0)
# This gives us a total of 360 permutations.
alleles = list(map("".join, itertools.permutations("ABCDEF", 4)))
assert len(alleles) > 127
tables.sites.add_row(0, alleles[0])
parent = -1
num_alleles = 1
for allele in alleles[1:]:
ts = tables.tree_sequence()
if num_alleles > 127:
with pytest.raises(exceptions.LibraryError):
next(ts.variants())
else:
var = next(ts.variants())
assert var.has_missing_data
assert var.num_alleles == num_alleles
assert len(var.alleles) == num_alleles + 1
assert list(var.alleles)[:-1] == alleles[:num_alleles]
assert var.alleles[-1] is None
assert var.alleles[var.genotypes[0]] == alleles[num_alleles - 1]
assert var.genotypes[-1] == -1
samples = ts.samples()
for u in samples[:-1]:
if u != 0:
assert var.alleles[var.genotypes[u]] == alleles[0]
tables.mutations.add_row(0, 0, allele, parent=parent)
parent += 1
num_alleles += 1
def test_site_information(self):
ts = self.get_tree_sequence()
for site, variant in zip(ts.sites(), ts.variants()):
assert site.position == variant.position
assert site == variant.site
def test_no_mutations(self):
ts = msprime.simulate(10)
assert ts.get_num_mutations() == 0
variants = list(ts.variants())
assert len(variants) == 0
def test_genotype_matrix(self):
ts = self.get_tree_sequence()
G = np.empty((ts.num_sites, ts.num_samples), dtype=np.int8)
for v in ts.variants():
G[v.index, :] = v.genotypes
G2 = ts.genotype_matrix()
assert np.array_equal(G, G2)
assert G2.dtype == np.int8
def test_recurrent_mutations_over_samples(self):
ts = self.get_tree_sequence()
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
num_sites = 5
for j in range(num_sites):
tables.sites.add_row(
position=j * ts.sequence_length / num_sites, ancestral_state="0"
)
for u in range(ts.sample_size):
tables.mutations.add_row(site=j, node=u, derived_state="1")
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == num_sites
for site, variant in zip(ts.sites(), variants):
assert site.position == variant.position
assert site == variant.site
assert site.id == variant.index
assert variant.alleles == ("0", "1")
assert np.all(variant.genotypes == np.ones(ts.sample_size))
def test_silent_mutations(self):
ts = self.get_tree_sequence()
tree = next(ts.trees())
tables = ts.dump_tables()
for u in tree.nodes():
for sample in tree.samples(u):
if sample != u:
tables.sites.clear()
tables.mutations.clear()
site = tables.sites.add_row(position=0, ancestral_state="0")
tables.mutations.add_row(site=site, node=u, derived_state="1")
tables.mutations.add_row(site=site, node=sample, derived_state="1")
ts_new = tables.tree_sequence()
assert all([v.genotypes[sample] == 1 for v in ts_new.variants()])
def test_zero_samples(self):
ts = self.get_tree_sequence()
for var1, var2 in zip(ts.variants(), ts.variants(samples=[])):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert var2.genotypes.shape[0] == 0
def test_samples(self):
n = 4
ts = msprime.simulate(
n, length=5, recombination_rate=1, mutation_rate=5, random_seed=2
)
assert ts.num_sites > 1
samples = list(range(n))
# Generate all possible sample lists.
for j in range(n + 1):
for s in itertools.permutations(samples, j):
s = np.array(s, dtype=np.int32)
count = 0
for var1, var2 in zip(ts.variants(), ts.variants(samples=s)):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert var2.genotypes.shape == (len(s),)
assert np.array_equal(var1.genotypes[s], var2.genotypes)
count += 1
assert count == ts.num_sites
def test_samples_missing_data(self):
n = 4
ts = msprime.simulate(
n, length=5, recombination_rate=1, mutation_rate=5, random_seed=2
)
assert ts.num_sites > 1
tables = ts.dump_tables()
tables.delete_intervals([[0.5, 0.6]])
tables.sites.add_row(0.5, ancestral_state="0")
tables.sort()
ts = tables.tree_sequence()
samples = list(range(n))
# Generate all possible sample lists.
for j in range(1, n + 1):
for s in itertools.permutations(samples, j):
s = np.array(s, dtype=np.int32)
count = 0
for var1, var2 in zip(ts.variants(), ts.variants(samples=s)):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert var2.genotypes.shape == (len(s),)
assert np.array_equal(var1.genotypes[s], var2.genotypes)
count += 1
assert count == ts.num_sites
def test_non_sample_samples(self):
# We don't have to use sample nodes. This does make the terminology confusing
# but it's probably still the best option.
ts = msprime.simulate(
10, length=5, recombination_rate=1, mutation_rate=5, random_seed=2
)
tables = ts.dump_tables()
tables.nodes.set_columns(
flags=np.zeros_like(tables.nodes.flags) + tskit.NODE_IS_SAMPLE,
time=tables.nodes.time,
)
all_samples_ts = tables.tree_sequence()
assert all_samples_ts.num_samples == ts.num_nodes
count = 0
samples = range(ts.num_nodes)
for var1, var2 in zip(
all_samples_ts.variants(isolated_as_missing=False),
ts.variants(samples=samples, isolated_as_missing=False),
):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert var2.genotypes.shape == (len(samples),)
assert np.array_equal(var1.genotypes, var2.genotypes)
count += 1
assert count == ts.num_sites
def verify_jukes_cantor(self, ts):
assert np.array_equal(ts.genotype_matrix(), ts.genotype_matrix())
tree = ts.first()
for variant in ts.variants():
assert not variant.has_missing_data
mutations = {
mutation.node: mutation.derived_state
for mutation in variant.site.mutations
}
for sample_index, u in enumerate(ts.samples()):
while u not in mutations and u != tskit.NULL:
u = tree.parent(u)
state1 = mutations.get(u, variant.site.ancestral_state)
state2 = variant.alleles[variant.genotypes[sample_index]]
assert state1 == state2
def test_jukes_cantor_n5(self):
ts = msprime.simulate(5, random_seed=2)
ts = tsutil.jukes_cantor(ts, 5, 1, seed=2)
self.verify_jukes_cantor(ts)
def test_jukes_cantor_n20(self):
ts = msprime.simulate(20, random_seed=2)
ts = tsutil.jukes_cantor(ts, 5, 1, seed=2)
self.verify_jukes_cantor(ts)
def test_zero_edge_missing_data(self):
ts = msprime.simulate(10, random_seed=2, mutation_rate=2)
tables = ts.dump_tables()
tables.keep_intervals([[0.25, 0.75]])
# add some sites in the deleted regions
tables.sites.add_row(0.1, "A")
tables.sites.add_row(0.2, "A")
tables.sites.add_row(0.8, "A")
tables.sites.add_row(0.9, "A")
tables.sort()
ts = tables.tree_sequence()
Gnm = ts.genotype_matrix(isolated_as_missing=False)
assert np.all(Gnm[0] == 0)
assert np.all(Gnm[1] == 0)
assert np.all(Gnm[-1] == 0)
assert np.all(Gnm[-2] == 0)
Gm = isolated_samples_genotype_matrix(ts)
assert np.all(Gm[0] == -1)
assert np.all(Gm[1] == -1)
assert np.all(Gm[-1] == -1)
assert np.all(Gm[-2] == -1)
Gm2 = ts.genotype_matrix(isolated_as_missing=True)
assert np.array_equal(Gm, Gm2)
# Test deprecated param
with pytest.warns(FutureWarning):
Gi = ts.genotype_matrix(impute_missing_data=True)
assert np.array_equal(Gnm, Gi)
with pytest.warns(FutureWarning):
Gni = ts.genotype_matrix(impute_missing_data=False)
assert np.array_equal(Gm, Gni)
with pytest.warns(FutureWarning):
G = ts.genotype_matrix(isolated_as_missing=False, impute_missing_data=True)
assert np.array_equal(Gnm, G)
with pytest.warns(FutureWarning):
G = ts.genotype_matrix(isolated_as_missing=True, impute_missing_data=False)
assert np.array_equal(Gm, G)
def test_empty_ts_missing_data(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == 1
var = variants[0]
assert var.alleles == ("A", None)
assert var.num_alleles == 1
assert np.all(var.genotypes == -1)
def test_empty_ts_incomplete_samples(self):
# https://github.com/tskit-dev/tskit/issues/776
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
ts = tables.tree_sequence()
variants = list(ts.variants(samples=[0]))
assert list(variants[0].genotypes) == [-1]
variants = list(ts.variants(samples=[1]))
assert list(variants[0].genotypes) == [-1]
def test_missing_data_samples(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
tables.mutations.add_row(0, 0, "T")
ts = tables.tree_sequence()
# If we have no samples we still get a list of variants.
variants = list(ts.variants(samples=[]))
assert len(variants[0].genotypes) == 0
assert not variants[0].has_missing_data
assert variants[0].alleles == ("A", "T")
# If we have a single sample that's not missing, there's no
# missing data.
variants = list(ts.variants(samples=[0]))
assert len(variants[0].genotypes) == 1
assert variants[0].genotypes[0] == 1
assert not variants[0].has_missing_data
assert variants[0].alleles == ("A", "T")
# If we have a single sample that is missing, there is
# missing data.
variants = list(ts.variants(samples=[1]))
assert len(variants[0].genotypes) == 1
assert variants[0].genotypes[0] == -1
assert variants[0].has_missing_data
assert variants[0].alleles == ("A", "T", None)
def test_mutation_over_isolated_sample_not_missing(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
tables.mutations.add_row(0, 0, "T")
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == 1
var = variants[0]
assert var.alleles == ("A", "T", None)
assert var.num_alleles == 2
assert list(var.genotypes) == [1, -1]
def test_multiple_mutations_over_isolated_sample(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
tables.mutations.add_row(0, 0, "T")
tables.mutations.add_row(0, 0, "G", parent=0)
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == 1
var = variants[0]
assert var.alleles == ("A", "T", "G", None)
assert var.num_alleles == 3
assert len(var.site.mutations) == 2
assert list(var.genotypes) == [2, -1]
def test_snipped_tree_sequence_missing_data(self):
ts = msprime.simulate(
10, length=10, recombination_rate=0.1, mutation_rate=10, random_seed=3
)
tables = ts.dump_tables()
tables.delete_intervals([[4, 6]], simplify=False)
tables.sites.add_row(4, ancestral_state="0")
tables.sites.add_row(5, ancestral_state="0")
tables.sites.add_row(5.999999, ancestral_state="0")
tables.sort()
ts = tables.tree_sequence()
G = ts.genotype_matrix()
num_missing = 0
for var in ts.variants():
if 4 <= var.site.position < 6:
assert var.has_missing_data
assert np.all(var.genotypes == tskit.MISSING_DATA)
num_missing += 1
else:
assert not var.has_missing_data
assert np.all(var.genotypes != tskit.MISSING_DATA)
assert np.array_equal(var.genotypes, G[var.site.id])
assert num_missing == 3
G = ts.genotype_matrix(isolated_as_missing=False)
for var in ts.variants(isolated_as_missing=False):
if 4 <= var.site.position < 6:
assert not var.has_missing_data
assert np.all(var.genotypes == 0)
else:
assert not var.has_missing_data
assert np.all(var.genotypes != tskit.MISSING_DATA)
assert np.array_equal(var.genotypes, G[var.site.id])
def test_snipped_tree_sequence_mutations_over_isolated(self):
ts = msprime.simulate(
10, length=10, recombination_rate=0.1, mutation_rate=10, random_seed=3
)
tables = ts.dump_tables()
tables.delete_intervals([[4, 6]], simplify=False)
missing_site = tables.sites.add_row(4, ancestral_state="0")
tables.mutations.add_row(missing_site, node=0, derived_state="1")
# Add another site in which all the samples are marked with a mutation
# to the ancestral state. Note: this would normally not be allowed because
# there's not state change. However, this allows us to mark a sample
# as not-missing, so it's an important feature.
missing_site = tables.sites.add_row(5, ancestral_state="0")
for u in range(10):
tables.mutations.add_row(missing_site, node=u, derived_state="0")
tables.sort()
ts = tables.tree_sequence()
G = ts.genotype_matrix()
missing_found = False
non_missing_found = False
for var in ts.variants():
if var.site.position == 4:
assert var.has_missing_data
assert var.genotypes[0] == 1
assert np.all(var.genotypes[1:] == tskit.MISSING_DATA)
missing_found += 1
elif var.site.position == 5:
assert not var.has_missing_data
assert np.all(var.genotypes == 0)
non_missing_found = 1
else:
assert not var.has_missing_data
assert np.all(var.genotypes != tskit.MISSING_DATA)
assert np.array_equal(var.genotypes, G[var.site.id])
assert non_missing_found
assert missing_found
class TestHaplotypeGenerator:
"""
Tests the haplotype generation code.
"""
def verify_haplotypes(self, n, haplotypes):
"""
Verify that the specified set of haplotypes is consistent.
"""
assert len(haplotypes) == n
m = len(haplotypes[0])
for h in haplotypes:
assert len(h) == m
# Examine each column in H; we must have a mixture of 0s and 1s
for k in range(m):
zeros = 0
ones = 0
col = ""
for j in range(n):
b = haplotypes[j][k]
zeros += b == "0"
ones += b == "1"
col += b
assert zeros + ones == n
def verify_tree_sequence(self, tree_sequence):
n = tree_sequence.sample_size
m = tree_sequence.num_sites
haplotypes = list(tree_sequence.haplotypes())
A = np.zeros((n, m), dtype="u1")
B = np.zeros((n, m), dtype="u1")
for j, h in enumerate(haplotypes):
assert len(h) == m
A[j] = np.frombuffer(h.encode("ascii"), np.uint8) - ord("0")
for variant in tree_sequence.variants():
B[:, variant.index] = variant.genotypes
assert np.all(A == B)
self.verify_haplotypes(n, haplotypes)
def verify_simulation(self, n, m, r, theta):
"""
Verifies a simulation for the specified parameters.
"""
recomb_map = msprime.RecombinationMap.uniform_map(m, r, m)
tree_sequence = msprime.simulate(
n, recombination_map=recomb_map, mutation_rate=theta
)
self.verify_tree_sequence(tree_sequence)
def test_random_parameters(self):
num_random_sims = 10
for _ in range(num_random_sims):
n = random.randint(2, 50)
m = random.randint(10, 200)
r = random.random()
theta = random.uniform(0, 2)
self.verify_simulation(n, m, r, theta)
def test_nonbinary_trees(self):
bottlenecks = [
msprime.SimpleBottleneck(0.01, 0, proportion=0.05),
msprime.SimpleBottleneck(0.02, 0, proportion=0.25),
msprime.SimpleBottleneck(0.03, 0, proportion=1),
]
ts = msprime.simulate(
10,
length=100,
recombination_rate=1,
demographic_events=bottlenecks,
random_seed=1,
)
self.verify_tree_sequence(ts)
def test_acgt_mutations(self):
ts = msprime.simulate(10, mutation_rate=10)
assert ts.num_sites > 0
tables = ts.tables
sites = tables.sites
mutations = tables.mutations
sites.set_columns(
position=sites.position,
ancestral_state=np.zeros(ts.num_sites, dtype=np.int8) + ord("A"),
ancestral_state_offset=np.arange(ts.num_sites + 1, dtype=np.uint32),
)
mutations.set_columns(
site=mutations.site,
node=mutations.node,
derived_state=np.zeros(ts.num_sites, dtype=np.int8) + ord("T"),
derived_state_offset=np.arange(ts.num_sites + 1, dtype=np.uint32),
)
tsp = tables.tree_sequence()
H = [h.replace("0", "A").replace("1", "T") for h in ts.haplotypes()]
assert H == list(tsp.haplotypes())
def test_fails_multiletter_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.tables
tables.sites.add_row(0, "ACTG")
tsp = tables.tree_sequence()
with pytest.raises(TypeError):
list(tsp.haplotypes())
def test_fails_deletion_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.tables
tables.sites.add_row(0, "")
tsp = tables.tree_sequence()
with pytest.raises(TypeError):
list(tsp.haplotypes())
def test_nonascii_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.tables
tables.sites.add_row(0, chr(169)) # Copyright symbol
tsp = tables.tree_sequence()
with pytest.raises(TypeError):
list(tsp.haplotypes())
def test_recurrent_mutations_over_samples(self):
ts = msprime.simulate(10, random_seed=2)
num_sites = 5
tables = ts.dump_tables()
for j in range(num_sites):
tables.sites.add_row(
position=j * ts.sequence_length / num_sites, ancestral_state="0"
)
for u in range(ts.sample_size):
tables.mutations.add_row(site=j, node=u, derived_state="1")
ts_new = tables.tree_sequence()
ones = "1" * num_sites
for h in ts_new.haplotypes():
assert ones == h
def test_silent_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.dump_tables()
tree = next(ts.trees())
for u in tree.children(tree.root):
tables.sites.clear()
tables.mutations.clear()
site = tables.sites.add_row(position=0, ancestral_state="0")
tables.mutations.add_row(site=site, node=u, derived_state="1")
tables.mutations.add_row(site=site, node=tree.root, derived_state="1")
ts_new = tables.tree_sequence()
all(h == 1 for h in ts_new.haplotypes())
def test_back_mutations(self):
base_ts = msprime.simulate(10, random_seed=2)
for j in [1, 2, 3]:
ts = tsutil.insert_branch_mutations(base_ts, mutations_per_branch=j)
self.verify_tree_sequence(ts)
def test_missing_data(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
ts = tables.tree_sequence()
with pytest.raises(ValueError):
list(ts.haplotypes(missing_data_character="A"))
for c in ("-", ".", "a"):
h = list(ts.haplotypes(missing_data_character=c))
assert h == [c, c]
h = list(ts.haplotypes(isolated_as_missing=True))
assert h == ["N", "N"]
h = list(ts.haplotypes(isolated_as_missing=False))
assert h == ["A", "A"]
h = list(ts.haplotypes())
assert h == ["N", "N"]
# Test deprecated method
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(impute_missing_data=True))
assert h == ["A", "A"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(impute_missing_data=False))
assert h == ["N", "N"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(isolated_as_missing=True, impute_missing_data=True))
assert h == ["N", "N"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(isolated_as_missing=True, impute_missing_data=False))
assert h == ["N", "N"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(isolated_as_missing=False, impute_missing_data=True))
assert h == ["A", "A"]
with pytest.warns(FutureWarning):
h = list(
ts.haplotypes(isolated_as_missing=False, impute_missing_data=False)
)
assert h == ["A", "A"]
class TestUserAlleles:
"""
Tests the functionality of providing a user-specified allele mapping.
"""
def test_simple_01(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()
G2 = ts.genotype_matrix(alleles=("0", "1"))
assert np.array_equal(G1, G2)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=("0", "1"))
):
assert v1.alleles == v2.alleles
assert v1.site == v2.site
assert np.array_equal(v1.genotypes, v2.genotypes)
def test_simple_01_trailing_alleles(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()
alleles = ("0", "1", "2", "xxxxx")
G2 = ts.genotype_matrix(alleles=alleles)
assert np.array_equal(G1, G2)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=alleles)
):
assert v2.alleles == alleles
assert v1.site == v2.site
assert np.array_equal(v1.genotypes, v2.genotypes)
def test_simple_01_leading_alleles(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()
alleles = ("A", "B", "C", "0", "1")
G2 = ts.genotype_matrix(alleles=alleles)
assert np.array_equal(G1 + 3, G2)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=alleles)
):
assert v2.alleles == alleles
assert v1.site == v2.site
assert np.array_equal(v1.genotypes + 3, v2.genotypes)
def test_simple_01_duplicate_alleles(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()
alleles = ("0", "0", "1")
G2 = ts.genotype_matrix(alleles=alleles)
index = np.where(G1 == 1)
G1[index] = 2
assert np.array_equal(G1, G2)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=alleles)
):
assert v2.alleles == alleles
assert v1.site == v2.site
g = v1.genotypes
index = np.where(g == 1)
g[index] = 2
assert np.array_equal(g, v2.genotypes)
def test_simple_acgt(self):
ts = msprime.simulate(10, random_seed=2)
ts = msprime.mutate(
ts, rate=4, random_seed=2, model=msprime.InfiniteSites(msprime.NUCLEOTIDES)
)
assert ts.num_sites > 2
alleles = tskit.ALLELES_ACGT
G = ts.genotype_matrix(alleles=alleles)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=alleles)
):
assert v2.alleles == alleles
assert v1.site == v2.site
h1 = "".join(v1.alleles[g] for g in v1.genotypes)
h2 = "".join(v2.alleles[g] for g in v2.genotypes)
assert h1 == h2
assert np.array_equal(v2.genotypes, G[v1.site.id])
def test_missing_alleles(self):
ts = msprime.simulate(10, random_seed=2)
ts = msprime.mutate(
ts, rate=4, random_seed=2, model=msprime.InfiniteSites(msprime.NUCLEOTIDES)
)
assert ts.num_sites > 2
bad_allele_examples = [
tskit.ALLELES_01,
tuple(["A"]),
("C", "T", "G"),
("AA", "C", "T", "G"),
tuple(["ACTG"]),
]
for bad_alleles in bad_allele_examples:
with pytest.raises(exceptions.LibraryError):
ts.genotype_matrix(alleles=bad_alleles)
with pytest.raises(exceptions.LibraryError):
list(ts.variants(alleles=bad_alleles))
def test_too_many_alleles(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
for n in range(128, 138):
bad_alleles = tuple(["0" for _ in range(n)])
with pytest.raises(exceptions.LibraryError):
ts.genotype_matrix(alleles=bad_alleles)
with pytest.raises(exceptions.LibraryError):
list(ts.variants(alleles=bad_alleles))
def test_zero_allele(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
with pytest.raises(ValueError):
ts.genotype_matrix(alleles=tuple())
with pytest.raises(ValueError):
list(ts.variants(alleles=tuple()))
def test_missing_data(self):
tables = tskit.TableCollection(1)
tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0)
tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0)
tables.sites.add_row(0.5, "0")
tables.mutations.add_row(0, 0, "1")
ts = tables.tree_sequence()
for isolated_as_missing in [True, False]:
G1 = ts.genotype_matrix(isolated_as_missing=isolated_as_missing)
G2 = ts.genotype_matrix(
isolated_as_missing=isolated_as_missing, alleles=tskit.ALLELES_01
)
assert np.array_equal(G1, G2)
vars1 = ts.variants(isolated_as_missing=isolated_as_missing)
vars2 = ts.variants(
isolated_as_missing=isolated_as_missing, alleles=tskit.ALLELES_01
)
for v1, v2 in itertools.zip_longest(vars1, vars2):
assert v2.alleles == v1.alleles
assert v1.site == v2.site
assert np.array_equal(v1.genotypes, v2.genotypes)
class TestUserAllelesRoundTrip:
"""
Tests that we correctly produce haplotypes in a variety of situations for
the user specified allele map encoding.
"""
def verify(self, ts, alleles):
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=alleles)
):
h1 = [v1.alleles[g] for g in v1.genotypes]
h2 = [v2.alleles[g] for g in v2.genotypes]
assert h1 == h2
def test_simple_01(self):
ts = msprime.simulate(5, mutation_rate=2, random_seed=3)
assert ts.num_sites > 3
valid_alleles = [
tskit.ALLELES_01,
("0", "1", "xry"),
("xry", "0", "1", "xry"),
tuple([str(j) for j in range(127)]),
tuple(["0" for j in range(126)] + ["1"]),
]
for alleles in valid_alleles:
self.verify(ts, alleles)
def test_simple_acgt(self):
ts = msprime.simulate(5, random_seed=3)
ts = msprime.mutate(
ts, rate=4, random_seed=3, model=msprime.InfiniteSites(msprime.NUCLEOTIDES)
)
assert ts.num_sites > 3
valid_alleles = [
tskit.ALLELES_ACGT,
("A", "C", "T", "G", "AAAAAAAAAAAAAA"),
("AA", "CC", "TT", "GG", "A", "C", "T", "G"),
]
for alleles in valid_alleles:
self.verify(ts, alleles)
def test_jukes_cantor(self):
ts = msprime.simulate(6, random_seed=1, mutation_rate=1)
ts = tsutil.jukes_cantor(ts, 20, 1, seed=10)
valid_alleles = [
tskit.ALLELES_ACGT,
("A", "C", "T", "G", "AAAAAAAAAAAAAA"),
("AA", "CC", "TT", "GG", "A", "C", "T", "G"),
]
for alleles in valid_alleles:
self.verify(ts, alleles)
def test_multichar_mutations(self):
ts = msprime.simulate(6, random_seed=1, recombination_rate=2)
ts = tsutil.insert_multichar_mutations(ts)
assert ts.num_sites > 5
all_alleles = set()
for var in ts.variants():
all_alleles.update(var.alleles)
all_alleles = tuple(all_alleles)
self.verify(ts, all_alleles)
self.verify(ts, all_alleles[::-1])
def test_simple_01_missing_data(self):
ts = msprime.simulate(6, mutation_rate=2, random_seed=3)
tables = ts.dump_tables()
# Add another sample node. This will be missing data everywhere.
tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0)
ts = tables.tree_sequence()
assert ts.num_sites > 3
valid_alleles = [
tskit.ALLELES_01,
("0", "1", "xry"),
("xry", "0", "1", "xry"),
tuple([str(j) for j in range(127)]),
tuple(["0" for j in range(126)] + ["1"]),
]
for alleles in valid_alleles:
self.verify(ts, alleles)
class TestBinaryTreeExample:
# 2.00┊ 4 ┊
# ┊ ┏━┻┓ ┊
# 1.00┊ ┃ 3 ┊
# ┊ ┃ ┏┻┓ ┊
# 0.00┊ 0 1 2 ┊
# 0 10
# | |
# pos 2 9
# anc A T
@tests.cached_example
def ts(self):
ts = tskit.Tree.generate_balanced(3, span=10).tree_sequence
tables = ts.dump_tables()
tables.sites.add_row(2, ancestral_state="A")
tables.sites.add_row(9, ancestral_state="T")
tables.mutations.add_row(site=0, node=0, derived_state="G")
tables.mutations.add_row(site=1, node=3, derived_state="C")
return tables.tree_sequence()
def test_haplotypes(self):
H = list(self.ts().haplotypes())
assert H[0] == "GT"
assert H[1] == "AC"
assert H[2] == "AC"
def test_genotypes(self):
G = self.ts().genotype_matrix()
Gp = [[1, 0, 0], [0, 1, 1]]
np.testing.assert_array_equal(G, Gp)
@pytest.mark.skip("Reference sequence not implemented #1888")
def test_alignments_default(self):
A = list(self.ts().alignments())
assert A[0] == "NNGNNNNNNT"
assert A[1] == "NNANNNNNNC"
assert A[2] == "NNANNNNNNC"
@pytest.mark.skip("Reference sequence not implemented #1888")
def test_alignments_missing_char(self):
A = list(self.ts().alignments(missing_data_character="z"))
assert A[0] == "zzGzzzzzzT"
assert A[1] == "zzAzzzzzzC"
assert A[2] == "zzAzzzzzzC"
def test_alignments_reference_sequence(self):
ref = "0123456789"
A = list(self.ts().alignments(reference_sequence=ref))
assert A[0] == "01G345678T"
assert A[1] == "01A345678C"
assert A[2] == "01A345678C"
def test_alignments_reference_sequence_embedded_null(self):
# This is a total corner case, but just want to make sure
# we do something sensible.
ref = "0123" + "\0" + "56789"
A = list(self.ts().alignments(reference_sequence=ref))
assert A[0] == "01G3\x005678T"
assert A[1] == "01A3\x005678C"
assert A[2] == "01A3\x005678C"
def test_fasta_reference_sequence(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
>n0
01G345678T
>n1
01A345678C
>n2
01A345678C
"""
)
assert expected == self.ts().as_fasta(reference_sequence=ref)
def test_nexus_reference_sequence(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
#NEXUS
BEGIN TAXA;
DIMENSIONS NTAX=3;
TAXLABELS n0 n1 n2;
END;
BEGIN DATA;
DIMENSIONS NCHAR=10;
FORMAT DATATYPE=DNA;
MATRIX
n0 01G345678T
n1 01A345678C
n2 01A345678C
;
END;
BEGIN TREES;
TREE t0^10 = [&R] (n0:2,(n1:1,n2:1):1);
END;
"""
)
assert expected == self.ts().as_nexus(reference_sequence=ref)
class TestMissingDataExample:
# 2.00┊ 4 ┊
# ┊ ┏━┻┓ ┊
# 1.00┊ ┃ 3 ┊
# ┊ ┃ ┏┻┓ ┊
# 0.00┊ 0 1 2 5 ┊
# 0 10
# | |
# pos 2 9
# anc A T
@tests.cached_example
def ts(self):
ts = tskit.Tree.generate_balanced(3, span=10).tree_sequence
tables = ts.dump_tables()
tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0)
tables.sites.add_row(2, ancestral_state="A")
tables.sites.add_row(9, ancestral_state="T")
tables.mutations.add_row(site=0, node=0, derived_state="G")
tables.mutations.add_row(site=1, node=3, derived_state="C")
return tables.tree_sequence()
def test_haplotypes(self):
H = list(self.ts().haplotypes())
assert H[0] == "GT"
assert H[1] == "AC"
assert H[2] == "AC"
assert H[3] == "NN"
def test_haplotypes_missing_data_char(self):
H = list(self.ts().haplotypes(missing_data_character="?"))
assert H[0] == "GT"
assert H[1] == "AC"
assert H[2] == "AC"
assert H[3] == "??"
def test_genotypes(self):
G = self.ts().genotype_matrix()
Gp = [[1, 0, 0, -1], [0, 1, 1, -1]]
np.testing.assert_array_equal(G, Gp)
@pytest.mark.skip("Reference sequence not implemented #1888")
def test_alignments_default(self):
A = list(self.ts().alignments())
assert A[0] == "NNGNNNNNNT"
assert A[1] == "NNANNNNNNC"
assert A[2] == "NNANNNNNNC"
assert A[3] == "NNNNNNNNNN"
def test_alignments_fails(self):
# https://github.com/tskit-dev/tskit/issues/1896
ref = "N" * 10
with pytest.raises(ValueError, match="1896"):
next(self.ts().alignments(reference_sequence=ref))
@pytest.mark.skip("Missing data in alignments: #1896")
def test_alignments_impute_missing(self):
ref = "N" * 10
A = list(
self.ts().alignments(reference_sequence=ref, isolated_as_missing=False)
)
assert A[0] == "NNGNNNNNNT"
assert A[1] == "NNANNNNNNC"
assert A[2] == "NNANNNNNNC"
assert A[3] == "NNANNNNNNT"
@pytest.mark.skip("Reference sequence not implemented #1888")
def test_alignments_missing_char(self):
A = list(self.ts().alignments(missing_data_character="z"))
assert A[0] == "zzGzzzzzzT"
assert A[1] == "zzAzzzzzzC"
assert A[2] == "zzAzzzzzzC"
assert A[3] == "zzzzzzzzzz"
@pytest.mark.skip("Reference sequence not implemented #1888")
def test_alignments_missing_char_ref(self):
A = list(self.ts().alignments(missing_data_character="z"))
assert A[0] == "NNGNNNNNNT"
assert A[1] == "NNANNNNNNC"
assert A[2] == "NNANNNNNNC"
assert A[3] == "zzzzzzzzzz"
@pytest.mark.skip("Missing data in alignments: #1896")
def test_alignments_reference_sequence(self):
ref = "0123456789"
A = list(self.ts().alignments(reference_sequence=ref))
assert A[0] == "01G345678T"
assert A[1] == "01A345678C"
assert A[2] == "01A345678C"
assert A[3] == "NNNNNNNNNN"
@pytest.mark.skip("Missing data in alignments: #1896")
def test_alignments_reference_sequence_missing_data_char(self):
ref = "0123456789"
A = list(
self.ts().alignments(reference_sequence=ref, missing_data_character="Q")
)
assert A[0] == "01G345678T"
assert A[1] == "01A345678C"
assert A[2] == "01A345678C"
assert A[3] == "QQQQQQQQQQ"
@pytest.mark.skip("Missing data in alignments: #1896")
def test_fasta_reference_sequence(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
>n0
01G345678T
>n1
01A345678C
>n2
01A345678C
>n5
NNNNNNNNNN
"""
)
assert expected == self.ts().as_fasta(reference_sequence=ref)
@pytest.mark.skip("Missing data in alignments: #1896")
def test_fasta_reference_sequence_missing_data_char(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
>n0
01G345678T
>n1
01A345678C
>n2
01A345678C
>n5
QQQQQQQQQQ
"""
)
assert expected == self.ts().as_fasta(
reference_sequence=ref, missing_data_character="Q"
)
@pytest.mark.skip("Missing data in alignments: #1896")
def test_fasta_impute_missing(self):
ref = "N" * 10
expected = textwrap.dedent(
"""\
>n0
NNGNNNNNNT
>n1
NNANNNNNNC
>n2
NNANNNNNNC
>n5
NNANNNNNNT
"""
)
assert expected == self.ts().as_fasta(
reference_sequence=ref, isolated_as_missing=False
)
# Note: the nexus tree output isn't compatible with our representation of
# missing data as trees with isolated roots (newick parsers won't accept
# this as valid input), so we set include_trees=False for these examples.
@pytest.mark.skip("Missing data in alignments: #1896")
def test_nexus_reference_sequence(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
#NEXUS
BEGIN TAXA;
DIMENSIONS NTAX=4;
TAXLABELS n0 n1 n2 n5;
END;
BEGIN DATA;
DIMENSIONS NCHAR=10;
FORMAT DATATYPE=DNA MISSING=?;
MATRIX
n0 01G345678T
n1 01A345678C
n2 01A345678C
n5 ??????????
;
END;
"""
)
assert expected == self.ts().as_nexus(
reference_sequence=ref, include_trees=False
)
@pytest.mark.skip("Missing data in alignments: #1896")
def test_nexus_reference_sequence_missing_data_char(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
#NEXUS
BEGIN TAXA;
DIMENSIONS NTAX=4;
TAXLABELS n0 n1 n2 n5;
END;
BEGIN DATA;
DIMENSIONS NCHAR=10;
FORMAT DATATYPE=DNA MISSING=Q;
MATRIX
n0 01G345678T
n1 01A345678C
n2 01A345678C
n5 QQQQQQQQQQ
;
END;
"""
)
assert expected == self.ts().as_nexus(
reference_sequence=ref,
missing_data_character="Q",
include_trees=False,
)
@pytest.mark.skip("Missing data in alignments: #1896")
def test_nexus_impute_missing(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
#NEXUS
BEGIN TAXA;
DIMENSIONS NTAX=4;
TAXLABELS n0 n1 n2 n5;
END;
BEGIN DATA;
DIMENSIONS NCHAR=10;
FORMAT DATATYPE=DNA MISSING=?;
MATRIX
n0 01G345678T
n1 01A345678C
n2 01A345678C
n5 01A345678T
;
END;
"""
)
assert expected == self.ts().as_nexus(
reference_sequence=ref,
isolated_as_missing=False,
include_trees=False,
)
class TestMultiRootExample:
# 1.00┊ 4 5 ┊
# ┊ ┏┻┓ ┏┻┓ ┊
# 0.00┊ 0 1 2 3 ┊
# 0 10
# | |
# pos 2 8
# anc G C
@tests.cached_example
def ts(self):
tree = tskit.Tree.generate_balanced(4, arity=2, span=10)
tables = tree.tree_sequence.dump_tables()
edges = tables.edges.copy()
tables.edges.clear()
for edge in edges:
if edge.parent != 6:
tables.edges.append(edge)
tables.sites.add_row(2, ancestral_state="G")
tables.sites.add_row(8, ancestral_state="C")
tables.mutations.add_row(site=0, node=0, derived_state="T")
tables.mutations.add_row(site=1, node=5, derived_state="A")
return tables.tree_sequence()
def test_haplotypes(self):
H = list(self.ts().haplotypes())
assert H[0] == "TC"
assert H[1] == "GC"
assert H[2] == "GA"
assert H[3] == "GA"
def test_genotypes(self):
G = self.ts().genotype_matrix()
Gp = [[1, 0, 0, 0], [0, 0, 1, 1]]
np.testing.assert_array_equal(G, Gp)
@pytest.mark.skip("Reference sequence not implemented #1888")
def test_alignments_default(self):
A = list(self.ts().alignments())
assert A[0] == "NNTNNNNNCN"
assert A[1] == "NNGNNNNNCN"
assert A[2] == "NNGNNNNNAN"
assert A[3] == "NNGNNNNNAN"
def test_alignments_N_ref(self):
A = list(self.ts().alignments(reference_sequence="N" * 10))
assert A[0] == "NNTNNNNNCN"
assert A[1] == "NNGNNNNNCN"
assert A[2] == "NNGNNNNNAN"
assert A[3] == "NNGNNNNNAN"
def test_fasta_reference_sequence(self):
ref = "0123456789"
expected = textwrap.dedent(
"""\
>n0
01T34567C9
>n1
01G34567C9
>n2
01G34567A9
>n3
01G34567A9
"""
)
assert expected == self.ts().as_fasta(reference_sequence=ref)
class TestAlignmentsErrors:
@tests.cached_example
def simplest_ts(self):
tables = tskit.TableCollection(1)
tables.nodes.add_row(flags=1, time=0)
return tables.tree_sequence()
def test_non_discrete_genome(self):
ts = tskit.TableCollection(1.1).tree_sequence()
assert not ts.discrete_genome
with pytest.raises(ValueError, match="defined for discrete genomes"):
list(ts.alignments())
def test_no_reference(self):
ts = tskit.TableCollection(1).tree_sequence()
with pytest.raises(ValueError, match="1888"):
list(ts.alignments())
@pytest.mark.parametrize("ref", ["", "xy"])
def test_reference_sequence_length_mismatch(self, ref):
ts = self.simplest_ts()
with pytest.raises(ValueError, match="same length"):
list(ts.alignments(reference_sequence=ref))
@pytest.mark.parametrize("ref", ["À", "┃", "α"])
def test_non_ascii_references(self, ref):
ts = self.simplest_ts()
with pytest.raises(UnicodeEncodeError):
list(ts.alignments(reference_sequence=ref))
@pytest.mark.skip("Missing data in alignments: #1896")
@pytest.mark.parametrize("missing_data_char", ["À", "┃", "α"])
def test_non_ascii_missing_data_char(self, missing_data_char):
ts = self.simplest_ts()
with pytest.raises(UnicodeEncodeError):
list(
ts.alignments(
reference_sequence="-", missing_data_character=missing_data_char
)
)
class TestAlignmentExamples:
@pytest.mark.skip("Reference sequence not implemented #1888")
@pytest.mark.parametrize("ts", get_example_discrete_genome_tree_sequences())
def test_defaults(self, ts):
A = list(ts.alignments())
assert len(A) == ts.num_samples
H = list(ts.haplotypes())
pos = ts.tables.sites.position.astype(int)
for a, h in map(np.array, zip(A, H)):
last = 0
for j, x in enumerate(pos):
assert a[last:x] == "-" * (x - last)
assert a[x] == h[j]
last = x + 1
@pytest.mark.parametrize("ts", get_example_discrete_genome_tree_sequences())
def test_reference_sequence(self, ts):
ref = tskit.random_nucleotides(ts.sequence_length, seed=1234)
if any(tree.num_roots > 1 for tree in ts.trees()):
with pytest.raises(ValueError, match="1896"):
list(ts.alignments(reference_sequence=ref))
else:
A = list(ts.alignments(reference_sequence=ref))
assert len(A) == ts.num_samples
H = list(ts.haplotypes())
pos = ts.tables.sites.position.astype(int)
for a, h in map(np.array, zip(A, H)):
last = 0
for j, x in enumerate(pos):
assert a[last:x] == ref[last:x]
assert a[x] == h[j]
last = x + 1
assert a[last:] == ref[last:]
|
[
"msprime.RecombinationMap.uniform_map",
"numpy.empty",
"numpy.ones",
"msprime.InfiniteSites",
"numpy.arange",
"pytest.mark.parametrize",
"pytest.mark.skip",
"numpy.zeros_like",
"random.randint",
"pytest.warns",
"tskit.TableCollection",
"itertools.permutations",
"itertools.zip_longest",
"pytest.raises",
"tests.tsutil.jukes_cantor",
"tskit.random_nucleotides",
"numpy.testing.assert_array_equal",
"tests.test_highlevel.get_example_tree_sequences",
"numpy.frombuffer",
"random.random",
"msprime.simulate",
"msprime.mutate",
"numpy.all",
"msprime.SimpleBottleneck",
"textwrap.dedent",
"tests.tsutil.insert_multichar_mutations",
"random.uniform",
"tests.test_wright_fisher.wf_sim",
"numpy.zeros",
"numpy.where",
"numpy.array",
"tests.tsutil.insert_branch_mutations",
"numpy.array_equal",
"tskit.Tree.generate_balanced"
] |
[((1739, 1767), 'tests.test_highlevel.get_example_tree_sequences', 'get_example_tree_sequences', ([], {}), '()\n', (1765, 1767), False, 'from tests.test_highlevel import get_example_tree_sequences\n'), ((2312, 2365), 'numpy.zeros', 'np.zeros', (['(ts.num_nodes, ts.num_sites)'], {'dtype': 'np.int8'}), '((ts.num_nodes, ts.num_sites), dtype=np.int8)\n', (2320, 2365), True, 'import numpy as np\n'), ((43203, 43263), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Reference sequence not implemented #1888"""'], {}), "('Reference sequence not implemented #1888')\n", (43219, 43263), False, 'import pytest\n'), ((43458, 43518), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Reference sequence not implemented #1888"""'], {}), "('Reference sequence not implemented #1888')\n", (43474, 43518), False, 'import pytest\n'), ((46689, 46749), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Reference sequence not implemented #1888"""'], {}), "('Reference sequence not implemented #1888')\n", (46705, 46749), False, 'import pytest\n'), ((47215, 47268), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (47231, 47268), False, 'import pytest\n'), ((47600, 47660), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Reference sequence not implemented #1888"""'], {}), "('Reference sequence not implemented #1888')\n", (47616, 47660), False, 'import pytest\n'), ((47922, 47982), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Reference sequence not implemented #1888"""'], {}), "('Reference sequence not implemented #1888')\n", (47938, 47982), False, 'import pytest\n'), ((48248, 48301), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (48264, 48301), False, 'import pytest\n'), ((48592, 48645), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (48608, 48645), False, 'import pytest\n'), ((49004, 49057), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (49020, 49057), False, 'import pytest\n'), ((49441, 49494), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (49457, 49494), False, 'import pytest\n'), ((49946, 49999), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (49962, 49999), False, 'import pytest\n'), ((50657, 50710), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (50673, 50710), False, 'import pytest\n'), ((51389, 51442), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (51405, 51442), False, 'import pytest\n'), ((52192, 52245), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (52208, 52245), False, 'import pytest\n'), ((54099, 54159), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Reference sequence not implemented #1888"""'], {}), "('Reference sequence not implemented #1888')\n", (54115, 54159), False, 'import pytest\n'), ((55650, 55692), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ref"""', "['', 'xy']"], {}), "('ref', ['', 'xy'])\n", (55673, 55692), False, 'import pytest\n'), ((55908, 55955), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ref"""', "['À', '┃', 'α']"], {}), "('ref', ['À', '┃', 'α'])\n", (55931, 55955), False, 'import pytest\n'), ((56144, 56197), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Missing data in alignments: #1896"""'], {}), "('Missing data in alignments: #1896')\n", (56160, 56197), False, 'import pytest\n'), ((56203, 56264), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""missing_data_char"""', "['À', '┃', 'α']"], {}), "('missing_data_char', ['À', '┃', 'α'])\n", (56226, 56264), False, 'import pytest\n'), ((56614, 56674), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Reference sequence not implemented #1888"""'], {}), "('Reference sequence not implemented #1888')\n", (56630, 56674), False, 'import pytest\n'), ((3442, 3462), 'numpy.array_equal', 'np.array_equal', (['A', 'B'], {}), '(A, B)\n', (3456, 3462), True, 'import numpy as np\n'), ((3509, 3562), 'msprime.simulate', 'msprime.simulate', (['(5)'], {'mutation_rate': '(1)', 'random_seed': '(234)'}), '(5, mutation_rate=1, random_seed=234)\n', (3525, 3562), False, 'import msprime\n'), ((3632, 3709), 'msprime.simulate', 'msprime.simulate', (['(8)'], {'recombination_rate': '(10)', 'mutation_rate': '(10)', 'random_seed': '(234)'}), '(8, recombination_rate=10, mutation_rate=10, random_seed=234)\n', (3648, 3709), False, 'import msprime\n'), ((3879, 3930), 'msprime.simulate', 'msprime.simulate', (['(6)'], {'random_seed': '(1)', 'mutation_rate': '(1)'}), '(6, random_seed=1, mutation_rate=1)\n', (3895, 3930), False, 'import msprime\n'), ((3944, 3983), 'tests.tsutil.jukes_cantor', 'tsutil.jukes_cantor', (['ts', '(20)', '(1)'], {'seed': '(10)'}), '(ts, 20, 1, seed=10)\n', (3963, 3983), True, 'import tests.tsutil as tsutil\n'), ((4074, 4125), 'msprime.simulate', 'msprime.simulate', (['(6)'], {'random_seed': '(1)', 'mutation_rate': '(1)'}), '(6, random_seed=1, mutation_rate=1)\n', (4090, 4125), False, 'import msprime\n'), ((4139, 4176), 'tests.tsutil.insert_multichar_mutations', 'tsutil.insert_multichar_mutations', (['ts'], {}), '(ts)\n', (4172, 4176), True, 'import tests.tsutil as tsutil\n'), ((4261, 4334), 'msprime.simulate', 'msprime.simulate', (['(6)'], {'recombination_rate': '(2)', 'mutation_rate': '(2)', 'random_seed': '(1)'}), '(6, recombination_rate=2, mutation_rate=2, random_seed=1)\n', (4277, 4334), False, 'import msprime\n'), ((4494, 4585), 'tests.test_wright_fisher.wf_sim', 'wf.wf_sim', (['(6)', '(5)'], {'seed': '(3)', 'deep_history': '(True)', 'initial_generation_samples': '(True)', 'num_loci': '(2)'}), '(6, 5, seed=3, deep_history=True, initial_generation_samples=True,\n num_loci=2)\n', (4503, 4585), True, 'import tests.test_wright_fisher as wf\n'), ((4849, 4943), 'tests.test_wright_fisher.wf_sim', 'wf.wf_sim', (['(9)', '(10)'], {'seed': '(1)', 'deep_history': '(True)', 'initial_generation_samples': '(False)', 'num_loci': '(5)'}), '(9, 10, seed=1, deep_history=True, initial_generation_samples=\n False, num_loci=5)\n', (4858, 4943), True, 'import tests.test_wright_fisher as wf\n'), ((5104, 5150), 'msprime.mutate', 'msprime.mutate', (['ts'], {'rate': '(0.2)', 'random_seed': '(1234)'}), '(ts, rate=0.2, random_seed=1234)\n', (5118, 5150), False, 'import msprime\n'), ((5254, 5280), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.0)'], {}), '(1.0)\n', (5275, 5280), False, 'import tskit\n'), ((5687, 5720), 'numpy.zeros', 'np.zeros', (['ts.num_nodes'], {'dtype': 'int'}), '(ts.num_nodes, dtype=int)\n', (5695, 5720), True, 'import numpy as np\n'), ((6318, 6408), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'length': '(10)', 'recombination_rate': '(1)', 'mutation_rate': '(10)', 'random_seed': '(3)'}), '(10, length=10, recombination_rate=1, mutation_rate=10,\n random_seed=3)\n', (6334, 6408), False, 'import msprime\n'), ((6636, 6664), 'numpy.zeros', 'np.zeros', (['(m, n)'], {'dtype': '"""u1"""'}), "((m, n), dtype='u1')\n", (6644, 6664), True, 'import numpy as np\n'), ((6677, 6705), 'numpy.zeros', 'np.zeros', (['(m, n)'], {'dtype': '"""u1"""'}), "((m, n), dtype='u1')\n", (6685, 6705), True, 'import numpy as np\n'), ((7000, 7014), 'numpy.all', 'np.all', (['(A == B)'], {}), '(A == B)\n', (7006, 7014), True, 'import numpy as np\n'), ((11715, 11735), 'msprime.simulate', 'msprime.simulate', (['(10)'], {}), '(10)\n', (11731, 11735), False, 'import msprime\n'), ((11939, 11994), 'numpy.empty', 'np.empty', (['(ts.num_sites, ts.num_samples)'], {'dtype': 'np.int8'}), '((ts.num_sites, ts.num_samples), dtype=np.int8)\n', (11947, 11994), True, 'import numpy as np\n'), ((12116, 12137), 'numpy.array_equal', 'np.array_equal', (['G', 'G2'], {}), '(G, G2)\n', (12130, 12137), True, 'import numpy as np\n'), ((14159, 14246), 'msprime.simulate', 'msprime.simulate', (['n'], {'length': '(5)', 'recombination_rate': '(1)', 'mutation_rate': '(5)', 'random_seed': '(2)'}), '(n, length=5, recombination_rate=1, mutation_rate=5,\n random_seed=2)\n', (14175, 14246), False, 'import msprime\n'), ((15005, 15092), 'msprime.simulate', 'msprime.simulate', (['n'], {'length': '(5)', 'recombination_rate': '(1)', 'mutation_rate': '(5)', 'random_seed': '(2)'}), '(n, length=5, recombination_rate=1, mutation_rate=5,\n random_seed=2)\n', (15021, 15092), False, 'import msprime\n'), ((16168, 16256), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'length': '(5)', 'recombination_rate': '(1)', 'mutation_rate': '(5)', 'random_seed': '(2)'}), '(10, length=5, recombination_rate=1, mutation_rate=5,\n random_seed=2)\n', (16184, 16256), False, 'import msprime\n'), ((17850, 17884), 'msprime.simulate', 'msprime.simulate', (['(5)'], {'random_seed': '(2)'}), '(5, random_seed=2)\n', (17866, 17884), False, 'import msprime\n'), ((17898, 17935), 'tests.tsutil.jukes_cantor', 'tsutil.jukes_cantor', (['ts', '(5)', '(1)'], {'seed': '(2)'}), '(ts, 5, 1, seed=2)\n', (17917, 17935), True, 'import tests.tsutil as tsutil\n'), ((18024, 18059), 'msprime.simulate', 'msprime.simulate', (['(20)'], {'random_seed': '(2)'}), '(20, random_seed=2)\n', (18040, 18059), False, 'import msprime\n'), ((18073, 18110), 'tests.tsutil.jukes_cantor', 'tsutil.jukes_cantor', (['ts', '(5)', '(1)'], {'seed': '(2)'}), '(ts, 5, 1, seed=2)\n', (18092, 18110), True, 'import tests.tsutil as tsutil\n'), ((18205, 18257), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)', 'mutation_rate': '(2)'}), '(10, random_seed=2, mutation_rate=2)\n', (18221, 18257), False, 'import msprime\n'), ((18675, 18694), 'numpy.all', 'np.all', (['(Gnm[0] == 0)'], {}), '(Gnm[0] == 0)\n', (18681, 18694), True, 'import numpy as np\n'), ((18710, 18729), 'numpy.all', 'np.all', (['(Gnm[1] == 0)'], {}), '(Gnm[1] == 0)\n', (18716, 18729), True, 'import numpy as np\n'), ((18745, 18765), 'numpy.all', 'np.all', (['(Gnm[-1] == 0)'], {}), '(Gnm[-1] == 0)\n', (18751, 18765), True, 'import numpy as np\n'), ((18781, 18801), 'numpy.all', 'np.all', (['(Gnm[-2] == 0)'], {}), '(Gnm[-2] == 0)\n', (18787, 18801), True, 'import numpy as np\n'), ((18867, 18886), 'numpy.all', 'np.all', (['(Gm[0] == -1)'], {}), '(Gm[0] == -1)\n', (18873, 18886), True, 'import numpy as np\n'), ((18902, 18921), 'numpy.all', 'np.all', (['(Gm[1] == -1)'], {}), '(Gm[1] == -1)\n', (18908, 18921), True, 'import numpy as np\n'), ((18937, 18957), 'numpy.all', 'np.all', (['(Gm[-1] == -1)'], {}), '(Gm[-1] == -1)\n', (18943, 18957), True, 'import numpy as np\n'), ((18973, 18993), 'numpy.all', 'np.all', (['(Gm[-2] == -1)'], {}), '(Gm[-2] == -1)\n', (18979, 18993), True, 'import numpy as np\n'), ((19068, 19091), 'numpy.array_equal', 'np.array_equal', (['Gm', 'Gm2'], {}), '(Gm, Gm2)\n', (19082, 19091), True, 'import numpy as np\n'), ((19245, 19268), 'numpy.array_equal', 'np.array_equal', (['Gnm', 'Gi'], {}), '(Gnm, Gi)\n', (19259, 19268), True, 'import numpy as np\n'), ((19390, 19413), 'numpy.array_equal', 'np.array_equal', (['Gm', 'Gni'], {}), '(Gm, Gni)\n', (19404, 19413), True, 'import numpy as np\n'), ((19560, 19582), 'numpy.array_equal', 'np.array_equal', (['Gnm', 'G'], {}), '(Gnm, G)\n', (19574, 19582), True, 'import numpy as np\n'), ((19728, 19749), 'numpy.array_equal', 'np.array_equal', (['Gm', 'G'], {}), '(Gm, G)\n', (19742, 19749), True, 'import numpy as np\n'), ((19810, 19836), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.0)'], {}), '(1.0)\n', (19831, 19836), False, 'import tskit\n'), ((20212, 20239), 'numpy.all', 'np.all', (['(var.genotypes == -1)'], {}), '(var.genotypes == -1)\n', (20218, 20239), True, 'import numpy as np\n'), ((20362, 20388), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.0)'], {}), '(1.0)\n', (20383, 20388), False, 'import tskit\n'), ((20833, 20859), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.0)'], {}), '(1.0)\n', (20854, 20859), False, 'import tskit\n'), ((22088, 22114), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.0)'], {}), '(1.0)\n', (22109, 22114), False, 'import tskit\n'), ((22648, 22674), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.0)'], {}), '(1.0)\n', (22669, 22674), False, 'import tskit\n'), ((23302, 23394), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'length': '(10)', 'recombination_rate': '(0.1)', 'mutation_rate': '(10)', 'random_seed': '(3)'}), '(10, length=10, recombination_rate=0.1, mutation_rate=10,\n random_seed=3)\n', (23318, 23394), False, 'import msprime\n'), ((24774, 24866), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'length': '(10)', 'recombination_rate': '(0.1)', 'mutation_rate': '(10)', 'random_seed': '(3)'}), '(10, length=10, recombination_rate=0.1, mutation_rate=10,\n random_seed=3)\n', (24790, 24866), False, 'import msprime\n'), ((27356, 27384), 'numpy.zeros', 'np.zeros', (['(n, m)'], {'dtype': '"""u1"""'}), "((n, m), dtype='u1')\n", (27364, 27384), True, 'import numpy as np\n'), ((27397, 27425), 'numpy.zeros', 'np.zeros', (['(n, m)'], {'dtype': '"""u1"""'}), "((n, m), dtype='u1')\n", (27405, 27425), True, 'import numpy as np\n'), ((27689, 27703), 'numpy.all', 'np.all', (['(A == B)'], {}), '(A == B)\n', (27695, 27703), True, 'import numpy as np\n'), ((27905, 27950), 'msprime.RecombinationMap.uniform_map', 'msprime.RecombinationMap.uniform_map', (['m', 'r', 'm'], {}), '(m, r, m)\n', (27941, 27950), False, 'import msprime\n'), ((27975, 28045), 'msprime.simulate', 'msprime.simulate', (['n'], {'recombination_map': 'recomb_map', 'mutation_rate': 'theta'}), '(n, recombination_map=recomb_map, mutation_rate=theta)\n', (27991, 28045), False, 'import msprime\n'), ((28701, 28807), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'length': '(100)', 'recombination_rate': '(1)', 'demographic_events': 'bottlenecks', 'random_seed': '(1)'}), '(10, length=100, recombination_rate=1, demographic_events=\n bottlenecks, random_seed=1)\n', (28717, 28807), False, 'import msprime\n'), ((28961, 28999), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'mutation_rate': '(10)'}), '(10, mutation_rate=10)\n', (28977, 28999), False, 'import msprime\n'), ((29839, 29874), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (29855, 29874), False, 'import msprime\n'), ((30112, 30147), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (30128, 30147), False, 'import msprime\n'), ((30375, 30410), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (30391, 30410), False, 'import msprime\n'), ((30678, 30713), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (30694, 30713), False, 'import msprime\n'), ((31243, 31278), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (31259, 31278), False, 'import msprime\n'), ((31840, 31875), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (31856, 31875), False, 'import msprime\n'), ((32078, 32104), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.0)'], {}), '(1.0)\n', (32099, 32104), False, 'import tskit\n'), ((33900, 33952), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'mutation_rate': '(5)', 'random_seed': '(2)'}), '(10, mutation_rate=5, random_seed=2)\n', (33916, 33952), False, 'import msprime\n'), ((34086, 34108), 'numpy.array_equal', 'np.array_equal', (['G1', 'G2'], {}), '(G1, G2)\n', (34100, 34108), True, 'import numpy as np\n'), ((34429, 34481), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'mutation_rate': '(5)', 'random_seed': '(2)'}), '(10, mutation_rate=5, random_seed=2)\n', (34445, 34481), False, 'import msprime\n'), ((34655, 34677), 'numpy.array_equal', 'np.array_equal', (['G1', 'G2'], {}), '(G1, G2)\n', (34669, 34677), True, 'import numpy as np\n'), ((34991, 35043), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'mutation_rate': '(5)', 'random_seed': '(2)'}), '(10, mutation_rate=5, random_seed=2)\n', (35007, 35043), False, 'import msprime\n'), ((35218, 35244), 'numpy.array_equal', 'np.array_equal', (['(G1 + 3)', 'G2'], {}), '(G1 + 3, G2)\n', (35232, 35244), True, 'import numpy as np\n'), ((35564, 35616), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'mutation_rate': '(5)', 'random_seed': '(2)'}), '(10, mutation_rate=5, random_seed=2)\n', (35580, 35616), False, 'import msprime\n'), ((35782, 35799), 'numpy.where', 'np.where', (['(G1 == 1)'], {}), '(G1 == 1)\n', (35790, 35799), True, 'import numpy as np\n'), ((35837, 35859), 'numpy.array_equal', 'np.array_equal', (['G1', 'G2'], {}), '(G1, G2)\n', (35851, 35859), True, 'import numpy as np\n'), ((36239, 36274), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (36255, 36274), False, 'import msprime\n'), ((36975, 37010), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'random_seed': '(2)'}), '(10, random_seed=2)\n', (36991, 37010), False, 'import msprime\n'), ((37685, 37737), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'mutation_rate': '(5)', 'random_seed': '(2)'}), '(10, mutation_rate=5, random_seed=2)\n', (37701, 37737), False, 'import msprime\n'), ((38100, 38152), 'msprime.simulate', 'msprime.simulate', (['(10)'], {'mutation_rate': '(5)', 'random_seed': '(2)'}), '(10, mutation_rate=5, random_seed=2)\n', (38116, 38152), False, 'import msprime\n'), ((38379, 38403), 'tskit.TableCollection', 'tskit.TableCollection', (['(1)'], {}), '(1)\n', (38400, 38403), False, 'import tskit\n'), ((39879, 39930), 'msprime.simulate', 'msprime.simulate', (['(5)'], {'mutation_rate': '(2)', 'random_seed': '(3)'}), '(5, mutation_rate=2, random_seed=3)\n', (39895, 39930), False, 'import msprime\n'), ((40322, 40356), 'msprime.simulate', 'msprime.simulate', (['(5)'], {'random_seed': '(3)'}), '(5, random_seed=3)\n', (40338, 40356), False, 'import msprime\n'), ((40816, 40867), 'msprime.simulate', 'msprime.simulate', (['(6)'], {'random_seed': '(1)', 'mutation_rate': '(1)'}), '(6, random_seed=1, mutation_rate=1)\n', (40832, 40867), False, 'import msprime\n'), ((40881, 40920), 'tests.tsutil.jukes_cantor', 'tsutil.jukes_cantor', (['ts', '(20)', '(1)'], {'seed': '(10)'}), '(ts, 20, 1, seed=10)\n', (40900, 40920), True, 'import tests.tsutil as tsutil\n'), ((41228, 41284), 'msprime.simulate', 'msprime.simulate', (['(6)'], {'random_seed': '(1)', 'recombination_rate': '(2)'}), '(6, random_seed=1, recombination_rate=2)\n', (41244, 41284), False, 'import msprime\n'), ((41298, 41335), 'tests.tsutil.insert_multichar_mutations', 'tsutil.insert_multichar_mutations', (['ts'], {}), '(ts)\n', (41331, 41335), True, 'import tests.tsutil as tsutil\n'), ((41652, 41703), 'msprime.simulate', 'msprime.simulate', (['(6)'], {'mutation_rate': '(2)', 'random_seed': '(3)'}), '(6, mutation_rate=2, random_seed=3)\n', (41668, 41703), False, 'import msprime\n'), ((43160, 43196), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['G', 'Gp'], {}), '(G, Gp)\n', (43189, 43196), True, 'import numpy as np\n'), ((44464, 44626), 'textwrap.dedent', 'textwrap.dedent', (['""" >n0\n 01G345678T\n >n1\n 01A345678C\n >n2\n 01A345678C\n """'], {}), '(\n """ >n0\n 01G345678T\n >n1\n 01A345678C\n >n2\n 01A345678C\n """\n )\n', (44479, 44626), False, 'import textwrap\n'), ((44803, 45309), 'textwrap.dedent', 'textwrap.dedent', (['""" #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=3;\n TAXLABELS n0 n1 n2;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n ;\n END;\n BEGIN TREES;\n TREE t0^10 = [&R] (n0:2,(n1:1,n2:1):1);\n END;\n """'], {}), '(\n """ #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=3;\n TAXLABELS n0 n1 n2;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n ;\n END;\n BEGIN TREES;\n TREE t0^10 = [&R] (n0:2,(n1:1,n2:1):1);\n END;\n """\n )\n', (44818, 45309), False, 'import textwrap\n'), ((46646, 46682), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['G', 'Gp'], {}), '(G, Gp)\n', (46675, 46682), True, 'import numpy as np\n'), ((49149, 49350), 'textwrap.dedent', 'textwrap.dedent', (['""" >n0\n 01G345678T\n >n1\n 01A345678C\n >n2\n 01A345678C\n >n5\n NNNNNNNNNN\n """'], {}), '(\n """ >n0\n 01G345678T\n >n1\n 01A345678C\n >n2\n 01A345678C\n >n5\n NNNNNNNNNN\n """\n )\n', (49164, 49350), False, 'import textwrap\n'), ((49604, 49805), 'textwrap.dedent', 'textwrap.dedent', (['""" >n0\n 01G345678T\n >n1\n 01A345678C\n >n2\n 01A345678C\n >n5\n QQQQQQQQQQ\n """'], {}), '(\n """ >n0\n 01G345678T\n >n1\n 01A345678C\n >n2\n 01A345678C\n >n5\n QQQQQQQQQQ\n """\n )\n', (49619, 49805), False, 'import textwrap\n'), ((50083, 50284), 'textwrap.dedent', 'textwrap.dedent', (['""" >n0\n NNGNNNNNNT\n >n1\n NNANNNNNNC\n >n2\n NNANNNNNNC\n >n5\n NNANNNNNNT\n """'], {}), '(\n """ >n0\n NNGNNNNNNT\n >n1\n NNANNNNNNC\n >n2\n NNANNNNNNC\n >n5\n NNANNNNNNT\n """\n )\n', (50098, 50284), False, 'import textwrap\n'), ((50802, 51255), 'textwrap.dedent', 'textwrap.dedent', (['""" #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=4;\n TAXLABELS n0 n1 n2 n5;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA MISSING=?;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n n5 ??????????\n ;\n END;\n """'], {}), '(\n """ #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=4;\n TAXLABELS n0 n1 n2 n5;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA MISSING=?;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n n5 ??????????\n ;\n END;\n """\n )\n', (50817, 51255), False, 'import textwrap\n'), ((51552, 52005), 'textwrap.dedent', 'textwrap.dedent', (['""" #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=4;\n TAXLABELS n0 n1 n2 n5;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA MISSING=Q;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n n5 QQQQQQQQQQ\n ;\n END;\n """'], {}), '(\n """ #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=4;\n TAXLABELS n0 n1 n2 n5;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA MISSING=Q;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n n5 QQQQQQQQQQ\n ;\n END;\n """\n )\n', (51567, 52005), False, 'import textwrap\n'), ((52333, 52786), 'textwrap.dedent', 'textwrap.dedent', (['""" #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=4;\n TAXLABELS n0 n1 n2 n5;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA MISSING=?;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n n5 01A345678T\n ;\n END;\n """'], {}), '(\n """ #NEXUS\n BEGIN TAXA;\n DIMENSIONS NTAX=4;\n TAXLABELS n0 n1 n2 n5;\n END;\n BEGIN DATA;\n DIMENSIONS NCHAR=10;\n FORMAT DATATYPE=DNA MISSING=?;\n MATRIX\n n0 01G345678T\n n1 01A345678C\n n2 01A345678C\n n5 01A345678T\n ;\n END;\n """\n )\n', (52348, 52786), False, 'import textwrap\n'), ((53203, 53252), 'tskit.Tree.generate_balanced', 'tskit.Tree.generate_balanced', (['(4)'], {'arity': '(2)', 'span': '(10)'}), '(4, arity=2, span=10)\n', (53231, 53252), False, 'import tskit\n'), ((54056, 54092), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['G', 'Gp'], {}), '(G, Gp)\n', (54085, 54092), True, 'import numpy as np\n'), ((54726, 54927), 'textwrap.dedent', 'textwrap.dedent', (['""" >n0\n 01T34567C9\n >n1\n 01G34567C9\n >n2\n 01G34567A9\n >n3\n 01G34567A9\n """'], {}), '(\n """ >n0\n 01T34567C9\n >n1\n 01G34567C9\n >n2\n 01G34567A9\n >n3\n 01G34567A9\n """\n )\n', (54741, 54927), False, 'import textwrap\n'), ((55112, 55136), 'tskit.TableCollection', 'tskit.TableCollection', (['(1)'], {}), '(1)\n', (55133, 55136), False, 'import tskit\n'), ((57312, 57367), 'tskit.random_nucleotides', 'tskit.random_nucleotides', (['ts.sequence_length'], {'seed': '(1234)'}), '(ts.sequence_length, seed=1234)\n', (57336, 57367), False, 'import tskit\n'), ((7255, 7274), 'numpy.all', 'np.all', (['(A[j] == row)'], {}), '(A[j] == row)\n', (7261, 7274), True, 'import numpy as np\n'), ((7397, 7422), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7410, 7422), False, 'import pytest\n'), ((7951, 7994), 'numpy.array_equal', 'np.array_equal', (['G[var.index]', 'var.genotypes'], {}), '(G[var.index], var.genotypes)\n', (7965, 7994), True, 'import numpy as np\n'), ((8014, 8051), 'numpy.all', 'np.all', (['(G[var.index] == var.genotypes)'], {}), '(G[var.index] == var.genotypes)\n', (8020, 8051), True, 'import numpy as np\n'), ((8246, 8289), 'numpy.array_equal', 'np.array_equal', (['G[var.index]', 'var.genotypes'], {}), '(G[var.index], var.genotypes)\n', (8260, 8289), True, 'import numpy as np\n'), ((14428, 14462), 'itertools.permutations', 'itertools.permutations', (['samples', 'j'], {}), '(samples, j)\n', (14450, 14462), False, 'import itertools\n'), ((15470, 15504), 'itertools.permutations', 'itertools.permutations', (['samples', 'j'], {}), '(samples, j)\n', (15492, 15504), False, 'import itertools\n'), ((16971, 17017), 'numpy.array_equal', 'np.array_equal', (['var1.genotypes', 'var2.genotypes'], {}), '(var1.genotypes, var2.genotypes)\n', (16985, 17017), True, 'import numpy as np\n'), ((19139, 19166), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (19151, 19166), False, 'import pytest\n'), ((19282, 19309), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (19294, 19309), False, 'import pytest\n'), ((19428, 19455), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (19440, 19455), False, 'import pytest\n'), ((19596, 19623), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (19608, 19623), False, 'import pytest\n'), ((24159, 24204), 'numpy.array_equal', 'np.array_equal', (['var.genotypes', 'G[var.site.id]'], {}), '(var.genotypes, G[var.site.id])\n', (24173, 24204), True, 'import numpy as np\n'), ((24648, 24693), 'numpy.array_equal', 'np.array_equal', (['var.genotypes', 'G[var.site.id]'], {}), '(var.genotypes, G[var.site.id])\n', (24662, 24693), True, 'import numpy as np\n'), ((26340, 26385), 'numpy.array_equal', 'np.array_equal', (['var.genotypes', 'G[var.site.id]'], {}), '(var.genotypes, G[var.site.id])\n', (26354, 26385), True, 'import numpy as np\n'), ((28242, 28263), 'random.randint', 'random.randint', (['(2)', '(50)'], {}), '(2, 50)\n', (28256, 28263), False, 'import random\n'), ((28280, 28303), 'random.randint', 'random.randint', (['(10)', '(200)'], {}), '(10, 200)\n', (28294, 28303), False, 'import random\n'), ((28320, 28335), 'random.random', 'random.random', ([], {}), '()\n', (28333, 28335), False, 'import random\n'), ((28356, 28376), 'random.uniform', 'random.uniform', (['(0)', '(2)'], {}), '(0, 2)\n', (28370, 28376), False, 'import random\n'), ((28501, 28551), 'msprime.SimpleBottleneck', 'msprime.SimpleBottleneck', (['(0.01)', '(0)'], {'proportion': '(0.05)'}), '(0.01, 0, proportion=0.05)\n', (28525, 28551), False, 'import msprime\n'), ((28565, 28615), 'msprime.SimpleBottleneck', 'msprime.SimpleBottleneck', (['(0.02)', '(0)'], {'proportion': '(0.25)'}), '(0.02, 0, proportion=0.25)\n', (28589, 28615), False, 'import msprime\n'), ((28629, 28676), 'msprime.SimpleBottleneck', 'msprime.SimpleBottleneck', (['(0.03)', '(0)'], {'proportion': '(1)'}), '(0.03, 0, proportion=1)\n', (28653, 28676), False, 'import msprime\n'), ((29992, 30016), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (30005, 30016), False, 'import pytest\n'), ((30261, 30285), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (30274, 30285), False, 'import pytest\n'), ((30550, 30574), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (30563, 30574), False, 'import pytest\n'), ((31921, 31984), 'tests.tsutil.insert_branch_mutations', 'tsutil.insert_branch_mutations', (['base_ts'], {'mutations_per_branch': 'j'}), '(base_ts, mutations_per_branch=j)\n', (31951, 31984), True, 'import tests.tsutil as tsutil\n'), ((32301, 32326), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (32314, 32326), False, 'import pytest\n'), ((32805, 32832), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (32817, 32832), False, 'import pytest\n'), ((32940, 32967), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (32952, 32967), False, 'import pytest\n'), ((33076, 33103), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (33088, 33103), False, 'import pytest\n'), ((33237, 33264), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (33249, 33264), False, 'import pytest\n'), ((33399, 33426), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (33411, 33426), False, 'import pytest\n'), ((33561, 33588), 'pytest.warns', 'pytest.warns', (['FutureWarning'], {}), '(FutureWarning)\n', (33573, 33588), False, 'import pytest\n'), ((34325, 34367), 'numpy.array_equal', 'np.array_equal', (['v1.genotypes', 'v2.genotypes'], {}), '(v1.genotypes, v2.genotypes)\n', (34339, 34367), True, 'import numpy as np\n'), ((34888, 34930), 'numpy.array_equal', 'np.array_equal', (['v1.genotypes', 'v2.genotypes'], {}), '(v1.genotypes, v2.genotypes)\n', (34902, 34930), True, 'import numpy as np\n'), ((35455, 35501), 'numpy.array_equal', 'np.array_equal', (['(v1.genotypes + 3)', 'v2.genotypes'], {}), '(v1.genotypes + 3, v2.genotypes)\n', (35469, 35501), True, 'import numpy as np\n'), ((36100, 36116), 'numpy.where', 'np.where', (['(g == 1)'], {}), '(g == 1)\n', (36108, 36116), True, 'import numpy as np\n'), ((36161, 36192), 'numpy.array_equal', 'np.array_equal', (['g', 'v2.genotypes'], {}), '(g, v2.genotypes)\n', (36175, 36192), True, 'import numpy as np\n'), ((36881, 36924), 'numpy.array_equal', 'np.array_equal', (['v2.genotypes', 'G[v1.site.id]'], {}), '(v2.genotypes, G[v1.site.id])\n', (36895, 36924), True, 'import numpy as np\n'), ((38166, 38191), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (38179, 38191), False, 'import pytest\n'), ((38254, 38279), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (38267, 38279), False, 'import pytest\n'), ((38933, 38955), 'numpy.array_equal', 'np.array_equal', (['G1', 'G2'], {}), '(G1, G2)\n', (38947, 38955), True, 'import numpy as np\n'), ((39184, 39219), 'itertools.zip_longest', 'itertools.zip_longest', (['vars1', 'vars2'], {}), '(vars1, vars2)\n', (39205, 39219), False, 'import itertools\n'), ((42519, 42559), 'tskit.Tree.generate_balanced', 'tskit.Tree.generate_balanced', (['(3)'], {'span': '(10)'}), '(3, span=10)\n', (42547, 42559), False, 'import tskit\n'), ((45675, 45715), 'tskit.Tree.generate_balanced', 'tskit.Tree.generate_balanced', (['(3)'], {'span': '(10)'}), '(3, span=10)\n', (45703, 45715), False, 'import tskit\n'), ((47105, 47144), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""1896"""'}), "(ValueError, match='1896')\n", (47118, 47144), False, 'import pytest\n'), ((55369, 55432), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""defined for discrete genomes"""'}), "(ValueError, match='defined for discrete genomes')\n", (55382, 55432), False, 'import pytest\n'), ((55569, 55608), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""1888"""'}), "(ValueError, match='1888')\n", (55582, 55608), False, 'import pytest\n'), ((55798, 55844), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""same length"""'}), "(ValueError, match='same length')\n", (55811, 55844), False, 'import pytest\n'), ((56047, 56080), 'pytest.raises', 'pytest.raises', (['UnicodeEncodeError'], {}), '(UnicodeEncodeError)\n', (56060, 56080), False, 'import pytest\n'), ((56377, 56410), 'pytest.raises', 'pytest.raises', (['UnicodeEncodeError'], {}), '(UnicodeEncodeError)\n', (56390, 56410), False, 'import pytest\n'), ((6931, 6973), 'numpy.frombuffer', 'np.frombuffer', (['variant.genotypes', 'np.uint8'], {}), '(variant.genotypes, np.uint8)\n', (6944, 6973), True, 'import numpy as np\n'), ((7182, 7224), 'numpy.frombuffer', 'np.frombuffer', (['variant.genotypes', 'np.uint8'], {}), '(variant.genotypes, np.uint8)\n', (7195, 7224), True, 'import numpy as np\n'), ((8955, 8990), 'itertools.permutations', 'itertools.permutations', (['"""ABCDEF"""', '(4)'], {}), "('ABCDEF', 4)\n", (8977, 8990), False, 'import itertools\n'), ((10302, 10337), 'itertools.permutations', 'itertools.permutations', (['"""ABCDEF"""', '(4)'], {}), "('ABCDEF', 4)\n", (10324, 10337), False, 'import itertools\n'), ((14484, 14511), 'numpy.array', 'np.array', (['s'], {'dtype': 'np.int32'}), '(s, dtype=np.int32)\n', (14492, 14511), True, 'import numpy as np\n'), ((15526, 15553), 'numpy.array', 'np.array', (['s'], {'dtype': 'np.int32'}), '(s, dtype=np.int32)\n', (15534, 15553), True, 'import numpy as np\n'), ((23930, 23973), 'numpy.all', 'np.all', (['(var.genotypes == tskit.MISSING_DATA)'], {}), '(var.genotypes == tskit.MISSING_DATA)\n', (23936, 23973), True, 'import numpy as np\n'), ((24096, 24139), 'numpy.all', 'np.all', (['(var.genotypes != tskit.MISSING_DATA)'], {}), '(var.genotypes != tskit.MISSING_DATA)\n', (24102, 24139), True, 'import numpy as np\n'), ((24469, 24495), 'numpy.all', 'np.all', (['(var.genotypes == 0)'], {}), '(var.genotypes == 0)\n', (24475, 24495), True, 'import numpy as np\n'), ((24585, 24628), 'numpy.all', 'np.all', (['(var.genotypes != tskit.MISSING_DATA)'], {}), '(var.genotypes != tskit.MISSING_DATA)\n', (24591, 24628), True, 'import numpy as np\n'), ((25928, 25975), 'numpy.all', 'np.all', (['(var.genotypes[1:] == tskit.MISSING_DATA)'], {}), '(var.genotypes[1:] == tskit.MISSING_DATA)\n', (25934, 25975), True, 'import numpy as np\n'), ((29302, 29346), 'numpy.arange', 'np.arange', (['(ts.num_sites + 1)'], {'dtype': 'np.uint32'}), '(ts.num_sites + 1, dtype=np.uint32)\n', (29311, 29346), True, 'import numpy as np\n'), ((29564, 29608), 'numpy.arange', 'np.arange', (['(ts.num_sites + 1)'], {'dtype': 'np.uint32'}), '(ts.num_sites + 1, dtype=np.uint32)\n', (29573, 29608), True, 'import numpy as np\n'), ((36349, 36391), 'msprime.InfiniteSites', 'msprime.InfiniteSites', (['msprime.NUCLEOTIDES'], {}), '(msprime.NUCLEOTIDES)\n', (36370, 36391), False, 'import msprime\n'), ((37085, 37127), 'msprime.InfiniteSites', 'msprime.InfiniteSites', (['msprime.NUCLEOTIDES'], {}), '(msprime.NUCLEOTIDES)\n', (37106, 37127), False, 'import msprime\n'), ((37426, 37464), 'pytest.raises', 'pytest.raises', (['exceptions.LibraryError'], {}), '(exceptions.LibraryError)\n', (37439, 37464), False, 'import pytest\n'), ((37539, 37577), 'pytest.raises', 'pytest.raises', (['exceptions.LibraryError'], {}), '(exceptions.LibraryError)\n', (37552, 37577), False, 'import pytest\n'), ((37846, 37884), 'pytest.raises', 'pytest.raises', (['exceptions.LibraryError'], {}), '(exceptions.LibraryError)\n', (37859, 37884), False, 'import pytest\n'), ((37959, 37997), 'pytest.raises', 'pytest.raises', (['exceptions.LibraryError'], {}), '(exceptions.LibraryError)\n', (37972, 37997), False, 'import pytest\n'), ((39334, 39376), 'numpy.array_equal', 'np.array_equal', (['v1.genotypes', 'v2.genotypes'], {}), '(v1.genotypes, v2.genotypes)\n', (39348, 39376), True, 'import numpy as np\n'), ((40431, 40473), 'msprime.InfiniteSites', 'msprime.InfiniteSites', (['msprime.NUCLEOTIDES'], {}), '(msprime.NUCLEOTIDES)\n', (40452, 40473), False, 'import msprime\n'), ((55275, 55301), 'tskit.TableCollection', 'tskit.TableCollection', (['(1.1)'], {}), '(1.1)\n', (55296, 55301), False, 'import tskit\n'), ((55515, 55539), 'tskit.TableCollection', 'tskit.TableCollection', (['(1)'], {}), '(1)\n', (55536, 55539), False, 'import tskit\n'), ((57444, 57483), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""1896"""'}), "(ValueError, match='1896')\n", (57457, 57483), False, 'import pytest\n'), ((9245, 9283), 'pytest.raises', 'pytest.raises', (['exceptions.LibraryError'], {}), '(exceptions.LibraryError)\n', (9258, 9283), False, 'import pytest\n'), ((10592, 10630), 'pytest.raises', 'pytest.raises', (['exceptions.LibraryError'], {}), '(exceptions.LibraryError)\n', (10605, 10630), False, 'import pytest\n'), ((13073, 13096), 'numpy.ones', 'np.ones', (['ts.sample_size'], {}), '(ts.sample_size)\n', (13080, 13096), True, 'import numpy as np\n'), ((14810, 14859), 'numpy.array_equal', 'np.array_equal', (['var1.genotypes[s]', 'var2.genotypes'], {}), '(var1.genotypes[s], var2.genotypes)\n', (14824, 14859), True, 'import numpy as np\n'), ((15852, 15901), 'numpy.array_equal', 'np.array_equal', (['var1.genotypes[s]', 'var2.genotypes'], {}), '(var1.genotypes[s], var2.genotypes)\n', (15866, 15901), True, 'import numpy as np\n'), ((16361, 16394), 'numpy.zeros_like', 'np.zeros_like', (['tables.nodes.flags'], {}), '(tables.nodes.flags)\n', (16374, 16394), True, 'import numpy as np\n'), ((26123, 26149), 'numpy.all', 'np.all', (['(var.genotypes == 0)'], {}), '(var.genotypes == 0)\n', (26129, 26149), True, 'import numpy as np\n'), ((26277, 26320), 'numpy.all', 'np.all', (['(var.genotypes != tskit.MISSING_DATA)'], {}), '(var.genotypes != tskit.MISSING_DATA)\n', (26283, 26320), True, 'import numpy as np\n'), ((29217, 29254), 'numpy.zeros', 'np.zeros', (['ts.num_sites'], {'dtype': 'np.int8'}), '(ts.num_sites, dtype=np.int8)\n', (29225, 29254), True, 'import numpy as np\n'), ((29481, 29518), 'numpy.zeros', 'np.zeros', (['ts.num_sites'], {'dtype': 'np.int8'}), '(ts.num_sites, dtype=np.int8)\n', (29489, 29518), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# @file wrapper.py
# @Author <NAME> (adityavaishampayan)
# @copyright MIT
# @brief main file that calls all other sub functions
import sys
# noinspection PyBroadException
try:
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
except BaseException:
pass
import cv2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
import argparse
from scripts.LoadData import *
from scripts.bdl_adjst import *
from scripts.visibikity_matrx import *
from scripts.NonLinearPnP import *
from scripts.DrawCameras import camera_draw
from scripts.ExtractCameraPose import extract_cam_pose
from scripts.EssentialMatrixFromFundamentalMatrix import e_from_fundamental
from scripts.NonLinearTriangulation import *
from scripts.EstimateFundamentalMatrix import est_from_funda
from scripts.PnPRANSAC import *
from scripts.disambguate_camera_pose import *
from scripts.LinearTriangulation import *
K = np.array([[568.996140852, 0, 643.21055941],
[0, 568.988362396, 477.982801038],
[0, 0, 1]])
W = np.array([[0, -1, 0],
[1, 0, 0],
[0, 0, 1]])
n_images = 6
img1 = 1
img2 = 4
Parser = argparse.ArgumentParser()
Parser.add_argument(
'--DataPath', default="./Data/", help='Folder of Images')
Parser.add_argument(
'--Visualize', default=False, help='Show correspondences')
Args = Parser.parse_args()
DataPath = Args.DataPath
visualize = Args.Visualize
x_coord_matrix, y_coord_matrix, M, Color = LoadData(DataPath)
M, outlier_indices = inlier_filter(x_coord_matrix, y_coord_matrix, M, n_images)
recon_bin = np.zeros((M.shape[0], 1))
X_3D = np.zeros((M.shape[0], 3))
opt = np.logical_and(M[:, img1 - 1], M[:, img2 - 1])
outlier_idx = np.where(np.logical_and(outlier_indices[:, img1 - 1],
outlier_indices[:, img2 - 1]) == True)
indices, = np.where(opt == True)
rgb_list = Color[indices]
best_F = est_from_funda(np.float32(np.hstack((x_coord_matrix[indices, img1 - 1].reshape((-1, 1)),
y_coord_matrix[indices, img1 - 1].reshape((-1, 1))))),
np.float32(np.hstack((x_coord_matrix[indices, img2 - 1].reshape((-1, 1)),
y_coord_matrix[indices, img2 - 1].reshape((-1, 1))))))
E = e_from_fundamental(best_F, K)
R_set, C_set = extract_cam_pose(E, K)
X_set = []
for n in range(0, 4):
X1 = LinearTriangulation(K, np.zeros((3, 1)), np.identity(3),
C_set[n].T, R_set[n],
np.float32(np.hstack((x_coord_matrix[indices, img1 - 1].reshape((-1, 1)),
y_coord_matrix[indices, img1 - 1].reshape((-1, 1))))),
np.float32(np.hstack((x_coord_matrix[indices, img2 - 1].reshape((-1, 1)),
y_coord_matrix[indices, img2 - 1].reshape((-1, 1))))))
X_set.append(X1)
X, R, C = disambguate_camera_pose(C_set, R_set, X_set)
recon_bin = np.zeros((M.shape[0], 1))
X_3D = np.zeros((M.shape[0], 3))
Visibility = np.zeros((M.shape[0], n_images))
X = NonLinearTriangulation(K, np.float32(np.hstack((x_coord_matrix[indices, img1 - 1].reshape((-1, 1)),
y_coord_matrix[indices, img1 - 1].reshape((-1, 1))))),
np.float32(np.hstack((x_coord_matrix[indices, img2 - 1].reshape((-1, 1)),
y_coord_matrix[indices, img2 - 1].reshape((-1, 1))))), X, np.eye(3),
np.zeros((3, 1)), R, C)
recon_bin[indices] = 1
X_3D[indices, :] = X
Visibility[indices, img1 - 1] = 1
Visibility[indices, img2 - 1] = 1
Cset = []
Rset = []
Cset.append(C)
Rset.append(R)
r_indx = [img1, img2]
for i in range(0, n_images):
if (np.isin(r_indx, i)[0]):
continue
opt = np.logical_and(recon_bin, M[:, i].reshape((-1, 1)))
indices, _ = np.where(opt == True)
if (len(indices) < 8):
continue
x = np.transpose([x_coord_matrix[indices, i], y_coord_matrix[indices, i]])
X = X_3D[indices, :]
C, R = PnPRANSAC(X, x, K)
C, R = NonLinearPnP(X, x, K, C, R)
Cset.append(C)
Rset.append(R)
r_indx.append(i)
Visibility[indices, i] = 1
for j in range(0, len(r_indx) - 1):
opt = np.logical_and(
np.logical_and(1 - recon_bin, M[:, r_indx[j]].reshape(
(-1, 1))), M[:, i].reshape((-1, 1)))
indices, _ = np.where(opt == True)
if (len(indices) < 8):
continue
x1 = np.hstack((x_coord_matrix[indices, r_indx[j]].reshape((-1, 1)),
y_coord_matrix[indices, r_indx[j]].reshape((-1, 1))))
x2 = np.hstack((x_coord_matrix[indices, i].reshape((-1, 1)),
y_coord_matrix[indices, i].reshape((-1, 1))))
X = LinearTriangulation(K, Cset[j], Rset[j], C, R, x1, x2)
X_3D[indices, :] = X
recon_bin[indices] = 1
Visibility[indices, r_indx[j]] = 1
Visibility[indices, j] = 1
for o in range(len(X_3D)):
if (X_3D[o, 2] < 0):
Visibility[o, :] = 0
recon_bin[o] = 0
V_bundle = visibikity_matrx(Visibility, r_indx)
point_indices, _ = np.where(recon_bin == 1)
camera_indices = i * np.ones((len(point_indices), 1))
points_2d = np.hstack((x_coord_matrix[point_indices, i].reshape((-1, 1)),
x_coord_matrix[point_indices, i].reshape((-1, 1))))
Rset, Cset, X_3D = bdl_adjst(Cset, Rset, X_3D, K, points_2d,
camera_indices, recon_bin,
V_bundle)
ind, _ = np.where(recon_bin == 1)
X_3D = X_3D[ind, :]
Color = Color[ind, :]
ax = plt.axes(projection='3d')
ax.scatter3D(
X_3D[:, 0], X_3D[:, 1], X_3D[:, 2], c=Color / 255.0,
s=1)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_xlim([-0.5, 1])
ax.set_ylim([-0.5, 1])
ax.set_zlim([0, 1.5])
plt.show()
plt.scatter(X_3D[:, 0], X_3D[:, 2], c=Color / 255.0, s=1)
camera_draw(C_set, R_set)
ax1 = plt.gca()
ax1.set_xlabel('x')
ax1.set_ylabel('z')
plt.show()
|
[
"numpy.isin",
"sys.path.remove",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"numpy.logical_and",
"scripts.DrawCameras.camera_draw",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.scatter",
"numpy.eye",
"numpy.zeros",
"numpy.transpose",
"numpy.identity",
"numpy.where",
"numpy.array",
"matplotlib.pyplot.gca",
"scripts.ExtractCameraPose.extract_cam_pose",
"scripts.EssentialMatrixFromFundamentalMatrix.e_from_fundamental"
] |
[((2049, 2144), 'numpy.array', 'np.array', (['[[568.996140852, 0, 643.21055941], [0, 568.988362396, 477.982801038], [0, 0, 1]\n ]'], {}), '([[568.996140852, 0, 643.21055941], [0, 568.988362396, \n 477.982801038], [0, 0, 1]])\n', (2057, 2144), True, 'import numpy as np\n'), ((2240, 2284), 'numpy.array', 'np.array', (['[[0, -1, 0], [1, 0, 0], [0, 0, 1]]'], {}), '([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n', (2248, 2284), True, 'import numpy as np\n'), ((2358, 2383), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2381, 2383), False, 'import argparse\n'), ((2787, 2812), 'numpy.zeros', 'np.zeros', (['(M.shape[0], 1)'], {}), '((M.shape[0], 1))\n', (2795, 2812), True, 'import numpy as np\n'), ((2821, 2846), 'numpy.zeros', 'np.zeros', (['(M.shape[0], 3)'], {}), '((M.shape[0], 3))\n', (2829, 2846), True, 'import numpy as np\n'), ((2854, 2900), 'numpy.logical_and', 'np.logical_and', (['M[:, img1 - 1]', 'M[:, img2 - 1]'], {}), '(M[:, img1 - 1], M[:, img2 - 1])\n', (2868, 2900), True, 'import numpy as np\n'), ((3058, 3079), 'numpy.where', 'np.where', (['(opt == True)'], {}), '(opt == True)\n', (3066, 3079), True, 'import numpy as np\n'), ((3544, 3573), 'scripts.EssentialMatrixFromFundamentalMatrix.e_from_fundamental', 'e_from_fundamental', (['best_F', 'K'], {}), '(best_F, K)\n', (3562, 3573), False, 'from scripts.EssentialMatrixFromFundamentalMatrix import e_from_fundamental\n'), ((3589, 3611), 'scripts.ExtractCameraPose.extract_cam_pose', 'extract_cam_pose', (['E', 'K'], {}), '(E, K)\n', (3605, 3611), False, 'from scripts.ExtractCameraPose import extract_cam_pose\n'), ((4271, 4296), 'numpy.zeros', 'np.zeros', (['(M.shape[0], 1)'], {}), '((M.shape[0], 1))\n', (4279, 4296), True, 'import numpy as np\n'), ((4304, 4329), 'numpy.zeros', 'np.zeros', (['(M.shape[0], 3)'], {}), '((M.shape[0], 3))\n', (4312, 4329), True, 'import numpy as np\n'), ((4343, 4375), 'numpy.zeros', 'np.zeros', (['(M.shape[0], n_images)'], {}), '((M.shape[0], n_images))\n', (4351, 4375), True, 'import numpy as np\n'), ((6976, 7000), 'numpy.where', 'np.where', (['(recon_bin == 1)'], {}), '(recon_bin == 1)\n', (6984, 7000), True, 'import numpy as np\n'), ((7051, 7076), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (7059, 7076), True, 'import matplotlib.pyplot as plt\n'), ((7290, 7300), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7298, 7300), True, 'import matplotlib.pyplot as plt\n'), ((7302, 7359), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X_3D[:, 0]', 'X_3D[:, 2]'], {'c': '(Color / 255.0)', 's': '(1)'}), '(X_3D[:, 0], X_3D[:, 2], c=Color / 255.0, s=1)\n', (7313, 7359), True, 'import matplotlib.pyplot as plt\n'), ((7361, 7386), 'scripts.DrawCameras.camera_draw', 'camera_draw', (['C_set', 'R_set'], {}), '(C_set, R_set)\n', (7372, 7386), False, 'from scripts.DrawCameras import camera_draw\n'), ((7394, 7403), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (7401, 7403), True, 'import matplotlib.pyplot as plt\n'), ((7447, 7457), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7455, 7457), True, 'import matplotlib.pyplot as plt\n'), ((1284, 1347), 'sys.path.remove', 'sys.path.remove', (['"""/opt/ros/kinetic/lib/python2.7/dist-packages"""'], {}), "('/opt/ros/kinetic/lib/python2.7/dist-packages')\n", (1299, 1347), False, 'import sys\n'), ((4796, 4805), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (4802, 4805), True, 'import numpy as np\n'), ((4834, 4850), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (4842, 4850), True, 'import numpy as np\n'), ((5210, 5231), 'numpy.where', 'np.where', (['(opt == True)'], {}), '(opt == True)\n', (5218, 5231), True, 'import numpy as np\n'), ((5286, 5356), 'numpy.transpose', 'np.transpose', (['[x_coord_matrix[indices, i], y_coord_matrix[indices, i]]'], {}), '([x_coord_matrix[indices, i], y_coord_matrix[indices, i]])\n', (5298, 5356), True, 'import numpy as np\n'), ((6542, 6566), 'numpy.where', 'np.where', (['(recon_bin == 1)'], {}), '(recon_bin == 1)\n', (6550, 6566), True, 'import numpy as np\n'), ((2925, 2999), 'numpy.logical_and', 'np.logical_and', (['outlier_indices[:, img1 - 1]', 'outlier_indices[:, img2 - 1]'], {}), '(outlier_indices[:, img1 - 1], outlier_indices[:, img2 - 1])\n', (2939, 2999), True, 'import numpy as np\n'), ((3678, 3694), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (3686, 3694), True, 'import numpy as np\n'), ((3696, 3710), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (3707, 3710), True, 'import numpy as np\n'), ((5088, 5106), 'numpy.isin', 'np.isin', (['r_indx', 'i'], {}), '(r_indx, i)\n', (5095, 5106), True, 'import numpy as np\n'), ((5762, 5783), 'numpy.where', 'np.where', (['(opt == True)'], {}), '(opt == True)\n', (5770, 5783), True, 'import numpy as np\n')]
|
import numpy as _np
from openpnm.utils import Docorator
__all__ = ["pore_coords"]
docstr = Docorator()
@docstr.dedent
def pore_coords(target):
r"""
Calculate throat centroid values by averaging adjacent pore coordinates
Parameters
----------
%(models.target.parameters)s
Returns
-------
values : ndarray
A numpy ndarray containing throat centroid values
"""
network = target.project.network
Ts = network.throats(target.name)
conns = network['throat.conns']
coords = network['pore.coords']
return _np.mean(coords[conns], axis=1)[Ts]
|
[
"numpy.mean",
"openpnm.utils.Docorator"
] |
[((93, 104), 'openpnm.utils.Docorator', 'Docorator', ([], {}), '()\n', (102, 104), False, 'from openpnm.utils import Docorator\n'), ((567, 598), 'numpy.mean', '_np.mean', (['coords[conns]'], {'axis': '(1)'}), '(coords[conns], axis=1)\n', (575, 598), True, 'import numpy as _np\n')]
|
import numpy as np
from ldpc import bposd_decoder
from panqec.codes import StabilizerCode
from panqec.error_models import BaseErrorModel
from panqec.decoders import BaseDecoder
class BeliefPropagationOSDDecoder(BaseDecoder):
label = 'BP-OSD decoder'
def __init__(self,
code: StabilizerCode,
error_model: BaseErrorModel,
error_rate: float,
max_bp_iter: int = 1000,
channel_update: bool = False,
osd_order: int = 10,
bp_method: str = 'msl'):
super().__init__(code, error_model, error_rate)
self._max_bp_iter = max_bp_iter
self._channel_update = channel_update
self._osd_order = osd_order
self._bp_method = bp_method
# Do not initialize the decoder until we call the decode method.
# This is required because during analysis, there is no need to
# initialize the decoder every time.
self._initialized = False
def get_probabilities(self):
pi, px, py, pz = self.error_model.probability_distribution(
self.code, self.error_rate
)
return pi, px, py, pz
def update_probabilities(self, correction: np.ndarray,
px: np.ndarray, py: np.ndarray, pz: np.ndarray,
direction: str = "x->z") -> np.ndarray:
"""Update X probabilities once a Z correction has been applied"""
n_qubits = correction.shape[0]
new_probs = np.zeros(n_qubits)
if direction == "z->x":
for i in range(n_qubits):
if correction[i] == 1:
if pz[i] + py[i] != 0:
new_probs[i] = py[i] / (pz[i] + py[i])
else:
new_probs[i] = px[i] / (1 - pz[i] - py[i])
elif direction == "x->z":
for i in range(n_qubits):
if correction[i] == 1:
if px[i] + py[i] != 0:
new_probs[i] = py[i] / (px[i] + py[i])
else:
new_probs[i] = pz[i] / (1 - px[i] - py[i])
else:
raise ValueError(
f"Unrecognized direction {direction} when "
"updating probabilities"
)
return new_probs
def initialize_decoders(self):
is_css = self.code.is_css
if is_css:
self.z_decoder = bposd_decoder(
self.code.Hx,
error_rate=self.error_rate,
max_iter=self._max_bp_iter,
bp_method=self._bp_method,
ms_scaling_factor=0,
osd_method="osd_cs", # Choose from: "osd_e", "osd_cs", "osd0"
osd_order=self._osd_order
)
self.x_decoder = bposd_decoder(
self.code.Hz,
error_rate=self.error_rate,
max_iter=self._max_bp_iter,
bp_method=self._bp_method,
ms_scaling_factor=0,
osd_method="osd_cs", # Choose from: "osd_e", "osd_cs", "osd0"
osd_order=self._osd_order
)
else:
self.decoder = bposd_decoder(
self.code.stabilizer_matrix,
error_rate=self.error_rate,
max_iter=self._max_bp_iter,
bp_method=self._bp_method,
ms_scaling_factor=0,
osd_method="osd_cs", # Choose from: "osd_e", "osd_cs", "osd0"
osd_order=self._osd_order
)
def decode(self, syndrome: np.ndarray, **kwargs) -> np.ndarray:
"""Get X and Z corrections given code and measured syndrome."""
if not self._initialized:
self.initialize_decoders()
is_css = self.code.is_css
n_qubits = self.code.n
syndrome = np.array(syndrome, dtype=int)
if is_css:
syndrome_z = self.code.extract_z_syndrome(syndrome)
syndrome_x = self.code.extract_x_syndrome(syndrome)
pi, px, py, pz = self.get_probabilities()
probabilities_x = px + py
probabilities_z = pz + py
probabilities = np.hstack([probabilities_z, probabilities_x])
if is_css:
# Update probabilities (in case the distribution is new at each
# iteration)
self.x_decoder.update_channel_probs(probabilities_x)
self.z_decoder.update_channel_probs(probabilities_z)
# Decode Z errors
self.z_decoder.decode(syndrome_x)
z_correction = self.z_decoder.osdw_decoding
# Bayes update of the probability
if self._channel_update:
new_x_probs = self.update_probabilities(
z_correction, px, py, pz, direction="z->x"
)
self.x_decoder.update_channel_probs(new_x_probs)
# Decode X errors
self.x_decoder.decode(syndrome_z)
x_correction = self.x_decoder.osdw_decoding
correction = np.concatenate([x_correction, z_correction])
else:
# Update probabilities (in case the distribution is new at each
# iteration)
self.decoder.update_channel_probs(probabilities)
# Decode all errors
self.decoder.decode(syndrome)
correction = self.decoder.osdw_decoding
correction = np.concatenate(
[correction[n_qubits:], correction[:n_qubits]]
)
return correction
def test_decoder():
from panqec.codes import XCubeCode
from panqec.error_models import PauliErrorModel
import time
rng = np.random.default_rng()
L = 20
code = XCubeCode(L, L, L)
error_rate = 0.5
r_x, r_y, r_z = [0.15, 0.15, 0.7]
error_model = PauliErrorModel(r_x, r_y, r_z)
print("Create stabilizer matrix")
code.stabilizer_matrix
print("Create Hx and Hz")
code.Hx
code.Hz
print("Create logicals")
code.logicals_x
code.logicals_z
print("Instantiate BP-OSD")
decoder = BeliefPropagationOSDDecoder(
code, error_model, error_rate, osd_order=0, max_bp_iter=1000
)
# Start timer
start = time.time()
n_iter = 1
accuracy = 0
for i in range(n_iter):
print(f"\nRun {code.label} {i}...")
print("Generate errors")
error = error_model.generate(code, error_rate, rng=rng)
print("Calculate syndrome")
syndrome = code.measure_syndrome(error)
print("Decode")
correction = decoder.decode(syndrome)
print("Get total error")
total_error = (correction + error) % 2
codespace = code.in_codespace(total_error)
success = not code.is_logical_error(total_error) and codespace
print(success)
accuracy += success
accuracy /= n_iter
print("Average time per iteration", (time.time() - start) / n_iter)
print("Logical error rate", 1 - accuracy)
if __name__ == '__main__':
test_decoder()
|
[
"numpy.zeros",
"time.time",
"numpy.random.default_rng",
"numpy.hstack",
"numpy.array",
"panqec.error_models.PauliErrorModel",
"panqec.codes.XCubeCode",
"ldpc.bposd_decoder",
"numpy.concatenate"
] |
[((5722, 5745), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (5743, 5745), True, 'import numpy as np\n'), ((5769, 5787), 'panqec.codes.XCubeCode', 'XCubeCode', (['L', 'L', 'L'], {}), '(L, L, L)\n', (5778, 5787), False, 'from panqec.codes import XCubeCode\n'), ((5866, 5896), 'panqec.error_models.PauliErrorModel', 'PauliErrorModel', (['r_x', 'r_y', 'r_z'], {}), '(r_x, r_y, r_z)\n', (5881, 5896), False, 'from panqec.error_models import PauliErrorModel\n'), ((6270, 6281), 'time.time', 'time.time', ([], {}), '()\n', (6279, 6281), False, 'import time\n'), ((1532, 1550), 'numpy.zeros', 'np.zeros', (['n_qubits'], {}), '(n_qubits)\n', (1540, 1550), True, 'import numpy as np\n'), ((3891, 3920), 'numpy.array', 'np.array', (['syndrome'], {'dtype': 'int'}), '(syndrome, dtype=int)\n', (3899, 3920), True, 'import numpy as np\n'), ((4214, 4259), 'numpy.hstack', 'np.hstack', (['[probabilities_z, probabilities_x]'], {}), '([probabilities_z, probabilities_x])\n', (4223, 4259), True, 'import numpy as np\n'), ((2460, 2648), 'ldpc.bposd_decoder', 'bposd_decoder', (['self.code.Hx'], {'error_rate': 'self.error_rate', 'max_iter': 'self._max_bp_iter', 'bp_method': 'self._bp_method', 'ms_scaling_factor': '(0)', 'osd_method': '"""osd_cs"""', 'osd_order': 'self._osd_order'}), "(self.code.Hx, error_rate=self.error_rate, max_iter=self.\n _max_bp_iter, bp_method=self._bp_method, ms_scaling_factor=0,\n osd_method='osd_cs', osd_order=self._osd_order)\n", (2473, 2648), False, 'from ldpc import bposd_decoder\n'), ((2838, 3026), 'ldpc.bposd_decoder', 'bposd_decoder', (['self.code.Hz'], {'error_rate': 'self.error_rate', 'max_iter': 'self._max_bp_iter', 'bp_method': 'self._bp_method', 'ms_scaling_factor': '(0)', 'osd_method': '"""osd_cs"""', 'osd_order': 'self._osd_order'}), "(self.code.Hz, error_rate=self.error_rate, max_iter=self.\n _max_bp_iter, bp_method=self._bp_method, ms_scaling_factor=0,\n osd_method='osd_cs', osd_order=self._osd_order)\n", (2851, 3026), False, 'from ldpc import bposd_decoder\n'), ((3228, 3430), 'ldpc.bposd_decoder', 'bposd_decoder', (['self.code.stabilizer_matrix'], {'error_rate': 'self.error_rate', 'max_iter': 'self._max_bp_iter', 'bp_method': 'self._bp_method', 'ms_scaling_factor': '(0)', 'osd_method': '"""osd_cs"""', 'osd_order': 'self._osd_order'}), "(self.code.stabilizer_matrix, error_rate=self.error_rate,\n max_iter=self._max_bp_iter, bp_method=self._bp_method,\n ms_scaling_factor=0, osd_method='osd_cs', osd_order=self._osd_order)\n", (3241, 3430), False, 'from ldpc import bposd_decoder\n'), ((5090, 5134), 'numpy.concatenate', 'np.concatenate', (['[x_correction, z_correction]'], {}), '([x_correction, z_correction])\n', (5104, 5134), True, 'import numpy as np\n'), ((5463, 5525), 'numpy.concatenate', 'np.concatenate', (['[correction[n_qubits:], correction[:n_qubits]]'], {}), '([correction[n_qubits:], correction[:n_qubits]])\n', (5477, 5525), True, 'import numpy as np\n'), ((6957, 6968), 'time.time', 'time.time', ([], {}), '()\n', (6966, 6968), False, 'import time\n')]
|
import numpy as np
import pandas as pd
import random
from sklearn.model_selection import train_test_split
class SVM:
def __init__(self, max_iterations=1000, C=1, epsilon=0.001):
self.max_iterations = max_iterations
self.C = C
self.epsilon = epsilon
def fit(self, X, y):
# Ensure X and y are numpy arrays
X = np.array(X).astype('float')
y = np.array(y).astype('int')
# Initialize variables
n, d = X.shape
alpha = np.zeros(n)
iterations = 0
# Calculate starting w & b values
self.compute_w_b(y, alpha, X)
for iteration in range(1, self.max_iterations + 1):
# print('Iteration ', iteration)
alpha_prev = np.copy(alpha)
for i in range(0, n):
# Get random j so that i != j
j = random.randint(0, n - 2)
if j >= i:
j += 1
# Prepare variables
x_i, y_i = X[i,:], y[i]
x_j, y_j = X[j,:], y[j]
# Calculate nu
nu = np.dot(x_i, x_i) + np.dot(x_j, x_j) - np.dot(x_i, x_j)
# Calculate lower and upper bounds
L, H = self.L_H(alpha[i], alpha[j], y_i*y_j, self.C)
if L == H:
continue
# Compute E values
E_i = self.E(x_i, y_i, self.w, self.b)
E_j = self.E(x_j, y_j, self.w, self.b)
if nu == 0:
continue
"""
if self.obj_func(nu, alpha[j], L, y_i, E_i, E_j) > self.obj_func(nu, alpha[j], H, y_i, E_i, E_j):
new_alpha_j = L
else:
new_alpha_j = H
"""
else:
# Compute E values
E_i = self.E(x_i, y_i, self.w, self.b)
E_j = self.E(x_j, y_j, self.w, self.b)
# Compute new alpha j
new_alpha_j = alpha[j] + y_j*(E_i - E_j)/nu
new_alpha_j = max(min(new_alpha_j, H), L)
# Compute new alpha i & deltas
new_alpha_i = alpha[i] + y_i*y_j*(alpha[j] - new_alpha_j)
delta_i = (new_alpha_i - alpha[i])
delta_j = (new_alpha_j - alpha[j])
# Update w
self.w += delta_i*y_i*x_i + delta_j*y_j*x_j
# Update b
b_i = self.b - E_i - y_i*delta_i*np.dot(x_i, x_i) - y_j*delta_j*np.dot(x_i, x_j)
b_j = self.b - E_i - y_i*delta_i*np.dot(x_i, x_i) - y_j*delta_j*np.dot(x_i, x_j)
if 0 < new_alpha_i < self.C:
self.b = b_i
elif 0 < new_alpha_j < self.C:
self.b = b_j
else:
self.b = (b_i + b_j)/2
# Update alphas
alpha[i] = new_alpha_i
alpha[j] = new_alpha_j
"""
print('i: ', i, 'j: ', j)
print('f_i: ', self.f(x_i, self.w, self.b), 'y_i: ', y_i,
'f_j: ', self.f(x_j, self.w, self.b), 'y_j: ', y_j)
print('L: ', L, 'H: ', H, 'E_i: ', E_i, 'E_j: ', E_j)
print('New unbounded alpha j: ', new_alpha_j)
print('New alpha j: ', alpha[j])
"""
# End loop if convergence param is attained
if np.linalg.norm(alpha - alpha_prev) < self.epsilon:
break
# Save support vectors
self.train_iterations = iterations
self.support_vectors = X[np.where(alpha > 0)[0], :]
def score(self, X, y):
if not self.b:
print('SVM has not been trained yet')
else:
predictions = self.predict(X)
return np.sum(y == predictions)/y.shape[0]
def compute_w_b(self, y, alpha, X):
self.w = np.matmul(y*alpha, X).T
self.b = np.mean(y - np.matmul(self.w.T, X.T))
def f(self, x, w, b):
return np.sign(np.matmul(x.astype('float'), w) + b).astype(int)
def E(self, x, y, w, b):
return self.f(x, w, b) - y
def obj_func(self, nu, alpha_j, new_alpha_j, y_j, E_i, E_j):
return 0.5*nu*new_alpha_j**2 + (y_j*(E_i - E_j) - nu*alpha_j)*new_alpha_j
def L_H(self, alpha_i, alpha_j, s, C):
if s == -1:
return max(0, alpha_j - alpha_i), min(C, C + alpha_j - alpha_i)
else:
return max(0, alpha_i + alpha_j - C), min(C, alpha_i + alpha_j)
def predict(self, features):
return self.f(features, self.w, self.b)
def test_svm():
# Read data from text file
df = pd.read_csv('data/breast-cancer-wisconsin.data')
df = df.replace('?', -99999999).drop(['id'], axis=1)
# Prepare X and y inputs
X = df.drop(['class'], axis=1)
y = df['class'].replace(2, -1).replace(4, 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Train SVM
classifier = SVM()
classifier.fit(X_train, y_train)
# Print Model parameters
print('SVM parameters')
print('w: ', classifier.w, 'b: ', classifier.b)
print('Support vector count: ', len(classifier.support_vectors))
# Test SVM accuracy
accuracy = classifier.score(X_test, y_test)
print('SVM Accuracy: ', accuracy)
# Predict random examples
example_measures = np.array([[8,10,10,8,7,10,9,7,1], [6,1,1,1,2,1,3,1,1], [3,1,1,1,2,1,2,1,1]])
predictions = classifier.predict(example_measures)
print('SVM Predictions: ', predictions, '; Actual: ', [1, -1, -1])
test_svm()
|
[
"numpy.sum",
"random.randint",
"numpy.copy",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.zeros",
"numpy.where",
"numpy.array",
"numpy.linalg.norm",
"numpy.matmul",
"numpy.dot"
] |
[((4792, 4840), 'pandas.read_csv', 'pd.read_csv', (['"""data/breast-cancer-wisconsin.data"""'], {}), "('data/breast-cancer-wisconsin.data')\n", (4803, 4840), True, 'import pandas as pd\n'), ((5051, 5088), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (5067, 5088), False, 'from sklearn.model_selection import train_test_split\n'), ((5510, 5615), 'numpy.array', 'np.array', (['[[8, 10, 10, 8, 7, 10, 9, 7, 1], [6, 1, 1, 1, 2, 1, 3, 1, 1], [3, 1, 1, 1, \n 2, 1, 2, 1, 1]]'], {}), '([[8, 10, 10, 8, 7, 10, 9, 7, 1], [6, 1, 1, 1, 2, 1, 3, 1, 1], [3, \n 1, 1, 1, 2, 1, 2, 1, 1]])\n', (5518, 5615), True, 'import numpy as np\n'), ((498, 509), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (506, 509), True, 'import numpy as np\n'), ((745, 759), 'numpy.copy', 'np.copy', (['alpha'], {}), '(alpha)\n', (752, 759), True, 'import numpy as np\n'), ((4014, 4037), 'numpy.matmul', 'np.matmul', (['(y * alpha)', 'X'], {}), '(y * alpha, X)\n', (4023, 4037), True, 'import numpy as np\n'), ((361, 372), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (369, 372), True, 'import numpy as np\n'), ((401, 412), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (409, 412), True, 'import numpy as np\n'), ((877, 901), 'random.randint', 'random.randint', (['(0)', '(n - 2)'], {}), '(0, n - 2)\n', (891, 901), False, 'import random\n'), ((3536, 3570), 'numpy.linalg.norm', 'np.linalg.norm', (['(alpha - alpha_prev)'], {}), '(alpha - alpha_prev)\n', (3550, 3570), True, 'import numpy as np\n'), ((3920, 3944), 'numpy.sum', 'np.sum', (['(y == predictions)'], {}), '(y == predictions)\n', (3926, 3944), True, 'import numpy as np\n'), ((4067, 4091), 'numpy.matmul', 'np.matmul', (['self.w.T', 'X.T'], {}), '(self.w.T, X.T)\n', (4076, 4091), True, 'import numpy as np\n'), ((1164, 1180), 'numpy.dot', 'np.dot', (['x_i', 'x_j'], {}), '(x_i, x_j)\n', (1170, 1180), True, 'import numpy as np\n'), ((3717, 3736), 'numpy.where', 'np.where', (['(alpha > 0)'], {}), '(alpha > 0)\n', (3725, 3736), True, 'import numpy as np\n'), ((1126, 1142), 'numpy.dot', 'np.dot', (['x_i', 'x_i'], {}), '(x_i, x_i)\n', (1132, 1142), True, 'import numpy as np\n'), ((1145, 1161), 'numpy.dot', 'np.dot', (['x_j', 'x_j'], {}), '(x_j, x_j)\n', (1151, 1161), True, 'import numpy as np\n'), ((2603, 2619), 'numpy.dot', 'np.dot', (['x_i', 'x_j'], {}), '(x_i, x_j)\n', (2609, 2619), True, 'import numpy as np\n'), ((2700, 2716), 'numpy.dot', 'np.dot', (['x_i', 'x_j'], {}), '(x_i, x_j)\n', (2706, 2716), True, 'import numpy as np\n'), ((2572, 2588), 'numpy.dot', 'np.dot', (['x_i', 'x_i'], {}), '(x_i, x_i)\n', (2578, 2588), True, 'import numpy as np\n'), ((2669, 2685), 'numpy.dot', 'np.dot', (['x_i', 'x_i'], {}), '(x_i, x_i)\n', (2675, 2685), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 14:13:34 2020
Testing out the ADS1115 ADC with the raspberry pi
@author: nlourie
"""
import board
import busio
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime
import numpy as np
i2c = busio.I2C(board.SCL,board.SDA)
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
ads = ADS.ADS1115(i2c)
chan = AnalogIn(ads,ADS.P3)
xs = []
ys = []
fig = plt.figure()
ax = fig.add_subplot(111)
i = 0
dt = 10 # ms
T = 10 # seconds
Nmax = np.int(T*100/dt)
def animate(i,xs,ys):
v = chan.voltage
t = datetime.utcnow()
xs.append(t)
ys.append(v)
# limit the number of items in the vectors
xs = xs[-Nmax:]
ys = ys[-Nmax:]
# draw x and y lists
ax.clear()
ax.plot(xs,ys)
# set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig,animate,fargs = (xs,ys),interval = dt)
plt.show()
"""
while True:
print('loop = ',i, chan.voltage)
index.append(i)
v.append(chan.voltage)
ax.plot(index,v)
fig.canvas.draw()
#ax.set_xlim(left = max(0,i-50),right = i+50)
time.sleep(0.1)
i+=1
"""
|
[
"adafruit_ads1x15.ads1115.ADS1115",
"matplotlib.pyplot.show",
"busio.I2C",
"matplotlib.animation.FuncAnimation",
"datetime.datetime.utcnow",
"matplotlib.pyplot.figure",
"numpy.int",
"adafruit_ads1x15.analog_in.AnalogIn"
] |
[((333, 364), 'busio.I2C', 'busio.I2C', (['board.SCL', 'board.SDA'], {}), '(board.SCL, board.SDA)\n', (342, 364), False, 'import busio\n'), ((460, 476), 'adafruit_ads1x15.ads1115.ADS1115', 'ADS.ADS1115', (['i2c'], {}), '(i2c)\n', (471, 476), True, 'import adafruit_ads1x15.ads1115 as ADS\n'), ((485, 506), 'adafruit_ads1x15.analog_in.AnalogIn', 'AnalogIn', (['ads', 'ADS.P3'], {}), '(ads, ADS.P3)\n', (493, 506), False, 'from adafruit_ads1x15.analog_in import AnalogIn\n'), ((530, 542), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (540, 542), True, 'import matplotlib.pyplot as plt\n'), ((614, 634), 'numpy.int', 'np.int', (['(T * 100 / dt)'], {}), '(T * 100 / dt)\n', (620, 634), True, 'import numpy as np\n'), ((950, 1016), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'animate'], {'fargs': '(xs, ys)', 'interval': 'dt'}), '(fig, animate, fargs=(xs, ys), interval=dt)\n', (973, 1016), True, 'import matplotlib.animation as animation\n'), ((1017, 1027), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1025, 1027), True, 'import matplotlib.pyplot as plt\n'), ((683, 700), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (698, 700), False, 'from datetime import datetime\n')]
|
import sys
import string
from itertools import product
import scipy.constants as co
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import LogNorm
from scipy import stats
import h5py
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage[varg]{txfonts}')
plt.rc('axes', titlesize=54)
plt.rc('font', family='serif', size=12)
FOUT = "wavelength.pdf"
def main():
obs = 1
plt.figure(figsize=(8, 10))
plt.subplots_adjust(top=0.95, bottom=0.1)
lst = list(product([10, 12], [10, 20])) + [[0, 20]]
for i, (h, R) in enumerate(lst):
ax = plt.subplot(5, 1, i + 1)
if i == 4:
move_down(ax)
plot_panel(ax, h, R, letter=string.ascii_lowercase[i])
if i != 4:
noxticks(ax)
else:
ax.set_xlabel("pixel")
if i == 0:
ax.legend(["777 nm", "337 nm"])
ax.set_ylabel("brightness (a.u.)")
ax.set_xlim([472, 537])
ax.axvline(512, color='k', lw=0.75)
ax.grid()
plt.savefig(FOUT)
#plt.show()
def plot_panel(ax, h, R, letter):
plot_line(ax, h, R, 777, color='#ff7777')
plot_line(ax, h, R, 337, color='#7799bb')
if h > 0:
title = f"\\Large{{{{\\bf {letter}.}} {h} km, {R} µm}}"
else:
title = f"\\Large{{{{\\bf {letter}.}} 10-12 km, {R} µm}}"
ax.text(0.02, 0.85, title, transform=plt.gca().transAxes)
axins1 = ax.inset_axes([0.025, 0.1, 0.15, 0.6])
plot_map(axins1, h, R, 777)
axins2 = ax.inset_axes([0.18, 0.1, 0.15, 0.6])
plot_map(axins2, h, R, 337)
def plot_line(ax, h, R, lmbd, **kwargs):
if h != 0:
fname = f"wavelength_{lmbd}nm_{h}km_{R}um.h5"
else:
fname = f"wavelength_extended_{lmbd}nm_{R}um.h5"
fp = h5py.File(fname, "r")
obs = 1
# Note that the image is transposed wrt the julia array.
img = np.array(fp[f"obs{obs:05d}/image"])
width, height = img.shape
x, y = np.arange(width), np.arange(height)
v = img[:, height // 2]
ax.plot(x, v / np.amax(v), **kwargs)
def plot_map(ax, h, R, lmbd):
if h != 0:
fname = f"wavelength_{lmbd}nm_{h}km_{R}um.h5"
else:
fname = f"wavelength_extended_{lmbd}nm_{R}um.h5"
fp = h5py.File(fname, "r")
obs = 1
# Note that the image is transposed wrt the julia array.
img = np.array(fp[f"obs{obs:05d}/image"])
width, height = img.shape
ax.pcolormesh(img[492:532, 492:532], cmap="gnuplot2", rasterized=True)
noxticks(ax)
noyticks(ax)
ax.tick_params('both', length=2, width=0.5, which='major')
ax.axhline(512 - 492, lw=0.75, c="#777777")
ax.text(0.03, 0.05, f"\small{{{lmbd} nm}}", color="w",
transform=ax.transAxes)
def move_down(ax):
[left, bottom, width, height] = ax.get_position().bounds
ax.set_position([left, bottom - 0.05, width, height])
def noxticks(ax):
""" Remove xticks from the plot. """
loc = ax.get_xticks()
ax.set_xticklabels(['' for l in loc])
def noyticks(ax):
""" Remove xticks from the plot. """
loc = ax.get_yticks()
ax.set_yticklabels(['' for l in loc])
if __name__ == '__main__':
main()
|
[
"matplotlib.pyplot.subplot",
"h5py.File",
"matplotlib.pyplot.gca",
"numpy.amax",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.rc",
"numpy.arange",
"itertools.product",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.savefig"
] |
[((218, 245), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (224, 245), True, 'from matplotlib import pyplot as plt\n'), ((246, 306), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text.latex"""'], {'preamble': '"""\\\\usepackage[varg]{txfonts}"""'}), "('text.latex', preamble='\\\\usepackage[varg]{txfonts}')\n", (252, 306), True, 'from matplotlib import pyplot as plt\n'), ((307, 335), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'titlesize': '(54)'}), "('axes', titlesize=54)\n", (313, 335), True, 'from matplotlib import pyplot as plt\n'), ((336, 375), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""', 'size': '(12)'}), "('font', family='serif', size=12)\n", (342, 375), True, 'from matplotlib import pyplot as plt\n'), ((430, 457), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 10)'}), '(figsize=(8, 10))\n', (440, 457), True, 'from matplotlib import pyplot as plt\n'), ((462, 503), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': '(0.95)', 'bottom': '(0.1)'}), '(top=0.95, bottom=0.1)\n', (481, 503), True, 'from matplotlib import pyplot as plt\n'), ((1091, 1108), 'matplotlib.pyplot.savefig', 'plt.savefig', (['FOUT'], {}), '(FOUT)\n', (1102, 1108), True, 'from matplotlib import pyplot as plt\n'), ((1846, 1867), 'h5py.File', 'h5py.File', (['fname', '"""r"""'], {}), "(fname, 'r')\n", (1855, 1867), False, 'import h5py\n'), ((1956, 1991), 'numpy.array', 'np.array', (["fp[f'obs{obs:05d}/image']"], {}), "(fp[f'obs{obs:05d}/image'])\n", (1964, 1991), True, 'import numpy as np\n'), ((2326, 2347), 'h5py.File', 'h5py.File', (['fname', '"""r"""'], {}), "(fname, 'r')\n", (2335, 2347), False, 'import h5py\n'), ((2436, 2471), 'numpy.array', 'np.array', (["fp[f'obs{obs:05d}/image']"], {}), "(fp[f'obs{obs:05d}/image'])\n", (2444, 2471), True, 'import numpy as np\n'), ((615, 639), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(5)', '(1)', '(i + 1)'], {}), '(5, 1, i + 1)\n', (626, 639), True, 'from matplotlib import pyplot as plt\n'), ((2034, 2050), 'numpy.arange', 'np.arange', (['width'], {}), '(width)\n', (2043, 2050), True, 'import numpy as np\n'), ((2052, 2069), 'numpy.arange', 'np.arange', (['height'], {}), '(height)\n', (2061, 2069), True, 'import numpy as np\n'), ((519, 546), 'itertools.product', 'product', (['[10, 12]', '[10, 20]'], {}), '([10, 12], [10, 20])\n', (526, 546), False, 'from itertools import product\n'), ((2122, 2132), 'numpy.amax', 'np.amax', (['v'], {}), '(v)\n', (2129, 2132), True, 'import numpy as np\n'), ((1460, 1469), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1467, 1469), True, 'from matplotlib import pyplot as plt\n')]
|
# Copyright 2021 Sony Group Corporation.
#
# 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.
import numpy as np
import click
import nnabla as nn
import nnabla.functions as F
from layers import *
class ResidualBlock(object):
def __init__(self,
out_channels=None,
scale_shift_norm=False,
dropout=0,
conv_shortcut=False):
self.out_channels = out_channels
self.scale_shift_norm = scale_shift_norm
self.dropout = dropout
self.conv_shortcut = conv_shortcut
def in_layers(self, x):
h = normalize(x, name='norm_in')
h = nonlinearity(h)
h = conv(h, self.out_channels, name='conv_in')
return h
def emb_layers(self, emb):
out_channels = self.out_channels
if self.scale_shift_norm:
out_channels *= 2
return nin(emb, out_channels, name="emb_proj")
def out_layers(self, h, emb):
if self.scale_shift_norm:
scale, shift = chunk(emb, num_chunk=2, axis=1)
h = normalize(h, name="norm_out") * (scale + 1) + shift
else:
h += emb
h = normalize(h, name="norm_out")
h = nonlinearity(h)
if self.dropout > 0:
h = F.dropout(h, p=self.dropout)
h = conv(h, self.out_channels, name="conv_out", zeroing_w=True)
return h
def shortcut(self, x):
if self.out_channels == x.shape[1]:
return x
elif self.conv_shortcut:
return conv(x, self.out_channels, name="conv_shortcut")
else:
return nin(x, self.out_channels, name="conv_shortcut")
def __call__(self, x, temb, name):
C = x.shape[1]
if self.out_channels is None:
self.out_channels = C
with nn.parameter_scope(name):
# first block
h = self.in_layers(x)
# embed
emb = self.emb_layers(temb)
# second block
h = self.out_layers(h, emb)
# add residual
out = F.add2(h, self.shortcut(x), inplace=True)
return out
def attn_block(x, name, num_heads=4, fix_parameters=False):
"""Multihead attention block"""
B, C, H, W = x.shape
with nn.parameter_scope(name):
# Get query, key, value
h = normalize(x, name="norm")
# nin(3 * C) -> split is faster?
q = nin(h, C, name="q")
k = nin(h, C, name="k")
v = nin(h, C, name="v")
# Attention
w = F.batch_matmul(F.reshape(q, (B * num_heads, -1, H * W)),
F.reshape(k, (B * num_heads, -1, H * W)), transpose_a=True)
w = F.mul_scalar(w, int(C) ** (-0.5), inplace=True)
assert w.shape == (B * num_heads, H * W, H * W)
w = F.softmax(w, axis=-1)
h = F.reshape(v, (B * num_heads, -1, H * W))
h = F.batch_matmul(h, w)
h = F.reshape(h, (B, C, H, W))
# output projection
h = nin(h, C, name='proj_out', zeroing_w=True)
assert h.shape == x.shape
return F.add2(h, x, inplace=True)
class UNet(object):
def __init__(self,
num_classes,
model_channels,
output_channels,
num_res_blocks,
attention_resolutions,
attention_num_heads,
channel_mult=(1, 2, 4, 8),
dropout=0.,
scale_shift_norm=False,
conv_resample=True):
self.num_classes = num_classes
self.model_channels = model_channels
self.output_channels = output_channels
self.num_res_blocks = num_res_blocks
self.attention_resolutions = attention_resolutions
self.attention_num_heads = attention_num_heads
self.channel_mult = channel_mult
self.dropout = dropout
self.scale_shift_norm = scale_shift_norm
self.conv_resample = conv_resample
def timestep_embedding(self, t):
with nn.parameter_scope('timestep_embedding'):
# sinusoidal embedding
emb = sinusoidal_embedding(t, self.model_channels)
# reshape to use conv rather than affine
emb = F.reshape(emb, emb.shape + (1, 1))
# linear transforms
emb = nin(emb, self.model_channels * 4, name='dense0')
emb = nonlinearity(emb)
emb = nin(emb, self.model_channels * 4, name='dense1')
return emb
def resblock_with_attention(self, h, emb, out_channels, name):
with nn.parameter_scope(name):
block = ResidualBlock(out_channels,
scale_shift_norm=self.scale_shift_norm,
dropout=self.dropout)
h = block(h, emb, f"res_block")
res = h.shape[-1]
if self.attention_resolutions is not None and res in self.attention_resolutions:
h = attn_block(h, f"attention",
num_heads=self.attention_num_heads)
return h
def downsample_blocks(self, h, emb, out_channels, name):
hs = []
with nn.parameter_scope(name):
for i in range(self.num_res_blocks):
h = self.resblock_with_attention(
h, emb, out_channels, name=f"resblock_{i}")
hs.append(h)
return hs
def upsample_blocks(self, h, emb, hs_down, out_channels, name):
hs_up = []
with nn.parameter_scope(name):
for i in range(self.num_res_blocks + 1):
# concat skip
h = F.concatenate(h, hs_down.pop(), axis=1)
h = self.resblock_with_attention(
h, emb, out_channels, name=f"resblock_{i}")
hs_up.append(h)
return hs_up
def middle_block(self, h, emb):
ch = h.shape[1]
block = ResidualBlock(
ch, scale_shift_norm=self.scale_shift_norm, dropout=self.dropout)
h = block(h, emb, name="resblock_0")
res = h.shape[-1]
if self.attention_resolutions is not None and res in self.attention_resolutions:
h = attn_block(h, f"attention", num_heads=self.attention_num_heads)
h = block(h, emb, name="resblock_1")
return h
def output_block(self, h):
h = normalize(h, "last_norm")
h = nonlinearity(h)
h = conv(h, self.output_channels, name="last_conv", zeroing_w=True)
return h
def get_intermediates(self, x, t, name=None):
ret = dict()
with nn.auto_forward(True):
ch = self.model_channels
with nn.parameter_scope('UNet' if name is None else name):
h = conv(x, ch, name="first_conv")
emb = self.timestep_embedding(t)
ret["emb"] = emb
emb = nonlinearity(emb)
hs = [h]
# downsample block
with nn.parameter_scope("downsample_block"):
for level, mult in enumerate(self.channel_mult):
# apply resblock and attention for this resolution
outs = self.downsample_blocks(h, emb, ch * mult,
name=f"block_{level}")
hs += outs
h = outs[-1]
# downsample to lower resolution except last
if level < len(self.channel_mult) - 1:
h = downsample(h, name=f"downsample_{level}",
with_conv=self.conv_resample)
hs.append(h)
ret["down"] = hs.copy()
# middle block
with nn.parameter_scope("middle_block"):
h = self.middle_block(h, emb)
ret["middle"] = h
# upsample block
hs_up = []
with nn.parameter_scope("upsample_block"):
for level, mult in enumerate(reversed(self.channel_mult)):
# apply resblock and attention for this resolution
outs = self.upsample_blocks(h, emb, hs, ch * mult,
name=f"output_{level}")
h = outs[-1]
# downsample to lower resolution except last
if level < len(self.channel_mult) - 1:
h = upsample(h, name=f"upsample_{level}",
with_conv=self.conv_resample)
outs.pop()
outs.append(h)
hs_up += outs
assert len(hs) == 0
ret["up"] = hs_up.copy()
# output block
with nn.parameter_scope("output_block"):
out = self.output_block(h)
ret["out"] = out
assert out.shape == x.shape[:1] + \
(self.output_channels, ) + x.shape[2:]
return ret
def __call__(self, x, t, name=None):
ch = self.model_channels
with nn.parameter_scope('UNet' if name is None else name):
h = conv(x, ch, name="first_conv")
emb = self.timestep_embedding(t)
emb = nonlinearity(emb)
hs = [h]
# downsample block
with nn.parameter_scope("downsample_block"):
for level, mult in enumerate(self.channel_mult):
# apply resblock and attention for this resolution
outs = self.downsample_blocks(h, emb, ch * mult,
name=f"block_{level}")
hs += outs
h = outs[-1]
# downsample to lower resolution except last
if level < len(self.channel_mult) - 1:
h = downsample(h, name=f"downsample_{level}",
with_conv=self.conv_resample)
hs.append(h)
# middle block
with nn.parameter_scope("middle_block"):
h = self.middle_block(h, emb)
# upsample block
with nn.parameter_scope("upsample_block"):
for level, mult in enumerate(reversed(self.channel_mult)):
# apply resblock and attention for this resolution
outs = self.upsample_blocks(h, emb, hs, ch * mult,
name=f"output_{level}")
h = outs[-1]
# downsample to lower resolution except last
if level < len(self.channel_mult) - 1:
h = upsample(h, name=f"upsample_{level}",
with_conv=self.conv_resample)
assert len(hs) == 0
# output block
with nn.parameter_scope("output_block"):
out = self.output_block(h)
assert out.shape == x.shape[:1] + \
(self.output_channels, ) + x.shape[2:]
return out
# Functions below are for dubugging UNet class.
def test_simple_loop():
nn.clear_parameters()
x = nn.Variable.from_numpy_array(np.random.randn(10, 3, 128, 128))
t = nn.Variable.from_numpy_array(np.random.randint(0, 100, (10, )))
unet = UNet(num_classes=1, model_channels=128, output_channels=3,
num_res_blocks=2,
attention_resolutions=(16, 8),
attention_num_heads=4,
channel_mult=(1, 1, 2, 2, 4, 4))
y = unet(x, t)
loss = F.mean(F.squared_error(y, x))
import nnabla.solvers as S
solver = S.Sgd()
solver.set_parameters(nn.get_parameters())
from tqdm import trange
tr = trange(100)
for i in tr:
loss.forward(clear_no_need_grad=True)
solver.zero_grad()
loss.backward(clear_buffer=True)
solver.update()
tr.set_description(f"diff: {loss.d.copy():.5f}")
def test_intermediate():
import os
os.environ["NNABLA_CUDNN_DETERMINISTIC"] = '1'
nn.clear_parameters()
x = nn.Variable.from_numpy_array(np.full((1, 3, 256, 256), 0.1))
t = nn.Variable.from_numpy_array([803])
unet = UNet(num_classes=1, model_channels=128, output_channels=3,
num_res_blocks=3,
attention_resolutions=(16, 8),
attention_num_heads=4,
channel_mult=(1, 1, 2, 2, 4, 4))
res = unet.get_intermediates(x, t)
print("[emb]")
dump(res["emb"])
print("")
print("[down]")
dump(res["down"])
print("")
print("[middle]")
dump(res["middle"])
print("")
print("[up]")
dump(res["up"])
print("")
print("[out]")
dump(res["out"])
print("")
def dump(var):
if isinstance(var, list):
for x in var:
dump(x)
return
arr = var.d
mean = arr.mean()
std = arr.std()
abs_sum = np.abs(arr).sum()
print("mean: {:-6.1g} std: {:-6.1g} abs_sum: {:-6.1g} size: {}".format(mean,
std, abs_sum, arr.size))
@click.command()
@click.option("--loop/--no-loop", default=True)
@click.option("--intermediate/--no-intermediate", default=False)
def test(loop, intermediate):
# This function is for a unit test of UNet.
from nnabla.ext_utils import get_extension_context
ctx = get_extension_context("cudnn")
nn.set_default_context(ctx)
from nnabla.logger import logger
if loop:
logger.info("Test Unet by simple training loop.")
test_simple_loop()
if intermediate:
logger.info("Test intermediate values of Unet.")
test_intermediate()
if __name__ == "__main__":
test()
|
[
"numpy.abs",
"nnabla.ext_utils.get_extension_context",
"nnabla.Variable.from_numpy_array",
"click.option",
"nnabla.get_parameters",
"numpy.random.randint",
"nnabla.functions.add2",
"nnabla.functions.dropout",
"numpy.full",
"nnabla.logger.logger.info",
"numpy.random.randn",
"nnabla.solvers.Sgd",
"click.command",
"nnabla.functions.reshape",
"nnabla.functions.squared_error",
"nnabla.functions.batch_matmul",
"tqdm.trange",
"nnabla.auto_forward",
"nnabla.set_default_context",
"nnabla.functions.softmax",
"nnabla.parameter_scope",
"nnabla.clear_parameters"
] |
[((13790, 13805), 'click.command', 'click.command', ([], {}), '()\n', (13803, 13805), False, 'import click\n'), ((13807, 13853), 'click.option', 'click.option', (['"""--loop/--no-loop"""'], {'default': '(True)'}), "('--loop/--no-loop', default=True)\n", (13819, 13853), False, 'import click\n'), ((13855, 13918), 'click.option', 'click.option', (['"""--intermediate/--no-intermediate"""'], {'default': '(False)'}), "('--intermediate/--no-intermediate', default=False)\n", (13867, 13918), False, 'import click\n'), ((3583, 3609), 'nnabla.functions.add2', 'F.add2', (['h', 'x'], {'inplace': '(True)'}), '(h, x, inplace=True)\n', (3589, 3609), True, 'import nnabla.functions as F\n'), ((11851, 11872), 'nnabla.clear_parameters', 'nn.clear_parameters', ([], {}), '()\n', (11870, 11872), True, 'import nnabla as nn\n'), ((12363, 12370), 'nnabla.solvers.Sgd', 'S.Sgd', ([], {}), '()\n', (12368, 12370), True, 'import nnabla.solvers as S\n'), ((12456, 12467), 'tqdm.trange', 'trange', (['(100)'], {}), '(100)\n', (12462, 12467), False, 'from tqdm import trange\n'), ((12779, 12800), 'nnabla.clear_parameters', 'nn.clear_parameters', ([], {}), '()\n', (12798, 12800), True, 'import nnabla as nn\n'), ((12879, 12914), 'nnabla.Variable.from_numpy_array', 'nn.Variable.from_numpy_array', (['[803]'], {}), '([803])\n', (12907, 12914), True, 'import nnabla as nn\n'), ((14062, 14092), 'nnabla.ext_utils.get_extension_context', 'get_extension_context', (['"""cudnn"""'], {}), "('cudnn')\n", (14083, 14092), False, 'from nnabla.ext_utils import get_extension_context\n'), ((14097, 14124), 'nnabla.set_default_context', 'nn.set_default_context', (['ctx'], {}), '(ctx)\n', (14119, 14124), True, 'import nnabla as nn\n'), ((2770, 2794), 'nnabla.parameter_scope', 'nn.parameter_scope', (['name'], {}), '(name)\n', (2788, 2794), True, 'import nnabla as nn\n'), ((3309, 3330), 'nnabla.functions.softmax', 'F.softmax', (['w'], {'axis': '(-1)'}), '(w, axis=-1)\n', (3318, 3330), True, 'import nnabla.functions as F\n'), ((3344, 3384), 'nnabla.functions.reshape', 'F.reshape', (['v', '(B * num_heads, -1, H * W)'], {}), '(v, (B * num_heads, -1, H * W))\n', (3353, 3384), True, 'import nnabla.functions as F\n'), ((3397, 3417), 'nnabla.functions.batch_matmul', 'F.batch_matmul', (['h', 'w'], {}), '(h, w)\n', (3411, 3417), True, 'import nnabla.functions as F\n'), ((3430, 3456), 'nnabla.functions.reshape', 'F.reshape', (['h', '(B, C, H, W)'], {}), '(h, (B, C, H, W))\n', (3439, 3456), True, 'import nnabla.functions as F\n'), ((11911, 11943), 'numpy.random.randn', 'np.random.randn', (['(10)', '(3)', '(128)', '(128)'], {}), '(10, 3, 128, 128)\n', (11926, 11943), True, 'import numpy as np\n'), ((11982, 12014), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)', '(10,)'], {}), '(0, 100, (10,))\n', (11999, 12014), True, 'import numpy as np\n'), ((12295, 12316), 'nnabla.functions.squared_error', 'F.squared_error', (['y', 'x'], {}), '(y, x)\n', (12310, 12316), True, 'import nnabla.functions as F\n'), ((12397, 12416), 'nnabla.get_parameters', 'nn.get_parameters', ([], {}), '()\n', (12414, 12416), True, 'import nnabla as nn\n'), ((12839, 12869), 'numpy.full', 'np.full', (['(1, 3, 256, 256)', '(0.1)'], {}), '((1, 3, 256, 256), 0.1)\n', (12846, 12869), True, 'import numpy as np\n'), ((14185, 14234), 'nnabla.logger.logger.info', 'logger.info', (['"""Test Unet by simple training loop."""'], {}), "('Test Unet by simple training loop.')\n", (14196, 14234), False, 'from nnabla.logger import logger\n'), ((14292, 14340), 'nnabla.logger.logger.info', 'logger.info', (['"""Test intermediate values of Unet."""'], {}), "('Test intermediate values of Unet.')\n", (14303, 14340), False, 'from nnabla.logger import logger\n'), ((1770, 1798), 'nnabla.functions.dropout', 'F.dropout', (['h'], {'p': 'self.dropout'}), '(h, p=self.dropout)\n', (1779, 1798), True, 'import nnabla.functions as F\n'), ((2314, 2338), 'nnabla.parameter_scope', 'nn.parameter_scope', (['name'], {}), '(name)\n', (2332, 2338), True, 'import nnabla as nn\n'), ((3051, 3091), 'nnabla.functions.reshape', 'F.reshape', (['q', '(B * num_heads, -1, H * W)'], {}), '(q, (B * num_heads, -1, H * W))\n', (3060, 3091), True, 'import nnabla.functions as F\n'), ((3120, 3160), 'nnabla.functions.reshape', 'F.reshape', (['k', '(B * num_heads, -1, H * W)'], {}), '(k, (B * num_heads, -1, H * W))\n', (3129, 3160), True, 'import nnabla.functions as F\n'), ((4520, 4560), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""timestep_embedding"""'], {}), "('timestep_embedding')\n", (4538, 4560), True, 'import nnabla as nn\n'), ((4732, 4766), 'nnabla.functions.reshape', 'F.reshape', (['emb', '(emb.shape + (1, 1))'], {}), '(emb, emb.shape + (1, 1))\n', (4741, 4766), True, 'import nnabla.functions as F\n'), ((5072, 5096), 'nnabla.parameter_scope', 'nn.parameter_scope', (['name'], {}), '(name)\n', (5090, 5096), True, 'import nnabla as nn\n'), ((5669, 5693), 'nnabla.parameter_scope', 'nn.parameter_scope', (['name'], {}), '(name)\n', (5687, 5693), True, 'import nnabla as nn\n'), ((6007, 6031), 'nnabla.parameter_scope', 'nn.parameter_scope', (['name'], {}), '(name)\n', (6025, 6031), True, 'import nnabla as nn\n'), ((7098, 7119), 'nnabla.auto_forward', 'nn.auto_forward', (['(True)'], {}), '(True)\n', (7113, 7119), True, 'import nnabla as nn\n'), ((9760, 9812), 'nnabla.parameter_scope', 'nn.parameter_scope', (["('UNet' if name is None else name)"], {}), "('UNet' if name is None else name)\n", (9778, 9812), True, 'import nnabla as nn\n'), ((13653, 13664), 'numpy.abs', 'np.abs', (['arr'], {}), '(arr)\n', (13659, 13664), True, 'import numpy as np\n'), ((7175, 7227), 'nnabla.parameter_scope', 'nn.parameter_scope', (["('UNet' if name is None else name)"], {}), "('UNet' if name is None else name)\n", (7193, 7227), True, 'import nnabla as nn\n'), ((10012, 10050), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""downsample_block"""'], {}), "('downsample_block')\n", (10030, 10050), True, 'import nnabla as nn\n'), ((10740, 10774), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""middle_block"""'], {}), "('middle_block')\n", (10758, 10774), True, 'import nnabla as nn\n'), ((10869, 10905), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""upsample_block"""'], {}), "('upsample_block')\n", (10887, 10905), True, 'import nnabla as nn\n'), ((11565, 11599), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""output_block"""'], {}), "('output_block')\n", (11583, 11599), True, 'import nnabla as nn\n'), ((7485, 7523), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""downsample_block"""'], {}), "('downsample_block')\n", (7503, 7523), True, 'import nnabla as nn\n'), ((8306, 8340), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""middle_block"""'], {}), "('middle_block')\n", (8324, 8340), True, 'import nnabla as nn\n'), ((8509, 8545), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""upsample_block"""'], {}), "('upsample_block')\n", (8527, 8545), True, 'import nnabla as nn\n'), ((9415, 9449), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""output_block"""'], {}), "('output_block')\n", (9433, 9449), True, 'import nnabla as nn\n')]
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modified 2017 Microsoft Corporation.
#
# 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.
# ==============================================================================
"""Generic training script that trains a model using a given dataset."""
import tensorflow as tf
import pandas as pd
import numpy as np
import os
import functools
from tensorflow.python.ops import control_flow_ops
from deployment import model_deploy
from nets import resnet_v1 # Needed to be modified, see https://github.com/tensorflow/models/issues/533
from tensorflow.contrib.training.python.training import evaluation
slim = tf.contrib.slim
''' Enumerate the flags '''
tf.app.flags.DEFINE_string('train_dir',
'D:\\tf\\models',
'Directory where checkpoints and event logs are written to.')
tf.app.flags.DEFINE_string('dataset_name', 'aerial', 'The name of the dataset to load.')
tf.app.flags.DEFINE_string('dataset_dir',
'D:\\combined\\train_subsample',
'The directory where the dataset files are stored.')
tf.app.flags.DEFINE_string('checkpoint_path',
'D:\\tf\\resnet_v1_50.ckpt',
'The path to a checkpoint from which to fine-tune.')
tf.app.flags.DEFINE_string('checkpoint_exclude_scopes', 'resnet_v1_50/logits',
'Comma-separated list of scopes of variables to exclude when restoring '
'from a checkpoint.')
tf.app.flags.DEFINE_string('trainable_scopes', 'resnet_v1_50/logits',
'Comma-separated list of scopes to filter the set of variables to train.'
'By default, None would train all the variables.')
tf.app.flags.DEFINE_integer('num_clones', 1, 'Number of model clones to deploy.')
tf.app.flags.DEFINE_boolean('clone_on_cpu', False, 'Use CPUs to deploy clones.')
tf.app.flags.DEFINE_integer('num_readers', 4, 'The number of parallel readers that read data from the dataset.')
tf.app.flags.DEFINE_integer('num_preprocessing_threads', 4, 'The number of threads used to create the batches.')
tf.app.flags.DEFINE_integer('log_every_n_steps', 10, 'The frequency with which logs are printed.')
tf.app.flags.DEFINE_integer('save_summaries_secs', 600, 'The frequency with which summaries are saved, in seconds.')
tf.app.flags.DEFINE_integer('save_interval_secs', 600, 'The frequency with which the model is saved, in seconds.')
tf.app.flags.DEFINE_float('weight_decay', 0.00004, 'The weight decay on the model weights.')
tf.app.flags.DEFINE_float('opt_epsilon', 1.0, 'Epsilon term for the optimizer.')
tf.app.flags.DEFINE_float('rmsprop_momentum', 0.9, 'Momentum.')
tf.app.flags.DEFINE_float('rmsprop_decay', 0.9, 'Decay term for RMSProp.')
tf.app.flags.DEFINE_float('learning_rate', 0.02, 'Initial learning rate.')
tf.app.flags.DEFINE_float('label_smoothing', 0.0, 'The amount of label smoothing.')
tf.app.flags.DEFINE_float('learning_rate_decay_factor', 0.9, 'Learning rate decay factor.')
tf.app.flags.DEFINE_float('num_epochs_per_decay', 2.0, 'Number of epochs after which learning rate decays.')
tf.app.flags.DEFINE_integer('replicas_to_aggregate', 1, 'The number of gradients to collect before updating params.')
tf.app.flags.DEFINE_integer('batch_size', 32, 'The number of samples in each batch.')
tf.app.flags.DEFINE_integer('max_number_of_steps', 4000, 'The maximum number of training steps.')
FLAGS = tf.app.flags.FLAGS
def get_image_and_class_count(dataset_dir, split_name):
df = pd.read_csv(os.path.join(dataset_dir, 'dataset_split_info.csv'))
image_count = len(df.loc[df['split_name'] == split_name].index)
class_count = len(df['class_name'].unique())
return(image_count, class_count)
def read_label_file(dataset_dir, filename='labels.txt'):
labels_filename = os.path.join(dataset_dir, filename)
with tf.gfile.Open(labels_filename, 'r') as f:
lines = f.read()
lines = lines.split('\n')
lines = filter(None, lines)
labels_to_class_names = {}
for line in lines:
index = line.index(':')
labels_to_class_names[line[:index]] = line[index+1:]
return(labels_to_class_names)
def mean_image_subtraction(image, means):
if image.get_shape().ndims != 3:
raise ValueError('Input must be of size [height, width, C>0]')
num_channels = image.get_shape().as_list()[-1]
if len(means) != num_channels:
raise ValueError('len(means) must match the number of channels')
channels = tf.split(axis=2, num_or_size_splits=num_channels, value=image)
for i in range(num_channels):
channels[i] -= means[i]
return(tf.concat(axis=2, values=channels))
def get_preprocessing():
def preprocessing_fn(image, output_height=224, output_width=224):
''' Resize the image and subtract "mean" RGB values '''
_R_MEAN = 123.68
_G_MEAN = 116.78
_B_MEAN = 103.94
#image = tf.expand_dims(image, 0)
temp_dim = np.random.randint(175, 223)
distorted_image = tf.random_crop(image, [output_height, output_width, 3])
distorted_image = tf.expand_dims(distorted_image, 0)
resized_image = tf.image.resize_bilinear(distorted_image, [output_height, output_width], align_corners=False)
resized_image = tf.squeeze(resized_image)
resized_image.set_shape([output_height, output_width, 3])
resized_image = tf.image.random_flip_left_right(resized_image)
image = tf.to_float(resized_image)
return(mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN]))
return(preprocessing_fn)
def get_network_fn(num_classes, weight_decay=0.0):
arg_scope = resnet_v1.resnet_arg_scope(weight_decay=weight_decay)
func = resnet_v1.resnet_v1_50
@functools.wraps(func)
def network_fn(images):
with slim.arg_scope(arg_scope):
return func(images, num_classes)
if hasattr(func, 'default_image_size'):
network_fn.default_image_size = func.default_image_size
return(network_fn)
def _add_variables_summaries(learning_rate):
summaries = []
for variable in slim.get_model_variables():
summaries.append(tf.summary.image(variable.op.name, variable))
summaries.append(tf.summary.scalar(learning_rate, name='training/Learning Rate'))
return(summaries)
def _get_init_fn():
if (FLAGS.checkpoint_path is None) or (tf.train.latest_checkpoint(FLAGS.train_dir)):
return None
exclusions = []
if FLAGS.checkpoint_exclude_scopes:
exclusions = [scope.strip() for scope in FLAGS.checkpoint_exclude_scopes.split(',')]
variables_to_restore = []
for var in slim.get_model_variables():
excluded = False
for exclusion in exclusions:
if var.op.name.startswith(exclusion):
excluded = True
break
if not excluded:
variables_to_restore.append(var)
if tf.gfile.IsDirectory(FLAGS.checkpoint_path):
checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
else:
checkpoint_path = FLAGS.checkpoint_path
tf.logging.info('Fine-tuning from {}'.format(checkpoint_path))
return(slim.assign_from_checkpoint_fn(checkpoint_path,
variables_to_restore,
ignore_missing_vars=False))
def _get_variables_to_train():
scopes = [scope.strip() for scope in FLAGS.trainable_scopes.split(',')]
variables_to_train = []
for scope in scopes:
variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
variables_to_train.extend(variables)
return(variables_to_train)
def get_dataset(dataset_name, dataset_dir, image_count, class_count, split_name):
slim = tf.contrib.slim
items_to_descriptions = {'image': 'A color image.',
'label': 'An integer in range(0, class_count)'}
file_pattern = os.path.join(dataset_dir, '{}_{}_*.tfrecord'.format(dataset_name, split_name))
reader = tf.TFRecordReader
keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),
'image/format': tf.FixedLenFeature((), tf.string, default_value='png'),
'image/class/label': tf.FixedLenFeature([], tf.int64,
default_value=tf.zeros([], dtype=tf.int64))}
items_to_handlers = {'image': slim.tfexample_decoder.Image(),
'label': slim.tfexample_decoder.Tensor('image/class/label')}
decoder = slim.tfexample_decoder.TFExampleDecoder(keys_to_features, items_to_handlers)
labels_to_names = read_label_file(dataset_dir)
return(slim.dataset.Dataset(data_sources=file_pattern,
reader=reader,
decoder=decoder,
num_samples=image_count,
items_to_descriptions=items_to_descriptions,
num_classes=class_count,
labels_to_names=labels_to_names,
shuffle=True))
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Graph().as_default():
deploy_config = model_deploy.DeploymentConfig(num_clones=FLAGS.num_clones,
clone_on_cpu=FLAGS.clone_on_cpu,
replica_id=0,
num_replicas=1,
num_ps_tasks=0)
with tf.device(deploy_config.variables_device()):
global_step = slim.create_global_step()
image_count, class_count = get_image_and_class_count(FLAGS.dataset_dir, 'train')
dataset = get_dataset('aerial', FLAGS.dataset_dir, image_count, class_count, 'train')
network_fn = get_network_fn(num_classes=(dataset.num_classes), weight_decay=FLAGS.weight_decay)
image_preprocessing_fn = get_preprocessing()
with tf.device(deploy_config.inputs_device()):
provider = slim.dataset_data_provider.DatasetDataProvider(dataset,
num_readers=FLAGS.num_readers,
common_queue_capacity=20 * FLAGS.batch_size,
common_queue_min=10 * FLAGS.batch_size)
[image, label] = provider.get(['image', 'label'])
image = image_preprocessing_fn(image, 224, 224)
images, labels = tf.train.batch([image, label],
batch_size=FLAGS.batch_size,
num_threads=FLAGS.num_preprocessing_threads,
capacity=5 * FLAGS.batch_size)
labels = slim.one_hot_encoding(labels, dataset.num_classes)
batch_queue = slim.prefetch_queue.prefetch_queue([images, labels], capacity=2 * deploy_config.num_clones)
def clone_fn(batch_queue):
images, labels = batch_queue.dequeue()
logits, end_points = network_fn(images)
logits = tf.squeeze(logits) # added -- does this help?
slim.losses.softmax_cross_entropy(logits, labels, label_smoothing=FLAGS.label_smoothing, weights=1.0)
return(end_points)
summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES))
clones = model_deploy.create_clones(deploy_config, clone_fn, [batch_queue])
first_clone_scope = deploy_config.clone_scope(0)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone_scope)
end_points = clones[0].outputs
for end_point in end_points:
x = end_points[end_point]
summaries.add(tf.summary.histogram('activations/' + end_point, x))
summaries.add(tf.summary.scalar('sparsity/' + end_point, tf.nn.zero_fraction(x)))
for loss in tf.get_collection(tf.GraphKeys.LOSSES, first_clone_scope):
summaries.add(tf.summary.scalar('losses/%s' % loss.op.name, loss))
for variable in slim.get_model_variables():
summaries.add(tf.summary.histogram(variable.op.name, variable))
with tf.device(deploy_config.optimizer_device()):
decay_steps = int(dataset.num_samples / FLAGS.batch_size * FLAGS.num_epochs_per_decay)
learning_rate = tf.train.exponential_decay(FLAGS.learning_rate,
global_step,
decay_steps,
FLAGS.learning_rate_decay_factor,
staircase=True,
name='exponential_decay_learning_rate')
optimizer = tf.train.RMSPropOptimizer(learning_rate,
decay=FLAGS.rmsprop_decay,
momentum=FLAGS.rmsprop_momentum,
epsilon=FLAGS.opt_epsilon)
summaries.add(tf.summary.scalar('learning_rate', learning_rate))
variables_to_train = _get_variables_to_train()
total_loss, clones_gradients = model_deploy.optimize_clones(clones, optimizer, var_list=variables_to_train)
summaries.add(tf.summary.scalar('total_loss', total_loss))
grad_updates = optimizer.apply_gradients(clones_gradients, global_step=global_step)
update_ops.append(grad_updates)
update_op = tf.group(*update_ops)
train_tensor = control_flow_ops.with_dependencies([update_op], total_loss, name='train_op')
summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES, first_clone_scope))
summary_op = tf.summary.merge(list(summaries), name='summary_op')
slim.learning.train(train_tensor,
logdir=FLAGS.train_dir,
master='',
is_chief=True,
init_fn=_get_init_fn(),
summary_op=summary_op,
number_of_steps=FLAGS.max_number_of_steps,
log_every_n_steps=FLAGS.log_every_n_steps,
save_summaries_secs=FLAGS.save_summaries_secs,
save_interval_secs=FLAGS.save_interval_secs,
sync_optimizer=None)
if __name__ == '__main__':
tf.app.run()
|
[
"tensorflow.app.flags.DEFINE_float",
"tensorflow.nn.zero_fraction",
"tensorflow.get_collection",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.logging.set_verbosity",
"tensorflow.app.flags.DEFINE_boolean",
"numpy.random.randint",
"tensorflow.train.latest_checkpoint",
"tensorflow.python.ops.control_flow_ops.with_dependencies",
"tensorflow.split",
"tensorflow.app.flags.DEFINE_integer",
"os.path.join",
"tensorflow.train.batch",
"tensorflow.concat",
"nets.resnet_v1.resnet_arg_scope",
"tensorflow.summary.histogram",
"tensorflow.to_float",
"tensorflow.squeeze",
"tensorflow.random_crop",
"tensorflow.app.run",
"deployment.model_deploy.DeploymentConfig",
"tensorflow.summary.image",
"tensorflow.summary.scalar",
"tensorflow.gfile.IsDirectory",
"tensorflow.image.random_flip_left_right",
"tensorflow.group",
"functools.wraps",
"tensorflow.Graph",
"tensorflow.train.exponential_decay",
"tensorflow.expand_dims",
"deployment.model_deploy.create_clones",
"deployment.model_deploy.optimize_clones",
"tensorflow.zeros",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.FixedLenFeature",
"tensorflow.gfile.Open",
"tensorflow.image.resize_bilinear"
] |
[((1201, 1324), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""train_dir"""', '"""D:\\\\tf\\\\models"""', '"""Directory where checkpoints and event logs are written to."""'], {}), "('train_dir', 'D:\\\\tf\\\\models',\n 'Directory where checkpoints and event logs are written to.')\n", (1227, 1324), True, 'import tensorflow as tf\n'), ((1375, 1467), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""dataset_name"""', '"""aerial"""', '"""The name of the dataset to load."""'], {}), "('dataset_name', 'aerial',\n 'The name of the dataset to load.')\n", (1401, 1467), True, 'import tensorflow as tf\n'), ((1464, 1595), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""dataset_dir"""', '"""D:\\\\combined\\\\train_subsample"""', '"""The directory where the dataset files are stored."""'], {}), "('dataset_dir', 'D:\\\\combined\\\\train_subsample',\n 'The directory where the dataset files are stored.')\n", (1490, 1595), True, 'import tensorflow as tf\n'), ((1646, 1777), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""checkpoint_path"""', '"""D:\\\\tf\\\\resnet_v1_50.ckpt"""', '"""The path to a checkpoint from which to fine-tune."""'], {}), "('checkpoint_path', 'D:\\\\tf\\\\resnet_v1_50.ckpt',\n 'The path to a checkpoint from which to fine-tune.')\n", (1672, 1777), True, 'import tensorflow as tf\n'), ((1829, 2012), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""checkpoint_exclude_scopes"""', '"""resnet_v1_50/logits"""', '"""Comma-separated list of scopes of variables to exclude when restoring from a checkpoint."""'], {}), "('checkpoint_exclude_scopes',\n 'resnet_v1_50/logits',\n 'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.'\n )\n", (1855, 2012), True, 'import tensorflow as tf\n'), ((2057, 2257), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""trainable_scopes"""', '"""resnet_v1_50/logits"""', '"""Comma-separated list of scopes to filter the set of variables to train.By default, None would train all the variables."""'], {}), "('trainable_scopes', 'resnet_v1_50/logits',\n 'Comma-separated list of scopes to filter the set of variables to train.By default, None would train all the variables.'\n )\n", (2083, 2257), True, 'import tensorflow as tf\n'), ((2307, 2392), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_clones"""', '(1)', '"""Number of model clones to deploy."""'], {}), "('num_clones', 1,\n 'Number of model clones to deploy.')\n", (2334, 2392), True, 'import tensorflow as tf\n'), ((2389, 2474), 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""clone_on_cpu"""', '(False)', '"""Use CPUs to deploy clones."""'], {}), "('clone_on_cpu', False, 'Use CPUs to deploy clones.'\n )\n", (2416, 2474), True, 'import tensorflow as tf\n'), ((2470, 2586), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_readers"""', '(4)', '"""The number of parallel readers that read data from the dataset."""'], {}), "('num_readers', 4,\n 'The number of parallel readers that read data from the dataset.')\n", (2497, 2586), True, 'import tensorflow as tf\n'), ((2583, 2699), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_preprocessing_threads"""', '(4)', '"""The number of threads used to create the batches."""'], {}), "('num_preprocessing_threads', 4,\n 'The number of threads used to create the batches.')\n", (2610, 2699), True, 'import tensorflow as tf\n'), ((2696, 2798), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""log_every_n_steps"""', '(10)', '"""The frequency with which logs are printed."""'], {}), "('log_every_n_steps', 10,\n 'The frequency with which logs are printed.')\n", (2723, 2798), True, 'import tensorflow as tf\n'), ((2795, 2915), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""save_summaries_secs"""', '(600)', '"""The frequency with which summaries are saved, in seconds."""'], {}), "('save_summaries_secs', 600,\n 'The frequency with which summaries are saved, in seconds.')\n", (2822, 2915), True, 'import tensorflow as tf\n'), ((2912, 3030), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""save_interval_secs"""', '(600)', '"""The frequency with which the model is saved, in seconds."""'], {}), "('save_interval_secs', 600,\n 'The frequency with which the model is saved, in seconds.')\n", (2939, 3030), True, 'import tensorflow as tf\n'), ((3028, 3122), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""weight_decay"""', '(4e-05)', '"""The weight decay on the model weights."""'], {}), "('weight_decay', 4e-05,\n 'The weight decay on the model weights.')\n", (3053, 3122), True, 'import tensorflow as tf\n'), ((3121, 3206), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""opt_epsilon"""', '(1.0)', '"""Epsilon term for the optimizer."""'], {}), "('opt_epsilon', 1.0, 'Epsilon term for the optimizer.'\n )\n", (3146, 3206), True, 'import tensorflow as tf\n'), ((3202, 3265), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""rmsprop_momentum"""', '(0.9)', '"""Momentum."""'], {}), "('rmsprop_momentum', 0.9, 'Momentum.')\n", (3227, 3265), True, 'import tensorflow as tf\n'), ((3266, 3340), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""rmsprop_decay"""', '(0.9)', '"""Decay term for RMSProp."""'], {}), "('rmsprop_decay', 0.9, 'Decay term for RMSProp.')\n", (3291, 3340), True, 'import tensorflow as tf\n'), ((3341, 3415), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""learning_rate"""', '(0.02)', '"""Initial learning rate."""'], {}), "('learning_rate', 0.02, 'Initial learning rate.')\n", (3366, 3415), True, 'import tensorflow as tf\n'), ((3416, 3503), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""label_smoothing"""', '(0.0)', '"""The amount of label smoothing."""'], {}), "('label_smoothing', 0.0,\n 'The amount of label smoothing.')\n", (3441, 3503), True, 'import tensorflow as tf\n'), ((3500, 3595), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""learning_rate_decay_factor"""', '(0.9)', '"""Learning rate decay factor."""'], {}), "('learning_rate_decay_factor', 0.9,\n 'Learning rate decay factor.')\n", (3525, 3595), True, 'import tensorflow as tf\n'), ((3592, 3704), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""num_epochs_per_decay"""', '(2.0)', '"""Number of epochs after which learning rate decays."""'], {}), "('num_epochs_per_decay', 2.0,\n 'Number of epochs after which learning rate decays.')\n", (3617, 3704), True, 'import tensorflow as tf\n'), ((3701, 3822), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""replicas_to_aggregate"""', '(1)', '"""The number of gradients to collect before updating params."""'], {}), "('replicas_to_aggregate', 1,\n 'The number of gradients to collect before updating params.')\n", (3728, 3822), True, 'import tensorflow as tf\n'), ((3819, 3908), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""batch_size"""', '(32)', '"""The number of samples in each batch."""'], {}), "('batch_size', 32,\n 'The number of samples in each batch.')\n", (3846, 3908), True, 'import tensorflow as tf\n'), ((3905, 4006), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""max_number_of_steps"""', '(4000)', '"""The maximum number of training steps."""'], {}), "('max_number_of_steps', 4000,\n 'The maximum number of training steps.')\n", (3932, 4006), True, 'import tensorflow as tf\n'), ((4396, 4431), 'os.path.join', 'os.path.join', (['dataset_dir', 'filename'], {}), '(dataset_dir, filename)\n', (4408, 4431), False, 'import os\n'), ((5078, 5140), 'tensorflow.split', 'tf.split', ([], {'axis': '(2)', 'num_or_size_splits': 'num_channels', 'value': 'image'}), '(axis=2, num_or_size_splits=num_channels, value=image)\n', (5086, 5140), True, 'import tensorflow as tf\n'), ((5218, 5252), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(2)', 'values': 'channels'}), '(axis=2, values=channels)\n', (5227, 5252), True, 'import tensorflow as tf\n'), ((6243, 6296), 'nets.resnet_v1.resnet_arg_scope', 'resnet_v1.resnet_arg_scope', ([], {'weight_decay': 'weight_decay'}), '(weight_decay=weight_decay)\n', (6269, 6296), False, 'from nets import resnet_v1\n'), ((6336, 6357), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (6351, 6357), False, 'import functools\n'), ((7506, 7549), 'tensorflow.gfile.IsDirectory', 'tf.gfile.IsDirectory', (['FLAGS.checkpoint_path'], {}), '(FLAGS.checkpoint_path)\n', (7526, 7549), True, 'import tensorflow as tf\n'), ((9782, 9823), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), '(tf.logging.INFO)\n', (9806, 9823), True, 'import tensorflow as tf\n'), ((15311, 15323), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (15321, 15323), True, 'import tensorflow as tf\n'), ((4109, 4160), 'os.path.join', 'os.path.join', (['dataset_dir', '"""dataset_split_info.csv"""'], {}), "(dataset_dir, 'dataset_split_info.csv')\n", (4121, 4160), False, 'import os\n'), ((4441, 4476), 'tensorflow.gfile.Open', 'tf.gfile.Open', (['labels_filename', '"""r"""'], {}), "(labels_filename, 'r')\n", (4454, 4476), True, 'import tensorflow as tf\n'), ((5551, 5578), 'numpy.random.randint', 'np.random.randint', (['(175)', '(223)'], {}), '(175, 223)\n', (5568, 5578), True, 'import numpy as np\n'), ((5605, 5660), 'tensorflow.random_crop', 'tf.random_crop', (['image', '[output_height, output_width, 3]'], {}), '(image, [output_height, output_width, 3])\n', (5619, 5660), True, 'import tensorflow as tf\n'), ((5687, 5721), 'tensorflow.expand_dims', 'tf.expand_dims', (['distorted_image', '(0)'], {}), '(distorted_image, 0)\n', (5701, 5721), True, 'import tensorflow as tf\n'), ((5746, 5843), 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (['distorted_image', '[output_height, output_width]'], {'align_corners': '(False)'}), '(distorted_image, [output_height, output_width],\n align_corners=False)\n', (5770, 5843), True, 'import tensorflow as tf\n'), ((5864, 5889), 'tensorflow.squeeze', 'tf.squeeze', (['resized_image'], {}), '(resized_image)\n', (5874, 5889), True, 'import tensorflow as tf\n'), ((5980, 6026), 'tensorflow.image.random_flip_left_right', 'tf.image.random_flip_left_right', (['resized_image'], {}), '(resized_image)\n', (6011, 6026), True, 'import tensorflow as tf\n'), ((6044, 6070), 'tensorflow.to_float', 'tf.to_float', (['resized_image'], {}), '(resized_image)\n', (6055, 6070), True, 'import tensorflow as tf\n'), ((6807, 6870), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['learning_rate'], {'name': '"""training/Learning Rate"""'}), "(learning_rate, name='training/Learning Rate')\n", (6824, 6870), True, 'import tensorflow as tf\n'), ((6958, 7001), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['FLAGS.train_dir'], {}), '(FLAGS.train_dir)\n', (6984, 7001), True, 'import tensorflow as tf\n'), ((7577, 7626), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['FLAGS.checkpoint_path'], {}), '(FLAGS.checkpoint_path)\n', (7603, 7626), True, 'import tensorflow as tf\n'), ((8128, 8186), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES', 'scope'], {}), '(tf.GraphKeys.TRAINABLE_VARIABLES, scope)\n', (8145, 8186), True, 'import tensorflow as tf\n'), ((8676, 8727), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.string'], {'default_value': '""""""'}), "((), tf.string, default_value='')\n", (8694, 8727), True, 'import tensorflow as tf\n'), ((8769, 8823), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.string'], {'default_value': '"""png"""'}), "((), tf.string, default_value='png')\n", (8787, 8823), True, 'import tensorflow as tf\n'), ((9882, 10024), 'deployment.model_deploy.DeploymentConfig', 'model_deploy.DeploymentConfig', ([], {'num_clones': 'FLAGS.num_clones', 'clone_on_cpu': 'FLAGS.clone_on_cpu', 'replica_id': '(0)', 'num_replicas': '(1)', 'num_ps_tasks': '(0)'}), '(num_clones=FLAGS.num_clones, clone_on_cpu=\n FLAGS.clone_on_cpu, replica_id=0, num_replicas=1, num_ps_tasks=0)\n', (9911, 10024), False, 'from deployment import model_deploy\n'), ((12195, 12261), 'deployment.model_deploy.create_clones', 'model_deploy.create_clones', (['deploy_config', 'clone_fn', '[batch_queue]'], {}), '(deploy_config, clone_fn, [batch_queue])\n', (12221, 12261), False, 'from deployment import model_deploy\n'), ((12340, 12401), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS', 'first_clone_scope'], {}), '(tf.GraphKeys.UPDATE_OPS, first_clone_scope)\n', (12357, 12401), True, 'import tensorflow as tf\n'), ((12710, 12767), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.LOSSES', 'first_clone_scope'], {}), '(tf.GraphKeys.LOSSES, first_clone_scope)\n', (12727, 12767), True, 'import tensorflow as tf\n'), ((14077, 14153), 'deployment.model_deploy.optimize_clones', 'model_deploy.optimize_clones', (['clones', 'optimizer'], {'var_list': 'variables_to_train'}), '(clones, optimizer, var_list=variables_to_train)\n', (14105, 14153), False, 'from deployment import model_deploy\n'), ((14375, 14396), 'tensorflow.group', 'tf.group', (['*update_ops'], {}), '(*update_ops)\n', (14383, 14396), True, 'import tensorflow as tf\n'), ((14420, 14496), 'tensorflow.python.ops.control_flow_ops.with_dependencies', 'control_flow_ops.with_dependencies', (['[update_op]', 'total_loss'], {'name': '"""train_op"""'}), "([update_op], total_loss, name='train_op')\n", (14454, 14496), False, 'from tensorflow.python.ops import control_flow_ops\n'), ((6740, 6784), 'tensorflow.summary.image', 'tf.summary.image', (['variable.op.name', 'variable'], {}), '(variable.op.name, variable)\n', (6756, 6784), True, 'import tensorflow as tf\n'), ((11300, 11440), 'tensorflow.train.batch', 'tf.train.batch', (['[image, label]'], {'batch_size': 'FLAGS.batch_size', 'num_threads': 'FLAGS.num_preprocessing_threads', 'capacity': '(5 * FLAGS.batch_size)'}), '([image, label], batch_size=FLAGS.batch_size, num_threads=\n FLAGS.num_preprocessing_threads, capacity=5 * FLAGS.batch_size)\n', (11314, 11440), True, 'import tensorflow as tf\n'), ((11918, 11936), 'tensorflow.squeeze', 'tf.squeeze', (['logits'], {}), '(logits)\n', (11928, 11936), True, 'import tensorflow as tf\n'), ((12134, 12175), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.SUMMARIES'], {}), '(tf.GraphKeys.SUMMARIES)\n', (12151, 12175), True, 'import tensorflow as tf\n'), ((13162, 13334), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['FLAGS.learning_rate', 'global_step', 'decay_steps', 'FLAGS.learning_rate_decay_factor'], {'staircase': '(True)', 'name': '"""exponential_decay_learning_rate"""'}), "(FLAGS.learning_rate, global_step, decay_steps,\n FLAGS.learning_rate_decay_factor, staircase=True, name=\n 'exponential_decay_learning_rate')\n", (13188, 13334), True, 'import tensorflow as tf\n'), ((13625, 13756), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', (['learning_rate'], {'decay': 'FLAGS.rmsprop_decay', 'momentum': 'FLAGS.rmsprop_momentum', 'epsilon': 'FLAGS.opt_epsilon'}), '(learning_rate, decay=FLAGS.rmsprop_decay,\n momentum=FLAGS.rmsprop_momentum, epsilon=FLAGS.opt_epsilon)\n', (13650, 13756), True, 'import tensorflow as tf\n'), ((14176, 14219), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""total_loss"""', 'total_loss'], {}), "('total_loss', total_loss)\n", (14193, 14219), True, 'import tensorflow as tf\n'), ((14523, 14583), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.SUMMARIES', 'first_clone_scope'], {}), '(tf.GraphKeys.SUMMARIES, first_clone_scope)\n', (14540, 14583), True, 'import tensorflow as tf\n'), ((8981, 9009), 'tensorflow.zeros', 'tf.zeros', (['[]'], {'dtype': 'tf.int64'}), '([], dtype=tf.int64)\n', (8989, 9009), True, 'import tensorflow as tf\n'), ((9833, 9843), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (9841, 9843), True, 'import tensorflow as tf\n'), ((12543, 12594), 'tensorflow.summary.histogram', 'tf.summary.histogram', (["('activations/' + end_point)", 'x'], {}), "('activations/' + end_point, x)\n", (12563, 12594), True, 'import tensorflow as tf\n'), ((12795, 12846), 'tensorflow.summary.scalar', 'tf.summary.scalar', (["('losses/%s' % loss.op.name)", 'loss'], {}), "('losses/%s' % loss.op.name, loss)\n", (12812, 12846), True, 'import tensorflow as tf\n'), ((12926, 12974), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['variable.op.name', 'variable'], {}), '(variable.op.name, variable)\n', (12946, 12974), True, 'import tensorflow as tf\n'), ((13929, 13978), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""learning_rate"""', 'learning_rate'], {}), "('learning_rate', learning_rate)\n", (13946, 13978), True, 'import tensorflow as tf\n'), ((12665, 12687), 'tensorflow.nn.zero_fraction', 'tf.nn.zero_fraction', (['x'], {}), '(x)\n', (12684, 12687), True, 'import tensorflow as tf\n')]
|
import jieba
import pandas as pd
import numpy as np
from sklearn import feature_extraction
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
import time
import os
import re
def readExcel(url):
df=pd.read_excel(url,na_values='')
return df
def writeExcel(df,url=''):
write = pd.ExcelWriter(url)
df.to_excel(write, sheet_name='Sheet1',merge_cells=False)
write.save()
def genDF(df_Base,df_IPC):
columns=df_Base['合并后'].unique()
index=df_IPC['NAME'].unique()
return pd.DataFrame(None,index=index,columns=columns)
pass
def checkVect(df_Input,vectkey,vectipc):
coripc=__ipc(df_Input['IPC'])
corkey=__jiebabatch(df_Input['ABSTRACT'])
matkey=vectkey.transform(corkey)
matipc=vectipc.transform(coripc)
matkey = np.where(matkey.toarray() > 0, 1, 0)
matipc = np.where(matipc.toarray() > 0, 1, 0)
return matkey,matipc
def addNewPT(key,newkey,ipc,newipc,Cpy,Cat,df_result=[],s_Cat=[],corkeyNo=[]):
'''输出两个:1. 公司各个行业属性的专利记录,2. 专利对应的属性'''
if df_result==[]:
df_result=pd.DataFrame(None,columns=['Company','Cat','Val'])
for i in range(newkey.shape[0]):
print('Processing--------------',i)
onekey=newkey[i]
oneipc=newipc[i]
companyName=Cpy[i]
mat=np.dot(key, onekey) * np.dot(ipc, oneipc)
matcat=Cat[(mat-corkeyNo)>=0].unique()
cat=[]#用于记录ip的属性
for j in matcat:
df_result=df_result.append({'Company':companyName,'Cat':j,'Val':1},ignore_index=True)
cat.append(j)
s_Cat.append(' '.join(cat))
return df_result,s_Cat
pass
def __jiebabatch(summary):
'''每行增加none,使得没有的也能匹配上'''
cor=[]
for j,i in enumerate(summary):
if j%1000==0:
print('ABSTRACT@----------',j)
subcor = ['None']
if type(i)!=type(1.1):
b=jieba.cut(i)
for j in b:
subcor.append(j)
joint=' '
subcor=joint.join(subcor)
else:
subcor='None'
cor.append(subcor)
return cor
pass
def __ipc(ipc):
'''每行增加none,使得没有的也能匹配上'''
cor=[]
lv0=re.compile(u'\D+[0-9]{1,3}')
lv1=re.compile(u'\D+[0-9]{1,3}\D+')
lv2=re.compile(u'\D+[0-9]{1,3}\D+[0-9]{1,3}')
for j,i in enumerate(ipc):
if j%1000==0:#todo
print('IPC@---------',j)
subcor=['none']
if type(i)!=type(1.1):#写入ipc三级域名 modified--0828
subcor.append(lv0.findall(i)[0])
subcor.append(lv1.findall(i)[0])
if lv2.findall(i):
subcor.append(lv2.findall(i)[0])
a = i.split(sep='_')
if len(a)>1:
subcor.append(i)
joint = ' '
subcor = joint.join(subcor)
cor.append(subcor)
return cor
pass
def addDict(df):
'''根据分类标准在结巴分词中加入新关键词'''
word=set(df['keywords'].unique())
word1=set(df['keywords1'].unique())
word2 = set(df['keyward2'].unique())
word3 = set(df['notkeywords'].unique())
word=word | word1 | word2 | word3
for i in word:
jieba.add_word(str(i),freq=100)
pass
def getBaseCor(df):
'''用于tdidf'''
corkey=[]
coripc = []
corkeyNo=[]
for i in df.index:
subcor=[]
no=0
if type(df.loc[i,'keywords'])!=type(1.1):
subcor.append(df.loc[i,'keywords'])
no=no+1
if type(df.loc[i, 'keywords1']) != type(1.1):
subcor.append(df.loc[i, 'keywords1'])
no=no+1
else:
subcor=['None']
no=1
joint=' '
subcor=joint.join(subcor)
corkey.append(subcor)
corkeyNo.append(no)
subcor=[]
if type(df.loc[i, 'IPC']) != type(1.1):
subcor.append(df.loc[i, 'IPC'])
# a=df.loc[i,'IPC'].split(sep='/')
# if len(a)>1:
# subcor.append(a[0])
else:
subcor=['None']
joint=' '
subcor=joint.join(subcor)
coripc.append(subcor)
return corkey,coripc,np.array(corkeyNo)
def TFtraintfidf(corkey,coripc):
'''计算分词矩阵'''
vectorizerkey = CountVectorizer(analyzer='word',token_pattern='(?<KEY>')
#CountVectorizer(analyzer='word',token_pattern='(?<KEY>')
key=vectorizerkey.fit_transform(corkey)
vectorizeripc = CountVectorizer()
ipc=vectorizeripc.fit_transform(coripc)
return np.where(key.toarray()>0,1,0),vectorizerkey,np.where(ipc.toarray()>0,1,0),vectorizeripc
def readFilesName(dir):
name=[]
for parent,dirnames,filenames in os.walk(dir):
for filename in filenames:
url=parent+filename
name.append(url)
return name
if __name__=="__main__":
#1.inial
docdir = os.path.abspath('..') + '\\doc\\'
name=readFilesName(docdir+'raw\\')
IndustryFileName='industry_sep.xlsx'
print('Initialize Finished')#todo
#df_IPC=readExcel(docdir+IPCFileName)
#2.read file
for j,i in enumerate(name):
df_Input=readExcel(i)
df_Input['IPC']=df_Input['IPC'].str.replace('/','_')
df_Base=readExcel(docdir+IndustryFileName)
df_Base['IPC']=df_Base['IPC'].str.replace('/','_')
addDict(df_Base)
print('Data_Read_Finished')#todo
#3.run
start=time.clock()
corkey, coripc,corkeyNo=getBaseCor(df_Base)
print('Classify Finished')#todo
key, vectkey, ipc, vectipc=TFtraintfidf(corkey,coripc)
newkey,newipc=checkVect(df_Input,vectkey,vectipc)
print('Analysising new input finished')#todo
Cpy=df_Input['APPLICATION']
Cat=df_Base['合并后']
w,cat=addNewPT(key, newkey, ipc, newipc, Cpy, Cat, df_result=[],s_Cat=[],corkeyNo=corkeyNo)
end=time.clock()
dur=end-start
df_f=w.groupby(['Company','Cat'])['Cat'].count()
#4.export excel
#for check
df_Input['Cat']=cat
writeExcel(df_Input, docdir + 're\\check0828' + str(j) + '.xlsx')
writeExcel(df_f,docdir+'re\\result0828'+str(j)+'.xlsx')
print(dur)
|
[
"pandas.DataFrame",
"sklearn.feature_extraction.text.CountVectorizer",
"os.path.abspath",
"jieba.cut",
"os.walk",
"time.clock",
"pandas.read_excel",
"numpy.array",
"numpy.dot",
"pandas.ExcelWriter",
"re.compile"
] |
[((272, 304), 'pandas.read_excel', 'pd.read_excel', (['url'], {'na_values': '""""""'}), "(url, na_values='')\n", (285, 304), True, 'import pandas as pd\n'), ((358, 377), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['url'], {}), '(url)\n', (372, 377), True, 'import pandas as pd\n'), ((566, 614), 'pandas.DataFrame', 'pd.DataFrame', (['None'], {'index': 'index', 'columns': 'columns'}), '(None, index=index, columns=columns)\n', (578, 614), True, 'import pandas as pd\n'), ((2190, 2219), 're.compile', 're.compile', (['u"""\\\\D+[0-9]{1,3}"""'], {}), "(u'\\\\D+[0-9]{1,3}')\n", (2200, 2219), False, 'import re\n'), ((2227, 2260), 're.compile', 're.compile', (['u"""\\\\D+[0-9]{1,3}\\\\D+"""'], {}), "(u'\\\\D+[0-9]{1,3}\\\\D+')\n", (2237, 2260), False, 'import re\n'), ((2267, 2310), 're.compile', 're.compile', (['u"""\\\\D+[0-9]{1,3}\\\\D+[0-9]{1,3}"""'], {}), "(u'\\\\D+[0-9]{1,3}\\\\D+[0-9]{1,3}')\n", (2277, 2310), False, 'import re\n'), ((4194, 4251), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'analyzer': '"""word"""', 'token_pattern': '"""(?<KEY>"""'}), "(analyzer='word', token_pattern='(?<KEY>')\n", (4209, 4251), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((4377, 4394), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (4392, 4394), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((4612, 4624), 'os.walk', 'os.walk', (['dir'], {}), '(dir)\n', (4619, 4624), False, 'import os\n'), ((1106, 1159), 'pandas.DataFrame', 'pd.DataFrame', (['None'], {'columns': "['Company', 'Cat', 'Val']"}), "(None, columns=['Company', 'Cat', 'Val'])\n", (1118, 1159), True, 'import pandas as pd\n'), ((4104, 4122), 'numpy.array', 'np.array', (['corkeyNo'], {}), '(corkeyNo)\n', (4112, 4122), True, 'import numpy as np\n'), ((4790, 4811), 'os.path.abspath', 'os.path.abspath', (['""".."""'], {}), "('..')\n", (4805, 4811), False, 'import os\n'), ((5331, 5343), 'time.clock', 'time.clock', ([], {}), '()\n', (5341, 5343), False, 'import time\n'), ((5786, 5798), 'time.clock', 'time.clock', ([], {}), '()\n', (5796, 5798), False, 'import time\n'), ((1327, 1346), 'numpy.dot', 'np.dot', (['key', 'onekey'], {}), '(key, onekey)\n', (1333, 1346), True, 'import numpy as np\n'), ((1349, 1368), 'numpy.dot', 'np.dot', (['ipc', 'oneipc'], {}), '(ipc, oneipc)\n', (1355, 1368), True, 'import numpy as np\n'), ((1903, 1915), 'jieba.cut', 'jieba.cut', (['i'], {}), '(i)\n', (1912, 1915), False, 'import jieba\n')]
|
# ============================================================================
# 第十章 家電・調理
# Ver.04(エネルギー消費性能計算プログラム(住宅版)Ver.02~)
# ============================================================================
import numpy as np
from pyhees.section11_3 import load_schedule, get_schedule_app, get_schedule_cc
# ============================================================================
# 5. 家電の一次エネルギー消費量
# ============================================================================
# ============================================================================
# 5.1 消費電力量
# ============================================================================
def calc_E_E_AP_d_t(n_p):
"""1 時間当たりの家電の消費電力量
Args:
n_p(float): 仮想居住人数 仮想居住人数
Returns:
ndarray: 1 時間当たりの家電の消費電力量
"""
schedule = load_schedule()
schedule_app = get_schedule_app(schedule)
if 1 <= n_p and n_p <= 2:
E_E_AP_1_d_t = get_E_E_AP_p_d_t(1, schedule_app)
E_E_AP_2_d_t = get_E_E_AP_p_d_t(2, schedule_app)
return E_E_AP_1_d_t * (2 - n_p) / (2 - 1) + E_E_AP_2_d_t * (n_p - 1) / (2 - 1)
elif 2 <= n_p and n_p <= 3:
E_E_AP_2_d_t = get_E_E_AP_p_d_t(2, schedule_app)
E_E_AP_3_d_t = get_E_E_AP_p_d_t(3, schedule_app)
return E_E_AP_2_d_t * (3 - n_p) / (3 - 2) + E_E_AP_3_d_t * (n_p - 2) / (3 - 2)
elif 3 <= n_p and n_p <= 4:
E_E_AP_3_d_t = get_E_E_AP_p_d_t(3, schedule_app)
E_E_AP_4_d_t = get_E_E_AP_p_d_t(4, schedule_app)
return E_E_AP_3_d_t * (4 - n_p) / (4 - 3) + E_E_AP_4_d_t * (n_p - 3) / (4 - 3)
else:
raise ValueError(n_p)
# ============================================================================
# 5.2 ガス消費量
# ============================================================================
def get_E_G_AP_d_t():
"""1 時間当たりの家電のガス消費量
Args:
Returns:
ndarray: 1 時間当たりの家電のガス消費量
"""
return np.zeros(24 * 365)
# ============================================================================
# 5.3 灯油消費量
# ============================================================================
def get_E_K_AP_d_t():
"""1 時間当たりの家電の灯油消費量
Args:
Returns:
ndarray: 1 時間当たりの家電の灯油消費量
"""
return np.zeros(24 * 365)
# ============================================================================
# 5.4 その他の燃料による一次エネルギー消費量
# ============================================================================
def get_E_M_AP_d_t():
"""1 時間当たりの家電のその他の燃料による一次エネルギー消費量
Args:
Returns:
ndarray: 1 時間当たりの家電のその他の燃料による一次エネルギー消費量
"""
return np.zeros(24 * 365)
# ============================================================================
# 6. 調理の一次エネルギー消費量
# ============================================================================
# ============================================================================
# 6.1 消費電力量
# ============================================================================
def get_E_E_CC_d_t():
"""1 時間当たりの調理の消費電力量
Args:
Returns:
ndarray: 1 時間当たりの調理の消費電力量
"""
return np.zeros(24 * 365)
# ============================================================================
# 6.2 ガス消費量
# ============================================================================
def calc_E_G_CC_d_t(n_p):
"""1 時間当たりの調理のガス消費量
Args:
n_p(float): 仮想居住人数
Returns:
ndarray: 1 時間当たりの調理のガス消費量
"""
schedule = load_schedule()
schedule_cc = get_schedule_cc(schedule)
if 1 <= n_p and n_p <= 2:
E_G_CC_1_d_t = get_E_G_CC_p_d_t(1, schedule_cc)
E_G_CC_2_d_t = get_E_G_CC_p_d_t(2, schedule_cc)
return E_G_CC_1_d_t * (2 - n_p) / (2 - 1) + E_G_CC_2_d_t * (n_p - 1) / (2 - 1)
elif 2 <= n_p and n_p <= 3:
E_G_CC_2_d_t = get_E_G_CC_p_d_t(2, schedule_cc)
E_G_CC_3_d_t = get_E_G_CC_p_d_t(3, schedule_cc)
return E_G_CC_2_d_t * (3 - n_p) / (3 - 2) + E_G_CC_3_d_t * (n_p - 2) / (3 - 2)
elif 3 <= n_p and n_p <= 4:
E_G_CC_3_d_t = get_E_G_CC_p_d_t(3, schedule_cc)
E_G_CC_4_d_t = get_E_G_CC_p_d_t(4, schedule_cc)
return E_G_CC_3_d_t * (4 - n_p) / (4 - 3) + E_G_CC_4_d_t * (n_p - 3) / (4 - 3)
else:
raise ValueError(n_p)
# ============================================================================
# 6.3 灯油消費量
# ============================================================================
def get_E_K_CC_d_t():
"""1 時間当たりの調理の灯油消費量
Args:
Returns:
ndarray: 1 時間当たりの調理の灯油消費量
"""
return np.zeros(24 * 365)
# ============================================================================
# 6.4 その他の燃料による一次エネルギー消費量
# ============================================================================
def get_E_M_CC_d_t():
"""1 時間当たりの調理のその他の燃料による一次エネルギー消費量
Args:
Returns:
ndarray: 1 時間当たりの調理のその他の燃料による一次エネルギー消費量
"""
return np.zeros(24 * 365)
# ============================================================================
# 付録 A 1 時間当たりのエネルギー消費量の計算方法
# ============================================================================
# ============================================================================
# A.1 家電による消費電力量
# ============================================================================
def get_E_E_AP_p_d_t(p, schedule_app):
"""1 時間当たりの居住人数がp人における家電の消費電力量
Args:
p(float): 居住人数
schedule_app(ndarray): 家電スケジュール
Returns:
ndarray: 1 時間当たりの居住人数がp人における家電の消費電力量
"""
# 平日
workday = np.tile([get_table_a_1()[i][(p - 1) * 3 + 0] for i in range(24)], 365)
# 休日外出
holiday_out = np.tile([get_table_a_1()[i][(p - 1) * 3 + 1] for i in range(24)], 365)
# 休日在宅
holiday_in = np.tile([get_table_a_1()[i][(p - 1) * 3 + 2] for i in range(24)], 365)
# スケジュールを時間ごとに拡張
schedule = np.repeat(schedule_app, 24)
return (workday * (schedule == '平日')
+ holiday_out * (schedule == '休日外')
+ holiday_in * (schedule == '休日在'))
# ============================================================================
# A.2 調理によるガス消費量
# ============================================================================
def get_E_G_CC_p_d_t(p, schedule_cc):
"""1 時間当たりの居住人数がp人における調理のガス消費量
Args:
p(float): 居住人数
schedule_cc(ndarray): 調理スケジュール
Returns:
ndarray: 1 時間当たりの居住人数がp人における調理のガス消費量
"""
# 平日
workday = np.tile([get_table_a_2()[i][(p - 1) * 3 + 0] for i in range(24)], 365)
# 休日外出
holiday_out = np.tile([get_table_a_2()[i][(p - 1) * 3 + 1] for i in range(24)], 365)
# 休日在宅
holiday_in = np.tile([get_table_a_2()[i][(p - 1) * 3 + 2] for i in range(24)], 365)
# スケジュールを時間ごとに拡張
schedule = np.repeat(schedule_cc, 24)
return (workday * (schedule == '平日')
+ holiday_out * (schedule == '休日外')
+ holiday_in * (schedule == '休日在'))
def get_table_a_1():
"""表 A.1 家電による 1 時間当たりの消費電力量
Args:
Returns:
list: 表 A.1 家電による 1 時間当たりの消費電力量
"""
table_a_1 = [
(0.1578, 0.1578, 0.1578, 0.1578, 0.1578, 0.1578, 0.1806, 0.1806, 0.1806, 0.1812, 0.1812, 0.1812),
(0.0483, 0.0483, 0.0483, 0.0483, 0.0483, 0.0483, 0.0711, 0.0711, 0.0711, 0.0717, 0.0717, 0.0717),
(0.0560, 0.0560, 0.0560, 0.0561, 0.0561, 0.0561, 0.0788, 0.0788, 0.0788, 0.0795, 0.0795, 0.0795),
(0.0560, 0.0560, 0.0560, 0.0561, 0.0561, 0.0561, 0.0788, 0.0788, 0.0788, 0.0795, 0.0795, 0.0795),
(0.0483, 0.0483, 0.0483, 0.0483, 0.0483, 0.0483, 0.0711, 0.0711, 0.0711, 0.0717, 0.0717, 0.0717),
(0.0560, 0.0560, 0.0560, 0.0561, 0.0561, 0.0561, 0.0788, 0.0788, 0.0788, 0.0795, 0.0795, 0.0795),
(0.1925, 0.0859, 0.0560, 0.2611, 0.1159, 0.0561, 0.3525, 0.1685, 0.0788, 0.3531, 0.1692, 0.0795),
(0.1524, 0.2346, 0.1168, 0.2480, 0.2703, 0.1854, 0.3662, 0.3287, 0.2767, 0.3669, 0.3294, 0.2774),
(0.1091, 0.2282, 0.2156, 0.1448, 0.3325, 0.2812, 0.2032, 0.4595, 0.3696, 0.2039, 0.4602, 0.3702),
(0.3011, 0.0560, 0.2163, 0.3368, 0.0561, 0.2520, 0.3953, 0.0788, 0.3265, 0.3960, 0.0795, 0.3272),
(0.0483, 0.0483, 0.1917, 0.0483, 0.0483, 0.2274, 0.0711, 0.0711, 0.3128, 0.0717, 0.0717, 0.3134),
(0.0560, 0.0560, 0.1994, 0.0561, 0.0561, 0.2352, 0.0788, 0.0788, 0.3150, 0.0795, 0.0795, 0.3157),
(0.1983, 0.0560, 0.1983, 0.2727, 0.0561, 0.2727, 0.3698, 0.0788, 0.3698, 0.3705, 0.0795, 0.3705),
(0.0483, 0.0483, 0.0483, 0.0483, 0.0483, 0.0483, 0.0711, 0.0711, 0.0711, 0.0717, 0.0717, 0.0717),
(0.0560, 0.0560, 0.0560, 0.0561, 0.0561, 0.0561, 0.0788, 0.0788, 0.0788, 0.0795, 0.0795, 0.0795),
(0.0560, 0.0560, 0.0560, 0.0561, 0.0561, 0.0561, 0.0788, 0.0788, 0.0788, 0.0795, 0.0795, 0.0795),
(0.0483, 0.0483, 0.2095, 0.0483, 0.0483, 0.2750, 0.0711, 0.0711, 0.3956, 0.0717, 0.0717, 0.5453),
(0.1304, 0.0560, 0.2423, 0.2048, 0.0561, 0.2781, 0.3019, 0.0788, 0.3689, 0.3026, 0.0795, 0.5187),
(0.3030, 0.0560, 0.1819, 0.3387, 0.0561, 0.2177, 0.3972, 0.0788, 0.2978, 0.5469, 0.0795, 0.4476),
(0.0991, 0.0483, 0.0998, 0.1348, 0.0483, 0.1355, 0.1932, 0.0711, 0.2049, 0.1939, 0.0717, 0.2056),
(0.0917, 0.1304, 0.0917, 0.1275, 0.2048, 0.1275, 0.2102, 0.3129, 0.2183, 0.2109, 0.4626, 0.2190),
(0.1216, 0.1755, 0.1755, 0.1873, 0.2411, 0.2411, 0.2837, 0.3322, 0.3458, 0.2844, 0.4447, 0.3465),
(0.1738, 0.0510, 0.1139, 0.1917, 0.0511, 0.1795, 0.2620, 0.0952, 0.3002, 0.2626, 0.0959, 0.3009),
(0.1877, 0.1877, 0.1578, 0.2176, 0.2176, 0.1578, 0.2756, 0.2703, 0.1806, 0.2763, 0.2709, 0.1812),
]
return table_a_1
def get_table_a_2():
"""表 A.2 調理による 1 時間当たりのガス消費量
Args:
Returns:
list: 表 A.2 調理による 1 時間当たりのガス消費量
"""
table_a_2 = [
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 1.5935, 0, 0, 1.9235, 0, 0, 2.2536, 0, 0),
(1.0672, 0, 0, 0, 1.116, 1.116, 0, 0, 0, 0, 0, 0),
(0, 1.0672, 1.0672, 0, 0, 0, 0, 1.3472, 1.3472, 0, 1.5783, 1.5783),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 1.1401, 1.3762, 0, 1.3762, 1.6123, 0, 1.6123),
(0, 0, 1.0902, 1.1401, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 5.4175, 0, 0, 6.5395, 0, 0, 7.6615),
(0, 0, 5.1806, 5.4175, 0, 0, 6.5395, 0, 0, 7.6615, 0, 0),
(5.1806, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
]
return table_a_2
|
[
"pyhees.section11_3.get_schedule_cc",
"pyhees.section11_3.get_schedule_app",
"numpy.zeros",
"pyhees.section11_3.load_schedule",
"numpy.repeat"
] |
[((823, 838), 'pyhees.section11_3.load_schedule', 'load_schedule', ([], {}), '()\n', (836, 838), False, 'from pyhees.section11_3 import load_schedule, get_schedule_app, get_schedule_cc\n'), ((858, 884), 'pyhees.section11_3.get_schedule_app', 'get_schedule_app', (['schedule'], {}), '(schedule)\n', (874, 884), False, 'from pyhees.section11_3 import load_schedule, get_schedule_app, get_schedule_cc\n'), ((1919, 1937), 'numpy.zeros', 'np.zeros', (['(24 * 365)'], {}), '(24 * 365)\n', (1927, 1937), True, 'import numpy as np\n'), ((2234, 2252), 'numpy.zeros', 'np.zeros', (['(24 * 365)'], {}), '(24 * 365)\n', (2242, 2252), True, 'import numpy as np\n'), ((2591, 2609), 'numpy.zeros', 'np.zeros', (['(24 * 365)'], {}), '(24 * 365)\n', (2599, 2609), True, 'import numpy as np\n'), ((3084, 3102), 'numpy.zeros', 'np.zeros', (['(24 * 365)'], {}), '(24 * 365)\n', (3092, 3102), True, 'import numpy as np\n'), ((3432, 3447), 'pyhees.section11_3.load_schedule', 'load_schedule', ([], {}), '()\n', (3445, 3447), False, 'from pyhees.section11_3 import load_schedule, get_schedule_app, get_schedule_cc\n'), ((3466, 3491), 'pyhees.section11_3.get_schedule_cc', 'get_schedule_cc', (['schedule'], {}), '(schedule)\n', (3481, 3491), False, 'from pyhees.section11_3 import load_schedule, get_schedule_app, get_schedule_cc\n'), ((4520, 4538), 'numpy.zeros', 'np.zeros', (['(24 * 365)'], {}), '(24 * 365)\n', (4528, 4538), True, 'import numpy as np\n'), ((4878, 4896), 'numpy.zeros', 'np.zeros', (['(24 * 365)'], {}), '(24 * 365)\n', (4886, 4896), True, 'import numpy as np\n'), ((5805, 5832), 'numpy.repeat', 'np.repeat', (['schedule_app', '(24)'], {}), '(schedule_app, 24)\n', (5814, 5832), True, 'import numpy as np\n'), ((6689, 6715), 'numpy.repeat', 'np.repeat', (['schedule_cc', '(24)'], {}), '(schedule_cc, 24)\n', (6698, 6715), True, 'import numpy as np\n')]
|
from __future__ import print_function, division
import numpy as np
import imgaug as ia
from imgaug import augmenters as iaa
def main():
quokka = ia.quokka(size=0.5)
h, w = quokka.shape[0:2]
heatmap = np.zeros((h, w), dtype=np.float32)
heatmap[70:120, 90:150] = 0.1
heatmap[30:70, 50:65] = 0.5
heatmap[20:50, 55:85] = 1.0
heatmap[120:140, 0:20] = 0.75
heatmaps = ia.HeatmapsOnImage(heatmap[..., np.newaxis], quokka.shape)
print("Affine...")
aug = iaa.Affine(translate_px={"x": 20}, mode="constant", cval=128)
quokka_aug = aug.augment_image(quokka)
heatmaps_aug = aug.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("Affine with mode=edge...")
aug = iaa.Affine(translate_px={"x": 20}, mode="edge")
quokka_aug = aug.augment_image(quokka)
heatmaps_aug = aug.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("PiecewiseAffine...")
aug = iaa.PiecewiseAffine(scale=0.04)
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("PerspectiveTransform...")
aug = iaa.PerspectiveTransform(scale=0.04)
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("ElasticTransformation alpha=3, sig=0.5...")
aug = iaa.ElasticTransformation(alpha=3.0, sigma=0.5)
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("ElasticTransformation alpha=10, sig=3...")
aug = iaa.ElasticTransformation(alpha=10.0, sigma=3.0)
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("CopAndPad mode=constant...")
aug = iaa.CropAndPad(px=(-10, 10, 15, -15), pad_mode="constant", pad_cval=128)
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("CopAndPad mode=constant + percent...")
aug = iaa.CropAndPad(percent=(-0.05, 0.05, 0.1, -0.1), pad_mode="constant", pad_cval=128)
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("CropAndPad mode=edge...")
aug = iaa.CropAndPad(px=(-10, 10, 15, -15), pad_mode="edge")
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
print("Scale...")
aug = iaa.Scale(0.5, interpolation="nearest")
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(ia.draw_grid([heatmaps_drawn[0], heatmaps_aug_drawn[0]], cols=2))
print("Alpha...")
aug = iaa.Alpha(0.7, iaa.Affine(rotate=20))
aug_det = aug.to_deterministic()
quokka_aug = aug_det.augment_image(quokka)
heatmaps_aug = aug_det.augment_heatmaps([heatmaps])[0]
heatmaps_drawn = heatmaps.draw_on_image(quokka)
heatmaps_aug_drawn = heatmaps_aug.draw_on_image(quokka_aug)
ia.imshow(
np.hstack([
heatmaps_drawn[0],
heatmaps_aug_drawn[0]
])
)
if __name__ == "__main__":
main()
|
[
"imgaug.HeatmapsOnImage",
"imgaug.augmenters.ElasticTransformation",
"imgaug.draw_grid",
"imgaug.quokka",
"numpy.zeros",
"numpy.hstack",
"imgaug.augmenters.Affine",
"imgaug.augmenters.PerspectiveTransform",
"imgaug.augmenters.CropAndPad",
"imgaug.augmenters.Scale",
"imgaug.augmenters.PiecewiseAffine"
] |
[((153, 172), 'imgaug.quokka', 'ia.quokka', ([], {'size': '(0.5)'}), '(size=0.5)\n', (162, 172), True, 'import imgaug as ia\n'), ((216, 250), 'numpy.zeros', 'np.zeros', (['(h, w)'], {'dtype': 'np.float32'}), '((h, w), dtype=np.float32)\n', (224, 250), True, 'import numpy as np\n'), ((399, 457), 'imgaug.HeatmapsOnImage', 'ia.HeatmapsOnImage', (['heatmap[..., np.newaxis]', 'quokka.shape'], {}), '(heatmap[..., np.newaxis], quokka.shape)\n', (417, 457), True, 'import imgaug as ia\n'), ((492, 553), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'translate_px': "{'x': 20}", 'mode': '"""constant"""', 'cval': '(128)'}), "(translate_px={'x': 20}, mode='constant', cval=128)\n", (502, 553), True, 'from imgaug import augmenters as iaa\n'), ((935, 982), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'translate_px': "{'x': 20}", 'mode': '"""edge"""'}), "(translate_px={'x': 20}, mode='edge')\n", (945, 982), True, 'from imgaug import augmenters as iaa\n'), ((1358, 1389), 'imgaug.augmenters.PiecewiseAffine', 'iaa.PiecewiseAffine', ([], {'scale': '(0.04)'}), '(scale=0.04)\n', (1377, 1389), True, 'from imgaug import augmenters as iaa\n'), ((1815, 1851), 'imgaug.augmenters.PerspectiveTransform', 'iaa.PerspectiveTransform', ([], {'scale': '(0.04)'}), '(scale=0.04)\n', (1839, 1851), True, 'from imgaug import augmenters as iaa\n'), ((2295, 2342), 'imgaug.augmenters.ElasticTransformation', 'iaa.ElasticTransformation', ([], {'alpha': '(3.0)', 'sigma': '(0.5)'}), '(alpha=3.0, sigma=0.5)\n', (2320, 2342), True, 'from imgaug import augmenters as iaa\n'), ((2785, 2833), 'imgaug.augmenters.ElasticTransformation', 'iaa.ElasticTransformation', ([], {'alpha': '(10.0)', 'sigma': '(3.0)'}), '(alpha=10.0, sigma=3.0)\n', (2810, 2833), True, 'from imgaug import augmenters as iaa\n'), ((3262, 3334), 'imgaug.augmenters.CropAndPad', 'iaa.CropAndPad', ([], {'px': '(-10, 10, 15, -15)', 'pad_mode': '"""constant"""', 'pad_cval': '(128)'}), "(px=(-10, 10, 15, -15), pad_mode='constant', pad_cval=128)\n", (3276, 3334), True, 'from imgaug import augmenters as iaa\n'), ((3773, 3860), 'imgaug.augmenters.CropAndPad', 'iaa.CropAndPad', ([], {'percent': '(-0.05, 0.05, 0.1, -0.1)', 'pad_mode': '"""constant"""', 'pad_cval': '(128)'}), "(percent=(-0.05, 0.05, 0.1, -0.1), pad_mode='constant',\n pad_cval=128)\n", (3787, 3860), True, 'from imgaug import augmenters as iaa\n'), ((4282, 4336), 'imgaug.augmenters.CropAndPad', 'iaa.CropAndPad', ([], {'px': '(-10, 10, 15, -15)', 'pad_mode': '"""edge"""'}), "(px=(-10, 10, 15, -15), pad_mode='edge')\n", (4296, 4336), True, 'from imgaug import augmenters as iaa\n'), ((4747, 4786), 'imgaug.augmenters.Scale', 'iaa.Scale', (['(0.5)'], {'interpolation': '"""nearest"""'}), "(0.5, interpolation='nearest')\n", (4756, 4786), True, 'from imgaug import augmenters as iaa\n'), ((792, 845), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (801, 845), True, 'import numpy as np\n'), ((1221, 1274), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (1230, 1274), True, 'import numpy as np\n'), ((1673, 1726), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (1682, 1726), True, 'import numpy as np\n'), ((2135, 2188), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (2144, 2188), True, 'import numpy as np\n'), ((2626, 2679), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (2635, 2679), True, 'import numpy as np\n'), ((3117, 3170), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (3126, 3170), True, 'import numpy as np\n'), ((3618, 3671), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (3627, 3671), True, 'import numpy as np\n'), ((4140, 4193), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (4149, 4193), True, 'import numpy as np\n'), ((4620, 4673), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (4629, 4673), True, 'import numpy as np\n'), ((5061, 5125), 'imgaug.draw_grid', 'ia.draw_grid', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {'cols': '(2)'}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]], cols=2)\n', (5073, 5125), True, 'import imgaug as ia\n'), ((5175, 5196), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'rotate': '(20)'}), '(rotate=20)\n', (5185, 5196), True, 'from imgaug import augmenters as iaa\n'), ((5481, 5534), 'numpy.hstack', 'np.hstack', (['[heatmaps_drawn[0], heatmaps_aug_drawn[0]]'], {}), '([heatmaps_drawn[0], heatmaps_aug_drawn[0]])\n', (5490, 5534), True, 'import numpy as np\n')]
|
import pytest
import numpy as np
import pclpy
def test_eigen_vectorxf():
a = np.array([1, 1, 1, 1], "f")
vec = pclpy.pcl.vectors.VectorXf(a)
assert np.allclose(np.array(vec), a)
|
[
"numpy.array",
"pclpy.pcl.vectors.VectorXf"
] |
[((84, 111), 'numpy.array', 'np.array', (['[1, 1, 1, 1]', '"""f"""'], {}), "([1, 1, 1, 1], 'f')\n", (92, 111), True, 'import numpy as np\n'), ((122, 151), 'pclpy.pcl.vectors.VectorXf', 'pclpy.pcl.vectors.VectorXf', (['a'], {}), '(a)\n', (148, 151), False, 'import pclpy\n'), ((175, 188), 'numpy.array', 'np.array', (['vec'], {}), '(vec)\n', (183, 188), True, 'import numpy as np\n')]
|
"""StyleGAN.
This module implements teh Generative Adversarial Network described in:
A Style-Based Generator Architecture for Generative Adversarial Networks
<NAME> (NVIDIA), <NAME> (NVIDIA), <NAME> (NVIDIA)
http://stylegan.xyz/paper
Code derived from:
https://github.com/SsnL/stylegan
"""
import collections
import os
import re
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
DIM_Z = collections.defaultdict(lambda: 512)
FULL_RESOLUTIONS = {
'lsun_car': (512, 384),
'ff_hq': (1024, 1024),
'celeba_hq': (1024, 1024),
'lsun_bedroom': (256, 256),
'lsun_cat': (256, 256),
}
RESOLUTIONS = {
'ff_hq': 1024,
'celeba_hq': 1024,
'lsun_bedroom': 256,
'lsun_car': 512,
'lsun_cat': 256,
}
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
root_url = 'http://pretorched-x.csail.mit.edu/gans/StyleGAN'
model_urls = {
'celeba_hq': {
1024: {
'G': os.path.join(root_url, 'celeba_hq_1024x1024_G-c8acef81.pth'),
},
},
'ff_hq': {
1024: {
'G': os.path.join(root_url, 'ff_hq_1024x1024_G-21a7044d.pth'),
}
},
'lsun_bedroom': {
256: {
'G': os.path.join(root_url, 'lsun_bedroom_256x256_G-da907d98.pth'),
},
},
'lsun_car': {
512: {
'G': os.path.join(root_url, 'lsun_car_512x384_G-d2188b0a.pth'),
},
},
'lsun_cat': {
256: {
'G': os.path.join(root_url, 'lsun_cat_256x256_G-384e9e73.pth'),
},
},
}
def stylegan(pretrained='ff_hq', resolution=None):
if pretrained is not None:
resolution = RESOLUTIONS.get(pretrained) if resolution is None else resolution
url = model_urls[pretrained][resolution]['G']
state_dict = torch.hub.load_state_dict_from_url(url)
net = G(out_res=resolution)
net.load_state_dict(state_dict)
else:
assert resolution is not None, 'Must specify pretrained model or resolution!'
net = G(out_res=max(resolution))
return net
class NonLinearityMeta(type):
def __call__(cls, *args, **kwargs):
return cls.activate(*args, **kwargs)
class NonLinearity(object, metaclass=NonLinearityMeta):
gain = NotImplemented
activate = NotImplemented
class ReLU(NonLinearity):
gain = np.sqrt(2)
activate = F.relu
class LeakyReLU(NonLinearity):
gain = np.sqrt(2)
@staticmethod
def activate(x, inplace=False):
return F.leaky_relu(x, negative_slope=0.2, inplace=inplace)
class ScaledParamModule(nn.Module):
# linear w: [ fan_out, fan_in ]
# conv w: [ nc_out, nc_in, k1, k2 ]
# convT w: [ nc_in, nc_out, k1, k2 ], but let's ignore this case because
# (1) the tf impl doesn't special-case
# (2) convT is only used for fusing Upsample & Conv2d, and in that case, the
# weight should be done as if it is for a Conv2d.
#
# NB: in tf code, use_wscale has default value False, but for StyleGAN it is
# True everywhere, so I changed it.
def scale_weight(self, gain=np.sqrt(2), use_wscale=True, lrmul=1, new_name='_weight'):
weight = self.weight
assert isinstance(weight, nn.Parameter)
fan_in = np.prod(weight.shape[1:])
he_std = gain / np.sqrt(fan_in) # He init
# Equalized learning rate and custom learning rate multiplier.
if use_wscale:
init_std = 1.0 / lrmul
runtime_coef = he_std * lrmul
else:
init_std = he_std / lrmul
runtime_coef = lrmul
# Init variable using He init.
weight.data.normal_(0, init_std)
# add scale hook
self.add_scale_hook('weight', new_name, runtime_coef)
def scale_bias(self, lrmul=1, new_name='_bias'):
if self.bias is None:
assert not hasattr(self, new_name)
# do not delete so we don't have to restore in forward
# del self.bias
self.register_parameter(new_name, None)
return
bias = self.bias
assert isinstance(bias, nn.Parameter)
# zero out
bias.data.zero_()
# add scale hook
self.add_scale_hook('bias', new_name, lrmul)
def add_scale_hook(self, name, new_name, coef):
param = getattr(self, name)
assert isinstance(param, nn.Parameter)
assert not hasattr(self, new_name)
delattr(self, name)
self.register_parameter(new_name, param)
# Note that the following line uses `m` rather than `self`, and thus
# doesn't maintaing the reference and allows for deep copying.
self.register_forward_pre_hook(lambda m, inp: setattr(m, name, getattr(m, new_name) * coef))
class ScaledParamLinear(nn.Linear, ScaledParamModule):
def __init__(self, *args, gain=np.sqrt(2), use_wscale=True, lrmul=1, **kwargs):
super().__init__(*args, **kwargs)
self.scale_weight(gain, use_wscale, lrmul)
self.scale_bias(lrmul)
def extra_repr(self):
return 'in_features={}, out_features={}, bias={}'.format(
self.in_features, self.out_features, self._bias is not None # use the _real param
)
class ScaledParamConv2d(nn.Conv2d, ScaledParamModule):
def __init__(self, *args, gain=np.sqrt(2), use_wscale=True, lrmul=1, **kwargs):
super().__init__(*args, **kwargs)
self.scale_weight(gain, use_wscale, lrmul)
self.scale_bias(lrmul)
def extra_repr(self):
s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'
', stride={stride}')
if self.padding != (0,) * len(self.padding):
s += ', padding={padding}'
if self.dilation != (1,) * len(self.dilation):
s += ', dilation={dilation}'
if self.output_padding != (0,) * len(self.output_padding):
s += ', output_padding={output_padding}'
if self.groups != 1:
s += ', groups={groups}'
if self._bias is None: # use the _real param
s += ', bias=False'
return s.format(**self.__dict__)
class UpConv2d(ScaledParamConv2d):
# Fuse Upsample 2x and Conv2d if desirable.
# NOTE [ Fusing Nearest Neighbor Upsampling and Conv2d to a ConvTranspose2d ]
#
# For exact match, we should flip the kernel along the spatial
# dimensions, e.g., with a `.flip(2, 3)`.
# This is because we will calculate the sum combinations in kernel
# and then apply convT with stride so that each input pixel hits the
# exact same kernel values as it would with upsample + conv, but
# now summed as a single value. In ConvT, kernel and input are in
# reversed space, in the sense that the top-left input pixel sees
# top-left kernel region in conv, but bottom-right in convT.
# However, the tf code doesn't do this and this is also a problem in
# tf, so to keep trained weights compatibility, we don't flip.
def __init__(self, in_res, in_channels, out_channels, kernel_size, padding=0,
bias=True, gain=np.sqrt(2), use_wscale=True, lrmul=1):
super().__init__(in_channels, out_channels, kernel_size, padding=padding, bias=bias,
gain=gain, use_wscale=use_wscale, lrmul=lrmul)
self.do_fuse = in_res * 2 >= 128
def forward(self, x):
if self.do_fuse:
w = F.pad(self.weight.transpose(0, 1), (1, 1, 1, 1))
w = w[:, :, 1:, 1:] + w[:, :, 1:, :-1] + w[:, :, :-1, 1:] + w[:, :, :-1, :-1]
return F.conv_transpose2d(x, w, self.bias, stride=(2, 2), padding=self.padding)
else:
return nn.Conv2d.forward(self, F.interpolate(x, scale_factor=2))
class Blur2d(nn.Module):
def __init__(self, kernel=[1, 2, 1], padding=1, normalize=True, flip=False, stride=1):
super().__init__()
self.stride = stride
self.padding = padding
# build kernel
kernel = torch.as_tensor(kernel, dtype=torch.get_default_dtype())
if kernel.dim() == 1:
kernel = kernel[:, None] * kernel
assert kernel.dim() == 2
if normalize:
kernel /= kernel.sum()
if flip:
kernel = kernel.flip(0, 1)
if kernel.numel() == 1 and kernel[0, 0].item() == 1:
# No-op => early exit.
self.no_conv = True
else:
self.no_conv = False
# prepare for conv2d
# use single channel (merge nc to batch dimension)
self.register_buffer('kernel', kernel.expand(1, 1, -1, -1).contiguous())
def forward(self, x):
if self.no_conv:
if self.stride == 1:
return x
else:
return x[:, :, ::self.stride, ::self.stride]
else:
b, nc, h, w = x.size()
y = F.conv2d(x.reshape(-1, 1, h, w), self.kernel, bias=None, stride=self.stride, padding=self.padding)
return y.view(b, nc, y.size(2), y.size(3))
class MappingG(nn.Module):
def __init__(self, z_dim=512, w_dim=512, dim_latent=512, n_layers=8,
nonlinearity=LeakyReLU, use_wscale=True,
use_class_labels=False, nlabels=1, embed_size=0, lrmul=0.01):
super().__init__()
self.z_dim = z_dim
self.w_dim = w_dim
self.dim_latent = dim_latent
assert n_layers >= 1
self.n_layers = n_layers
self.act = nonlinearity
scale_param_opt = dict(gain=self.act.gain, lrmul=lrmul, use_wscale=use_wscale)
self.use_class_labels = use_class_labels
if self.use_class_labels:
self.embedding = nn.Embedding(nlabels, embed_size)
dim = z_dim + embed_size if use_class_labels else z_dim
self.fcs = nn.ModuleList()
for i in range(n_layers):
self.fcs.append(
ScaledParamLinear(dim, dim_latent if i < (n_layers - 1) else w_dim, **scale_param_opt),
)
dim = dim_latent
def forward(self, z, y=None):
if self.use_class_labels:
yembed = self.embedding(y)
yembed = yembed / torch.norm(yembed, p=2, dim=1, keepdim=True)
z = torch.cat([z, yembed], dim=1)
# NB: this is not z.norm(p=2, dim=1, keepdim=True)!!!!
z = z * z.pow(2).mean(dim=1, keepdim=True).add_(1e-8).rsqrt()
for fc in self.fcs:
z = self.act(fc(z))
return z
def __repr__(self):
return '{}(z_dim={}, w_dim={}, dim_latent={}, n_layers={}, ...)'.format(
self.__class__.__name__, self.z_dim, self.w_dim, self.dim_latent, self.n_layers)
class SynthesisG(nn.Module):
class AddNoise(ScaledParamModule):
# `B` block + Noise in Fig1
def __init__(self, nc, res):
super().__init__()
self.res = res
self.weight = nn.Parameter(torch.zeros(nc, 1, 1, requires_grad=True))
self.bias = nn.Parameter(torch.zeros(nc, 1, 1, requires_grad=True))
self.scale_bias(lrmul=1)
def forward(self, x, noise=None):
if noise is None:
noise = torch.randn(x.size(0), 1, self.res, self.res, device=x.device, dtype=x.dtype)
return x + noise * self.weight + self.bias
class AffineStyle(nn.Module):
# `A` block + AdaIN in Fig1
def __init__(self, w_dim, nc):
super().__init__()
self.nc = nc
self.fc = ScaledParamLinear(w_dim, nc * 2, gain=1)
def forward(self, x, w):
normalized = F.instance_norm(x, weight=None, bias=None, eps=1e-8)
affine_params = self.fc(w).view(-1, 2, self.nc, 1, 1)
return normalized * (affine_params[:, 0].add_(1)) + affine_params[:, 1]
class Block(nn.Module):
def __init__(self, w_dim, in_res, in_nc, out_res, out_nc,
blur_filter=[1, 2, 1],
nonlinearity=LeakyReLU, use_wscale=True, lrmul=1,
skip_first_layer=False): # skip_first_layer skips the upsample & first conv, used for first block
super().__init__()
self.skip_first_layer = skip_first_layer
self.act = nonlinearity
scale_param_opt = dict(gain=self.act.gain, lrmul=lrmul, use_wscale=use_wscale)
# NB: the following (up)conv* layers have bias=False, because we
# assume that we are always using noise, and the bias is applied
# in noise* layers. This is still consistent with official tf
# code.
if not self.skip_first_layer:
self.upconv1 = UpConv2d(in_res, in_nc, out_nc, 3, padding=1, bias=False, **scale_param_opt)
assert len(blur_filter) % 2 == 1
self.blur1 = Blur2d(blur_filter, padding=(len(blur_filter) >> 1))
self.noise1 = SynthesisG.AddNoise(out_nc, out_res)
self.style1 = SynthesisG.AffineStyle(w_dim, out_nc)
self.conv2 = ScaledParamConv2d(out_nc, out_nc, 3, padding=1, bias=False, **scale_param_opt)
self.noise2 = SynthesisG.AddNoise(out_nc, out_res)
self.style2 = SynthesisG.AffineStyle(w_dim, out_nc)
def forward(self, x, ws, noises=(None, None)):
if not self.skip_first_layer:
x = self.blur1(self.upconv1(x))
x = self.noise1(x, noises[0])
x = self.act(x)
x = self.style1(x, ws[0])
x = self.conv2(x)
x = self.noise2(x, noises[1])
x = self.act(x)
x = self.style2(x, ws[1])
return x
def __init__(self, w_dim=512, image_out_nc=3, image_out_res=1024,
nc_base=8192, nc_decay=1.0, nc_max=512,
nonlinearity=LeakyReLU, use_wscale=True, lrmul=1):
super().__init__()
self.out_res = image_out_res
log_image_out_res = int(np.log2(image_out_res))
assert image_out_res == 2 ** log_image_out_res and image_out_res >= 4
# output nc of a block.
#
# log_res refers to the input to the block, which is immediately
# upsampled.
#
# In the first block, there is no upsample, and input is directly 4x4,
# but you should still treat as if it is upsampled from 2x2 and use
# log_res=1.
def get_out_nc(log_res):
return min(int(nc_base / 2 ** (log_res * nc_decay)), nc_max)
self.const = nn.Parameter(torch.ones(1, get_out_nc(1), 4, 4, requires_grad=True))
# start at 4x4
in_res = 2
in_nc = None # first shouldn't matter
for in_log_res in range(1, log_image_out_res):
out_res = in_res * 2
out_nc = get_out_nc(in_log_res)
b = SynthesisG.Block(
w_dim, in_res, in_nc, out_res, out_nc,
skip_first_layer=(in_log_res == 1),
nonlinearity=nonlinearity, use_wscale=use_wscale, lrmul=lrmul,
)
self.add_module('{res}x{res}'.format(res=out_res), b)
to_rgb = ScaledParamConv2d(out_nc, image_out_nc, 1, gain=1, use_wscale=use_wscale, lrmul=lrmul)
out_log_res = in_log_res + 1
self.add_module('{res}x{res}_to_rgb_lod{lod}'.format(
res=out_res, lod=(log_image_out_res - out_log_res)), to_rgb)
in_res = out_res
in_nc = out_nc
assert in_res == image_out_res
self.num_blocks = len(self.blocks)
self.num_layers = self.num_blocks * 2
@property
def blocks(self):
blocks = []
children_dict = {}
for name, module in self.named_children():
children_dict[name] = module
log_out_res = int(np.log2(self.out_res))
out_res = 4
for _ in range(1, log_out_res):
name = '{res}x{res}'.format(res=out_res)
module = children_dict[name]
blocks.append(module)
out_res = out_res * 2
return blocks
@property
def rgb_convs(self):
rgb_convs = []
children_dict = {}
for name, module in self.named_children():
children_dict[name] = module
log_out_res = int(np.log2(self.out_res))
out_res = 4
for in_log_res in range(1, log_out_res):
out_log_res = in_log_res + 1
name = '{res}x{res}_to_rgb_lod{lod}'.format(res=out_res, lod=(log_out_res - out_log_res))
module = children_dict[name]
rgb_convs.append(module)
out_res = out_res * 2
return rgb_convs
# allow taking in a list of W for style mixing
def forward(self, ws, lod=0, alpha=1, noises=None):
blocks = self.blocks
rgb_convs = self.rgb_convs
assert 0 <= lod < len(blocks)
stop_after = len(blocks) - lod - 1
num_layers = (stop_after + 1) * 2
if isinstance(ws, torch.Tensor) and ws.dim() == 3:
ws = ws.unbind(dim=1) # assuming its [batch x num_layer x w]
if not isinstance(ws, collections.abc.Sequence):
ws = [ws for _ in range(num_layers)]
if not isinstance(noises, collections.abc.Sequence):
noises = [noises for _ in range(num_layers)]
x = self.const.expand(ws[0].size(0), -1, -1, -1)
for i, b in enumerate(blocks):
block_extra_inp_indices = slice(i * 2, i * 2 + 2)
x = b(x, ws[block_extra_inp_indices], noises=noises[block_extra_inp_indices])
if i == stop_after - 1:
y = F.interpolate(x, scale_factor=2)
y = rgb_convs[stop_after - 1](y)
if i == stop_after:
x = rgb_convs[i](x)
return x if stop_after == 0 else (1 - alpha) * y + alpha * x
class G(nn.Module):
def __init__(self, z_dim=512, w_dim=512, out_nc=3, out_res=1024, use_class_labels=False,
w_avg_beta=0.995, # find moving average of w, in training
style_mixing_prob=0.995, # prob of applying style mixing, in training
truncation_psi=0.7, # mixing rate to w_avg for truncation, in eval
truncation_cutoff=8, # layer cutoff index index for truncation, in eval
nlabels=1, # number of classes (if using class labels)
embed_size=256, # embedding size for encoding class label information
nonlinearity=LeakyReLU, use_wscale=True, **kwargs):
super().__init__()
self.register_buffer('w_avg', torch.zeros(w_dim))
self.z_dim = z_dim
self.w_dim = w_dim
self.out_nc = out_nc
self.out_res = out_res
self.w_avg_beta = w_avg_beta
self.style_mixing_prob = style_mixing_prob
self.truncation_psi = truncation_psi
self.truncation_cutoff = truncation_cutoff
self.mapping = MappingG(z_dim, w_dim, nonlinearity=nonlinearity,
use_wscale=use_wscale,
use_class_labels=use_class_labels,
nlabels=nlabels, embed_size=embed_size)
self.synthesis = SynthesisG(w_dim, out_nc, out_res, nonlinearity=nonlinearity, use_wscale=use_wscale)
def forward(self, z, y=None, lod=0, alpha=1, w=None, noises=None, get_w=False,
w_avg_beta=None, style_mixing_prob=None,
truncation_psi=None, truncation_cutoff=None):
# really is the total number of layers for the synthesis network
total_num_layers = self.synthesis.num_layers
forward_num_layers = total_num_layers - lod * 2
if w is None:
assert z is not None and z.dim() == 2 and z.size(1) == self.z_dim
w = self.mapping(z, y)
else:
assert w.dim() == 2 and w.size(1) == self.w_dim
if get_w:
mapping_output_w = w.clone()
ws = [w for _ in range(total_num_layers)]
if self.training:
# update moving average
if w_avg_beta is None:
w_avg_beta = self.w_avg_beta
if w_avg_beta != 1:
with torch.no_grad():
torch.lerp(w.mean(0), self.w_avg, self.w_avg_beta, out=self.w_avg)
# style mixing
if style_mixing_prob is None:
style_mixing_prob = self.style_mixing_prob
if style_mixing_prob > 0 and torch.rand((), device='cpu').item() < style_mixing_prob:
w2 = self.mapping(torch.randn_like(z), y)
cutoff = int(torch.randint(low=1, high=forward_num_layers, size=(), device='cpu').item())
# w for < cutoff; w2 for >= cutoff
ws = ws[:cutoff] + [w2 for _ in range(forward_num_layers - cutoff)]
else:
# truncation
if truncation_psi is None:
truncation_psi = self.truncation_psi
if truncation_cutoff is None:
truncation_cutoff = self.truncation_cutoff
# truncate for < cutoff
if truncation_cutoff > 0 and truncation_psi != 1:
expanded_avg_w = self.w_avg.expand_as(ws[0])
# in eval part, current code implies that ws is a list of the same w
# tensor repeated many times since there is no style mixing, but
# let's be general and detect before optimizing for that.
if all(_w is w for _w in ws):
truncate_w = torch.lerp(expanded_avg_w, w, truncation_psi)
ws = [truncate_w for _ in range(truncation_cutoff)] + ws[:(forward_num_layers - truncation_cutoff)]
else:
for i in range(truncation_cutoff):
# use out-of-place because these ws may be references to the
# same tensor
ws[i] = torch.lerp(expanded_avg_w, w[i], truncation_psi)
ims = self.synthesis(ws, lod=lod, noises=noises, alpha=alpha)
if get_w:
return mapping_output_w, ims
else:
return ims
def __repr__(self):
return '{}(z_dim={}, w_dim={}, out_nc={}, out_res={}, ...)'.format(
self.__class__.__name__, self.z_dim, self.w_dim, self.out_nc, self.out_res)
def convert_tf_weights_to_state_dict(self, tf_net, device=torch.device('cpu')):
# full of hacks
state_dict = {}
def raise_unexpected(tf_k, v):
raise RuntimeError("Unexpected key '{}' with shape: {}".format(tf_k, v.size()))
def transform_conv_w(v):
# tf: [ k1, k2, nc_in, nc_out ]
# pt: [ nc_out, nc_in, k1, k2 ]
return v.permute(3, 2, 0, 1)
def transform_fc_w(v):
# tf: [ fan_in, fan_out ]
# pt: [ fan_out, fan_in ]
return v.t()
def sub_synthesis(k, tf_k, v):
k = k.replace('G_synthesis.', 'synthesis.')
def replace_tail_if_match(pattern, new):
nonlocal k
if k.endswith(pattern):
k = k[:-len(pattern)] + new
return True
return False
# deal with the first block
if k == 'synthesis.4x4.Const.const':
return 'synthesis.const', v
elif k.startswith('synthesis.4x4.'):
if 'synthesis.4x4.Const' in k:
k = k.replace('synthesis.4x4.Const', 'synthesis.4x4.Conv0_up')
elif 'synthesis.4x4.Conv' in k:
k = k.replace('synthesis.4x4.Conv', 'synthesis.4x4.Conv1')
else:
raise_unexpected(tf_k, v)
if replace_tail_if_match('.Conv0_up.weight', '.upconv1._weight'): # noqa: E241, E202
return k, transform_conv_w(v)
if replace_tail_if_match('.Conv0_up.Noise.weight', '.noise1.weight'): # noqa: E241, E202
return k, v.view(-1, 1, 1)
if replace_tail_if_match('.Conv0_up.bias', '.noise1._bias'): # noqa: E241, E202
return k, v.view(-1, 1, 1)
if replace_tail_if_match('.Conv0_up.StyleMod.weight', '.style1.fc._weight'): # noqa: E241, E202
return k, transform_fc_w(v)
if replace_tail_if_match('.Conv0_up.StyleMod.bias', '.style1.fc._bias'): # noqa: E241, E202
return k, v
if 'Conv0_up' in k:
raise_unexpected(tf_k, v)
if replace_tail_if_match('.Conv1.weight', '.conv2._weight'): # noqa: E241, E202
return k, transform_conv_w(v)
if replace_tail_if_match('.Conv1.Noise.weight', '.noise2.weight'): # noqa: E241, E202
return k, v.view(-1, 1, 1)
if replace_tail_if_match('.Conv1.bias', '.noise2._bias'): # noqa: E241, E202
return k, v.view(-1, 1, 1)
if replace_tail_if_match('.Conv1.StyleMod.weight', '.style2.fc._weight'): # noqa: E241, E202
return k, transform_fc_w(v)
if replace_tail_if_match('.Conv1.StyleMod.bias', '.style2.fc._bias'): # noqa: E241, E202
return k, v
if 'Conv1' in k:
raise_unexpected(tf_k, v)
m = re.match(r'^synthesis\.ToRGB_lod(\d+)\.(weight|bias)$', k)
if m:
lod = int(m.group(1))
k = 'synthesis.{res}x{res}_to_rgb_lod{lod}._{name}'.format(
res=int(self.out_res / 2 ** lod), lod=lod, name=m.group(2))
if m.group(2) == 'weight':
v = transform_conv_w(v)
return k, v
raise_unexpected(tf_k, v)
for tf_k, tf_v in tf_net.vars.items():
assert '.' not in tf_k
k = tf_k.replace('/', '.')
v = torch.as_tensor(tf_v.eval())
if k in {'lod', 'G_synthesis.lod'} or k.startswith('G_synthesis.noise'):
# no input buffer
continue
elif k == 'dlatent_avg':
k = 'w_avg'
elif k.startswith('G_synthesis.'):
k, v = sub_synthesis(k, tf_k, v)
elif k.startswith('G_mapping.'):
m = re.match(r'^G_mapping\.Dense(\d+)\.(weight|bias)$', k)
if not m:
raise_unexpected(tf_k, v)
k = 'mapping.fcs.{}._{}'.format(m.group(1), m.group(2))
if m.group(2) == 'weight':
v = transform_fc_w(v)
else:
raise_unexpected(tf_k, v)
state_dict[k] = v
# tf state dict doesn't have the blur kernels, but pytorch wants to see
# them
for k, v in self.state_dict().items():
if re.match(r'^synthesis\.\d+x\d+\.blur1\.kernel$', k):
state_dict[k] = v.detach()
# device & contiguity
for k in state_dict:
state_dict[k] = state_dict[k].to(device).contiguous()
return state_dict
@property
def dim_z(self):
return self.z_dim
class D(nn.Module):
# Discriminator from https://arxiv.org/pdf/1710.10196.pdf
class MinibatchStddev(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, group_size=4):
'''
Implements the MinibatchStddevLayer from https://arxiv.org/pdf/1710.10196.pdf
group size: int, must divide the batch size
in: BS x C x H x W
out: BS x (C + 1) x H x W
'''
s = x.size()
group_size = min(group_size, s[0])
y = x.view(group_size, -1, s[1], s[2], s[3])
y = y - torch.mean(y, 0, keepdim=True)
y = (y**2).mean(0, keepdim=False)
y = torch.sqrt(y + 10**-8)
# y = y.mean((1, 2, 3), keepdim=True).expand_as(x)
y = y.mean((1, 2, 3), keepdim=True).repeat(group_size, 1, s[2], s[3])
return torch.cat([x, y], 1)
class ConvBlock(nn.Module):
def __init__(self, in_nc, out_nc, last_layer=False, nonlinearity=LeakyReLU, use_wscale=True, lrmul=1.0):
super().__init__()
self.act = nonlinearity
self.last_layer = last_layer
scale_param_opt = dict(gain=self.act.gain, lrmul=lrmul, use_wscale=use_wscale)
if not self.last_layer:
self.blur = Blur2d(kernel=[1, 2, 1], normalize=True, stride=1, padding=1)
self.pool = Blur2d(kernel=[0.5, 0.5], normalize=False, stride=2, padding=0)
self.conv1 = ScaledParamConv2d(in_nc, in_nc, 3, padding=1, bias=True, **scale_param_opt)
self.conv2 = ScaledParamConv2d(in_nc, out_nc, 3, padding=1, bias=True, **scale_param_opt)
else:
self.minibatch_stddev = D.MinibatchStddev()
self.conv1 = ScaledParamConv2d(in_nc + 1, in_nc, 3, padding=1, bias=True, **scale_param_opt)
self.conv2 = ScaledParamLinear(in_nc * 16, out_nc, bias=True, **scale_param_opt)
def forward(self, x):
if self.last_layer:
x = self.minibatch_stddev(x)
out = self.act(self.conv1(x))
if self.last_layer:
out = out.view(out.size(0), -1)
else:
out = self.blur(out)
# out = self.act(self.conv2(out)) #possible change in order
out = self.conv2(out)
if not self.last_layer:
out = self.pool(out)
return out
def __init__(self, image_in_nc=3, out_res=1024,
nc_base=16, nc_decay=1.0, nc_max=512,
nonlinearity=LeakyReLU, use_wscale=True, use_class_labels=False, nlabels=None, lrmul=1, **kwargs):
super().__init__()
self.out_res = out_res
log_out_res = int(np.log2(out_res))
assert out_res == 2 ** log_out_res and out_res >= 4
# output nc of a block.
#
# log_res refers to the input to the block, which is immediately
# upsampled.
#
# In the first block, there is no upsample, and input is directly 4x4,
# but you should still treat as if it is upsampled from 2x2 and use
# log_res=1.
def get_in_nc(log_res):
return min(int(nc_base * 2**(log_res - 1)), nc_max)
def get_out_nc(log_res):
return min(int(nc_base * 2**log_res), nc_max)
# plain list
# we will register them using more meaningful names, mainly to be easier
# loading tf weights, which are stored in namespaces alike 4x4, 16x16,
# etc.
# start at 4x4
in_res = 2
# first shouldn't matter
for in_log_res in reversed(range(1, log_out_res)):
out_res = in_res * 2
in_nc = get_in_nc(in_log_res)
out_nc = get_out_nc(in_log_res)
from_rgb = ScaledParamConv2d(image_in_nc, in_nc, kernel_size=1, gain=nonlinearity.gain,
bias=True, use_wscale=use_wscale, lrmul=lrmul)
b = D.ConvBlock(in_nc, out_nc, last_layer=(in_log_res == log_out_res - 1),
nonlinearity=nonlinearity, use_wscale=use_wscale, lrmul=lrmul)
self.add_module('{res}x{res}'.format(res=out_res), b)
out_log_res = in_log_res + 1
self.add_module('{res}x{res}_from_rgb_lod{lod}'.format(
res=out_res, lod=(out_log_res - 2)), from_rgb)
in_res = out_res
assert in_res == out_res
self.num_blocks = len(self.blocks)
self.num_layers = self.num_blocks * 2
self.use_class_labels = use_class_labels
self.avgpool = Blur2d(kernel=[0.5, 0.5], normalize=False, stride=2, padding=0)
if self.use_class_labels:
self.fc = ScaledParamLinear(min(get_out_nc(log_out_res - 1), nc_max), nlabels,
gain=1.0, bias=True, use_wscale=True, lrmul=lrmul)
else:
self.fc = ScaledParamLinear(min(get_out_nc(log_out_res - 1), nc_max), 1,
gain=1.0, bias=True, use_wscale=True, lrmul=lrmul)
@property
def blocks(self):
blocks = []
children_dict = {}
for name, module in self.named_children():
children_dict[name] = module
log_out_res = int(np.log2(self.out_res))
out_res = 4
for _ in reversed(range(1, log_out_res)):
name = '{res}x{res}'.format(res=out_res)
module = children_dict[name]
blocks.append(module)
out_res = out_res * 2
return blocks
@property
def rgb_convs(self):
rgb_convs = []
children_dict = {}
for name, module in self.named_children():
children_dict[name] = module
log_out_res = int(np.log2(self.out_res))
out_res = 4
for in_log_res in reversed(range(1, log_out_res)):
out_log_res = in_log_res + 1
name = '{res}x{res}_from_rgb_lod{lod}'.format(res=out_res, lod=(out_log_res - 2))
module = children_dict[name]
rgb_convs.append(module)
out_res = out_res * 2
return rgb_convs
def forward(self, x, labels=None, lod=0, alpha=1):
blocks = self.blocks
rgb_convs = self.rgb_convs
assert 0 <= lod < len(blocks)
stop_after = len(blocks) - lod - 1
if stop_after != 0:
y = self.avgpool(x)
y = rgb_convs[stop_after - 1](y)
x = rgb_convs[stop_after](x)
x = blocks[stop_after](x)
# x = alpha * x + (1 - alpha) * y
x = torch.lerp(y, x, alpha)
stop_after -= 1
else:
x = rgb_convs[stop_after](x)
for i, b in reversed(list(enumerate(blocks))):
if i <= stop_after:
x = b(x)
x = x.view(x.size(0), -1)
out = self.fc(x)
if self.use_class_labels:
if labels.dim() != 2:
labels = labels.unsqueeze(1)
out = out.gather(1, labels)
# index = Variable(torch.LongTensor(range(out.size(0))))
# if labels.is_cuda:
# index = index.cuda()
# out = out[index, labels]
return out
def convert_tf_weights_to_state_dict(self, tf_net, device=torch.device('cpu')):
# full of hacks
state_dict = {}
def raise_unexpected(tf_k, v):
raise RuntimeError("Unexpected key '{}' with shape: {}".format(tf_k, v.size()))
def transform_conv_w(v):
# tf: [ k1, k2, nc_in, nc_out ]
# pt: [ nc_out, nc_in, k1, k2 ]
return v.permute(3, 2, 0, 1)
def transform_fc_w(v):
# tf: [ fan_in, fan_out ]
# pt: [ fan_out, fan_in ]
return v.t()
def from_rgb(k, tf_k, v):
m = re.match(r'^FromRGB_lod(\d+)\.(weight|bias)$', k)
if m:
lod = int(m.group(1))
k = '{res}x{res}_from_rgb_lod{lod}._{name}'.format(
res=int(self.out_res / 2 ** lod), lod=lod, name=m.group(2))
if m.group(2) == 'weight':
v = transform_conv_w(v)
else:
v = v.view(-1)
return k, v
def sub_synthesis(k, tf_k, v):
def replace_tail_if_match(pattern, new):
nonlocal k
if k.endswith(pattern):
k = k[:-len(pattern)] + new
return True
return False
if k.startswith('4x4.'):
if '4x4.Conv' in k:
k = k.replace('4x4.Conv', '4x4.Conv0')
elif '4x4.Dense0' in k:
if k == '4x4.Dense0.weight':
return '4x4.conv2._weight', transform_fc_w(v)
if k == '4x4.Dense0.bias':
return '4x4.conv2._bias', v.view(-1)
raise_unexpected(tf_k, v)
elif '4x4.Dense1' in k:
k = k.replace('4x4.Dense1', 'fc')
if k.endswith('weight'):
k = k.replace('weight', '_weight')
return k, transform_fc_w(v)
if k.endswith('bias'):
k = k.replace('bias', '_bias')
return k, v
raise_unexpected(tf_k, v)
else:
raise_unexpected(tf_k, v)
if replace_tail_if_match('.Conv0.weight', '.conv1._weight'): # noqa: E241, E202
return k, transform_conv_w(v)
if replace_tail_if_match('.Conv0.bias', '.conv1._bias'): # noqa: E241, E202
return k, v.view(-1)
if 'Conv0' in k:
raise_unexpected(tf_k, v)
if replace_tail_if_match('.Conv1_down.weight', '.conv2._weight'): # noqa: E241, E202
return k, transform_conv_w(v)
if replace_tail_if_match('.Conv1_down.bias', '.conv2._bias'): # noqa: E241, E202
return k, v.view(-1)
if 'Conv1' in k:
raise_unexpected(tf_k, v)
raise_unexpected(tf_k, v)
for tf_k, tf_v in tf_net.vars.items():
assert '.' not in tf_k
k = tf_k.replace('/', '.')
v = torch.as_tensor(tf_v.eval())
if k in {'lod'}:
# no input buffer
continue
elif k.startswith('FromRGB'):
k, v = from_rgb(k, tf_k, v)
elif 'weight' in k or 'bias' in k:
k, v = sub_synthesis(k, tf_k, v)
else:
raise_unexpected(tf_k, v)
state_dict[k] = v
# tf state dict doesn't have the blur kernels, but pytorch wants to see
# them
for k, v in self.state_dict().items():
if re.match(r'\d+x\d+\.blur\.kernel$', k):
state_dict[k] = v.detach()
if re.match(r'\d+x\d+\.pool\.kernel$', k):
state_dict[k] = v.detach()
if k == 'avgpool.kernel':
state_dict[k] = v.detach()
# device & contiguity
for k in state_dict:
state_dict[k] = state_dict[k].to(device).contiguous()
return state_dict
|
[
"torch.sqrt",
"torch.nn.Embedding",
"torch.cat",
"collections.defaultdict",
"torch.nn.functional.leaky_relu",
"torch.device",
"torch.no_grad",
"os.path.join",
"numpy.prod",
"os.path.dirname",
"torch.lerp",
"torch.zeros",
"torch.hub.load_state_dict_from_url",
"torch.mean",
"torch.randint",
"torch.randn_like",
"torch.nn.ModuleList",
"numpy.log2",
"torch.norm",
"re.match",
"torch.rand",
"torch.nn.functional.instance_norm",
"torch.nn.functional.conv_transpose2d",
"torch.nn.functional.interpolate",
"torch.get_default_dtype",
"numpy.sqrt"
] |
[((428, 465), 'collections.defaultdict', 'collections.defaultdict', (['(lambda : 512)'], {}), '(lambda : 512)\n', (451, 465), False, 'import collections\n'), ((790, 815), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (805, 815), False, 'import os\n'), ((2324, 2334), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (2331, 2334), True, 'import numpy as np\n'), ((2401, 2411), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (2408, 2411), True, 'import numpy as np\n'), ((1786, 1825), 'torch.hub.load_state_dict_from_url', 'torch.hub.load_state_dict_from_url', (['url'], {}), '(url)\n', (1820, 1825), False, 'import torch\n'), ((2482, 2534), 'torch.nn.functional.leaky_relu', 'F.leaky_relu', (['x'], {'negative_slope': '(0.2)', 'inplace': 'inplace'}), '(x, negative_slope=0.2, inplace=inplace)\n', (2494, 2534), True, 'import torch.nn.functional as F\n'), ((3087, 3097), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (3094, 3097), True, 'import numpy as np\n'), ((3241, 3266), 'numpy.prod', 'np.prod', (['weight.shape[1:]'], {}), '(weight.shape[1:])\n', (3248, 3266), True, 'import numpy as np\n'), ((4836, 4846), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4843, 4846), True, 'import numpy as np\n'), ((5299, 5309), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (5306, 5309), True, 'import numpy as np\n'), ((7067, 7077), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7074, 7077), True, 'import numpy as np\n'), ((9766, 9781), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (9779, 9781), True, 'import torch.nn as nn\n'), ((22423, 22442), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (22435, 22442), False, 'import torch\n'), ((34470, 34489), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (34482, 34489), False, 'import torch\n'), ((946, 1006), 'os.path.join', 'os.path.join', (['root_url', '"""celeba_hq_1024x1024_G-c8acef81.pth"""'], {}), "(root_url, 'celeba_hq_1024x1024_G-c8acef81.pth')\n", (958, 1006), False, 'import os\n'), ((1074, 1130), 'os.path.join', 'os.path.join', (['root_url', '"""ff_hq_1024x1024_G-21a7044d.pth"""'], {}), "(root_url, 'ff_hq_1024x1024_G-21a7044d.pth')\n", (1086, 1130), False, 'import os\n'), ((1203, 1264), 'os.path.join', 'os.path.join', (['root_url', '"""lsun_bedroom_256x256_G-da907d98.pth"""'], {}), "(root_url, 'lsun_bedroom_256x256_G-da907d98.pth')\n", (1215, 1264), False, 'import os\n'), ((1334, 1391), 'os.path.join', 'os.path.join', (['root_url', '"""lsun_car_512x384_G-d2188b0a.pth"""'], {}), "(root_url, 'lsun_car_512x384_G-d2188b0a.pth')\n", (1346, 1391), False, 'import os\n'), ((1461, 1518), 'os.path.join', 'os.path.join', (['root_url', '"""lsun_cat_256x256_G-384e9e73.pth"""'], {}), "(root_url, 'lsun_cat_256x256_G-384e9e73.pth')\n", (1473, 1518), False, 'import os\n'), ((3291, 3306), 'numpy.sqrt', 'np.sqrt', (['fan_in'], {}), '(fan_in)\n', (3298, 3306), True, 'import numpy as np\n'), ((7538, 7610), 'torch.nn.functional.conv_transpose2d', 'F.conv_transpose2d', (['x', 'w', 'self.bias'], {'stride': '(2, 2)', 'padding': 'self.padding'}), '(x, w, self.bias, stride=(2, 2), padding=self.padding)\n', (7556, 7610), True, 'import torch.nn.functional as F\n'), ((9647, 9680), 'torch.nn.Embedding', 'nn.Embedding', (['nlabels', 'embed_size'], {}), '(nlabels, embed_size)\n', (9659, 9680), True, 'import torch.nn as nn\n'), ((10191, 10220), 'torch.cat', 'torch.cat', (['[z, yembed]'], {'dim': '(1)'}), '([z, yembed], dim=1)\n', (10200, 10220), False, 'import torch\n'), ((11548, 11601), 'torch.nn.functional.instance_norm', 'F.instance_norm', (['x'], {'weight': 'None', 'bias': 'None', 'eps': '(1e-08)'}), '(x, weight=None, bias=None, eps=1e-08)\n', (11563, 11601), True, 'import torch.nn.functional as F\n'), ((13904, 13926), 'numpy.log2', 'np.log2', (['image_out_res'], {}), '(image_out_res)\n', (13911, 13926), True, 'import numpy as np\n'), ((15731, 15752), 'numpy.log2', 'np.log2', (['self.out_res'], {}), '(self.out_res)\n', (15738, 15752), True, 'import numpy as np\n'), ((16208, 16229), 'numpy.log2', 'np.log2', (['self.out_res'], {}), '(self.out_res)\n', (16215, 16229), True, 'import numpy as np\n'), ((18615, 18633), 'torch.zeros', 'torch.zeros', (['w_dim'], {}), '(w_dim)\n', (18626, 18633), False, 'import torch\n'), ((25326, 25386), 're.match', 're.match', (['"""^synthesis\\\\.ToRGB_lod(\\\\d+)\\\\.(weight|bias)$"""', 'k'], {}), "('^synthesis\\\\.ToRGB_lod(\\\\d+)\\\\.(weight|bias)$', k)\n", (25334, 25386), False, 'import re\n'), ((26828, 26883), 're.match', 're.match', (['"""^synthesis\\\\.\\\\d+x\\\\d+\\\\.blur1\\\\.kernel$"""', 'k'], {}), "('^synthesis\\\\.\\\\d+x\\\\d+\\\\.blur1\\\\.kernel$', k)\n", (26836, 26883), False, 'import re\n'), ((27855, 27879), 'torch.sqrt', 'torch.sqrt', (['(y + 10 ** -8)'], {}), '(y + 10 ** -8)\n', (27865, 27879), False, 'import torch\n'), ((28042, 28062), 'torch.cat', 'torch.cat', (['[x, y]', '(1)'], {}), '([x, y], 1)\n', (28051, 28062), False, 'import torch\n'), ((29917, 29933), 'numpy.log2', 'np.log2', (['out_res'], {}), '(out_res)\n', (29924, 29933), True, 'import numpy as np\n'), ((32466, 32487), 'numpy.log2', 'np.log2', (['self.out_res'], {}), '(self.out_res)\n', (32473, 32487), True, 'import numpy as np\n'), ((32954, 32975), 'numpy.log2', 'np.log2', (['self.out_res'], {}), '(self.out_res)\n', (32961, 32975), True, 'import numpy as np\n'), ((33778, 33801), 'torch.lerp', 'torch.lerp', (['y', 'x', 'alpha'], {}), '(y, x, alpha)\n', (33788, 33801), False, 'import torch\n'), ((35019, 35069), 're.match', 're.match', (['"""^FromRGB_lod(\\\\d+)\\\\.(weight|bias)$"""', 'k'], {}), "('^FromRGB_lod(\\\\d+)\\\\.(weight|bias)$', k)\n", (35027, 35069), False, 'import re\n'), ((38074, 38115), 're.match', 're.match', (['"""\\\\d+x\\\\d+\\\\.blur\\\\.kernel$"""', 'k'], {}), "('\\\\d+x\\\\d+\\\\.blur\\\\.kernel$', k)\n", (38082, 38115), False, 'import re\n'), ((38172, 38213), 're.match', 're.match', (['"""\\\\d+x\\\\d+\\\\.pool\\\\.kernel$"""', 'k'], {}), "('\\\\d+x\\\\d+\\\\.pool\\\\.kernel$', k)\n", (38180, 38213), False, 'import re\n'), ((7668, 7700), 'torch.nn.functional.interpolate', 'F.interpolate', (['x'], {'scale_factor': '(2)'}), '(x, scale_factor=2)\n', (7681, 7700), True, 'import torch.nn.functional as F\n'), ((7979, 8004), 'torch.get_default_dtype', 'torch.get_default_dtype', ([], {}), '()\n', (8002, 8004), False, 'import torch\n'), ((10130, 10174), 'torch.norm', 'torch.norm', (['yembed'], {'p': '(2)', 'dim': '(1)', 'keepdim': '(True)'}), '(yembed, p=2, dim=1, keepdim=True)\n', (10140, 10174), False, 'import torch\n'), ((10870, 10911), 'torch.zeros', 'torch.zeros', (['nc', '(1)', '(1)'], {'requires_grad': '(True)'}), '(nc, 1, 1, requires_grad=True)\n', (10881, 10911), False, 'import torch\n'), ((10950, 10991), 'torch.zeros', 'torch.zeros', (['nc', '(1)', '(1)'], {'requires_grad': '(True)'}), '(nc, 1, 1, requires_grad=True)\n', (10961, 10991), False, 'import torch\n'), ((17543, 17575), 'torch.nn.functional.interpolate', 'F.interpolate', (['x'], {'scale_factor': '(2)'}), '(x, scale_factor=2)\n', (17556, 17575), True, 'import torch.nn.functional as F\n'), ((27762, 27792), 'torch.mean', 'torch.mean', (['y', '(0)'], {'keepdim': '(True)'}), '(y, 0, keepdim=True)\n', (27772, 27792), False, 'import torch\n'), ((20213, 20228), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (20226, 20228), False, 'import torch\n'), ((20578, 20597), 'torch.randn_like', 'torch.randn_like', (['z'], {}), '(z)\n', (20594, 20597), False, 'import torch\n'), ((21556, 21601), 'torch.lerp', 'torch.lerp', (['expanded_avg_w', 'w', 'truncation_psi'], {}), '(expanded_avg_w, w, truncation_psi)\n', (21566, 21601), False, 'import torch\n'), ((21954, 22002), 'torch.lerp', 'torch.lerp', (['expanded_avg_w', 'w[i]', 'truncation_psi'], {}), '(expanded_avg_w, w[i], truncation_psi)\n', (21964, 22002), False, 'import torch\n'), ((20487, 20515), 'torch.rand', 'torch.rand', (['()'], {'device': '"""cpu"""'}), "((), device='cpu')\n", (20497, 20515), False, 'import torch\n'), ((20631, 20699), 'torch.randint', 'torch.randint', ([], {'low': '(1)', 'high': 'forward_num_layers', 'size': '()', 'device': '"""cpu"""'}), "(low=1, high=forward_num_layers, size=(), device='cpu')\n", (20644, 20699), False, 'import torch\n'), ((26293, 26349), 're.match', 're.match', (['"""^G_mapping\\\\.Dense(\\\\d+)\\\\.(weight|bias)$"""', 'k'], {}), "('^G_mapping\\\\.Dense(\\\\d+)\\\\.(weight|bias)$', k)\n", (26301, 26349), False, 'import re\n')]
|
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.
# Lint as: python3
"""Tests for supcon.classification_head."""
from absl.testing import parameterized
import numpy as np
import tensorflow.compat.v1 as tf
from supcon import classification_head
class ClassificationHeadTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
('rank_1', 1),
('rank_4', 4),
('rank_8', 8),
)
def testIncorrectRank(self, rank):
inputs = tf.compat.v1.placeholder(tf.float32, shape=[10] * rank)
with self.assertRaisesRegex(ValueError, 'is expected to have rank 2'):
classifier = classification_head.ClassificationHead(num_classes=10)
classifier(inputs)
@parameterized.named_parameters(
('float32', tf.float32),
('float64', tf.float64),
('float16', tf.float16),
)
def testConstructClassificationHead(self, dtype):
batch_size = 3
num_classes = 10
input_shape = [batch_size, 4]
expected_output_shape = [batch_size, num_classes]
inputs = tf.random.uniform(input_shape, seed=1, dtype=dtype)
classifier = classification_head.ClassificationHead(num_classes=num_classes)
output = classifier(inputs)
self.assertListEqual(expected_output_shape, output.shape.as_list())
self.assertEqual(inputs.dtype, output.dtype)
def testGradient(self):
inputs = tf.random.uniform((3, 4), dtype=tf.float64, seed=1)
classifier = classification_head.ClassificationHead(num_classes=10)
output = classifier(inputs)
gradient = tf.gradients(output, inputs)
self.assertIsNotNone(gradient)
def testCreateVariables(self):
inputs = tf.random.uniform((3, 4), dtype=tf.float64, seed=1)
classifier = classification_head.ClassificationHead(num_classes=10)
classifier(inputs)
self.assertLen(
[var for var in tf.trainable_variables() if 'kernel' in var.name], 1)
self.assertLen(
[var for var in tf.trainable_variables() if 'bias' in var.name], 1)
def testInputOutput(self):
batch_size = 3
num_classes = 10
expected_output_shape = (batch_size, num_classes)
inputs = tf.random.uniform((batch_size, 4), dtype=tf.float64, seed=1)
classifier = classification_head.ClassificationHead(num_classes=num_classes)
output_tensor = classifier(inputs)
with self.cached_session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
outputs = sess.run(output_tensor)
# Make sure that there are no NaNs
self.assertFalse(np.isnan(outputs).any())
self.assertEqual(outputs.shape, expected_output_shape)
if __name__ == '__main__':
tf.test.main()
|
[
"supcon.classification_head.ClassificationHead",
"tensorflow.compat.v1.random.uniform",
"numpy.isnan",
"tensorflow.compat.v1.test.main",
"tensorflow.compat.v1.gradients",
"absl.testing.parameterized.named_parameters",
"tensorflow.compat.v1.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.trainable_variables",
"tensorflow.compat.v1.compat.v1.placeholder"
] |
[((882, 957), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["('rank_1', 1)", "('rank_4', 4)", "('rank_8', 8)"], {}), "(('rank_1', 1), ('rank_4', 4), ('rank_8', 8))\n", (912, 957), False, 'from absl.testing import parameterized\n'), ((1265, 1375), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["('float32', tf.float32)", "('float64', tf.float64)", "('float16', tf.float16)"], {}), "(('float32', tf.float32), ('float64', tf.\n float64), ('float16', tf.float16))\n", (1295, 1375), False, 'from absl.testing import parameterized\n'), ((3175, 3189), 'tensorflow.compat.v1.test.main', 'tf.test.main', ([], {}), '()\n', (3187, 3189), True, 'import tensorflow.compat.v1 as tf\n'), ((1031, 1086), 'tensorflow.compat.v1.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32'], {'shape': '([10] * rank)'}), '(tf.float32, shape=[10] * rank)\n', (1055, 1086), True, 'import tensorflow.compat.v1 as tf\n'), ((1587, 1638), 'tensorflow.compat.v1.random.uniform', 'tf.random.uniform', (['input_shape'], {'seed': '(1)', 'dtype': 'dtype'}), '(input_shape, seed=1, dtype=dtype)\n', (1604, 1638), True, 'import tensorflow.compat.v1 as tf\n'), ((1656, 1719), 'supcon.classification_head.ClassificationHead', 'classification_head.ClassificationHead', ([], {'num_classes': 'num_classes'}), '(num_classes=num_classes)\n', (1694, 1719), False, 'from supcon import classification_head\n'), ((1913, 1964), 'tensorflow.compat.v1.random.uniform', 'tf.random.uniform', (['(3, 4)'], {'dtype': 'tf.float64', 'seed': '(1)'}), '((3, 4), dtype=tf.float64, seed=1)\n', (1930, 1964), True, 'import tensorflow.compat.v1 as tf\n'), ((1982, 2036), 'supcon.classification_head.ClassificationHead', 'classification_head.ClassificationHead', ([], {'num_classes': '(10)'}), '(num_classes=10)\n', (2020, 2036), False, 'from supcon import classification_head\n'), ((2084, 2112), 'tensorflow.compat.v1.gradients', 'tf.gradients', (['output', 'inputs'], {}), '(output, inputs)\n', (2096, 2112), True, 'import tensorflow.compat.v1 as tf\n'), ((2195, 2246), 'tensorflow.compat.v1.random.uniform', 'tf.random.uniform', (['(3, 4)'], {'dtype': 'tf.float64', 'seed': '(1)'}), '((3, 4), dtype=tf.float64, seed=1)\n', (2212, 2246), True, 'import tensorflow.compat.v1 as tf\n'), ((2264, 2318), 'supcon.classification_head.ClassificationHead', 'classification_head.ClassificationHead', ([], {'num_classes': '(10)'}), '(num_classes=10)\n', (2302, 2318), False, 'from supcon import classification_head\n'), ((2673, 2733), 'tensorflow.compat.v1.random.uniform', 'tf.random.uniform', (['(batch_size, 4)'], {'dtype': 'tf.float64', 'seed': '(1)'}), '((batch_size, 4), dtype=tf.float64, seed=1)\n', (2690, 2733), True, 'import tensorflow.compat.v1 as tf\n'), ((2751, 2814), 'supcon.classification_head.ClassificationHead', 'classification_head.ClassificationHead', ([], {'num_classes': 'num_classes'}), '(num_classes=num_classes)\n', (2789, 2814), False, 'from supcon import classification_head\n'), ((1181, 1235), 'supcon.classification_head.ClassificationHead', 'classification_head.ClassificationHead', ([], {'num_classes': '(10)'}), '(num_classes=10)\n', (1219, 1235), False, 'from supcon import classification_head\n'), ((2909, 2952), 'tensorflow.compat.v1.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (2950, 2952), True, 'import tensorflow.compat.v1 as tf\n'), ((2386, 2410), 'tensorflow.compat.v1.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (2408, 2410), True, 'import tensorflow.compat.v1 as tf\n'), ((2484, 2508), 'tensorflow.compat.v1.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (2506, 2508), True, 'import tensorflow.compat.v1 as tf\n'), ((3058, 3075), 'numpy.isnan', 'np.isnan', (['outputs'], {}), '(outputs)\n', (3066, 3075), True, 'import numpy as np\n')]
|
# License: MIT
# ref: https://github.com/thomas-young-2013/open-box/blob/master/openbox/surrogate/skrf.py
import logging
import typing
import numpy as np
from typing import List, Optional, Tuple, Union
from xbbo.surrogate.base import BaseRF
from xbbo.configspace.space import DenseConfigurationSpace
from xbbo.utils.constants import MAXINT
from xbbo.utils.util import get_types
logger = logging.getLogger(__name__)
class RandomForestSurrogate(BaseRF):
def __init__(
self,
configspace: DenseConfigurationSpace,
ensemble_size: int = 10,
normalize_y: bool = True,
instance_features: typing.Optional[np.ndarray] = None,
pca_components: typing.Optional[int] = None,
rng: np.random.RandomState = np.random.RandomState(42),types=None,bounds=None,
**kwargs
):
self.model_config = dict()
self.model_config["n_estimators"] = 10
self.model_config["criterion"] = "mse"
self.model_config["max_depth"] = 12
self.model_config["min_samples_split"] = 3
self.model_config["min_samples_leaf"] = 3
self.model_config["min_weight_fraction_leaf"] = 0.
self.model_config["max_features"] = 5. / 6.
self.model_config["max_leaf_nodes"] = None
self.model_config["n_jobs"] = -1
# self.model_config["random_state"] = -1
# self.model_config["max_samples"] = 1.
self.ensemble_size = ensemble_size
self.models = list()
self.configspace = configspace
self.rng = rng
self.random_seeds = self.rng.randint(low=1, high=MAXINT, size=self.ensemble_size)
if types is None or bounds is None:
types, bounds = get_types(configspace)
super().__init__(
configspace=configspace,
types=types,
bounds=bounds,
instance_features=instance_features,
pca_components=pca_components,
**kwargs
)
self.normalize_y = normalize_y
self.is_trained = False
def _train(self, X: np.ndarray, y: np.ndarray, **kwargs):
"""
Train a Random Forest Regression model on X and y
Parameters
----------
X: np.ndarray (N, D)
Input data points. The dimensionality of X is (N, D),
with N as the number of points and D is the number of features.
y: np.ndarray (N,)
The corresponding target values.
"""
from sklearn.ensemble import RandomForestRegressor
X = self._impute_inactive(X)
if self.normalize_y:
y = self._normalize_y(y)
self.models = list()
for i in range(self.ensemble_size):
configs = self.model_config.copy()
configs["random_state"] = self.random_seeds[i]
rf_model = RandomForestRegressor(**configs)
rf_model.fit(X, y)
self.models.append(rf_model)
self.is_trained = True
return self
def _predict(self, X_test: np.ndarray, **kwargs):
r"""
Returns the predictive mean and variance of the objective function
Parameters
----------
X_test: np.ndarray (N, D)
Input test points
Returns
----------
np.array(N,)
predictive mean
np.array(N,)
predictive variance
"""
if not self.is_trained:
raise Exception('Model has to be trained first!')
X_test = self._impute_inactive(X_test)
predictions = list()
for i, model in enumerate(self.models):
pred = model.predict(X_test)
# print(i)
predictions.append(pred)
m = np.mean(predictions, axis=0)
v = np.var(predictions, axis=0)
# Clip negative variances and set them to the smallest
# positive float value
if v.shape[0] == 1:
v = np.clip(v, np.finfo(v.dtype).eps, np.inf)
else:
v = np.clip(v, np.finfo(v.dtype).eps, np.inf)
v[np.where((v < np.finfo(v.dtype).eps) & (v > -np.finfo(v.dtype).eps))] = 0
if self.normalize_y:
m, v = self._untransform_y(m, v)
return m, v
def _normalize_y(self, y: np.ndarray) -> np.ndarray:
"""Normalize data to zero mean unit standard deviation.
"""
self.mean_y_ = np.mean(y)
self.std_y_ = np.std(y)
if self.std_y_ == 0:
self.std_y_ = 1
return (y - self.mean_y_) / self.std_y_
def _untransform_y(
self,
y: np.ndarray,
var: Optional[np.ndarray] = None,
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
"""Transform zeromean unit standard deviation data into the regular space.
"""
y = y * self.std_y_ + self.mean_y_
if var is not None:
var = var * self.std_y_ ** 2
return y, var
return y
def _impute_inactive(self, X: np.ndarray) -> np.ndarray:
X = X.copy()
X[~np.isfinite(X)] = -1
return X
|
[
"numpy.std",
"numpy.isfinite",
"numpy.random.RandomState",
"xbbo.utils.util.get_types",
"sklearn.ensemble.RandomForestRegressor",
"numpy.finfo",
"numpy.mean",
"numpy.var",
"logging.getLogger"
] |
[((390, 417), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (407, 417), False, 'import logging\n'), ((784, 809), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (805, 809), True, 'import numpy as np\n'), ((3751, 3779), 'numpy.mean', 'np.mean', (['predictions'], {'axis': '(0)'}), '(predictions, axis=0)\n', (3758, 3779), True, 'import numpy as np\n'), ((3792, 3819), 'numpy.var', 'np.var', (['predictions'], {'axis': '(0)'}), '(predictions, axis=0)\n', (3798, 3819), True, 'import numpy as np\n'), ((4414, 4424), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (4421, 4424), True, 'import numpy as np\n'), ((4447, 4456), 'numpy.std', 'np.std', (['y'], {}), '(y)\n', (4453, 4456), True, 'import numpy as np\n'), ((1738, 1760), 'xbbo.utils.util.get_types', 'get_types', (['configspace'], {}), '(configspace)\n', (1747, 1760), False, 'from xbbo.utils.util import get_types\n'), ((2863, 2895), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {}), '(**configs)\n', (2884, 2895), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((5081, 5095), 'numpy.isfinite', 'np.isfinite', (['X'], {}), '(X)\n', (5092, 5095), True, 'import numpy as np\n'), ((3970, 3987), 'numpy.finfo', 'np.finfo', (['v.dtype'], {}), '(v.dtype)\n', (3978, 3987), True, 'import numpy as np\n'), ((4042, 4059), 'numpy.finfo', 'np.finfo', (['v.dtype'], {}), '(v.dtype)\n', (4050, 4059), True, 'import numpy as np\n'), ((4101, 4118), 'numpy.finfo', 'np.finfo', (['v.dtype'], {}), '(v.dtype)\n', (4109, 4118), True, 'import numpy as np\n'), ((4132, 4149), 'numpy.finfo', 'np.finfo', (['v.dtype'], {}), '(v.dtype)\n', (4140, 4149), True, 'import numpy as np\n')]
|
from __future__ import division
import numpy as np
from pdb import set_trace
class Counter:
def __init__(self, before, after, indx):
self.indx = indx
self.actual = before
self.predicted = after
self.TP, self.TN, self.FP, self.FN = 0, 0, 0, 0
for a, b in zip(self.actual, self.predicted):
if a == indx and b == indx:
self.TP += 1
elif a == b and a != indx:
self.TN += 1
elif a != indx and b == indx:
self.FP += 1
elif a == indx and b != indx:
self.FN += 1
elif a != indx and b != indx:
pass
def stats(self):
try:
Sen = self.TP / (self.TP + self.FN)
Spec = self.TN / (self.TN + self.FP)
Prec = self.TP / (self.TP + self.FP)
# Acc = (self.TP + self.TN) / (self.TP + self.FN + self.TN + self.FP)
F1 = 2 * (Prec * Sen) / (Prec + Sen)
G = np.sqrt(Sen * Spec)
# ED = np.sqrt(0.6*(1-Sen)**2+0.3*(1-Spec)**2)
ED = 2 * Sen * Spec / (Sen + Spec)
return Sen * 100, (1 - Spec) * 100, Prec * 100, Sen * 100, F1 * 100, ED * 100, G * 100
except ZeroDivisionError:
return 0, 0, 0, 0, 0, 0, 0
class ABCD:
""" Statistics Stuff, confusion matrix, all that jazz...
"""
def __init__(self, before, after):
self.actual = before
self.predicted = after
def __call__(self):
uniques = set(self.actual)
for u in list(uniques):
yield Counter(self.actual, self.predicted, indx=u)
|
[
"numpy.sqrt"
] |
[((1004, 1023), 'numpy.sqrt', 'np.sqrt', (['(Sen * Spec)'], {}), '(Sen * Spec)\n', (1011, 1023), True, 'import numpy as np\n')]
|
'''
Author : <NAME>
Description :
-------------
The following code lets you click on a set of points and then create a curve that fits the set of points.
In order to execute this code, you need to install bokeh,
'''
from bokeh.io import curdoc
from bokeh.plotting import figure, output_file
from bokeh.layouts import column,row
from bokeh.models import ColumnDataSource
from bokeh.models import PointDrawTool
from bokeh.models import Button
from bokeh.events import DoubleTap
from scipy.spatial import ConvexHull
import numpy as np
from scipy import interpolate
from os import sys
from os import system
print('START OF THE PROGRAM')
try:
print(sys.argv)
if len(sys.argv)<=1:
command='bokeh serve --show draggablepoints.py --args d1 d2 d3'
if system(command) == 0:
pass
else:
print('Error occured in running the program')
exit()
except:
print('Error in system command (may be)')
exit()
finally:
pass
# Create a plot
fig = figure( title="CAD/Curves/Curve Fit",
plot_width=800,
plot_height=500,
x_range=(-5, 5),
y_range=(-5, 5)
)
fig.title.text_font_size='24pt'
fig.title.text_color='blue'
# Create some data sources
xydict=dict(x=[],y=[])
psource = ColumnDataSource(data=xydict)
csource = ColumnDataSource(data=xydict)
hsource = ColumnDataSource(data=xydict)
# Create some glyphs
lines = fig.line('x', 'y', source=psource)
vertices = fig.square('x', 'y', source=psource,size=10)
curved = fig.line('x','y',source=csource, color='red')
hullbnd = fig.patch('x','y',
source=hsource,
fill_color='red',
fill_alpha=0.1)
# curve fitting/interpolation
def curvefit():
print('Interpolation')
xarr=np.array(psource.data['x'])
yarr=np.array(psource.data['y'])
f=interpolate.interp1d(xarr,yarr,kind='cubic')
x1arr=np.linspace(xarr.min(),xarr.max(),100)
y1arr=f(x1arr)
csource.data['x']=x1arr.tolist()
csource.data['y']=y1arr.tolist()
# constructing a convex hull
def conhull():
xarr=np.array(psource.data['x'])
yarr=np.array(psource.data['y'])
pt=np.array([xarr,yarr])
hull=ConvexHull(pt.T)
bnd=np.append(hull.vertices,hull.vertices[0])
hsource.data['x']=pt.T[bnd,0].tolist()
hsource.data['y']=pt.T[bnd,1].tolist()
# clear all
def clearall():
psource.data['x']=[]
psource.data['y']=[]
csource.data['x']=[]
csource.data['y']=[]
hsource.data['x']=[]
hsource.data['y']=[]
##################################################################
def callback(event):
curvefit()
conhull()
fig.on_event(DoubleTap,callback)
##################################################################
xbutton=Button(label='Exit')
def xbutton_func():
exit()
xbutton.on_click(xbutton_func)
###################################################################
cfitbutton=Button(label='Curve Fit')
def cfit_func():
curvefit()
cfitbutton.on_click(cfit_func)
#########################################################
hullbutton=Button(label='Show Convex Hull')
def hullbutton_func():
conhull()
hullbutton.on_click(hullbutton_func)
##########################################################
wipebutton=Button(label='Clear all points')
def wipe_func():
clearall()
wipebutton.on_click(wipe_func)
##########################################################
brow1 = row(cfitbutton,hullbutton)
brow2 = row(wipebutton,xbutton)
layout = column(fig,brow1,brow2)
pointdrawtool = PointDrawTool(renderers=[vertices,lines,curved,hullbnd])
fig.add_tools(pointdrawtool)
curdoc().add_root(layout)
'''
Example :
---------
save the
'''
########################################################################
########################################################################
# End of File
|
[
"bokeh.models.ColumnDataSource",
"bokeh.models.PointDrawTool",
"bokeh.plotting.figure",
"bokeh.models.Button",
"os.system",
"numpy.append",
"bokeh.io.curdoc",
"numpy.array",
"bokeh.layouts.column",
"scipy.interpolate.interp1d",
"scipy.spatial.ConvexHull",
"bokeh.layouts.row"
] |
[((1052, 1159), 'bokeh.plotting.figure', 'figure', ([], {'title': '"""CAD/Curves/Curve Fit"""', 'plot_width': '(800)', 'plot_height': '(500)', 'x_range': '(-5, 5)', 'y_range': '(-5, 5)'}), "(title='CAD/Curves/Curve Fit', plot_width=800, plot_height=500,\n x_range=(-5, 5), y_range=(-5, 5))\n", (1058, 1159), False, 'from bokeh.plotting import figure, output_file\n'), ((1360, 1389), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', ([], {'data': 'xydict'}), '(data=xydict)\n', (1376, 1389), False, 'from bokeh.models import ColumnDataSource\n'), ((1401, 1430), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', ([], {'data': 'xydict'}), '(data=xydict)\n', (1417, 1430), False, 'from bokeh.models import ColumnDataSource\n'), ((1442, 1471), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', ([], {'data': 'xydict'}), '(data=xydict)\n', (1458, 1471), False, 'from bokeh.models import ColumnDataSource\n'), ((2941, 2961), 'bokeh.models.Button', 'Button', ([], {'label': '"""Exit"""'}), "(label='Exit')\n", (2947, 2961), False, 'from bokeh.models import Button\n'), ((3114, 3139), 'bokeh.models.Button', 'Button', ([], {'label': '"""Curve Fit"""'}), "(label='Curve Fit')\n", (3120, 3139), False, 'from bokeh.models import Button\n'), ((3289, 3321), 'bokeh.models.Button', 'Button', ([], {'label': '"""Show Convex Hull"""'}), "(label='Show Convex Hull')\n", (3295, 3321), False, 'from bokeh.models import Button\n'), ((3481, 3513), 'bokeh.models.Button', 'Button', ([], {'label': '"""Clear all points"""'}), "(label='Clear all points')\n", (3487, 3513), False, 'from bokeh.models import Button\n'), ((3671, 3698), 'bokeh.layouts.row', 'row', (['cfitbutton', 'hullbutton'], {}), '(cfitbutton, hullbutton)\n', (3674, 3698), False, 'from bokeh.layouts import column, row\n'), ((3707, 3731), 'bokeh.layouts.row', 'row', (['wipebutton', 'xbutton'], {}), '(wipebutton, xbutton)\n', (3710, 3731), False, 'from bokeh.layouts import column, row\n'), ((3741, 3766), 'bokeh.layouts.column', 'column', (['fig', 'brow1', 'brow2'], {}), '(fig, brow1, brow2)\n', (3747, 3766), False, 'from bokeh.layouts import column, row\n'), ((3784, 3843), 'bokeh.models.PointDrawTool', 'PointDrawTool', ([], {'renderers': '[vertices, lines, curved, hullbnd]'}), '(renderers=[vertices, lines, curved, hullbnd])\n', (3797, 3843), False, 'from bokeh.models import PointDrawTool\n'), ((1914, 1941), 'numpy.array', 'np.array', (["psource.data['x']"], {}), "(psource.data['x'])\n", (1922, 1941), True, 'import numpy as np\n'), ((1952, 1979), 'numpy.array', 'np.array', (["psource.data['y']"], {}), "(psource.data['y'])\n", (1960, 1979), True, 'import numpy as np\n'), ((1987, 2033), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['xarr', 'yarr'], {'kind': '"""cubic"""'}), "(xarr, yarr, kind='cubic')\n", (2007, 2033), False, 'from scipy import interpolate\n'), ((2242, 2269), 'numpy.array', 'np.array', (["psource.data['x']"], {}), "(psource.data['x'])\n", (2250, 2269), True, 'import numpy as np\n'), ((2280, 2307), 'numpy.array', 'np.array', (["psource.data['y']"], {}), "(psource.data['y'])\n", (2288, 2307), True, 'import numpy as np\n'), ((2316, 2338), 'numpy.array', 'np.array', (['[xarr, yarr]'], {}), '([xarr, yarr])\n', (2324, 2338), True, 'import numpy as np\n'), ((2348, 2364), 'scipy.spatial.ConvexHull', 'ConvexHull', (['pt.T'], {}), '(pt.T)\n', (2358, 2364), False, 'from scipy.spatial import ConvexHull\n'), ((2374, 2416), 'numpy.append', 'np.append', (['hull.vertices', 'hull.vertices[0]'], {}), '(hull.vertices, hull.vertices[0])\n', (2383, 2416), True, 'import numpy as np\n'), ((3876, 3884), 'bokeh.io.curdoc', 'curdoc', ([], {}), '()\n', (3882, 3884), False, 'from bokeh.io import curdoc\n'), ((797, 812), 'os.system', 'system', (['command'], {}), '(command)\n', (803, 812), False, 'from os import system\n')]
|
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from .GetDataAvailability import GetDataAvailability
import DateTimeTools as TT
months = ['J','F','M','A','M','J','J','A','S','O','N','D']
def PlotDataAvailability(Stations,Date,fig=None,maps=[1,1,0,0]):
#get the data availability for each station
ns = len(Stations)
for i in range(0,ns):
d,e = GetDataAvailability(Stations[i],Date)
if i == 0:
nd = d.size
x = d
grid = np.zeros((ns,nd),dtype='float32')
grid[i] = np.float32(e)
#Get the x-axis and y-axis
xe = np.arange(nd+1)*1.0
ye = np.arange(ns+1)*1.0
xg,yg = np.meshgrid(xe,ye)
#get axis limits
xlim = [0,nd]
ylim = [0,ns]
#get all of the years and months
yr,mn,dy = TT.DateSplit(x)
#determine where the ticks go
mtick = np.where((dy == 1))[0]
ytick = np.where((dy == 1) & (mn == 1))[0]
if ytick.size > 2:
#use yearly ticks
xticks = xe[ytick]
xticklabels = ['{:04d}'.format(yr[yt]) for yt in ytick]
else:
xticks = xe[mtick]
xticklabels = []
for i in range(0,mtick.size):
if mn[mtick[i]] == 1:
tmp = '{:s}\n{:04d}'.format(months[mn[mtick[i]]-1],yr[mtick[i]])
else:
tmp = '{:s}'.format(months[mn[mtick[i]]-1])
xticklabels.append(tmp)
yticks = ye
yticklabels = ['']*(ns+1)
#get the scale
scale = [0.0,1.0]
#set norm
norm = colors.Normalize(vmin=scale[0],vmax=scale[1])
if fig is None:
fig = plt
fig.figure()
if hasattr(fig,'Axes'):
ax = fig.subplot2grid((maps[1],maps[0]),(maps[3],maps[2]))
else:
ax = fig
sm = ax.pcolormesh(xg,yg,grid,cmap='RdYlGn',norm=norm,zorder=1.0)
#set limits
ax.set_xlim(xlim)
ax.set_ylim(ylim)
#set ticks
ax.xaxis.set_ticks(xticks)
ax.xaxis.set_ticklabels(xticklabels)
ax.yaxis.set_ticks(yticks)
ax.yaxis.set_ticklabels(yticklabels)
for i in range(0,ns):
ax.text(-0.03,(0.5 + i)/ns,Stations[i].upper(),ha='center',va='center',transform=ax.transAxes)
#plot a grid
#horizontal lines between stations
ax.hlines(ye,xlim[0],xlim[1],color=[0.0,0.0,0.0],zorder=4)
#vertical lines every year
ax.vlines(xe[ytick],ylim[0],ylim[1],color=[0.0,0.0,0.0],zorder=4,lw=2.0)
if ytick.size <= 5:
#vertical lines every month
ax.vlines(xe[mtick],ylim[0],ylim[1],color=[0.0,0.0,0.0],zorder=4,linestyle=':')
return ax
|
[
"numpy.meshgrid",
"matplotlib.colors.Normalize",
"numpy.float32",
"numpy.zeros",
"numpy.where",
"numpy.arange",
"DateTimeTools.DateSplit"
] |
[((684, 703), 'numpy.meshgrid', 'np.meshgrid', (['xe', 'ye'], {}), '(xe, ye)\n', (695, 703), True, 'import numpy as np\n'), ((800, 815), 'DateTimeTools.DateSplit', 'TT.DateSplit', (['x'], {}), '(x)\n', (812, 815), True, 'import DateTimeTools as TT\n'), ((1404, 1450), 'matplotlib.colors.Normalize', 'colors.Normalize', ([], {'vmin': 'scale[0]', 'vmax': 'scale[1]'}), '(vmin=scale[0], vmax=scale[1])\n', (1420, 1450), True, 'import matplotlib.colors as colors\n'), ((578, 591), 'numpy.float32', 'np.float32', (['e'], {}), '(e)\n', (588, 591), True, 'import numpy as np\n'), ((628, 645), 'numpy.arange', 'np.arange', (['(nd + 1)'], {}), '(nd + 1)\n', (637, 645), True, 'import numpy as np\n'), ((654, 671), 'numpy.arange', 'np.arange', (['(ns + 1)'], {}), '(ns + 1)\n', (663, 671), True, 'import numpy as np\n'), ((859, 876), 'numpy.where', 'np.where', (['(dy == 1)'], {}), '(dy == 1)\n', (867, 876), True, 'import numpy as np\n'), ((891, 922), 'numpy.where', 'np.where', (['((dy == 1) & (mn == 1))'], {}), '((dy == 1) & (mn == 1))\n', (899, 922), True, 'import numpy as np\n'), ((532, 567), 'numpy.zeros', 'np.zeros', (['(ns, nd)'], {'dtype': '"""float32"""'}), "((ns, nd), dtype='float32')\n", (540, 567), True, 'import numpy as np\n')]
|
# this script is based on ./examples/cars segmentation (camvid).ipynb
# ========== loading data ==========
'''
For this example, we will use PASCAL2012 dataset. It is a set of:
- train images + instance segmentation masks
- validation images + instance segmentation masks
'''
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # Will use only the first GPU device
import numpy as np
import cv2
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from skimage.transform import resize
from skimage.morphology import dilation, thin, binary_erosion
from scipy.ndimage import measurements
from tqdm import tqdm
import math
DATA_DIR = './data/voc/VOC2012/'
x_dir = os.path.join(DATA_DIR, 'JPEGImages')
y_dir = os.path.join(DATA_DIR, 'SegmentationObject')
cls_dir = os.path.join(DATA_DIR, 'SegmentationClass')
train_ids = os.path.join(DATA_DIR, 'ImageSets/Segmentation/train.txt')
valid_ids = os.path.join(DATA_DIR, 'ImageSets/Segmentation/val.txt')
# some useful constants
dim = (256, 256) # resize all images to dim=(256, 256)
background_centerness_const = 0 # gt val to indicate the pixel is a background
# ========== visualization helper ==========
def viz_centerness(y, id, folder_name):
"""Visualize centerness based on centerness scores
Args:
y: array of size [(1, H, W)], with the first dimension being centerness score
Return:
visualization plot
"""
# read in ground truth, display as background in plots
im = plt.imread(os.path.join(DATA_DIR, 'SegmentationObject', id[:-3]+'.png'))
im = np.where(im == 0, 255, im) # convert the background pixels to white (for visualization)
res_im = resize(im, dim)
mask = np.array(Image.open(os.path.join(DATA_DIR, 'SegmentationObject', id[:-3]+'.png')).resize(dim, resample=Image.NEAREST), dtype=int)
mask = np.where(mask == 255, 0, mask)
y = y.squeeze()
# y = np.where(mask == 0, 0, y)
# save centerness image
plt.figure(figsize = (20, 20))
plt.xticks([])
plt.yticks([])
plt.imshow(y[:,:,None], cmap='gray_r', interpolation='nearest')
plt.imshow(res_im, interpolation='nearest', alpha=0.4)
plt.savefig('./' + folder_name + '/' + id + '.png', dpi=300, bbox_inches='tight')
plt.close()
# save modified mask
modified_mask = np.zeros(mask.shape)
for label in np.unique(mask):
if label == 0:
continue
# perform morphological thinning and dilation
cur_mask = np.array(mask == label, dtype=int)
cur_mask = binary_erosion(cur_mask)
cur_mask = dilation(cur_mask)
modified_mask = modified_mask + cur_mask
# save modified mask
plt.figure(figsize = (20, 20))
plt.xticks([])
plt.yticks([])
plt.imshow(modified_mask[:,:,None], cmap='gray_r', interpolation='nearest')
plt.imshow(res_im, interpolation='nearest', alpha=0.4)
plt.savefig('./' + folder_name + '/' + id[:-3] + '.png', dpi=300, bbox_inches='tight')
plt.close()
# ========== data loader ==========
'''
Writing helper class for data extraction, tranformation and preprocessing
https://pytorch.org/docs/stable/data
'''
from torch.utils.data import DataLoader
from torch.utils.data import Dataset as BaseDataset
class Dataset(BaseDataset):
"""PASCAL Dataset. Read images, apply augmentation and preprocessing transformations.
Args:
images_dir (str): path to images folder
masks_dir (str): path to segmentation masks folder
img_ids (str): path to the file containing image ids
augmentation (albumentations.Compose): data transfromation pipeline
(e.g. flip, scale, etc.)
preprocessing (albumentations.Compose): data preprocessing
(e.g. noralization, shape manipulation, etc.)
"""
def __init__(
self,
images_dir,
masks_dir,
img_ids,
augmentation=None,
preprocessing=None,
):
with open(img_ids, 'r') as f:
self.ids = [x.strip() for x in f.readlines()]
print(img_ids + ': ' + str(len(self.ids)) + ' Images')
self.images_fps = [os.path.join(images_dir, image_id + '.jpg') for image_id in self.ids]
self.masks_fps = [os.path.join(masks_dir, image_id + '.png') for image_id in self.ids]
self.augmentation = augmentation
self.preprocessing = preprocessing
def __getitem__(self, i):
# read data
image = np.array(Image.open(self.images_fps[i]).resize(dim, resample=Image.NEAREST))
mask = np.array(Image.open(self.masks_fps[i]).resize(dim, resample=Image.NEAREST), dtype=int)
assert image.shape[:-1] == mask.shape
# concat xy position info on image (RGBXY)
# xx, yy = np.arange(image.shape[0]), np.arange(image.shape[1])
# grid_x, grid_y = np.meshgrid(xx, yy, indexing='ij')
# image = np.concatenate((image, grid_x[:,:,None], grid_y[:,:,None]), axis=-1).astype('float')
mask = np.where(mask == 255, 0, mask) # convert the void pixels to background
# print(np.unique(mask))
centerness = np.zeros(mask.shape)
weight = np.ones(mask.shape)
eps = 0.0001
for label in np.unique(mask):
if label == 0:
continue
# perform morphological thinning and dilation
cur_mask = (mask == label)
cur_mask = binary_erosion(cur_mask)
cur_mask = dilation(cur_mask)
if np.count_nonzero(cur_mask) == 0: # avoid empty object after erosion
cur_mask = (mask == label)
# compute the center coordinate by average all coordinates in the current object
xx, yy = np.arange(mask.shape[0]), np.arange(mask.shape[1])
grid_x, grid_y = np.meshgrid(xx, yy, indexing='ij')
grid_x = np.where(cur_mask == 1, grid_x, 0)
grid_y = np.where(cur_mask == 1, grid_y, 0)
center_x, center_y = np.sum(grid_x) / np.count_nonzero(grid_x), np.sum(grid_y) / np.count_nonzero(grid_y)
# assign center-ness score (between 0 and 1) to each pixel of 'label' based on distance to center
# const / distance
x_sqr_diff = np.square(np.absolute(grid_x - center_x))
y_sqr_diff = np.square(np.absolute(grid_y - center_y))
dist = np.sqrt(x_sqr_diff + y_sqr_diff) + eps # prevent division by 0
scores = np.minimum(1, np.divide(10, dist))
scores = np.where(mask == label, scores, 0)
# uniformly spread more weight to smaller objects (at least weight of a radius-10 circle)
if np.sum(scores) >= 314:
centerness = np.where(mask == label, scores, centerness)
else:
inc = (314 - np.sum(scores)) / np.sum(mask == label)
centerness = np.where(mask == label, scores + inc, centerness)
# update weight on pixels of current instance, used in loss computation
# weight = np.where(mask == label, 10000 / np.sum(mask == label), weight)
# weight = np.where(mask == label, (100 / np.sum(mask == label))**2, weight)
weight = np.where(mask == label, 100 / math.sqrt(np.sum(mask == label)), weight)
# sanity check
assert np.all(centerness >= np.zeros(centerness.shape))
assert np.all(centerness[mask == 0] == 0)
assert np.all(centerness[mask != 0] > 0)
centerness = centerness[:,:,None].astype('float')
weight = weight[:,:,None].astype('float')
# apply augmentations
if self.augmentation:
sample = self.augmentation(image=image, mask=centerness)
image, centerness = sample['image'], sample['mask']
# apply preprocessing
if self.preprocessing:
sample = self.preprocessing(image=image, mask=centerness)
image, centerness = sample['image'], sample['mask']
return image, centerness, weight.transpose(2, 0, 1).astype('float32')
def __len__(self):
return len(self.ids)
# look at the data we have
# dataset = Dataset(x_dir, y_dir, train_ids)
# image, centerness = dataset[14] # get some sample
# with open(train_ids, 'r') as f:
# ids = [x.strip() for x in f.readlines()]
# print(ids[14])
# viz_centerness(centerness, 'plot2', '.')
# ========== preprocess image ==========
import albumentations as albu
def to_tensor(x, **kwargs):
return x.transpose(2, 0, 1).astype('float32')
def get_preprocessing(preprocessing_fn):
"""Construct preprocessing transform
Args:
preprocessing_fn (callbale): data normalization function
(can be specific for each pretrained neural network)
Return:
transform: albumentations.Compose
"""
_transform = [
albu.Lambda(image=preprocessing_fn),
albu.Lambda(image=to_tensor, mask=to_tensor),
]
return albu.Compose(_transform)
# ========== create model and train ==========
import torch
import segmentation_models_pytorch as smp
ENCODER = 'se_resnext50_32x4d'
ENCODER_WEIGHTS = 'imagenet'
pascal_class = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car',
'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',
'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # 20 classes (excluding background)
ACTIVATION = 'sigmoid' # for centerness head
DEVICE = 'cuda'
# create segmentation model with pretrained encoder
model = smp.FPN(
encoder_name=ENCODER,
encoder_weights=ENCODER_WEIGHTS,
classes=1, # centerness (1 output channels)
activation=ACTIVATION,
)
preprocessing_fn = smp.encoders.get_preprocessing_fn(ENCODER, ENCODER_WEIGHTS)
train_dataset = Dataset(
x_dir,
y_dir,
train_ids,
preprocessing=get_preprocessing(preprocessing_fn),
)
valid_dataset = Dataset(
x_dir,
y_dir,
valid_ids,
preprocessing=get_preprocessing(preprocessing_fn),
)
train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True, num_workers=6)
valid_loader = DataLoader(valid_dataset, batch_size=8, shuffle=False, num_workers=6)
# Dice/F1 score - https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
# IoU/Jaccard score - https://en.wikipedia.org/wiki/Jaccard_index
loss = smp.utils.losses.Weighted_MSELoss(ignore_val=background_centerness_const) # smp.utils.losses.L1Loss(ignore_val=background_centerness_const) # total loss computed on object pixels
metrics = [
smp.utils.metrics.L1_centerness_object(), # per pixel score
]
optimizer = torch.optim.Adam([
dict(params=model.parameters(), lr=0.0001),
])
# create epoch runners
# it is a simple loop of iterating over dataloader`s samples
train_epoch = smp.utils.train.TrainEpoch(
model,
loss=loss,
metrics=metrics,
optimizer=optimizer,
device=DEVICE,
verbose=True,
)
valid_epoch = smp.utils.train.ValidEpoch(
model,
loss=loss,
metrics=metrics,
device=DEVICE,
verbose=True,
)
# # train model for 20 epochs
# min_score = 100000
# '''plot the training and validation losses
# sanity check if they are decreasing over epochs
# '''
# train_loss, valid_loss = [], []
# l1_centerness = []
# epochs = range(0,20)
# for i in range(0,20):
# print('\nEpoch: {}'.format(i))
# train_logs = train_epoch.run(train_loader)
# valid_logs = valid_epoch.run(valid_loader)
# train_loss.append(train_logs['weighted_mse_loss'])
# valid_loss.append(valid_logs['weighted_mse_loss'])
# l1_centerness.append(valid_logs['L1_centerness_object'])
# # do something (save model, change lr, etc.)
# if valid_logs['L1_centerness_object'] < min_score:
# min_score = valid_logs['L1_centerness_object']
# torch.save(model, './best_model_centerness_weightedL2_invsqrt.pth')
# print('Model saved!')
# # save the plots of training and validation losses
# plt.plot(epochs, train_loss, label='training_loss', color='red')
# plt.plot(epochs, valid_loss, label='validation_loss', color='blue')
# plt.title('loss visualization', fontsize=12)
# plt.legend(loc='upper left')
# plt.xlabel('epochs', fontsize=12)
# plt.ylabel('loss', fontsize=12)
# plt.savefig('./loss.png', dpi=300, bbox_inches='tight')
# plt.close()
# ========== visualize predictions ==========
# load best saved checkpoint
best_model = torch.load('./best_model_centerness_weightedL2_invsqrt.pth')\
# with open(valid_ids, 'r') as f:
# ids = [x.strip() for x in f.readlines()]
# for idx in range(10):
# i = idx # np.random.choice(len(valid_dataset))
# print(ids[i])
# image, gt_mask, weight = valid_dataset[i]
# gt_mask = gt_mask.squeeze()
# x_tensor = torch.from_numpy(image).to(DEVICE).unsqueeze(0)
# centerness = best_model.predict(x_tensor)
# centerness = (centerness.squeeze().cpu().numpy().round())
# # print(np.sum(centerness))
# # print(np.amax(centerness))
# # print(np.amin(centerness))
# viz_centerness(gt_mask, str(ids[i]) + '_gt', 'centerness_val_viz')
# viz_centerness(centerness, str(ids[i]) + '_pr', 'centerness_val_viz')
# with open(train_ids, 'r') as f:
# ids = [x.strip() for x in f.readlines()]
# for idx in [24, 121, 135, 431, 837, 871, 966, 1118, 1294, 1374]:
# i = idx # np.random.choice(len(train_dataset))
# print(ids[i])
# image, gt_mask, weight = train_dataset[i]
# gt_mask = gt_mask.squeeze()
# x_tensor = torch.from_numpy(image).to(DEVICE).unsqueeze(0)
# centerness = best_model.predict(x_tensor)
# centerness = (centerness.squeeze().cpu().numpy().round())
# viz_centerness(gt_mask, str(ids[i]) + '_gt', 'centerness_train_viz')
# viz_centerness(centerness, str(ids[i]) + '_pr', 'centerness_train_viz')
# ========== other evaluations ==========
# percentage of correct centers detected (on validation set)
with open(valid_ids, 'r') as f:
val_ids_arr = [x.strip() for x in f.readlines()]
masks_fps = [os.path.join(y_dir, image_id + '.png') for image_id in val_ids_arr]
semantic_fps = [os.path.join(cls_dir, image_id + '.png') for image_id in val_ids_arr]
total_count = 0
evals = dict()
for i in tqdm(range(len(val_ids_arr))):
image, gt_mask, weight = valid_dataset[i]
x_tensor = torch.from_numpy(image).to(DEVICE).unsqueeze(0)
centerness = best_model.predict(x_tensor)
# 1) threshold centerness scores
centerness = (centerness.squeeze().cpu().numpy().round())
# 2) compute connected components
labeled_array, num_features = measurements.label(centerness)
obj_mask = np.array(Image.open(masks_fps[i]).resize(dim, resample=Image.NEAREST), dtype=int)
cls_mask = np.array(Image.open(semantic_fps[i]).resize(dim, resample=Image.NEAREST), dtype=int)
image = image.transpose(1, 2, 0)
assert image.shape[:-1] == obj_mask.shape
assert image.shape[:-1] == cls_mask.shape
obj_mask = np.where(obj_mask == 255, 0, obj_mask) # convert the void pixels to background
cls_mask = np.where(cls_mask == 255, 0, cls_mask)
# 3) assign connected component to class it has the largest overlap with
for component in np.unique(labeled_array):
if component == 0: continue
largest_overlap = 0
cls_belong = 0
for cur_cls in np.unique(cls_mask):
if cur_cls == 0: continue
overlap = np.count_nonzero(np.logical_and(labeled_array == component, cls_mask == cur_cls))
if overlap > largest_overlap:
largest_overlap = overlap
cls_belong = cur_cls
pos = np.logical_and(labeled_array == component, cls_mask == cls_belong)
labeled_array[labeled_array == component] = 0
labeled_array[pos] = component
# 4) compute how many connected components fall inside each instance
for label in np.unique(obj_mask):
if label == 0:
continue
cur_centerness = np.where(obj_mask == label, labeled_array, 0)
num_components = np.unique(cur_centerness)
num_components = len(num_components[num_components != 0])
if num_components in evals:
evals[num_components] += 1
else:
evals[num_components] = 1
total_count += 1
# 5) compute precentages of connected components per instance
print("====================")
print("total number of instances in val set: " + str(total_count))
for num_components in evals:
percentage = evals[num_components] / total_count
print(str(num_components) + ' connected component(s): ' + str(percentage))
|
[
"numpy.absolute",
"segmentation_models_pytorch.utils.train.ValidEpoch",
"albumentations.Lambda",
"numpy.sum",
"scipy.ndimage.measurements.label",
"numpy.ones",
"segmentation_models_pytorch.utils.train.TrainEpoch",
"matplotlib.pyplot.figure",
"skimage.transform.resize",
"numpy.arange",
"segmentation_models_pytorch.utils.metrics.L1_centerness_object",
"os.path.join",
"numpy.unique",
"skimage.morphology.dilation",
"numpy.meshgrid",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.imshow",
"torch.load",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.close",
"skimage.morphology.binary_erosion",
"matplotlib.pyplot.xticks",
"numpy.divide",
"segmentation_models_pytorch.utils.losses.Weighted_MSELoss",
"segmentation_models_pytorch.FPN",
"numpy.all",
"torch.from_numpy",
"albumentations.Compose",
"numpy.count_nonzero",
"numpy.logical_and",
"numpy.zeros",
"PIL.Image.open",
"numpy.where",
"numpy.array",
"segmentation_models_pytorch.encoders.get_preprocessing_fn",
"matplotlib.pyplot.savefig",
"numpy.sqrt"
] |
[((702, 738), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""JPEGImages"""'], {}), "(DATA_DIR, 'JPEGImages')\n", (714, 738), False, 'import os\n'), ((747, 791), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""SegmentationObject"""'], {}), "(DATA_DIR, 'SegmentationObject')\n", (759, 791), False, 'import os\n'), ((802, 845), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""SegmentationClass"""'], {}), "(DATA_DIR, 'SegmentationClass')\n", (814, 845), False, 'import os\n'), ((859, 917), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""ImageSets/Segmentation/train.txt"""'], {}), "(DATA_DIR, 'ImageSets/Segmentation/train.txt')\n", (871, 917), False, 'import os\n'), ((930, 986), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""ImageSets/Segmentation/val.txt"""'], {}), "(DATA_DIR, 'ImageSets/Segmentation/val.txt')\n", (942, 986), False, 'import os\n'), ((9628, 9728), 'segmentation_models_pytorch.FPN', 'smp.FPN', ([], {'encoder_name': 'ENCODER', 'encoder_weights': 'ENCODER_WEIGHTS', 'classes': '(1)', 'activation': 'ACTIVATION'}), '(encoder_name=ENCODER, encoder_weights=ENCODER_WEIGHTS, classes=1,\n activation=ACTIVATION)\n', (9635, 9728), True, 'import segmentation_models_pytorch as smp\n'), ((9797, 9856), 'segmentation_models_pytorch.encoders.get_preprocessing_fn', 'smp.encoders.get_preprocessing_fn', (['ENCODER', 'ENCODER_WEIGHTS'], {}), '(ENCODER, ENCODER_WEIGHTS)\n', (9830, 9856), True, 'import segmentation_models_pytorch as smp\n'), ((10117, 10185), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': '(8)', 'shuffle': '(True)', 'num_workers': '(6)'}), '(train_dataset, batch_size=8, shuffle=True, num_workers=6)\n', (10127, 10185), False, 'from torch.utils.data import DataLoader\n'), ((10201, 10270), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_dataset'], {'batch_size': '(8)', 'shuffle': '(False)', 'num_workers': '(6)'}), '(valid_dataset, batch_size=8, shuffle=False, num_workers=6)\n', (10211, 10270), False, 'from torch.utils.data import DataLoader\n'), ((10433, 10506), 'segmentation_models_pytorch.utils.losses.Weighted_MSELoss', 'smp.utils.losses.Weighted_MSELoss', ([], {'ignore_val': 'background_centerness_const'}), '(ignore_val=background_centerness_const)\n', (10466, 10506), True, 'import segmentation_models_pytorch as smp\n'), ((10874, 10990), 'segmentation_models_pytorch.utils.train.TrainEpoch', 'smp.utils.train.TrainEpoch', (['model'], {'loss': 'loss', 'metrics': 'metrics', 'optimizer': 'optimizer', 'device': 'DEVICE', 'verbose': '(True)'}), '(model, loss=loss, metrics=metrics, optimizer=\n optimizer, device=DEVICE, verbose=True)\n', (10900, 10990), True, 'import segmentation_models_pytorch as smp\n'), ((11031, 11125), 'segmentation_models_pytorch.utils.train.ValidEpoch', 'smp.utils.train.ValidEpoch', (['model'], {'loss': 'loss', 'metrics': 'metrics', 'device': 'DEVICE', 'verbose': '(True)'}), '(model, loss=loss, metrics=metrics, device=DEVICE,\n verbose=True)\n', (11057, 11125), True, 'import segmentation_models_pytorch as smp\n'), ((12506, 12566), 'torch.load', 'torch.load', (['"""./best_model_centerness_weightedL2_invsqrt.pth"""'], {}), "('./best_model_centerness_weightedL2_invsqrt.pth')\n", (12516, 12566), False, 'import torch\n'), ((1587, 1613), 'numpy.where', 'np.where', (['(im == 0)', '(255)', 'im'], {}), '(im == 0, 255, im)\n', (1595, 1613), True, 'import numpy as np\n'), ((1688, 1703), 'skimage.transform.resize', 'resize', (['im', 'dim'], {}), '(im, dim)\n', (1694, 1703), False, 'from skimage.transform import resize\n'), ((1856, 1886), 'numpy.where', 'np.where', (['(mask == 255)', '(0)', 'mask'], {}), '(mask == 255, 0, mask)\n', (1864, 1886), True, 'import numpy as np\n'), ((1980, 2008), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (1990, 2008), True, 'import matplotlib.pyplot as plt\n'), ((2015, 2029), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (2025, 2029), True, 'import matplotlib.pyplot as plt\n'), ((2034, 2048), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (2044, 2048), True, 'import matplotlib.pyplot as plt\n'), ((2053, 2118), 'matplotlib.pyplot.imshow', 'plt.imshow', (['y[:, :, None]'], {'cmap': '"""gray_r"""', 'interpolation': '"""nearest"""'}), "(y[:, :, None], cmap='gray_r', interpolation='nearest')\n", (2063, 2118), True, 'import matplotlib.pyplot as plt\n'), ((2121, 2175), 'matplotlib.pyplot.imshow', 'plt.imshow', (['res_im'], {'interpolation': '"""nearest"""', 'alpha': '(0.4)'}), "(res_im, interpolation='nearest', alpha=0.4)\n", (2131, 2175), True, 'import matplotlib.pyplot as plt\n'), ((2180, 2266), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./' + folder_name + '/' + id + '.png')"], {'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "('./' + folder_name + '/' + id + '.png', dpi=300, bbox_inches=\n 'tight')\n", (2191, 2266), True, 'import matplotlib.pyplot as plt\n'), ((2266, 2277), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2275, 2277), True, 'import matplotlib.pyplot as plt\n'), ((2324, 2344), 'numpy.zeros', 'np.zeros', (['mask.shape'], {}), '(mask.shape)\n', (2332, 2344), True, 'import numpy as np\n'), ((2362, 2377), 'numpy.unique', 'np.unique', (['mask'], {}), '(mask)\n', (2371, 2377), True, 'import numpy as np\n'), ((2696, 2724), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (2706, 2724), True, 'import matplotlib.pyplot as plt\n'), ((2731, 2745), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (2741, 2745), True, 'import matplotlib.pyplot as plt\n'), ((2750, 2764), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (2760, 2764), True, 'import matplotlib.pyplot as plt\n'), ((2769, 2846), 'matplotlib.pyplot.imshow', 'plt.imshow', (['modified_mask[:, :, None]'], {'cmap': '"""gray_r"""', 'interpolation': '"""nearest"""'}), "(modified_mask[:, :, None], cmap='gray_r', interpolation='nearest')\n", (2779, 2846), True, 'import matplotlib.pyplot as plt\n'), ((2849, 2903), 'matplotlib.pyplot.imshow', 'plt.imshow', (['res_im'], {'interpolation': '"""nearest"""', 'alpha': '(0.4)'}), "(res_im, interpolation='nearest', alpha=0.4)\n", (2859, 2903), True, 'import matplotlib.pyplot as plt\n'), ((2908, 2998), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./' + folder_name + '/' + id[:-3] + '.png')"], {'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "('./' + folder_name + '/' + id[:-3] + '.png', dpi=300,\n bbox_inches='tight')\n", (2919, 2998), True, 'import matplotlib.pyplot as plt\n'), ((2999, 3010), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3008, 3010), True, 'import matplotlib.pyplot as plt\n'), ((9023, 9047), 'albumentations.Compose', 'albu.Compose', (['_transform'], {}), '(_transform)\n', (9035, 9047), True, 'import albumentations as albu\n'), ((10628, 10668), 'segmentation_models_pytorch.utils.metrics.L1_centerness_object', 'smp.utils.metrics.L1_centerness_object', ([], {}), '()\n', (10666, 10668), True, 'import segmentation_models_pytorch as smp\n'), ((14110, 14148), 'os.path.join', 'os.path.join', (['y_dir', "(image_id + '.png')"], {}), "(y_dir, image_id + '.png')\n", (14122, 14148), False, 'import os\n'), ((14194, 14234), 'os.path.join', 'os.path.join', (['cls_dir', "(image_id + '.png')"], {}), "(cls_dir, image_id + '.png')\n", (14206, 14234), False, 'import os\n'), ((14662, 14692), 'scipy.ndimage.measurements.label', 'measurements.label', (['centerness'], {}), '(centerness)\n', (14680, 14692), False, 'from scipy.ndimage import measurements\n'), ((15040, 15078), 'numpy.where', 'np.where', (['(obj_mask == 255)', '(0)', 'obj_mask'], {}), '(obj_mask == 255, 0, obj_mask)\n', (15048, 15078), True, 'import numpy as np\n'), ((15134, 15172), 'numpy.where', 'np.where', (['(cls_mask == 255)', '(0)', 'cls_mask'], {}), '(cls_mask == 255, 0, cls_mask)\n', (15142, 15172), True, 'import numpy as np\n'), ((15272, 15296), 'numpy.unique', 'np.unique', (['labeled_array'], {}), '(labeled_array)\n', (15281, 15296), True, 'import numpy as np\n'), ((15957, 15976), 'numpy.unique', 'np.unique', (['obj_mask'], {}), '(obj_mask)\n', (15966, 15976), True, 'import numpy as np\n'), ((1516, 1578), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""SegmentationObject"""', "(id[:-3] + '.png')"], {}), "(DATA_DIR, 'SegmentationObject', id[:-3] + '.png')\n", (1528, 1578), False, 'import os\n'), ((2496, 2530), 'numpy.array', 'np.array', (['(mask == label)'], {'dtype': 'int'}), '(mask == label, dtype=int)\n', (2504, 2530), True, 'import numpy as np\n'), ((2550, 2574), 'skimage.morphology.binary_erosion', 'binary_erosion', (['cur_mask'], {}), '(cur_mask)\n', (2564, 2574), False, 'from skimage.morphology import dilation, thin, binary_erosion\n'), ((2594, 2612), 'skimage.morphology.dilation', 'dilation', (['cur_mask'], {}), '(cur_mask)\n', (2602, 2612), False, 'from skimage.morphology import dilation, thin, binary_erosion\n'), ((5052, 5082), 'numpy.where', 'np.where', (['(mask == 255)', '(0)', 'mask'], {}), '(mask == 255, 0, mask)\n', (5060, 5082), True, 'import numpy as np\n'), ((5177, 5197), 'numpy.zeros', 'np.zeros', (['mask.shape'], {}), '(mask.shape)\n', (5185, 5197), True, 'import numpy as np\n'), ((5215, 5234), 'numpy.ones', 'np.ones', (['mask.shape'], {}), '(mask.shape)\n', (5222, 5234), True, 'import numpy as np\n'), ((5278, 5293), 'numpy.unique', 'np.unique', (['mask'], {}), '(mask)\n', (5287, 5293), True, 'import numpy as np\n'), ((7430, 7464), 'numpy.all', 'np.all', (['(centerness[mask == 0] == 0)'], {}), '(centerness[mask == 0] == 0)\n', (7436, 7464), True, 'import numpy as np\n'), ((7480, 7513), 'numpy.all', 'np.all', (['(centerness[mask != 0] > 0)'], {}), '(centerness[mask != 0] > 0)\n', (7486, 7513), True, 'import numpy as np\n'), ((8915, 8950), 'albumentations.Lambda', 'albu.Lambda', ([], {'image': 'preprocessing_fn'}), '(image=preprocessing_fn)\n', (8926, 8950), True, 'import albumentations as albu\n'), ((8960, 9004), 'albumentations.Lambda', 'albu.Lambda', ([], {'image': 'to_tensor', 'mask': 'to_tensor'}), '(image=to_tensor, mask=to_tensor)\n', (8971, 9004), True, 'import albumentations as albu\n'), ((15408, 15427), 'numpy.unique', 'np.unique', (['cls_mask'], {}), '(cls_mask)\n', (15417, 15427), True, 'import numpy as np\n'), ((15706, 15772), 'numpy.logical_and', 'np.logical_and', (['(labeled_array == component)', '(cls_mask == cls_belong)'], {}), '(labeled_array == component, cls_mask == cls_belong)\n', (15720, 15772), True, 'import numpy as np\n'), ((16047, 16092), 'numpy.where', 'np.where', (['(obj_mask == label)', 'labeled_array', '(0)'], {}), '(obj_mask == label, labeled_array, 0)\n', (16055, 16092), True, 'import numpy as np\n'), ((16118, 16143), 'numpy.unique', 'np.unique', (['cur_centerness'], {}), '(cur_centerness)\n', (16127, 16143), True, 'import numpy as np\n'), ((4184, 4227), 'os.path.join', 'os.path.join', (['images_dir', "(image_id + '.jpg')"], {}), "(images_dir, image_id + '.jpg')\n", (4196, 4227), False, 'import os\n'), ((4280, 4322), 'os.path.join', 'os.path.join', (['masks_dir', "(image_id + '.png')"], {}), "(masks_dir, image_id + '.png')\n", (4292, 4322), False, 'import os\n'), ((5467, 5491), 'skimage.morphology.binary_erosion', 'binary_erosion', (['cur_mask'], {}), '(cur_mask)\n', (5481, 5491), False, 'from skimage.morphology import dilation, thin, binary_erosion\n'), ((5515, 5533), 'skimage.morphology.dilation', 'dilation', (['cur_mask'], {}), '(cur_mask)\n', (5523, 5533), False, 'from skimage.morphology import dilation, thin, binary_erosion\n'), ((5854, 5888), 'numpy.meshgrid', 'np.meshgrid', (['xx', 'yy'], {'indexing': '"""ij"""'}), "(xx, yy, indexing='ij')\n", (5865, 5888), True, 'import numpy as np\n'), ((5910, 5944), 'numpy.where', 'np.where', (['(cur_mask == 1)', 'grid_x', '(0)'], {}), '(cur_mask == 1, grid_x, 0)\n', (5918, 5944), True, 'import numpy as np\n'), ((5966, 6000), 'numpy.where', 'np.where', (['(cur_mask == 1)', 'grid_y', '(0)'], {}), '(cur_mask == 1, grid_y, 0)\n', (5974, 6000), True, 'import numpy as np\n'), ((6553, 6587), 'numpy.where', 'np.where', (['(mask == label)', 'scores', '(0)'], {}), '(mask == label, scores, 0)\n', (6561, 6587), True, 'import numpy as np\n'), ((5549, 5575), 'numpy.count_nonzero', 'np.count_nonzero', (['cur_mask'], {}), '(cur_mask)\n', (5565, 5575), True, 'import numpy as np\n'), ((5774, 5798), 'numpy.arange', 'np.arange', (['mask.shape[0]'], {}), '(mask.shape[0])\n', (5783, 5798), True, 'import numpy as np\n'), ((5800, 5824), 'numpy.arange', 'np.arange', (['mask.shape[1]'], {}), '(mask.shape[1])\n', (5809, 5824), True, 'import numpy as np\n'), ((6295, 6325), 'numpy.absolute', 'np.absolute', (['(grid_x - center_x)'], {}), '(grid_x - center_x)\n', (6306, 6325), True, 'import numpy as np\n'), ((6362, 6392), 'numpy.absolute', 'np.absolute', (['(grid_y - center_y)'], {}), '(grid_y - center_y)\n', (6373, 6392), True, 'import numpy as np\n'), ((6413, 6445), 'numpy.sqrt', 'np.sqrt', (['(x_sqr_diff + y_sqr_diff)'], {}), '(x_sqr_diff + y_sqr_diff)\n', (6420, 6445), True, 'import numpy as np\n'), ((6511, 6530), 'numpy.divide', 'np.divide', (['(10)', 'dist'], {}), '(10, dist)\n', (6520, 6530), True, 'import numpy as np\n'), ((6705, 6719), 'numpy.sum', 'np.sum', (['scores'], {}), '(scores)\n', (6711, 6719), True, 'import numpy as np\n'), ((6757, 6800), 'numpy.where', 'np.where', (['(mask == label)', 'scores', 'centerness'], {}), '(mask == label, scores, centerness)\n', (6765, 6800), True, 'import numpy as np\n'), ((6917, 6966), 'numpy.where', 'np.where', (['(mask == label)', '(scores + inc)', 'centerness'], {}), '(mask == label, scores + inc, centerness)\n', (6925, 6966), True, 'import numpy as np\n'), ((7387, 7413), 'numpy.zeros', 'np.zeros', (['centerness.shape'], {}), '(centerness.shape)\n', (7395, 7413), True, 'import numpy as np\n'), ((14722, 14746), 'PIL.Image.open', 'Image.open', (['masks_fps[i]'], {}), '(masks_fps[i])\n', (14732, 14746), False, 'from PIL import Image\n'), ((14819, 14846), 'PIL.Image.open', 'Image.open', (['semantic_fps[i]'], {}), '(semantic_fps[i])\n', (14829, 14846), False, 'from PIL import Image\n'), ((15506, 15569), 'numpy.logical_and', 'np.logical_and', (['(labeled_array == component)', '(cls_mask == cur_cls)'], {}), '(labeled_array == component, cls_mask == cur_cls)\n', (15520, 15569), True, 'import numpy as np\n'), ((1735, 1797), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""SegmentationObject"""', "(id[:-3] + '.png')"], {}), "(DATA_DIR, 'SegmentationObject', id[:-3] + '.png')\n", (1747, 1797), False, 'import os\n'), ((4531, 4561), 'PIL.Image.open', 'Image.open', (['self.images_fps[i]'], {}), '(self.images_fps[i])\n', (4541, 4561), False, 'from PIL import Image\n'), ((4623, 4652), 'PIL.Image.open', 'Image.open', (['self.masks_fps[i]'], {}), '(self.masks_fps[i])\n', (4633, 4652), False, 'from PIL import Image\n'), ((6034, 6048), 'numpy.sum', 'np.sum', (['grid_x'], {}), '(grid_x)\n', (6040, 6048), True, 'import numpy as np\n'), ((6051, 6075), 'numpy.count_nonzero', 'np.count_nonzero', (['grid_x'], {}), '(grid_x)\n', (6067, 6075), True, 'import numpy as np\n'), ((6077, 6091), 'numpy.sum', 'np.sum', (['grid_y'], {}), '(grid_y)\n', (6083, 6091), True, 'import numpy as np\n'), ((6094, 6118), 'numpy.count_nonzero', 'np.count_nonzero', (['grid_y'], {}), '(grid_y)\n', (6110, 6118), True, 'import numpy as np\n'), ((6866, 6887), 'numpy.sum', 'np.sum', (['(mask == label)'], {}), '(mask == label)\n', (6872, 6887), True, 'import numpy as np\n'), ((14397, 14420), 'torch.from_numpy', 'torch.from_numpy', (['image'], {}), '(image)\n', (14413, 14420), False, 'import torch\n'), ((6848, 6862), 'numpy.sum', 'np.sum', (['scores'], {}), '(scores)\n', (6854, 6862), True, 'import numpy as np\n'), ((7287, 7308), 'numpy.sum', 'np.sum', (['(mask == label)'], {}), '(mask == label)\n', (7293, 7308), True, 'import numpy as np\n')]
|
import unittest.mock as umock
from argparse import ArgumentTypeError
import numpy as np
import pytest
from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, \
do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image
test_array = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
test_image = read_image("test_images/test_img.png")
args_mock = umock.MagicMock()
# zesvetleni a ztmaveni, TODO udelat aby mock vzdy vracel 50, pro pripad ze bude vic unit testu nez hodnot
args_mock.darken = [50, 50, 50, 50, 80, 70, 80, 10, 80] # TODO mockovat veci v danem testu
args_mock.lighten = [50, 50, 50, 50, 100, 70, 40, 50, 100]
def test_read_image():
assert read_image("test_images/test_img.png").ndim > 0 # jakykoliv non fail vysledek je ok
def test_image_fail():
with pytest.raises(FileNotFoundError):
read_image("nonexistent_file_please_dont_create_file_named_like_this.pls")
def test_do_embossing():
out = do_embossing(test_array)
def test_do_edge_detection():
out = do_edge_detection(test_array)
def test_do_blur_5x5():
out = do_blur_5x5(test_array)
def test_do_blur_3x3():
out = do_blur_3x3(test_array)
def test_do_sharpen():
out = do_sharpen(test_array)
def test_do_bw():
out = do_bw(test_array)
def test_do_inverse():
out = do_inverse(test_array)
assert (out == 254).all()
def test_do_darken():
out = do_darken(test_array, args_mock)
assert np.all(out == 0.5)
def test_do_lighten():
out = do_lighten(test_array, args_mock)
assert np.all(out == 1.5)
def test_do_mirror():
out = do_mirror(test_array)
assert ((test_array == out).all()) # po zrcadleni musi byt identicke
def test_do_rotate():
out = do_rotate(test_array)
assert ((test_array == out).all()) # po rotaci musi byt identicke
def test_percentage_invalid():
a = None
with pytest.raises(ArgumentTypeError):
percentage(-1)
assert (a is None)
def test_percentage_high_value():
a = None
a = percentage(10000000)
assert a == 10000000
def test_percentage_zero():
a = None
a = percentage(0)
assert a == 0
def test_rotation_identity():
# pokud otocime jeden obrazek 4x musi byt stejny jako puvodni
out = do_rotate(test_image)
out = do_rotate(out)
out = do_rotate(out)
final = do_rotate(out)
assert (final == test_image).all()
def test_mirror_identity():
out = do_mirror(test_image)
final = do_mirror(out)
assert (final == test_image).all()
def test_multiple_bw():
# vicero pouzitych bw musi vracet stejnou hodnotu
out = do_bw(test_image)
second_out = do_bw(out)
third_out = do_bw(second_out)
assert np.logical_and((out == second_out).all(), (second_out == third_out).all())
def test_compare_rotate():
out = do_rotate(test_image)
test_input = read_image("test_images/rotate.png")
assert (out == test_input).all()
def test_compare_mirror():
out = do_mirror(test_image)
test_input = read_image("test_images/mirror.png")
assert (out == test_input).all()
def test_compare_inverse():
out = do_inverse(test_image)
test_input = read_image("test_images/inverse.png")
assert (out == test_input).all()
# TODO before saving there are some slight data diference, that causes fail even if images are same
def test_compare_bw():
out = do_bw(test_image)
save_image(out, "test_images/bwOut.png")
output = read_image("test_images/bwOut.png")
test_input = read_image("test_images/bw.png")
assert (output == test_input).all()
# TODO before saving there are some slight data diference, that causes fail even if images are same
def test_compare_lighten():
out = do_lighten(test_image, args_mock)
save_image(out, "test_images/lightenOut.png")
output = read_image("test_images/lightenOut.png")
test_input = read_image("test_images/lighten.png")
assert (output == test_input).all()
# TODO before saving there are some slight data diference, that causes fail even if images are same
def test_compare_darken():
out = do_darken(test_image, args_mock)
save_image(out, "test_images/darkenOut.png")
output = read_image("test_images/darkenOut.png")
test_input = read_image("test_images/darken.png")
assert (output == test_input).all()
def test_argument_chaining_one_convolution():
# testuje funkcnost retezeni, vzajmne kompability a toho, ze si testy navzajem neznici file
# kvuli casove narocnosti testujeme pouze jednu konvolucni fci (pouzivaji stejny kod, pouze kernel se meni)
out = do_mirror(test_image)
out = do_rotate(out)
out = do_lighten(out, args_mock)
out = do_inverse(out)
out = do_darken(out, args_mock)
out = do_bw(out)
out = do_sharpen(out)
out = do_mirror(test_image)
out = do_rotate(out)
out = do_lighten(out, args_mock)
out = do_inverse(out)
out = do_darken(out, args_mock)
"""
casove narocne testy
def test_compare_sharpen():
out = do_sharpen(test_image)
test_input = read_image("test_images/sharpen.png")
assert (out == test_input).all()
def test_compare_blur_3x3():
out = do_blur_3x3(test_image)
test_input = read_image("test_images/blur3.png")
assert (out == test_input).all()
def test_compare_blur_5x5():
out = do_blur_5x5(test_image)
test_input = read_image("test_images/blur5.png")
assert (out == test_input).all()
def test_compare_edge_detection():
out = do_edge_detection(test_image)
test_input = read_image("test_images/edges.png")
assert (out == test_input).all()
def test_compare_embossing():
out = do_embossing(test_image)
test_input = read_image("test_images/embossing.png")
assert (out == test_input).all()
"""
|
[
"functions.do_bw",
"functions.do_lighten",
"unittest.mock.MagicMock",
"functions.percentage",
"functions.do_darken",
"functions.do_inverse",
"functions.do_blur_5x5",
"numpy.all",
"functions.do_rotate",
"functions.do_embossing",
"functions.save_image",
"pytest.raises",
"numpy.array",
"functions.do_mirror",
"functions.do_sharpen",
"functions.read_image",
"functions.do_blur_3x3",
"functions.do_edge_detection"
] |
[((316, 359), 'numpy.array', 'np.array', (['[[1, 1, 1], [1, 1, 1], [1, 1, 1]]'], {}), '([[1, 1, 1], [1, 1, 1], [1, 1, 1]])\n', (324, 359), True, 'import numpy as np\n'), ((374, 412), 'functions.read_image', 'read_image', (['"""test_images/test_img.png"""'], {}), "('test_images/test_img.png')\n", (384, 412), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((426, 443), 'unittest.mock.MagicMock', 'umock.MagicMock', ([], {}), '()\n', (441, 443), True, 'import unittest.mock as umock\n'), ((1011, 1035), 'functions.do_embossing', 'do_embossing', (['test_array'], {}), '(test_array)\n', (1023, 1035), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1078, 1107), 'functions.do_edge_detection', 'do_edge_detection', (['test_array'], {}), '(test_array)\n', (1095, 1107), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1144, 1167), 'functions.do_blur_5x5', 'do_blur_5x5', (['test_array'], {}), '(test_array)\n', (1155, 1167), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1204, 1227), 'functions.do_blur_3x3', 'do_blur_3x3', (['test_array'], {}), '(test_array)\n', (1215, 1227), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1263, 1285), 'functions.do_sharpen', 'do_sharpen', (['test_array'], {}), '(test_array)\n', (1273, 1285), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1316, 1333), 'functions.do_bw', 'do_bw', (['test_array'], {}), '(test_array)\n', (1321, 1333), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1369, 1391), 'functions.do_inverse', 'do_inverse', (['test_array'], {}), '(test_array)\n', (1379, 1391), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1456, 1488), 'functions.do_darken', 'do_darken', (['test_array', 'args_mock'], {}), '(test_array, args_mock)\n', (1465, 1488), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1500, 1518), 'numpy.all', 'np.all', (['(out == 0.5)'], {}), '(out == 0.5)\n', (1506, 1518), True, 'import numpy as np\n'), ((1554, 1587), 'functions.do_lighten', 'do_lighten', (['test_array', 'args_mock'], {}), '(test_array, args_mock)\n', (1564, 1587), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1599, 1617), 'numpy.all', 'np.all', (['(out == 1.5)'], {}), '(out == 1.5)\n', (1605, 1617), True, 'import numpy as np\n'), ((1652, 1673), 'functions.do_mirror', 'do_mirror', (['test_array'], {}), '(test_array)\n', (1661, 1673), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1782, 1803), 'functions.do_rotate', 'do_rotate', (['test_array'], {}), '(test_array)\n', (1791, 1803), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2067, 2087), 'functions.percentage', 'percentage', (['(10000000)'], {}), '(10000000)\n', (2077, 2087), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2164, 2177), 'functions.percentage', 'percentage', (['(0)'], {}), '(0)\n', (2174, 2177), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2304, 2325), 'functions.do_rotate', 'do_rotate', (['test_image'], {}), '(test_image)\n', (2313, 2325), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2336, 2350), 'functions.do_rotate', 'do_rotate', (['out'], {}), '(out)\n', (2345, 2350), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2361, 2375), 'functions.do_rotate', 'do_rotate', (['out'], {}), '(out)\n', (2370, 2375), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2388, 2402), 'functions.do_rotate', 'do_rotate', (['out'], {}), '(out)\n', (2397, 2402), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2482, 2503), 'functions.do_mirror', 'do_mirror', (['test_image'], {}), '(test_image)\n', (2491, 2503), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2516, 2530), 'functions.do_mirror', 'do_mirror', (['out'], {}), '(out)\n', (2525, 2530), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2660, 2677), 'functions.do_bw', 'do_bw', (['test_image'], {}), '(test_image)\n', (2665, 2677), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2695, 2705), 'functions.do_bw', 'do_bw', (['out'], {}), '(out)\n', (2700, 2705), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2722, 2739), 'functions.do_bw', 'do_bw', (['second_out'], {}), '(second_out)\n', (2727, 2739), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2866, 2887), 'functions.do_rotate', 'do_rotate', (['test_image'], {}), '(test_image)\n', (2875, 2887), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((2905, 2941), 'functions.read_image', 'read_image', (['"""test_images/rotate.png"""'], {}), "('test_images/rotate.png')\n", (2915, 2941), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3018, 3039), 'functions.do_mirror', 'do_mirror', (['test_image'], {}), '(test_image)\n', (3027, 3039), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3057, 3093), 'functions.read_image', 'read_image', (['"""test_images/mirror.png"""'], {}), "('test_images/mirror.png')\n", (3067, 3093), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3171, 3193), 'functions.do_inverse', 'do_inverse', (['test_image'], {}), '(test_image)\n', (3181, 3193), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3211, 3248), 'functions.read_image', 'read_image', (['"""test_images/inverse.png"""'], {}), "('test_images/inverse.png')\n", (3221, 3248), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3421, 3438), 'functions.do_bw', 'do_bw', (['test_image'], {}), '(test_image)\n', (3426, 3438), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3443, 3483), 'functions.save_image', 'save_image', (['out', '"""test_images/bwOut.png"""'], {}), "(out, 'test_images/bwOut.png')\n", (3453, 3483), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3497, 3532), 'functions.read_image', 'read_image', (['"""test_images/bwOut.png"""'], {}), "('test_images/bwOut.png')\n", (3507, 3532), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3550, 3582), 'functions.read_image', 'read_image', (['"""test_images/bw.png"""'], {}), "('test_images/bw.png')\n", (3560, 3582), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3763, 3796), 'functions.do_lighten', 'do_lighten', (['test_image', 'args_mock'], {}), '(test_image, args_mock)\n', (3773, 3796), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3801, 3846), 'functions.save_image', 'save_image', (['out', '"""test_images/lightenOut.png"""'], {}), "(out, 'test_images/lightenOut.png')\n", (3811, 3846), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3860, 3900), 'functions.read_image', 'read_image', (['"""test_images/lightenOut.png"""'], {}), "('test_images/lightenOut.png')\n", (3870, 3900), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((3918, 3955), 'functions.read_image', 'read_image', (['"""test_images/lighten.png"""'], {}), "('test_images/lighten.png')\n", (3928, 3955), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4135, 4167), 'functions.do_darken', 'do_darken', (['test_image', 'args_mock'], {}), '(test_image, args_mock)\n', (4144, 4167), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4172, 4216), 'functions.save_image', 'save_image', (['out', '"""test_images/darkenOut.png"""'], {}), "(out, 'test_images/darkenOut.png')\n", (4182, 4216), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4230, 4269), 'functions.read_image', 'read_image', (['"""test_images/darkenOut.png"""'], {}), "('test_images/darkenOut.png')\n", (4240, 4269), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4287, 4323), 'functions.read_image', 'read_image', (['"""test_images/darken.png"""'], {}), "('test_images/darken.png')\n", (4297, 4323), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4630, 4651), 'functions.do_mirror', 'do_mirror', (['test_image'], {}), '(test_image)\n', (4639, 4651), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4662, 4676), 'functions.do_rotate', 'do_rotate', (['out'], {}), '(out)\n', (4671, 4676), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4687, 4713), 'functions.do_lighten', 'do_lighten', (['out', 'args_mock'], {}), '(out, args_mock)\n', (4697, 4713), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4724, 4739), 'functions.do_inverse', 'do_inverse', (['out'], {}), '(out)\n', (4734, 4739), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4750, 4775), 'functions.do_darken', 'do_darken', (['out', 'args_mock'], {}), '(out, args_mock)\n', (4759, 4775), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4786, 4796), 'functions.do_bw', 'do_bw', (['out'], {}), '(out)\n', (4791, 4796), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4807, 4822), 'functions.do_sharpen', 'do_sharpen', (['out'], {}), '(out)\n', (4817, 4822), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4833, 4854), 'functions.do_mirror', 'do_mirror', (['test_image'], {}), '(test_image)\n', (4842, 4854), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4865, 4879), 'functions.do_rotate', 'do_rotate', (['out'], {}), '(out)\n', (4874, 4879), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4890, 4916), 'functions.do_lighten', 'do_lighten', (['out', 'args_mock'], {}), '(out, args_mock)\n', (4900, 4916), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4927, 4942), 'functions.do_inverse', 'do_inverse', (['out'], {}), '(out)\n', (4937, 4942), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((4953, 4978), 'functions.do_darken', 'do_darken', (['out', 'args_mock'], {}), '(out, args_mock)\n', (4962, 4978), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((857, 889), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (870, 889), False, 'import pytest\n'), ((899, 973), 'functions.read_image', 'read_image', (['"""nonexistent_file_please_dont_create_file_named_like_this.pls"""'], {}), "('nonexistent_file_please_dont_create_file_named_like_this.pls')\n", (909, 973), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((1930, 1962), 'pytest.raises', 'pytest.raises', (['ArgumentTypeError'], {}), '(ArgumentTypeError)\n', (1943, 1962), False, 'import pytest\n'), ((1972, 1986), 'functions.percentage', 'percentage', (['(-1)'], {}), '(-1)\n', (1982, 1986), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n'), ((738, 776), 'functions.read_image', 'read_image', (['"""test_images/test_img.png"""'], {}), "('test_images/test_img.png')\n", (748, 776), False, 'from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image\n')]
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import flags
sys.path.append("../")
from nmutant_util.utils_file import get_data_file
from nmutant_data.data import get_data
from nmutant_util.utils_imgproc import deprocess_image_1
FLAGS = flags.FLAGS
def ass(datasets, model, samples_path):
"""
:param datasets
:param model
:param samples_path
:return:
"""
tf.reset_default_graph()
X_train, Y_train, X_test, Y_test = get_data(datasets)
X_test = [deprocess_image_1(np.asarray([image])) for image in X_test]
[image_list, image_files, real_labels, predicted_labels] = get_data_file(samples_path)
if datasets=='cifar10':
image_list = [(img*255).reshape(img.shape[0], img.shape[1], img.shape[2]) for img in image_list]
else:
image_list = [(img*255).reshape(img.shape[0], img.shape[1]) for img in image_list]
result = 0
for i in range(len(image_list)):
index = int(image_files[i].split('_')[-4])
result = result + ssim(np.asarray(image_list[i]), np.asarray(X_test[index]))
result = result / len(image_list)
print('average structural similarity is %.4f' % (result))
return result
def ssim(adv, ori):
#change to gray pic
if 3 == len(adv.shape):
adv = adv * np.asarray([0.3 , 0.59, 0.11])
adv = adv.sum(axis=2)
ori = ori * np.asarray([0.3 , 0.59, 0.11])
ori = ori.sum(axis=2)
adv = adv.reshape(-1)
ori = ori.reshape(-1)
c1 = (0.01 * 255) ** 2
c2 = (0.03 * 255) ** 2
c3 = c2 / 2
alpha = 1
beta = 1
gama = 1
miu_x = adv.mean()
miu_y = ori.mean()
theta_x = adv.std(ddof=1)
theta_y = ori.std(ddof=1)
theta_xy = sum((adv - miu_x) * (ori - miu_y)) / (len(adv) - 1)
l = (2 * miu_x * miu_y + c1) / (miu_x ** 2 + miu_y ** 2 + c1)
c = (2 * theta_x * theta_y + c2) / (theta_x ** 2 + theta_y ** 2 + c2)
s = (theta_xy + c3) / (theta_x * theta_y + c3)
return (l ** alpha) * (c ** beta) * (s ** gama)
def main(argv=None):
ass(datasets = FLAGS.datasets,
model=FLAGS.model,
samples_path=FLAGS.samples)
if __name__ == '__main__':
flags.DEFINE_string('datasets', 'mnist', 'The target datasets.')
flags.DEFINE_string('model', 'lenet1', 'The name of model')
flags.DEFINE_string('samples', '../mt_result/cifar10_jsma/adv_jsma', 'The path to load samples.')
tf.app.run()
|
[
"sys.path.append",
"tensorflow.python.platform.flags.DEFINE_string",
"tensorflow.reset_default_graph",
"nmutant_util.utils_file.get_data_file",
"numpy.asarray",
"nmutant_data.data.get_data",
"tensorflow.app.run"
] |
[((251, 273), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (266, 273), False, 'import sys\n'), ((577, 601), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (599, 601), True, 'import tensorflow as tf\n'), ((641, 659), 'nmutant_data.data.get_data', 'get_data', (['datasets'], {}), '(datasets)\n', (649, 659), False, 'from nmutant_data.data import get_data\n'), ((798, 825), 'nmutant_util.utils_file.get_data_file', 'get_data_file', (['samples_path'], {}), '(samples_path)\n', (811, 825), False, 'from nmutant_util.utils_file import get_data_file\n'), ((2338, 2402), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""datasets"""', '"""mnist"""', '"""The target datasets."""'], {}), "('datasets', 'mnist', 'The target datasets.')\n", (2357, 2402), False, 'from tensorflow.python.platform import flags\n'), ((2407, 2466), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""model"""', '"""lenet1"""', '"""The name of model"""'], {}), "('model', 'lenet1', 'The name of model')\n", (2426, 2466), False, 'from tensorflow.python.platform import flags\n'), ((2471, 2572), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""samples"""', '"""../mt_result/cifar10_jsma/adv_jsma"""', '"""The path to load samples."""'], {}), "('samples', '../mt_result/cifar10_jsma/adv_jsma',\n 'The path to load samples.')\n", (2490, 2572), False, 'from tensorflow.python.platform import flags\n'), ((2574, 2586), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (2584, 2586), True, 'import tensorflow as tf\n'), ((692, 711), 'numpy.asarray', 'np.asarray', (['[image]'], {}), '([image])\n', (702, 711), True, 'import numpy as np\n'), ((1461, 1490), 'numpy.asarray', 'np.asarray', (['[0.3, 0.59, 0.11]'], {}), '([0.3, 0.59, 0.11])\n', (1471, 1490), True, 'import numpy as np\n'), ((1542, 1571), 'numpy.asarray', 'np.asarray', (['[0.3, 0.59, 0.11]'], {}), '([0.3, 0.59, 0.11])\n', (1552, 1571), True, 'import numpy as np\n'), ((1194, 1219), 'numpy.asarray', 'np.asarray', (['image_list[i]'], {}), '(image_list[i])\n', (1204, 1219), True, 'import numpy as np\n'), ((1221, 1246), 'numpy.asarray', 'np.asarray', (['X_test[index]'], {}), '(X_test[index])\n', (1231, 1246), True, 'import numpy as np\n')]
|
from datetime import datetime
import traceback
import numpy as np
import face_recognition as fr
import glob
import datetime
import os
from stat import *
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
import cv2
import matplotlib.pyplot as plt
import time
import sys
import re
import dlib
N_CLUSTERS = 8
BATCH_SIZE = 32
UPSAMPLE = 1
FRAME_START = 400
FRAME_END = 1300
FORMAT = '%-20s: %s'
def isDir(path):
mode = os.stat(path)[ST_MODE]
return S_ISDIR(mode)
def extractFaces(frame_paths):
n = len(frame_paths)
face_encodings = []
enc_to_loc = []
frame_batch = []
for frame_counter in range(n):
frame = fr.load_image_file(frame_paths[frame_counter])
frame_batch.append(frame)
if frame_counter != n - 1 and len(frame_batch) != BATCH_SIZE:
continue
loc_batch = fr.batch_face_locations(frame_batch, number_of_times_to_upsample=UPSAMPLE)
for frame_number_in_batch, curr_locations in enumerate(loc_batch):
curr_frame_number = frame_counter + 1 - len(frame_batch) + frame_number_in_batch
curr_frame_path = frame_paths[curr_frame_number]
curr_frame = frame_batch[frame_number_in_batch]
m = ('%-20s %-6d %-3d' % (curr_frame_path, curr_frame_number, len(curr_locations)))
print(FORMAT % ('proc_frame', m))
if len(curr_locations) == 0:
continue
curr_encodings = fr.face_encodings(curr_frame, known_face_locations=curr_locations)
for k in range(len(curr_encodings)):
enc = curr_encodings[k]
loc = curr_locations[k]
enc_to_loc.append({'frame': curr_frame_number, 'loc': loc})
face_encodings.append(enc)
frame_batch = []
return (face_encodings, enc_to_loc)
def detectSpeaker(frame_paths, face_encodings, enc_to_loc, vid_name):
print(FORMAT % ('cluster_inp', len(face_encodings)))
if len(face_encodings) < N_CLUSTERS:
return
enc_arr = np.asanyarray(face_encodings)
k_means = KMeans(n_clusters=N_CLUSTERS).fit(enc_arr)
preds = k_means.predict(enc_arr)
dists = k_means.transform(enc_arr)
largest_cluster = np.argmax(np.unique(preds, return_counts=True)[1])
closest_to_center = np.argmin(dists[:, largest_cluster])
face_loc = enc_to_loc[closest_to_center]
top, right, bottom, left = face_loc['loc']
frame_number = face_loc['frame']
speaker_frame_path = frame_paths[frame_number]
speaker_cluster_center = k_means.cluster_centers_[largest_cluster, :]
speaker_cluster_size = dists[:, largest_cluster].shape[0]
print(FORMAT % ('speaker_clsize', '%d' % (speaker_cluster_size)))
print(FORMAT % ('speaker', '%s -> (%d, %d, %d, %d)' % \
(speaker_frame_path, top, right, bottom, left)))
im = cv2.imread(speaker_frame_path)
cv2.rectangle(im, (left, top), (right, bottom), (0, 255, 0), 3)
cv2.imwrite(vid_name + '.jpg', im)
np.save(vid_name + '.npy', speaker_cluster_center)
return closest_to_center
def clipPaths(paths):
pat = re.compile(r'([0-9]+)\.jpg$')
sorted_paths = ['' for i in range(len(paths))]
for path in paths:
m = pat.search(path)
num = int(m.group(1))
sorted_paths[num-1] = path
return sorted_paths[FRAME_START:FRAME_END]
sep = ''.join(['='] * 70)
def handlePaths(paths):
for path in paths:
if not isDir(path):
continue
tic = time.time()
print(FORMAT % ('start_path', path))
frame_paths = clipPaths(glob.glob(path + '/*'))
face_encodings, enc_to_loc = extractFaces(frame_paths)
vid_name = re.sub(r'^.+\/', '', path)
face_idx = detectSpeaker(frame_paths, face_encodings, enc_to_loc, vid_name)
toc = time.time()
print(FORMAT % ('duration', '%.5f s' % (toc-tic)))
print(FORMAT % ('done', sep))
# Logger to give output to console as well as a file simultaneously.
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
dt = str(datetime.datetime.now().date())
tm = str(datetime.datetime.now().time())
fname = 'detect_speaker_' + dt + '_' + tm.replace(':', '.') + '.log'
self.log = open(fname, "a") # specify file name here
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
#this flush method is needed for python 3 compatibility.
#this handles the flush command by doing nothing.
#you might want to specify some extra behavior here.
pass
sys.stdout = Logger()
sys.stderr = sys.stdout
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Incorrect usage. Needs paths to speaker frames directories.')
sys.exit(1)
paths = sys.argv[1:]
print(FORMAT % ('all_devices', str(dlib.cuda.get_num_devices())))
print(FORMAT % ('gpu_device', str(dlib.cuda.get_device())))
try:
handlePaths(paths)
except Exception as e:
print(FORMAT % ('error', traceback.format_exc()))
|
[
"numpy.argmin",
"cv2.rectangle",
"glob.glob",
"numpy.unique",
"cv2.imwrite",
"face_recognition.face_encodings",
"sklearn.cluster.KMeans",
"traceback.format_exc",
"datetime.datetime.now",
"re.sub",
"numpy.save",
"os.stat",
"face_recognition.batch_face_locations",
"dlib.cuda.get_device",
"sys.exit",
"re.compile",
"numpy.asanyarray",
"dlib.cuda.get_num_devices",
"time.time",
"cv2.imread",
"face_recognition.load_image_file"
] |
[((2125, 2154), 'numpy.asanyarray', 'np.asanyarray', (['face_encodings'], {}), '(face_encodings)\n', (2138, 2154), True, 'import numpy as np\n'), ((2392, 2428), 'numpy.argmin', 'np.argmin', (['dists[:, largest_cluster]'], {}), '(dists[:, largest_cluster])\n', (2401, 2428), True, 'import numpy as np\n'), ((2963, 2993), 'cv2.imread', 'cv2.imread', (['speaker_frame_path'], {}), '(speaker_frame_path)\n', (2973, 2993), False, 'import cv2\n'), ((2999, 3062), 'cv2.rectangle', 'cv2.rectangle', (['im', '(left, top)', '(right, bottom)', '(0, 255, 0)', '(3)'], {}), '(im, (left, top), (right, bottom), (0, 255, 0), 3)\n', (3012, 3062), False, 'import cv2\n'), ((3068, 3102), 'cv2.imwrite', 'cv2.imwrite', (["(vid_name + '.jpg')", 'im'], {}), "(vid_name + '.jpg', im)\n", (3079, 3102), False, 'import cv2\n'), ((3108, 3158), 'numpy.save', 'np.save', (["(vid_name + '.npy')", 'speaker_cluster_center'], {}), "(vid_name + '.npy', speaker_cluster_center)\n", (3115, 3158), True, 'import numpy as np\n'), ((3227, 3256), 're.compile', 're.compile', (['"""([0-9]+)\\\\.jpg$"""'], {}), "('([0-9]+)\\\\.jpg$')\n", (3237, 3256), False, 'import re\n'), ((472, 485), 'os.stat', 'os.stat', (['path'], {}), '(path)\n', (479, 485), False, 'import os\n'), ((704, 750), 'face_recognition.load_image_file', 'fr.load_image_file', (['frame_paths[frame_counter]'], {}), '(frame_paths[frame_counter])\n', (722, 750), True, 'import face_recognition as fr\n'), ((904, 978), 'face_recognition.batch_face_locations', 'fr.batch_face_locations', (['frame_batch'], {'number_of_times_to_upsample': 'UPSAMPLE'}), '(frame_batch, number_of_times_to_upsample=UPSAMPLE)\n', (927, 978), True, 'import face_recognition as fr\n'), ((3630, 3641), 'time.time', 'time.time', ([], {}), '()\n', (3639, 3641), False, 'import time\n'), ((3829, 3855), 're.sub', 're.sub', (['"""^.+\\\\/"""', '""""""', 'path'], {}), "('^.+\\\\/', '', path)\n", (3835, 3855), False, 'import re\n'), ((3956, 3967), 'time.time', 'time.time', ([], {}), '()\n', (3965, 3967), False, 'import time\n'), ((4989, 5000), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4997, 5000), False, 'import sys\n'), ((1522, 1588), 'face_recognition.face_encodings', 'fr.face_encodings', (['curr_frame'], {'known_face_locations': 'curr_locations'}), '(curr_frame, known_face_locations=curr_locations)\n', (1539, 1588), True, 'import face_recognition as fr\n'), ((2170, 2199), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'N_CLUSTERS'}), '(n_clusters=N_CLUSTERS)\n', (2176, 2199), False, 'from sklearn.cluster import KMeans\n'), ((2326, 2362), 'numpy.unique', 'np.unique', (['preds'], {'return_counts': '(True)'}), '(preds, return_counts=True)\n', (2335, 2362), True, 'import numpy as np\n'), ((3721, 3743), 'glob.glob', 'glob.glob', (["(path + '/*')"], {}), "(path + '/*')\n", (3730, 3743), False, 'import glob\n'), ((4243, 4266), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4264, 4266), False, 'import datetime\n'), ((4293, 4316), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4314, 4316), False, 'import datetime\n'), ((5069, 5096), 'dlib.cuda.get_num_devices', 'dlib.cuda.get_num_devices', ([], {}), '()\n', (5094, 5096), False, 'import dlib\n'), ((5139, 5161), 'dlib.cuda.get_device', 'dlib.cuda.get_device', ([], {}), '()\n', (5159, 5161), False, 'import dlib\n'), ((5267, 5289), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (5287, 5289), False, 'import traceback\n')]
|
# Copyright 2019 Google LLC
#
# 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.
"""To perform inference on test set given a trained model."""
import copy
import os
import random
import re
import time
import json
from tqdm import tqdm
import math
import numpy as np
import tensorflow as tf
import model as diag_model
import model_helper
from dialogue import SelfplayDialogue
from utils import dialogue_utils
from utils import misc_utils as utils
from utils.dialogue_utils import task_SP_DISTRIBUTED
def handle_summary(diag_mode, summary_writer, global_step, all_summary,
summary_weight):
"""hanel all summary and combine them together."""
combined = {}
for summary in all_summary:
for key in summary:
if key not in combined:
combined[key] = []
combined[key].append(summary[key])
print('combined', combined)
for key in combined:
combined[key] = np.average(combined[key], weights=summary_weight)
name = diag_mode + '_' + key
utils.add_summary(summary_writer, global_step, name, combined[key])
def pred_action_to_obj(pred_action):
action_obj = {
'name': ' '.join([pred_action[0], pred_action[1]]),
'flight': [''],
'status': ''
}
fl_match = re.match('<fl_(\d+)>', pred_action[2])
if fl_match:
action_obj['flight'][0] = fl_match[0]
status_match = re.match('<st_(\w+)>', pred_action[3])
if status_match:
action_obj['status'] = status_match[0]
return action_obj
def utterance_to_dialogue(utt):
stack = ""
dialogue = []
for s in utt:
if s == "<t1>" or s == "<t2>":
if stack:
dialogue.append(stack)
stack = ""
stack += "customer:" if s == "<t1>" else "agent:"
elif s == "<eod>":
break
else:
stack += " " + s
if stack:
dialogue.append(stack)
return dialogue
def output_generated_data(generated_data, eval_out):
bs_intent, bs_pred_action, bs_truth_action, utt_arr, bs_kb = generated_data
for intent, pred_action, true_action, utterance, kb in zip(
bs_intent, bs_pred_action, bs_truth_action, utt_arr, bs_kb):
generated_obj = {
# 'intent': intent,
'pred_action': pred_action_to_obj(pred_action),
# 'action': true_action,
'dialogue': utterance_to_dialogue(utterance),
# 'kb': kb
}
# print('generated_obj', generated_obj)
eval_out.write(json.dumps(generated_obj) + '\n')
def single_worker_selfplay(mutable_model, immutable_model, mutable_sess,
immutable_sess, selfplay_data_file, selfplay_kb_file,
global_step, hparams, summary_writer):
"""selfplay with a single worker.
This is preminarily used for self play
evaluation.
"""
dialogue_mode = dialogue_utils.mode_self_play_dialogue_eval
# Read self play data
selfplay_data = dialogue_utils.load_data(selfplay_data_file)
selfplay_kb = dialogue_utils.load_data(selfplay_kb_file)
# construct dialogue object
dialogue = SelfplayDialogue(
mutable_model,
immutable_model,
mutable_sess,
immutable_sess,
hparams.max_dialogue_turns,
hparams.train_threadhold,
hparams.start_of_turn1,
hparams.start_of_turn2,
hparams.end_of_dialogue,
summary_writer=summary_writer,
dialogue_mode=dialogue_mode,
hparams=hparams)
batch_size = dialogue.self_play_eval_batch_size
assert batch_size <= len(selfplay_data)
loaded_mutable, _ = load_self_play_model(
dialogue.mutable_model, dialogue.mutable_sess, 'mutable',
hparams.self_play_pretrain_dir, hparams.out_dir)
loaded_immutable, _ = load_self_play_model(
dialogue.immutable_model, dialogue.immutable_sess, 'immutable',
hparams.self_play_pretrain_dir, hparams.out_dir)
worker_step = 0
all_summary = []
summary_weight = [] # used in combination with all_summary
# max_eval_per_flip = 100000
# We flip the role of the agent for exactly two times. In the first iteration
# when flip = 0, mutable model will be agent 1 and immutable model will be
# agent 2. The other way around when flip = 1.
start_time = time.time()
num_flips_for_initial_speaker = 2
with tf.gfile.GFile(hparams.selfplay_eval_output_file, 'w') as selfplay_out:
print('flip 1')
for flip in range(num_flips_for_initial_speaker):
# epoch = -1
i = len(selfplay_data) # force shuffling at the beginning
agent1, agent2, _ = dialogue.flip_agent(
(loaded_mutable, mutable_sess, dialogue.mutable_handles),
(loaded_immutable, immutable_sess, dialogue.immutable_handles), flip)
# only eval one epoch
# while epoch <= 0:
# print(i, max_eval_per_flip)
# if i * batch_size >= len(selfplay_data): # reacehd the end
input_data = list(zip(selfplay_data, selfplay_kb))
# we don't shuffle in evaluation
# random.shuffle(input_data) # random shuffle input data
# i = 0
selfplay_data, selfplay_kb = list(zip(*input_data))
# epoch += 1
ceil = int(math.ceil(len(selfplay_data) *1.0 / batch_size))
for i in tqdm(list(range(0, ceil))):
start_ind = i * batch_size
end_ind = min(i * batch_size + batch_size, len(selfplay_data))
batch_data = selfplay_data[start_ind:end_ind]
batch_kb = selfplay_kb[start_ind:end_ind]
# we indicate to let agent1 to talk first. Keep in mind that we will
# swap between agent1 and agent2.
speaker = flip % 2
generated_data, _, summary = dialogue.talk(hparams.max_dialogue_len,
batch_data, batch_kb, agent1,
agent2, worker_step,
end_ind - start_ind, speaker)
output_generated_data(generated_data, selfplay_out)
all_summary.append(summary)
# number of elements processed
summary_weight.append(end_ind - start_ind)
worker_step += 1
handle_summary(dialogue_mode, summary_writer, global_step, all_summary,
summary_weight)
end_time = time.time()
print('finished')
utils.add_summary(summary_writer, global_step, dialogue_mode + '_time',
end_time - start_time) # step wise summary
def load_self_play_model(model, sess, identity, supervised_learning_path,
self_play_path):
"""This function loads the self-play model.
It will first check the self play
directory. If it's empty it will then load the pre-trained model from
supervised learning.
"""
ckpt = tf.train.latest_checkpoint(self_play_path)
# first try self_play out dir
if ckpt:
print('{0} restore from self_play path at {1}'.format(
identity, self_play_path))
with model.graph.as_default():
model_helper.full_restore(sess, ckpt)
# if model doesn't exist then load supervised learning model
else:
print('{0} restore from supervised learning at {1}'.format(
identity, supervised_learning_path))
ckpt = tf.train.latest_checkpoint(supervised_learning_path)
assert ckpt
with model.graph.as_default():
# first do initialization to make sure that all variables are initialized
sess.run(tf.global_variables_initializer())
sess.run(tf.tables_initializer())
model_helper.full_restore(sess, ckpt)
return model, sess
def self_play_eval_fn(hparams,
identity,
num_workers=1,
jobid=0,
scope=None,
target_session=''):
"""This is the single worker self play.
Mostly used for self play
evaluation. identity is used here to distinguish between workers.
"""
model_creator = diag_model.Model
mutable_model = model_helper.create_selfplay_model(
model_creator,
True, # mutable is True
num_workers,
jobid,
hparams=hparams,
scope=scope)
immutable_model = model_helper.create_selfplay_model(
model_creator,
False, # mutable is False
num_workers,
jobid,
hparams=hparams,
scope=scope)
mutable_sess = tf.Session(
graph=mutable_model.graph,
config=tf.ConfigProto(
allow_soft_placement=True, device_count={'GPU': hparams.num_gpus}))
immutable_sess = tf.Session(
graph=immutable_model.graph,
config=tf.ConfigProto(
allow_soft_placement=True, device_count={'GPU': hparams.num_gpus}))
# number of steps per external eval
steps_per_external_eval = 10
# force conducting a self play at the beginning
last_external_eval_step = -1 * steps_per_external_eval
print('hparams.self_play_pretrain_dir=', hparams.self_play_pretrain_dir)
print('steps_per_external_eval=', steps_per_external_eval)
writer_path = os.path.join(hparams.out_dir,
identity + hparams.task_type + '_log')
summary_writer = tf.summary.FileWriter(writer_path, mutable_sess.graph)
print('summary_writer estabilished at', writer_path)
# waiting for checkpoints and loop forever
latest_ckpt = None
while True:
latest_ckpt = tf.contrib.training.wait_for_new_checkpoint(
hparams.out_dir, latest_ckpt)
print('got checkpoint', latest_ckpt)
# get the global_step variable first
with mutable_model.graph.as_default():
# first initialize to avoid encountering missing component for adam optimizer
_, global_step = model_helper.create_or_load_model(
mutable_model.model, hparams.out_dir, mutable_sess, hparams.task_type)
# valid evaluation step
if (not hparams.eval_forever) or (global_step - last_external_eval_step >=
steps_per_external_eval):
# if eval_forever is disabled, we will do one selfplay evalation
# otherwise, we will wait until certain number of timesteps are elapsed.
last_external_eval_step = global_step
print('do single worker evaluation')
single_worker_selfplay(mutable_model, immutable_model, mutable_sess,
immutable_sess, hparams.self_play_eval_data,
hparams.self_play_eval_kb, global_step, hparams,
summary_writer)
else:
print('Wait until steps_per_external_eval is reached.', global_step,
last_external_eval_step, steps_per_external_eval)
if not hparams.eval_forever:
break # if eval_foever is disabled, we only evaluate once
mutable_sess.close()
immutable_sess.close()
def multi_worker_selfplay(hparams,
identity,
scope=None,
target_session='',
is_chief=True,
ps_tasks=0,
num_workers=1,
jobid=0,
startup_delay_steps=0):
"""This is the multi worker selfplay, mostly used for self play
distributed training.
identity is used.
"""
immutable_model_reload_freq = hparams.immutable_model_reload_freq
# 1. models and summary writer
model_creator = diag_model.Model
extra_args = model_helper.ExtraArgs(
single_cell_fn=None,
model_device_fn=tf.train.replica_device_setter(ps_tasks),
attention_mechanism_fn=None)
mutable_model = model_helper.create_selfplay_model(
model_creator,
is_mutable=True,
num_workers=num_workers,
jobid=jobid,
hparams=hparams,
scope=scope,
extra_args=extra_args)
immutable_hparams = copy.deepcopy(hparams)
immutable_hparams.num_gpus = 0
immutable_model = model_helper.create_selfplay_model(
model_creator,
is_mutable=False,
num_workers=num_workers,
jobid=jobid,
hparams=immutable_hparams,
scope=scope)
if hparams.self_play_immutable_gpu:
print('using GPU for immutable')
immutable_sess = tf.Session(
graph=immutable_model.graph,
config=tf.ConfigProto(allow_soft_placement=True))
else:
print('not using GPU for immutable')
immutable_sess = tf.Session(
graph=immutable_model.graph,
config=tf.ConfigProto(
allow_soft_placement=True, device_count={'GPU': 0}))
immutable_model, immutable_sess = load_self_play_model(
immutable_model, immutable_sess, 'immutable',
hparams.self_play_pretrain_dir, hparams.out_dir)
global_step = immutable_model.model.global_step.eval(session=immutable_sess)
if is_chief:
ckpt = tf.train.latest_checkpoint(hparams.out_dir)
if not ckpt:
print('global_step, saving pretrain model to hparams.out_dir',
global_step, hparams.out_dir)
immutable_model.model.saver.save( # this is the prevent adam error
immutable_sess,
os.path.join(hparams.out_dir, 'dialogue.ckpt'),
global_step=global_step)
print('save finished')
if is_chief:
summary_writer_path = os.path.join(hparams.out_dir,
identity + task_SP_DISTRIBUTED + '_log')
summary_writer = tf.summary.FileWriter(summary_writer_path,
mutable_model.graph)
print('summary writer established at', summary_writer_path)
else:
summary_writer = None
# 2. supervisor and sessions
sv = tf.train.Supervisor(
graph=mutable_model.graph,
is_chief=is_chief,
saver=mutable_model.model.saver,
save_model_secs=0, # disable automatic save checkpoints
summary_op=None,
logdir=hparams.out_dir,
checkpoint_basename='dialogue.ckpt')
mutable_config = utils.get_config_proto(
log_device_placement=hparams.log_device_placement,
allow_soft_placement=True)
mutable_config.device_count['GPU'] = hparams.num_gpus
mutable_sess = sv.prepare_or_wait_for_session(
target_session,
config=mutable_config)
# 3. additiona preparations
global_step = mutable_model.model.global_step.eval(session=mutable_sess)
while global_step < (jobid * (jobid + 1) * startup_delay_steps / 2):
time.sleep(1)
global_step = mutable_model.model.global_step.eval(session=mutable_sess)
# save first model
if is_chief:
print('saving the first checkpoint to', hparams.out_dir)
mutable_model.model.saver.save(
mutable_sess,
os.path.join(hparams.out_dir, 'dialogue.ckpt'),
global_step=global_step)
last_save_step = global_step
# Read data
selfplay_data = dialogue_utils.load_data(hparams.self_play_train_data)
selfplay_kb = dialogue_utils.load_data(hparams.self_play_train_kb)
dialogue = SelfplayDialogue(
mutable_model,
immutable_model,
mutable_sess,
immutable_sess,
hparams.max_dialogue_turns,
hparams.train_threadhold,
hparams.start_of_turn1,
hparams.start_of_turn2,
hparams.end_of_dialogue,
summary_writer=summary_writer,
dialogue_mode=task_SP_DISTRIBUTED,
hparams=hparams)
# 4. main loop
last_immmutable_model_reload = global_step
last_save_step = global_step
batch_size = dialogue.batch_size
assert batch_size <= len(selfplay_data)
# this is the start point of the self-play data. force shuffling at the beginning
i = len(selfplay_data)
train_stats = [0, 0]
while global_step < hparams.num_self_play_train_steps + hparams.num_train_steps:
# a. reload immutable model, muttable will be automated managed by supervisor
if immutable_model_reload_freq > 0 and global_step - last_immmutable_model_reload > immutable_model_reload_freq:
immutable_model, immutable_sess = load_self_play_model(
immutable_model, immutable_sess, 'immutable',
hparams.self_play_pretrain_dir, hparams.out_dir)
last_immmutable_model_reload = global_step
# b. possiblely flip between speakers (or roll out models),
# based on either a random policy or by step counts
agent1, agent2, mutable_agent_index = dialogue.flip_agent(
(mutable_model, mutable_sess, dialogue.mutable_handles),
(immutable_model, immutable_sess, dialogue.immutable_handles))
train_stats[mutable_agent_index] += 1
# read selfplay data
start_time = time.time()
if i * batch_size + batch_size > len(selfplay_data): # reached the end
input_data = list(zip(selfplay_data, selfplay_kb))
random.shuffle(input_data) # random shuffle input data
i = 0
selfplay_data, selfplay_kb = list(zip(*input_data))
start_ind, end_ind = i * batch_size, i * batch_size + batch_size
batch_data, batch_kb = selfplay_data[start_ind:end_ind], selfplay_kb[
start_ind:end_ind]
train_example, _, _ = dialogue.talk(hparams.max_dialogue_len, batch_data,
batch_kb, agent1, agent2, global_step,
batch_size)
possible_global_step = dialogue.maybe_train(
train_example, mutable_agent_index, global_step, force=True)
if possible_global_step:
global_step = possible_global_step
if is_chief and global_step - last_save_step > hparams.self_play_dist_save_freq:
mutable_model.model.saver.save(
mutable_sess,
os.path.join(hparams.out_dir, 'dialogue.ckpt'),
global_step=global_step)
last_save_step = global_step
end_time = time.time()
if is_chief:
utils.add_summary(summary_writer, global_step,
task_SP_DISTRIBUTED + '_' + 'time',
end_time - start_time)
utils.add_summary(summary_writer, global_step,
task_SP_DISTRIBUTED + '_' + 'train_ratio',
train_stats[0] * 1.0 / (train_stats[1] + 0.1))
i += 1
if is_chief:
summary_writer.close()
mutable_sess.close()
immutable_sess.close()
|
[
"random.shuffle",
"json.dumps",
"tensorflow.ConfigProto",
"tensorflow.train.latest_checkpoint",
"tensorflow.tables_initializer",
"os.path.join",
"utils.misc_utils.add_summary",
"tensorflow.summary.FileWriter",
"tensorflow.contrib.training.wait_for_new_checkpoint",
"copy.deepcopy",
"numpy.average",
"model_helper.create_or_load_model",
"tensorflow.global_variables_initializer",
"dialogue.SelfplayDialogue",
"re.match",
"time.sleep",
"tensorflow.gfile.GFile",
"tensorflow.train.replica_device_setter",
"utils.dialogue_utils.load_data",
"utils.misc_utils.get_config_proto",
"model_helper.full_restore",
"time.time",
"tensorflow.train.Supervisor",
"model_helper.create_selfplay_model"
] |
[((1737, 1776), 're.match', 're.match', (['"""<fl_(\\\\d+)>"""', 'pred_action[2]'], {}), "('<fl_(\\\\d+)>', pred_action[2])\n", (1745, 1776), False, 'import re\n'), ((1858, 1897), 're.match', 're.match', (['"""<st_(\\\\w+)>"""', 'pred_action[3]'], {}), "('<st_(\\\\w+)>', pred_action[3])\n", (1866, 1897), False, 'import re\n'), ((3415, 3459), 'utils.dialogue_utils.load_data', 'dialogue_utils.load_data', (['selfplay_data_file'], {}), '(selfplay_data_file)\n', (3439, 3459), False, 'from utils import dialogue_utils\n'), ((3476, 3518), 'utils.dialogue_utils.load_data', 'dialogue_utils.load_data', (['selfplay_kb_file'], {}), '(selfplay_kb_file)\n', (3500, 3518), False, 'from utils import dialogue_utils\n'), ((3563, 3862), 'dialogue.SelfplayDialogue', 'SelfplayDialogue', (['mutable_model', 'immutable_model', 'mutable_sess', 'immutable_sess', 'hparams.max_dialogue_turns', 'hparams.train_threadhold', 'hparams.start_of_turn1', 'hparams.start_of_turn2', 'hparams.end_of_dialogue'], {'summary_writer': 'summary_writer', 'dialogue_mode': 'dialogue_mode', 'hparams': 'hparams'}), '(mutable_model, immutable_model, mutable_sess,\n immutable_sess, hparams.max_dialogue_turns, hparams.train_threadhold,\n hparams.start_of_turn1, hparams.start_of_turn2, hparams.end_of_dialogue,\n summary_writer=summary_writer, dialogue_mode=dialogue_mode, hparams=hparams\n )\n', (3579, 3862), False, 'from dialogue import SelfplayDialogue\n'), ((4699, 4710), 'time.time', 'time.time', ([], {}), '()\n', (4708, 4710), False, 'import time\n'), ((6698, 6709), 'time.time', 'time.time', ([], {}), '()\n', (6707, 6709), False, 'import time\n'), ((6732, 6831), 'utils.misc_utils.add_summary', 'utils.add_summary', (['summary_writer', 'global_step', "(dialogue_mode + '_time')", '(end_time - start_time)'], {}), "(summary_writer, global_step, dialogue_mode + '_time', \n end_time - start_time)\n", (6749, 6831), True, 'from utils import misc_utils as utils\n'), ((7180, 7222), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['self_play_path'], {}), '(self_play_path)\n', (7206, 7222), True, 'import tensorflow as tf\n'), ((8377, 8486), 'model_helper.create_selfplay_model', 'model_helper.create_selfplay_model', (['model_creator', '(True)', 'num_workers', 'jobid'], {'hparams': 'hparams', 'scope': 'scope'}), '(model_creator, True, num_workers, jobid,\n hparams=hparams, scope=scope)\n', (8411, 8486), False, 'import model_helper\n'), ((8559, 8669), 'model_helper.create_selfplay_model', 'model_helper.create_selfplay_model', (['model_creator', '(False)', 'num_workers', 'jobid'], {'hparams': 'hparams', 'scope': 'scope'}), '(model_creator, False, num_workers, jobid,\n hparams=hparams, scope=scope)\n', (8593, 8669), False, 'import model_helper\n'), ((9396, 9464), 'os.path.join', 'os.path.join', (['hparams.out_dir', "(identity + hparams.task_type + '_log')"], {}), "(hparams.out_dir, identity + hparams.task_type + '_log')\n", (9408, 9464), False, 'import os\n'), ((9513, 9567), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['writer_path', 'mutable_sess.graph'], {}), '(writer_path, mutable_sess.graph)\n', (9534, 9567), True, 'import tensorflow as tf\n'), ((11925, 12090), 'model_helper.create_selfplay_model', 'model_helper.create_selfplay_model', (['model_creator'], {'is_mutable': '(True)', 'num_workers': 'num_workers', 'jobid': 'jobid', 'hparams': 'hparams', 'scope': 'scope', 'extra_args': 'extra_args'}), '(model_creator, is_mutable=True,\n num_workers=num_workers, jobid=jobid, hparams=hparams, scope=scope,\n extra_args=extra_args)\n', (11959, 12090), False, 'import model_helper\n'), ((12148, 12170), 'copy.deepcopy', 'copy.deepcopy', (['hparams'], {}), '(hparams)\n', (12161, 12170), False, 'import copy\n'), ((12224, 12378), 'model_helper.create_selfplay_model', 'model_helper.create_selfplay_model', (['model_creator'], {'is_mutable': '(False)', 'num_workers': 'num_workers', 'jobid': 'jobid', 'hparams': 'immutable_hparams', 'scope': 'scope'}), '(model_creator, is_mutable=False,\n num_workers=num_workers, jobid=jobid, hparams=immutable_hparams, scope=\n scope)\n', (12258, 12378), False, 'import model_helper\n'), ((13909, 14114), 'tensorflow.train.Supervisor', 'tf.train.Supervisor', ([], {'graph': 'mutable_model.graph', 'is_chief': 'is_chief', 'saver': 'mutable_model.model.saver', 'save_model_secs': '(0)', 'summary_op': 'None', 'logdir': 'hparams.out_dir', 'checkpoint_basename': '"""dialogue.ckpt"""'}), "(graph=mutable_model.graph, is_chief=is_chief, saver=\n mutable_model.model.saver, save_model_secs=0, summary_op=None, logdir=\n hparams.out_dir, checkpoint_basename='dialogue.ckpt')\n", (13928, 14114), True, 'import tensorflow as tf\n'), ((14206, 14310), 'utils.misc_utils.get_config_proto', 'utils.get_config_proto', ([], {'log_device_placement': 'hparams.log_device_placement', 'allow_soft_placement': '(True)'}), '(log_device_placement=hparams.log_device_placement,\n allow_soft_placement=True)\n', (14228, 14310), True, 'from utils import misc_utils as utils\n'), ((15060, 15114), 'utils.dialogue_utils.load_data', 'dialogue_utils.load_data', (['hparams.self_play_train_data'], {}), '(hparams.self_play_train_data)\n', (15084, 15114), False, 'from utils import dialogue_utils\n'), ((15131, 15183), 'utils.dialogue_utils.load_data', 'dialogue_utils.load_data', (['hparams.self_play_train_kb'], {}), '(hparams.self_play_train_kb)\n', (15155, 15183), False, 'from utils import dialogue_utils\n'), ((15198, 15502), 'dialogue.SelfplayDialogue', 'SelfplayDialogue', (['mutable_model', 'immutable_model', 'mutable_sess', 'immutable_sess', 'hparams.max_dialogue_turns', 'hparams.train_threadhold', 'hparams.start_of_turn1', 'hparams.start_of_turn2', 'hparams.end_of_dialogue'], {'summary_writer': 'summary_writer', 'dialogue_mode': 'task_SP_DISTRIBUTED', 'hparams': 'hparams'}), '(mutable_model, immutable_model, mutable_sess,\n immutable_sess, hparams.max_dialogue_turns, hparams.train_threadhold,\n hparams.start_of_turn1, hparams.start_of_turn2, hparams.end_of_dialogue,\n summary_writer=summary_writer, dialogue_mode=task_SP_DISTRIBUTED,\n hparams=hparams)\n', (15214, 15502), False, 'from dialogue import SelfplayDialogue\n'), ((1399, 1448), 'numpy.average', 'np.average', (['combined[key]'], {'weights': 'summary_weight'}), '(combined[key], weights=summary_weight)\n', (1409, 1448), True, 'import numpy as np\n'), ((1486, 1553), 'utils.misc_utils.add_summary', 'utils.add_summary', (['summary_writer', 'global_step', 'name', 'combined[key]'], {}), '(summary_writer, global_step, name, combined[key])\n', (1503, 1553), True, 'from utils import misc_utils as utils\n'), ((4754, 4808), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['hparams.selfplay_eval_output_file', '"""w"""'], {}), "(hparams.selfplay_eval_output_file, 'w')\n", (4768, 4808), True, 'import tensorflow as tf\n'), ((7630, 7682), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['supervised_learning_path'], {}), '(supervised_learning_path)\n', (7656, 7682), True, 'import tensorflow as tf\n'), ((9722, 9795), 'tensorflow.contrib.training.wait_for_new_checkpoint', 'tf.contrib.training.wait_for_new_checkpoint', (['hparams.out_dir', 'latest_ckpt'], {}), '(hparams.out_dir, latest_ckpt)\n', (9765, 9795), True, 'import tensorflow as tf\n'), ((13098, 13141), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['hparams.out_dir'], {}), '(hparams.out_dir)\n', (13124, 13141), True, 'import tensorflow as tf\n'), ((13534, 13604), 'os.path.join', 'os.path.join', (['hparams.out_dir', "(identity + task_SP_DISTRIBUTED + '_log')"], {}), "(hparams.out_dir, identity + task_SP_DISTRIBUTED + '_log')\n", (13546, 13604), False, 'import os\n'), ((13665, 13728), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['summary_writer_path', 'mutable_model.graph'], {}), '(summary_writer_path, mutable_model.graph)\n', (13686, 13728), True, 'import tensorflow as tf\n'), ((14658, 14671), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (14668, 14671), False, 'import time\n'), ((16775, 16786), 'time.time', 'time.time', ([], {}), '()\n', (16784, 16786), False, 'import time\n'), ((17910, 17921), 'time.time', 'time.time', ([], {}), '()\n', (17919, 17921), False, 'import time\n'), ((7401, 7438), 'model_helper.full_restore', 'model_helper.full_restore', (['sess', 'ckpt'], {}), '(sess, ckpt)\n', (7426, 7438), False, 'import model_helper\n'), ((7910, 7947), 'model_helper.full_restore', 'model_helper.full_restore', (['sess', 'ckpt'], {}), '(sess, ckpt)\n', (7935, 7947), False, 'import model_helper\n'), ((8799, 8885), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'device_count': "{'GPU': hparams.num_gpus}"}), "(allow_soft_placement=True, device_count={'GPU': hparams.\n num_gpus})\n", (8813, 8885), True, 'import tensorflow as tf\n'), ((8972, 9058), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'device_count': "{'GPU': hparams.num_gpus}"}), "(allow_soft_placement=True, device_count={'GPU': hparams.\n num_gpus})\n", (8986, 9058), True, 'import tensorflow as tf\n'), ((10037, 10145), 'model_helper.create_or_load_model', 'model_helper.create_or_load_model', (['mutable_model.model', 'hparams.out_dir', 'mutable_sess', 'hparams.task_type'], {}), '(mutable_model.model, hparams.out_dir,\n mutable_sess, hparams.task_type)\n', (10070, 10145), False, 'import model_helper\n'), ((11829, 11869), 'tensorflow.train.replica_device_setter', 'tf.train.replica_device_setter', (['ps_tasks'], {}), '(ps_tasks)\n', (11859, 11869), True, 'import tensorflow as tf\n'), ((14913, 14959), 'os.path.join', 'os.path.join', (['hparams.out_dir', '"""dialogue.ckpt"""'], {}), "(hparams.out_dir, 'dialogue.ckpt')\n", (14925, 14959), False, 'import os\n'), ((16926, 16952), 'random.shuffle', 'random.shuffle', (['input_data'], {}), '(input_data)\n', (16940, 16952), False, 'import random\n'), ((17946, 18055), 'utils.misc_utils.add_summary', 'utils.add_summary', (['summary_writer', 'global_step', "(task_SP_DISTRIBUTED + '_' + 'time')", '(end_time - start_time)'], {}), "(summary_writer, global_step, task_SP_DISTRIBUTED + '_' +\n 'time', end_time - start_time)\n", (17963, 18055), True, 'from utils import misc_utils as utils\n'), ((18106, 18246), 'utils.misc_utils.add_summary', 'utils.add_summary', (['summary_writer', 'global_step', "(task_SP_DISTRIBUTED + '_' + 'train_ratio')", '(train_stats[0] * 1.0 / (train_stats[1] + 0.1))'], {}), "(summary_writer, global_step, task_SP_DISTRIBUTED + '_' +\n 'train_ratio', train_stats[0] * 1.0 / (train_stats[1] + 0.1))\n", (18123, 18246), True, 'from utils import misc_utils as utils\n'), ((2956, 2981), 'json.dumps', 'json.dumps', (['generated_obj'], {}), '(generated_obj)\n', (2966, 2981), False, 'import json\n'), ((7829, 7862), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (7860, 7862), True, 'import tensorflow as tf\n'), ((7879, 7902), 'tensorflow.tables_initializer', 'tf.tables_initializer', ([], {}), '()\n', (7900, 7902), True, 'import tensorflow as tf\n'), ((12568, 12609), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (12582, 12609), True, 'import tensorflow as tf\n'), ((12745, 12811), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'device_count': "{'GPU': 0}"}), "(allow_soft_placement=True, device_count={'GPU': 0})\n", (12759, 12811), True, 'import tensorflow as tf\n'), ((13380, 13426), 'os.path.join', 'os.path.join', (['hparams.out_dir', '"""dialogue.ckpt"""'], {}), "(hparams.out_dir, 'dialogue.ckpt')\n", (13392, 13426), False, 'import os\n'), ((17777, 17823), 'os.path.join', 'os.path.join', (['hparams.out_dir', '"""dialogue.ckpt"""'], {}), "(hparams.out_dir, 'dialogue.ckpt')\n", (17789, 17823), False, 'import os\n')]
|
import logging
import time
import numpy as np
from param_net.param_fcnet import ParamFCNetRegression
from keras.losses import mean_squared_error
from keras import backend as K
from smac.tae.execute_func import ExecuteTAFuncDict
from smac.scenario.scenario import Scenario
from smac.facade.smac_facade import SMAC
from mini_autonet.intensification.intensification import Intensifier
from mini_autonet.tae.simple_tae import SimpleTAFunc
from sklearn.preprocessing import StandardScaler
from ConfigSpace.configuration_space import Configuration
from ConfigSpace.util import fix_types
class DNN(object):
def __init__(self, num_layers_range:list=[1,4,10],
use_dropout:bool=False,
use_l2_regularization:bool=False):
self.logger = logging.getLogger("AutoNet")
self.num_layers_range = num_layers_range
self.use_dropout = use_dropout
self.use_l2_regularization = use_l2_regularization
self.scalerX = StandardScaler()
self.scalerY = StandardScaler()
def fit(self, X, y,
max_epochs:int,
runcount_limit:int=100,
wc_limit:int=60,
config:Configuration=None,
seed:int=12345):
X_all = None
y_all = None
for idx, (X_q, y_q) in enumerate(zip(X,y)):
if idx == 0:
X_all = X_q
y_all = y_q
else:
X_all = np.vstack([X_all, X_q])
y_all = np.hstack([y_all, y_q])
def obj_func(config, instance=None, seed=None, pc=None):
# continuing training if pc is given
# otherwise, construct new DNN
models = []
losses = []
for model_idx, [train_idx, valid_idx] in enumerate([[0,3],[3,0],[1,2],[2,1]]):
X_train = X[train_idx]
y_train = y[train_idx]
X_train = self.scalerX.fit_transform(X_train)
y_train = np.log10(y_train)
y_train = self.scalerY.fit_transform(y_train.reshape(-1, 1))[:,0]
X_valid, y_valid = X_all, y_all
X_valid = self.scalerX.transform(X_valid)
y_valid = np.log10(y_valid)
y_valid = self.scalerY.transform(y_valid.reshape(-1, 1))[:,0]
if pc is None:
if model_idx == 0:
K.clear_session()
model = ParamFCNetRegression(config=config, n_feat=X_train.shape[1],
expected_num_epochs=max_epochs,
n_outputs=1,
verbose=1)
else:
model = pc[model_idx]
history = model.train(X_train=X_train, y_train=y_train,
X_valid=X_valid, y_valid=y_valid,
n_epochs=1)
models.append(model)
final_loss = history["val_loss"][-1]
losses.append(final_loss)
return np.mean(losses), {"model": models}
taf = SimpleTAFunc(obj_func)
cs = ParamFCNetRegression.get_config_space(num_layers_range=self.num_layers_range,
use_l2_regularization=self.use_l2_regularization,
use_dropout=self.use_dropout)
print(cs)
ac_scenario = Scenario({"run_obj": "quality", # we optimize quality
"runcount-limit": max_epochs*runcount_limit,
"wallclock-limit": wc_limit,
"cost_for_crash": 10,
"cs": cs,
"deterministic": "true",
"abort_on_first_run_crash": False,
"output-dir": ""
})
intensifier = Intensifier(tae_runner=taf, stats=None,
traj_logger=None,
rng=np.random.RandomState(42),
run_limit=100,
max_epochs=max_epochs)
if isinstance(config, dict):
config = fix_types(configuration=dict, configuration_space=cs)
config = Configuration(configuration_space=cs, values=config)
elif runcount_limit==1:
config = cs.get_default_configuration()
else:
smac = SMAC(scenario=ac_scenario,
tae_runner=taf,
rng=np.random.RandomState(seed),
intensifier=intensifier)
smac.solver.runhistory.overwrite_existing_runs = True
config = smac.optimize()
print("Final Incumbent")
print(config)
X_all = self.scalerX.fit_transform(X_all)
y_all = np.log10(y_all)
y_all = self.scalerY.fit_transform(y_all.reshape(-1, 1))[:,0]
K.clear_session()
start_time = time.time()
model = ParamFCNetRegression(config=config, n_feat=X_all.shape[1],
expected_num_epochs=max_epochs,
n_outputs=1,
verbose=1)
history = model.train(X_train=X_all, y_train=y_all,
X_valid=X_all, y_valid=y_all,
n_epochs=max_epochs)
print("Training Time: %f" %(time.time() - start_time))
self.model = model
def predict(self, X_test):
X_test = self.scalerX.transform(X_test)
y_pred = self.model.predict(X_test)
y_pred = self.scalerY.inverse_transform(y_pred)
y_pred = 10**y_pred
y_pred = np.maximum(0.0005,y_pred)
return y_pred
|
[
"sklearn.preprocessing.StandardScaler",
"keras.backend.clear_session",
"numpy.maximum",
"param_net.param_fcnet.ParamFCNetRegression",
"mini_autonet.tae.simple_tae.SimpleTAFunc",
"ConfigSpace.util.fix_types",
"numpy.random.RandomState",
"time.time",
"param_net.param_fcnet.ParamFCNetRegression.get_config_space",
"numpy.hstack",
"smac.scenario.scenario.Scenario",
"numpy.mean",
"ConfigSpace.configuration_space.Configuration",
"numpy.vstack",
"numpy.log10",
"logging.getLogger"
] |
[((784, 812), 'logging.getLogger', 'logging.getLogger', (['"""AutoNet"""'], {}), "('AutoNet')\n", (801, 812), False, 'import logging\n'), ((1006, 1022), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1020, 1022), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1046, 1062), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1060, 1062), False, 'from sklearn.preprocessing import StandardScaler\n'), ((3386, 3408), 'mini_autonet.tae.simple_tae.SimpleTAFunc', 'SimpleTAFunc', (['obj_func'], {}), '(obj_func)\n', (3398, 3408), False, 'from mini_autonet.tae.simple_tae import SimpleTAFunc\n'), ((3422, 3588), 'param_net.param_fcnet.ParamFCNetRegression.get_config_space', 'ParamFCNetRegression.get_config_space', ([], {'num_layers_range': 'self.num_layers_range', 'use_l2_regularization': 'self.use_l2_regularization', 'use_dropout': 'self.use_dropout'}), '(num_layers_range=self.\n num_layers_range, use_l2_regularization=self.use_l2_regularization,\n use_dropout=self.use_dropout)\n', (3459, 3588), False, 'from param_net.param_fcnet import ParamFCNetRegression\n'), ((3742, 3972), 'smac.scenario.scenario.Scenario', 'Scenario', (["{'run_obj': 'quality', 'runcount-limit': max_epochs * runcount_limit,\n 'wallclock-limit': wc_limit, 'cost_for_crash': 10, 'cs': cs,\n 'deterministic': 'true', 'abort_on_first_run_crash': False,\n 'output-dir': ''}"], {}), "({'run_obj': 'quality', 'runcount-limit': max_epochs *\n runcount_limit, 'wallclock-limit': wc_limit, 'cost_for_crash': 10, 'cs':\n cs, 'deterministic': 'true', 'abort_on_first_run_crash': False,\n 'output-dir': ''})\n", (3750, 3972), False, 'from smac.scenario.scenario import Scenario\n'), ((5197, 5212), 'numpy.log10', 'np.log10', (['y_all'], {}), '(y_all)\n', (5205, 5212), True, 'import numpy as np\n'), ((5308, 5325), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (5323, 5325), True, 'from keras import backend as K\n'), ((5356, 5367), 'time.time', 'time.time', ([], {}), '()\n', (5365, 5367), False, 'import time\n'), ((5393, 5511), 'param_net.param_fcnet.ParamFCNetRegression', 'ParamFCNetRegression', ([], {'config': 'config', 'n_feat': 'X_all.shape[1]', 'expected_num_epochs': 'max_epochs', 'n_outputs': '(1)', 'verbose': '(1)'}), '(config=config, n_feat=X_all.shape[1],\n expected_num_epochs=max_epochs, n_outputs=1, verbose=1)\n', (5413, 5511), False, 'from param_net.param_fcnet import ParamFCNetRegression\n'), ((6196, 6222), 'numpy.maximum', 'np.maximum', (['(0.0005)', 'y_pred'], {}), '(0.0005, y_pred)\n', (6206, 6222), True, 'import numpy as np\n'), ((4534, 4587), 'ConfigSpace.util.fix_types', 'fix_types', ([], {'configuration': 'dict', 'configuration_space': 'cs'}), '(configuration=dict, configuration_space=cs)\n', (4543, 4587), False, 'from ConfigSpace.util import fix_types\n'), ((4609, 4661), 'ConfigSpace.configuration_space.Configuration', 'Configuration', ([], {'configuration_space': 'cs', 'values': 'config'}), '(configuration_space=cs, values=config)\n', (4622, 4661), False, 'from ConfigSpace.configuration_space import Configuration\n'), ((1479, 1502), 'numpy.vstack', 'np.vstack', (['[X_all, X_q]'], {}), '([X_all, X_q])\n', (1488, 1502), True, 'import numpy as np\n'), ((1527, 1550), 'numpy.hstack', 'np.hstack', (['[y_all, y_q]'], {}), '([y_all, y_q])\n', (1536, 1550), True, 'import numpy as np\n'), ((2066, 2083), 'numpy.log10', 'np.log10', (['y_train'], {}), '(y_train)\n', (2074, 2083), True, 'import numpy as np\n'), ((2315, 2332), 'numpy.log10', 'np.log10', (['y_valid'], {}), '(y_valid)\n', (2323, 2332), True, 'import numpy as np\n'), ((3336, 3351), 'numpy.mean', 'np.mean', (['losses'], {}), '(losses)\n', (3343, 3351), True, 'import numpy as np\n'), ((4368, 4393), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (4389, 4393), True, 'import numpy as np\n'), ((2589, 2709), 'param_net.param_fcnet.ParamFCNetRegression', 'ParamFCNetRegression', ([], {'config': 'config', 'n_feat': 'X_train.shape[1]', 'expected_num_epochs': 'max_epochs', 'n_outputs': '(1)', 'verbose': '(1)'}), '(config=config, n_feat=X_train.shape[1],\n expected_num_epochs=max_epochs, n_outputs=1, verbose=1)\n', (2609, 2709), False, 'from param_net.param_fcnet import ParamFCNetRegression\n'), ((5872, 5883), 'time.time', 'time.time', ([], {}), '()\n', (5881, 5883), False, 'import time\n'), ((2543, 2560), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (2558, 2560), True, 'from keras import backend as K\n'), ((4867, 4894), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (4888, 4894), True, 'import numpy as np\n')]
|
import unittest
import os
import numpy as np
from skimage.io import imsave
import torch
import neural_renderer as nr
current_dir = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(current_dir, 'data')
class TestCore(unittest.TestCase):
def test_tetrahedron(self):
vertices_ref = np.array(
[
[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]],
'float32')
faces_ref = np.array(
[
[1, 3, 2],
[3, 1, 0],
[2, 0, 1],
[0, 2, 3]],
'int32')
obj_file = os.path.join(data_dir, 'tetrahedron.obj')
vertices, faces = nr.load_obj(obj_file, False)
assert (torch.allclose(torch.from_numpy(vertices_ref).cuda(), vertices))
assert (torch.allclose(torch.from_numpy(faces_ref).cuda(), faces))
vertices, faces = nr.load_obj(obj_file, True)
assert (torch.allclose(torch.from_numpy(vertices_ref).cuda() * 2 - 1.0, vertices))
assert (torch.allclose(torch.from_numpy(faces_ref).cuda(), faces))
def test_teapot(self):
obj_file = os.path.join(data_dir, 'teapot.obj')
vertices, faces = nr.load_obj(obj_file)
assert (faces.shape[0] == 2464)
assert (vertices.shape[0] == 1292)
def test_texture(self):
renderer = nr.Renderer(camera_mode='look_at')
vertices, faces, textures = nr.load_obj(
os.path.join(data_dir, '1cde62b063e14777c9152a706245d48/model.obj'), load_texture=True)
renderer.eye = nr.get_points_from_angles(2, 15, 30)
images, _, _ = renderer.render(vertices[None, :, :], faces[None, :, :], textures[None, :, :, :, :, :])
images = images.permute(0, 2, 3, 1).detach().cpu().numpy()
imsave(os.path.join(data_dir, 'car.png'), images[0])
vertices, faces, textures = nr.load_obj(
os.path.join(data_dir, '4e49873292196f02574b5684eaec43e9/model.obj'), load_texture=True, texture_size=16)
renderer.eye = nr.get_points_from_angles(2, 15, -90)
images, _, _ = renderer.render(vertices[None, :, :], faces[None, :, :], textures[None, :, :, :, :, :])
images = images.permute(0, 2, 3, 1).detach().cpu().numpy()
imsave(os.path.join(data_dir, 'display.png'), images[0])
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"os.path.realpath",
"neural_renderer.load_obj",
"numpy.array",
"neural_renderer.get_points_from_angles",
"neural_renderer.Renderer",
"os.path.join",
"torch.from_numpy"
] |
[((189, 222), 'os.path.join', 'os.path.join', (['current_dir', '"""data"""'], {}), "(current_dir, 'data')\n", (201, 222), False, 'import os\n'), ((150, 176), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (166, 176), False, 'import os\n'), ((2219, 2234), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2232, 2234), False, 'import unittest\n'), ((309, 403), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]', '"""float32"""'], {}), "([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0\n ]], 'float32')\n", (317, 403), True, 'import numpy as np\n'), ((449, 512), 'numpy.array', 'np.array', (['[[1, 3, 2], [3, 1, 0], [2, 0, 1], [0, 2, 3]]', '"""int32"""'], {}), "([[1, 3, 2], [3, 1, 0], [2, 0, 1], [0, 2, 3]], 'int32')\n", (457, 512), True, 'import numpy as np\n'), ((579, 620), 'os.path.join', 'os.path.join', (['data_dir', '"""tetrahedron.obj"""'], {}), "(data_dir, 'tetrahedron.obj')\n", (591, 620), False, 'import os\n'), ((643, 671), 'neural_renderer.load_obj', 'nr.load_obj', (['obj_file', '(False)'], {}), '(obj_file, False)\n', (654, 671), True, 'import neural_renderer as nr\n'), ((842, 869), 'neural_renderer.load_obj', 'nr.load_obj', (['obj_file', '(True)'], {}), '(obj_file, True)\n', (853, 869), True, 'import neural_renderer as nr\n'), ((1071, 1107), 'os.path.join', 'os.path.join', (['data_dir', '"""teapot.obj"""'], {}), "(data_dir, 'teapot.obj')\n", (1083, 1107), False, 'import os\n'), ((1130, 1151), 'neural_renderer.load_obj', 'nr.load_obj', (['obj_file'], {}), '(obj_file)\n', (1141, 1151), True, 'import neural_renderer as nr\n'), ((1271, 1305), 'neural_renderer.Renderer', 'nr.Renderer', ([], {'camera_mode': '"""look_at"""'}), "(camera_mode='look_at')\n", (1282, 1305), True, 'import neural_renderer as nr\n'), ((1474, 1510), 'neural_renderer.get_points_from_angles', 'nr.get_points_from_angles', (['(2)', '(15)', '(30)'], {}), '(2, 15, 30)\n', (1499, 1510), True, 'import neural_renderer as nr\n'), ((1919, 1956), 'neural_renderer.get_points_from_angles', 'nr.get_points_from_angles', (['(2)', '(15)', '(-90)'], {}), '(2, 15, -90)\n', (1944, 1956), True, 'import neural_renderer as nr\n'), ((1362, 1429), 'os.path.join', 'os.path.join', (['data_dir', '"""1cde62b063e14777c9152a706245d48/model.obj"""'], {}), "(data_dir, '1cde62b063e14777c9152a706245d48/model.obj')\n", (1374, 1429), False, 'import os\n'), ((1692, 1725), 'os.path.join', 'os.path.join', (['data_dir', '"""car.png"""'], {}), "(data_dir, 'car.png')\n", (1704, 1725), False, 'import os\n'), ((1794, 1862), 'os.path.join', 'os.path.join', (['data_dir', '"""4e49873292196f02574b5684eaec43e9/model.obj"""'], {}), "(data_dir, '4e49873292196f02574b5684eaec43e9/model.obj')\n", (1806, 1862), False, 'import os\n'), ((2138, 2175), 'os.path.join', 'os.path.join', (['data_dir', '"""display.png"""'], {}), "(data_dir, 'display.png')\n", (2150, 2175), False, 'import os\n'), ((699, 729), 'torch.from_numpy', 'torch.from_numpy', (['vertices_ref'], {}), '(vertices_ref)\n', (715, 729), False, 'import torch\n'), ((776, 803), 'torch.from_numpy', 'torch.from_numpy', (['faces_ref'], {}), '(faces_ref)\n', (792, 803), False, 'import torch\n'), ((984, 1011), 'torch.from_numpy', 'torch.from_numpy', (['faces_ref'], {}), '(faces_ref)\n', (1000, 1011), False, 'import torch\n'), ((897, 927), 'torch.from_numpy', 'torch.from_numpy', (['vertices_ref'], {}), '(vertices_ref)\n', (913, 927), False, 'import torch\n')]
|
# Lint as: python3
# Copyright 2019 The TensorFlow 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.
# ==============================================================================
"""Tests for waymo_ap_metric."""
from lingvo import compat as tf
from lingvo.core import py_utils
from lingvo.core import test_utils
from lingvo.tasks.car.waymo import waymo_ap_metric
from lingvo.tasks.car.waymo import waymo_metadata
import numpy as np
from waymo_open_dataset import label_pb2
FLAGS = tf.flags.FLAGS
class APTest(test_utils.TestCase):
def testWaymoAPConfig(self):
metadata = waymo_metadata.WaymoMetadata()
# Use 2D metric.
config = waymo_ap_metric.BuildWaymoMetricConfig(metadata, '2d', [])
vehicle_idx = label_pb2.Label.Type.Value('TYPE_VEHICLE')
ped_idx = label_pb2.Label.Type.Value('TYPE_PEDESTRIAN')
cyc_idx = label_pb2.Label.Type.Value('TYPE_CYCLIST')
thresholds_meta = metadata.IoUThresholds()
self.assertNear(config.iou_thresholds[vehicle_idx],
thresholds_meta['Vehicle'], 1e-6)
self.assertNear(config.iou_thresholds[ped_idx],
thresholds_meta['Pedestrian'], 1e-6)
self.assertNear(config.iou_thresholds[cyc_idx], thresholds_meta['Cyclist'],
1e-6)
def testPerfectBox(self):
metadata = waymo_metadata.WaymoMetadata()
params = waymo_ap_metric.WaymoAPMetrics.Params(metadata)
m = params.Instantiate()
# Make one update with a perfect box.
update_dict = py_utils.NestedMap(
groundtruth_labels=np.array([1]),
groundtruth_bboxes=np.ones(shape=(1, 7)),
groundtruth_difficulties=np.zeros(shape=(1)),
groundtruth_num_points=None,
detection_scores=np.ones(shape=(5, 1)),
detection_boxes=np.ones(shape=(5, 1, 7)),
detection_heights_in_pixels=np.ones(shape=(5, 1)))
m.Update('1234', update_dict)
waymo_ap = m.value
self.assertAllClose(waymo_ap, 1. / 3.)
# Write a summary.
summary = m.Summary('foo')
# Check that both AP and APH are in the tags.
tags = [v.tag for v in summary.value]
self.assertIn('foo/Pedestrian/AP_LEVEL_1', tags)
self.assertIn('foo/Pedestrian/APH_LEVEL_1', tags)
self.assertIn('foo/Pedestrian/AP_LEVEL_2', tags)
self.assertIn('foo/Pedestrian/APH_LEVEL_2', tags)
def testWaymoBreakdowns(self):
metadata = waymo_metadata.WaymoMetadata()
params = waymo_ap_metric.WaymoAPMetrics.Params(metadata)
params.waymo_breakdown_metrics = ['RANGE', 'VELOCITY']
m = params.Instantiate()
# Make one update with a perfect box.
update_dict = py_utils.NestedMap(
groundtruth_labels=np.array([1]),
groundtruth_bboxes=np.ones(shape=(1, 7)),
groundtruth_difficulties=np.zeros(shape=(1)),
groundtruth_num_points=None,
groundtruth_speed=np.zeros(shape=(1, 2)),
detection_scores=np.ones(shape=(5, 1)),
detection_boxes=np.ones(shape=(5, 1, 7)),
detection_heights_in_pixels=np.ones(shape=(5, 1)))
m.Update('1234', update_dict)
# Write a summary.
summary = m.Summary('foo')
# Check that the summary value for default ap and
# a waymo breakdown version by range is the same.
for v in summary.value:
if v.tag == 'foo/Vehicle/AP_LEVEL_1':
default_val = v.simple_value
elif v.tag == 'foo/Vehicle/APH_LEVEL_1':
aph_default_val = v.simple_value
elif v.tag == 'foo_extra/AP_RANGE_TYPE_VEHICLE_[0, 30)_LEVEL_1':
ap_bd_val_l1 = v.simple_value
elif v.tag == 'foo_extra/AP_RANGE_TYPE_VEHICLE_[0, 30)_LEVEL_2':
ap_bd_val_l2 = v.simple_value
elif v.tag == 'foo_extra/APH_RANGE_TYPE_VEHICLE_[0, 30)_LEVEL_1':
aph_bd_val_l1 = v.simple_value
elif v.tag == 'foo_extra/APH_RANGE_TYPE_VEHICLE_[0, 30)_LEVEL_2':
aph_bd_val_l2 = v.simple_value
elif v.tag == 'foo_extra/AP_VELOCITY_TYPE_VEHICLE_STATIONARY_LEVEL_1':
vbd_val_l1 = v.simple_value
elif v.tag == 'foo_extra/AP_VELOCITY_TYPE_VEHICLE_STATIONARY_LEVEL_2':
vbd_val_l2 = v.simple_value
self.assertEqual(ap_bd_val_l1, default_val)
self.assertEqual(ap_bd_val_l2, default_val)
self.assertEqual(aph_bd_val_l1, aph_default_val)
self.assertEqual(aph_bd_val_l2, aph_default_val)
self.assertEqual(vbd_val_l1, default_val)
self.assertEqual(vbd_val_l2, default_val)
# Check that eval classes not evaluated are not present.
tags = [v.tag for v in summary.value]
self.assertNotIn('foo_extra/APH_RANGE_TYPE_SIGN_[0, 30)_LEVEL_1', tags)
self.assertNotIn('foo_extra/APH_RANGE_TYPE_SIGN_[0, 30)_LEVEL_2', tags)
if __name__ == '__main__':
tf.test.main()
|
[
"lingvo.compat.test.main",
"waymo_open_dataset.label_pb2.Label.Type.Value",
"lingvo.tasks.car.waymo.waymo_ap_metric.WaymoAPMetrics.Params",
"numpy.zeros",
"numpy.ones",
"lingvo.tasks.car.waymo.waymo_ap_metric.BuildWaymoMetricConfig",
"numpy.array",
"lingvo.tasks.car.waymo.waymo_metadata.WaymoMetadata"
] |
[((5177, 5191), 'lingvo.compat.test.main', 'tf.test.main', ([], {}), '()\n', (5189, 5191), True, 'from lingvo import compat as tf\n'), ((1111, 1141), 'lingvo.tasks.car.waymo.waymo_metadata.WaymoMetadata', 'waymo_metadata.WaymoMetadata', ([], {}), '()\n', (1139, 1141), False, 'from lingvo.tasks.car.waymo import waymo_metadata\n'), ((1176, 1234), 'lingvo.tasks.car.waymo.waymo_ap_metric.BuildWaymoMetricConfig', 'waymo_ap_metric.BuildWaymoMetricConfig', (['metadata', '"""2d"""', '[]'], {}), "(metadata, '2d', [])\n", (1214, 1234), False, 'from lingvo.tasks.car.waymo import waymo_ap_metric\n'), ((1253, 1295), 'waymo_open_dataset.label_pb2.Label.Type.Value', 'label_pb2.Label.Type.Value', (['"""TYPE_VEHICLE"""'], {}), "('TYPE_VEHICLE')\n", (1279, 1295), False, 'from waymo_open_dataset import label_pb2\n'), ((1310, 1355), 'waymo_open_dataset.label_pb2.Label.Type.Value', 'label_pb2.Label.Type.Value', (['"""TYPE_PEDESTRIAN"""'], {}), "('TYPE_PEDESTRIAN')\n", (1336, 1355), False, 'from waymo_open_dataset import label_pb2\n'), ((1370, 1412), 'waymo_open_dataset.label_pb2.Label.Type.Value', 'label_pb2.Label.Type.Value', (['"""TYPE_CYCLIST"""'], {}), "('TYPE_CYCLIST')\n", (1396, 1412), False, 'from waymo_open_dataset import label_pb2\n'), ((1830, 1860), 'lingvo.tasks.car.waymo.waymo_metadata.WaymoMetadata', 'waymo_metadata.WaymoMetadata', ([], {}), '()\n', (1858, 1860), False, 'from lingvo.tasks.car.waymo import waymo_metadata\n'), ((1874, 1921), 'lingvo.tasks.car.waymo.waymo_ap_metric.WaymoAPMetrics.Params', 'waymo_ap_metric.WaymoAPMetrics.Params', (['metadata'], {}), '(metadata)\n', (1911, 1921), False, 'from lingvo.tasks.car.waymo import waymo_ap_metric\n'), ((2883, 2913), 'lingvo.tasks.car.waymo.waymo_metadata.WaymoMetadata', 'waymo_metadata.WaymoMetadata', ([], {}), '()\n', (2911, 2913), False, 'from lingvo.tasks.car.waymo import waymo_metadata\n'), ((2927, 2974), 'lingvo.tasks.car.waymo.waymo_ap_metric.WaymoAPMetrics.Params', 'waymo_ap_metric.WaymoAPMetrics.Params', (['metadata'], {}), '(metadata)\n', (2964, 2974), False, 'from lingvo.tasks.car.waymo import waymo_ap_metric\n'), ((2058, 2071), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (2066, 2071), True, 'import numpy as np\n'), ((2100, 2121), 'numpy.ones', 'np.ones', ([], {'shape': '(1, 7)'}), '(shape=(1, 7))\n', (2107, 2121), True, 'import numpy as np\n'), ((2156, 2173), 'numpy.zeros', 'np.zeros', ([], {'shape': '(1)'}), '(shape=1)\n', (2164, 2173), True, 'import numpy as np\n'), ((2239, 2260), 'numpy.ones', 'np.ones', ([], {'shape': '(5, 1)'}), '(shape=(5, 1))\n', (2246, 2260), True, 'import numpy as np\n'), ((2286, 2310), 'numpy.ones', 'np.ones', ([], {'shape': '(5, 1, 7)'}), '(shape=(5, 1, 7))\n', (2293, 2310), True, 'import numpy as np\n'), ((2348, 2369), 'numpy.ones', 'np.ones', ([], {'shape': '(5, 1)'}), '(shape=(5, 1))\n', (2355, 2369), True, 'import numpy as np\n'), ((3171, 3184), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (3179, 3184), True, 'import numpy as np\n'), ((3213, 3234), 'numpy.ones', 'np.ones', ([], {'shape': '(1, 7)'}), '(shape=(1, 7))\n', (3220, 3234), True, 'import numpy as np\n'), ((3269, 3286), 'numpy.zeros', 'np.zeros', ([], {'shape': '(1)'}), '(shape=1)\n', (3277, 3286), True, 'import numpy as np\n'), ((3353, 3375), 'numpy.zeros', 'np.zeros', ([], {'shape': '(1, 2)'}), '(shape=(1, 2))\n', (3361, 3375), True, 'import numpy as np\n'), ((3402, 3423), 'numpy.ones', 'np.ones', ([], {'shape': '(5, 1)'}), '(shape=(5, 1))\n', (3409, 3423), True, 'import numpy as np\n'), ((3449, 3473), 'numpy.ones', 'np.ones', ([], {'shape': '(5, 1, 7)'}), '(shape=(5, 1, 7))\n', (3456, 3473), True, 'import numpy as np\n'), ((3511, 3532), 'numpy.ones', 'np.ones', ([], {'shape': '(5, 1)'}), '(shape=(5, 1))\n', (3518, 3532), True, 'import numpy as np\n')]
|
import numpy as np
import torch
from scipy.special import comb
class Metric:
def __init__(self, **kwargs):
self.requires = ['kmeans_cosine', 'kmeans_nearest_cosine', 'features_cosine', 'target_labels']
self.name = 'c_f1'
def __call__(self, target_labels, computed_cluster_labels_cosine, features_cosine, centroids_cosine):
if isinstance(features_cosine, torch.Tensor):
features_cosine = features_cosine.detach().cpu().numpy()
d = np.zeros(len(features_cosine))
for i in range(len(features_cosine)):
d[i] = np.linalg.norm(features_cosine[i, :] - centroids_cosine[computed_cluster_labels_cosine[i], :])
labels_pred = np.zeros(len(features_cosine))
for i in np.unique(computed_cluster_labels_cosine):
index = np.where(computed_cluster_labels_cosine == i)[0]
ind = np.argmin(d[index])
cid = index[ind]
labels_pred[index] = cid
N = len(target_labels)
# cluster n_labels
avail_labels = np.unique(target_labels)
n_labels = len(avail_labels)
# count the number of objects in each cluster
count_cluster = np.zeros(n_labels)
for i in range(n_labels):
count_cluster[i] = len(np.where(target_labels == avail_labels[i])[0])
# build a mapping from item_id to item index
keys = np.unique(labels_pred)
num_item = len(keys)
values = range(num_item)
item_map = dict()
for i in range(len(keys)):
item_map.update([(keys[i], values[i])])
# count the number of objects of each item
count_item = np.zeros(num_item)
for i in range(N):
index = item_map[labels_pred[i]]
count_item[index] = count_item[index] + 1
# compute True Positive (TP) plus False Positive (FP)
# tp_fp = 0
tp_fp = comb(count_cluster, 2).sum()
# for k in range(n_labels):
# if count_cluster[k] > 1:
# tp_fp = tp_fp + comb(count_cluster[k], 2)
# compute True Positive (TP)
tp = 0
for k in range(n_labels):
member = np.where(target_labels == avail_labels[k])[0]
member_ids = labels_pred[member]
count = np.zeros(num_item)
for j in range(len(member)):
index = item_map[member_ids[j]]
count[index] = count[index] + 1
# for i in range(num_item):
# if count[i] > 1:
# tp = tp + comb(count[i], 2)
tp += comb(count, 2).sum()
# False Positive (FP)
fp = tp_fp - tp
# Compute False Negative (FN)
count = comb(count_item, 2).sum()
# count = 0
# for j in range(num_item):
# if count_item[j] > 1:
# count = count + comb(count_item[j], 2)
fn = count - tp
# compute F measure
P = tp / (tp + fp)
R = tp / (tp + fn)
beta = 1
F = (beta * beta + 1) * P * R / (beta * beta * P + R)
return F
|
[
"scipy.special.comb",
"numpy.zeros",
"numpy.argmin",
"numpy.where",
"numpy.linalg.norm",
"numpy.unique"
] |
[((747, 788), 'numpy.unique', 'np.unique', (['computed_cluster_labels_cosine'], {}), '(computed_cluster_labels_cosine)\n', (756, 788), True, 'import numpy as np\n'), ((1046, 1070), 'numpy.unique', 'np.unique', (['target_labels'], {}), '(target_labels)\n', (1055, 1070), True, 'import numpy as np\n'), ((1187, 1205), 'numpy.zeros', 'np.zeros', (['n_labels'], {}), '(n_labels)\n', (1195, 1205), True, 'import numpy as np\n'), ((1391, 1413), 'numpy.unique', 'np.unique', (['labels_pred'], {}), '(labels_pred)\n', (1400, 1413), True, 'import numpy as np\n'), ((1662, 1680), 'numpy.zeros', 'np.zeros', (['num_item'], {}), '(num_item)\n', (1670, 1680), True, 'import numpy as np\n'), ((581, 680), 'numpy.linalg.norm', 'np.linalg.norm', (['(features_cosine[i, :] - centroids_cosine[computed_cluster_labels_cosine[i], :]\n )'], {}), '(features_cosine[i, :] - centroids_cosine[\n computed_cluster_labels_cosine[i], :])\n', (595, 680), True, 'import numpy as np\n'), ((877, 896), 'numpy.argmin', 'np.argmin', (['d[index]'], {}), '(d[index])\n', (886, 896), True, 'import numpy as np\n'), ((2289, 2307), 'numpy.zeros', 'np.zeros', (['num_item'], {}), '(num_item)\n', (2297, 2307), True, 'import numpy as np\n'), ((810, 855), 'numpy.where', 'np.where', (['(computed_cluster_labels_cosine == i)'], {}), '(computed_cluster_labels_cosine == i)\n', (818, 855), True, 'import numpy as np\n'), ((1906, 1928), 'scipy.special.comb', 'comb', (['count_cluster', '(2)'], {}), '(count_cluster, 2)\n', (1910, 1928), False, 'from scipy.special import comb\n'), ((2178, 2220), 'numpy.where', 'np.where', (['(target_labels == avail_labels[k])'], {}), '(target_labels == avail_labels[k])\n', (2186, 2220), True, 'import numpy as np\n'), ((2718, 2737), 'scipy.special.comb', 'comb', (['count_item', '(2)'], {}), '(count_item, 2)\n', (2722, 2737), False, 'from scipy.special import comb\n'), ((1275, 1317), 'numpy.where', 'np.where', (['(target_labels == avail_labels[i])'], {}), '(target_labels == avail_labels[i])\n', (1283, 1317), True, 'import numpy as np\n'), ((2588, 2602), 'scipy.special.comb', 'comb', (['count', '(2)'], {}), '(count, 2)\n', (2592, 2602), False, 'from scipy.special import comb\n')]
|
#right now, requires source /project/projectdirs/desi/software/desi_environment.sh master
from astropy.table import Table
import numpy as np
import os
import argparse
import fitsio
from desitarget.targetmask import zwarn_mask
parser = argparse.ArgumentParser()
parser.add_argument("--night", help="use this if you want to specify the night, rather than just use the last one",default=None)
args = parser.parse_args()
month = args.night[:6]
#get the right tileids
exps = Table.read('/global/cfs/cdirs/desi/spectro/redux/daily/exposure_tables/'+month+'/exposure_table_'+args.night+'.csv')
print('number of exposures found:')
print(len(exps))
#cut to dark tiles
sel = exps['FAPRGRM']=='dark'
print('number that are dark time:')
print(len(exps[sel]))
exps = exps[sel]
#get the list of tileids observed on the last night
tidl = np.unique(exps['TILEID'])
#get total exposure time for tiles
exptl = np.zeros(len(tidl))
for ii in range(0, len(tidl)):
w = exps['TILEID'] == tidl[ii]
expt = np.sum(exps[w]['EFFTIME_ETC'])
exptl[ii] = expt
#sel &= exps['EFFTIME_ETC'] > 850 #select only tiles that should be near completion
sel = exptl > 850
tidl = tidl[sel]
print('number dark tiles that have EFFTIME_ETC > 850 during the night:')
print(len(tidl))
print('looking at LRG redshift results from the night '+str(args.night))
print('the tileids are:')
print(tidl)
#one list for each petal for total targets
gz = np.zeros(10)
tz = np.zeros(10)
zdir = '/global/cfs/cdirs/desi/spectro/redux/daily/tiles/cumulative/'
for tid in tidl:
for pt in range(0,10):
zmtlf = fitsio.read(zdir+str(tid)+'/'+args.night+'/zmtl-'+str(pt)+'-'+str(tid)+'-thru'+args.night+'.fits')
nodata = zmtlf["ZWARN"] & zwarn_mask["NODATA"] != 0
num_nod = np.sum(nodata)
print('looking at petal '+str(pt)+' on tile '+str(tid))
print('number with no data '+str(num_nod))
badqa = zmtlf["ZWARN"] & zwarn_mask.mask("BAD_SPECQA|BAD_PETALQA") != 0
num_badqa = np.sum(badqa)
print('number with bad qa '+str(num_badqa))
nomtl = nodata | badqa
wfqa = ~nomtl
wlrg = (zmtlf['DESI_TARGET'] & 1) > 0
zlrg = zmtlf[wfqa&wlrg]
if len(zlrg) > 0:
wzwarn = zmtlf['ZWARN'] == 0
gzlrg = zmtlf[wzwarn&wlrg]
print('The fraction of good LRGs is '+str(len(gzlrg)/len(zlrg))+' for '+str(len(zlrg))+' considered spectra')
gz[pt] += len(gzlrg)
tz[pt] += len(zlrg)
else:
print('no good lrg data')
print('the total number of LRG considered per petal for the night is:')
print(tz)
tzs = gz/tz
print('the total fraction of good LRG z per petal for the night is:')
print(tzs)
|
[
"astropy.table.Table.read",
"numpy.sum",
"argparse.ArgumentParser",
"desitarget.targetmask.zwarn_mask.mask",
"numpy.zeros",
"numpy.unique"
] |
[((236, 261), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (259, 261), False, 'import argparse\n'), ((472, 600), 'astropy.table.Table.read', 'Table.read', (["('/global/cfs/cdirs/desi/spectro/redux/daily/exposure_tables/' + month +\n '/exposure_table_' + args.night + '.csv')"], {}), "('/global/cfs/cdirs/desi/spectro/redux/daily/exposure_tables/' +\n month + '/exposure_table_' + args.night + '.csv')\n", (482, 600), False, 'from astropy.table import Table\n'), ((829, 854), 'numpy.unique', 'np.unique', (["exps['TILEID']"], {}), "(exps['TILEID'])\n", (838, 854), True, 'import numpy as np\n'), ((1424, 1436), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (1432, 1436), True, 'import numpy as np\n'), ((1442, 1454), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (1450, 1454), True, 'import numpy as np\n'), ((997, 1027), 'numpy.sum', 'np.sum', (["exps[w]['EFFTIME_ETC']"], {}), "(exps[w]['EFFTIME_ETC'])\n", (1003, 1027), True, 'import numpy as np\n'), ((1764, 1778), 'numpy.sum', 'np.sum', (['nodata'], {}), '(nodata)\n', (1770, 1778), True, 'import numpy as np\n'), ((1994, 2007), 'numpy.sum', 'np.sum', (['badqa'], {}), '(badqa)\n', (2000, 2007), True, 'import numpy as np\n'), ((1927, 1968), 'desitarget.targetmask.zwarn_mask.mask', 'zwarn_mask.mask', (['"""BAD_SPECQA|BAD_PETALQA"""'], {}), "('BAD_SPECQA|BAD_PETALQA')\n", (1942, 1968), False, 'from desitarget.targetmask import zwarn_mask\n')]
|
#!/usr/bin/env python3
import numpy as np
import random
if __name__ == '__main__':
nbViewpoint = 3
nbTileList = [1, 3*2, 6*4]
#nbTileList = [1]
#nbQuality = 4
nbQuality = 3
#nbChunk = 4*60
nbChunk = 256
#nbChunk = 60
nbBandwidth = 1
nbUser = 4
nbProcessedChunk = 32
#nbLagChunkList = [2,10]
#nbLagChunkList = [2,3,4]
nbLagChunkList = [2]
optimalGap=0.03
nbThread=4
#averageLowBitrate = 5
#averageHighBitrate = 35
averageBitrateList = [5, 8, 16]
avgBitrateList = [[5.00638565625, 8.00672046875, 16.01394303125], [5.0235795, 8.02069896875, 16.019751999999997], [5.0842264375, 8.08175678125, 16.080042812500004]]
varBitrateList = [[0.05197598260550684, 0.13243587169603027, 0.5569402424963116], [0.013006378470749997, 0.043633303918936515, 0.3272058487585], [0.012634444530058589, 0.04158807113638965, 0.3401763092415898]]
#averageLowQuality = 220
#averageHighQuality = 5
averageQualityList = [2.8642533333333335, 2.5503899999999997, 2.1635133333333334]
varQualityList = [0.6041990998222223, 0.3490154629, 0.13785629982222222]
#averageBandwidthList = [4, 7, 16, 24, 32, 48, 60]
#averageBandwidthList = [4, 7, 10, 15, 20]
#averageBandwidthList = [5, 10, 15, 20, 25, 30, 35, 40]
#averageBandwidthList = [3, 4, 7, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60]
#averageBandwidthList = [3, 4, 5, 7, 10, 15, 20, 25 ,30]
averageBandwidthList = [3, 5, 7, 10, 15]
#averageBandwidthList = [20, 25, 30, 35, 40, 45, 50, 55, 60]
#averageBandwidthList = [4, 7, 10]
#for i in range(15, 61):
# averageBandwidthList.append(i)
outputUser = dict()
outputAdaptationSet = dict()
for nbTile in nbTileList:
outputUser[nbTile] = dict()
for userId in range(nbUser):
#if userId != 0:
# outputUser[nbTile][userId] = 'scenarios/user_{nbViewpoint}_{nbTile}_{nbChunk}_{userId}.txt'.format(nbViewpoint=nbViewpoint, nbTile=nbTile, nbChunk=nbChunk, userId=userId)
outputUser[nbTile][userId] = 'scenarios/user_{nbViewpoint}_{nbTile}_{nbChunk}_{userId}.txt'.format(nbViewpoint=nbViewpoint, nbTile=nbTile, nbChunk=nbChunk, userId=userId)
#else:
# outputUser[nbTile][userId] = 'scenarios/user_{nbViewpoint}_{nbTile}_{nbChunk}.txt'.format(nbViewpoint=nbViewpoint, nbTile=nbTile, nbChunk=nbChunk)
outputAdaptationSet[nbTile] = 'scenarios/adaptationSet_{nbViewpoint}_{nbTile}_{nbChunk}_{nbQuality}.txt'.format(nbViewpoint=nbViewpoint, nbTile=nbTile, nbChunk=nbChunk, nbQuality=nbQuality)
outputBandwidth = dict()
for averageBandwidth in averageBandwidthList:
outputBandwidth[averageBandwidth] = dict()
for nbLagChunk in nbLagChunkList:
outputBandwidth[averageBandwidth][nbLagChunk] = dict()
for bandwidthId in range(nbBandwidth):
outputBandwidth[averageBandwidth][nbLagChunk][bandwidthId] = 'scenarios/bandwdithFake_{nbChunk}_{nbLagChunk}_{averageBandwidth}Mbps_id{bandwidthId}.txt'.format(nbChunk=nbChunk, nbLagChunk=nbLagChunk, averageBandwidth=averageBandwidth, bandwidthId=bandwidthId)
random.seed(42)
np.random.seed(42)
#Configuration file
with open('Config.ini', 'w') as o:
o.write('[Global]\nNbViewpoint={nbViewpoint}\nNbScenario={nbScenario}\noptimalGap={optimalGap}\nnbThread={nbThread}\n'.format(nbViewpoint=nbViewpoint, nbScenario=len(averageBandwidthList)*len(nbTileList)*len(nbLagChunkList), optimalGap=optimalGap, nbThread=nbThread))
counter = 0
#for scenarioId in reversed(range(len(averageBandwidthList))):
for scenarioId in range(len(averageBandwidthList)):
for nbTileId in range(len(nbTileList)):
for nbLagChunkId in range(len(nbLagChunkList)):
nbTile = nbTileList[nbTileId]
nbLagChunk = nbLagChunkList[nbLagChunkId]
o.write('Scenario{id}={name}\n'.format(id=counter, name='Test_{}_{}_{}_{}Mbps'.format(nbChunk, nbLagChunk, nbTile, averageBandwidthList[scenarioId])))
counter += 1
o.write('\n')
#for scenarioId in reversed(range(len(averageBandwidthList))):
for scenarioId in range(len(averageBandwidthList)):
for nbTile in nbTileList:
for nbLagChunk in nbLagChunkList:
bandwidthConf = ""
for bandwidthId in range(nbBandwidth):
bandwidthConf += '{}../{}'.format(';' if bandwidthConf != "" else '', outputBandwidth[averageBandwidthList[scenarioId]][nbLagChunk][bandwidthId])
userConf = ""
for userId in range(nbUser):
userConf += '{}../{}'.format(';' if userConf != "" else '', outputUser[nbTile][userId])
o.write('[{name}]\nNbTile={nbTile}\nNbQuality={nbQuality}\nNbChunk={nbChunk}\nNbProcessedChunk={nbProcessedChunk}\nNbLagDownloadChunk={nbLagChunk}\nAdaptationSetConf=../{asName}\nBandwidthConf={bName}\nUserConf={uName}\n'.format(name='Test_{}_{}_{}_{}Mbps'.format(nbChunk, nbLagChunk, nbTile, averageBandwidthList[scenarioId]), nbTile=nbTile, nbChunk=nbChunk, nbProcessedChunk=nbProcessedChunk, nbQuality=nbQuality, nbLagChunk=nbLagChunk, asName=outputAdaptationSet[nbTile], uName=userConf, bName=bandwidthConf))
o.write('horizontalOptimal={}\n'.format('true'))# if averageBandwidthList[scenarioId] > 0.9*nbViewpoint*averageLowBitrate else 'false'))
o.write('optimal={}\n'.format('true'))
o.write('verticalOptimal={}\n'.format('true'))
o.write('avgBandwidth={}\n'.format(averageBandwidthList[scenarioId]))
o.write('\n')
#Bandwidth file
#bandwidthList = [max(0.1*averageBandwidthList[0], np.random.normal(averageBandwidthList[0], 0.15*averageBandwidthList[0])) for i in range(-nbLagChunk, nbChunk)]
for averageBandwidth in averageBandwidthList:
for nbLagChunk in nbLagChunkList:
for bandwidthId in range(nbBandwidth):
with open(outputBandwidth[averageBandwidth][nbLagChunk][bandwidthId], 'w') as ob:
ob.write('#chunId,bandwidth\n')
for chunId in range(-nbLagChunk, nbChunk):
ob.write('{},{}\n'.format(chunId, np.random.normal(averageBandwidth, 0.05*averageBandwidth)))
#ob.write('{},{}\n'.format(chunId, bandwidthList[chunId]*averageBandwidth/averageBandwidthList[0]))
##User:
#for userId in range(nbUser):
# viewpointList = list()
# switchingTime = list()
# lastViewpoint = None
# for chunId in range(nbChunk):
# if lastViewpoint is None:
# currentViewpoint = random.randint(0,nbViewpoint-1)
# else:
# vList = [i for i in range(0, nbViewpoint)]
# pList = list()
# for v in vList:
# if v == lastViewpoint:
# pList.append(35)
# else:
# pList.append(1)
# pList = np.array(pList)/sum(pList)
# currentViewpoint = np.random.choice(vList, p=pList)
# if lastViewpoint != currentViewpoint:
# if lastViewpoint is not None:
# switchingTime.append(np.random.uniform())
# print('Switch at',chunId, 'from',lastViewpoint,'to',currentViewpoint)
# else:
# switchingTime.append(-1)
# lastViewpoint = currentViewpoint
# viewpointList.append(currentViewpoint)
# switchingTime.append(-1)
# visibility = list()
# for chunId in range(nbChunk):
# visiList = list()
# nbTile = 24
# totalVisi = 0
# for tileId in range(nbTile):
# if tileId != nbTile-1:
# visiList.append(random.randint(0,1000-totalVisi)/1000)
# totalVisi += int(visiList[tileId]*1000)
# else:
# visiList.append(1-totalVisi/1000)
# random.shuffle(visiList)
# visibility.append(visiList)
# for nbTile in nbTileList:
# if userId != 0:
# with open(outputUser[nbTile][userId], 'w') as ou:
# ou.write('#chunkId,viewpointId,tileId,visibilityRatio,switchingDecisionTime\n')
# for chunId in range(nbChunk):
# currentViewpoint = viewpointList[chunId]
# for viewpointId in range(nbViewpoint):
# for tileId in range(nbTile):
# if viewpointId != currentViewpoint:
# ou.write('{},{},{},{},{}\n'.format(chunId, viewpointId, tileId, 0, switchingTime[chunId]))
# else:
# if nbTile == 24:
# visi = visibility[chunId][tileId]
# elif nbTile == 6:
# if tileId == 5:
# visi = round(10000*sum(visibility[chunId][tileId*6:(tileId+1)*6]))/10000
# else:
# visi = round(1000*sum(visibility[chunId][tileId*6:(tileId+1)*6]))/1000
# elif nbTile == 1:
# visi = round(1000*sum(visibility[chunId])/1000)
# else:
# raise 'NOT SUPPORTED TILE NUMBER'
# ou.write('{},{},{},{}, {}\n'.format(chunId, viewpointId, tileId, visi, switchingTime[chunId]))
#AdaptationSet
#for nbTile in nbTileList:
# with open(outputAdaptationSet[nbTile], 'w') as oas:
# oas.write('#chunkId,viewpointId,tileId,qualityId,distortion,bitrate\n')
# for chunId in range(nbChunk):
# for viewpointId in range(nbViewpoint):
# for tileId in range(nbTile):
# for qualityId in range(nbQuality):
# #avBitrate = (qualityId*(averageHighBitrate-averageLowBitrate)/(nbQuality-1) + averageLowBitrate)/nbTile
# #avBitrate = averageBitrateList[qualityId]/nbTile
# #avDistortion = (qualityId*(averageHighQuality-averageLowQuality)/(nbQuality-1) + averageLowQuality)**2
# #bitrate = np.random.normal(avBitrate, 0.05*avBitrate/nbTile)
# bitrate = np.random.normal(avgBitrateList[nbTileList.index(nbTile)][qualityId], varBitrateList[nbTileList.index(nbTile)][qualityId])/nbTile
# #distortion = np.random.normal(avDistortion, avDistortion*0.005)
# distortion = np.random.normal(averageQualityList[qualityId], varQualityList[qualityId])
# #bitrate = max(bitrate, 0.05*avBitrate/nbTile)
# distortion = min(255*255, max(0, distortion))
# oas.write('{},{},{},{},{},{}\n'.format(chunId, viewpointId, tileId, qualityId, distortion, bitrate))
|
[
"numpy.random.seed",
"random.seed",
"numpy.random.normal"
] |
[((3166, 3181), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (3177, 3181), False, 'import random\n'), ((3186, 3204), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (3200, 3204), True, 'import numpy as np\n'), ((6374, 6433), 'numpy.random.normal', 'np.random.normal', (['averageBandwidth', '(0.05 * averageBandwidth)'], {}), '(averageBandwidth, 0.05 * averageBandwidth)\n', (6390, 6433), True, 'import numpy as np\n')]
|
# %matplotlib inline
# +
import os, sys
import numpy as np
import random
import copy
import torch
import torch.autograd as autograd
from torch.autograd import Variable
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset, TensorDataset
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data.sampler import SubsetRandomSampler
from config import *
from models import *
from utils import *
from datasets.celeba import CelebA
from ops import exp_mov_avg
#from torchsummary import summary
from torchinfo import summary
from tqdm import tqdm
IMG_DIM = -1
NUM_CLASSES = -1
CLIP_BOUND = 1.
SENSITIVITY = 2.
DATA_ROOT = './../data'
# +
def master_hook_adder(module, grad_input, grad_output):
'''
global hook
:param module:
:param grad_input:
:param grad_output:
:return:
'''
global dynamic_hook_function
return dynamic_hook_function(module, grad_input, grad_output)
def dummy_hook(module, grad_input, grad_output):
'''
dummy hook
:param module:
:param grad_input:
:param grad_output:
:return:
'''
pass
def modify_gradnorm_conv_hook(module, grad_input, grad_output):
'''
gradient modification hook
:param module:
:param grad_input:
:param grad_output:
:return:
'''
### get grad wrt. input (image)
grad_wrt_image = grad_input[0]
grad_input_shape = grad_wrt_image.size()
batchsize = grad_input_shape[0]
clip_bound_ = CLIP_BOUND / batchsize # account for the 'sum' operation in GP
grad_wrt_image = grad_wrt_image.view(batchsize, -1)
grad_input_norm = torch.norm(grad_wrt_image, p=2, dim=1)
### clip
clip_coef = clip_bound_ / (grad_input_norm + 1e-10)
clip_coef = clip_coef.unsqueeze(-1)
grad_wrt_image = clip_coef * grad_wrt_image
grad_input = (grad_wrt_image.view(grad_input_shape), grad_input[1], grad_input[2])
return tuple(grad_input)
def dp_conv_hook(module, grad_input, grad_output):
'''
gradient modification + noise hook
:param module:
:param grad_input:
:param grad_output:
:return:
'''
global noise_multiplier
### get grad wrt. input (image)
grad_wrt_image = grad_input[0]
grad_input_shape = grad_wrt_image.size()
batchsize = grad_input_shape[0]
clip_bound_ = CLIP_BOUND / batchsize
grad_wrt_image = grad_wrt_image.view(batchsize, -1)
grad_input_norm = torch.norm(grad_wrt_image, p=2, dim=1)
### clip
clip_coef = clip_bound_ / (grad_input_norm + 1e-10)
clip_coef = torch.min(clip_coef, torch.ones_like(clip_coef))
clip_coef = clip_coef.unsqueeze(-1)
grad_wrt_image = clip_coef * grad_wrt_image
### add noise
noise = clip_bound_ * noise_multiplier * SENSITIVITY * torch.randn_like(grad_wrt_image)
grad_wrt_image = grad_wrt_image + noise
grad_input_new = [grad_wrt_image.view(grad_input_shape)]
for i in range(len(grad_input)-1):
grad_input_new.append(grad_input[i+1])
return tuple(grad_input_new)
FloatTensor = torch.cuda.FloatTensor
LongTensor = torch.cuda.LongTensor
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv2d') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
# -
def main(args):
### config
global noise_multiplier
dataset = args.dataset
num_discriminators = args.num_discriminators
noise_multiplier = args.noise_multiplier
z_dim = args.z_dim
if dataset == 'celeba':
z_dim = 100
model_dim = args.model_dim
batchsize = args.batchsize
L_gp = args.L_gp
L_epsilon = args.L_epsilon
critic_iters = args.critic_iters
latent_type = args.latent_type
load_dir = args.load_dir
save_dir = args.save_dir
if_dp = (args.noise_multiplier > 0.)
gen_arch = args.gen_arch
num_gpus = args.num_gpus
### CUDA
use_cuda = torch.cuda.is_available()
devices = [torch.device("cuda:%d" % i if use_cuda else "cpu") for i in range(num_gpus)]
device0 = devices[0]
if use_cuda:
torch.set_default_tensor_type('torch.cuda.FloatTensor')
### Random seed
if args.random_seed == 1:
args.random_seed = np.random.randint(10000, size=1)[0]
print('random_seed: {}'.format(args.random_seed))
os.system('rm ' + os.path.join(save_dir, 'seed*'))
os.system('touch ' + os.path.join(save_dir, 'seed=%s' % str(args.random_seed)))
random.seed(args.random_seed)
np.random.seed(args.random_seed)
torch.manual_seed(args.random_seed)
### Set up models
print('gen_arch:' + gen_arch)
if dataset == 'celeba':
ngpu = 1
netG = Generator_celeba(ngpu).to(device0)
#netG.load_state_dict(torch.load('../results/celeba/main/d_1_2e-4_g_1_2e-4_SN_full/netG_15000.pth'))
# Handle multi-gpu if desired
if (device0.type == 'cuda') and (ngpu > 1):
netG = nn.DataParallel(netG, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.02.
netG.apply(weights_init)
netGS = copy.deepcopy(netG).to(device0)
if dataset == 'celeba':
ngpu = 1
netD = Discriminator_celeba(ngpu).to(device0)
#netD.load_state_dict(torch.load('../results/celeba/main/d_1_2e-4_g_1_2e-4_SN_full/netD_15000.pth'))
# Handle multi-gpu if desired
if (device0.type == 'cuda') and (ngpu > 1):
netD = nn.DataParallel(netD, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
#netD.apply(weights_init)
### Set up optimizers
optimizerD = optim.Adam(netD.parameters(), lr=2e-4, betas=(0.5, 0.99))
optimizerG = optim.Adam(netG.parameters(), lr=2e-4, betas=(0.5, 0.99))
### Data loaders
if dataset == 'celeba':
transform_train = transforms.Compose([
transforms.Resize(64),
transforms.CenterCrop(64),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
if dataset == 'celeba':
IMG_DIM = 64*64*3
NUM_CLASSES = 2
trainset = CelebA(root=os.path.join('/work/u5366584/exp/datasets/celeba'), split='train',
transform=transform_train, download=False)#, custom_subset=True)
#trainset = CelebA(root=os.path.join('../data'), split='train',
# transform=transform_train, download=False, custom_subset=True)
else:
raise NotImplementedError
###fix sub-training set (fix to 10000 training samples)
if args.update_train_dataset:
if dataset == 'mnist':
indices_full = np.arange(60000)
elif dataset == 'cifar_10':
indices_full = np.arange(50000)
elif dataset == 'celeba':
indices_full = np.arange(len(trainset))
np.random.shuffle(indices_full)
'''
#####ref
indices = np.loadtxt('index_20k.txt', dtype=np.int_)
remove_idx = [np.argwhere(indices_full==x) for x in indices]
indices_ref = np.delete(indices_full, remove_idx)
indices_slice = indices_ref[:20000]
np.savetxt('index_20k_ref.txt', indices_slice, fmt='%i') ##ref index is disjoint to original index
'''
### growing dataset
indices = np.loadtxt('index_20k.txt', dtype=np.int_)
remove_idx = [np.argwhere(indices_full==x) for x in indices]
indices_rest = np.delete(indices_full, remove_idx)
indices_rest = indices_rest[:20000]
indices_slice = np.concatenate((indices, indices_rest), axis=0)
np.savetxt('index_40k.txt', indices_slice, fmt='%i')
indices = np.loadtxt('index_100k.txt', dtype=np.int_)
trainset = torch.utils.data.Subset(trainset, indices)
print(len(trainset))
workers = 4
dataloader = torch.utils.data.DataLoader(trainset, batch_size=batchsize,
shuffle=True, num_workers=workers)
if if_dp:
### Register hook
global dynamic_hook_function
for netD in netD_list:
netD.conv1.register_backward_hook(master_hook_adder)
criterion = nn.BCELoss()
real_label = 1.
fake_label = 0.
nz = 100
fixed_noise = torch.randn(100, nz, 1, 1, device=device0)
iters = 0
num_epochs = 256 * 5 + 1
print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
# For each batch in the dataloader
for i, (data,y) in enumerate(dataloader, 0):
############################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
###########################
## Train with all-real batch
netD.zero_grad()
# Format batch
real_cpu = data.to(device0)
b_size = real_cpu.size(0)
label = torch.full((b_size,), real_label, dtype=torch.float, device=device0)
# Forward pass real batch through D
output = netD(real_cpu).view(-1)
# Calculate loss on all-real batch
errD_real = criterion(output, label)
# Calculate gradients for D in backward pass
errD_real.backward()
D_x = output.mean().item()
## Train with all-fake batch
# Generate batch of latent vectors
noise = torch.randn(b_size, nz, 1, 1, device=device0)
# Generate fake image batch with G
fake = netG(noise)
label.fill_(fake_label)
# Classify all fake batch with D
output = netD(fake.detach()).view(-1)
# Calculate D's loss on the all-fake batch
errD_fake = criterion(output, label)
# Calculate the gradients for this batch, accumulated (summed) with previous gradients
errD_fake.backward()
D_G_z1 = output.mean().item()
# Compute error of D as sum over the fake and the real batches
errD = errD_real + errD_fake
# Update D
optimizerD.step()
iters += 1
for iter_g in range(1):
############################
# Update G network
###########################
if if_dp:
### Sanitize the gradients passed to the Generator
dynamic_hook_function = dp_conv_hook
else:
### Only modify the gradient norm, without adding noise
dynamic_hook_function = modify_gradnorm_conv_hook
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
noise = torch.randn(b_size, nz, 1, 1, device=device0)
fake = netG(noise)
label = torch.full((b_size,), real_label, dtype=torch.float, device=device0)
netG.zero_grad()
label.fill_(real_label) # fake labels are real for generator cost
# Since we just updated D, perform another forward pass of all-fake batch through D
output = netD(fake).view(-1)
# Calculate G's loss based on this output
errG = criterion(output, label)
# Calculate gradients for G
errG.backward()
D_G_z2 = output.mean().item()
# Update G
optimizerG.step()
### update the exponential moving average
exp_mov_avg(netGS, netG, alpha=0.999, global_step=iters)
############################
### Results visualization
############################
if iters % 10 ==0:
print('iter:{}, G_cost:{:.2f}, D_cost:{:.2f}'.format(iters, errG.item(),
errD.item(),
))
if iters % args.vis_step == 0:
if dataset == 'celeba':
generate_image_celeba(str(iters+0), netGS, fixed_noise, save_dir, device0)
if iters % args.save_step==0:
### save model
torch.save(netGS.state_dict(), os.path.join(save_dir, 'netGS_%s.pth' % str(iters+0)))
torch.save(netD.state_dict(), os.path.join(save_dir, 'netD_%s.pth' % str(iters+0)))
torch.cuda.empty_cache()
#if ((iters+1) % 500 == 0):
# classify_training(netGS, dataset, iters+1)
if __name__ == '__main__':
args = parse_arguments()
save_config(args)
main(args)
|
[
"numpy.random.seed",
"torch.randn",
"torch.set_default_tensor_type",
"torch.full",
"numpy.random.randint",
"numpy.arange",
"torch.device",
"torchvision.transforms.Normalize",
"os.path.join",
"torch.utils.data.DataLoader",
"numpy.savetxt",
"random.seed",
"numpy.loadtxt",
"torchvision.transforms.CenterCrop",
"numpy.random.shuffle",
"copy.deepcopy",
"torch.randn_like",
"torch.manual_seed",
"torch.norm",
"torch.cuda.is_available",
"numpy.argwhere",
"numpy.delete",
"numpy.concatenate",
"torchvision.transforms.Resize",
"torch.utils.data.Subset",
"torch.ones_like",
"ops.exp_mov_avg",
"torch.cuda.empty_cache",
"torchvision.transforms.ToTensor"
] |
[((1654, 1692), 'torch.norm', 'torch.norm', (['grad_wrt_image'], {'p': '(2)', 'dim': '(1)'}), '(grad_wrt_image, p=2, dim=1)\n', (1664, 1692), False, 'import torch\n'), ((2455, 2493), 'torch.norm', 'torch.norm', (['grad_wrt_image'], {'p': '(2)', 'dim': '(1)'}), '(grad_wrt_image, p=2, dim=1)\n', (2465, 2493), False, 'import torch\n'), ((4009, 4034), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4032, 4034), False, 'import torch\n'), ((4544, 4573), 'random.seed', 'random.seed', (['args.random_seed'], {}), '(args.random_seed)\n', (4555, 4573), False, 'import random\n'), ((4578, 4610), 'numpy.random.seed', 'np.random.seed', (['args.random_seed'], {}), '(args.random_seed)\n', (4592, 4610), True, 'import numpy as np\n'), ((4615, 4650), 'torch.manual_seed', 'torch.manual_seed', (['args.random_seed'], {}), '(args.random_seed)\n', (4632, 4650), False, 'import torch\n'), ((7849, 7892), 'numpy.loadtxt', 'np.loadtxt', (['"""index_100k.txt"""'], {'dtype': 'np.int_'}), "('index_100k.txt', dtype=np.int_)\n", (7859, 7892), True, 'import numpy as np\n'), ((7908, 7950), 'torch.utils.data.Subset', 'torch.utils.data.Subset', (['trainset', 'indices'], {}), '(trainset, indices)\n', (7931, 7950), False, 'import torch\n'), ((8014, 8112), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainset'], {'batch_size': 'batchsize', 'shuffle': '(True)', 'num_workers': 'workers'}), '(trainset, batch_size=batchsize, shuffle=True,\n num_workers=workers)\n', (8041, 8112), False, 'import torch\n'), ((8433, 8475), 'torch.randn', 'torch.randn', (['(100)', 'nz', '(1)', '(1)'], {'device': 'device0'}), '(100, nz, 1, 1, device=device0)\n', (8444, 8475), False, 'import torch\n'), ((2601, 2627), 'torch.ones_like', 'torch.ones_like', (['clip_coef'], {}), '(clip_coef)\n', (2616, 2627), False, 'import torch\n'), ((2795, 2827), 'torch.randn_like', 'torch.randn_like', (['grad_wrt_image'], {}), '(grad_wrt_image)\n', (2811, 2827), False, 'import torch\n'), ((4050, 4100), 'torch.device', 'torch.device', (["('cuda:%d' % i if use_cuda else 'cpu')"], {}), "('cuda:%d' % i if use_cuda else 'cpu')\n", (4062, 4100), False, 'import torch\n'), ((4177, 4232), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.cuda.FloatTensor"""'], {}), "('torch.cuda.FloatTensor')\n", (4206, 4232), False, 'import torch\n'), ((6999, 7030), 'numpy.random.shuffle', 'np.random.shuffle', (['indices_full'], {}), '(indices_full)\n', (7016, 7030), True, 'import numpy as np\n'), ((7486, 7528), 'numpy.loadtxt', 'np.loadtxt', (['"""index_20k.txt"""'], {'dtype': 'np.int_'}), "('index_20k.txt', dtype=np.int_)\n", (7496, 7528), True, 'import numpy as np\n'), ((7621, 7656), 'numpy.delete', 'np.delete', (['indices_full', 'remove_idx'], {}), '(indices_full, remove_idx)\n', (7630, 7656), True, 'import numpy as np\n'), ((7726, 7773), 'numpy.concatenate', 'np.concatenate', (['(indices, indices_rest)'], {'axis': '(0)'}), '((indices, indices_rest), axis=0)\n', (7740, 7773), True, 'import numpy as np\n'), ((7782, 7834), 'numpy.savetxt', 'np.savetxt', (['"""index_40k.txt"""', 'indices_slice'], {'fmt': '"""%i"""'}), "('index_40k.txt', indices_slice, fmt='%i')\n", (7792, 7834), True, 'import numpy as np\n'), ((12673, 12697), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (12695, 12697), False, 'import torch\n'), ((4311, 4343), 'numpy.random.randint', 'np.random.randint', (['(10000)'], {'size': '(1)'}), '(10000, size=1)\n', (4328, 4343), True, 'import numpy as np\n'), ((4423, 4454), 'os.path.join', 'os.path.join', (['save_dir', '"""seed*"""'], {}), "(save_dir, 'seed*')\n", (4435, 4454), False, 'import os, sys\n'), ((5221, 5240), 'copy.deepcopy', 'copy.deepcopy', (['netG'], {}), '(netG)\n', (5234, 5240), False, 'import copy\n'), ((6806, 6822), 'numpy.arange', 'np.arange', (['(60000)'], {}), '(60000)\n', (6815, 6822), True, 'import numpy as np\n'), ((7551, 7581), 'numpy.argwhere', 'np.argwhere', (['(indices_full == x)'], {}), '(indices_full == x)\n', (7562, 7581), True, 'import numpy as np\n'), ((9063, 9131), 'torch.full', 'torch.full', (['(b_size,)', 'real_label'], {'dtype': 'torch.float', 'device': 'device0'}), '((b_size,), real_label, dtype=torch.float, device=device0)\n', (9073, 9131), False, 'import torch\n'), ((9559, 9604), 'torch.randn', 'torch.randn', (['b_size', 'nz', '(1)', '(1)'], {'device': 'device0'}), '(b_size, nz, 1, 1, device=device0)\n', (9570, 9604), False, 'import torch\n'), ((11751, 11807), 'ops.exp_mov_avg', 'exp_mov_avg', (['netGS', 'netG'], {'alpha': '(0.999)', 'global_step': 'iters'}), '(netGS, netG, alpha=0.999, global_step=iters)\n', (11762, 11807), False, 'from ops import exp_mov_avg\n'), ((6039, 6060), 'torchvision.transforms.Resize', 'transforms.Resize', (['(64)'], {}), '(64)\n', (6056, 6060), True, 'import torchvision.transforms as transforms\n'), ((6070, 6095), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(64)'], {}), '(64)\n', (6091, 6095), True, 'import torchvision.transforms as transforms\n'), ((6105, 6126), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (6124, 6126), True, 'import torchvision.transforms as transforms\n'), ((6136, 6190), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (6156, 6190), True, 'import torchvision.transforms as transforms\n'), ((6313, 6363), 'os.path.join', 'os.path.join', (['"""/work/u5366584/exp/datasets/celeba"""'], {}), "('/work/u5366584/exp/datasets/celeba')\n", (6325, 6363), False, 'import os, sys\n'), ((6887, 6903), 'numpy.arange', 'np.arange', (['(50000)'], {}), '(50000)\n', (6896, 6903), True, 'import numpy as np\n'), ((10941, 10986), 'torch.randn', 'torch.randn', (['b_size', 'nz', '(1)', '(1)'], {'device': 'device0'}), '(b_size, nz, 1, 1, device=device0)\n', (10952, 10986), False, 'import torch\n'), ((11046, 11114), 'torch.full', 'torch.full', (['(b_size,)', 'real_label'], {'dtype': 'torch.float', 'device': 'device0'}), '((b_size,), real_label, dtype=torch.float, device=device0)\n', (11056, 11114), False, 'import torch\n')]
|
import open3d as o3d
import glob, plyfile, numpy as np, multiprocessing as mp, torch
import copy
import numpy as np
import json
import pdb
import os
#CLASS_LABELS = ['cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'shower curtain', 'toilet', 'sink', 'bathtub', 'otherfurniture']
CLASS_LABELS = ['wall', 'floor', 'chair', 'table', 'desk', 'bed', 'bookshelf', 'sofa', 'sink', 'bathtub', 'toilet', 'curtain', 'counter', 'door', 'window', 'shower curtain', 'refrigerator', 'picture', 'cabinet', 'otherfurniture']
VALID_CLASS_IDS = np.array([1,2,3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39])
NYUID_TO_LABEL = {}
LABEL_TO_NYUID = {}
NYUID_TO_SEGID = {}
for i in range(len(VALID_CLASS_IDS)):
LABEL_TO_NYUID[CLASS_LABELS[i]] = VALID_CLASS_IDS[i]
NYUID_TO_LABEL [VALID_CLASS_IDS[i]] = CLASS_LABELS[i]
NYUID_TO_SEGID[VALID_CLASS_IDS[i]] = i
SELECTED_LABEL_IDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39]
LABEL_ID_TO_CLASS_ID = {
# 9: 3 #force 'desk' to be the same class_id as 'table'
}
for i, label_id in enumerate(SELECTED_LABEL_IDS):
if label_id not in LABEL_ID_TO_CLASS_ID:
LABEL_ID_TO_CLASS_ID[label_id] = i
UNKNOWN_ID = -100
MIN_INSTANCE_SIZE = 600
remapper=np.ones(500)*(-100)
for i,x in enumerate([1,2,3,4,5,6,7,8,9,10,11,12,14,16,24,28,33,34,36,39]):
remapper[x]=i
## read coordinates, color, semantic_labels, indices and dists of 2 nearest points
def f(fn):
# output_file = output_path + "/" + fn.rsplit("/", 1)[1][:-18]+'.pth'
# if os.path.exists(output_file)==True:
# print("exist:",output_file)
# return 0
a=plyfile.PlyData().read(fn)
v=np.array([list(x) for x in a.elements[0]])
coords=np.ascontiguousarray(v[:,:3])
colors=np.ascontiguousarray(v[:,3:6])/255.0 - 0.5
position=np.ascontiguousarray(v[:,8:10])
dis=np.ascontiguousarray(v[:,10:12])
# filter out very small segements and reassign instance labels
w = np.zeros((len(coords),2), dtype = np.int32)
w[:,:] = UNKNOWN_ID
semantic_labels_ori = np.array(a.elements[0]['label'])
instance_labels = np.array(a.elements[0]['instance_label'])
semantic_labels = np.array(list(
map(lambda label_id: LABEL_ID_TO_CLASS_ID[label_id] if label_id in LABEL_ID_TO_CLASS_ID else UNKNOWN_ID,
semantic_labels_ori)))
for id in range(instance_labels.max()+1):
instance_indices = (instance_labels == id)
instance_size = instance_indices.sum()
# print(instance_size)
if instance_size > MIN_INSTANCE_SIZE:
w[instance_indices,0] = semantic_labels[instance_indices]
w[instance_indices,1] = id
# print(np.unique(w[:,0]))
# print(np.unique(w[:,1]))
# w[:,0] = remapper[]
# w[:,1] = remapper[]
json_file = open(fn[:-3]+'0.010000.segs.json')
region = np.asarray(json.load(json_file)['segIndices'])
all={
"coords":coords,
"colors":colors,
"w":w,
'region': region
}
# print("save to "+ output_file)
# # pdb.set_trace()
# torch.save((coords,colors,w1,w2,position,dis),output_file )
fileName = fn[:-4] + '_instance.pth'
torch.save(all, fileName)
print(fileName)
print("avilable cpus: ", mp.cpu_count())
files = sorted(glob.glob('/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_1/train/*.ply'))
# print(files[0])
# f(files[0])
p = mp.Pool(processes=mp.cpu_count() - 4)
p.map(f, files)
p.close()
p.join()
files = sorted(glob.glob('/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_1/val/*.ply'))
p = mp.Pool(processes=mp.cpu_count() - 4)
p.map(f, files)
p.close()
p.join()
files = sorted(glob.glob('/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_2/train/*.ply'))
p = mp.Pool(processes=mp.cpu_count() - 4)
p.map(f, files)
p.close()
p.join()
files = sorted(glob.glob('/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_2/val/*.ply'))
p = mp.Pool(processes=mp.cpu_count() - 4)
p.map(f, files)
p.close()
p.join()
# # parallel
# p = mp.Pool(processes=mp.cpu_count())
# p.map(f_gene_ply,files)
# p.close()
# p.join()
|
[
"json.load",
"plyfile.PlyData",
"numpy.ones",
"torch.save",
"numpy.array",
"glob.glob",
"numpy.ascontiguousarray",
"multiprocessing.cpu_count"
] |
[((613, 698), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36,\n 39])\n', (621, 698), True, 'import numpy as np\n'), ((1322, 1334), 'numpy.ones', 'np.ones', (['(500)'], {}), '(500)\n', (1329, 1334), True, 'import numpy as np\n'), ((1800, 1830), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['v[:, :3]'], {}), '(v[:, :3])\n', (1820, 1830), True, 'import numpy as np\n'), ((1908, 1940), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['v[:, 8:10]'], {}), '(v[:, 8:10])\n', (1928, 1940), True, 'import numpy as np\n'), ((1948, 1981), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['v[:, 10:12]'], {}), '(v[:, 10:12])\n', (1968, 1981), True, 'import numpy as np\n'), ((2159, 2191), 'numpy.array', 'np.array', (["a.elements[0]['label']"], {}), "(a.elements[0]['label'])\n", (2167, 2191), True, 'import numpy as np\n'), ((2214, 2255), 'numpy.array', 'np.array', (["a.elements[0]['instance_label']"], {}), "(a.elements[0]['instance_label'])\n", (2222, 2255), True, 'import numpy as np\n'), ((3279, 3304), 'torch.save', 'torch.save', (['all', 'fileName'], {}), '(all, fileName)\n', (3289, 3304), False, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((3351, 3365), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (3363, 3365), True, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((3383, 3486), 'glob.glob', 'glob.glob', (['"""/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_1/train/*.ply"""'], {}), "(\n '/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_1/train/*.ply'\n )\n", (3392, 3486), False, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((3603, 3704), 'glob.glob', 'glob.glob', (['"""/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_1/val/*.ply"""'], {}), "(\n '/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_1/val/*.ply'\n )\n", (3612, 3704), False, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((3789, 3892), 'glob.glob', 'glob.glob', (['"""/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_2/train/*.ply"""'], {}), "(\n '/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_2/train/*.ply'\n )\n", (3798, 3892), False, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((3977, 4078), 'glob.glob', 'glob.glob', (['"""/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_2/val/*.ply"""'], {}), "(\n '/media/hdd/zhengtian/Occuseg/data/scannet_partial/instance/partial_2/val/*.ply'\n )\n", (3986, 4078), False, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((1713, 1730), 'plyfile.PlyData', 'plyfile.PlyData', ([], {}), '()\n', (1728, 1730), False, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((1841, 1872), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['v[:, 3:6]'], {}), '(v[:, 3:6])\n', (1861, 1872), True, 'import numpy as np\n'), ((2965, 2985), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (2974, 2985), False, 'import json\n'), ((3532, 3546), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (3544, 3546), True, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((3718, 3732), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (3730, 3732), True, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((3906, 3920), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (3918, 3920), True, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n'), ((4092, 4106), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (4104, 4106), True, 'import glob, plyfile, numpy as np, multiprocessing as mp, torch\n')]
|
import numpy as np
import cv2
from skimage.io import imread, imsave
from skimage.io import imshow
# lifted from http://blog.christianperone.com/2015/01/real-time-drone-object-tracking-using-python-and-opencv/
def run_main():
cap = cv2.VideoCapture('upabove.mp4')
# Read the first frame of the video
ret, frame = cap.read()
imsave("frame0001.png",cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
imshow(frame)
# Set the ROI (Region of Interest). Actually, this is a
# rectangle of the building that we're tracking
c,r,w,h = 150,250,70,70
track_window = (c,r,w,h)
# Create mask and normalized histogram
roi = frame[r:r+h, c:c+w]
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 30.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 80, 1)
while True:
ret, frame = cap.read()
if not ret:
break
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([hsv], [0], roi_hist, [0,180], 1)
ret, track_window = cv2.meanShift(dst, track_window, term_crit)
x,y,w,h = track_window
cv2.rectangle(frame, (x,y), (x+w,y+h), 255, 2)
cv2.putText(frame, 'Tracked', (x-25,y-10), cv2.FONT_HERSHEY_SIMPLEX,
1, (255,255,255), 2)
cv2.imshow('Tracking', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
run_main()
|
[
"cv2.putText",
"cv2.cvtColor",
"cv2.calcHist",
"cv2.waitKey",
"cv2.imshow",
"cv2.VideoCapture",
"cv2.rectangle",
"numpy.array",
"cv2.calcBackProject",
"skimage.io.imshow",
"cv2.normalize",
"cv2.destroyAllWindows",
"cv2.meanShift"
] |
[((237, 268), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""upabove.mp4"""'], {}), "('upabove.mp4')\n", (253, 268), False, 'import cv2\n'), ((411, 424), 'skimage.io.imshow', 'imshow', (['frame'], {}), '(frame)\n', (417, 424), False, 'from skimage.io import imshow\n'), ((683, 719), 'cv2.cvtColor', 'cv2.cvtColor', (['roi', 'cv2.COLOR_BGR2HSV'], {}), '(roi, cv2.COLOR_BGR2HSV)\n', (695, 719), False, 'import cv2\n'), ((820, 871), 'cv2.calcHist', 'cv2.calcHist', (['[hsv_roi]', '[0]', 'mask', '[180]', '[0, 180]'], {}), '([hsv_roi], [0], mask, [180], [0, 180])\n', (832, 871), False, 'import cv2\n'), ((876, 934), 'cv2.normalize', 'cv2.normalize', (['roi_hist', 'roi_hist', '(0)', '(255)', 'cv2.NORM_MINMAX'], {}), '(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)\n', (889, 934), False, 'import cv2\n'), ((1635, 1658), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1656, 1658), False, 'import cv2\n'), ((366, 404), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (378, 404), False, 'import cv2\n'), ((752, 779), 'numpy.array', 'np.array', (['(0.0, 30.0, 32.0)'], {}), '((0.0, 30.0, 32.0))\n', (760, 779), True, 'import numpy as np\n'), ((777, 808), 'numpy.array', 'np.array', (['(180.0, 255.0, 255.0)'], {}), '((180.0, 255.0, 255.0))\n', (785, 808), True, 'import numpy as np\n'), ((1123, 1161), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HSV'], {}), '(frame, cv2.COLOR_BGR2HSV)\n', (1135, 1161), False, 'import cv2\n'), ((1176, 1230), 'cv2.calcBackProject', 'cv2.calcBackProject', (['[hsv]', '[0]', 'roi_hist', '[0, 180]', '(1)'], {}), '([hsv], [0], roi_hist, [0, 180], 1)\n', (1195, 1230), False, 'import cv2\n'), ((1259, 1302), 'cv2.meanShift', 'cv2.meanShift', (['dst', 'track_window', 'term_crit'], {}), '(dst, track_window, term_crit)\n', (1272, 1302), False, 'import cv2\n'), ((1343, 1395), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(255)', '(2)'], {}), '(frame, (x, y), (x + w, y + h), 255, 2)\n', (1356, 1395), False, 'import cv2\n'), ((1398, 1498), 'cv2.putText', 'cv2.putText', (['frame', '"""Tracked"""', '(x - 25, y - 10)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(255, 255, 255)', '(2)'], {}), "(frame, 'Tracked', (x - 25, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (255, 255, 255), 2)\n", (1409, 1498), False, 'import cv2\n'), ((1517, 1546), 'cv2.imshow', 'cv2.imshow', (['"""Tracking"""', 'frame'], {}), "('Tracking', frame)\n", (1527, 1546), False, 'import cv2\n'), ((1559, 1573), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1570, 1573), False, 'import cv2\n')]
|
"""
EfficientNet for ImageNet-1K, implemented in Keras.
Original paper: 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
"""
__all__ = ['efficientnet_model', 'efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3',
'efficientnet_b4', 'efficientnet_b5', 'efficientnet_b6', 'efficientnet_b7', 'efficientnet_b0b',
'efficientnet_b1b', 'efficientnet_b2b', 'efficientnet_b3b']
import os
import math
from keras import layers as nn
from keras.models import Model
from .common import is_channels_first, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, se_block
def calc_tf_padding(x,
kernel_size,
strides=1,
dilation=1):
"""
Calculate TF-same like padding size.
Parameters:
----------
x : tensor
Input tensor.
kernel_size : int
Convolution window size.
strides : int, default 1
Strides of the convolution.
dilation : int, default 1
Dilation value for convolution layer.
Returns
-------
tuple of 4 int
The size of the padding.
"""
height, width = x.shape[2:]
oh = math.ceil(height / strides)
ow = math.ceil(width / strides)
pad_h = max((oh - 1) * strides + (kernel_size - 1) * dilation + 1 - height, 0)
pad_w = max((ow - 1) * strides + (kernel_size - 1) * dilation + 1 - width, 0)
return (pad_h // 2, pad_h - pad_h // 2), (pad_w // 2, pad_w - pad_w // 2)
def round_channels(channels,
factor,
divisor=8):
"""
Round weighted channel number.
Parameters:
----------
channels : int
Original number of channels.
factor : float
Weight factor.
divisor : int
Alignment value.
Returns
-------
int
Weighted number of channels.
"""
channels *= factor
new_channels = max(int(channels + divisor / 2.0) // divisor * divisor, divisor)
if new_channels < 0.9 * channels:
new_channels += divisor
return new_channels
def effi_dws_conv_unit(x,
in_channels,
out_channels,
strides,
bn_epsilon,
activation,
tf_mode,
name="effi_dws_conv_unit"):
"""
EfficientNet specific depthwise separable convolution block/unit with BatchNorms and activations at each convolution
layers.
Parameters:
----------
x : keras.backend tensor/variable/symbol
Input tensor/variable/symbol.
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the second convolution layer.
bn_epsilon : float
Small float added to variance in Batch norm.
activation : str
Name of activation function.
tf_mode : bool
Whether to use TF-like mode.
name : str, default 'effi_dws_conv_unit'
Block name.
Returns
-------
keras.backend tensor/variable/symbol
Resulted tensor/variable/symbol.
"""
residual = (in_channels == out_channels) and (strides == 1)
if residual:
identity = x
if tf_mode:
x = nn.ZeroPadding2D(
padding=calc_tf_padding(x, kernel_size=3),
name=name + "/dw_conv_pad")(x)
x = dwconv3x3_block(
x=x,
in_channels=in_channels,
out_channels=in_channels,
padding=(0 if tf_mode else 1),
bn_epsilon=bn_epsilon,
activation=activation,
name=name + "/dw_conv")
x = se_block(
x=x,
channels=in_channels,
reduction=4,
activation=activation,
name=name + "/se")
x = conv1x1_block(
x=x,
in_channels=in_channels,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
activation=None,
name=name + "/pw_conv")
if residual:
x = nn.add([x, identity], name=name + "/add")
return x
def effi_inv_res_unit(x,
in_channels,
out_channels,
kernel_size,
strides,
expansion_factor,
bn_epsilon,
activation,
tf_mode,
name="effi_inv_res_unit"):
"""
EfficientNet inverted residual unit.
Parameters:
----------
x : keras.backend tensor/variable/symbol
Input tensor/variable/symbol.
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
expansion_factor : int
Factor for expansion of channels.
bn_epsilon : float
Small float added to variance in Batch norm.
activation : str
Name of activation function.
tf_mode : bool
Whether to use TF-like mode.
name : str, default 'effi_inv_res_unit'
Unit name.
Returns
-------
keras.backend tensor/variable/symbol
Resulted tensor/variable/symbol.
"""
residual = (in_channels == out_channels) and (strides == 1)
mid_channels = in_channels * expansion_factor
dwconv_block_fn = dwconv3x3_block if kernel_size == 3 else (dwconv5x5_block if kernel_size == 5 else None)
if residual:
identity = x
x = conv1x1_block(
x=x,
in_channels=in_channels,
out_channels=mid_channels,
bn_epsilon=bn_epsilon,
activation=activation,
name=name + "/conv1")
if tf_mode:
x = nn.ZeroPadding2D(
padding=calc_tf_padding(x, kernel_size=kernel_size, strides=strides),
name=name + "/conv2_pad")(x)
x = dwconv_block_fn(
x=x,
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
padding=(0 if tf_mode else (kernel_size // 2)),
bn_epsilon=bn_epsilon,
activation=activation,
name=name + "/conv2")
x = se_block(
x=x,
channels=mid_channels,
reduction=24,
activation=activation,
name=name + "/se")
x = conv1x1_block(
x=x,
in_channels=mid_channels,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
activation=None,
name=name + "/conv3")
if residual:
x = nn.add([x, identity], name=name + "/add")
return x
def effi_init_block(x,
in_channels,
out_channels,
bn_epsilon,
activation,
tf_mode,
name="effi_init_block"):
"""
EfficientNet specific initial block.
Parameters:
----------
x : keras.backend tensor/variable/symbol
Input tensor/variable/symbol.
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
activation : str
Name of activation function.
tf_mode : bool
Whether to use TF-like mode.
name : str, default 'effi_init_block'
Block name.
Returns
-------
keras.backend tensor/variable/symbol
Resulted tensor/variable/symbol.
"""
if tf_mode:
x = nn.ZeroPadding2D(
padding=calc_tf_padding(x, kernel_size=3, strides=2),
name=name + "/conv_pad")(x)
x = conv3x3_block(
x=x,
in_channels=in_channels,
out_channels=out_channels,
strides=2,
padding=(0 if tf_mode else 1),
bn_epsilon=bn_epsilon,
activation=activation,
name=name + "/conv")
return x
def efficientnet_model(channels,
init_block_channels,
final_block_channels,
kernel_sizes,
strides_per_stage,
expansion_factors,
dropout_rate=0.2,
tf_mode=False,
bn_epsilon=1e-5,
in_channels=3,
in_size=(224, 224),
classes=1000):
"""
EfficientNet(-B0) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : list of 2 int
Numbers of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
kernel_sizes : list of list of int
Number of kernel sizes for each unit.
strides_per_stage : list int
Stride value for the first unit of each stage.
expansion_factors : list of list of int
Number of expansion factors for each unit.
dropout_rate : float, default 0.2
Fraction of the input units to drop. Must be a number between 0 and 1.
tf_mode : bool, default False
Whether to use TF-like mode.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
input_shape = (in_channels, in_size[0], in_size[1]) if is_channels_first() else\
(in_size[0], in_size[1], in_channels)
input = nn.Input(shape=input_shape)
activation = "swish"
x = effi_init_block(
x=input,
in_channels=in_channels,
out_channels=init_block_channels,
bn_epsilon=bn_epsilon,
activation=activation,
tf_mode=tf_mode,
name="features/init_block")
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
kernel_sizes_per_stage = kernel_sizes[i]
expansion_factors_per_stage = expansion_factors[i]
for j, out_channels in enumerate(channels_per_stage):
kernel_size = kernel_sizes_per_stage[j]
expansion_factor = expansion_factors_per_stage[j]
strides = strides_per_stage[i] if (j == 0) else 1
if i == 0:
x = effi_dws_conv_unit(
x=x,
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_epsilon=bn_epsilon,
activation=activation,
tf_mode=tf_mode,
name="features/stage{}/unit{}".format(i + 1, j + 1))
else:
x = effi_inv_res_unit(
x=x,
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
expansion_factor=expansion_factor,
bn_epsilon=bn_epsilon,
activation=activation,
tf_mode=tf_mode,
name="features/stage{}/unit{}".format(i + 1, j + 1))
in_channels = out_channels
x = conv1x1_block(
x=x,
in_channels=in_channels,
out_channels=final_block_channels,
bn_epsilon=bn_epsilon,
activation=activation,
name="features/final_block")
in_channels = final_block_channels
x = nn.GlobalAveragePooling2D(
name="features/final_pool")(x)
if dropout_rate > 0.0:
x = nn.Dropout(
rate=dropout_rate,
name="output/dropout")(x)
x = nn.Dense(
units=classes,
input_dim=in_channels,
name="output/fc")(x)
model = Model(inputs=input, outputs=x)
model.in_size = in_size
model.classes = classes
return model
def get_efficientnet(version,
in_size,
tf_mode=False,
bn_epsilon=1e-5,
model_name=None,
pretrained=False,
root=os.path.join("~", ".keras", "models"),
**kwargs):
"""
Create EfficientNet model with specific parameters.
Parameters:
----------
version : str
Version of EfficientNet ('b0'...'b7').
in_size : tuple of two ints
Spatial size of the expected input image.
tf_mode : bool, default False
Whether to use TF-like mode.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
if version == "b0":
assert (in_size == (224, 224))
depth_factor = 1.0
width_factor = 1.0
dropout_rate = 0.2
elif version == "b1":
assert (in_size == (240, 240))
depth_factor = 1.1
width_factor = 1.0
dropout_rate = 0.2
elif version == "b2":
assert (in_size == (260, 260))
depth_factor = 1.2
width_factor = 1.1
dropout_rate = 0.3
elif version == "b3":
assert (in_size == (300, 300))
depth_factor = 1.4
width_factor = 1.2
dropout_rate = 0.3
elif version == "b4":
assert (in_size == (380, 380))
depth_factor = 1.8
width_factor = 1.4
dropout_rate = 0.4
elif version == "b5":
assert (in_size == (456, 456))
depth_factor = 2.2
width_factor = 1.6
dropout_rate = 0.4
elif version == "b6":
assert (in_size == (528, 528))
depth_factor = 2.6
width_factor = 1.8
dropout_rate = 0.5
elif version == "b7":
assert (in_size == (600, 600))
depth_factor = 3.1
width_factor = 2.0
dropout_rate = 0.5
else:
raise ValueError("Unsupported EfficientNet version {}".format(version))
init_block_channels = 32
layers = [1, 2, 2, 3, 3, 4, 1]
downsample = [1, 1, 1, 1, 0, 1, 0]
channels_per_layers = [16, 24, 40, 80, 112, 192, 320]
expansion_factors_per_layers = [1, 6, 6, 6, 6, 6, 6]
kernel_sizes_per_layers = [3, 3, 5, 3, 5, 5, 3]
strides_per_stage = [1, 2, 2, 2, 1, 2, 1]
final_block_channels = 1280
layers = [int(math.ceil(li * depth_factor)) for li in layers]
channels_per_layers = [round_channels(ci, width_factor) for ci in channels_per_layers]
from functools import reduce
channels = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(channels_per_layers, layers, downsample), [])
kernel_sizes = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(kernel_sizes_per_layers, layers, downsample), [])
expansion_factors = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(expansion_factors_per_layers, layers, downsample), [])
strides_per_stage = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(strides_per_stage, layers, downsample), [])
strides_per_stage = [si[0] for si in strides_per_stage]
init_block_channels = round_channels(init_block_channels, width_factor)
if width_factor > 1.0:
assert (int(final_block_channels * width_factor) == round_channels(final_block_channels, width_factor))
final_block_channels = round_channels(final_block_channels, width_factor)
net = efficientnet_model(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
kernel_sizes=kernel_sizes,
strides_per_stage=strides_per_stage,
expansion_factors=expansion_factors,
dropout_rate=dropout_rate,
tf_mode=tf_mode,
bn_epsilon=bn_epsilon,
in_size=in_size,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def efficientnet_b0(in_size=(224, 224), **kwargs):
"""
EfficientNet-B0 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b0", in_size=in_size, model_name="efficientnet_b0", **kwargs)
def efficientnet_b1(in_size=(240, 240), **kwargs):
"""
EfficientNet-B1 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (240, 240)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b1", in_size=in_size, model_name="efficientnet_b1", **kwargs)
def efficientnet_b2(in_size=(260, 260), **kwargs):
"""
EfficientNet-B2 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (260, 260)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b2", in_size=in_size, model_name="efficientnet_b2", **kwargs)
def efficientnet_b3(in_size=(300, 300), **kwargs):
"""
EfficientNet-B3 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (300, 300)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b3", in_size=in_size, model_name="efficientnet_b3", **kwargs)
def efficientnet_b4(in_size=(380, 380), **kwargs):
"""
EfficientNet-B4 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (380, 380)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b4", in_size=in_size, model_name="efficientnet_b4", **kwargs)
def efficientnet_b5(in_size=(456, 456), **kwargs):
"""
EfficientNet-B5 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (456, 456)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b5", in_size=in_size, model_name="efficientnet_b5", **kwargs)
def efficientnet_b6(in_size=(528, 528), **kwargs):
"""
EfficientNet-B6 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (528, 528)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b6", in_size=in_size, model_name="efficientnet_b6", **kwargs)
def efficientnet_b7(in_size=(600, 600), **kwargs):
"""
EfficientNet-B7 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (600, 600)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b7", in_size=in_size, model_name="efficientnet_b7", **kwargs)
def efficientnet_b0b(in_size=(224, 224), **kwargs):
"""
EfficientNet-B0-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b0", in_size=in_size, tf_mode=True, bn_epsilon=1e-3, model_name="efficientnet_b0b",
**kwargs)
def efficientnet_b1b(in_size=(240, 240), **kwargs):
"""
EfficientNet-B1-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (240, 240)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b1", in_size=in_size, tf_mode=True, bn_epsilon=1e-3, model_name="efficientnet_b1b",
**kwargs)
def efficientnet_b2b(in_size=(260, 260), **kwargs):
"""
EfficientNet-B2-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (260, 260)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b2", in_size=in_size, tf_mode=True, bn_epsilon=1e-3, model_name="efficientnet_b2b",
**kwargs)
def efficientnet_b3b(in_size=(300, 300), **kwargs):
"""
EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (300, 300)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.keras/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b3", in_size=in_size, tf_mode=True, bn_epsilon=1e-3, model_name="efficientnet_b3b",
**kwargs)
def _test():
import numpy as np
import keras
pretrained = False
models = [
efficientnet_b0,
efficientnet_b1,
efficientnet_b2,
efficientnet_b3,
efficientnet_b4,
efficientnet_b5,
efficientnet_b6,
efficientnet_b7,
efficientnet_b0b,
efficientnet_b1b,
efficientnet_b2b,
efficientnet_b3b,
]
for model in models:
net = model(pretrained=pretrained)
# net.summary()
weight_count = keras.utils.layer_utils.count_params(net.trainable_weights)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != efficientnet_b0 or weight_count == 5288548)
assert (model != efficientnet_b1 or weight_count == 7794184)
assert (model != efficientnet_b2 or weight_count == 9109994)
assert (model != efficientnet_b3 or weight_count == 12233232)
assert (model != efficientnet_b4 or weight_count == 19341616)
assert (model != efficientnet_b5 or weight_count == 30389784)
assert (model != efficientnet_b6 or weight_count == 43040704)
assert (model != efficientnet_b7 or weight_count == 66347960)
assert (model != efficientnet_b0b or weight_count == 5288548)
assert (model != efficientnet_b1b or weight_count == 7794184)
assert (model != efficientnet_b2b or weight_count == 9109994)
assert (model != efficientnet_b3b or weight_count == 12233232)
if is_channels_first():
x = np.zeros((1, 3, net.in_size[0], net.in_size[1]), np.float32)
else:
x = np.zeros((1, net.in_size[0], net.in_size[1], 3), np.float32)
y = net.predict(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
|
[
"math.ceil",
"keras.layers.Dropout",
"keras.layers.add",
"numpy.zeros",
"keras.models.Model",
"keras.layers.GlobalAveragePooling2D",
"keras.layers.Dense",
"keras.utils.layer_utils.count_params",
"keras.layers.Input",
"os.path.join"
] |
[((1245, 1272), 'math.ceil', 'math.ceil', (['(height / strides)'], {}), '(height / strides)\n', (1254, 1272), False, 'import math\n'), ((1282, 1308), 'math.ceil', 'math.ceil', (['(width / strides)'], {}), '(width / strides)\n', (1291, 1308), False, 'import math\n'), ((9902, 9929), 'keras.layers.Input', 'nn.Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (9910, 9929), True, 'from keras import layers as nn\n'), ((12152, 12182), 'keras.models.Model', 'Model', ([], {'inputs': 'input', 'outputs': 'x'}), '(inputs=input, outputs=x)\n', (12157, 12182), False, 'from keras.models import Model\n'), ((12495, 12532), 'os.path.join', 'os.path.join', (['"""~"""', '""".keras"""', '"""models"""'], {}), "('~', '.keras', 'models')\n", (12507, 12532), False, 'import os\n'), ((4100, 4141), 'keras.layers.add', 'nn.add', (['[x, identity]'], {'name': "(name + '/add')"}), "([x, identity], name=name + '/add')\n", (4106, 4141), True, 'from keras import layers as nn\n'), ((6651, 6692), 'keras.layers.add', 'nn.add', (['[x, identity]'], {'name': "(name + '/add')"}), "([x, identity], name=name + '/add')\n", (6657, 6692), True, 'from keras import layers as nn\n'), ((11851, 11904), 'keras.layers.GlobalAveragePooling2D', 'nn.GlobalAveragePooling2D', ([], {'name': '"""features/final_pool"""'}), "(name='features/final_pool')\n", (11876, 11904), True, 'from keras import layers as nn\n'), ((12046, 12110), 'keras.layers.Dense', 'nn.Dense', ([], {'units': 'classes', 'input_dim': 'in_channels', 'name': '"""output/fc"""'}), "(units=classes, input_dim=in_channels, name='output/fc')\n", (12054, 12110), True, 'from keras import layers as nn\n'), ((25474, 25533), 'keras.utils.layer_utils.count_params', 'keras.utils.layer_utils.count_params', (['net.trainable_weights'], {}), '(net.trainable_weights)\n', (25510, 25533), False, 'import keras\n'), ((11957, 12009), 'keras.layers.Dropout', 'nn.Dropout', ([], {'rate': 'dropout_rate', 'name': '"""output/dropout"""'}), "(rate=dropout_rate, name='output/dropout')\n", (11967, 12009), True, 'from keras import layers as nn\n'), ((14883, 14911), 'math.ceil', 'math.ceil', (['(li * depth_factor)'], {}), '(li * depth_factor)\n', (14892, 14911), False, 'import math\n'), ((26484, 26544), 'numpy.zeros', 'np.zeros', (['(1, 3, net.in_size[0], net.in_size[1])', 'np.float32'], {}), '((1, 3, net.in_size[0], net.in_size[1]), np.float32)\n', (26492, 26544), True, 'import numpy as np\n'), ((26575, 26635), 'numpy.zeros', 'np.zeros', (['(1, net.in_size[0], net.in_size[1], 3)', 'np.float32'], {}), '((1, net.in_size[0], net.in_size[1], 3), np.float32)\n', (26583, 26635), True, 'import numpy as np\n')]
|
# Copyright (c) ElementAI and its affiliates.
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Script to train DCGAN on MNIST, adaptted from https://github.com/pytorch/examples/blob/master/dcgan/main.py"""
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.nn.utils import spectral_norm
from tensorboardX import SummaryWriter
import json
from gan_eval_metrics import mnist_inception_score
from lib.optim import ExtraAdam
import numpy as np
from torch.utils.data import Subset
from plot_path_tools import compute_path_stats, plot_path_stats, compute_eigenvalues,\
plot_eigenvalues
import time
import pickle
from lib import models
import torch.nn.functional as F
def load_mnist(batchSize, imageSize=32, train=True, workers=2, dataroot='./data', subset=None):
dataset = dset.MNIST(root=dataroot, train=train, download=True,
transform=transforms.Compose([
transforms.Resize(imageSize),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)),
]))
if subset is not None:
idx = np.arange(len(dataset))
np.random.RandomState(123).shuffle(idx)
dataset = Subset(dataset, idx[:subset])
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batchSize,
shuffle=True, num_workers=int(workers))
return dataloader
def normalize_module2D(module, norm, dim):
"""
Applies normalization `norm` to `module`.
Optionally uses `dim`
Returns a list of modules.
"""
if norm == 'none':
return [module]
elif norm == 'batch':
return [module, nn.BatchNorm2d(dim)]
elif norm == 'instance':
return [module, nn.InstanceNorm2d(dim)]
elif norm == 'layer':
return [module, nn.GroupNorm(1, dim)]
elif norm == 'spectral':
return [spectral_norm(module)]
else:
raise NotImplementedError('normalization [%s] is not found' % norm)
class Generator(nn.Module):
def __init__(self, ngpu, nc, ngf, nz):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
nn.ConvTranspose2d(nz, ngf * 4, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=True),
nn.Tanh()
)
def forward(self, input):
if input.is_cuda and self.ngpu > 1:
output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))
else:
output = self.main(input)
return output
class Discriminator(models.Discriminator):
def __init__(self, ngpu, nc, ndf, norm='spectral', sigmoid=True):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.norm = norm
self.sigmoid = sigmoid
# NOTE: made a special cose for BN because we don't normalize first layer
# I kept it this way to be able to load pre-trained models
if self.norm != 'batch':
self.main = nn.Sequential(
*normalize_module2D(nn.Conv2d(nc, ndf, 4, 2, 1, bias=True), norm, ndf),
nn.LeakyReLU(0.2, inplace=True),
*normalize_module2D(nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=True), norm, ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
*normalize_module2D(nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=True), norm, ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf * 4, 1, 4, 1, 0, bias=True),
)
else:
self.main = nn.Sequential(
nn.Conv2d(nc, ndf, 4, 2, 1, bias=True),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=True),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=True),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf * 4, 1, 4, 1, 0, bias=True),
)
def forward(self, input):
if input.is_cuda and self.ngpu > 1:
output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))
else:
output = self.main(input)
if self.sigmoid:
output = torch.sigmoid(output)
return output.view(-1, 1).squeeze(1)
def weights_init(m):
""" custom weights initialization called on netG and netD """
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
def define_model_loss(config):
"""returns dis/gen loss functions based on the model"""
if config.model == 'dcgan':
return dcgan_loss_dis, dcgan_loss_gen
elif config.model in ['wgan', 'wgan_gp']:
return wgan_loss_dis, wgan_loss_gen
# elif config.model == 'wgan_gp':
# return functools.partial(wgan_loss_dis, grad_penalty=True, gp_lambda=config.gp_lambda), wgan_loss_gen
else:
raise NotImplementedError('%s model is not implemented!' % config.model)
# def dcgan_loss_dis(x_real, x_fake, netD, device):
# p_real, p_gen = netD(x_real), netD(x_fake)
# criterion = nn.BCELoss()
# real_label = torch.full((p_real.size(0),), 1, device=device)
# fake_label = torch.full((p_real.size(0),), 0, device=device)
# errD_real = criterion(p_real, real_label)
# errD_gen = criterion(p_gen, fake_label)
# dis_loss = errD_real + errD_gen
# return dis_loss, p_real, p_gen
# def dcgan_loss_gen(x_fake, netD, device):
# p_gen = netD(x_fake)
# criterion = nn.BCELoss()
# real_label = torch.full((p_gen.size(0),), 1, device=device)
# gen_loss = criterion(p_gen, real_label)
# return gen_loss, p_gen
def dcgan_loss_dis(x_real, x_fake, netD, device):
p_real, p_gen = netD(x_real), netD(x_fake)
dis_loss = F.softplus(-p_real).mean() + F.softplus(p_gen).mean()
return dis_loss, p_real, p_gen
def dcgan_loss_gen(x_fake, netD, device):
p_gen = netD(x_fake)
gen_loss = F.softplus(-p_gen).mean()
return gen_loss, p_gen
def wgan_loss_gen(x_fake, netD, device):
score_gen = netD(x_fake)
gen_loss = -score_gen.mean()
return gen_loss, score_gen
def wgan_loss_dis(x_real, x_fake, netD, device):
score_real, score_gen = netD(x_real), netD(x_fake)
dis_loss = score_gen.mean() - score_real.mean()
# if grad_penalty:
# dis_loss += gp_lambda * netD.get_penalty(x_real.detach(), x_fake.detach())
return dis_loss, score_real, score_gen
def main(config):
print("Hyper-params:")
print(config)
# create exp folder and save config
exp_dir = os.path.join(config.exp_dir, config.exp_name)
if not os.path.exists(exp_dir):
os.makedirs(exp_dir)
plots_dir = os.path.join(exp_dir, 'extra_plots')
if not os.path.exists(plots_dir):
os.makedirs(plots_dir)
if config.manualSeed is None:
config.manualSeed = random.randint(1, 10000)
print("Random Seed: ", config.manualSeed)
random.seed(config.manualSeed)
torch.manual_seed(config.manualSeed)
np.random.seed(config.manualSeed)
if torch.cuda.is_available():
torch.cuda.manual_seed(config.manualSeed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device {0!s}".format(device))
dataloader = load_mnist(config.batchSize)
eval_dataloader = load_mnist(config.batchSize, subset=5000)
eig_dataloader = load_mnist(1000, train=True, subset=1000)
fixed_noise = torch.randn(64, config.nz, 1, 1, device=device)
# define the model
netG = Generator(config.ngpu, config.nc, config.ngf, config.nz).to(device)
netG.apply(weights_init)
if config.netG != '':
print('loading generator from %s' % config.netG)
netG.load_state_dict(torch.load(config.netG)['state_gen'])
print(netG)
# sigmoid = config.model == 'dcgan'
sigmoid = False
netD = Discriminator(config.ngpu, config.nc, config.ndf, config.dnorm, sigmoid).to(device)
netD.apply(weights_init)
if config.netD != '':
print('loading discriminator from %s' % config.netD)
netD.load_state_dict(torch.load(config.netD)['state_dis'])
print(netD)
# evaluation G and D
evalG = Generator(config.ngpu, config.nc, config.ngf, config.nz).to(device)
evalG.apply(weights_init)
evalD = Discriminator(config.ngpu, config.nc, config.ndf, config.dnorm, sigmoid).to(device)
evalD.apply(weights_init)
# defining the loss function
model_loss_dis, model_loss_gen = define_model_loss(config)
# # defining learning rates based on the model
# if config.model in ['wgan', 'wgan_gp']:
# config.lrG = config.lrD / config.n_critic
# warnings.warn('modifying learning rates to lrD=%f, lrG=%f' % (config.lrD, config.lrG))
if config.lrG is None:
config.lrG = config.lrD
# setup optimizer
if config.optimizer == 'adam':
optimizerD = optim.Adam(netD.parameters(), lr=config.lrD, betas=(config.beta1, config.beta2))
optimizerG = optim.Adam(netG.parameters(), lr=config.lrG, betas=(config.beta1, config.beta2))
elif config.optimizer == 'extraadam':
optimizerD = ExtraAdam(netD.parameters(), lr=config.lrD)
optimizerG = ExtraAdam(netG.parameters(), lr=config.lrG)
elif config.optimizer == 'rmsprop':
optimizerD = optim.RMSprop(netD.parameters(), lr=config.lrD)
optimizerG = optim.RMSprop(netG.parameters(), lr=config.lrG)
elif config.optimizer == 'sgd':
optimizerD = optim.SGD(netD.parameters(), lr=config.lrD, momentum=config.beta1)
optimizerG = optim.SGD(netG.parameters(), lr=config.lrG, momentum=config.beta1)
else:
raise ValueError('Optimizer %s not supported' % config.optimizer)
with open(os.path.join(exp_dir, 'config.json'), 'w') as f:
json.dump(vars(config), f, indent=4)
summary_writer = SummaryWriter(log_dir=exp_dir)
global_step = 0
torch.save({'state_gen': netG.state_dict(),
'state_dis': netD.state_dict()},
'%s/checkpoint_step_%06d.pth' % (exp_dir, global_step))
# compute and save eigen values function
def comp_and_save_eigs(step, n_eigs=20):
eig_checkpoint = torch.load('%s/checkpoint_step_%06d.pth' % (exp_dir, step),
map_location=device)
evalG.load_state_dict(eig_checkpoint['state_gen'])
evalD.load_state_dict(eig_checkpoint['state_dis'])
gen_eigs, dis_eigs, game_eigs = \
compute_eigenvalues(evalG, evalD, eig_dataloader, config,
model_loss_gen, model_loss_dis,
device, verbose=True, n_eigs=n_eigs)
np.savez(os.path.join(plots_dir, 'eigenvalues_%d' % step),
gen_eigs=gen_eigs, dis_eigs=dis_eigs, game_eigs=game_eigs)
return gen_eigs, dis_eigs, game_eigs
if config.compute_eig:
# eigenvalues of initialization
gen_eigs_init, dis_eigs_init, game_eigs_init = comp_and_save_eigs(0)
for epoch in range(config.niter):
for i, data in enumerate(dataloader, 0):
global_step += 1
############################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
###########################
# train with real
netD.zero_grad()
x_real = data[0].to(device)
batch_size = x_real.size(0)
noise = torch.randn(batch_size, config.nz, 1, 1, device=device)
x_fake = netG(noise)
errD, D_x, D_G_z1 = model_loss_dis(x_real, x_fake.detach(), netD, device)
# gradient penalty
if config.model == 'wgan_gp':
errD += config.gp_lambda * netD.get_penalty(x_real.detach(), x_fake.detach())
errD.backward()
D_x = D_x.mean().item()
D_G_z1 = D_G_z1.mean().item()
if config.optimizer == "extraadam":
if i % 2 == 0:
optimizerD.extrapolation()
else:
optimizerD.step()
else:
optimizerD.step()
# weight clipping
if config.model == 'wgan':
for p in netD.parameters():
p.data.clamp_(-config.clip, config.clip)
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
if config.model == 'dcgan' or (config.model in ['wgan', 'wgan_gp'] and i % config.n_critic == 0):
netG.zero_grad()
errG, D_G_z2 = model_loss_gen(x_fake, netD, device)
errG.backward()
D_G_z2 = D_G_z2.mean().item()
if config.optimizer == "extraadam":
if i % 2 == 0:
optimizerG.extrapolation()
else:
optimizerG.step()
else:
optimizerG.step()
if global_step % config.printFreq == 0:
print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f / %.4f'
% (epoch, config.niter, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
summary_writer.add_scalar("loss/D", errD.item(), global_step)
summary_writer.add_scalar("loss/G", errG.item(), global_step)
summary_writer.add_scalar("output/D_real", D_x, global_step)
summary_writer.add_scalar("output/D_fake", D_G_z1, global_step)
# every epoch save samples
fake = netG(fixed_noise)
# vutils.save_image(fake.detach(),
# '%s/fake_samples_step-%06d.png' % (exp_dir, global_step),
# normalize=True)
fake_grid = vutils.make_grid(fake.detach(), normalize=True)
summary_writer.add_image("G_samples", fake_grid, global_step)
# generate samples for IS evaluation
IS_fake = []
for i in range(10):
noise = torch.randn(500, config.nz, 1, 1, device=device)
IS_fake.append(netG(noise))
IS_fake = torch.cat(IS_fake)
IS_mean, IS_std = mnist_inception_score(IS_fake, device)
print("IS score: mean=%.4f, std=%.4f" % (IS_mean, IS_std))
summary_writer.add_scalar("IS_mean", IS_mean, global_step)
# do checkpointing
checkpoint = {'state_gen': netG.state_dict(),
'state_dis': netD.state_dict()}
torch.save(checkpoint, '%s/checkpoint_step_%06d.pth' % (exp_dir, global_step))
last_chkpt = '%s/checkpoint_step_%06d.pth' % (exp_dir, global_step)
if epoch == 0:
# last_chkpt = '%s/checkpoint_step_%06d.pth' % (exp_dir, 0) # for now
checkpoint_1 = torch.load(last_chkpt, map_location=device)
if config.compute_eig:
# compute eigenvalues for epoch 1, just in case
gen_eigs_curr, dis_eigs_curr, game_eigs_curr = comp_and_save_eigs(global_step)
# if (epoch + 1) % 10 == 0:
if global_step > 30000 and epoch % 5 == 0:
checkpoint_2 = torch.load(last_chkpt, map_location=device)
print("Computing path statistics...")
t = time.time()
hist = compute_path_stats(evalG, evalD, checkpoint_1, checkpoint_2, eval_dataloader,
config, model_loss_gen, model_loss_dis, device, verbose=True)
with open("%s/hist_%d.pkl" % (plots_dir, global_step), 'wb') as f:
pickle.dump(hist, f)
plot_path_stats(hist, plots_dir, summary_writer, global_step)
print("Took %.2f minutes" % ((time.time() - t) / 60.))
if config.compute_eig and global_step > 30000 and epoch % 10 == 0:
# compute eigenvalues and save them
gen_eigs_curr, dis_eigs_curr, game_eigs_curr = comp_and_save_eigs(global_step)
plot_eigenvalues([gen_eigs_init, gen_eigs_curr], [dis_eigs_init, dis_eigs_curr],
[game_eigs_init, game_eigs_curr],
['init', 'step_%d' % global_step], plots_dir, summary_writer,
step=global_step)
class Config(object):
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument('--dataroot', default='./data', help='path to dataset')
parser.add_argument('--workers', type=int, default=2, help='number of data loading workers')
parser.add_argument('--batchSize', type=int, default=100, help='input batch size')
parser.add_argument('--printFreq', type=int, default=50, help='# updates before each print')
parser.add_argument('--model', type=str, default='dcgan', choices=['dcgan', 'wgan', 'wgan_gp'],
help='model type of GAN model')
parser.add_argument('--n_critic', type=int, default=5, help='number of critic updates per generator update (wgan/wgan_gp)')
parser.add_argument('--gp_lambda', type=int, default=10, help='weight for gradient penalty (wgan_gp)')
parser.add_argument('--clip', type=float, default=0.01, help='weight clip range (wgan)')
parser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')
parser.add_argument('--ngf', type=int, default=64)
parser.add_argument('--ndf', type=int, default=64)
parser.add_argument('--nc', type=int, default=1)
parser.add_argument('--niter', type=int, default=200, help='number of epochs to train for')
parser.add_argument('--lrD', type=float, default=0.0001, help='learning rate, default=0.0002')
parser.add_argument('--lrG', type=float, default=None, help='learning rate, default=0.0002 -- same as lrD')
parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')
parser.add_argument('--beta2', type=float, default=0.999, help='beta1 for adam. default=0.999')
parser.add_argument('--optimizer', type=str, default='adam', choices=['adam', 'extraadam', 'sgd', 'rmsprop'],
help='training optimizer')
parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')
parser.add_argument('--netG', default='', help="path to netG (to continue training)")
parser.add_argument('--netD', default='', help="path to netD (to continue training)")
parser.add_argument('--dnorm', default='spectral', choices=['batch', 'spectral', 'none', 'instance', 'layer'], help="Discriminator normalization")
parser.add_argument('--exp_dir', type=str, default='EXP', help='directory of experiment')
parser.add_argument('--exp_name', type=str, default='debug', help='directory of experiment')
parser.add_argument('--manualSeed', type=int, help='manual seed')
parser.add_argument('--compute_eig', type=int, choices=[0, 1], default=0)
self.parser = parser
def parse_args(self):
return self.parser.parse_args()
if __name__ == "__main__":
main(Config().parse_args())
|
[
"pickle.dump",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.randn",
"torch.cat",
"torch.nn.InstanceNorm2d",
"torch.nn.GroupNorm",
"torchvision.transforms.Normalize",
"os.path.join",
"random.randint",
"plot_path_tools.plot_eigenvalues",
"torch.load",
"os.path.exists",
"numpy.random.RandomState",
"torchvision.transforms.ToTensor",
"random.seed",
"gan_eval_metrics.mnist_inception_score",
"torch.nn.Tanh",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.cuda.manual_seed",
"torch.nn.BatchNorm2d",
"plot_path_tools.plot_path_stats",
"torch.cuda.is_available",
"torch.nn.LeakyReLU",
"torchvision.transforms.Resize",
"torch.utils.data.Subset",
"tensorboardX.SummaryWriter",
"torch.nn.ReLU",
"os.makedirs",
"torch.nn.ConvTranspose2d",
"torch.nn.utils.spectral_norm",
"time.time",
"torch.save",
"torch.sigmoid",
"plot_path_tools.compute_eigenvalues",
"torch.nn.functional.softplus",
"plot_path_tools.compute_path_stats"
] |
[((7565, 7610), 'os.path.join', 'os.path.join', (['config.exp_dir', 'config.exp_name'], {}), '(config.exp_dir, config.exp_name)\n', (7577, 7610), False, 'import os\n'), ((7693, 7729), 'os.path.join', 'os.path.join', (['exp_dir', '"""extra_plots"""'], {}), "(exp_dir, 'extra_plots')\n", (7705, 7729), False, 'import os\n'), ((7937, 7967), 'random.seed', 'random.seed', (['config.manualSeed'], {}), '(config.manualSeed)\n', (7948, 7967), False, 'import random\n'), ((7972, 8008), 'torch.manual_seed', 'torch.manual_seed', (['config.manualSeed'], {}), '(config.manualSeed)\n', (7989, 8008), False, 'import torch\n'), ((8013, 8046), 'numpy.random.seed', 'np.random.seed', (['config.manualSeed'], {}), '(config.manualSeed)\n', (8027, 8046), True, 'import numpy as np\n'), ((8054, 8079), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8077, 8079), False, 'import torch\n'), ((8445, 8492), 'torch.randn', 'torch.randn', (['(64)', 'config.nz', '(1)', '(1)'], {'device': 'device'}), '(64, config.nz, 1, 1, device=device)\n', (8456, 8492), False, 'import torch\n'), ((10854, 10884), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {'log_dir': 'exp_dir'}), '(log_dir=exp_dir)\n', (10867, 10884), False, 'from tensorboardX import SummaryWriter\n'), ((1623, 1652), 'torch.utils.data.Subset', 'Subset', (['dataset', 'idx[:subset]'], {}), '(dataset, idx[:subset])\n', (1629, 1652), False, 'from torch.utils.data import Subset\n'), ((7622, 7645), 'os.path.exists', 'os.path.exists', (['exp_dir'], {}), '(exp_dir)\n', (7636, 7645), False, 'import os\n'), ((7655, 7675), 'os.makedirs', 'os.makedirs', (['exp_dir'], {}), '(exp_dir)\n', (7666, 7675), False, 'import os\n'), ((7741, 7766), 'os.path.exists', 'os.path.exists', (['plots_dir'], {}), '(plots_dir)\n', (7755, 7766), False, 'import os\n'), ((7776, 7798), 'os.makedirs', 'os.makedirs', (['plots_dir'], {}), '(plots_dir)\n', (7787, 7798), False, 'import os\n'), ((7862, 7886), 'random.randint', 'random.randint', (['(1)', '(10000)'], {}), '(1, 10000)\n', (7876, 7886), False, 'import random\n'), ((8089, 8130), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['config.manualSeed'], {}), '(config.manualSeed)\n', (8111, 8130), False, 'import torch\n'), ((11190, 11275), 'torch.load', 'torch.load', (["('%s/checkpoint_step_%06d.pth' % (exp_dir, step))"], {'map_location': 'device'}), "('%s/checkpoint_step_%06d.pth' % (exp_dir, step), map_location=device\n )\n", (11200, 11275), False, 'import torch\n'), ((11479, 11609), 'plot_path_tools.compute_eigenvalues', 'compute_eigenvalues', (['evalG', 'evalD', 'eig_dataloader', 'config', 'model_loss_gen', 'model_loss_dis', 'device'], {'verbose': '(True)', 'n_eigs': 'n_eigs'}), '(evalG, evalD, eig_dataloader, config, model_loss_gen,\n model_loss_dis, device, verbose=True, n_eigs=n_eigs)\n', (11498, 11609), False, 'from plot_path_tools import compute_path_stats, plot_path_stats, compute_eigenvalues, plot_eigenvalues\n'), ((15201, 15219), 'torch.cat', 'torch.cat', (['IS_fake'], {}), '(IS_fake)\n', (15210, 15219), False, 'import torch\n'), ((15247, 15285), 'gan_eval_metrics.mnist_inception_score', 'mnist_inception_score', (['IS_fake', 'device'], {}), '(IS_fake, device)\n', (15268, 15285), False, 'from gan_eval_metrics import mnist_inception_score\n'), ((15564, 15642), 'torch.save', 'torch.save', (['checkpoint', "('%s/checkpoint_step_%06d.pth' % (exp_dir, global_step))"], {}), "(checkpoint, '%s/checkpoint_step_%06d.pth' % (exp_dir, global_step))\n", (15574, 15642), False, 'import torch\n'), ((17362, 17387), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (17385, 17387), False, 'import argparse\n'), ((2610, 2662), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['nz', '(ngf * 4)', '(4)', '(1)', '(0)'], {'bias': '(False)'}), '(nz, ngf * 4, 4, 1, 0, bias=False)\n', (2628, 2662), True, 'import torch.nn as nn\n'), ((2676, 2699), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(ngf * 4)'], {}), '(ngf * 4)\n', (2690, 2699), True, 'import torch.nn as nn\n'), ((2713, 2726), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (2720, 2726), True, 'import torch.nn as nn\n'), ((2741, 2798), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(ngf * 4)', '(ngf * 2)', '(4)', '(2)', '(1)'], {'bias': '(False)'}), '(ngf * 4, ngf * 2, 4, 2, 1, bias=False)\n', (2759, 2798), True, 'import torch.nn as nn\n'), ((2812, 2835), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(ngf * 2)'], {}), '(ngf * 2)\n', (2826, 2835), True, 'import torch.nn as nn\n'), ((2849, 2862), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (2856, 2862), True, 'import torch.nn as nn\n'), ((2877, 2930), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(ngf * 2)', 'ngf', '(4)', '(2)', '(1)'], {'bias': '(False)'}), '(ngf * 2, ngf, 4, 2, 1, bias=False)\n', (2895, 2930), True, 'import torch.nn as nn\n'), ((2944, 2963), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['ngf'], {}), '(ngf)\n', (2958, 2963), True, 'import torch.nn as nn\n'), ((2977, 2990), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (2984, 2990), True, 'import torch.nn as nn\n'), ((3005, 3052), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['ngf', 'nc', '(4)', '(2)', '(1)'], {'bias': '(True)'}), '(ngf, nc, 4, 2, 1, bias=True)\n', (3023, 3052), True, 'import torch.nn as nn\n'), ((3066, 3075), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (3073, 3075), True, 'import torch.nn as nn\n'), ((5086, 5107), 'torch.sigmoid', 'torch.sigmoid', (['output'], {}), '(output)\n', (5099, 5107), False, 'import torch\n'), ((6944, 6962), 'torch.nn.functional.softplus', 'F.softplus', (['(-p_gen)'], {}), '(-p_gen)\n', (6954, 6962), True, 'import torch.nn.functional as F\n'), ((8168, 8193), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8191, 8193), False, 'import torch\n'), ((10738, 10774), 'os.path.join', 'os.path.join', (['exp_dir', '"""config.json"""'], {}), "(exp_dir, 'config.json')\n", (10750, 10774), False, 'import os\n'), ((11687, 11735), 'os.path.join', 'os.path.join', (['plots_dir', "('eigenvalues_%d' % step)"], {}), "(plots_dir, 'eigenvalues_%d' % step)\n", (11699, 11735), False, 'import os\n'), ((12435, 12490), 'torch.randn', 'torch.randn', (['batch_size', 'config.nz', '(1)', '(1)'], {'device': 'device'}), '(batch_size, config.nz, 1, 1, device=device)\n', (12446, 12490), False, 'import torch\n'), ((15094, 15142), 'torch.randn', 'torch.randn', (['(500)', 'config.nz', '(1)', '(1)'], {'device': 'device'}), '(500, config.nz, 1, 1, device=device)\n', (15105, 15142), False, 'import torch\n'), ((15853, 15896), 'torch.load', 'torch.load', (['last_chkpt'], {'map_location': 'device'}), '(last_chkpt, map_location=device)\n', (15863, 15896), False, 'import torch\n'), ((16207, 16250), 'torch.load', 'torch.load', (['last_chkpt'], {'map_location': 'device'}), '(last_chkpt, map_location=device)\n', (16217, 16250), False, 'import torch\n'), ((16317, 16328), 'time.time', 'time.time', ([], {}), '()\n', (16326, 16328), False, 'import time\n'), ((16349, 16496), 'plot_path_tools.compute_path_stats', 'compute_path_stats', (['evalG', 'evalD', 'checkpoint_1', 'checkpoint_2', 'eval_dataloader', 'config', 'model_loss_gen', 'model_loss_dis', 'device'], {'verbose': '(True)'}), '(evalG, evalD, checkpoint_1, checkpoint_2,\n eval_dataloader, config, model_loss_gen, model_loss_dis, device,\n verbose=True)\n', (16367, 16496), False, 'from plot_path_tools import compute_path_stats, plot_path_stats, compute_eigenvalues, plot_eigenvalues\n'), ((16657, 16718), 'plot_path_tools.plot_path_stats', 'plot_path_stats', (['hist', 'plots_dir', 'summary_writer', 'global_step'], {}), '(hist, plots_dir, summary_writer, global_step)\n', (16672, 16718), False, 'from plot_path_tools import compute_path_stats, plot_path_stats, compute_eigenvalues, plot_eigenvalues\n'), ((17015, 17217), 'plot_path_tools.plot_eigenvalues', 'plot_eigenvalues', (['[gen_eigs_init, gen_eigs_curr]', '[dis_eigs_init, dis_eigs_curr]', '[game_eigs_init, game_eigs_curr]', "['init', 'step_%d' % global_step]", 'plots_dir', 'summary_writer'], {'step': 'global_step'}), "([gen_eigs_init, gen_eigs_curr], [dis_eigs_init,\n dis_eigs_curr], [game_eigs_init, game_eigs_curr], ['init', 'step_%d' %\n global_step], plots_dir, summary_writer, step=global_step)\n", (17031, 17217), False, 'from plot_path_tools import compute_path_stats, plot_path_stats, compute_eigenvalues, plot_eigenvalues\n'), ((1565, 1591), 'numpy.random.RandomState', 'np.random.RandomState', (['(123)'], {}), '(123)\n', (1586, 1591), True, 'import numpy as np\n'), ((2099, 2118), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['dim'], {}), '(dim)\n', (2113, 2118), True, 'import torch.nn as nn\n'), ((3885, 3916), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (3897, 3916), True, 'import torch.nn as nn\n'), ((4032, 4063), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (4044, 4063), True, 'import torch.nn as nn\n'), ((4183, 4214), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (4195, 4214), True, 'import torch.nn as nn\n'), ((4233, 4274), 'torch.nn.Conv2d', 'nn.Conv2d', (['(ndf * 4)', '(1)', '(4)', '(1)', '(0)'], {'bias': '(True)'}), '(ndf * 4, 1, 4, 1, 0, bias=True)\n', (4242, 4274), True, 'import torch.nn as nn\n'), ((4359, 4397), 'torch.nn.Conv2d', 'nn.Conv2d', (['nc', 'ndf', '(4)', '(2)', '(1)'], {'bias': '(True)'}), '(nc, ndf, 4, 2, 1, bias=True)\n', (4368, 4397), True, 'import torch.nn as nn\n'), ((4415, 4446), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (4427, 4446), True, 'import torch.nn as nn\n'), ((4465, 4508), 'torch.nn.Conv2d', 'nn.Conv2d', (['ndf', '(ndf * 2)', '(4)', '(2)', '(1)'], {'bias': '(True)'}), '(ndf, ndf * 2, 4, 2, 1, bias=True)\n', (4474, 4508), True, 'import torch.nn as nn\n'), ((4526, 4549), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(ndf * 2)'], {}), '(ndf * 2)\n', (4540, 4549), True, 'import torch.nn as nn\n'), ((4567, 4598), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (4579, 4598), True, 'import torch.nn as nn\n'), ((4617, 4664), 'torch.nn.Conv2d', 'nn.Conv2d', (['(ndf * 2)', '(ndf * 4)', '(4)', '(2)', '(1)'], {'bias': '(True)'}), '(ndf * 2, ndf * 4, 4, 2, 1, bias=True)\n', (4626, 4664), True, 'import torch.nn as nn\n'), ((4682, 4705), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(ndf * 4)'], {}), '(ndf * 4)\n', (4696, 4705), True, 'import torch.nn as nn\n'), ((4723, 4754), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (4735, 4754), True, 'import torch.nn as nn\n'), ((4773, 4814), 'torch.nn.Conv2d', 'nn.Conv2d', (['(ndf * 4)', '(1)', '(4)', '(1)', '(0)'], {'bias': '(True)'}), '(ndf * 4, 1, 4, 1, 0, bias=True)\n', (4782, 4814), True, 'import torch.nn as nn\n'), ((6771, 6790), 'torch.nn.functional.softplus', 'F.softplus', (['(-p_real)'], {}), '(-p_real)\n', (6781, 6790), True, 'import torch.nn.functional as F\n'), ((6800, 6817), 'torch.nn.functional.softplus', 'F.softplus', (['p_gen'], {}), '(p_gen)\n', (6810, 6817), True, 'import torch.nn.functional as F\n'), ((8737, 8760), 'torch.load', 'torch.load', (['config.netG'], {}), '(config.netG)\n', (8747, 8760), False, 'import torch\n'), ((9093, 9116), 'torch.load', 'torch.load', (['config.netD'], {}), '(config.netD)\n', (9103, 9116), False, 'import torch\n'), ((16623, 16643), 'pickle.dump', 'pickle.dump', (['hist', 'f'], {}), '(hist, f)\n', (16634, 16643), False, 'import pickle\n'), ((1314, 1342), 'torchvision.transforms.Resize', 'transforms.Resize', (['imageSize'], {}), '(imageSize)\n', (1331, 1342), True, 'import torchvision.transforms as transforms\n'), ((1373, 1394), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1392, 1394), True, 'import torchvision.transforms as transforms\n'), ((1425, 1461), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5,)', '(0.5,)'], {}), '((0.5,), (0.5,))\n', (1445, 1461), True, 'import torchvision.transforms as transforms\n'), ((2173, 2195), 'torch.nn.InstanceNorm2d', 'nn.InstanceNorm2d', (['dim'], {}), '(dim)\n', (2190, 2195), True, 'import torch.nn as nn\n'), ((2247, 2267), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(1)', 'dim'], {}), '(1, dim)\n', (2259, 2267), True, 'import torch.nn as nn\n'), ((3817, 3855), 'torch.nn.Conv2d', 'nn.Conv2d', (['nc', 'ndf', '(4)', '(2)', '(1)'], {'bias': '(True)'}), '(nc, ndf, 4, 2, 1, bias=True)\n', (3826, 3855), True, 'import torch.nn as nn\n'), ((3955, 3998), 'torch.nn.Conv2d', 'nn.Conv2d', (['ndf', '(ndf * 2)', '(4)', '(2)', '(1)'], {'bias': '(True)'}), '(ndf, ndf * 2, 4, 2, 1, bias=True)\n', (3964, 3998), True, 'import torch.nn as nn\n'), ((4102, 4149), 'torch.nn.Conv2d', 'nn.Conv2d', (['(ndf * 2)', '(ndf * 4)', '(4)', '(2)', '(1)'], {'bias': '(True)'}), '(ndf * 2, ndf * 4, 4, 2, 1, bias=True)\n', (4111, 4149), True, 'import torch.nn as nn\n'), ((2314, 2335), 'torch.nn.utils.spectral_norm', 'spectral_norm', (['module'], {}), '(module)\n', (2327, 2335), False, 'from torch.nn.utils import spectral_norm\n'), ((16762, 16773), 'time.time', 'time.time', ([], {}), '()\n', (16771, 16773), False, 'import time\n')]
|
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from src.system import System
def plot():
data = {
"hp": {
"cop": 3.0
},
"swhe": {
"pipe": {
"outer-dia": 0.02667,
"inner-dia": 0.0215392,
"length": 100,
"density": 950,
"conductivity": 0.4
},
"diameter": 1.2,
"horizontal-spacing": 0.05,
"vertical-spacing": 0.05,
},
"fluid": {
"fluid-name": "PG",
"concentration": 20
}
}
system = System(data)
x = np.arange(-3000, 3000, 200)
y_a = [system.simulate(m, 0.1, 15) for m in x]
y_b = [system.simulate(m, 0.25, 15) for m in x]
y_c = [system.simulate(m, 1.0, 15) for m in x]
fig, ax = plt.subplots()
ax.plot(x, y_a, label=r"$T_{appr}$ $\dot{m}=0.10$ [kg/s]")
ax.plot(x, y_b, label=r"$T_{appr}$ $\dot{m}=0.25$ [kg/s]", linestyle="--")
ax.plot(x, y_c, label=r"$T_{appr}$ $\dot{m}=1.00$ [kg/s]", linestyle=":")
ax.set_xlabel(r"$\dot{q}_{zone}$ [W]")
ax.set_ylabel(r"$T_{appr}$ [C]")
ax.legend()
ax.grid()
f_name = Path(__file__).parent / "_system_approach_temp.png"
plt.savefig(f_name, bbox_inches="tight")
if __name__ == "__main__":
plot()
|
[
"src.system.System",
"pathlib.Path",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] |
[((648, 660), 'src.system.System', 'System', (['data'], {}), '(data)\n', (654, 660), False, 'from src.system import System\n'), ((670, 697), 'numpy.arange', 'np.arange', (['(-3000)', '(3000)', '(200)'], {}), '(-3000, 3000, 200)\n', (679, 697), True, 'import numpy as np\n'), ((866, 880), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (878, 880), True, 'import matplotlib.pyplot as plt\n'), ((1281, 1321), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f_name'], {'bbox_inches': '"""tight"""'}), "(f_name, bbox_inches='tight')\n", (1292, 1321), True, 'import matplotlib.pyplot as plt\n'), ((1225, 1239), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1229, 1239), False, 'from pathlib import Path\n')]
|
# analyze binom_test to each pair
# for further analyze ANOVA
# gt/-our gt/-nerf -our/gt -our/nerf -nerf/gt nerf/-our
# 40 1 38 77 1 75
# 78 78 78 78 78 78
from scipy import stats
import numpy as np
# choose us, or nerf is no us
choose = [64, 110, 111]
stimuli = ["our-gt", "our-nerf", "nerf-gt"]
total = 60*2
binresult = []
for eachChoose in choose:
prob = stats.binom_test(eachChoose, n=total, p=0.5, alternative="greater")
print(prob)
binresult.append(prob)
np.savetxt("bintest.csv", binresult)
|
[
"numpy.savetxt",
"scipy.stats.binom_test"
] |
[((525, 561), 'numpy.savetxt', 'np.savetxt', (['"""bintest.csv"""', 'binresult'], {}), "('bintest.csv', binresult)\n", (535, 561), True, 'import numpy as np\n'), ((413, 480), 'scipy.stats.binom_test', 'stats.binom_test', (['eachChoose'], {'n': 'total', 'p': '(0.5)', 'alternative': '"""greater"""'}), "(eachChoose, n=total, p=0.5, alternative='greater')\n", (429, 480), False, 'from scipy import stats\n')]
|
"""Plots (and/or saves) the graphical trading data using Matplotlib"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from models.Trading import TechnicalAnalysis
import datetime, re, sys
sys.path.append('.')
class TradingGraphs():
def __init__(self, technicalAnalysis):
"""Trading Graphs object model
Parameters
----------
technicalAnalysis : object
TechnicalAnalysis object to provide the trading data to visualise
"""
# validates the technicalAnalysis object
if not isinstance(technicalAnalysis, TechnicalAnalysis):
raise TypeError('Coinbase Pro model required.')
# only one figure can be open at a time, close all open figures
plt.close('all')
self.technicalAnalysis = technicalAnalysis
# stores the pandas dataframe from technicalAnalysis object
self.df = technicalAnalysis.getDataFrame()
# stores the support and resistance levels from technicalAnalysis object
self.levels = technicalAnalysis.supportResistanceLevels()
# seaborn style plots
plt.style.use('seaborn')
def renderBuySellSignalEMA1226(self, saveFile='', saveOnly=False):
"""Render the EMA12 and EMA26 buy and sell signals
Parameters
----------
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
buysignals = self.df[self.df.ema12gtema26co == True]
sellsignals = self.df[self.df.ema12ltema26co == True]
plt.subplot(111)
plt.plot(self.df.close, label="price", color="royalblue")
plt.plot(self.df.ema12, label="ema12", color="orange")
plt.plot(self.df.ema26, label="ema26", color="purple")
plt.ylabel('Price')
for idx in buysignals.index.tolist():
plt.axvline(x=idx, color='green')
for idx in sellsignals.index.tolist():
plt.axvline(x=idx, color='red')
plt.xticks(rotation=90)
plt.tight_layout()
plt.legend()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderBuySellSignalEMA1226MACD(self, saveFile='', saveOnly=False):
"""Render the EMA12, EMA26 and MACD buy and sell signals
Parameters
----------
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
buysignals = ((self.df.ema12gtema26co == True) & (self.df.macdgtsignal == True) & (self.df.obv_pc >= 2)) | ((self.df.ema12gtema26 == True) & (self.df.macdgtsignal == True) & (self.df.obv_pc >= 5))
sellsignals = ((self.df.ema12ltema26co == True) & (self.df.macdltsignal == True)) | ((self.df.ema12gtema26 == True) & (self.df.macdltsignal == True) & (self.df.obv_pc < 0))
df_signals = self.df[(buysignals) | (sellsignals)]
ax1 = plt.subplot(211)
plt.plot(self.df.close, label="price", color="royalblue")
plt.plot(self.df.ema12, label="ema12", color="orange")
plt.plot(self.df.ema26, label="ema26", color="purple")
plt.ylabel('Price')
action = ''
last_action = ''
for idx, row in df_signals.iterrows():
if row['ema12gtema26co'] == True and row['macdgtsignal'] == True and last_action != 'buy':
action = 'buy'
plt.axvline(x=idx, color='green')
elif row['ema12ltema26'] == True and row['macdltsignal'] == True and action == 'buy':
action = 'sell'
plt.axvline(x=idx, color='red')
last_action = action
plt.xticks(rotation=90)
plt.subplot(212, sharex=ax1)
plt.plot(self.df.macd, label="macd")
plt.plot(self.df.signal, label="signal")
plt.legend()
plt.ylabel('Divergence')
plt.xticks(rotation=90)
plt.tight_layout()
plt.legend()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderPriceEMA12EMA26(self, saveFile='', saveOnly=False):
"""Render the price, EMA12 and EMA26
Parameters
----------
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
plt.subplot(111)
plt.plot(self.df.close, label="price")
plt.plot(self.df.ema12, label="ema12")
plt.plot(self.df.ema26, label="ema26")
plt.legend()
plt.ylabel('Price')
plt.xticks(rotation=90)
plt.tight_layout()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderPriceSupportResistance(self, saveFile='', saveOnly=False):
"""Render the price, support and resistance levels
Parameters
----------
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
plt.subplot(111)
plt.plot(self.df.close)
plt.ylabel('Price')
for level in self.levels:
plt.axhline(y=level, color='grey')
plt.xticks(rotation=90)
plt.tight_layout()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderEMAandMACD(self, period=30, saveFile='', saveOnly=False):
"""Render the price, EMA12, EMA26 and MACD
Parameters
----------
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
if not isinstance(period, int):
raise TypeError('Period parameter is not perioderic.')
if period < 1 or period > len(self.df):
raise ValueError('Period is out of range')
df_subset = self.df.iloc[-period::]
date = pd.to_datetime(df_subset.index).to_pydatetime()
df_subset_length = len(df_subset)
indices = np.arange(df_subset_length) # the evenly spaced plot indices
def format_date(x, pos=None): #pylint: disable=unused-argument
thisind = np.clip(int(x + 0.5), 0, df_subset_length - 1)
return date[thisind].strftime('%Y-%m-%d %H:%M:%S')
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(12, 6))
fig.suptitle(df_subset.iloc[0]['market'] + ' | ' + str(df_subset.iloc[0]['granularity']), fontsize=16)
plt.style.use('seaborn')
plt.xticks(rotation=90)
#plt.tight_layout()
indices = np.arange(len(df_subset))
ax1.plot(indices, df_subset['close'], label='price', color='royalblue')
ax1.plot(indices, df_subset['ema12'], label='ema12', color='orange')
ax1.plot(indices, df_subset['ema26'], label='ema26', color='purple')
ax1.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
ax1.set_title('Price, EMA12 and EMA26')
ax1.set_ylabel('Price')
ax1.legend()
fig.autofmt_xdate()
ax2.plot(indices, df_subset.macd, label='macd')
ax2.plot(indices, df_subset.signal, label='signal')
ax2.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
ax2.set_title('MACD')
ax2.set_ylabel('Divergence')
ax2.legend()
fig.autofmt_xdate()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderSeasonalARIMAModel(self, saveFile='', saveOnly=False):
"""Render the seasonal ARIMA model
Parameters
----------
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
fittedValues = self.technicalAnalysis.seasonalARIMAModelFittedValues()
plt.plot(self.df['close'], label='original')
plt.plot(fittedValues, color='red', label='fitted')
plt.title('RSS: %.4f' % sum((fittedValues-self.df['close'])**2))
plt.legend()
plt.ylabel('Price')
plt.xticks(rotation=90)
plt.tight_layout()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderSeasonalARIMAModelPredictionDays(self, days=30, saveFile='', saveOnly=False):
"""Render the seasonal ARIMA model prediction
Parameters
----------
days : int
Number of days to predict
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
results_ARIMA = self.technicalAnalysis.seasonalARIMAModel()
df = pd.DataFrame(self.df['close'])
start_date = df.last_valid_index()
end_date = start_date + datetime.timedelta(days=days)
pred = results_ARIMA.predict(start=str(start_date), end=str(end_date), dynamic=True)
plt.plot(pred, label='prediction')
plt.ylabel('Price')
plt.xlabel('Days')
plt.xticks(rotation=90)
plt.tight_layout()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderSMAandMACD(self, saveFile='', saveOnly=False):
"""Render the price, SMA20, SMA50, and SMA200
Parameters
----------
saveFile : str, optional
Save the figure
saveOnly : bool
Save the figure without displaying it
"""
ax1 = plt.subplot(211)
plt.plot(self.df.close, label="price")
plt.plot(self.df.sma20, label="sma20")
plt.plot(self.df.sma50, label="sma50")
plt.plot(self.df.sma200, label="sma200")
plt.legend()
plt.ylabel('Price')
plt.xticks(rotation=90)
plt.subplot(212, sharex=ax1)
plt.plot(self.df.macd, label="macd")
plt.plot(self.df.signal, label="signal")
plt.legend()
plt.ylabel('Price')
plt.xlabel('Days')
plt.xticks(rotation=90)
plt.tight_layout()
try:
if saveFile != '':
plt.savefig(saveFile)
except OSError:
raise SystemExit('Unable to save: ', saveFile)
if saveOnly == False:
plt.show()
def renderEMA12EMA26CloseCandles(self, period=30, outputpng=''):
if not isinstance(period, int):
raise TypeError('Period parameter is not perioderic.')
if period < 1 or period > len(self.df):
raise ValueError('Period is out of range')
df_subset = self.df.iloc[-period::]
fig, axes = plt.subplots(ncols=1, figsize=(12, 6)) #pylint: disable=unused-variable
fig.autofmt_xdate()
ax1 = plt.subplot(111)
ax1.set_title(df_subset.iloc[0]['market'] + ' | ' + str(df_subset.iloc[0]['granularity']))
plt.style.use('seaborn')
plt.plot(df_subset['close'], label='price', color='royalblue')
plt.plot(df_subset['ema12'], label='ema12', color='orange')
plt.plot(df_subset['ema26'], label='ema26', color='purple')
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
df_candlestick = self.df[self.df['three_white_soldiers'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'gx')
df_candlestick = self.df[self.df['three_black_crows'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'rx')
df_candlestick = self.df[self.df['inverted_hammer'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'g^')
df_candlestick = self.df[self.df['hammer'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'rv')
df_candlestick = self.df[self.df['hanging_man'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'go')
df_candlestick = self.df[self.df['shooting_star'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'r*')
df_candlestick = self.df[self.df['doji'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'yd')
df_candlestick = self.df[self.df['three_line_strike'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'y^')
df_candlestick = self.df[self.df['two_black_gapping'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'yv')
df_candlestick = self.df[self.df['evening_star'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'mv')
df_candlestick = self.df[self.df['abandoned_baby'] == True]
df_candlestick_in_range = df_candlestick[df_candlestick.index >= np.min(df_subset.index)]
for idx in df_candlestick_in_range.index.tolist():
plt.plot(idx, df_candlestick_in_range.loc[idx]['close'], 'm^')
plt.ylabel('Price')
plt.xticks(rotation=90)
plt.tight_layout()
plt.legend()
if outputpng != '':
plt.savefig(outputpng)
plt.show()
|
[
"matplotlib.pyplot.style.use",
"numpy.arange",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.tight_layout",
"sys.path.append",
"pandas.DataFrame",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.close",
"datetime.timedelta",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"numpy.min",
"matplotlib.ticker.FuncFormatter",
"pandas.to_datetime",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] |
[((248, 268), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (263, 268), False, 'import datetime, re, sys\n'), ((799, 815), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (808, 815), True, 'import matplotlib.pyplot as plt\n'), ((1175, 1199), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (1188, 1199), True, 'import matplotlib.pyplot as plt\n'), ((1659, 1675), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (1670, 1675), True, 'import matplotlib.pyplot as plt\n'), ((1684, 1741), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.close'], {'label': '"""price"""', 'color': '"""royalblue"""'}), "(self.df.close, label='price', color='royalblue')\n", (1692, 1741), True, 'import matplotlib.pyplot as plt\n'), ((1750, 1804), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.ema12'], {'label': '"""ema12"""', 'color': '"""orange"""'}), "(self.df.ema12, label='ema12', color='orange')\n", (1758, 1804), True, 'import matplotlib.pyplot as plt\n'), ((1813, 1867), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.ema26'], {'label': '"""ema26"""', 'color': '"""purple"""'}), "(self.df.ema26, label='ema26', color='purple')\n", (1821, 1867), True, 'import matplotlib.pyplot as plt\n'), ((1876, 1895), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (1886, 1895), True, 'import matplotlib.pyplot as plt\n'), ((2090, 2113), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (2100, 2113), True, 'import matplotlib.pyplot as plt\n'), ((2122, 2140), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2138, 2140), True, 'import matplotlib.pyplot as plt\n'), ((2149, 2161), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2159, 2161), True, 'import matplotlib.pyplot as plt\n'), ((3189, 3205), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (3200, 3205), True, 'import matplotlib.pyplot as plt\n'), ((3214, 3271), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.close'], {'label': '"""price"""', 'color': '"""royalblue"""'}), "(self.df.close, label='price', color='royalblue')\n", (3222, 3271), True, 'import matplotlib.pyplot as plt\n'), ((3280, 3334), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.ema12'], {'label': '"""ema12"""', 'color': '"""orange"""'}), "(self.df.ema12, label='ema12', color='orange')\n", (3288, 3334), True, 'import matplotlib.pyplot as plt\n'), ((3343, 3397), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.ema26'], {'label': '"""ema26"""', 'color': '"""purple"""'}), "(self.df.ema26, label='ema26', color='purple')\n", (3351, 3397), True, 'import matplotlib.pyplot as plt\n'), ((3406, 3425), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (3416, 3425), True, 'import matplotlib.pyplot as plt\n'), ((3924, 3947), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (3934, 3947), True, 'import matplotlib.pyplot as plt\n'), ((3957, 3985), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {'sharex': 'ax1'}), '(212, sharex=ax1)\n', (3968, 3985), True, 'import matplotlib.pyplot as plt\n'), ((3994, 4030), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.macd'], {'label': '"""macd"""'}), "(self.df.macd, label='macd')\n", (4002, 4030), True, 'import matplotlib.pyplot as plt\n'), ((4039, 4079), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.signal'], {'label': '"""signal"""'}), "(self.df.signal, label='signal')\n", (4047, 4079), True, 'import matplotlib.pyplot as plt\n'), ((4088, 4100), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4098, 4100), True, 'import matplotlib.pyplot as plt\n'), ((4109, 4133), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Divergence"""'], {}), "('Divergence')\n", (4119, 4133), True, 'import matplotlib.pyplot as plt\n'), ((4142, 4165), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (4152, 4165), True, 'import matplotlib.pyplot as plt\n'), ((4175, 4193), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4191, 4193), True, 'import matplotlib.pyplot as plt\n'), ((4202, 4214), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4212, 4214), True, 'import matplotlib.pyplot as plt\n'), ((4760, 4776), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (4771, 4776), True, 'import matplotlib.pyplot as plt\n'), ((4785, 4823), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.close'], {'label': '"""price"""'}), "(self.df.close, label='price')\n", (4793, 4823), True, 'import matplotlib.pyplot as plt\n'), ((4832, 4870), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.ema12'], {'label': '"""ema12"""'}), "(self.df.ema12, label='ema12')\n", (4840, 4870), True, 'import matplotlib.pyplot as plt\n'), ((4879, 4917), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.ema26'], {'label': '"""ema26"""'}), "(self.df.ema26, label='ema26')\n", (4887, 4917), True, 'import matplotlib.pyplot as plt\n'), ((4926, 4938), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4936, 4938), True, 'import matplotlib.pyplot as plt\n'), ((4947, 4966), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (4957, 4966), True, 'import matplotlib.pyplot as plt\n'), ((4975, 4998), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (4985, 4998), True, 'import matplotlib.pyplot as plt\n'), ((5007, 5025), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5023, 5025), True, 'import matplotlib.pyplot as plt\n'), ((5583, 5599), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (5594, 5599), True, 'import matplotlib.pyplot as plt\n'), ((5608, 5631), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.close'], {}), '(self.df.close)\n', (5616, 5631), True, 'import matplotlib.pyplot as plt\n'), ((5640, 5659), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (5650, 5659), True, 'import matplotlib.pyplot as plt\n'), ((5751, 5774), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (5761, 5774), True, 'import matplotlib.pyplot as plt\n'), ((5783, 5801), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5799, 5801), True, 'import matplotlib.pyplot as plt\n'), ((6733, 6760), 'numpy.arange', 'np.arange', (['df_subset_length'], {}), '(df_subset_length)\n', (6742, 6760), True, 'import numpy as np\n'), ((7026, 7064), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'figsize': '(12, 6)'}), '(nrows=2, figsize=(12, 6))\n', (7038, 7064), True, 'import matplotlib.pyplot as plt\n'), ((7184, 7208), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (7197, 7208), True, 'import matplotlib.pyplot as plt\n'), ((7217, 7240), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (7227, 7240), True, 'import matplotlib.pyplot as plt\n'), ((8684, 8728), 'matplotlib.pyplot.plot', 'plt.plot', (["self.df['close']"], {'label': '"""original"""'}), "(self.df['close'], label='original')\n", (8692, 8728), True, 'import matplotlib.pyplot as plt\n'), ((8737, 8788), 'matplotlib.pyplot.plot', 'plt.plot', (['fittedValues'], {'color': '"""red"""', 'label': '"""fitted"""'}), "(fittedValues, color='red', label='fitted')\n", (8745, 8788), True, 'import matplotlib.pyplot as plt\n'), ((8870, 8882), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (8880, 8882), True, 'import matplotlib.pyplot as plt\n'), ((8891, 8910), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (8901, 8910), True, 'import matplotlib.pyplot as plt\n'), ((8919, 8942), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (8929, 8942), True, 'import matplotlib.pyplot as plt\n'), ((8951, 8969), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8967, 8969), True, 'import matplotlib.pyplot as plt\n'), ((9685, 9715), 'pandas.DataFrame', 'pd.DataFrame', (["self.df['close']"], {}), "(self.df['close'])\n", (9697, 9715), True, 'import pandas as pd\n'), ((9923, 9957), 'matplotlib.pyplot.plot', 'plt.plot', (['pred'], {'label': '"""prediction"""'}), "(pred, label='prediction')\n", (9931, 9957), True, 'import matplotlib.pyplot as plt\n'), ((9966, 9985), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (9976, 9985), True, 'import matplotlib.pyplot as plt\n'), ((9994, 10012), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Days"""'], {}), "('Days')\n", (10004, 10012), True, 'import matplotlib.pyplot as plt\n'), ((10021, 10044), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (10031, 10044), True, 'import matplotlib.pyplot as plt\n'), ((10053, 10071), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10069, 10071), True, 'import matplotlib.pyplot as plt\n'), ((10626, 10642), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (10637, 10642), True, 'import matplotlib.pyplot as plt\n'), ((10651, 10689), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.close'], {'label': '"""price"""'}), "(self.df.close, label='price')\n", (10659, 10689), True, 'import matplotlib.pyplot as plt\n'), ((10698, 10736), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.sma20'], {'label': '"""sma20"""'}), "(self.df.sma20, label='sma20')\n", (10706, 10736), True, 'import matplotlib.pyplot as plt\n'), ((10745, 10783), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.sma50'], {'label': '"""sma50"""'}), "(self.df.sma50, label='sma50')\n", (10753, 10783), True, 'import matplotlib.pyplot as plt\n'), ((10792, 10832), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.sma200'], {'label': '"""sma200"""'}), "(self.df.sma200, label='sma200')\n", (10800, 10832), True, 'import matplotlib.pyplot as plt\n'), ((10841, 10853), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (10851, 10853), True, 'import matplotlib.pyplot as plt\n'), ((10862, 10881), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (10872, 10881), True, 'import matplotlib.pyplot as plt\n'), ((10890, 10913), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (10900, 10913), True, 'import matplotlib.pyplot as plt\n'), ((10922, 10950), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {'sharex': 'ax1'}), '(212, sharex=ax1)\n', (10933, 10950), True, 'import matplotlib.pyplot as plt\n'), ((10959, 10995), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.macd'], {'label': '"""macd"""'}), "(self.df.macd, label='macd')\n", (10967, 10995), True, 'import matplotlib.pyplot as plt\n'), ((11004, 11044), 'matplotlib.pyplot.plot', 'plt.plot', (['self.df.signal'], {'label': '"""signal"""'}), "(self.df.signal, label='signal')\n", (11012, 11044), True, 'import matplotlib.pyplot as plt\n'), ((11053, 11065), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (11063, 11065), True, 'import matplotlib.pyplot as plt\n'), ((11074, 11093), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (11084, 11093), True, 'import matplotlib.pyplot as plt\n'), ((11102, 11120), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Days"""'], {}), "('Days')\n", (11112, 11120), True, 'import matplotlib.pyplot as plt\n'), ((11129, 11152), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (11139, 11152), True, 'import matplotlib.pyplot as plt\n'), ((11161, 11179), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (11177, 11179), True, 'import matplotlib.pyplot as plt\n'), ((11748, 11786), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(1)', 'figsize': '(12, 6)'}), '(ncols=1, figsize=(12, 6))\n', (11760, 11786), True, 'import matplotlib.pyplot as plt\n'), ((11862, 11878), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (11873, 11878), True, 'import matplotlib.pyplot as plt\n'), ((11986, 12010), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (11999, 12010), True, 'import matplotlib.pyplot as plt\n'), ((12019, 12081), 'matplotlib.pyplot.plot', 'plt.plot', (["df_subset['close']"], {'label': '"""price"""', 'color': '"""royalblue"""'}), "(df_subset['close'], label='price', color='royalblue')\n", (12027, 12081), True, 'import matplotlib.pyplot as plt\n'), ((12090, 12149), 'matplotlib.pyplot.plot', 'plt.plot', (["df_subset['ema12']"], {'label': '"""ema12"""', 'color': '"""orange"""'}), "(df_subset['ema12'], label='ema12', color='orange')\n", (12098, 12149), True, 'import matplotlib.pyplot as plt\n'), ((12158, 12217), 'matplotlib.pyplot.plot', 'plt.plot', (["df_subset['ema26']"], {'label': '"""ema26"""', 'color': '"""purple"""'}), "(df_subset['ema26'], label='ema26', color='purple')\n", (12166, 12217), True, 'import matplotlib.pyplot as plt\n'), ((12227, 12314), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'axis': '"""x"""', 'which': '"""both"""', 'bottom': '(False)', 'top': '(False)', 'labelbottom': '(False)'}), "(axis='x', which='both', bottom=False, top=False,\n labelbottom=False)\n", (12242, 12314), True, 'import matplotlib.pyplot as plt\n'), ((15911, 15930), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (15921, 15930), True, 'import matplotlib.pyplot as plt\n'), ((15939, 15962), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (15949, 15962), True, 'import matplotlib.pyplot as plt\n'), ((15971, 15989), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (15987, 15989), True, 'import matplotlib.pyplot as plt\n'), ((15998, 16010), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (16008, 16010), True, 'import matplotlib.pyplot as plt\n'), ((16092, 16102), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16100, 16102), True, 'import matplotlib.pyplot as plt\n'), ((1955, 1988), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': 'idx', 'color': '"""green"""'}), "(x=idx, color='green')\n", (1966, 1988), True, 'import matplotlib.pyplot as plt\n'), ((2049, 2080), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': 'idx', 'color': '"""red"""'}), "(x=idx, color='red')\n", (2060, 2080), True, 'import matplotlib.pyplot as plt\n'), ((2372, 2382), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2380, 2382), True, 'import matplotlib.pyplot as plt\n'), ((4425, 4435), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4433, 4435), True, 'import matplotlib.pyplot as plt\n'), ((5236, 5246), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5244, 5246), True, 'import matplotlib.pyplot as plt\n'), ((5707, 5741), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': 'level', 'color': '"""grey"""'}), "(y=level, color='grey')\n", (5718, 5741), True, 'import matplotlib.pyplot as plt\n'), ((6012, 6022), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6020, 6022), True, 'import matplotlib.pyplot as plt\n'), ((7588, 7621), 'matplotlib.ticker.FuncFormatter', 'ticker.FuncFormatter', (['format_date'], {}), '(format_date)\n', (7608, 7621), True, 'import matplotlib.ticker as ticker\n'), ((7907, 7940), 'matplotlib.ticker.FuncFormatter', 'ticker.FuncFormatter', (['format_date'], {}), '(format_date)\n', (7927, 7940), True, 'import matplotlib.ticker as ticker\n'), ((8268, 8278), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8276, 8278), True, 'import matplotlib.pyplot as plt\n'), ((9180, 9190), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9188, 9190), True, 'import matplotlib.pyplot as plt\n'), ((9791, 9820), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'days'}), '(days=days)\n', (9809, 9820), False, 'import datetime, re, sys\n'), ((10282, 10292), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10290, 10292), True, 'import matplotlib.pyplot as plt\n'), ((11390, 11400), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11398, 11400), True, 'import matplotlib.pyplot as plt\n'), ((12827, 12889), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""gx"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'gx')\n", (12835, 12889), True, 'import matplotlib.pyplot as plt\n'), ((13131, 13193), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""rx"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'rx')\n", (13139, 13193), True, 'import matplotlib.pyplot as plt\n'), ((13435, 13497), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""g^"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'g^')\n", (13443, 13497), True, 'import matplotlib.pyplot as plt\n'), ((13729, 13791), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""rv"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'rv')\n", (13737, 13791), True, 'import matplotlib.pyplot as plt\n'), ((14027, 14089), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""go"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'go')\n", (14035, 14089), True, 'import matplotlib.pyplot as plt\n'), ((14328, 14390), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""r*"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'r*')\n", (14336, 14390), True, 'import matplotlib.pyplot as plt\n'), ((14621, 14683), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""yd"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'yd')\n", (14629, 14683), True, 'import matplotlib.pyplot as plt\n'), ((14927, 14989), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""y^"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'y^')\n", (14935, 14989), True, 'import matplotlib.pyplot as plt\n'), ((15233, 15295), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""yv"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'yv')\n", (15241, 15295), True, 'import matplotlib.pyplot as plt\n'), ((15534, 15596), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""mv"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'mv')\n", (15542, 15596), True, 'import matplotlib.pyplot as plt\n'), ((15837, 15899), 'matplotlib.pyplot.plot', 'plt.plot', (['idx', "df_candlestick_in_range.loc[idx]['close']", '"""m^"""'], {}), "(idx, df_candlestick_in_range.loc[idx]['close'], 'm^')\n", (15845, 15899), True, 'import matplotlib.pyplot as plt\n'), ((16052, 16074), 'matplotlib.pyplot.savefig', 'plt.savefig', (['outputpng'], {}), '(outputpng)\n', (16063, 16074), True, 'import matplotlib.pyplot as plt\n'), ((2223, 2244), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (2234, 2244), True, 'import matplotlib.pyplot as plt\n'), ((3669, 3702), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': 'idx', 'color': '"""green"""'}), "(x=idx, color='green')\n", (3680, 3702), True, 'import matplotlib.pyplot as plt\n'), ((4276, 4297), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (4287, 4297), True, 'import matplotlib.pyplot as plt\n'), ((5087, 5108), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (5098, 5108), True, 'import matplotlib.pyplot as plt\n'), ((5863, 5884), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (5874, 5884), True, 'import matplotlib.pyplot as plt\n'), ((6624, 6655), 'pandas.to_datetime', 'pd.to_datetime', (['df_subset.index'], {}), '(df_subset.index)\n', (6638, 6655), True, 'import pandas as pd\n'), ((8119, 8140), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (8130, 8140), True, 'import matplotlib.pyplot as plt\n'), ((9031, 9052), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (9042, 9052), True, 'import matplotlib.pyplot as plt\n'), ((10133, 10154), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (10144, 10154), True, 'import matplotlib.pyplot as plt\n'), ((11241, 11262), 'matplotlib.pyplot.savefig', 'plt.savefig', (['saveFile'], {}), '(saveFile)\n', (11252, 11262), True, 'import matplotlib.pyplot as plt\n'), ((12731, 12754), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (12737, 12754), True, 'import numpy as np\n'), ((13035, 13058), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (13041, 13058), True, 'import numpy as np\n'), ((13339, 13362), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (13345, 13362), True, 'import numpy as np\n'), ((13633, 13656), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (13639, 13656), True, 'import numpy as np\n'), ((13931, 13954), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (13937, 13954), True, 'import numpy as np\n'), ((14232, 14255), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (14238, 14255), True, 'import numpy as np\n'), ((14525, 14548), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (14531, 14548), True, 'import numpy as np\n'), ((14831, 14854), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (14837, 14854), True, 'import numpy as np\n'), ((15137, 15160), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (15143, 15160), True, 'import numpy as np\n'), ((15438, 15461), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (15444, 15461), True, 'import numpy as np\n'), ((15741, 15764), 'numpy.min', 'np.min', (['df_subset.index'], {}), '(df_subset.index)\n', (15747, 15764), True, 'import numpy as np\n'), ((3849, 3880), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': 'idx', 'color': '"""red"""'}), "(x=idx, color='red')\n", (3860, 3880), True, 'import matplotlib.pyplot as plt\n')]
|
import h5py
import numpy as np
import math
import matplotlib.pyplot as plt
# multiple h5 files?
f = h5py.File('shockwave.h5', 'r')
dset2 = f['2'] # fourier
k_density_re = dset2['k_density_re'][...]
k_density_im = dset2['k_density_im'][...]
kx = dset2['kx'][...]
tk = dset2['t'][...]
k_density = k_density_re + 1j * k_density_im
dset4 = f['4'] # constants
R = dset4['radius'][...]
Omega = dset4['omega'][...]
delta = dset4['d_omega'][...]
L = dset4['length'][...]
N = dset4['no_atoms'][...]
phi = dset4['phi'][...]
g = dset4['non_lin'][...]
A_psi = dset4['amplitude_psi'][...]
w_psi = dset4['width_psi'][...]
A = dset4['amplitude'][...]
w = dset4['width'][...]
T_imag = dset4['t_imag'][...]
T_evo = dset4['t_evo'][...]
def find_zero_gradient(f_mag, t, k_index):
f_2k = np.abs(f_mag[..., k_index])
max_indices = []
f_grad = np.gradient(f_2k)
for i in range(1, f_grad.shape[0] - 1):
if (abs(f_grad[i - 1]) > abs(f_grad[i]) < abs(f_grad[i + 1])) and (f_grad[i - 1] > 0 > f_grad[i + 1]):
max_indices.append(i)
return max_indices
# samples
imag_samples = 0
evo_samples = 1000
t_imag_start = 0
t_imag_end = t_imag_start + imag_samples
t_evo_start = 0
t_evo_end = t_evo_start + evo_samples - 1
k_dom = 4
k_half = int(kx.shape[0]/2)
k_index = k_half + k_dom
max_indices = find_zero_gradient(k_density, tk, k_index)
t_max = []
f_max = []
f_plats = []
for index in max_indices:
t_max.append(tk[index])
f_max.append(np.abs(k_density[index, k_index]))
f_plats.append(np.angle(k_density[index, k_index]))
start_index = 0
t_plat = []
plat_vals = []
for i in range(start_index, len(t_max)):
t_plat.append(t_max[i])
if f_plats[i] < 0:
plat_vals.append(f_plats[i] + math.pi)
else:
plat_vals.append(f_plats[i])
# plot fourier mag peaks matching plateaus
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
fig.suptitle('Fourier transform (2k={}, '.format(str(round(kx[k_index], 4))) + r'$\Omega$' + '={})'.format(Omega))
ax1.plot(tk - T_imag, np.abs(k_density[..., k_index]))
ax1.plot(t_max - T_imag, f_max, 'r.')
ax1.set_ylabel(r'$|F_{2k}|$')
ax2.plot(tk - T_imag, np.angle(k_density[..., k_index]), label='phase')
ax2.plot(tk - T_imag, np.angle(k_density[..., k_index]) + math.pi, label='phase + ' + r'$\pi$')
ax2.plot(t_plat - T_imag, plat_vals, 'r.')
ax2.set_ylabel(r'$arg(F_{2k})$')
ax2.set_ylim([-math.pi, math.pi])
ax2.legend(loc='lower right')
ax2.set_yticks([-math.pi, -math.pi/2, 0, math.pi/2, math.pi])
ax2.set_yticklabels([r'$-\pi$', r'$-\frac{\pi}{2}$', '0', r'$\frac{\pi}{2}$', r'$\pi$'])
plt.xlabel('t')
fig.savefig('fourier_combined.png')
def phase_adjust(k):
phase = np.angle(k_density[..., k_half + k])
grad = np.gradient(phase)
t_phase = []
if not k % 2 == 0: # shift odd wavenumbers
phase = phase - math.pi/2
adjusted = []
for i in range(len(phase)):
if abs(grad[i]) < 0.005: # gradient threshold
if phase[i] < 0:
phase[i] += math.pi
if 0.1 < phase[i] < 2:
adjusted.append(phase[i])
t_phase.append(tk[i] - T_imag)
return t_phase, adjusted
# plot plateaus for different k
fig, ax = plt.subplots()
ax.plot(phase_adjust(2)[0], phase_adjust(2)[1], label='2k=2')
ax.plot(phase_adjust(3)[0], phase_adjust(3)[1], label='2k=3')
ax.plot(phase_adjust(4)[0], phase_adjust(4)[1], label='2k=4')
ax.plot(phase_adjust(5)[0], phase_adjust(5)[1], label='2k=5')
ax.plot(phase_adjust(6)[0], phase_adjust(6)[1], label='2k=6')
ax.set_xlabel('t')
ax.set_ylabel(r'$arg(F_{2k})$')
ax.set_ylim([0, math.pi])
ax.set_title('Fourier density phase (' + r'$\Omega$' + '={})'.format(Omega))
ax.legend()
plt.yticks([0, math.pi/4, math.pi/2, 3*math.pi/4, math.pi], ['0', r'$\frac{\pi}{4}$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'])
fig.savefig('fourier_phase.png')
fig, ax = plt.subplots()
ax.plot(tk - T_imag, np.abs(k_density[..., k_index]))
ax.plot(t_max - T_imag, f_max, 'r.')
ax.set_ylim([0, 1])
fig.savefig('fourier_peaks.png')
|
[
"h5py.File",
"numpy.abs",
"numpy.angle",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
"numpy.gradient"
] |
[((101, 131), 'h5py.File', 'h5py.File', (['"""shockwave.h5"""', '"""r"""'], {}), "('shockwave.h5', 'r')\n", (110, 131), False, 'import h5py\n'), ((1842, 1870), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {'sharex': '(True)'}), '(2, sharex=True)\n', (1854, 1870), True, 'import matplotlib.pyplot as plt\n'), ((2568, 2583), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""t"""'], {}), "('t')\n", (2578, 2583), True, 'import matplotlib.pyplot as plt\n'), ((3184, 3198), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3196, 3198), True, 'import matplotlib.pyplot as plt\n'), ((3675, 3827), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0, math.pi / 4, math.pi / 2, 3 * math.pi / 4, math.pi]', "['0', '$\\\\frac{\\\\pi}{4}$', '$\\\\frac{\\\\pi}{2}$', '$\\\\frac{3\\\\pi}{4}$', '$\\\\pi$']"], {}), "([0, math.pi / 4, math.pi / 2, 3 * math.pi / 4, math.pi], ['0',\n '$\\\\frac{\\\\pi}{4}$', '$\\\\frac{\\\\pi}{2}$', '$\\\\frac{3\\\\pi}{4}$', '$\\\\pi$'])\n", (3685, 3827), True, 'import matplotlib.pyplot as plt\n'), ((3857, 3871), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3869, 3871), True, 'import matplotlib.pyplot as plt\n'), ((776, 803), 'numpy.abs', 'np.abs', (['f_mag[..., k_index]'], {}), '(f_mag[..., k_index])\n', (782, 803), True, 'import numpy as np\n'), ((838, 855), 'numpy.gradient', 'np.gradient', (['f_2k'], {}), '(f_2k)\n', (849, 855), True, 'import numpy as np\n'), ((2008, 2039), 'numpy.abs', 'np.abs', (['k_density[..., k_index]'], {}), '(k_density[..., k_index])\n', (2014, 2039), True, 'import numpy as np\n'), ((2131, 2164), 'numpy.angle', 'np.angle', (['k_density[..., k_index]'], {}), '(k_density[..., k_index])\n', (2139, 2164), True, 'import numpy as np\n'), ((2654, 2690), 'numpy.angle', 'np.angle', (['k_density[..., k_half + k]'], {}), '(k_density[..., k_half + k])\n', (2662, 2690), True, 'import numpy as np\n'), ((2702, 2720), 'numpy.gradient', 'np.gradient', (['phase'], {}), '(phase)\n', (2713, 2720), True, 'import numpy as np\n'), ((3893, 3924), 'numpy.abs', 'np.abs', (['k_density[..., k_index]'], {}), '(k_density[..., k_index])\n', (3899, 3924), True, 'import numpy as np\n'), ((1459, 1492), 'numpy.abs', 'np.abs', (['k_density[index, k_index]'], {}), '(k_density[index, k_index])\n', (1465, 1492), True, 'import numpy as np\n'), ((1513, 1548), 'numpy.angle', 'np.angle', (['k_density[index, k_index]'], {}), '(k_density[index, k_index])\n', (1521, 1548), True, 'import numpy as np\n'), ((2203, 2236), 'numpy.angle', 'np.angle', (['k_density[..., k_index]'], {}), '(k_density[..., k_index])\n', (2211, 2236), True, 'import numpy as np\n')]
|
import os
import time
import numpy as np
import pandas as pd
import normalizedDistance
from pprint import pprint
from recourse.builder import RecourseBuilder
from recourse.builder import ActionSet
def genExp(model_trained, factual_sample, norm_type, dataset_obj):
start_time = time.time()
# SIMPLE HACK!!
# ActionSet() construction demands that all variables have a range to them. In
# the case of one-hot ordinal variables (e.g., x2_ord_0, x2_ord_1, x2_ord_2)),
# the first sub-category (i.e., x2_ord_0) will always have range(1,1), failing
# the requirements of ActionSet(). Therefore, we add a DUMMY ROW to the data-
# frame, which is a copy of another row (so not to throw off the range of other
# attributes), but setting a 0 value to all _ord_ variables. (might as well do
# this for all _cat_ variables as well).
tmp_df = dataset_obj.data_frame_kurz
sample_row = tmp_df.loc[0].to_dict()
for attr_name_kurz in dataset_obj.getOneHotAttributesNames('kurz'):
sample_row[attr_name_kurz] = 0
tmp_df = tmp_df.append(pd.Series(sample_row), ignore_index=True)
df = tmp_df
X = df.loc[:, df.columns != 'y']
# Enforce binary, categorical (including ordinal) variables only take on 2 values
custom_bounds = {attr_name_kurz: (0, 100, 'p') for attr_name_kurz in np.union1d(
dataset_obj.getOneHotAttributesNames('kurz'),
dataset_obj.getBinaryAttributeNames('kurz')
)}
action_set = ActionSet(X = X, custom_bounds = custom_bounds)
# action_set['x1'].mutable = False # x1 = 'Race'
# In the current implementation, we only supports any/none actionability
for attr_name_kurz in dataset_obj.getInputAttributeNames('kurz'):
attr_obj = dataset_obj.attributes_kurz[attr_name_kurz]
if attr_obj.actionability == 'none':
action_set[attr_name_kurz].mutable = False
elif attr_obj.actionability == 'any':
continue # do nothing
else:
raise ValueError(f'Actionable Recourse does not support actionability type {attr_obj.actionability}')
# Enforce search over integer-based grid for integer-based variables
for attr_name_kurz in np.union1d(
dataset_obj.getIntegerBasedAttributeNames('kurz'),
dataset_obj.getBinaryAttributeNames('kurz'),
):
action_set[attr_name_kurz].step_type = "absolute"
action_set[attr_name_kurz].step_size = 1
coefficients = model_trained.coef_[0]
intercept = model_trained.intercept_[0]
if norm_type == 'one_norm':
mip_cost_type = 'total'
elif norm_type == 'infty_norm':
mip_cost_type = 'max'
else:
raise ValueError(f'Actionable Recourse does not support norm_type {norm_type}')
factual_sample_values = list(factual_sample.values())
# p = .8
rb = RecourseBuilder(
optimizer="cplex",
coefficients=coefficients,
intercept=intercept, # - (np.log(p / (1. - p))),
action_set=action_set,
x=factual_sample_values,
mip_cost_type=mip_cost_type
)
output = rb.fit()
counterfactual_sample_values = np.add(factual_sample_values, output['actions'])
counterfactual_sample = dict(zip(factual_sample.keys(), counterfactual_sample_values))
# factual_sample['y'] = False
# counterfactual_sample['y'] = True
counterfactual_sample['y'] = not factual_sample['y']
counterfactual_plausible = True
# IMPORTANT: no need to check for integer-based / binary-based plausibility,
# because those were set above when we said step_type = absolute! Just round!
for attr_name_kurz in np.union1d(
dataset_obj.getOneHotAttributesNames('kurz'),
dataset_obj.getBinaryAttributeNames('kurz')
):
try:
assert np.isclose(
counterfactual_sample[attr_name_kurz],
np.round(counterfactual_sample[attr_name_kurz])
)
counterfactual_sample[attr_name_kurz] = np.round(counterfactual_sample[attr_name_kurz])
except:
distance = -1
counterfactual_plausible = False
# return counterfactual_sample, distance
# Perform plausibility-data-type check! Remember, all ordinal variables
# have already been converted to categorical variables. It is important now
# to check that 1 (and only 1) sub-category is activated in the resulting
# counterfactual sample.
already_considered = []
for attr_name_kurz in dataset_obj.getOneHotAttributesNames('kurz'):
if attr_name_kurz not in already_considered:
siblings_kurz = dataset_obj.getSiblingsFor(attr_name_kurz)
activations_for_category = [
counterfactual_sample[attr_name_kurz] for attr_name_kurz in siblings_kurz
]
sum_activations_for_category = np.sum(activations_for_category)
if 'cat' in dataset_obj.attributes_kurz[attr_name_kurz].attr_type:
if sum_activations_for_category == 1:
continue
else:
# print('not plausible, fixing..', end='')
# TODO: don't actually return early! Instead see the actual distance,
# fingers crossed that we can say that not only is their method giving
# counterfactuals are larger distances, but in a lot of cases they are
# not data-type plausible
# INSTEAD, do below:
# Convert to correct categorical/ordinal activations so we can
# compute the distance using already written function.
# Turns out we need to do nothing, because the distance between
# [0,1,0] and anything other than itself, (e.g., [1,1,0] or [1,0,1])
# is always 1 :)
# continue
distance = -1
counterfactual_plausible = False
# return counterfactual_sample, distance
elif 'ord' in dataset_obj.attributes_kurz[attr_name_kurz].attr_type:
# TODO: assert activations are in order...
# if not, repeat as above...
for idx in range(int(sum_activations_for_category)):
if activations_for_category[idx] != 1:
# Convert to correct categorical/ordinal activations so we can
# compute the distance using already written function.
# Find the max index of 1 in the array, and set everything before that to 1
# print('not plausible, fixing..', end='')
# max_index_of_1 = np.where(np.array(activations_for_category) == 1)[0][-1]
# for idx2 in range(max_index_of_1 + 1):
# counterfactual_sample[siblings_kurz[idx2]] = 1
# break
distance = -1
counterfactual_plausible = False
# return counterfactual_sample, distance
else:
raise Exception(f'{attr_name_kurz} must include either `cat` or `ord`.')
already_considered.extend(siblings_kurz)
# TODO: convert to correct categorical/ordinal activations so we can compute
# distance = output['cost'] # TODO: this must change / be verified!???
distance = normalizedDistance.getDistanceBetweenSamples(
factual_sample,
counterfactual_sample,
norm_type,
dataset_obj
)
# # TODO: post-feasibible needed???? NO
# # make plausible by rounding all non-numeric-real attributes to
# # nearest value in range
# for idx, elem in enumerate(es_instance):
# attr_name_kurz = dataset_obj.getInputAttributeNames('kurz')[idx]
# attr_obj = dataset_obj.attributes_kurz[attr_name_kurz]
# if attr_obj.attr_type != 'numeric-real':
# # round() might give a value that is NOT in plausible.
# # instead find the nearest plausible value
# es_instance[idx] = min(
# list(range(int(attr_obj.lower_bound), int(attr_obj.upper_bound) + 1)),
# key = lambda x : abs(x - es_instance[idx])
# )
end_time = time.time()
return {
'factual_sample': factual_sample,
'cfe_sample': counterfactual_sample,
'cfe_found': True, # TODO?
'cfe_plausible': counterfactual_plausible,
'cfe_distance': distance,
'cfe_time': end_time - start_time,
}
|
[
"numpy.sum",
"time.time",
"normalizedDistance.getDistanceBetweenSamples",
"recourse.builder.ActionSet",
"pandas.Series",
"numpy.add",
"recourse.builder.RecourseBuilder",
"numpy.round"
] |
[((282, 293), 'time.time', 'time.time', ([], {}), '()\n', (291, 293), False, 'import time\n'), ((1428, 1471), 'recourse.builder.ActionSet', 'ActionSet', ([], {'X': 'X', 'custom_bounds': 'custom_bounds'}), '(X=X, custom_bounds=custom_bounds)\n', (1437, 1471), False, 'from recourse.builder import ActionSet\n'), ((2692, 2860), 'recourse.builder.RecourseBuilder', 'RecourseBuilder', ([], {'optimizer': '"""cplex"""', 'coefficients': 'coefficients', 'intercept': 'intercept', 'action_set': 'action_set', 'x': 'factual_sample_values', 'mip_cost_type': 'mip_cost_type'}), "(optimizer='cplex', coefficients=coefficients, intercept=\n intercept, action_set=action_set, x=factual_sample_values,\n mip_cost_type=mip_cost_type)\n", (2707, 2860), False, 'from recourse.builder import RecourseBuilder\n'), ((2986, 3034), 'numpy.add', 'np.add', (['factual_sample_values', "output['actions']"], {}), "(factual_sample_values, output['actions'])\n", (2992, 3034), True, 'import numpy as np\n'), ((6797, 6908), 'normalizedDistance.getDistanceBetweenSamples', 'normalizedDistance.getDistanceBetweenSamples', (['factual_sample', 'counterfactual_sample', 'norm_type', 'dataset_obj'], {}), '(factual_sample,\n counterfactual_sample, norm_type, dataset_obj)\n', (6841, 6908), False, 'import normalizedDistance\n'), ((7628, 7639), 'time.time', 'time.time', ([], {}), '()\n', (7637, 7639), False, 'import time\n'), ((1050, 1071), 'pandas.Series', 'pd.Series', (['sample_row'], {}), '(sample_row)\n', (1059, 1071), True, 'import pandas as pd\n'), ((3774, 3821), 'numpy.round', 'np.round', (['counterfactual_sample[attr_name_kurz]'], {}), '(counterfactual_sample[attr_name_kurz])\n', (3782, 3821), True, 'import numpy as np\n'), ((4568, 4600), 'numpy.sum', 'np.sum', (['activations_for_category'], {}), '(activations_for_category)\n', (4574, 4600), True, 'import numpy as np\n'), ((3672, 3719), 'numpy.round', 'np.round', (['counterfactual_sample[attr_name_kurz]'], {}), '(counterfactual_sample[attr_name_kurz])\n', (3680, 3719), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# coding=utf8
import os
import matplotlib as mpl
import numpy as np
import path
import pytest
from triflow import Model, Simulation, display_fields, display_probe # noqa
if os.environ.get('DISPLAY', '') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
@pytest.fixture
def heat_model():
model = Model(differential_equations="k * dxxT",
dependent_variables="T",
parameters="k", compiler="numpy")
return model
@pytest.fixture
def simul(heat_model):
x, dx = np.linspace(0, 10, 50, retstep=True, endpoint=False)
T = np.cos(x * 2 * np.pi / 10)
initial_fields = heat_model.fields_template(x=x, T=T)
parameters = dict(periodic=True, k=1)
simul = Simulation(heat_model, initial_fields, parameters,
dt=.5, tmax=2, tol=1E-1)
return simul
def test_display_fields(simul):
display_fields(simul)
simul.run()
def test_display_probes(simul):
display_probe(simul, function=lambda simul: simul.timer.total)
simul.run()
def test_display_mul(simul):
display_fields(simul) * display_fields(simul)
display_fields(simul) * display_fields(simul).hv_curve
def test_display_add(simul):
display_fields(simul) + display_fields(simul)
display_fields(simul) + display_fields(simul).hv_curve
@pytest.mark.parametrize("fmt",
["png", "svg", "pdf"])
def test_display_fields_on_disk(simul, fmt):
with path.tempdir() as d:
display = display_fields(simul, on_disk=d, fmt=fmt)
simul.run()
[process.join() for process in display._writers]
assert len(d.glob("*.%s" % fmt)) == 5
@pytest.mark.parametrize("fmt",
["png", "svg", "pdf"])
def test_display_probles_on_disk(simul, fmt):
with path.tempdir() as d:
display = display_probe(simul,
function=lambda simul: simul.timer.total,
on_disk=d, fmt=fmt)
simul.run()
[process.join() for process in display._writers]
assert len(d.glob("*.%s" % fmt)) == 5
def test_display_api(simul):
display = display_fields(simul)
display.hv_curve
|
[
"triflow.Model",
"triflow.display_probe",
"path.tempdir",
"os.environ.get",
"triflow.display_fields",
"matplotlib.use",
"triflow.Simulation",
"numpy.linspace",
"numpy.cos",
"pytest.mark.parametrize"
] |
[((1367, 1420), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fmt"""', "['png', 'svg', 'pdf']"], {}), "('fmt', ['png', 'svg', 'pdf'])\n", (1390, 1420), False, 'import pytest\n'), ((1707, 1760), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fmt"""', "['png', 'svg', 'pdf']"], {}), "('fmt', ['png', 'svg', 'pdf'])\n", (1730, 1760), False, 'import pytest\n'), ((200, 229), 'os.environ.get', 'os.environ.get', (['"""DISPLAY"""', '""""""'], {}), "('DISPLAY', '')\n", (214, 229), False, 'import os\n'), ((306, 320), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (313, 320), True, 'import matplotlib as mpl\n'), ((369, 472), 'triflow.Model', 'Model', ([], {'differential_equations': '"""k * dxxT"""', 'dependent_variables': '"""T"""', 'parameters': '"""k"""', 'compiler': '"""numpy"""'}), "(differential_equations='k * dxxT', dependent_variables='T',\n parameters='k', compiler='numpy')\n", (374, 472), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((575, 627), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(50)'], {'retstep': '(True)', 'endpoint': '(False)'}), '(0, 10, 50, retstep=True, endpoint=False)\n', (586, 627), True, 'import numpy as np\n'), ((636, 662), 'numpy.cos', 'np.cos', (['(x * 2 * np.pi / 10)'], {}), '(x * 2 * np.pi / 10)\n', (642, 662), True, 'import numpy as np\n'), ((775, 850), 'triflow.Simulation', 'Simulation', (['heat_model', 'initial_fields', 'parameters'], {'dt': '(0.5)', 'tmax': '(2)', 'tol': '(0.1)'}), '(heat_model, initial_fields, parameters, dt=0.5, tmax=2, tol=0.1)\n', (785, 850), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((929, 950), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (943, 950), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1005, 1067), 'triflow.display_probe', 'display_probe', (['simul'], {'function': '(lambda simul: simul.timer.total)'}), '(simul, function=lambda simul: simul.timer.total)\n', (1018, 1067), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((2195, 2216), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (2209, 2216), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1119, 1140), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1133, 1140), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1143, 1164), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1157, 1164), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1169, 1190), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1183, 1190), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1259, 1280), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1273, 1280), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1283, 1304), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1297, 1304), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1309, 1330), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1323, 1330), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1500, 1514), 'path.tempdir', 'path.tempdir', ([], {}), '()\n', (1512, 1514), False, 'import path\n'), ((1539, 1580), 'triflow.display_fields', 'display_fields', (['simul'], {'on_disk': 'd', 'fmt': 'fmt'}), '(simul, on_disk=d, fmt=fmt)\n', (1553, 1580), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1841, 1855), 'path.tempdir', 'path.tempdir', ([], {}), '()\n', (1853, 1855), False, 'import path\n'), ((1880, 1966), 'triflow.display_probe', 'display_probe', (['simul'], {'function': '(lambda simul: simul.timer.total)', 'on_disk': 'd', 'fmt': 'fmt'}), '(simul, function=lambda simul: simul.timer.total, on_disk=d,\n fmt=fmt)\n', (1893, 1966), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1193, 1214), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1207, 1214), False, 'from triflow import Model, Simulation, display_fields, display_probe\n'), ((1333, 1354), 'triflow.display_fields', 'display_fields', (['simul'], {}), '(simul)\n', (1347, 1354), False, 'from triflow import Model, Simulation, display_fields, display_probe\n')]
|
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# 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.
#
#
import time
import sys
import numpy as np
import unicodedata
import six
import re
import tensorflow as tf
from absl import app
from argparse import ArgumentParser
import pandas as pd
from utils import tokenizer
from utils.tokenizer import Subtokenizer
from utils import metrics
flags = tf.compat.v1.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer("batch_size", 64,
"run batch size")
flags.DEFINE_string("input_graph", None,
"The path of input model file.")
flags.DEFINE_string("inputs_file", None,
"File saved to an output file.")
flags.DEFINE_string("reference_file", None,
"File containing reference translation.")
flags.DEFINE_string("vocab_file", None,
"Path to subtoken vocabulary file.")
flags.DEFINE_string("config", None,
"Config json file")
flags.DEFINE_string("output_model", None,
"The output model of the quantized model.")
flags.DEFINE_string("mode", "tune",
"One of three options: 'benchmark'/'accuracy'/'tune'.")
flags.DEFINE_integer("iters", -1,
"The iteration used for benchmark.")
class UnicodeRegex(object):
def __init__(self):
punctuation = self.property_chars("P")
self.nondigit_punct_re = re.compile(r"([^\d])([" + punctuation + r"])")
self.punct_nondigit_re = re.compile(r"([" + punctuation + r"])([^\d])")
self.symbol_re = re.compile("([" + self.property_chars("S") + "])")
def property_chars(self, prefix):
return "".join(six.unichr(x) for x in range(sys.maxunicode)
if unicodedata.category(six.unichr(x)).startswith(prefix))
uregex = UnicodeRegex()
def bleu_tokenize(string):
string = uregex.nondigit_punct_re.sub(r"\1 \2 ", string)
string = uregex.punct_nondigit_re.sub(r" \1 \2", string)
string = uregex.symbol_re.sub(r" \1 ", string)
return string.split()
class bleu(object):
def __init__(self):
self.translations = []
self.labels = []
def reset(self):
self.translations = []
self.labels = []
def update(self, pred, label):
if len(label) != len(pred):
raise ValueError("Reference and translation files have different number "
"of lines. If training only a few steps (100-200), the "
"translation may be empty.")
label = [x.lower() for x in label]
pred = [x.lower() for x in pred]
label = [bleu_tokenize(x) for x in label]
pred = [bleu_tokenize(x) for x in pred]
self.labels.extend(label)
self.translations.extend(pred)
def result(self):
return metrics.compute_bleu(self.labels, self.translations) * 100
def collate_fn(batch):
"""Puts each data field into a pd frame with outer dimension batch size"""
elem = batch[0]
if isinstance(elem, tuple):
batch = zip(*batch)
return [collate_fn(samples) for samples in batch]
elif isinstance(elem, np.ndarray):
return [list(elem) for elem in batch]
elif isinstance(elem, str):
return batch
else:
return pd.DataFrame(batch).fillna(0).values.astype(np.int32)
def load_graph(file_name):
tf.compat.v1.logging.info('Loading graph from: ' + file_name)
with tf.io.gfile.GFile(file_name, "rb") as f:
graph_def = tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name='')
return graph
def eval_func(infer_graph, iteration=-1):
if isinstance(infer_graph, tf.compat.v1.GraphDef):
graph = tf.Graph()
with graph.as_default():
tf.import_graph_def(infer_graph, name='')
infer_graph = graph
subtokenizer = Subtokenizer(FLAGS.vocab_file)
input_tensor = infer_graph.get_tensor_by_name('input_tensor:0')
output_tensor = infer_graph.get_tensor_by_name(\
'model/Transformer/strided_slice_19:0')
ds = Dataset(FLAGS.inputs_file, FLAGS.reference_file, FLAGS.vocab_file)
from neural_compressor.data import DATALOADERS
dataloader = DATALOADERS['tensorflow'](ds, batch_size=FLAGS.batch_size,
collate_fn=collate_fn)
config = tf.compat.v1.ConfigProto()
config.use_per_session_threads = 1
config.inter_op_parallelism_threads = 1
sess = tf.compat.v1.Session(graph=infer_graph, config=config)
time_list = []
bleu_eval = bleu()
predictions = []
labels = []
warmup = 10
if iteration != -1:
assert iteration >= warmup, 'iteration must be larger than warmup'
for idx, (input_data, label) in enumerate(dataloader):
if idx < iteration or iteration == -1:
time_start = time.time()
out = sess.run([output_tensor], {input_tensor: input_data})
duration = time.time() - time_start
time_list.append(duration)
predictions.append(out)
labels.extend(label)
else:
break
latency = np.array(time_list[warmup: ]).mean() / FLAGS.batch_size
print('Batch size = {}'.format(FLAGS.batch_size))
print('Latency: {:.3f} ms'.format(latency * 1000))
print('Throughput: {:.3f} items/sec'.format(1./ latency))
# only calculate accuracy when running out all predictions
if iteration == -1:
decode = []
for i,tr in enumerate(predictions):
for j,itr in enumerate(tr):
for k, otr in enumerate(itr):
try:
index = list(otr).index(tokenizer.EOS_ID)
decode.append(subtokenizer.decode(otr[:index]))
except:
decode.append(subtokenizer.decode(otr))
bleu_eval.update(decode, labels)
print('Accuracy is {:.3f}'.format(bleu_eval.result()))
return bleu_eval.result()
class Dataset(object):
def __init__(self, inputs_file, reference_file, vocab_file):
with tf.io.gfile.GFile(inputs_file) as f:
records = f.read().split("\n")
inputs = [record.strip() for record in records]
if not inputs[-1]:
inputs.pop()
self.ref_lines = tokenizer.native_to_unicode(
tf.io.gfile.GFile(reference_file).read()).strip().splitlines()
subtokenizer = Subtokenizer(vocab_file)
self.batch = []
token_lens=[]
for i, line in enumerate(inputs):
enc = subtokenizer.encode(line, add_eos=True)
token_lens.append((i, len(enc)))
sorted_by_token_input_lens = sorted(token_lens, key=lambda x: x[1], reverse=True)
sorted_inputs = [None] * len(sorted_by_token_input_lens)
sorted_keys = [0] * len(sorted_by_token_input_lens)
lines = []
for i, (index, _) in enumerate(sorted_by_token_input_lens):
sorted_inputs[i] = inputs[index]
sorted_keys[index] = i
enc=subtokenizer.encode(sorted_inputs[i], add_eos=True)
lines.append([enc])
for i in sorted_keys:
self.batch.append(lines[i])
def __getitem__(self, index):
data = self.batch[index]
label = self.ref_lines[index]
return data[0], label
def __len__(self):
return len(self.batch)
def main(_):
graph = load_graph(FLAGS.input_graph)
if FLAGS.mode == 'tune':
from neural_compressor.experimental import Quantization, common
quantizer = Quantization(FLAGS.config)
ds = Dataset(FLAGS.inputs_file, FLAGS.reference_file, FLAGS.vocab_file)
quantizer.calib_dataloader = common.DataLoader(ds, collate_fn=collate_fn, \
batch_size=FLAGS.batch_size)
quantizer.model = common.Model(graph)
quantizer.eval_func = eval_func
q_model = quantizer.fit()
try:
q_model.save(FLAGS.output_model)
except Exception as e:
print("Failed to save model due to {}".format(str(e)))
elif FLAGS.mode == 'benchmark':
eval_func(graph, FLAGS.iters)
elif FLAGS.mode == 'accuracy':
eval_func(graph, -1)
if __name__ == "__main__":
tf.compat.v1.app.run()
|
[
"pandas.DataFrame",
"neural_compressor.experimental.Quantization",
"tensorflow.io.gfile.GFile",
"utils.tokenizer.Subtokenizer",
"six.unichr",
"tensorflow.compat.v1.logging.info",
"time.time",
"tensorflow.compat.v1.Session",
"neural_compressor.experimental.common.Model",
"numpy.array",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.Graph",
"utils.metrics.compute_bleu",
"tensorflow.import_graph_def",
"tensorflow.compat.v1.GraphDef",
"neural_compressor.experimental.common.DataLoader",
"tensorflow.compat.v1.app.run",
"re.compile"
] |
[((3905, 3966), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (["('Loading graph from: ' + file_name)"], {}), "('Loading graph from: ' + file_name)\n", (3930, 3966), True, 'import tensorflow as tf\n'), ((4475, 4505), 'utils.tokenizer.Subtokenizer', 'Subtokenizer', (['FLAGS.vocab_file'], {}), '(FLAGS.vocab_file)\n', (4487, 4505), False, 'from utils.tokenizer import Subtokenizer\n'), ((4958, 4984), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (4982, 4984), True, 'import tensorflow as tf\n'), ((5079, 5133), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'graph': 'infer_graph', 'config': 'config'}), '(graph=infer_graph, config=config)\n', (5099, 5133), True, 'import tensorflow as tf\n'), ((8950, 8972), 'tensorflow.compat.v1.app.run', 'tf.compat.v1.app.run', ([], {}), '()\n', (8970, 8972), True, 'import tensorflow as tf\n'), ((1941, 1986), 're.compile', 're.compile', (["('([^\\\\d])([' + punctuation + '])')"], {}), "('([^\\\\d])([' + punctuation + '])')\n", (1951, 1986), False, 'import re\n'), ((2021, 2066), 're.compile', 're.compile', (["('([' + punctuation + '])([^\\\\d])')"], {}), "('([' + punctuation + '])([^\\\\d])')\n", (2031, 2066), False, 'import re\n'), ((3976, 4010), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['file_name', '"""rb"""'], {}), "(file_name, 'rb')\n", (3993, 4010), True, 'import tensorflow as tf\n'), ((4037, 4060), 'tensorflow.compat.v1.GraphDef', 'tf.compat.v1.GraphDef', ([], {}), '()\n', (4058, 4060), True, 'import tensorflow as tf\n'), ((4156, 4195), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['graph_def'], {'name': '""""""'}), "(graph_def, name='')\n", (4175, 4195), True, 'import tensorflow as tf\n'), ((4327, 4337), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (4335, 4337), True, 'import tensorflow as tf\n'), ((7076, 7100), 'utils.tokenizer.Subtokenizer', 'Subtokenizer', (['vocab_file'], {}), '(vocab_file)\n', (7088, 7100), False, 'from utils.tokenizer import Subtokenizer\n'), ((8227, 8253), 'neural_compressor.experimental.Quantization', 'Quantization', (['FLAGS.config'], {}), '(FLAGS.config)\n', (8239, 8253), False, 'from neural_compressor.experimental import Quantization, common\n'), ((8371, 8444), 'neural_compressor.experimental.common.DataLoader', 'common.DataLoader', (['ds'], {'collate_fn': 'collate_fn', 'batch_size': 'FLAGS.batch_size'}), '(ds, collate_fn=collate_fn, batch_size=FLAGS.batch_size)\n', (8388, 8444), False, 'from neural_compressor.experimental import Quantization, common\n'), ((8522, 8541), 'neural_compressor.experimental.common.Model', 'common.Model', (['graph'], {}), '(graph)\n', (8534, 8541), False, 'from neural_compressor.experimental import Quantization, common\n'), ((3356, 3408), 'utils.metrics.compute_bleu', 'metrics.compute_bleu', (['self.labels', 'self.translations'], {}), '(self.labels, self.translations)\n', (3376, 3408), False, 'from utils import metrics\n'), ((4384, 4425), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['infer_graph'], {'name': '""""""'}), "(infer_graph, name='')\n", (4403, 4425), True, 'import tensorflow as tf\n'), ((5459, 5470), 'time.time', 'time.time', ([], {}), '()\n', (5468, 5470), False, 'import time\n'), ((6710, 6740), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['inputs_file'], {}), '(inputs_file)\n', (6727, 6740), True, 'import tensorflow as tf\n'), ((2206, 2219), 'six.unichr', 'six.unichr', (['x'], {}), '(x)\n', (2216, 2219), False, 'import six\n'), ((4114, 4124), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (4122, 4124), True, 'import tensorflow as tf\n'), ((5566, 5577), 'time.time', 'time.time', ([], {}), '()\n', (5575, 5577), False, 'import time\n'), ((5745, 5773), 'numpy.array', 'np.array', (['time_list[warmup:]'], {}), '(time_list[warmup:])\n', (5753, 5773), True, 'import numpy as np\n'), ((2295, 2308), 'six.unichr', 'six.unichr', (['x'], {}), '(x)\n', (2305, 2308), False, 'import six\n'), ((3819, 3838), 'pandas.DataFrame', 'pd.DataFrame', (['batch'], {}), '(batch)\n', (3831, 3838), True, 'import pandas as pd\n'), ((6981, 7014), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['reference_file'], {}), '(reference_file)\n', (6998, 7014), True, 'import tensorflow as tf\n')]
|
import argparse
import torch
import os
import numpy as np
import datasets.crowd as crowd
from models import vgg19
def run():
torch.multiprocessing.freeze_support()
parser = argparse.ArgumentParser(description='Test ')
parser.add_argument('--device', default='0', help='assign device')
parser.add_argument('--crop-size', type=int, default=512,
help='the crop size of the train image')
parser.add_argument('--model-path', type=str, default='',
help='saved model path')
parser.add_argument('--data-path', type=str,
default='data/ShanghaiTech/part_A/',
help='saved model path')
parser.add_argument('--dataset', type=str, default='sha',
help='dataset name: sha, shb')
parser.add_argument('--pred-density-map-path', type=str, default='',
help='save predicted density maps when pred-density-map-path is not empty.')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.device # set vis gpu
device = torch.device('cuda')
model_path = args.model_path
crop_size = args.crop_size
data_path = args.data_path
if args.dataset.lower() == 'sha' or args.dataset.lower() == 'shb':
dataset = crowd.Crowd_sh(os.path.join(data_path, 'test_data'), crop_size, 8, method='val')
else:
raise NotImplementedError
dataloader = torch.utils.data.DataLoader(dataset, 1, shuffle=False,
num_workers=1, pin_memory=True)
if args.pred_density_map_path:
import cv2
if not os.path.exists(args.pred_density_map_path):
os.makedirs(args.pred_density_map_path)
model = vgg19()
model.to(device)
model.load_state_dict(torch.load(model_path, device))
model.eval()
image_errs = []
print(dataloader)
for inputs, count, name in dataloader:
inputs = inputs.to(device)
assert inputs.size(0) == 1, 'the batch size should equal to 1'
with torch.set_grad_enabled(False):
outputs, _ = model(inputs)
img_err = count[0].item() - torch.sum(outputs).item()
image_errs.append(img_err)
if args.pred_density_map_path:
vis_img = outputs[0, 0].cpu().numpy()
# normalize density map values from 0 to 1, then map it to 0-255.
vis_img = (vis_img - vis_img.min()) / (vis_img.max() - vis_img.min() + 1e-5)
vis_img = (vis_img * 255).astype(np.uint8)
vis_img = cv2.applyColorMap(vis_img, cv2.COLORMAP_JET)
cv2.imwrite(os.path.join(args.pred_density_map_path, str(name[0]) + '.png'), vis_img)
image_errs = np.array(image_errs)
mse = np.sqrt(np.mean(np.square(image_errs)))
mae = np.mean(np.abs(image_errs))
print('{}: mae {}, mse {}\n'.format(model_path, mae, mse))
if __name__ == '__main__':
run()
|
[
"numpy.abs",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"os.makedirs",
"torch.sum",
"torch.load",
"torch.set_grad_enabled",
"os.path.exists",
"numpy.square",
"models.vgg19",
"torch.multiprocessing.freeze_support",
"numpy.array",
"cv2.applyColorMap",
"torch.device",
"os.path.join"
] |
[((130, 168), 'torch.multiprocessing.freeze_support', 'torch.multiprocessing.freeze_support', ([], {}), '()\n', (166, 168), False, 'import torch\n'), ((183, 227), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test """'}), "(description='Test ')\n", (206, 227), False, 'import argparse\n'), ((1102, 1122), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1114, 1122), False, 'import torch\n'), ((1451, 1541), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset', '(1)'], {'shuffle': '(False)', 'num_workers': '(1)', 'pin_memory': '(True)'}), '(dataset, 1, shuffle=False, num_workers=1,\n pin_memory=True)\n', (1478, 1541), False, 'import torch\n'), ((1762, 1769), 'models.vgg19', 'vgg19', ([], {}), '()\n', (1767, 1769), False, 'from models import vgg19\n'), ((2733, 2753), 'numpy.array', 'np.array', (['image_errs'], {}), '(image_errs)\n', (2741, 2753), True, 'import numpy as np\n'), ((1817, 1847), 'torch.load', 'torch.load', (['model_path', 'device'], {}), '(model_path, device)\n', (1827, 1847), False, 'import torch\n'), ((2822, 2840), 'numpy.abs', 'np.abs', (['image_errs'], {}), '(image_errs)\n', (2828, 2840), True, 'import numpy as np\n'), ((1324, 1360), 'os.path.join', 'os.path.join', (['data_path', '"""test_data"""'], {}), "(data_path, 'test_data')\n", (1336, 1360), False, 'import os\n'), ((1653, 1695), 'os.path.exists', 'os.path.exists', (['args.pred_density_map_path'], {}), '(args.pred_density_map_path)\n', (1667, 1695), False, 'import os\n'), ((1709, 1748), 'os.makedirs', 'os.makedirs', (['args.pred_density_map_path'], {}), '(args.pred_density_map_path)\n', (1720, 1748), False, 'import os\n'), ((2070, 2099), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (2092, 2099), False, 'import torch\n'), ((2572, 2616), 'cv2.applyColorMap', 'cv2.applyColorMap', (['vis_img', 'cv2.COLORMAP_JET'], {}), '(vis_img, cv2.COLORMAP_JET)\n', (2589, 2616), False, 'import cv2\n'), ((2780, 2801), 'numpy.square', 'np.square', (['image_errs'], {}), '(image_errs)\n', (2789, 2801), True, 'import numpy as np\n'), ((2176, 2194), 'torch.sum', 'torch.sum', (['outputs'], {}), '(outputs)\n', (2185, 2194), False, 'import torch\n')]
|
# coding=utf-8
# Copyright 2020 The uncertainty_metrics Authors.
#
# 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.
# Lint as: python3
"""Tests for calibration metrics."""
import numpy as np
import tensorflow.compat.v2 as tf
import uncertainty_metrics as um
class ExpectedCalibrationErrorTest(tf.test.TestCase):
def testBinaryClassification(self):
num_bins = 10
pred_probs = np.array([0.51, 0.45, 0.39, 0.66, 0.68, 0.29, 0.81, 0.85])
# max_pred_probs: [0.51, 0.55, 0.61, 0.66, 0.68, 0.71, 0.81, 0.85]
# pred_class: [1, 0, 0, 1, 1, 0, 1, 1]
labels = np.array([0., 0., 0., 1., 0., 1., 1., 1.])
n = len(pred_probs)
# Bins for the max predicted probabilities are (0, 0.1), [0.1, 0.2), ...,
# [0.9, 1) and are numbered starting at zero.
bin_counts = np.array([0, 0, 0, 0, 0, 2, 3, 1, 2, 0])
bin_correct_sums = np.array([0, 0, 0, 0, 0, 1, 2, 0, 2, 0])
bin_prob_sums = np.array([0, 0, 0, 0, 0, 0.51 + 0.55, 0.61 + 0.66 + 0.68,
0.71, 0.81 + 0.85, 0])
correct_ece = 0.
bin_accs = np.array([0.] * num_bins)
bin_confs = np.array([0.] * num_bins)
for i in range(num_bins):
if bin_counts[i] > 0:
bin_accs[i] = bin_correct_sums[i] / bin_counts[i]
bin_confs[i] = bin_prob_sums[i] / bin_counts[i]
correct_ece += bin_counts[i] / n * abs(bin_accs[i] - bin_confs[i])
metric = um.ExpectedCalibrationError(
num_bins, name='ECE', dtype=tf.float64)
self.assertEqual(len(metric.variables), 3)
ece1 = metric(labels, pred_probs)
self.assertAllClose(ece1, correct_ece)
actual_bin_counts = tf.convert_to_tensor(metric.counts)
actual_bin_correct_sums = tf.convert_to_tensor(metric.correct_sums)
actual_bin_prob_sums = tf.convert_to_tensor(metric.prob_sums)
self.assertAllEqual(bin_counts, actual_bin_counts)
self.assertAllEqual(bin_correct_sums, actual_bin_correct_sums)
self.assertAllClose(bin_prob_sums, actual_bin_prob_sums)
# Test various types of input shapes.
metric.reset_states()
metric.update_state(labels[:2], pred_probs[:2])
metric.update_state(labels[2:6].reshape(2, 2),
pred_probs[2:6].reshape(2, 2))
metric.update_state(labels[6:7], pred_probs[6:7])
ece2 = metric(labels[7:, np.newaxis], pred_probs[7:, np.newaxis])
ece3 = metric.result()
self.assertAllClose(ece2, ece3)
self.assertAllClose(ece3, correct_ece)
actual_bin_counts = tf.convert_to_tensor(metric.counts)
actual_bin_correct_sums = tf.convert_to_tensor(metric.correct_sums)
actual_bin_prob_sums = tf.convert_to_tensor(metric.prob_sums)
self.assertAllEqual(bin_counts, actual_bin_counts)
self.assertAllEqual(bin_correct_sums, actual_bin_correct_sums)
self.assertAllClose(bin_prob_sums, actual_bin_prob_sums)
def testBinaryClassificationKerasModel(self):
num_bins = 10
pred_probs = np.array([0.51, 0.45, 0.39, 0.66, 0.68, 0.29, 0.81, 0.85])
# max_pred_probs: [0.51, 0.55, 0.61, 0.66, 0.68, 0.71, 0.81, 0.85]
# pred_class: [1, 0, 0, 1, 1, 0, 1, 1]
labels = np.array([0., 0., 0., 1., 0., 1., 1., 1.])
n = len(pred_probs)
# Bins for the max predicted probabilities are (0, 0.1), [0.1, 0.2), ...,
# [0.9, 1) and are numbered starting at zero.
bin_counts = [0, 0, 0, 0, 0, 2, 3, 1, 2, 0]
bin_correct_sums = [0, 0, 0, 0, 0, 1, 2, 0, 2, 0]
bin_prob_sums = [0, 0, 0, 0, 0, 0.51 + 0.55, 0.61 + 0.66 + 0.68, 0.71,
0.81 + 0.85, 0]
correct_ece = 0.
bin_accs = [0.] * num_bins
bin_confs = [0.] * num_bins
for i in range(num_bins):
if bin_counts[i] > 0:
bin_accs[i] = bin_correct_sums[i] / bin_counts[i]
bin_confs[i] = bin_prob_sums[i] / bin_counts[i]
correct_ece += bin_counts[i] / n * abs(bin_accs[i] - bin_confs[i])
metric = um.ExpectedCalibrationError(num_bins, name='ECE')
self.assertEqual(len(metric.variables), 3)
model = tf.keras.models.Sequential([tf.keras.layers.Lambda(lambda x: 1*x)])
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=[metric])
outputs = model.predict(pred_probs)
self.assertAllClose(pred_probs.reshape([n, 1]), outputs)
_, ece = model.evaluate(pred_probs, labels)
self.assertAllClose(ece, correct_ece)
actual_bin_counts = tf.convert_to_tensor(metric.counts)
actual_bin_correct_sums = tf.convert_to_tensor(metric.correct_sums)
actual_bin_prob_sums = tf.convert_to_tensor(metric.prob_sums)
self.assertAllEqual(bin_counts, actual_bin_counts)
self.assertAllEqual(bin_correct_sums, actual_bin_correct_sums)
self.assertAllClose(bin_prob_sums, actual_bin_prob_sums)
def testMulticlassClassification(self):
num_bins = 10
pred_probs = [
[0.31, 0.32, 0.27],
[0.37, 0.33, 0.30],
[0.30, 0.31, 0.39],
[0.61, 0.38, 0.01],
[0.10, 0.65, 0.25],
[0.91, 0.05, 0.04],
]
# max_pred_probs: [0.32, 0.37, 0.39, 0.61, 0.65, 0.91]
# pred_class: [1, 0, 2, 0, 1, 0]
labels = [1., 0, 0., 1., 0., 0.]
n = len(pred_probs)
# Bins for the max predicted probabilities are (0, 0.1), [0.1, 0.2), ...,
# [0.9, 1) and are numbered starting at zero.
bin_counts = [0, 0, 0, 3, 0, 0, 2, 0, 0, 1]
bin_correct_sums = [0, 0, 0, 2, 0, 0, 0, 0, 0, 1]
bin_prob_sums = [0, 0, 0, 0.32 + 0.37 + 0.39, 0, 0, 0.61 + 0.65, 0, 0, 0.91]
correct_ece = 0.
bin_accs = [0.] * num_bins
bin_confs = [0.] * num_bins
for i in range(num_bins):
if bin_counts[i] > 0:
bin_accs[i] = bin_correct_sums[i] / bin_counts[i]
bin_confs[i] = bin_prob_sums[i] / bin_counts[i]
correct_ece += bin_counts[i] / n * abs(bin_accs[i] - bin_confs[i])
metric = um.ExpectedCalibrationError(
num_bins, name='ECE', dtype=tf.float64)
self.assertEqual(len(metric.variables), 3)
metric.update_state(labels[:4], pred_probs[:4])
ece1 = metric(labels[4:], pred_probs[4:])
ece2 = metric.result()
self.assertAllClose(ece1, ece2)
self.assertAllClose(ece2, correct_ece)
actual_bin_counts = tf.convert_to_tensor(metric.counts)
actual_bin_correct_sums = tf.convert_to_tensor(metric.correct_sums)
actual_bin_prob_sums = tf.convert_to_tensor(metric.prob_sums)
self.assertAllEqual(bin_counts, actual_bin_counts)
self.assertAllEqual(bin_correct_sums, actual_bin_correct_sums)
self.assertAllClose(bin_prob_sums, actual_bin_prob_sums)
if __name__ == '__main__':
tf.enable_v2_behavior()
tf.test.main()
|
[
"tensorflow.compat.v2.keras.layers.Lambda",
"tensorflow.compat.v2.test.main",
"tensorflow.compat.v2.enable_v2_behavior",
"tensorflow.compat.v2.convert_to_tensor",
"numpy.array",
"uncertainty_metrics.ExpectedCalibrationError"
] |
[((6981, 7004), 'tensorflow.compat.v2.enable_v2_behavior', 'tf.enable_v2_behavior', ([], {}), '()\n', (7002, 7004), True, 'import tensorflow.compat.v2 as tf\n'), ((7007, 7021), 'tensorflow.compat.v2.test.main', 'tf.test.main', ([], {}), '()\n', (7019, 7021), True, 'import tensorflow.compat.v2 as tf\n'), ((884, 942), 'numpy.array', 'np.array', (['[0.51, 0.45, 0.39, 0.66, 0.68, 0.29, 0.81, 0.85]'], {}), '([0.51, 0.45, 0.39, 0.66, 0.68, 0.29, 0.81, 0.85])\n', (892, 942), True, 'import numpy as np\n'), ((1070, 1120), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0]'], {}), '([0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0])\n', (1078, 1120), True, 'import numpy as np\n'), ((1283, 1323), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 2, 3, 1, 2, 0]'], {}), '([0, 0, 0, 0, 0, 2, 3, 1, 2, 0])\n', (1291, 1323), True, 'import numpy as np\n'), ((1347, 1387), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 1, 2, 0, 2, 0]'], {}), '([0, 0, 0, 0, 0, 1, 2, 0, 2, 0])\n', (1355, 1387), True, 'import numpy as np\n'), ((1408, 1493), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0.51 + 0.55, 0.61 + 0.66 + 0.68, 0.71, 0.81 + 0.85, 0]'], {}), '([0, 0, 0, 0, 0, 0.51 + 0.55, 0.61 + 0.66 + 0.68, 0.71, 0.81 + 0.85, 0]\n )\n', (1416, 1493), True, 'import numpy as np\n'), ((1556, 1582), 'numpy.array', 'np.array', (['([0.0] * num_bins)'], {}), '([0.0] * num_bins)\n', (1564, 1582), True, 'import numpy as np\n'), ((1598, 1624), 'numpy.array', 'np.array', (['([0.0] * num_bins)'], {}), '([0.0] * num_bins)\n', (1606, 1624), True, 'import numpy as np\n'), ((1885, 1952), 'uncertainty_metrics.ExpectedCalibrationError', 'um.ExpectedCalibrationError', (['num_bins'], {'name': '"""ECE"""', 'dtype': 'tf.float64'}), "(num_bins, name='ECE', dtype=tf.float64)\n", (1912, 1952), True, 'import uncertainty_metrics as um\n'), ((2116, 2151), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.counts'], {}), '(metric.counts)\n', (2136, 2151), True, 'import tensorflow.compat.v2 as tf\n'), ((2182, 2223), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.correct_sums'], {}), '(metric.correct_sums)\n', (2202, 2223), True, 'import tensorflow.compat.v2 as tf\n'), ((2251, 2289), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.prob_sums'], {}), '(metric.prob_sums)\n', (2271, 2289), True, 'import tensorflow.compat.v2 as tf\n'), ((2955, 2990), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.counts'], {}), '(metric.counts)\n', (2975, 2990), True, 'import tensorflow.compat.v2 as tf\n'), ((3021, 3062), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.correct_sums'], {}), '(metric.correct_sums)\n', (3041, 3062), True, 'import tensorflow.compat.v2 as tf\n'), ((3090, 3128), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.prob_sums'], {}), '(metric.prob_sums)\n', (3110, 3128), True, 'import tensorflow.compat.v2 as tf\n'), ((3396, 3454), 'numpy.array', 'np.array', (['[0.51, 0.45, 0.39, 0.66, 0.68, 0.29, 0.81, 0.85]'], {}), '([0.51, 0.45, 0.39, 0.66, 0.68, 0.29, 0.81, 0.85])\n', (3404, 3454), True, 'import numpy as np\n'), ((3582, 3632), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0]'], {}), '([0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0])\n', (3590, 3632), True, 'import numpy as np\n'), ((4338, 4387), 'uncertainty_metrics.ExpectedCalibrationError', 'um.ExpectedCalibrationError', (['num_bins'], {'name': '"""ECE"""'}), "(num_bins, name='ECE')\n", (4365, 4387), True, 'import uncertainty_metrics as um\n'), ((4813, 4848), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.counts'], {}), '(metric.counts)\n', (4833, 4848), True, 'import tensorflow.compat.v2 as tf\n'), ((4879, 4920), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.correct_sums'], {}), '(metric.correct_sums)\n', (4899, 4920), True, 'import tensorflow.compat.v2 as tf\n'), ((4948, 4986), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.prob_sums'], {}), '(metric.prob_sums)\n', (4968, 4986), True, 'import tensorflow.compat.v2 as tf\n'), ((6239, 6306), 'uncertainty_metrics.ExpectedCalibrationError', 'um.ExpectedCalibrationError', (['num_bins'], {'name': '"""ECE"""', 'dtype': 'tf.float64'}), "(num_bins, name='ECE', dtype=tf.float64)\n", (6266, 6306), True, 'import uncertainty_metrics as um\n'), ((6593, 6628), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.counts'], {}), '(metric.counts)\n', (6613, 6628), True, 'import tensorflow.compat.v2 as tf\n'), ((6659, 6700), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.correct_sums'], {}), '(metric.correct_sums)\n', (6679, 6700), True, 'import tensorflow.compat.v2 as tf\n'), ((6728, 6766), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', (['metric.prob_sums'], {}), '(metric.prob_sums)\n', (6748, 6766), True, 'import tensorflow.compat.v2 as tf\n'), ((4476, 4515), 'tensorflow.compat.v2.keras.layers.Lambda', 'tf.keras.layers.Lambda', (['(lambda x: 1 * x)'], {}), '(lambda x: 1 * x)\n', (4498, 4515), True, 'import tensorflow.compat.v2 as tf\n')]
|
# Copyright (c) 2021, TU Wien, Department of Geodesy and Geoinformation
# 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 TU Wien, Department of Geodesy and Geoinformation
# 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 TU WIEN DEPARTMENT OF GEODESY AND
# GEOINFORMATION 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.
"""
Readers for ASCAT Level 1b in HDF5 format.
"""
from collections import OrderedDict
import h5py
import numpy as np
import xarray as xr
from ascat.read_native.eps_native import set_flags
class AscatL1bHdf5File:
"""
Read ASCAT Level 1b file in HDF5 format.
"""
def __init__(self, filename):
"""
Initialize AscatL1bHdf5File.
Parameters
----------
filename : str
Filename.
"""
self.filename = filename
def read(self, generic=False, to_xarray=False):
"""
Read ASCAT Level 1b data.
Parameters
----------
generic : bool, optional
'True' reading and converting into generic format or
'False' reading original field names (default: False).
to_xarray : bool, optional
'True' return data as xarray.Dataset
'False' return data as numpy.ndarray (default: False).
Returns
-------
ds : xarray.Dataset, numpy.ndarray
ASCAT Level 1b data.
"""
data = {}
metadata = {}
root = 'U-MARF/EPS/ASCA_SZF_1B/'
mdr_path = root + 'DATA/MDR_1B_FULL_ASCA_Level_1_ARRAY_000001'
mdr_descr_path = root + 'DATA/MDR_1B_FULL_ASCA_Level_1_DESCR'
metadata_path = root + 'METADATA'
with h5py.File(self.filename, mode='r') as fid:
mdr = fid[mdr_path]
mdr_descr = fid[mdr_descr_path]
mdr_metadata = fid[metadata_path]
var_names = list(mdr.dtype.names)
for var_name in var_names:
data[var_name.lower()] = mdr[var_name]
if var_name.encode() in mdr_descr['EntryName']:
pos = mdr_descr['EntryName'] == var_name.encode()
scale = mdr_descr['Scale Factor'][pos][0].decode()
if scale != 'n/a':
data[var_name.lower()] = (data[
var_name.lower()] / (10. ** float(scale))).astype(
np.float32)
fields = ['SPACECRAFT_ID', 'ORBIT_START',
'PROCESSOR_MAJOR_VERSION', 'PROCESSOR_MINOR_VERSION',
'FORMAT_MAJOR_VERSION', 'FORMAT_MINOR_VERSION']
for f in fields:
pos = np.core.defchararray.startswith(
mdr_metadata['MPHR/MPHR_TABLE']['EntryName'], f.encode())
var = mdr_metadata['MPHR/MPHR_TABLE']['EntryValue'][
pos][0].decode()
if f == 'SPACECRAFT_ID':
var = var[-1]
metadata[f.lower()] = int(var)
# modify longitudes [0, 360] to [-180, 180]
mask = data['longitude_full'] > 180
data['longitude_full'][mask] += -360.
data['time'] = np.datetime64('2000-01-01') + data[
'utc_localisation-days'].astype('timedelta64[D]') + data[
'utc_localisation-milliseconds'].astype('timedelta64[ms]')
# modify azimuth angles to [0, 360]
if 'azi_angle_full' in var_names:
mask = data['azi_angle_full'] < 0
data['azi_angle_full'][mask] += 360
rename_coords = {'longitude_full': ('lon', np.float32),
'latitude_full': ('lat', np.float32)}
for var_name, (new_name, new_dtype) in rename_coords.items():
data[new_name] = data.pop(var_name).astype(new_dtype)
if generic:
data = conv_hdf5l1b_generic(data, metadata)
# 1 Left Fore Antenna, 2 Left Mid Antenna 3 Left Aft Antenna
# 4 Right Fore Antenna, 5 Right Mid Antenna, 6 Right Aft Antenna
antennas = ['lf', 'lm', 'la', 'rf', 'rm', 'ra']
ds = OrderedDict()
for i, antenna in enumerate(antennas):
subset = data['beam_number'] == i+1
metadata['beam_number'] = i+1
metadata['beam_name'] = antenna
# convert dict to xarray.Dataset or numpy.ndarray
if to_xarray:
sub_data = {}
for var_name in data.keys():
if var_name == 'beam_number' and generic:
continue
if len(data[var_name].shape) == 1:
dim = ['obs']
elif len(data[var_name].shape) == 2:
dim = ['obs', 'echo']
sub_data[var_name] = (dim, data[var_name][subset])
coords = {}
coords_fields = ['lon', 'lat', 'time']
for cf in coords_fields:
coords[cf] = sub_data.pop(cf)
ds[antenna] = xr.Dataset(sub_data, coords=coords,
attrs=metadata)
else:
# collect dtype info
dtype = []
for var_name in data.keys():
if len(data[var_name][subset].shape) == 1:
dtype.append(
(var_name, data[var_name][subset].dtype.str))
elif len(data[var_name][subset].shape) > 1:
dtype.append((var_name, data[var_name][
subset].dtype.str, data[var_name][
subset].shape[1:]))
ds[antenna] = np.empty(
data['time'][subset].size, dtype=np.dtype(dtype))
for var_name in data.keys():
if var_name == 'beam_number' and generic:
continue
ds[antenna][var_name] = data[var_name][subset]
return ds
def close(self):
"""
Close file.
"""
pass
def conv_hdf5l1b_generic(data, metadata):
"""
Rename and convert data types of dataset.
Parameters
----------
data : dict of numpy.ndarray
Original dataset.
metadata : dict
Metadata.
Returns
-------
data : dict of numpy.ndarray
Converted dataset.
"""
# convert spacecraft_id to internal sat_id
sat_id = np.array([4, 3, 5])
metadata['sat_id'] = sat_id[metadata['spacecraft_id']-1]
# compute ascending/descending direction
data['as_des_pass'] = (
data['sat_track_azi'] < 270).astype(np.uint8)
flags = {'flagfield_rf1': np.tile(data['flagfield_rf1'], 192),
'flagfield_rf2': np.tile(data['flagfield_rf2'], 192),
'flagfield_pl': np.tile(data['flagfield_pl'], 192),
'flagfield_gen1': data['flagfield_gen1'].flatten(),
'flagfield_gen2': data['flagfield_gen2'].flatten()}
data['f_usable'] = set_flags(flags)
data['f_usable'] = data['f_usable'].reshape(-1, 192)
data['swath_indicator'] = np.int8(data['beam_number'].flatten() > 3)
skip_fields = ['utc_localisation-days', 'utc_localisation-milliseconds',
'degraded_inst_mdr', 'degraded_proc_mdr', 'flagfield_rf1',
'flagfield_rf2', 'flagfield_pl', 'flagfield_gen1',
'flagfield_gen2']
gen_fields_lut = {'inc_angle_full': ('inc', np.float32),
'azi_angle_full': ('azi', np.float32),
'sigma0_full': ('sig', np.float32)}
for var_name in skip_fields:
if var_name in data:
data.pop(var_name)
num_cells = data['lat'].shape[1]
for var_name in data.keys():
if len(data[var_name].shape) == 1:
data[var_name] = np.repeat(data[var_name], num_cells)
if len(data[var_name].shape) == 2:
data[var_name] = data[var_name].flatten()
if var_name in gen_fields_lut.items():
new_name = gen_fields_lut[var_name][0]
new_dtype = gen_fields_lut[var_name][1]
data[new_name] = data.pop(var_name).astype(new_dtype)
return data
|
[
"h5py.File",
"numpy.datetime64",
"numpy.dtype",
"xarray.Dataset",
"numpy.array",
"numpy.tile",
"numpy.repeat",
"collections.OrderedDict",
"ascat.read_native.eps_native.set_flags"
] |
[((7767, 7786), 'numpy.array', 'np.array', (['[4, 3, 5]'], {}), '([4, 3, 5])\n', (7775, 7786), True, 'import numpy as np\n'), ((8330, 8346), 'ascat.read_native.eps_native.set_flags', 'set_flags', (['flags'], {}), '(flags)\n', (8339, 8346), False, 'from ascat.read_native.eps_native import set_flags\n'), ((5399, 5412), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5410, 5412), False, 'from collections import OrderedDict\n'), ((8007, 8042), 'numpy.tile', 'np.tile', (["data['flagfield_rf1']", '(192)'], {}), "(data['flagfield_rf1'], 192)\n", (8014, 8042), True, 'import numpy as np\n'), ((8074, 8109), 'numpy.tile', 'np.tile', (["data['flagfield_rf2']", '(192)'], {}), "(data['flagfield_rf2'], 192)\n", (8081, 8109), True, 'import numpy as np\n'), ((8140, 8174), 'numpy.tile', 'np.tile', (["data['flagfield_pl']", '(192)'], {}), "(data['flagfield_pl'], 192)\n", (8147, 8174), True, 'import numpy as np\n'), ((2991, 3025), 'h5py.File', 'h5py.File', (['self.filename'], {'mode': '"""r"""'}), "(self.filename, mode='r')\n", (3000, 3025), False, 'import h5py\n'), ((9160, 9196), 'numpy.repeat', 'np.repeat', (['data[var_name]', 'num_cells'], {}), '(data[var_name], num_cells)\n', (9169, 9196), True, 'import numpy as np\n'), ((4483, 4510), 'numpy.datetime64', 'np.datetime64', (['"""2000-01-01"""'], {}), "('2000-01-01')\n", (4496, 4510), True, 'import numpy as np\n'), ((6332, 6383), 'xarray.Dataset', 'xr.Dataset', (['sub_data'], {'coords': 'coords', 'attrs': 'metadata'}), '(sub_data, coords=coords, attrs=metadata)\n', (6342, 6383), True, 'import xarray as xr\n'), ((7065, 7080), 'numpy.dtype', 'np.dtype', (['dtype'], {}), '(dtype)\n', (7073, 7080), True, 'import numpy as np\n')]
|
'''
Functions similar to blocks.graph
'''
import logging
import numpy
import theano
from theano import tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams
from blocks.config import config
from blocks.bricks.base import Brick, application
from picklable_itertools.extras import equizip
from blocks.graph import ComputationGraph
from collections import OrderedDict
logger = logging.getLogger(__name__)
class NoiseBrick(Brick):
"""
A brick to hold parameters introducd by adaptive noise.
For each model parameter, adaptive noise adds its standard deviations.
These new parameters will be held by this brick.
Do not use this brick directly! Its main purpose is to hold noise
parameters and to wrap the new cost.
"""
def __init__(self):
super(NoiseBrick, self).__init__(name='adaptive_noise')
self.parameters = []
self.allocated = True
self.initialized = True
@application(inputs=['train_cost', 'model_cost',
'model_prior_mean', 'model_prior_variance'],
outputs=['total_cost'])
def apply(self, application_call, train_cost, model_cost,
model_prior_mean, model_prior_variance):
# We need to add those as auxiliary variables, as they are not
# used to compute the output, and therefore are lost
application_call.add_auxiliary_variable(model_prior_mean.copy(),
name='model_prior_mean')
application_call.add_auxiliary_variable(model_prior_variance.copy(),
name='model_prior_variance')
total_cost = train_cost + model_cost
total_cost.name = 'total_cost'
return total_cost
def __get_name(param):
brick = None
for annotation in param.tag.annotations:
if isinstance(annotation, Brick):
brick = annotation
break
brick_hierarchy = [brick]
while brick_hierarchy[-1].parents:
brick_hierarchy.append(brick_hierarchy[-1].parents[0])
name = "{}.{}".format('/'.join((b.name for b in brick_hierarchy[::-1])),
param.name)
return name
def apply_adaptive_noise(computation_graph,
cost,
variables,
num_examples,
parameters=None,
init_sigma=1e-6,
model_cost_coefficient=1.0,
seed=None,
gradients=None,
):
"""Add adaptive noise to parameters of a model.
Each of the given variables will be replaced by a normal
distribution with learned mean and standard deviation.
A model cost is computed based on the precision of the the distributions
associated with each variable. It is added to the given cost used to
train the model.
See: <NAME> "Practical Variational Inference for Neural Networks",
NIPS 2011
Parameters
----------
computation_graph : instance of :class:`ComputationGraph`
The computation graph.
cost : :class:`~tensor.TensorVariable`
The cost without weight noise. It should be a member of the
computation_graph.
variables : :class:`~tensor.TensorVariable`
Variables to add noise to.
num_examples : int
Number of training examples. The cost of the model is divided by
the number of training examples, please see
<NAME> "Practical Variational Inference for Neural Networks"
for justification
parameters : list of :class:`~tensor.TensorVariable`
parameters of the model, if gradients are given the list will not
be used. Otherwise, it will be used to compute the gradients
init_sigma : float,
initial standard deviation of noise variables
model_cost_coefficient : float,
the weight of the model cost
seed : int, optional
The seed with which
:class:`~theano.sandbox.rng_mrg.MRG_RandomStreams` is initialized,
is set to 1 by default.
gradients : dict, optional
Adaptive weight noise introduces new parameters for which new cost
and gradients must be computed. Unless the gradients paramter is
given, it will use theano.grad to get the gradients
Returns
-------
cost : :class:`~tensor.TensorVariable`
The new cost
computation_graph : instance of :class:`ComputationGraph`
new graph with added noise.
gradients : dict
a dictionary of gradients for all parameters: the original ones
and the adaptive noise ones
noise_brick : :class:~lvsr.graph.NoiseBrick
the brick that holds all noise parameters and whose .apply method
can be used to find variables added by adaptive noise
"""
if not seed:
seed = config.default_seed
rng = MRG_RandomStreams(seed)
try:
cost_index = computation_graph.outputs.index(cost)
except ValueError:
raise ValueError("cost is not part of the computation_graph")
if gradients is None:
if parameters is None:
raise ValueError("Either gradients or parameters must be given")
logger.info("Taking the cost gradient")
gradients = dict(equizip(parameters,
tensor.grad(cost, parameters)))
else:
if parameters is not None:
logger.warn("Both gradients and parameters given, will ignore"
"parameters")
parameters = gradients.keys()
gradients = OrderedDict(gradients)
log_sigma_scale = 2048.0
P_noisy = variables # We will add noise to these
Beta = [] # will hold means, log_stdev and stdevs
P_with_noise = [] # will hold parames with added noise
# These don't change
P_clean = list(set(parameters).difference(P_noisy))
noise_brick = NoiseBrick()
for p in P_noisy:
p_u = p
p_val = p.get_value(borrow=True)
p_ls2 = theano.shared((numpy.zeros_like(p_val) +
numpy.log(init_sigma) * 2. / log_sigma_scale
).astype(dtype=numpy.float32))
p_ls2.name = __get_name(p_u)
noise_brick.parameters.append(p_ls2)
p_s2 = tensor.exp(p_ls2 * log_sigma_scale)
Beta.append((p_u, p_ls2, p_s2))
p_noisy = p_u + rng.normal(size=p_val.shape) * tensor.sqrt(p_s2)
p_noisy = tensor.patternbroadcast(p_noisy, p.type.broadcastable)
P_with_noise.append(p_noisy)
# compute the prior mean and variation
temp_sum = 0.0
temp_param_count = 0.0
for p_u, unused_p_ls2, unused_p_s2 in Beta:
temp_sum = temp_sum + p_u.sum()
temp_param_count = temp_param_count + p_u.shape.prod()
prior_u = tensor.cast(temp_sum / temp_param_count, 'float32')
temp_sum = 0.0
for p_u, unused_ls2, p_s2 in Beta:
temp_sum = temp_sum + (p_s2).sum() + (((p_u-prior_u)**2).sum())
prior_s2 = tensor.cast(temp_sum/temp_param_count, 'float32')
# convert everything to use the noisy parameters
full_computation_graph = ComputationGraph(computation_graph.outputs +
gradients.values())
full_computation_graph = full_computation_graph.replace(
dict(zip(P_noisy, P_with_noise)))
LC = 0.0 # model cost
for p_u, p_ls2, p_s2 in Beta:
LC = (LC +
0.5 * ((tensor.log(prior_s2) - p_ls2 * log_sigma_scale).sum()) +
1.0 / (2.0 * prior_s2) * (((p_u - prior_u)**2) + p_s2 - prior_s2
).sum()
)
LC = LC / num_examples * model_cost_coefficient
train_cost = noise_brick.apply(
full_computation_graph.outputs[cost_index].copy(), LC,
prior_u, prior_s2)
gradients = OrderedDict(
zip(gradients.keys(),
full_computation_graph.outputs[-len(gradients):]))
#
# Delete the gradients form the computational graph
#
del full_computation_graph.outputs[-len(gradients):]
new_grads = {p: gradients.pop(p) for p in P_clean}
#
# Warning!!!
# This only works for batch size 1 (we want that the sum of squares
# be the square of the sum!
#
diag_hessian_estimate = {p: g**2 for p, g in gradients.iteritems()}
for p_u, p_ls2, p_s2 in Beta:
p_grad = gradients[p_u]
p_u_grad = (model_cost_coefficient * (p_u - prior_u) /
(num_examples*prior_s2) + p_grad)
p_ls2_grad = (numpy.float32(model_cost_coefficient *
0.5 / num_examples * log_sigma_scale) *
(p_s2/prior_s2 - 1.0) +
(0.5*log_sigma_scale) * p_s2 * diag_hessian_estimate[p_u]
)
new_grads[p_u] = p_u_grad
new_grads[p_ls2] = p_ls2_grad
return train_cost, full_computation_graph, new_grads, noise_brick
|
[
"theano.tensor.log",
"numpy.zeros_like",
"numpy.log",
"theano.tensor.exp",
"theano.tensor.cast",
"numpy.float32",
"blocks.bricks.base.application",
"theano.tensor.patternbroadcast",
"theano.tensor.grad",
"theano.sandbox.rng_mrg.MRG_RandomStreams",
"theano.tensor.sqrt",
"collections.OrderedDict",
"logging.getLogger"
] |
[((387, 414), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (404, 414), False, 'import logging\n'), ((945, 1065), 'blocks.bricks.base.application', 'application', ([], {'inputs': "['train_cost', 'model_cost', 'model_prior_mean', 'model_prior_variance']", 'outputs': "['total_cost']"}), "(inputs=['train_cost', 'model_cost', 'model_prior_mean',\n 'model_prior_variance'], outputs=['total_cost'])\n", (956, 1065), False, 'from blocks.bricks.base import Brick, application\n'), ((4942, 4965), 'theano.sandbox.rng_mrg.MRG_RandomStreams', 'MRG_RandomStreams', (['seed'], {}), '(seed)\n', (4959, 4965), False, 'from theano.sandbox.rng_mrg import MRG_RandomStreams\n'), ((5634, 5656), 'collections.OrderedDict', 'OrderedDict', (['gradients'], {}), '(gradients)\n', (5645, 5656), False, 'from collections import OrderedDict\n'), ((6860, 6911), 'theano.tensor.cast', 'tensor.cast', (['(temp_sum / temp_param_count)', '"""float32"""'], {}), "(temp_sum / temp_param_count, 'float32')\n", (6871, 6911), False, 'from theano import tensor\n'), ((7059, 7110), 'theano.tensor.cast', 'tensor.cast', (['(temp_sum / temp_param_count)', '"""float32"""'], {}), "(temp_sum / temp_param_count, 'float32')\n", (7070, 7110), False, 'from theano import tensor\n'), ((6343, 6378), 'theano.tensor.exp', 'tensor.exp', (['(p_ls2 * log_sigma_scale)'], {}), '(p_ls2 * log_sigma_scale)\n', (6353, 6378), False, 'from theano import tensor\n'), ((6511, 6565), 'theano.tensor.patternbroadcast', 'tensor.patternbroadcast', (['p_noisy', 'p.type.broadcastable'], {}), '(p_noisy, p.type.broadcastable)\n', (6534, 6565), False, 'from theano import tensor\n'), ((5389, 5418), 'theano.tensor.grad', 'tensor.grad', (['cost', 'parameters'], {}), '(cost, parameters)\n', (5400, 5418), False, 'from theano import tensor\n'), ((6475, 6492), 'theano.tensor.sqrt', 'tensor.sqrt', (['p_s2'], {}), '(p_s2)\n', (6486, 6492), False, 'from theano import tensor\n'), ((8608, 8684), 'numpy.float32', 'numpy.float32', (['(model_cost_coefficient * 0.5 / num_examples * log_sigma_scale)'], {}), '(model_cost_coefficient * 0.5 / num_examples * log_sigma_scale)\n', (8621, 8684), False, 'import numpy\n'), ((6082, 6105), 'numpy.zeros_like', 'numpy.zeros_like', (['p_val'], {}), '(p_val)\n', (6098, 6105), False, 'import numpy\n'), ((6139, 6160), 'numpy.log', 'numpy.log', (['init_sigma'], {}), '(init_sigma)\n', (6148, 6160), False, 'import numpy\n'), ((7510, 7530), 'theano.tensor.log', 'tensor.log', (['prior_s2'], {}), '(prior_s2)\n', (7520, 7530), False, 'from theano import tensor\n')]
|
# -*- coding: utf-8 -*-
"""
===============================================================================
Generating pulse trains
===============================================================================
This example shows how to use :py:class:`~pulse2percept.stimuli.PulseTrain`
and its variants.
Biphasic pulse trains
---------------------
A series of biphasic pulses can be created with the
:py:class:`~pulse2percept.stimuli.BiphasicPulseTrain` class.
You have the same options as when setting up a single
:py:class:`~pulse2percept.stimuli.BiphasicPulse`, in addition to specifying
a pulse train frequency (``freq``) and total stimulus duration (``stim_dur``).
For example, a 20 Hz pulse train lasting 200 ms and made from anodic-first
biphasic pulses (30 uA, 2 ms pulse duration, no interphase gap) can be
created as follows:
"""
# sphinx_gallery_thumbnail_number = 4
from pulse2percept.stimuli import BiphasicPulseTrain
pt = BiphasicPulseTrain(20, 30, 2, stim_dur=200, cathodic_first=False)
pt.plot()
###############################################################################
# You can also limit the number of pulses in the train, but still make the
# stimulus last 200 ms:
pt = BiphasicPulseTrain(20, 30, 2, n_pulses=3, stim_dur=200,
cathodic_first=False)
pt.plot()
###############################################################################
# Asymmetric biphasic pulse trains
# --------------------------------
#
# To create a 20 Hz pulse train lasting 200 ms created from asymmetric biphasic
# pulses, use :py:class:`~pulse2percept.stimuli.AsymmetricBiphasicPulseTrain`:
from pulse2percept.stimuli import AsymmetricBiphasicPulseTrain
# First pulse:
amp1 = 10
phase_dur1 = 2
# Second pulse
amp2 = 2
phase_dur2 = 10
pt = AsymmetricBiphasicPulseTrain(20, amp1, amp2, phase_dur1, phase_dur2,
stim_dur=200)
pt.plot()
###############################################################################
# Biphasic triplet trains
# -----------------------
#
# To create a train of pulse triplets, use
# :py:class:`~pulse2percept.stimuli.BiphasicTripletTrain`:
from pulse2percept.stimuli import BiphasicTripletTrain
amp = 15
phase_dur = 2
pt = BiphasicTripletTrain(20, amp, phase_dur, stim_dur=200)
pt.plot()
###############################################################################
# Generic pulse trains
# --------------------
#
# Finally, you can concatenate any :py:class:`~pulse2percept.stimuli.Stimulus`
# object into a pulse train.
#
# For example, let's define a single ramp stimulus:
import numpy as np
from pulse2percept.stimuli import Stimulus, PulseTrain
# Single ramp:
dt = 1e-3
ramp = Stimulus([[0, 0, 1, 1, 2, 2, 0, 0]],
time=[0, 1, 1 + dt, 2, 2 + dt, 3, 3 + dt, 5 - dt])
ramp.plot()
# Ramp train:
PulseTrain(20, ramp, stim_dur=200).plot()
# Biphasic ramp:
biphasic_ramp = Stimulus(np.concatenate((ramp.data, -ramp.data), axis=1),
time=np.concatenate((ramp.time, ramp.time + 5)))
biphasic_ramp.plot()
# Biphasic ramp train:
PulseTrain(20, biphasic_ramp, stim_dur=200).plot()
|
[
"pulse2percept.stimuli.BiphasicTripletTrain",
"pulse2percept.stimuli.BiphasicPulseTrain",
"pulse2percept.stimuli.PulseTrain",
"pulse2percept.stimuli.Stimulus",
"pulse2percept.stimuli.AsymmetricBiphasicPulseTrain",
"numpy.concatenate"
] |
[((945, 1010), 'pulse2percept.stimuli.BiphasicPulseTrain', 'BiphasicPulseTrain', (['(20)', '(30)', '(2)'], {'stim_dur': '(200)', 'cathodic_first': '(False)'}), '(20, 30, 2, stim_dur=200, cathodic_first=False)\n', (963, 1010), False, 'from pulse2percept.stimuli import BiphasicPulseTrain\n'), ((1207, 1284), 'pulse2percept.stimuli.BiphasicPulseTrain', 'BiphasicPulseTrain', (['(20)', '(30)', '(2)'], {'n_pulses': '(3)', 'stim_dur': '(200)', 'cathodic_first': '(False)'}), '(20, 30, 2, n_pulses=3, stim_dur=200, cathodic_first=False)\n', (1225, 1284), False, 'from pulse2percept.stimuli import BiphasicPulseTrain\n'), ((1783, 1869), 'pulse2percept.stimuli.AsymmetricBiphasicPulseTrain', 'AsymmetricBiphasicPulseTrain', (['(20)', 'amp1', 'amp2', 'phase_dur1', 'phase_dur2'], {'stim_dur': '(200)'}), '(20, amp1, amp2, phase_dur1, phase_dur2,\n stim_dur=200)\n', (1811, 1869), False, 'from pulse2percept.stimuli import AsymmetricBiphasicPulseTrain\n'), ((2233, 2287), 'pulse2percept.stimuli.BiphasicTripletTrain', 'BiphasicTripletTrain', (['(20)', 'amp', 'phase_dur'], {'stim_dur': '(200)'}), '(20, amp, phase_dur, stim_dur=200)\n', (2253, 2287), False, 'from pulse2percept.stimuli import BiphasicTripletTrain\n'), ((2697, 2788), 'pulse2percept.stimuli.Stimulus', 'Stimulus', (['[[0, 0, 1, 1, 2, 2, 0, 0]]'], {'time': '[0, 1, 1 + dt, 2, 2 + dt, 3, 3 + dt, 5 - dt]'}), '([[0, 0, 1, 1, 2, 2, 0, 0]], time=[0, 1, 1 + dt, 2, 2 + dt, 3, 3 +\n dt, 5 - dt])\n', (2705, 2788), False, 'from pulse2percept.stimuli import Stimulus, PulseTrain\n'), ((2913, 2960), 'numpy.concatenate', 'np.concatenate', (['(ramp.data, -ramp.data)'], {'axis': '(1)'}), '((ramp.data, -ramp.data), axis=1)\n', (2927, 2960), True, 'import numpy as np\n'), ((2828, 2862), 'pulse2percept.stimuli.PulseTrain', 'PulseTrain', (['(20)', 'ramp'], {'stim_dur': '(200)'}), '(20, ramp, stim_dur=200)\n', (2838, 2862), False, 'from pulse2percept.stimuli import Stimulus, PulseTrain\n'), ((2992, 3034), 'numpy.concatenate', 'np.concatenate', (['(ramp.time, ramp.time + 5)'], {}), '((ramp.time, ramp.time + 5))\n', (3006, 3034), True, 'import numpy as np\n'), ((3081, 3124), 'pulse2percept.stimuli.PulseTrain', 'PulseTrain', (['(20)', 'biphasic_ramp'], {'stim_dur': '(200)'}), '(20, biphasic_ramp, stim_dur=200)\n', (3091, 3124), False, 'from pulse2percept.stimuli import Stimulus, PulseTrain\n')]
|
"""This module implements the RYGate."""
from __future__ import annotations
import numpy as np
from bqskit.ir.gates.qubitgate import QubitGate
from bqskit.qis.unitary.differentiable import DifferentiableUnitary
from bqskit.qis.unitary.optimizable import LocallyOptimizableUnitary
from bqskit.qis.unitary.unitary import RealVector
from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix
from bqskit.utils.cachedclass import CachedClass
class RYGate(
QubitGate,
DifferentiableUnitary,
LocallyOptimizableUnitary,
CachedClass,
):
"""
A gate representing an arbitrary rotation around the Y axis.
It is given by the following parameterized unitary:
.. math::
\\begin{pmatrix}
\\cos{\\frac{\\theta}{2}} & -\\sin{\\frac{\\theta}{2}} \\\\
\\sin{\\frac{\\theta}{2}} & \\cos{\\frac{\\theta}{2}} \\\\
\\end{pmatrix}
"""
_num_qudits = 1
_num_params = 1
_qasm_name = 'ry'
def get_unitary(self, params: RealVector = []) -> UnitaryMatrix:
"""Return the unitary for this gate, see :class:`Unitary` for more."""
self.check_parameters(params)
cos = np.cos(params[0] / 2)
sin = np.sin(params[0] / 2)
return UnitaryMatrix(
[
[cos, -sin],
[sin, cos],
],
)
def get_grad(self, params: RealVector = []) -> np.ndarray:
"""
Return the gradient for this gate.
See :class:`DifferentiableUnitary` for more info.
"""
self.check_parameters(params)
dcos = -np.sin(params[0] / 2) / 2
dsin = np.cos(params[0] / 2) / 2
return np.array(
[
[
[dcos, -dsin],
[dsin, dcos],
],
], dtype=np.complex128,
)
def optimize(self, env_matrix: np.ndarray) -> list[float]:
"""
Return the optimal parameters with respect to an environment matrix.
See :class:`LocallyOptimizableUnitary` for more info.
"""
self.check_env_matrix(env_matrix)
a = np.real(env_matrix[0, 0] + env_matrix[1, 1])
b = np.real(env_matrix[1, 0] - env_matrix[0, 1])
theta = 2 * np.arccos(a / np.sqrt(a ** 2 + b ** 2))
theta *= -1 if b > 0 else 1
return [theta]
|
[
"bqskit.qis.unitary.unitarymatrix.UnitaryMatrix",
"numpy.sin",
"numpy.array",
"numpy.real",
"numpy.cos",
"numpy.sqrt"
] |
[((1151, 1172), 'numpy.cos', 'np.cos', (['(params[0] / 2)'], {}), '(params[0] / 2)\n', (1157, 1172), True, 'import numpy as np\n'), ((1187, 1208), 'numpy.sin', 'np.sin', (['(params[0] / 2)'], {}), '(params[0] / 2)\n', (1193, 1208), True, 'import numpy as np\n'), ((1225, 1265), 'bqskit.qis.unitary.unitarymatrix.UnitaryMatrix', 'UnitaryMatrix', (['[[cos, -sin], [sin, cos]]'], {}), '([[cos, -sin], [sin, cos]])\n', (1238, 1265), False, 'from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix\n'), ((1664, 1726), 'numpy.array', 'np.array', (['[[[dcos, -dsin], [dsin, dcos]]]'], {'dtype': 'np.complex128'}), '([[[dcos, -dsin], [dsin, dcos]]], dtype=np.complex128)\n', (1672, 1726), True, 'import numpy as np\n'), ((2122, 2166), 'numpy.real', 'np.real', (['(env_matrix[0, 0] + env_matrix[1, 1])'], {}), '(env_matrix[0, 0] + env_matrix[1, 1])\n', (2129, 2166), True, 'import numpy as np\n'), ((2179, 2223), 'numpy.real', 'np.real', (['(env_matrix[1, 0] - env_matrix[0, 1])'], {}), '(env_matrix[1, 0] - env_matrix[0, 1])\n', (2186, 2223), True, 'import numpy as np\n'), ((1622, 1643), 'numpy.cos', 'np.cos', (['(params[0] / 2)'], {}), '(params[0] / 2)\n', (1628, 1643), True, 'import numpy as np\n'), ((1581, 1602), 'numpy.sin', 'np.sin', (['(params[0] / 2)'], {}), '(params[0] / 2)\n', (1587, 1602), True, 'import numpy as np\n'), ((2258, 2282), 'numpy.sqrt', 'np.sqrt', (['(a ** 2 + b ** 2)'], {}), '(a ** 2 + b ** 2)\n', (2265, 2282), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
import logging
import numpy as np
import copy
import crosstalk
import gates
import predistortion
import pulses
import qubits
import readout
import tomography
# Allow logging to Labber's instrument log
log = logging.getLogger('LabberDriver')
# TODO Reduce calc of CZ by finding all unique TwoQubitGates in seq and calc.
# TODO Make I(width=None) have the width of the longest gate in the step
# TODO Add checks so that not both t0 and dt are given
# TODO Two composite gates should be able to be parallell
# TODO check number of qubits in seq and in gate added to seq
# TODO Remove pulse from I gates
class GateOnQubit:
def __init__(self, gate, qubit, pulse=None):
self.gate = gate
self.qubit = qubit
self.pulse = pulse
if pulse is None:
self.duration = 0
else:
self.duration = pulse.total_duration()
def __str__(self):
return "Gate {} on qubit {}".format(self.gate, self.qubit)
def __repr__(self):
return self.__str__()
class Step:
"""Represent one step in a sequence.
Parameters
----------
n_qubit : int
Number of qubits in the sequece.
t0 : float
Center of the sequence in seconds (the default is None).
dt : float
Spacing to previous pulse in seconds (the default is None). Use only
either t0 or dt.
align : str {'left', 'center', 'right'}
The alignment of pulses if they have different lengths,
(the default is 'center').
Attributes
----------
gates : list of :dict:
The different gates in the step.
"""
def __init__(self, t0=None, dt=None, align='center'):
self.gates = []
self.align = align
self.t0 = t0
self.dt = dt
self.t_start = None
self.t_end = None
def add_gate(self, qubit, gate):
"""Add the given gate to the specified qubit(s).
The number of gates must equal the number of qubits.
If the number of qubits given are less than the number of qubits in the
step, I gates are added to the other qubits.
Parameters
----------
qubit : int or list of int
The qubit indices.
gate : :obj:`BaseGate`
The gate(s).
"""
if gate.number_of_qubits() > 1 and not isinstance(qubit, list):
raise ValueError(
"Provide a list of qubits for gates with more than one qubit")
if gate.number_of_qubits() > 1 and not gate.number_of_qubits() == len(
qubit):
raise ValueError(
"""Number of qubits in the gate must equal the number of qubit
indices given""")
if gate.number_of_qubits() == 1 and not isinstance(qubit, int):
raise ValueError("Provide qubit as int for gates with one qubit")
if isinstance(qubit, int):
if self._qubit_in_step(qubit):
raise ValueError("Qubit {} already in step.".format(qubit))
else:
for n in qubit:
if self._qubit_in_step(n):
raise ValueError("Qubit {} already in step.".format(n))
self.gates.append(GateOnQubit(gate, qubit))
def time_shift(self, shift):
"""Shift the timings of the step.
Parameters
----------
shift : float
The amount of shift to apply in seconds.
"""
self.t_start += shift
self.t0 += shift
self.t_end += shift
def _qubit_in_step(self, qubit):
"""Returns whatever the given qubit is in the step or not. """
if not isinstance(qubit, int):
raise ValueError("Qubit index should be int.")
def _in(input_list, n):
flat_list = []
for sublist_or_el in input_list:
if isinstance(sublist_or_el, list):
if _in(sublist_or_el, n) is True:
return True
elif sublist_or_el == n:
return True
return False
return _in([x.qubit for x in self.gates], qubit)
def __str__(self):
return str(self.gates)
def __repr__(self):
return str(self.gates)
class Sequence:
"""A multi qubit seqence.
Parameters
----------
n_qubit : type
The number of qubits in the sequence.
Attributes
----------
sequences : list of :obj:`Step`
Holds the steps of the sequence.
perform_process_tomography : bool
Flag for performing process tomography.
perform_state_tomography : bool
Flag for performing state tomography.
readout_delay : float
Delay time between last pulse and readout, in seconds.
n_qubit
"""
def __init__(self, n_qubit):
self.n_qubit = n_qubit
# log.info('initiating empty seqence list')
self.sequence_list = []
# process tomography
self.perform_process_tomography = False
self._process_tomography = tomography.ProcessTomography()
# state tomography
self.perform_state_tomography = False
self._state_tomography = tomography.StateTomography()
# readout
self.readout_delay = 0.0
# Public methods
def generate_sequence(self, config):
"""Generate sequence by adding gates/pulses to waveforms.
Parameters
----------
config : dict
Configuration as defined by Labber driver configuration window.
"""
raise NotImplementedError()
def get_sequence(self, config):
"""Compile sequence and return it.
Parameters
----------
config : dict
Labber instrument configuration.
Returns
-------
list of :obj:`Step`
The compiled qubit sequence.
"""
self.sequence_list = []
if self.perform_process_tomography:
self._process_tomography.add_pulses(self)
self.generate_sequence(config)
if self.perform_state_tomography:
self._state_tomography.add_pulses(self)
if self.readout_delay > 0:
delay = gates.IdentityGate(width=self.readout_delay)
self.add_gate_to_all(delay, dt=0)
self.add_gate_to_all(gates.ReadoutGate(), dt=0, align='left')
return self
# Public methods for adding pulses and gates to the sequence.
def add_single_pulse(self,
qubit,
pulse,
t0=None,
dt=None,
align_left=False):
"""Add single qubit pulse to specified qubit.
This function still exist to not break existing
funcationallity. You should really use the add_gate method.
t0 or dt can be used to override the global pulse spacing.
Parameters
----------
qubit : int
Qubit number, indexed from 0.
pulse : :obj:`Pulse`
Definition of pulse to add.
t0 : float, optional
Absolute pulse position.
dt : float, optional
Pulse spacing, referenced to the previous pulse.
align_left: bool, optional
If True, aligns the pulse to the left. Defaults to False.
"""
gate = gates.CustomGate(pulse)
if align_left is True:
self.add_gate(qubit, gate, t0, dt, 'left')
else:
self.add_gate(qubit, gate, t0, dt, 'center')
def add_single_gate(self, qubit, gate, t0=None, dt=None, align_left=False):
"""Add single gate to specified qubit sequence.
Note, this function still exist is to not break existing
funcationallity. You should really use the add_gate method.
t0 or dt can be used to override the global pulse spacing.
Parameters
----------
qubit : int
Qubit number, indexed from 0.
gate : :obj:`Gate`
Definition of gate to add.
t0 : float, optional
Absolute pulse position.
dt : float, optional
Pulse spacing, referenced to the previous pulse.
align_left : boolean, optional
If True, t0 is the start of the pulse, otherwise it is the center
of the pulse. False is the default.
"""
if align_left is True:
self.add_gate(qubit, gate, t0, dt, 'left')
else:
self.add_gate(qubit, gate, t0, dt, 'center')
def add_gate(self,
qubit,
gate,
t0=None,
dt=None,
align='center',
index=None):
"""Add a set of gates to the given qubit sequences.
For the qubits with no specificied gate, an IdentityGate will be given.
The length of the step is given by the longest pulse.
Parameters
----------
qubit : int or list of int
The qubit(s) to add the gate(s) to.
gate : :obj:`BaseGate` or list of :obj:`BaseGate`
The gate(s) to add.
t0 : float, optional
Absolute gate position (the default is None).
dt : float, optional
Gate spacing, referenced to the previous pulse
(the default is None).
align : str, optional
If two or more qubits have differnt pulse lengths, `align`
specifies how those pulses should be aligned. 'Left' aligns the
start, 'center' aligns the centers, and 'right' aligns the end,
(the default is 'center').
index : int, optional
Where in the sequence to insert the new gate.
"""
step = Step(t0=t0, dt=dt, align=align)
if isinstance(gate, list):
if not isinstance(qubit, list):
raise ValueError(
"""Provide qubit indices as a list when adding more than
one gate.""")
if len(gate) != len(qubit):
raise ValueError(
"Length of gate list must equal length of qubit list.")
for q, g in zip(qubit, gate):
step.add_gate(q, g)
else:
if gate.number_of_qubits() > 1:
if not isinstance(qubit, list):
raise ValueError(
"Provide qubit list for gates with more than one qubit"
)
else:
if not isinstance(qubit, int):
raise ValueError(
"For single gates, give qubit as int (not list).")
step.add_gate(qubit, gate)
# log.info('adding gate {} to {}. 2qb gate: {}'.format(gate, qubit, isinstance(gate, gates.TwoQubitGate)))
if index is None:
self.sequence_list.append(step)
# log.info('adding step to sequence list')
# log.info('sequence len is {}'.format(len(self.sequence_list)))
else:
self.sequence_list.insert(index + 1, step)
# log.info('inserting step in sequence list')
# log.info('sequence len is {}'.format(len(self.sequence_list)))
def add_gate_to_all(self, gate, t0=None, dt=None, align='center'):
"""Add a single gate to all qubits.
Pulses are added at the end of the sequence, with the gate spacing set
by either the spacing parameter or the aboslut position.
"""
if isinstance(gate, list):
raise ValueError("Only single gates allowed.")
if isinstance(gate, (gates.BaseGate, gates.CompositeGate)):
if gate.number_of_qubits() > 1:
raise ValueError(
"Not clear how to add multi-qubit gates to all qubits.")
qubit = list(range((self.n_qubit)))
gate = [gate for n in range(self.n_qubit)]
self.add_gate(qubit, gate, t0=t0, dt=dt, align=align)
def add_gates(self, gates):
"""Add multiple gates to the qubit waveform.
Pulses are added at the end of the sequence, with the gate spacing set
by the spacing parameter.
Examples
--------
Add three gates to a two-qubit sequence, first a positive pi-pulse
around X to qubit 1, then a negative pi/2-pulse to qubit 2, finally
simultaneous positive pi-pulses to qubits 1 and 2.
>>> add_gates([[gates.Xp, None ],
[None, gates.Y2m],
[gates.Xp, gates.Xp]])
Parameters
----------
gates : list of list of :obj:`BaseGate`
List of lists defining gates to add. The innermost list should
have the same length as number of qubits in the sequence.
"""
# make sure we have correct input
if not isinstance(gates, (list, tuple)):
raise Exception('The input must be a list of list with gates')
if len(gates) == 0:
return
if not isinstance(gates[0], (list, tuple)):
raise Exception('The input must be a list of list with gates')
# add gates sequence to waveforms
for gate in gates:
# add gate to specific qubit waveform
qubit = list(range(len(gate)))
self.add_gate(qubit, gate)
def set_parameters(self, config={}):
"""Set base parameters using config from from Labber driver.
Parameters
----------
config : dict
Configuration as defined by Labber driver configuration window
"""
# sequence parameters
d = dict(
Zero=0,
One=1,
Two=2,
Three=3,
Four=4,
Five=5,
Six=6,
Seven=7,
Eight=8,
Nine=9)
# If the number of qubits changed, we need to re-init
if self.n_qubit != d[config.get('Number of qubits')]:
self.__init__(d[config.get('Number of qubits')])
# Readout
self.readout_delay = config.get('Readout delay')
# process tomography prepulses
self.perform_process_tomography = \
config.get('Generate process tomography prepulse', False)
self._process_tomography.set_parameters(config)
# state tomography
self.perform_state_tomography = config.get(
'Generate state tomography postpulse', False)
self._state_tomography.set_parameters(config)
class SequenceToWaveforms:
"""Compile a multi qubit sequence into waveforms.
Parameters
----------
n_qubit : type
The maximum number of qubits.
Attributes
----------
dt : float
Pulse spacing, in seconds.
local_xy : bool
If False, collate all waveforms into one.
simultaneous_pulses : bool
If False, seperate all pulses in time.
sample_rate : float
AWG Sample rate.
n_pts : float
Number of points in the waveforms.
first_delay : float
Delay between start of waveform and start of the first pulse.
trim_to_sequence : bool
If True, adjust `n_points` to just fit the sequence.
align_to_end : bool
Align the whole sequence to the end of the waveforms.
Only relevant if `trim_to_sequence` is False.
sequences : list of :obj:`Step`
The qubit sequences.
qubits : list of :obj:`Qubit`
Parameters of each qubit.
wave_xy_delays : list of float
Indiviudal delays for the XY waveforms.
wave_z_delays : list of float
Indiviudal delays for the Z waveforms.
n_qubit
"""
def __init__(self, n_qubit):
self.n_qubit = n_qubit
self.dt = 10E-9
self.local_xy = True
self.simultaneous_pulses = True
# waveform parameter
self.sample_rate = 1.2E9
self.n_pts = 240E3
self.first_delay = 100E-9
self.trim_to_sequence = True
self.align_to_end = False
self.sequence_list = []
self.qubits = [qubits.Qubit() for n in range(self.n_qubit)]
# waveforms
self._wave_xy = [
np.zeros(0, dtype=np.complex) for n in range(self.n_qubit)
]
# log.info('_wave_z initiated to 0s')
self._wave_z = [np.zeros(0) for n in range(self.n_qubit)]
self._wave_gate = [np.zeros(0) for n in range(self.n_qubit)]
# waveform delays
self.wave_xy_delays = np.zeros(self.n_qubit)
self.wave_z_delays = np.zeros(self.n_qubit)
# define pulses
self.pulses_1qb_xy = [None for n in range(self.n_qubit)]
self.pulses_1qb_z = [None for n in range(self.n_qubit)]
self.pulses_2qb = [None for n in range(self.n_qubit - 1)]
self.pulses_readout = [None for n in range(self.n_qubit)]
# cross-talk
self.compensate_crosstalk = False
self._crosstalk = crosstalk.Crosstalk()
# predistortion
self.perform_predistortion = False
self._predistortions = [
predistortion.Predistortion(n) for n in range(self.n_qubit)
]
self._predistortions_z = [
predistortion.ExponentialPredistortion(n)
for n in range(self.n_qubit)
]
# gate switch waveform
self.generate_gate_switch = False
self.uniform_gate = False
self.gate_delay = 0.0
self.gate_overlap = 20E-9
self.minimal_gate_time = 20E-9
# filters
self.use_gate_filter = False
self.use_z_filter = False
# readout trig settings
self.readout_trig_generate = False
# readout wave object and settings
self.readout = readout.Demodulation(self.n_qubit)
self.readout_trig = np.array([], dtype=float)
self.readout_iq = np.array([], dtype=np.complex)
def get_waveforms(self, sequence):
"""Compile the given sequence into waveforms.
Parameters
----------
sequences : list of :obj:`Step`
The qubit sequence to be compiled.
Returns
-------
type
Description of returned object.
"""
self.sequence = sequence
self.sequence_list = sequence.sequence_list
# log.info('Start of get_waveforms. Len sequence list: {}'.format(len(self.sequence_list)))
# log.info('Point 1: Sequence_list[3].gates = {}'.format(self.sequence_list[3].gates))
if not self.simultaneous_pulses:
self._seperate_gates()
# log.info('Point 2: Sequence_list[6].gates = {}'.format(self.sequence_list[6].gates))
self._explode_composite_gates()
# log.info('Point 3: Sequence_list[6].gates = {}'.format(self.sequence_list[6].gates))
self._add_pulses_and_durations()
# log.info('Point 4: Sequence_list[6].gates = {}'.format(self.sequence_list[6].gates))
self._add_timings()
# log.info('Point 5: Sequence_list[6].gates = {}'.format(self.sequence_list[6].gates))
self._init_waveforms()
# log.info('Point 6: Sequence_list[6].gates = {}'.format(self.sequence_list[6].gates))
if self.align_to_end:
shift = self._round((self.n_pts - 2) / self.sample_rate -
self.sequence_list[-1].t_end)
for step in self.sequence_list:
step.time_shift(shift)
self._perform_virtual_z()
self._generate_waveforms()
# collapse all xy pulses to one waveform if no local XY control
if not self.local_xy:
# sum all waveforms to first one
self._wave_xy[0] = np.sum(self._wave_xy[:self.n_qubit], 0)
# clear other waveforms
for n in range(1, self.n_qubit):
self._wave_xy[n][:] = 0.0
# log.info('before predistortion, _wave_z max is {}'.format(np.max(self._wave_z)))
# if self.compensate_crosstalk:
# self._perform_crosstalk_compensation()
if self.perform_predistortion:
self._predistort_xy_waveforms()
if self.perform_predistortion_z:
self._predistort_z_waveforms()
if self.readout_trig_generate:
self._add_readout_trig()
if self.generate_gate_switch:
self._add_microwave_gate()
self._filter_output_waveforms()
# Apply offsets
self.readout_iq += self.readout_i_offset + 1j * self.readout_q_offset
# create and return dictionary with waveforms
waveforms = dict()
waveforms['xy'] = self._wave_xy
waveforms['z'] = self._wave_z
waveforms['gate'] = self._wave_gate
waveforms['readout_trig'] = self.readout_trig
waveforms['readout_iq'] = self.readout_iq
# log.info('returning z waveforms in get_waveforms. Max is {}'.format(np.max(waveforms['z'])))
return waveforms
def _seperate_gates(self):
new_sequences = []
for step in self.sequence_list:
if any(
isinstance(gate, (gates.ReadoutGate, gates.IdentityGate))
for gate in step.gates):
# Don't seperate I gates or readouts since we do
# multiplexed readout
new_sequences.append(step)
continue
for gate in step.gates:
# log.info('In seperate gates, handling gate {}'.format(gate))
if gate.gate is not None:
new_step = Step(
t0=step.t_start, dt=step.dt, align=step.align)
new_step.add_gate(gate.qubit, gate.gate)
new_sequences.append(new_step)
# log.info('New sequence [6] is {}'.format(new_sequences[6].gates))
self.sequence_list = new_sequences
def _add_timings(self):
t_start = 0
for step in self.sequence_list:
if step.dt is None and step.t0 is None:
# Use global pulse spacing
step.dt = self.dt
# Find longest gate in sequence
max_duration = np.max([x.duration for x in step.gates])
if step.t0 is None:
step.t_start = self._round(t_start + step.dt)
step.t0 = self._round(step.t_start + max_duration / 2)
else:
step.t_start = self._round(step.t0 - max_duration / 2)
step.t_end = self._round(step.t_start + max_duration)
t_start = step.t_end # Next step starts where this one ends
# Avoid double spacing for steps with 0 duration
if max_duration == 0:
t_start = t_start - step.dt
# Make sure that the sequence is sorted chronologically.
# self.sequence_list.sort(key=lambda x: x.t_start) # TODO Fix this
# Make sure that sequnce starts on first delay
time_diff = self._round(self.first_delay -
self.sequence_list[0].t_start)
for step in self.sequence_list:
step.time_shift(time_diff)
def _add_pulses_and_durations(self):
for step in self.sequence_list:
for gate in step.gates:
if gate.pulse is None:
gate.pulse = self._get_pulse_for_gate(gate)
if gate.pulse is None:
gate.duration = 0
else:
gate.duration = gate.pulse.total_duration()
def _get_pulse_for_gate(self, gate):
qubit = gate.qubit
gate = gate.gate
# Virtual Z is special since it has no length
if isinstance(gate, gates.VirtualZGate):
pulse = None
# Get the corresponding pulse for other gates
elif isinstance(gate, gates.SingleQubitXYRotation):
pulse = gate.get_adjusted_pulse(self.pulses_1qb_xy[qubit])
elif isinstance(gate, gates.SingleQubitZRotation):
pulse = gate.get_adjusted_pulse(self.pulses_1qb_z[qubit])
elif isinstance(gate, gates.IdentityGate):
pulse = gate.get_adjusted_pulse(self.pulses_1qb_xy[qubit])
elif isinstance(gate, gates.TwoQubitGate):
pulse = gate.get_adjusted_pulse(self.pulses_2qb[qubit[0]])
elif isinstance(gate, gates.ReadoutGate):
pulse = gate.get_adjusted_pulse(self.pulses_readout[qubit])
elif isinstance(gate, gates.CustomGate):
pulse = gate.get_adjusted_pulse(gate.pulse)
else:
raise ValueError('Please provide a pulse for {}'.format(gate))
return pulse
def _predistort_xy_waveforms(self):
"""Pre-distort the waveforms."""
# go through and predistort all xy waveforms
n_wave = self.n_qubit if self.local_xy else 1
for n in range(n_wave):
self._wave_xy[n] = self._predistortions[n].predistort(
self._wave_xy[n])
def _predistort_z_waveforms(self):
# go through and predistort all waveforms
for n in range(self.n_qubit):
self._wave_z[n] = self._predistortions_z[n].predistort(
self._wave_z[n])
def _perform_crosstalk_compensation(self):
"""Compensate for Z-control crosstalk."""
self._wave_z = self._crosstalk.compensate(self._wave_z)
def _explode_composite_gates(self):
# Loop through the sequence until all CompositeGates are removed
# Note that there could be nested CompositeGates
n = 0
while n < len(self.sequence_list):
step = self.sequence_list[n]
i = 0
while i < len(step.gates):
gate = step.gates[i]
if isinstance(gate.gate, gates.CompositeGate):
# # log.info('In exploded composite, handling composite gate {} at step {}'.format(gate, n))
for m, g in enumerate(gate.gate.sequence):
new_gate = [x.gate for x in g.gates]
# Single gates shouldn't be lists
if len(new_gate) == 1:
new_gate = new_gate[0]
# Translate gate qubit number to device qubit number
new_qubit = [x.qubit for x in g.gates]
for j, q in enumerate(new_qubit):
if isinstance(q, int):
if isinstance(gate.qubit, int):
new_qubit[j] = gate.qubit
continue
new_qubit[j] = gate.qubit[q]
else:
new_qubit[j] = []
for k in q:
new_qubit[j].append(gate.qubit[k])
# Single qubit shouldn't be lists
if len(new_qubit) == 1:
new_qubit = new_qubit[0]
# # log.info('In explode composite; modifying {} by adding gate {} at index {}'.format(gate, new_gate, n+m))
self.sequence.add_gate(
new_qubit, new_gate, index=n + m)
del step.gates[i]
# # log.info('In composite gates, removing step {}', i)
continue
i = i + 1
n = n + 1
# Remove any empty steps where the composite gates were
i = 0
while i < len(self.sequence_list):
step = self.sequence_list[i]
if len(step.gates) == 0:
del self.sequence_list[i]
# log.info('In composite gates, removing step {}', i)
continue
i = i + 1
# for i, step in enumerate(self.sequence_list):
# log.info('At end of explode, step {} is {}'.format(i, step.gates))
def _perform_virtual_z(self):
"""Shifts the phase of pulses subsequent to virtual z gates."""
for qubit in range(self.n_qubit):
phase = 0
for step in self.sequence_list:
for gate in step.gates:
gate_obj = None
if qubit == gate.qubit: # TODO Allow for 2 qb
gate_obj = gate.gate
if isinstance(gate_obj, gates.VirtualZGate):
phase += gate_obj.theta
continue
if (isinstance(gate_obj, gates.SingleQubitXYRotation)
and phase != 0):
gate.gate = copy.copy(gate_obj)
gate.gate.phi += phase
# Need to recomput the pulse
gate.pulse = self._get_pulse_for_gate(gate)
def _add_microwave_gate(self):
"""Create waveform for gating microwave switch."""
n_wave = self.n_qubit if self.local_xy else 1
# go through all waveforms
for n, wave in enumerate(self._wave_xy[:n_wave]):
if self.uniform_gate:
# the uniform gate is all ones
gate = np.ones_like(wave)
# if creating readout trig, turn off gate during readout
if self.readout_trig_generate:
gate[-int((self.readout_trig_duration - self.gate_overlap -
self.gate_delay) * self.sample_rate):] = 0.0
else:
# non-uniform gate, find non-zero elements
gate = np.array(np.abs(wave) > 0.0, dtype=float)
# fix gate overlap
n_overlap = int(np.round(self.gate_overlap * self.sample_rate))
diff_gate = np.diff(gate)
indx_up = np.nonzero(diff_gate > 0.0)[0]
indx_down = np.nonzero(diff_gate < 0.0)[0]
# add extra elements to left and right for overlap
for indx in indx_up:
gate[max(0, indx - n_overlap):(indx + 1)] = 1.0
for indx in indx_down:
gate[indx:(indx + n_overlap + 1)] = 1.0
# fix gaps in gate shorter than min (look for 1>0)
diff_gate = np.diff(gate)
indx_up = np.nonzero(diff_gate > 0.0)[0]
indx_down = np.nonzero(diff_gate < 0.0)[0]
# ignore first transition if starting in zero
if gate[0] == 0:
indx_up = indx_up[1:]
n_down_up = min(len(indx_down), len(indx_up))
len_down = indx_up[:n_down_up] - indx_down[:n_down_up]
# find short gaps
short_gaps = np.nonzero(
len_down < (self.minimal_gate_time * self.sample_rate))[0]
for indx in short_gaps:
gate[indx_down[indx]:(1 + indx_up[indx])] = 1.0
# shift gate in time
n_shift = int(np.round(self.gate_delay * self.sample_rate))
if n_shift < 0:
n_shift = abs(n_shift)
gate = np.r_[gate[n_shift:], np.zeros((n_shift, ))]
elif n_shift > 0:
gate = np.r_[np.zeros((n_shift, )), gate[:(-n_shift)]]
# make sure gate starts/ends in 0
gate[0] = 0.0
gate[-1] = 0.0
# store results
self._wave_gate[n] = gate
def _filter_output_waveforms(self):
"""Filter output waveforms"""
# start with gate
if self.use_gate_filter and self.gate_filter_size > 1:
# prepare filter
window = self._get_filter_window(
self.gate_filter_size, self.gate_filter,
self.gate_filter_kaiser_beta)
# apply filter to all output waveforms
n_wave = self.n_qubit if self.local_xy else 1
for n in range(n_wave):
self._wave_gate[n] = self._apply_window_filter(
self._wave_gate[n], window)
# make sure gate starts/ends in 0
self._wave_gate[n][0] = 0.0
self._wave_gate[n][-1] = 0.0
# same for z waveforms
if self.use_z_filter and self.z_filter_size > 1:
# prepare filter
window = self._get_filter_window(
self.z_filter_size, self.z_filter, self.z_filter_kaiser_beta)
# apply filter to all output waveforms
for n in range(self.n_qubit):
self._wave_z[n] = self._apply_window_filter(
self._wave_z[n], window)
def _get_filter_window(self, size=11, window='Kaiser', kaiser_beta=14.0):
"""Get filter for waveform convolution"""
if window == 'Rectangular':
w = np.ones(size)
elif window == 'Bartlett':
# for filters that start/end in zeros, add 2 points and truncate
w = np.bartlett(max(1, size+2))
w = w[1:-1]
elif window == 'Blackman':
w = np.blackman(size + 2)
w = w[1:-1]
elif window == 'Hamming':
w = np.hamming(size)
elif window == 'Hanning':
w = np.hanning(size + 2)
w = w[1:-1]
elif window == 'Kaiser':
w = np.kaiser(size, kaiser_beta)
else:
raise('Unknown filter windows function %s.' % str(window))
return w/w.sum()
def _apply_window_filter(self, x, window):
"""Apply window filter to input waveform
Parameters
----------
x: np.array
Input waveform.
window: np.array
Filter waveform.
Returns
-------
np.array
Filtered waveform.
"""
# buffer waveform to avoid wrapping effects at boundaries
n = len(window)
s = np.r_[2*x[0] - x[n-1::-1], x, 2*x[-1] - x[-1:-n:-1]]
# apply convolution
y = np.convolve(s, window, mode='same')
return y[n:-n+1]
def _round(self, t, acc=1E-12):
"""Round the time `t` with a certain accuarcy `acc`.
Parameters
----------
t : float
The time to be rounded.
acc : float
The accuarcy (the default is 1E-12).
Returns
-------
float
The rounded time.
"""
return int(np.round(t / acc)) * acc
def _add_readout_trig(self):
"""Create waveform for readout trigger."""
trig = np.zeros_like(self.readout_iq)
start = (np.abs(self.readout_iq) > 0.0).nonzero()[0][0]
end = int(
np.min((start + self.readout_trig_duration * self.sample_rate,
self.n_pts_readout)))
trig[start:end] = self.readout_trig_amplitude
# make sure trig starts and ends in 0.
trig[0] = 0.0
trig[-1] = 0.0
self.readout_trig = trig
def _init_waveforms(self):
"""Initialize waveforms according to sequence settings."""
# To keep the first pulse delay, use the smallest delay as reference.
min_delay = np.min([
self.wave_xy_delays[:self.n_qubit],
self.wave_z_delays[:self.n_qubit]
])
self.wave_xy_delays -= min_delay
self.wave_z_delays -= min_delay
max_delay = np.max([
self.wave_xy_delays[:self.n_qubit],
self.wave_z_delays[:self.n_qubit]
])
# find the end of the sequence
# only include readout in size estimate if all waveforms have same size
if self.readout_match_main_size:
if len(self.sequence_list) == 0:
end = max_delay
else:
end = np.max(
[s.t_end for s in self.sequence_list]) + max_delay
else:
if len(self.sequence_list) <= 1:
end = max_delay
else:
end = np.max(
[s.t_end for s in self.sequence_list[0:-1]]) + max_delay
# create empty waveforms of the correct size
if self.trim_to_sequence:
self.n_pts = int(np.ceil(end * self.sample_rate)) + 1
if self.n_pts % 2 == 1:
# Odd n_pts give spectral leakage in FFT
self.n_pts += 1
for n in range(self.n_qubit):
self._wave_xy[n] = np.zeros(self.n_pts, dtype=np.complex)
# log.info('wave z {} initiated to 0'.format(n))
self._wave_z[n] = np.zeros(self.n_pts, dtype=float)
self._wave_gate[n] = np.zeros(self.n_pts, dtype=float)
# Waveform time vector
self.t = np.arange(self.n_pts) / self.sample_rate
# readout trig and i/q waveforms
if self.readout_match_main_size:
# same number of points for readout and main waveform
self.n_pts_readout = self.n_pts
else:
# different number of points for readout and main waveform
self.n_pts_readout = 1 + int(
np.ceil(self.sample_rate * (self.sequence_list[-1].t_end -
self.sequence_list[-1].t_start)))
if self.n_pts_readout % 2 == 1:
# Odd n_pts give spectral leakage in FFT
self.n_pts_readout += 1
self.readout_trig = np.zeros(self.n_pts_readout, dtype=float)
self.readout_iq = np.zeros(self.n_pts_readout, dtype=np.complex)
def _generate_waveforms(self):
"""Generate the waveforms corresponding to the sequence."""
# log.info('generating waveform from sequence. Len is {}'.format(len(self.sequence_list)))
for step in self.sequence_list:
# log.info('Generating gates {}'.format(step.gates))
for gate in step.gates:
qubit = gate.qubit
if isinstance(qubit, list):
qubit = qubit[0]
gate_obj = gate.gate
if isinstance(gate_obj,
(gates.IdentityGate, gates.VirtualZGate)):
continue
elif isinstance(gate_obj, gates.SingleQubitZRotation):
waveform = self._wave_z[qubit]
delay = self.wave_z_delays[qubit]
if self.compensate_crosstalk:
crosstalk = self._crosstalk.compensation_matrix[:,
qubit]
elif isinstance(gate_obj, gates.TwoQubitGate):
# log.info('adding 2qb gate waveforms')
waveform = self._wave_z[qubit]
delay = self.wave_z_delays[qubit]
if self.compensate_crosstalk:
crosstalk = self._crosstalk.compensation_matrix[:,
qubit]
elif isinstance(gate_obj, gates.SingleQubitXYRotation):
waveform = self._wave_xy[qubit]
delay = self.wave_xy_delays[qubit]
elif isinstance(gate_obj, gates.ReadoutGate):
waveform = self.readout_iq
delay = 0
else:
raise ValueError(
"Don't know which waveform to add {} to.".format(
gate_obj))
# get the range of indices in use
if (isinstance(gate_obj, gates.ReadoutGate)
and not self.readout_match_main_size):
# special case for readout if not matching main wave size
start = 0.0
end = self._round(step.t_end - step.t_start)
else:
start = self._round(step.t_start + delay)
end = self._round(step.t_end + delay)
if (self.compensate_crosstalk and
isinstance(gate_obj,
(gates.SingleQubitZRotation,
gates.TwoQubitGate))):
for q in range(self.n_qubit):
waveform = self._wave_z[q]
delay = self.wave_z_delays[q]
start = self._round(step.t_start + delay)
end = self._round(step.t_end + delay)
indices = np.arange(
max(np.floor(start * self.sample_rate), 0),
min(
np.ceil(end * self.sample_rate),
len(waveform)),
dtype=int)
# return directly if no indices
if len(indices) == 0:
continue
# calculate time values for the pulse indices
t = indices / self.sample_rate
max_duration = end - start
middle = end - max_duration / 2
if step.align == 'center':
t0 = middle
elif step.align == 'left':
t0 = middle - (max_duration - gate.duration) / 2
elif step.align == 'right':
t0 = middle + (max_duration - gate.duration) / 2
scaling_factor = float(crosstalk[q, 0])
if q != qubit:
scaling_factor = -scaling_factor
waveform[indices] += (
scaling_factor
* gate.pulse.calculate_waveform(t0, t))
else:
# calculate the pulse waveform for the selected indices
indices = np.arange(
max(np.floor(start * self.sample_rate), 0),
min(np.ceil(end * self.sample_rate), len(waveform)),
dtype=int)
# return directly if no indices
if len(indices) == 0:
continue
# calculate time values for the pulse indices
t = indices / self.sample_rate
max_duration = end - start
middle = end - max_duration / 2
if step.align == 'center':
t0 = middle
elif step.align == 'left':
t0 = middle - (max_duration - gate.duration) / 2
elif step.align == 'right':
t0 = middle + (max_duration - gate.duration) / 2
waveform[indices] += gate.pulse.calculate_waveform(t0, t)
def set_parameters(self, config={}):
"""Set base parameters using config from from Labber driver.
Parameters
----------
config : dict
Configuration as defined by Labber driver configuration window
"""
# sequence parameters
d = dict(
Zero=0,
One=1,
Two=2,
Three=3,
Four=4,
Five=5,
Six=6,
Seven=7,
Eight=8,
Nine=9)
# If the number of qubits changed, re-init to update pulses etc
if self.n_qubit != d[config.get('Number of qubits')]:
self.__init__(d[config.get('Number of qubits')])
self.dt = config.get('Pulse spacing')
self.local_xy = config.get('Local XY control')
# default for simultaneous pulses is true, only option for benchmarking
self.simultaneous_pulses = config.get('Simultaneous pulses', True)
# waveform parameters
self.sample_rate = config.get('Sample rate')
self.n_pts = int(config.get('Number of points', 0))
self.first_delay = config.get('First pulse delay')
self.trim_to_sequence = config.get('Trim waveform to sequence')
self.trim_start = config.get('Trim both start and end')
self.align_to_end = config.get('Align pulses to end of waveform')
# qubit spectra
for n in range(self.n_qubit):
m = n + 1 # pulses are indexed from 1 in Labber
qubit = qubits.Transmon(
config.get('f01 max #{}'.format(m)),
config.get('f01 min #{}'.format(m)),
config.get('Ec #{}'.format(m)),
config.get('Vperiod #{}'.format(m)),
config.get('Voffset #{}'.format(m)),
config.get('V0 #{}'.format(m)),
)
self.qubits[n] = qubit
# single-qubit pulses XY
for n, pulse in enumerate(self.pulses_1qb_xy):
m = n + 1 # pulses are indexed from 1 in Labber
pulse = (getattr(pulses, config.get('Pulse type'))(complex=True))
# global parameters
pulse.truncation_range = config.get('Truncation range')
pulse.start_at_zero = config.get('Start at zero')
pulse.use_drag = config.get('Use DRAG')
# pulse shape
if config.get('Uniform pulse shape'):
pulse.width = config.get('Width')
pulse.plateau = config.get('Plateau')
else:
pulse.width = config.get('Width #%d' % m)
pulse.plateau = config.get('Plateau #%d' % m)
if config.get('Uniform amplitude'):
pulse.amplitude = config.get('Amplitude')
else:
pulse.amplitude = config.get('Amplitude #%d' % m)
# pulse-specific parameters
pulse.frequency = config.get('Frequency #%d' % m)
pulse.drag_coefficient = config.get('DRAG scaling #%d' % m)
pulse.drag_detuning = config.get('DRAG frequency detuning #%d' % m)
self.pulses_1qb_xy[n] = pulse
# single-qubit pulses Z
for n, pulse in enumerate(self.pulses_1qb_z):
# pulses are indexed from 1 in Labber
m = n + 1
# global parameters
pulse = (getattr(pulses,
config.get('Pulse type, Z'))(complex=False))
pulse.truncation_range = config.get('Truncation range, Z')
pulse.start_at_zero = config.get('Start at zero, Z')
# pulse shape
if config.get('Uniform pulse shape, Z'):
pulse.width = config.get('Width, Z')
pulse.plateau = config.get('Plateau, Z')
else:
pulse.width = config.get('Width #%d, Z' % m)
pulse.plateau = config.get('Plateau #%d, Z' % m)
if config.get('Uniform amplitude, Z'):
pulse.amplitude = config.get('Amplitude, Z')
else:
pulse.amplitude = config.get('Amplitude #%d, Z' % m)
self.pulses_1qb_z[n] = pulse
# two-qubit pulses
for n, pulse in enumerate(self.pulses_2qb):
# pulses are indexed from 1 in Labber
s = ' #%d%d' % (n + 1, n + 2)
# global parameters
pulse = (getattr(pulses,
config.get('Pulse type, 2QB'))(complex=False))
if config.get('Pulse type, 2QB') in ['CZ', 'NetZero']:
pulse.F_Terms = d[config.get('Fourier terms, 2QB')]
if config.get('Uniform 2QB pulses'):
pulse.width = config.get('Width, 2QB')
pulse.plateau = config.get('Plateau, 2QB')
else:
pulse.width = config.get('Width, 2QB' + s)
pulse.plateau = config.get('Plateau, 2QB')
# spectra
if config.get('Assume linear dependence' + s, True):
pulse.qubit = None
else:
pulse.qubit = self.qubits[n]
# Get Fourier values
if d[config.get('Fourier terms, 2QB')] == 4:
pulse.Lcoeff = np.array([
config.get('L1, 2QB' + s),
config.get('L2, 2QB' + s),
config.get('L3, 2QB' + s),
config.get('L4, 2QB' + s)
])
elif d[config.get('Fourier terms, 2QB')] == 3:
pulse.Lcoeff = np.array([
config.get('L1, 2QB' + s),
config.get('L2, 2QB' + s),
config.get('L3, 2QB' + s)
])
elif d[config.get('Fourier terms, 2QB')] == 2:
pulse.Lcoeff = np.array(
[config.get('L1, 2QB' + s),
config.get('L2, 2QB' + s)])
elif d[config.get('Fourier terms, 2QB')] == 1:
pulse.Lcoeff = np.array([config.get('L1, 2QB' + s)])
pulse.Coupling = config.get('Coupling, 2QB' + s)
pulse.Offset = config.get('f11-f20 initial, 2QB' + s)
pulse.amplitude = config.get('f11-f20 final, 2QB' + s)
pulse.dfdV = config.get('df/dV, 2QB' + s)
pulse.negative_amplitude = config.get('Negative amplitude' + s)
pulse.calculate_cz_waveform()
else:
pulse.truncation_range = config.get('Truncation range, 2QB')
pulse.start_at_zero = config.get('Start at zero, 2QB')
# pulse shape
if config.get('Uniform 2QB pulses'):
pulse.width = config.get('Width, 2QB')
pulse.plateau = config.get('Plateau, 2QB')
else:
pulse.width = config.get('Width, 2QB' + s)
pulse.plateau = config.get('Plateau, 2QB' + s)
# pulse-specific parameters
pulse.amplitude = config.get('Amplitude, 2QB' + s)
gates.CZ.new_angles(
config.get('QB1 Phi 2QB #12'), config.get('QB2 Phi 2QB #12'))
gates.CR.update_params(config.get('CR amplitude'), config.get('CR phase'), config.get('CR frequency'), 0, config.get('CR length'), config.get('CR cancelation amplitude'), config.get('CR cancelation phase'), np.pi/2, 0, np.pi/2)
self.pulses_2qb[n] = pulse
# predistortion
self.perform_predistortion = config.get('Predistort waveforms', False)
# update all predistorting objects
for p in self._predistortions:
p.set_parameters(config)
# Z predistortion
self.perform_predistortion_z = config.get('Predistort Z')
for p in self._predistortions_z:
p.set_parameters(config)
# crosstalk
self.compensate_crosstalk = config.get('Compensate cross-talk', False)
self._crosstalk.set_parameters(config)
# gate switch waveform
self.generate_gate_switch = config.get('Generate gate')
self.uniform_gate = config.get('Uniform gate')
self.gate_delay = config.get('Gate delay')
self.gate_overlap = config.get('Gate overlap')
self.minimal_gate_time = config.get('Minimal gate time')
# filters
self.use_gate_filter = config.get('Filter gate waveforms', False)
self.gate_filter = config.get('Gate filter', 'Kaiser')
self.gate_filter_size = int(config.get('Gate - Filter size', 5))
self.gate_filter_kaiser_beta = config.get(
'Gate - Kaiser beta', 14.0)
self.use_z_filter = config.get('Filter Z waveforms', False)
self.z_filter = config.get('Z filter', 'Kaiser')
self.z_filter_size = int(config.get('Z - Filter size', 5))
self.z_filter_kaiser_beta = config.get(
'Z - Kaiser beta', 14.0)
# readout
self.readout_match_main_size = config.get(
'Match main sequence waveform size')
self.readout_i_offset = config.get('Readout offset - I')
self.readout_q_offset = config.get('Readout offset - Q')
self.readout_trig_generate = config.get('Generate readout trig')
self.readout_trig_amplitude = config.get('Readout trig amplitude')
self.readout_trig_duration = config.get('Readout trig duration')
self.readout_predistort = config.get('Predistort readout waveform')
self.readout.set_parameters(config)
# get readout pulse parameters
phases = 2 * np.pi * np.array([
0.8847060, 0.2043214, 0.9426104, 0.6947334, 0.8752361, 0.2246747,
0.6503154, 0.7305004, 0.1309068
])
for n, pulse in enumerate(self.pulses_readout):
# pulses are indexed from 1 in Labber
m = n + 1
pulse = (getattr(pulses,
config.get('Readout pulse type'))(complex=True))
pulse.truncation_range = config.get('Readout truncation range')
pulse.start_at_zero = config.get('Readout start at zero')
pulse.iq_skew = config.get('Readout IQ skew') * np.pi / 180
pulse.iq_ratio = config.get('Readout I/Q ratio')
if config.get('Distribute readout phases'):
pulse.phase = phases[n]
else:
pulse.phase = 0
if config.get('Uniform readout pulse shape'):
pulse.width = config.get('Readout width')
pulse.plateau = config.get('Readout duration')
else:
pulse.width = config.get('Readout width #%d' % m)
pulse.plateau = config.get('Readout duration #%d' % m)
if config.get('Uniform readout amplitude') is True:
pulse.amplitude = config.get('Readout amplitude')
else:
pulse.amplitude = config.get('Readout amplitude #%d' % (n + 1))
pulse.frequency = config.get('Readout frequency #%d' % m)
self.pulses_readout[n] = pulse
# Delays
self.wave_xy_delays = np.zeros(self.n_qubit)
self.wave_z_delays = np.zeros(self.n_qubit)
for n in range(self.n_qubit):
m = n + 1
self.wave_xy_delays[n] = config.get('Qubit %d XY Delay' % m)
self.wave_z_delays[n] = config.get('Qubit %d Z Delay' % m)
if __name__ == '__main__':
pass
|
[
"numpy.kaiser",
"numpy.sum",
"readout.Demodulation",
"numpy.abs",
"numpy.floor",
"numpy.ones",
"numpy.arange",
"numpy.convolve",
"numpy.round",
"predistortion.Predistortion",
"tomography.StateTomography",
"numpy.zeros_like",
"crosstalk.Crosstalk",
"numpy.max",
"tomography.ProcessTomography",
"gates.ReadoutGate",
"numpy.hanning",
"numpy.ones_like",
"numpy.ceil",
"gates.IdentityGate",
"numpy.hamming",
"gates.CustomGate",
"numpy.min",
"predistortion.ExponentialPredistortion",
"numpy.blackman",
"qubits.Qubit",
"numpy.zeros",
"copy.copy",
"numpy.nonzero",
"numpy.diff",
"numpy.array",
"logging.getLogger"
] |
[((232, 265), 'logging.getLogger', 'logging.getLogger', (['"""LabberDriver"""'], {}), "('LabberDriver')\n", (249, 265), False, 'import logging\n'), ((5054, 5084), 'tomography.ProcessTomography', 'tomography.ProcessTomography', ([], {}), '()\n', (5082, 5084), False, 'import tomography\n'), ((5192, 5220), 'tomography.StateTomography', 'tomography.StateTomography', ([], {}), '()\n', (5218, 5220), False, 'import tomography\n'), ((7377, 7400), 'gates.CustomGate', 'gates.CustomGate', (['pulse'], {}), '(pulse)\n', (7393, 7400), False, 'import gates\n'), ((16514, 16536), 'numpy.zeros', 'np.zeros', (['self.n_qubit'], {}), '(self.n_qubit)\n', (16522, 16536), True, 'import numpy as np\n'), ((16566, 16588), 'numpy.zeros', 'np.zeros', (['self.n_qubit'], {}), '(self.n_qubit)\n', (16574, 16588), True, 'import numpy as np\n'), ((16965, 16986), 'crosstalk.Crosstalk', 'crosstalk.Crosstalk', ([], {}), '()\n', (16984, 16986), False, 'import crosstalk\n'), ((17754, 17788), 'readout.Demodulation', 'readout.Demodulation', (['self.n_qubit'], {}), '(self.n_qubit)\n', (17774, 17788), False, 'import readout\n'), ((17817, 17842), 'numpy.array', 'np.array', (['[]'], {'dtype': 'float'}), '([], dtype=float)\n', (17825, 17842), True, 'import numpy as np\n'), ((17869, 17899), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.complex'}), '([], dtype=np.complex)\n', (17877, 17899), True, 'import numpy as np\n'), ((33956, 33991), 'numpy.convolve', 'np.convolve', (['s', 'window'], {'mode': '"""same"""'}), "(s, window, mode='same')\n", (33967, 33991), True, 'import numpy as np\n'), ((34511, 34541), 'numpy.zeros_like', 'np.zeros_like', (['self.readout_iq'], {}), '(self.readout_iq)\n', (34524, 34541), True, 'import numpy as np\n'), ((35119, 35198), 'numpy.min', 'np.min', (['[self.wave_xy_delays[:self.n_qubit], self.wave_z_delays[:self.n_qubit]]'], {}), '([self.wave_xy_delays[:self.n_qubit], self.wave_z_delays[:self.n_qubit]])\n', (35125, 35198), True, 'import numpy as np\n'), ((35334, 35413), 'numpy.max', 'np.max', (['[self.wave_xy_delays[:self.n_qubit], self.wave_z_delays[:self.n_qubit]]'], {}), '([self.wave_xy_delays[:self.n_qubit], self.wave_z_delays[:self.n_qubit]])\n', (35340, 35413), True, 'import numpy as np\n'), ((37333, 37374), 'numpy.zeros', 'np.zeros', (['self.n_pts_readout'], {'dtype': 'float'}), '(self.n_pts_readout, dtype=float)\n', (37341, 37374), True, 'import numpy as np\n'), ((37401, 37447), 'numpy.zeros', 'np.zeros', (['self.n_pts_readout'], {'dtype': 'np.complex'}), '(self.n_pts_readout, dtype=np.complex)\n', (37409, 37447), True, 'import numpy as np\n'), ((54003, 54025), 'numpy.zeros', 'np.zeros', (['self.n_qubit'], {}), '(self.n_qubit)\n', (54011, 54025), True, 'import numpy as np\n'), ((54055, 54077), 'numpy.zeros', 'np.zeros', (['self.n_qubit'], {}), '(self.n_qubit)\n', (54063, 54077), True, 'import numpy as np\n'), ((6211, 6255), 'gates.IdentityGate', 'gates.IdentityGate', ([], {'width': 'self.readout_delay'}), '(width=self.readout_delay)\n', (6229, 6255), False, 'import gates\n'), ((6331, 6350), 'gates.ReadoutGate', 'gates.ReadoutGate', ([], {}), '()\n', (6348, 6350), False, 'import gates\n'), ((16103, 16117), 'qubits.Qubit', 'qubits.Qubit', ([], {}), '()\n', (16115, 16117), False, 'import qubits\n'), ((16207, 16236), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': 'np.complex'}), '(0, dtype=np.complex)\n', (16215, 16236), True, 'import numpy as np\n'), ((16346, 16357), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (16354, 16357), True, 'import numpy as np\n'), ((16415, 16426), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (16423, 16426), True, 'import numpy as np\n'), ((17100, 17130), 'predistortion.Predistortion', 'predistortion.Predistortion', (['n'], {}), '(n)\n', (17127, 17130), False, 'import predistortion\n'), ((17217, 17258), 'predistortion.ExponentialPredistortion', 'predistortion.ExponentialPredistortion', (['n'], {}), '(n)\n', (17255, 17258), False, 'import predistortion\n'), ((19695, 19734), 'numpy.sum', 'np.sum', (['self._wave_xy[:self.n_qubit]', '(0)'], {}), '(self._wave_xy[:self.n_qubit], 0)\n', (19701, 19734), True, 'import numpy as np\n'), ((22141, 22181), 'numpy.max', 'np.max', (['[x.duration for x in step.gates]'], {}), '([x.duration for x in step.gates])\n', (22147, 22181), True, 'import numpy as np\n'), ((32788, 32801), 'numpy.ones', 'np.ones', (['size'], {}), '(size)\n', (32795, 32801), True, 'import numpy as np\n'), ((34637, 34725), 'numpy.min', 'np.min', (['(start + self.readout_trig_duration * self.sample_rate, self.n_pts_readout)'], {}), '((start + self.readout_trig_duration * self.sample_rate, self.\n n_pts_readout))\n', (34643, 34725), True, 'import numpy as np\n'), ((36369, 36407), 'numpy.zeros', 'np.zeros', (['self.n_pts'], {'dtype': 'np.complex'}), '(self.n_pts, dtype=np.complex)\n', (36377, 36407), True, 'import numpy as np\n'), ((36499, 36532), 'numpy.zeros', 'np.zeros', (['self.n_pts'], {'dtype': 'float'}), '(self.n_pts, dtype=float)\n', (36507, 36532), True, 'import numpy as np\n'), ((36566, 36599), 'numpy.zeros', 'np.zeros', (['self.n_pts'], {'dtype': 'float'}), '(self.n_pts, dtype=float)\n', (36574, 36599), True, 'import numpy as np\n'), ((36649, 36670), 'numpy.arange', 'np.arange', (['self.n_pts'], {}), '(self.n_pts)\n', (36658, 36670), True, 'import numpy as np\n'), ((52464, 52577), 'numpy.array', 'np.array', (['[0.884706, 0.2043214, 0.9426104, 0.6947334, 0.8752361, 0.2246747, 0.6503154,\n 0.7305004, 0.1309068]'], {}), '([0.884706, 0.2043214, 0.9426104, 0.6947334, 0.8752361, 0.2246747, \n 0.6503154, 0.7305004, 0.1309068])\n', (52472, 52577), True, 'import numpy as np\n'), ((29150, 29168), 'numpy.ones_like', 'np.ones_like', (['wave'], {}), '(wave)\n', (29162, 29168), True, 'import numpy as np\n'), ((29730, 29743), 'numpy.diff', 'np.diff', (['gate'], {}), '(gate)\n', (29737, 29743), True, 'import numpy as np\n'), ((30227, 30240), 'numpy.diff', 'np.diff', (['gate'], {}), '(gate)\n', (30234, 30240), True, 'import numpy as np\n'), ((34386, 34403), 'numpy.round', 'np.round', (['(t / acc)'], {}), '(t / acc)\n', (34394, 34403), True, 'import numpy as np\n'), ((29654, 29700), 'numpy.round', 'np.round', (['(self.gate_overlap * self.sample_rate)'], {}), '(self.gate_overlap * self.sample_rate)\n', (29662, 29700), True, 'import numpy as np\n'), ((29770, 29797), 'numpy.nonzero', 'np.nonzero', (['(diff_gate > 0.0)'], {}), '(diff_gate > 0.0)\n', (29780, 29797), True, 'import numpy as np\n'), ((29829, 29856), 'numpy.nonzero', 'np.nonzero', (['(diff_gate < 0.0)'], {}), '(diff_gate < 0.0)\n', (29839, 29856), True, 'import numpy as np\n'), ((30267, 30294), 'numpy.nonzero', 'np.nonzero', (['(diff_gate > 0.0)'], {}), '(diff_gate > 0.0)\n', (30277, 30294), True, 'import numpy as np\n'), ((30326, 30353), 'numpy.nonzero', 'np.nonzero', (['(diff_gate < 0.0)'], {}), '(diff_gate < 0.0)\n', (30336, 30353), True, 'import numpy as np\n'), ((30690, 30754), 'numpy.nonzero', 'np.nonzero', (['(len_down < self.minimal_gate_time * self.sample_rate)'], {}), '(len_down < self.minimal_gate_time * self.sample_rate)\n', (30700, 30754), True, 'import numpy as np\n'), ((30957, 31001), 'numpy.round', 'np.round', (['(self.gate_delay * self.sample_rate)'], {}), '(self.gate_delay * self.sample_rate)\n', (30965, 31001), True, 'import numpy as np\n'), ((33033, 33054), 'numpy.blackman', 'np.blackman', (['(size + 2)'], {}), '(size + 2)\n', (33044, 33054), True, 'import numpy as np\n'), ((35726, 35771), 'numpy.max', 'np.max', (['[s.t_end for s in self.sequence_list]'], {}), '([s.t_end for s in self.sequence_list])\n', (35732, 35771), True, 'import numpy as np\n'), ((35936, 35987), 'numpy.max', 'np.max', (['[s.t_end for s in self.sequence_list[0:-1]]'], {}), '([s.t_end for s in self.sequence_list[0:-1]])\n', (35942, 35987), True, 'import numpy as np\n'), ((36138, 36169), 'numpy.ceil', 'np.ceil', (['(end * self.sample_rate)'], {}), '(end * self.sample_rate)\n', (36145, 36169), True, 'import numpy as np\n'), ((37026, 37122), 'numpy.ceil', 'np.ceil', (['(self.sample_rate * (self.sequence_list[-1].t_end - self.sequence_list[-1].\n t_start))'], {}), '(self.sample_rate * (self.sequence_list[-1].t_end - self.\n sequence_list[-1].t_start))\n', (37033, 37122), True, 'import numpy as np\n'), ((28616, 28635), 'copy.copy', 'copy.copy', (['gate_obj'], {}), '(gate_obj)\n', (28625, 28635), False, 'import copy\n'), ((29554, 29566), 'numpy.abs', 'np.abs', (['wave'], {}), '(wave)\n', (29560, 29566), True, 'import numpy as np\n'), ((33129, 33145), 'numpy.hamming', 'np.hamming', (['size'], {}), '(size)\n', (33139, 33145), True, 'import numpy as np\n'), ((31127, 31147), 'numpy.zeros', 'np.zeros', (['(n_shift,)'], {}), '((n_shift,))\n', (31135, 31147), True, 'import numpy as np\n'), ((33196, 33216), 'numpy.hanning', 'np.hanning', (['(size + 2)'], {}), '(size + 2)\n', (33206, 33216), True, 'import numpy as np\n'), ((34559, 34582), 'numpy.abs', 'np.abs', (['self.readout_iq'], {}), '(self.readout_iq)\n', (34565, 34582), True, 'import numpy as np\n'), ((41886, 41920), 'numpy.floor', 'np.floor', (['(start * self.sample_rate)'], {}), '(start * self.sample_rate)\n', (41894, 41920), True, 'import numpy as np\n'), ((41954, 41985), 'numpy.ceil', 'np.ceil', (['(end * self.sample_rate)'], {}), '(end * self.sample_rate)\n', (41961, 41985), True, 'import numpy as np\n'), ((31217, 31237), 'numpy.zeros', 'np.zeros', (['(n_shift,)'], {}), '((n_shift,))\n', (31225, 31237), True, 'import numpy as np\n'), ((33290, 33318), 'numpy.kaiser', 'np.kaiser', (['size', 'kaiser_beta'], {}), '(size, kaiser_beta)\n', (33299, 33318), True, 'import numpy as np\n'), ((40450, 40484), 'numpy.floor', 'np.floor', (['(start * self.sample_rate)'], {}), '(start * self.sample_rate)\n', (40458, 40484), True, 'import numpy as np\n'), ((40555, 40586), 'numpy.ceil', 'np.ceil', (['(end * self.sample_rate)'], {}), '(end * self.sample_rate)\n', (40562, 40586), True, 'import numpy as np\n')]
|
#
# @file plotter.py
# @package openmoc.plotter
# @brief The plotter module provides utility functions to plot data from
# OpenMOCs C++ classes, in particular, the geomery, including Material,
# Cells and flat source regions, and fluxes and pin powers.
# @author <NAME> (<EMAIL>)
# @date March 10, 2013
import os
import sys
import numpy as np
import numpy.random
import matplotlib
# force headless backend, or set 'backend' to 'Agg'
# in your ~/.matplotlib/matplotlibrc
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import openmoc
# For Python 2.X.X
if (sys.version_info[0] == 2):
from log import *
from process import *
# For Python 3.X.X
else:
from openmoc.log import *
from openmoc.process import *
# Force non-interactive mode, or set 'interactive' to False
# in your ~/.matplotlib/matplotlibrc
plt.ioff()
## A static variable for the output directory in which to save plots
subdirectory = "/plots/"
TINY_MOVE = openmoc.TINY_MOVE
##
# @brief Plots the characteristic tracks from an OpenMOC simulation.
# @details This method requires that Tracks have been generated by a
# TrackGenerator object. A user may invoke this function from
# an OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_tracks(track_generator)
# @endcode
#
# @param track_generator the TrackGenerator which has generated Tracks
def plot_tracks(track_generator):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Error checking
if not 'TrackGenerator' in str(type(track_generator)):
py_printf('ERROR', 'Unable to plot Tracks since %s was input rather ' + \
'than a TrackGenerator', str(type(track_generator)))
if not track_generator.containsTracks():
py_printf('ERROR', 'Unable to plot Tracks since the track ' + \
'generator has not yet generated tracks')
py_printf('NORMAL', 'Plotting the tracks...')
# Retrieve data from TrackGenerator
vals_per_track = openmoc.NUM_VALUES_PER_RETRIEVED_TRACK
num_azim = track_generator.getNumAzim()
spacing = track_generator.getTrackSpacing()
num_tracks = track_generator.getNumTracks()
coords = track_generator.retrieveTrackCoords(num_tracks*vals_per_track)
# Convert data to NumPy arrays
coords = np.array(coords)
x = coords[0::vals_per_track/2]
y = coords[1::vals_per_track/2]
# Make figure of line segments for each Track
fig = plt.figure()
for i in range(num_tracks):
plt.plot([x[i*2], x[i*2+1]], [y[i*2], y[i*2+1]], 'b-')
plt.xlim([x.min(), x.max()])
plt.ylim([y.min(), y.max()])
title = 'Tracks for ' + str(num_azim) + ' angles and ' + str(spacing) + \
' cm spacing'
plt.title(title)
filename = directory + 'tracks-' + str(num_azim) + '-angles-' + \
str(spacing) + '-spacing.png'
fig.savefig(filename, bbox_inches='tight')
plt.close(fig)
##
# @brief Plots the characteristic Track segments from an OpenMOC simulation.
# @details This method requires that tracks have been generated by a
# TrackGenerator object. Each segment is colored by the ID of the
# unique flat flat source region it is within. A user may invoke
# this function from an OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_segments(track_generator)
# @endcode
#
# @param track_generator the TrackGenerator which has generated Tracks
def plot_segments(track_generator):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Error checking
if not 'TrackGenerator' in str(type(track_generator)):
py_printf('ERROR', 'Unable to plot Track segments since %s was input ' + \
'rather than a TrackGenerator', str(type(track_generator)))
if not track_generator.containsTracks():
py_printf('ERROR', 'Unable to plot Track segments since the ' + \
'TrackGenerator has not yet generated Tracks.')
py_printf('NORMAL', 'Plotting the track segments...')
# Retrieve data from TrackGenerator
vals_per_segment = openmoc.NUM_VALUES_PER_RETRIEVED_SEGMENT
num_azim = track_generator.getNumAzim()
spacing = track_generator.getTrackSpacing()
num_segments = track_generator.getNumSegments()
num_fsrs = track_generator.getGeometry().getNumFSRs()
coords = track_generator.retrieveSegmentCoords(num_segments*vals_per_segment)
# Convert data to NumPy arrays
coords = np.array(coords)
x = numpy.zeros(num_segments*2)
y = numpy.zeros(num_segments*2)
z = numpy.zeros(num_segments*2)
fsrs = numpy.zeros(num_segments)
for i in range(num_segments):
fsrs[i] = coords[i*vals_per_segment]
x[i*2] = coords[i*vals_per_segment+1]
y[i*2] = coords[i*vals_per_segment+2]
z[i*2] = coords[i*vals_per_segment+3]
x[i*2+1] = coords[i*vals_per_segment+4]
y[i*2+1] = coords[i*vals_per_segment+5]
z[i*2+1] = coords[i*vals_per_segment+6]
# Create array of equally spaced randomized floats as a color map for plots
# Seed the NumPy random number generator to ensure reproducible color maps
numpy.random.seed(1)
color_map = np.linspace(0., 1., num_fsrs, endpoint=False)
numpy.random.shuffle(color_map)
# Make figure of line segments for each track
fig = plt.figure()
for i in range(num_segments):
# Create a color map corresponding to FSR IDs
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0, vmax=max(color_map))
scalarMap = cmx.ScalarMappable(norm=cNorm)
color = scalarMap.to_rgba(color_map[fsrs[i] % num_fsrs])
plt.plot([x[i*2], x[i*2+1]], [y[i*2], y[i*2+1]], c=color)
plt.xlim([x.min(), x.max()])
plt.ylim([y.min(), y.max()])
suptitle = 'Segments for ' + str(num_azim) + ' angles, and ' + str(spacing) + \
' cm spacing'
title = 'z = ' + str(z[0])
plt.suptitle(suptitle)
plt.title(title)
filename = directory + 'segments-' + str(num_azim) + '-angles-' + \
str(spacing) + '-spacing-z-' + str(z[0]) + '.png'
fig.savefig(filename, bbox_inches='tight')
plt.close(fig)
##
# @brief This method takes in a Geometry object and plots a color-coded 2D
# surface plot representing the Materials in the Geometry.
# @details The Geometry object must be initialized with Materials, Cells,
# Universes and lattices before being passed into this method. A user
# may invoke this function from an OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_materials(geometry)
# @endcode
#
# @param geometry a geometry object which has been initialized with Materials,
# Cells, Universes and Lattices
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
# @param zcoord optional the z coordinate (default is 0.0)
def plot_materials(geometry, gridsize=250, xlim=None, ylim=None, zcoord=None):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Error checking
if not 'Geometry' in str(type(geometry)):
py_printf('ERROR', 'Unable to plot the Materials since ' + \
'input was not a geometry class object')
if not is_integer(gridsize):
py_printf('ERROR', 'Unable to plot the Materials since ' + \
'the gridsize %d is not an integer', gridsize)
if gridsize <= 0:
py_printf('ERROR', 'Unable to plot the Materials ' + \
'with a negative gridsize (%d)', gridsize)
# If zcoord was not set, set the zcoord to 0.0
if zcoord is None:
zcoord = 0.0
# Check z-coord
check_zcoord(geometry, zcoord)
py_printf('NORMAL', 'Plotting the materials...')
# Initialize a NumPy array for the surface colors
surface = numpy.zeros((gridsize, gridsize), numpy.int64)
# Retrieve the pixel coordinates
coords = get_pixel_coords(geometry, gridsize, xlim, ylim)
# Find the <aterial IDs for each grid point
for i in range(gridsize):
for j in range(gridsize):
x = coords['x'][i]
y = coords['y'][j]
point = openmoc.LocalCoords(x, y, zcoord)
point.setUniverse(geometry.getRootUniverse())
cell = geometry.findCellContainingCoords(point)
# If we did not find a Cell for this region, use a -1 "bad" number color
if cell is None:
surface[j][i] = -1
else:
surface[j][i] = cell.getFillMaterial().getId()
# Get the number of Materials in the Geometry
materials = geometry.getAllMaterials()
num_materials = len(materials)
# Create array of all Material IDs and randomly (but reproducibly) permute it
material_ids = [material_id for material_id in materials]
numpy.random.seed(1)
numpy.random.shuffle(material_ids)
# Create an array of the colors (array indices) for each value in the surface
colors = np.zeros((gridsize, gridsize))
for material_id in np.unique(surface):
index = material_ids.index(material_id)
indices = np.where(surface == material_id)
colors[indices] = index
# Make Matplotlib color "bad" numbers (ie, NaN, INF) with transparent pixels
cmap = plt.get_cmap('spectral')
cmap.set_bad(alpha=0.0)
# Plot a 2D color map of the Materials
fig = plt.figure()
colors = np.flipud(colors)
plt.imshow(colors, extent=coords['bounds'],
interpolation='nearest', cmap=cmap, vmin=0, vmax=num_materials)
plt.suptitle('Materials')
plt.title('z = ' + str(zcoord))
filename = directory + 'materials-z-' + str(zcoord) + '.png'
fig.savefig(filename, bbox_inches='tight')
plt.close(fig)
##
# @brief This method takes in a Geometry object and plots a color-coded 2D
# surface plot representing the Cells in the Geometry.
# @details The geometry object must be initialized with Materials, Cells,
# Universes and Lattices before being passed into this method. A user
# may invoke this function from an OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_cells(geometry)
# @endcode
#
# @param geometry a Geometry object which has been initialized with Materials,
# Cells, Universes and Lattices
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
# @param zcoord optional the z coordinate (default is 0.0)
def plot_cells(geometry, gridsize=250, xlim=None, ylim=None, zcoord=None):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Error checking
if not 'Geometry' in str(type(geometry)):
py_printf('ERROR', 'Unable to plot the Cells since ' + \
'input was not a Geometry class object')
if not is_integer(gridsize):
py_printf('ERROR', 'Unable to plot the Cells since ' + \
'the gridsize %d is not an integer', gridsize)
if gridsize <= 0:
py_printf('ERROR', 'Unable to plot the Cells ' + \
'with a negative gridsize (%d)', gridsize)
if zcoord is None:
zcoord = 0.0
# Check z-coord
check_zcoord(geometry, zcoord)
py_printf('NORMAL', 'Plotting the cells...')
# Initialize a NumPy array for the surface colors
surface = np.zeros((gridsize, gridsize), numpy.int64)
# Retrieve the pixel coordinates
coords = get_pixel_coords(geometry, gridsize, xlim, ylim)
# Find the Cell IDs for each grid point
for i in range(gridsize):
for j in range(gridsize):
x = coords['x'][i]
y = coords['y'][j]
point = openmoc.LocalCoords(x, y, zcoord)
point.setUniverse(geometry.getRootUniverse())
cell = geometry.findCellContainingCoords(point)
# If we did not find a Cell for this region, use a -1 "bad" number color
if cell is None:
surface[j][i] = -1
else:
surface[j][i] = cell.getId()
# Get the number of Material Cells in the Geometry
material_cells = geometry.getAllMaterialCells()
num_cells = len(material_cells)
# Create array of all Cell IDs and randomly (but reproducibly) permute it
cell_ids = [cell_id for cell_id in material_cells]
numpy.random.seed(1)
numpy.random.shuffle(cell_ids)
# Create an array of the colors (array indices) for each value in the surface
colors = np.zeros((gridsize, gridsize))
for cell_id in np.unique(surface):
index = cell_ids.index(cell_id)
indices = np.where(surface == cell_id)
colors[indices] = index
# Make Matplotlib color "bad" numbers (ie, NaN, INF) with transparent pixels
cmap = plt.get_cmap('spectral')
cmap.set_bad(alpha=0.0)
# Plot a 2D color map of the Cells
fig = plt.figure()
colors = np.flipud(colors)
plt.imshow(colors, extent=coords['bounds'],
interpolation='nearest', cmap=cmap, vmin=0, vmax=num_cells)
plt.suptitle('Cells')
plt.title('z = ' + str(zcoord))
filename = directory + 'cells-z-' + str(zcoord) + '.png'
fig.savefig(filename, bbox_inches='tight')
plt.close(fig)
##
# @brief This method takes in a Geometry object and plots a color-coded 2D
# surface plot representing the flat source regions in the Geometry.
# The FSR centroids are plotted as black circles on top of the FSRs if
# the centroids boolean is set to True.
# @details The Geometry object must be initialized with Materials, Cells,
# Universes and Lattices before being passed into this method. A user
# may invoke this function from an OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_flat_source_regions(geometry)
# @endcode
#
# @param geometry a geometry object which has been initialized with Materials,
# Cells, Universes and Lattices
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
# @param centroids optional boolean to plot the FSR centroids
# @param marker_type optional string to set the centroids marker type
# @param marker_size optional int/float to set the centroids marker size
def plot_flat_source_regions(geometry, gridsize=250, xlim=None, ylim=None, \
centroids=False, marker_type='o', marker_size=2):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Error checking
if not 'Geometry' in str(type(geometry)):
py_printf('ERROR', 'Unable to plot the flat source regions since ' + \
'input was not a geometry class object')
if not is_integer(gridsize):
py_printf('ERROR', 'Unable to plot the flat source regions since ' + \
'the gridsize %d is not an integer', gridsize)
if gridsize <= 0:
py_printf('ERROR', 'Unable to plot the flat source regions ' + \
'with a negative gridsize (%d)', gridsize)
if not isinstance(centroids, bool):
py_printf('ERROR', 'Unable to plot the flat source regions since ' + \
'centroids is not a boolean')
if not isinstance(marker_type, str):
py_printf('ERROR', 'Unable to plot the flat source regions since ' + \
'marker_type is a string')
if marker_type not in matplotlib.markers.MarkerStyle().markers.keys():
py_printf('ERROR', 'Unable to plot the flat source regions since ' + \
'marker_type is not a valid marker (%d)', marker_type)
if not is_float(marker_size) and not is_integer(marker_size):
py_printf('ERROR', 'Unable to plot the flat source regions since ' + \
'marker_size is not an int or float', marker_size)
if marker_size <= 0:
py_printf('ERROR', 'Unable to plot the flat source regions ' + \
'with a negative marker_size (%d)', marker_size)
py_printf('NORMAL', 'Plotting the flat source regions...')
# Get the number of flat source regions
num_fsrs = geometry.getNumFSRs()
if num_fsrs == 0:
py_printf('ERROR', 'Unable to plot the flat source regions ' + \
'since no tracks have been generated.')
# Initialize a NumPy array for the surface colors
surface = numpy.zeros((gridsize, gridsize), dtype=np.int64)
# Retrieve the pixel coordinates
coords = get_pixel_coords(geometry, gridsize, xlim, ylim)
# Get the Geometry's z-coord
zcoord = geometry.getFSRPoint(0).getZ()
# Find the flat source region IDs for each grid point
for i in range(gridsize):
for j in range(gridsize):
x = coords['x'][i]
y = coords['y'][j]
local_coords = openmoc.LocalCoords(x, y, zcoord)
local_coords.setUniverse(geometry.getRootUniverse())
geometry.findCellContainingCoords(local_coords)
fsr_id = geometry.getFSRId(local_coords)
# If we did not find a region for this region, use a -1 "bad" number color
if fsr_id is None:
surface[j][i] = -1
else:
surface[j][i] = fsr_id
del local_coords
# Replace each Cell ID with a random (but reproducible) color ID
# NOTE: This color coding scheme only works for FSRs and CMFD cells and not
# for Materials and Cells. The reason is that FSRs and CMFD cells are by
# definition a sequence of consecutive, monotonically increasing integers.
# Material and Cell IDs however may be any sequence of positive integers.
all_ids = np.arange(num_fsrs, dtype=np.int64)
id_colors = np.arange(num_fsrs, dtype=np.int64)
numpy.random.seed(1)
np.random.shuffle(id_colors)
ids_to_colors = np.arange(num_fsrs, dtype=np.int64)
ids_to_colors[all_ids] = id_colors
colors = ids_to_colors.take(surface)
# Make Matplotlib color "bad" numbers (ie, NaN, INF) with transparent pixels
cmap = plt.get_cmap('spectral')
cmap.set_bad(alpha=0.0)
# Plot a 2D color map of the flat source regions
fig = plt.figure()
colors = np.flipud(colors)
plt.imshow(colors, extent=coords['bounds'],
interpolation='nearest', cmap=cmap, vmin=0, vmax=num_fsrs)
# Plot centroids on top of 2D FSR color map
if centroids:
centroids_x = []
centroids_y = []
for r in range(geometry.getNumFSRs()):
point = geometry.getFSRCentroid(r)
centroids_x.append(point.getX())
centroids_y.append(point.getY())
plt.scatter(centroids_x, centroids_y, color='k', marker=marker_type, \
s=marker_size)
# Matplotlib likes to add a buffer around scatter plots, so we will
# manually set the plot bounds
plt.xlim(min(coords['x']), max(coords['x']))
plt.ylim(min(coords['y']), max(coords['y']))
# Set the plot title and save the figure
plt.suptitle('Flat Source Regions')
plt.title('z = ' + str(zcoord))
filename = directory + 'flat-source-regions-z-' + str(zcoord) + '.png'
fig.savefig(filename, bbox_inches='tight')
plt.close(fig)
##
# @brief This method takes in a Geometry and Cmfd object and plots a
# color-coded 2D surface plot representing the CMFD cells in a geometry.
# @details The Geometry object must be initialized with Materials, Cells,
# Universes and Lattices before being passed into this method.
# Plotting the CMFD cells requires that segments must have been
# created for the geometry and FSR IDs assigned to regions. A user
# may invoke this function from an OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_cmfd_cells(geometry, cmfd)
# @endcode
#
# @param geometry a geometry object which has been initialized with Materials,
# Cells, Universes and Lattices. Segments must have been created or
# extracted from a file.
# @param cmfd a Cmfd object which has been used with the geometry in
# generating segments. The Cmfd object must have the _overlay_mesh
# flag set to true; otherwise, the map linking FSR IDs to CMFD cells
# would not have been created.
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
def plot_cmfd_cells(geometry, cmfd, gridsize=250, xlim=None, ylim=None):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Error checking
if not 'Geometry' in str(type(geometry)):
py_printf('ERROR', 'Unable to plot the CMFD cells since ' + \
'input was not a geometry class object')
if not 'Cmfd' in str(type(cmfd)):
py_printf('ERROR', 'Unable to plot the CMFD cells since ' + \
'input was not a CMFD class object')
if not is_integer(gridsize):
py_printf('ERROR', 'Unable to plot the CMFD cells since ' + \
'the gridsize %s is not an integer', str(gridsize))
if gridsize <= 0:
py_printf('ERROR', 'Unable to plot the CMFD cells ' + \
'with a negative gridsize (%d)', gridsize)
py_printf('NORMAL', 'Plotting the CMFD cells...')
# Initialize a NumPy array for the surface colors
surface = numpy.zeros((gridsize, gridsize), numpy.int64)
# Retrieve the pixel coordinates
coords = get_pixel_coords(geometry, gridsize, xlim, ylim)
# Get the Geometry's z-coord
zcoord = geometry.getFSRPoint(0).getZ()
# Find the CMFD cell ID for each grid point
for i in range(gridsize):
for j in range(gridsize):
x = coords['x'][i]
y = coords['y'][j]
local_coords = openmoc.LocalCoords(x, y, zcoord)
local_coords.setUniverse(geometry.getRootUniverse())
geometry.findCellContainingCoords(local_coords)
fsr_id = geometry.getFSRId(local_coords)
cell_id = cmfd.convertFSRIdToCmfdCell(fsr_id)
# If we did not find a cell for this point, use a -1 "bad" number color
if np.isnan(cell_id):
surface[j][i] = -1
else:
surface[j][i] = cell_id
# Get the number of CMFD cells
num_cmfd_cells = cmfd.getNumCells()
# Replace each Cell ID with a random (but reproducible) color ID
# NOTE: This color coding scheme only works for FSRs and CMFD cells and not
# for Materials and Cells. The reason is that FSRs and CMFD cells are by
# definition a sequence of consecutive, monotonically increasing integers.
# Material and Cell IDs however may be any sequence of positive integers.
all_ids = np.arange(num_cmfd_cells, dtype=np.int64)
id_colors = np.arange(num_cmfd_cells, dtype=np.int64)
numpy.random.seed(1)
np.random.shuffle(id_colors)
ids_to_colors = np.arange(num_cmfd_cells, dtype=np.int64)
ids_to_colors[all_ids] = id_colors
colors = ids_to_colors.take(surface)
# Make Matplotlib color "bad" numbers (ie, NaN, INF) with transparent pixels
cmap = plt.get_cmap('spectral')
cmap.set_bad(alpha=0.0)
# Plot a 2D color map of the CMFD cells
fig = plt.figure()
colors = np.flipud(colors)
plt.imshow(colors, extent=coords['bounds'],
interpolation='nearest', cmap=cmap)
plt.title('CMFD cells')
filename = directory + 'cmfd-cells.png'
fig.savefig(filename, bbox_inches='tight')
##
# @brief This method takes in a Solver object and plots a color-coded 2D
# surface plot representing the flat source region scalar fluxes.
# @details The Solver must have converged the flat source sources prior to
# calling this routine. A user may invoke this function from an
# OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_spatial_fluxes(solver, energy_groups=[1,7])
# @endcode
#
# @param solver a Solver object that has converged the source for the Geometry
# @param energy_groups a Python list of integer energy groups to plot
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
def plot_spatial_fluxes(solver, energy_groups=[1],
gridsize=250, xlim=None, ylim=None):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
if not 'Solver' in str(type(solver)):
py_printf('ERROR', 'Unable to plot the FSR flux since the ' + \
'input did not contain a solver class object')
geometry = solver.getGeometry()
num_groups = geometry.getNumEnergyGroups()
if isinstance(energy_groups, (list, tuple, np.ndarray)):
for group in energy_groups:
if not is_integer(group):
py_printf('ERROR', 'Unable to plot the FSR flux since the ' + \
'energy_groups contains %s which is not a number', str(group))
elif group <= 0:
py_printf('ERROR', 'Unable to plot the FSR flux since the ' + \
'energy_groups contains %d which is less than the ' + \
'index for all energy groups', group)
elif group > num_groups:
py_printf('ERROR', 'Unable to plot the FSR flux since the ' + \
'energy_groups contains %d which is greater than ' + \
'the index for all energy groups', group)
else:
py_printf('ERROR', 'Unable to plot the FSR flux since the ' + \
'energy_groups is not a Python tuple/list or NumPy array')
if not is_integer(gridsize):
py_printf('ERROR', 'Unable to plot the FSR flux since the ' + \
'gridsize %s is not an integer', str(gridsize))
if gridsize <= 0:
py_printf('ERROR', 'Unable to plot the FSR flux with a ' + \
'negative gridsize (%d)', gridsize)
py_printf('NORMAL', 'Plotting the FSR scalar fluxes...')
# Initialize a numpy array for the groupwise scalar fluxes
fluxes = numpy.zeros((len(energy_groups), gridsize, gridsize))
# Retrieve the pixel coordinates
coords = get_pixel_coords(geometry, gridsize, xlim, ylim)
# Get the Geometry's z-coord
zcoord = geometry.getFSRPoint(0).getZ()
for i in range(gridsize):
for j in range(gridsize):
# Find the flat source region IDs for each grid point
x = coords['x'][i]
y = coords['y'][j]
point = openmoc.LocalCoords(x, y, zcoord)
point.setUniverse(geometry.getRootUniverse())
geometry.findCellContainingCoords(point)
fsr_id = geometry.getFSRId(point)
# If we did not find a region for this region, use a -1 "bad" number color
if np.isnan(fsr_id):
fluxes[:,j,i] = -1
# Get the scalar flux for each energy group in this FSR
else:
for index, group in enumerate(energy_groups):
fluxes[index,j,i] = solver.getFlux(fsr_id, group)
# Loop over all energy group and create a plot
for index, group in enumerate(energy_groups):
# Plot a 2D color map of the flat source regions
fig = plt.figure()
plt.imshow(np.flipud(fluxes[index,:,:]), extent=coords['bounds'])
plt.colorbar()
plt.suptitle('FSR Scalar Flux (Group {0})'.format(group))
plt.title('z = ' + str(zcoord))
filename = directory + 'fsr-flux-group-' + str(group) + '-z-' + \
str(zcoord) + '.png'
fig.savefig(filename, bbox_inches='tight')
plt.close(fig)
##
# @brief This method takes in a Solver object and plots the scalar
# flux vs. energy for one or more flat source regions.
# @details The Solver must have converged the flat source sources prior to
# calling this routine. The routine will generate a step plot of the
# flat flux across each energy group.
#
# An optional parameter for the energy group bounds may be input.
# The group bounds should be input in increasing order of energy.
# If group bounds are not specified, the routine will use equal
# width steps for each energy group.
#
# A user may invoke this function from an OpenMOC Python file
# as follows:
#
# @code
# openmoc.plotter.plot_energy_fluxes(solver, fsrs=[1,5,20],
# group_bounds=[0., 0.625, 2e7])
# @endcode
#
# @param solver a Solver object that has converged the source for the Geometry
# @param fsrs the flat source region IDs of interest
# @param group_bounds an optional Python list of the energy group bounds (eV)
# @param norm a boolean indicating whether to normalize the flux
# @param loglog boolean indicating whether to plot use a log-log scale
def plot_energy_fluxes(solver, fsrs, group_bounds=None, norm=True, loglog=True):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
if not 'Solver' in str(type(solver)):
py_printf('ERROR', 'Unable to plot the flux vs. energy ' + \
'since input did not contain a Solver class object')
geometry = solver.getGeometry()
num_fsrs = geometry.getNumFSRs()
num_groups = geometry.getNumEnergyGroups()
if isinstance(fsrs, (tuple, list, np.ndarray)):
for fsr in fsrs:
if not is_integer(fsr):
py_printf('ERROR', 'Unable to plot the flux vs. energy since ' + \
'the fsrs contains %s which is not an int', str(fsr))
elif fsr < 0:
py_printf('ERROR', 'Unable to plot the flux vs. energy since ' + \
'the fsrs contains %d which is less than zero', fsr)
elif fsr >= num_fsrs:
py_printf('ERROR', 'Unable to plot the flux vs. energy since ' + \
'the fsrs contains %d which is greater than the ' + \
'total number of FSRs %d', fsr, num_fsrs)
else:
py_printf('ERROR', 'Unable to plot the flux vs. energy since ' + \
'the fsrs is not a Python tuple, list or NumPy array')
if isinstance(group_bounds, (tuple, list, np.ndarray)):
if not all(low < up for low, up in zip(group_bounds, group_bounds[1:])):
py_printf('ERROR', 'Unable to plot the flux vs. energy since the ' + \
'energy group bounds are not monotonically increasing')
elif len(group_bounds) != geometry.getNumEnergyGroups()+1:
py_printf('ERROR', 'Unable to plot the flux vs. energy since the ' + \
'group bounds does not correspond to %d groups', num_groups)
for bound in group_bounds:
if not is_integer(bound) and not is_float(bound):
py_printf('ERROR', 'Unable to plot the flux vs. energy since the ' + \
'group bounds contains %s which is not a number', str(fsr))
elif bound < 0:
py_printf('ERROR', 'Unable to plot the flux vs. energy since the ' + \
'group bounds contains %f which is less than zero', bound)
elif group_bounds is None:
group_bounds = np.arange(num_groups+1, dtype=np.int)
loglog = False
else:
py_printf('ERROR', 'Unable to plot the flux vs. energy since ' + \
'the group bounds is not a Python tuple, list or NumPy array')
py_printf('NORMAL', 'Plotting the scalar fluxes vs. energy...')
# Compute difference in energy bounds for each group
group_deltas = np.ediff1d(group_bounds)
group_bounds = np.flipud(group_bounds)
group_deltas = np.flipud(group_deltas)
# Iterate over all flat source regions
for fsr in fsrs:
# Allocate memory for an array of this FSR's fluxes
fluxes = np.zeros(num_groups, dtype=np.float)
# Extract the flux in each energy group
for group in range(num_groups):
fluxes[group] = solver.getFlux(fsr, group+1)
# Normalize fluxes to the total integrated flux
if norm:
fluxes /= np.sum(group_deltas * fluxes)
# Initialize a separate plot for this FSR's fluxes
fig = plt.figure()
# Draw horizontal/vertical lines on the plot for each energy group
for group in range(num_groups):
# Horizontal line
if loglog:
plt.loglog(group_bounds[group:group+2], [fluxes[group]]*2,
linewidth=3, c='b', label='openmoc', linestyle='-')
else:
plt.plot(group_bounds[group:group+2], [fluxes[group]]*2,
linewidth=3, c='b', label='openmoc', linestyle='-')
# Vertical lines
if group < num_groups - 1:
if loglog:
plt.loglog([group_bounds[group+1]]*2, fluxes[group:group+2],
c='b', linestyle='--')
else:
plt.plot([group_bounds[group+1]]*2, fluxes[group:group+2],
c='b', linestyle='--')
plt.xlabel('Energy')
plt.ylabel('Flux')
plt.xlim((min(group_bounds), max(group_bounds)))
plt.grid()
plt.title('FSR {0} Flux ({1} groups)'.format(fsr, num_groups))
filename = directory + 'flux-fsr-' + str(fsr) + '.png'
plt.savefig(filename, bbox_inches='tight')
plt.close(fig)
##
# @brief This method plots a color-coded 2D surface plot representing the
# FSR fission rates in the Geometry.
# @details The Solver must have converged the flat source sources prior to
# calling this routine. A user may invoke this function from an
# OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_fission_rates(solver)
# @endcode
#
# @param solver a Solver object that has converged the source for the Geometry
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
def plot_fission_rates(solver, gridsize=250, xlim=None, ylim=None):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
if not 'Solver' in str(type(solver)):
py_printf('ERROR', 'Unable to plot the fission rates ' + \
'since input did not contain a solver class object')
if not is_integer(gridsize):
py_printf('ERROR', 'Unable to plot the fission rates ' + \
'since the gridsize %s is not an integer', str(gridsize))
if gridsize <= 0:
py_printf('ERROR', 'Unable to plot the fission rates ' + \
'with a negative gridsize (%d)', gridsize)
py_printf('NORMAL', 'Plotting the flat source region fission rates...')
# Get geometry
geometry = solver.getGeometry()
# Compute the volume-weighted fission rates for each FSR
fission_rates = solver.computeFSRFissionRates(geometry.getNumFSRs())
# Initialize a numpy array of fission rates
surface = numpy.zeros((gridsize, gridsize))
# Retrieve the pixel coordinates
coords = get_pixel_coords(geometry, gridsize, xlim, ylim)
# Get the Geometry's z-coord
zcoord = geometry.getFSRPoint(0).getZ()
for i in range(gridsize):
for j in range(gridsize):
# Find the flat source region IDs for each grid point
x = coords['y'][i]
y = coords['x'][j]
point = openmoc.LocalCoords(x, y, zcoord)
point.setUniverse(geometry.getRootUniverse())
geometry.findCellContainingCoords(point)
fsr_id = geometry.getFSRId(point)
# If we did not find a region for this region, use a -1 "bad" number color
if np.isnan(fsr_id):
surface[j][i] = -1
# Get the fission rate in this FSR
else:
surface[j][i] = fission_rates[fsr_id]
# Plot a 2D color map of the flat source regions fission rates
fig = plt.figure()
plt.imshow(np.flipud(surface), extent=coords['bounds'])
plt.colorbar()
plt.suptitle('Flat Source Region Fission Rates')
plt.title('z = ' + str(zcoord))
filename = directory + 'fission-rates-z-' + str(zcoord) + '.png'
fig.savefig(filename, bbox_inches='tight')
##
# @brief This method plots a color-coded 2D surface plot representing the
# FSR scalar fluxes for various eigenmodes from an IRAMSolver.
# @details The IRAMSolver must have computed the eigenmodes prior to
# calling this routine. A user may invoke this function from
# an OpenMOC Python file as follows:
#
# @code
# openmoc.plotter.plot_eigenmode_fluxes(iramsolver, energy_groups=[1,7])
# @endcode
#
# @param iramsolver an IRAMSolver object that has computed the eigenmodes
# @param eigenmodes a Python list of integer eigenmodes to plot
# @param energy_groups a Python list of integer energy groups to plot
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
def plot_eigenmode_fluxes(iramsolver, eigenmodes=[], energy_groups=[1],
gridsize=250, xlim=None, ylim=None):
global subdirectory
directory = openmoc.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
if not 'IRAMSolver' in str(type(iramsolver)):
py_printf('ERROR', 'Unable to plot the eigenmode fluxes ' + \
'since input did not contain an IRAMSolver class object')
if isinstance(eigenmodes, (list, tuple, np.ndarray)):
# If eigenmodes parameters is empty list, plot all eigenmodes
if len(eigenmodes) == 0:
eigenmodes = np.arange(1, iramsolver._num_modes+1)
for mode in eigenmodes:
if not is_integer(mode):
py_printf('ERROR', 'Unable to plot the eigenmode flux since the ' + \
'eigenmodes contains %s which is not a number', str(mode))
elif mode <= 0:
py_printf('ERROR', 'Unable to plot the eigenmode flux since the ' + \
'eigenmodes contains %d which is negative', mode)
elif mode > iramsolver._num_modes:
py_printf('ERROR', 'Unable to plot the eigenmode flux since the ' + \
'eigenmodes contains %d but the IRAMSolver only ' + \
'computed %d modes', mode)
else:
py_printf('ERROR', 'Unable to plot the eigenmode flux since the ' + \
'eigenmodes is not a Python tuple/list or NumPy array')
py_printf('NORMAL', 'Plotting the eigenmode fluxes...')
# Extract the MOC Solver from the IRAMSolver
moc_solver = iramsolver._moc_solver
# Loop over each eigenmode
for mode in eigenmodes:
# Extract the eigenvector for this eigenmode from the IRAMSolver
eigenvec = iramsolver._eigenvectors[:,mode-1]
# Convert it into a form that SWIG will be happy with
eigenvec = np.squeeze(np.ascontiguousarray(eigenvec))
eigenvec = np.real(eigenvec).astype(iramsolver._precision)
# Ensure the primary eigenvector is positive
if(mode-1 == 0):
eigenvec = np.abs(eigenvec)
# Insert eigenvector into MOC Solver object
moc_solver.setFluxes(eigenvec)
# Set subdirectory folder for this eigenmode
num_digits = len(str(max(eigenmodes)))
subdirectory = '/plots/eig-{0}-flux/'.format(str(mode).zfill(num_digits))
# Plot this eigenmode's spatial fluxes
plot_spatial_fluxes(moc_solver, energy_groups, gridsize, xlim, ylim)
# Reset global subdirectory
subdirectory = '/plots/'
##
# @brief This is a helper method to define coordinates for a plotting window.
# @details This routine builds a coordinate surface map for the plotting
# window defined for by the user. If no window was defined, then
# this routine uses the outer bounding box around the geometry as
# the plotting window.
# @param geometry a Geometry object which has been initialized with Materials,
# Cells, Universes and Lattices
# @param gridsize an optional number of grid cells for the plot
# @param xlim optional list/tuple of the minimim/maximum x-coordinates
# @param ylim optional list/tuple of the minimim/maximum y-coordinates
# @return a dictionary with the plotting window map and bounding box
def get_pixel_coords(geometry, gridsize, xlim, ylim):
# initialize variables to be returned
bounds = [geometry.getMinX() + TINY_MOVE, geometry.getMaxX() - TINY_MOVE,
geometry.getMinY() + TINY_MOVE, geometry.getMaxY() - TINY_MOVE]
xcoords = None
ycoords = None
coords = dict()
if not xlim is None:
bounds[0] = xlim[0]
bounds[1] = xlim[1]
if not ylim is None:
bounds[2] = ylim[0]
bounds[3] = ylim[1]
xcoords = np.linspace(bounds[0], bounds[1], gridsize)
ycoords = np.linspace(bounds[2], bounds[3], gridsize)
# add attributes to coords dictionary
coords['x'] = xcoords
coords['y'] = ycoords
coords['bounds'] = bounds
return coords
##
# @brief This is a helper method to check that z-coord falls within the bounds
# of the geometry.
# @param geometry a Geometry object which has been initialized with Materials,
# Cells, Universes and Lattices
# @param zcoord the z coordinate
def check_zcoord(geometry, zcoord):
if not is_float(zcoord):
py_printf('ERROR', 'Unable to produce plot since ' + \
'the z-coord %d is not a float', zcoord)
elif zcoord < geometry.getMinZ() or zcoord > geometry.getMaxZ():
py_printf('ERROR', 'Unable to produce plot since ' + \
'the z-coord %d is outside the geometry z-bounds (%d, %d)', \
geometry.getMinZ(), geometry.getMaxZ())
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.loglog",
"numpy.sum",
"numpy.abs",
"matplotlib.pyplot.suptitle",
"numpy.isnan",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.unique",
"openmoc.get_output_directory",
"matplotlib.pyplot.close",
"matplotlib.pyplot.imshow",
"matplotlib.cm.ScalarMappable",
"os.path.exists",
"matplotlib.pyplot.colorbar",
"numpy.linspace",
"numpy.real",
"numpy.random.shuffle",
"matplotlib.markers.MarkerStyle",
"matplotlib.pyplot.get_cmap",
"numpy.flipud",
"matplotlib.use",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"os.makedirs",
"matplotlib.pyplot.ioff",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"numpy.zeros",
"numpy.where",
"numpy.array",
"matplotlib.pyplot.xlabel",
"numpy.ascontiguousarray",
"openmoc.LocalCoords",
"matplotlib.pyplot.savefig",
"numpy.ediff1d"
] |
[((486, 507), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (500, 507), False, 'import matplotlib\n'), ((898, 908), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (906, 908), True, 'import matplotlib.pyplot as plt\n'), ((2455, 2471), 'numpy.array', 'np.array', (['coords'], {}), '(coords)\n', (2463, 2471), True, 'import numpy as np\n'), ((2597, 2609), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2607, 2609), True, 'import matplotlib.pyplot as plt\n'), ((2868, 2884), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2877, 2884), True, 'import matplotlib.pyplot as plt\n'), ((3038, 3052), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (3047, 3052), True, 'import matplotlib.pyplot as plt\n'), ((4676, 4692), 'numpy.array', 'np.array', (['coords'], {}), '(coords)\n', (4684, 4692), True, 'import numpy as np\n'), ((5355, 5402), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'num_fsrs'], {'endpoint': '(False)'}), '(0.0, 1.0, num_fsrs, endpoint=False)\n', (5366, 5402), True, 'import numpy as np\n'), ((5492, 5504), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5502, 5504), True, 'import matplotlib.pyplot as plt\n'), ((6053, 6075), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['suptitle'], {}), '(suptitle)\n', (6065, 6075), True, 'import matplotlib.pyplot as plt\n'), ((6078, 6094), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (6087, 6094), True, 'import matplotlib.pyplot as plt\n'), ((6270, 6284), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (6279, 6284), True, 'import matplotlib.pyplot as plt\n'), ((9196, 9226), 'numpy.zeros', 'np.zeros', (['(gridsize, gridsize)'], {}), '((gridsize, gridsize))\n', (9204, 9226), True, 'import numpy as np\n'), ((9249, 9267), 'numpy.unique', 'np.unique', (['surface'], {}), '(surface)\n', (9258, 9267), True, 'import numpy as np\n'), ((9477, 9501), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""spectral"""'], {}), "('spectral')\n", (9489, 9501), True, 'import matplotlib.pyplot as plt\n'), ((9578, 9590), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9588, 9590), True, 'import matplotlib.pyplot as plt\n'), ((9602, 9619), 'numpy.flipud', 'np.flipud', (['colors'], {}), '(colors)\n', (9611, 9619), True, 'import numpy as np\n'), ((9622, 9734), 'matplotlib.pyplot.imshow', 'plt.imshow', (['colors'], {'extent': "coords['bounds']", 'interpolation': '"""nearest"""', 'cmap': 'cmap', 'vmin': '(0)', 'vmax': 'num_materials'}), "(colors, extent=coords['bounds'], interpolation='nearest', cmap=\n cmap, vmin=0, vmax=num_materials)\n", (9632, 9734), True, 'import matplotlib.pyplot as plt\n'), ((9745, 9770), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Materials"""'], {}), "('Materials')\n", (9757, 9770), True, 'import matplotlib.pyplot as plt\n'), ((9915, 9929), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (9924, 9929), True, 'import matplotlib.pyplot as plt\n'), ((11688, 11731), 'numpy.zeros', 'np.zeros', (['(gridsize, gridsize)', 'numpy.int64'], {}), '((gridsize, gridsize), numpy.int64)\n', (11696, 11731), True, 'import numpy as np\n'), ((12730, 12760), 'numpy.zeros', 'np.zeros', (['(gridsize, gridsize)'], {}), '((gridsize, gridsize))\n', (12738, 12760), True, 'import numpy as np\n'), ((12779, 12797), 'numpy.unique', 'np.unique', (['surface'], {}), '(surface)\n', (12788, 12797), True, 'import numpy as np\n'), ((12995, 13019), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""spectral"""'], {}), "('spectral')\n", (13007, 13019), True, 'import matplotlib.pyplot as plt\n'), ((13092, 13104), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13102, 13104), True, 'import matplotlib.pyplot as plt\n'), ((13116, 13133), 'numpy.flipud', 'np.flipud', (['colors'], {}), '(colors)\n', (13125, 13133), True, 'import numpy as np\n'), ((13136, 13244), 'matplotlib.pyplot.imshow', 'plt.imshow', (['colors'], {'extent': "coords['bounds']", 'interpolation': '"""nearest"""', 'cmap': 'cmap', 'vmin': '(0)', 'vmax': 'num_cells'}), "(colors, extent=coords['bounds'], interpolation='nearest', cmap=\n cmap, vmin=0, vmax=num_cells)\n", (13146, 13244), True, 'import matplotlib.pyplot as plt\n'), ((13255, 13276), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Cells"""'], {}), "('Cells')\n", (13267, 13276), True, 'import matplotlib.pyplot as plt\n'), ((13418, 13432), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (13427, 13432), True, 'import matplotlib.pyplot as plt\n'), ((17840, 17875), 'numpy.arange', 'np.arange', (['num_fsrs'], {'dtype': 'np.int64'}), '(num_fsrs, dtype=np.int64)\n', (17849, 17875), True, 'import numpy as np\n'), ((17891, 17926), 'numpy.arange', 'np.arange', (['num_fsrs'], {'dtype': 'np.int64'}), '(num_fsrs, dtype=np.int64)\n', (17900, 17926), True, 'import numpy as np\n'), ((17952, 17980), 'numpy.random.shuffle', 'np.random.shuffle', (['id_colors'], {}), '(id_colors)\n', (17969, 17980), True, 'import numpy as np\n'), ((18000, 18035), 'numpy.arange', 'np.arange', (['num_fsrs'], {'dtype': 'np.int64'}), '(num_fsrs, dtype=np.int64)\n', (18009, 18035), True, 'import numpy as np\n'), ((18202, 18226), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""spectral"""'], {}), "('spectral')\n", (18214, 18226), True, 'import matplotlib.pyplot as plt\n'), ((18313, 18325), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (18323, 18325), True, 'import matplotlib.pyplot as plt\n'), ((18337, 18354), 'numpy.flipud', 'np.flipud', (['colors'], {}), '(colors)\n', (18346, 18354), True, 'import numpy as np\n'), ((18357, 18464), 'matplotlib.pyplot.imshow', 'plt.imshow', (['colors'], {'extent': "coords['bounds']", 'interpolation': '"""nearest"""', 'cmap': 'cmap', 'vmin': '(0)', 'vmax': 'num_fsrs'}), "(colors, extent=coords['bounds'], interpolation='nearest', cmap=\n cmap, vmin=0, vmax=num_fsrs)\n", (18367, 18464), True, 'import matplotlib.pyplot as plt\n'), ((19099, 19134), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Flat Source Regions"""'], {}), "('Flat Source Regions')\n", (19111, 19134), True, 'import matplotlib.pyplot as plt\n'), ((19289, 19303), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (19298, 19303), True, 'import matplotlib.pyplot as plt\n'), ((22857, 22898), 'numpy.arange', 'np.arange', (['num_cmfd_cells'], {'dtype': 'np.int64'}), '(num_cmfd_cells, dtype=np.int64)\n', (22866, 22898), True, 'import numpy as np\n'), ((22914, 22955), 'numpy.arange', 'np.arange', (['num_cmfd_cells'], {'dtype': 'np.int64'}), '(num_cmfd_cells, dtype=np.int64)\n', (22923, 22955), True, 'import numpy as np\n'), ((22981, 23009), 'numpy.random.shuffle', 'np.random.shuffle', (['id_colors'], {}), '(id_colors)\n', (22998, 23009), True, 'import numpy as np\n'), ((23029, 23070), 'numpy.arange', 'np.arange', (['num_cmfd_cells'], {'dtype': 'np.int64'}), '(num_cmfd_cells, dtype=np.int64)\n', (23038, 23070), True, 'import numpy as np\n'), ((23237, 23261), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""spectral"""'], {}), "('spectral')\n", (23249, 23261), True, 'import matplotlib.pyplot as plt\n'), ((23339, 23351), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (23349, 23351), True, 'import matplotlib.pyplot as plt\n'), ((23363, 23380), 'numpy.flipud', 'np.flipud', (['colors'], {}), '(colors)\n', (23372, 23380), True, 'import numpy as np\n'), ((23383, 23462), 'matplotlib.pyplot.imshow', 'plt.imshow', (['colors'], {'extent': "coords['bounds']", 'interpolation': '"""nearest"""', 'cmap': 'cmap'}), "(colors, extent=coords['bounds'], interpolation='nearest', cmap=cmap)\n", (23393, 23462), True, 'import matplotlib.pyplot as plt\n'), ((23478, 23501), 'matplotlib.pyplot.title', 'plt.title', (['"""CMFD cells"""'], {}), "('CMFD cells')\n", (23487, 23501), True, 'import matplotlib.pyplot as plt\n'), ((31604, 31628), 'numpy.ediff1d', 'np.ediff1d', (['group_bounds'], {}), '(group_bounds)\n', (31614, 31628), True, 'import numpy as np\n'), ((31646, 31669), 'numpy.flipud', 'np.flipud', (['group_bounds'], {}), '(group_bounds)\n', (31655, 31669), True, 'import numpy as np\n'), ((31687, 31710), 'numpy.flipud', 'np.flipud', (['group_deltas'], {}), '(group_deltas)\n', (31696, 31710), True, 'import numpy as np\n'), ((35871, 35883), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (35881, 35883), True, 'import matplotlib.pyplot as plt\n'), ((35944, 35958), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (35956, 35958), True, 'import matplotlib.pyplot as plt\n'), ((35961, 36009), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Flat Source Region Fission Rates"""'], {}), "('Flat Source Region Fission Rates')\n", (35973, 36009), True, 'import matplotlib.pyplot as plt\n'), ((40738, 40781), 'numpy.linspace', 'np.linspace', (['bounds[0]', 'bounds[1]', 'gridsize'], {}), '(bounds[0], bounds[1], gridsize)\n', (40749, 40781), True, 'import numpy as np\n'), ((40794, 40837), 'numpy.linspace', 'np.linspace', (['bounds[2]', 'bounds[3]', 'gridsize'], {}), '(bounds[2], bounds[3], gridsize)\n', (40805, 40837), True, 'import numpy as np\n'), ((1516, 1546), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (1544, 1546), False, 'import openmoc\n'), ((1612, 1637), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (1626, 1637), False, 'import os\n'), ((1643, 1665), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (1654, 1665), False, 'import os\n'), ((2644, 2710), 'matplotlib.pyplot.plot', 'plt.plot', (['[x[i * 2], x[i * 2 + 1]]', '[y[i * 2], y[i * 2 + 1]]', '"""b-"""'], {}), "([x[i * 2], x[i * 2 + 1]], [y[i * 2], y[i * 2 + 1]], 'b-')\n", (2652, 2710), True, 'import matplotlib.pyplot as plt\n'), ((3643, 3673), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (3671, 3673), False, 'import openmoc\n'), ((3739, 3764), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (3753, 3764), False, 'import os\n'), ((3770, 3792), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (3781, 3792), False, 'import os\n'), ((5604, 5623), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""jet"""'], {}), "('jet')\n", (5616, 5623), True, 'import matplotlib.pyplot as plt\n'), ((5699, 5729), 'matplotlib.cm.ScalarMappable', 'cmx.ScalarMappable', ([], {'norm': 'cNorm'}), '(norm=cNorm)\n', (5717, 5729), True, 'import matplotlib.cm as cmx\n'), ((5795, 5864), 'matplotlib.pyplot.plot', 'plt.plot', (['[x[i * 2], x[i * 2 + 1]]', '[y[i * 2], y[i * 2 + 1]]'], {'c': 'color'}), '([x[i * 2], x[i * 2 + 1]], [y[i * 2], y[i * 2 + 1]], c=color)\n', (5803, 5864), True, 'import matplotlib.pyplot as plt\n'), ((7235, 7265), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (7263, 7265), False, 'import openmoc\n'), ((7331, 7356), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (7345, 7356), False, 'import os\n'), ((7362, 7384), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (7373, 7384), False, 'import os\n'), ((9327, 9359), 'numpy.where', 'np.where', (['(surface == material_id)'], {}), '(surface == material_id)\n', (9335, 9359), True, 'import numpy as np\n'), ((10867, 10897), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (10895, 10897), False, 'import openmoc\n'), ((10963, 10988), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (10977, 10988), False, 'import os\n'), ((10994, 11016), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (11005, 11016), False, 'import os\n'), ((12849, 12877), 'numpy.where', 'np.where', (['(surface == cell_id)'], {}), '(surface == cell_id)\n', (12857, 12877), True, 'import numpy as np\n'), ((14751, 14781), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (14779, 14781), False, 'import openmoc\n'), ((14847, 14872), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (14861, 14872), False, 'import os\n'), ((14878, 14900), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (14889, 14900), False, 'import os\n'), ((18745, 18833), 'matplotlib.pyplot.scatter', 'plt.scatter', (['centroids_x', 'centroids_y'], {'color': '"""k"""', 'marker': 'marker_type', 's': 'marker_size'}), "(centroids_x, centroids_y, color='k', marker=marker_type, s=\n marker_size)\n", (18756, 18833), True, 'import matplotlib.pyplot as plt\n'), ((20672, 20702), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (20700, 20702), False, 'import openmoc\n'), ((20768, 20793), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (20782, 20793), False, 'import os\n'), ((20799, 20821), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (20810, 20821), False, 'import os\n'), ((24535, 24565), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (24563, 24565), False, 'import openmoc\n'), ((24631, 24656), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (24645, 24656), False, 'import os\n'), ((24662, 24684), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (24673, 24684), False, 'import os\n'), ((27325, 27337), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (27335, 27337), True, 'import matplotlib.pyplot as plt\n'), ((27412, 27426), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (27424, 27426), True, 'import matplotlib.pyplot as plt\n'), ((27682, 27696), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (27691, 27696), True, 'import matplotlib.pyplot as plt\n'), ((29034, 29064), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (29062, 29064), False, 'import openmoc\n'), ((29130, 29155), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (29144, 29155), False, 'import os\n'), ((29161, 29183), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (29172, 29183), False, 'import os\n'), ((31843, 31879), 'numpy.zeros', 'np.zeros', (['num_groups'], {'dtype': 'np.float'}), '(num_groups, dtype=np.float)\n', (31851, 31879), True, 'import numpy as np\n'), ((32192, 32204), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (32202, 32204), True, 'import matplotlib.pyplot as plt\n'), ((32968, 32988), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Energy"""'], {}), "('Energy')\n", (32978, 32988), True, 'import matplotlib.pyplot as plt\n'), ((32993, 33011), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flux"""'], {}), "('Flux')\n", (33003, 33011), True, 'import matplotlib.pyplot as plt\n'), ((33069, 33079), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (33077, 33079), True, 'import matplotlib.pyplot as plt\n'), ((33210, 33252), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""'}), "(filename, bbox_inches='tight')\n", (33221, 33252), True, 'import matplotlib.pyplot as plt\n'), ((33257, 33271), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (33266, 33271), True, 'import matplotlib.pyplot as plt\n'), ((34055, 34085), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (34083, 34085), False, 'import openmoc\n'), ((34151, 34176), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (34165, 34176), False, 'import os\n'), ((34182, 34204), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (34193, 34204), False, 'import os\n'), ((35897, 35915), 'numpy.flipud', 'np.flipud', (['surface'], {}), '(surface)\n', (35906, 35915), True, 'import numpy as np\n'), ((37184, 37214), 'openmoc.get_output_directory', 'openmoc.get_output_directory', ([], {}), '()\n', (37212, 37214), False, 'import openmoc\n'), ((37280, 37305), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (37294, 37305), False, 'import os\n'), ((37311, 37333), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (37322, 37333), False, 'import os\n'), ((8443, 8476), 'openmoc.LocalCoords', 'openmoc.LocalCoords', (['x', 'y', 'zcoord'], {}), '(x, y, zcoord)\n', (8462, 8476), False, 'import openmoc\n'), ((11995, 12028), 'openmoc.LocalCoords', 'openmoc.LocalCoords', (['x', 'y', 'zcoord'], {}), '(x, y, zcoord)\n', (12014, 12028), False, 'import openmoc\n'), ((17060, 17093), 'openmoc.LocalCoords', 'openmoc.LocalCoords', (['x', 'y', 'zcoord'], {}), '(x, y, zcoord)\n', (17079, 17093), False, 'import openmoc\n'), ((21976, 22009), 'openmoc.LocalCoords', 'openmoc.LocalCoords', (['x', 'y', 'zcoord'], {}), '(x, y, zcoord)\n', (21995, 22009), False, 'import openmoc\n'), ((22310, 22327), 'numpy.isnan', 'np.isnan', (['cell_id'], {}), '(cell_id)\n', (22318, 22327), True, 'import numpy as np\n'), ((26665, 26698), 'openmoc.LocalCoords', 'openmoc.LocalCoords', (['x', 'y', 'zcoord'], {}), '(x, y, zcoord)\n', (26684, 26698), False, 'import openmoc\n'), ((26929, 26945), 'numpy.isnan', 'np.isnan', (['fsr_id'], {}), '(fsr_id)\n', (26937, 26945), True, 'import numpy as np\n'), ((27353, 27383), 'numpy.flipud', 'np.flipud', (['fluxes[index, :, :]'], {}), '(fluxes[index, :, :])\n', (27362, 27383), True, 'import numpy as np\n'), ((31250, 31289), 'numpy.arange', 'np.arange', (['(num_groups + 1)'], {'dtype': 'np.int'}), '(num_groups + 1, dtype=np.int)\n', (31259, 31289), True, 'import numpy as np\n'), ((32096, 32125), 'numpy.sum', 'np.sum', (['(group_deltas * fluxes)'], {}), '(group_deltas * fluxes)\n', (32102, 32125), True, 'import numpy as np\n'), ((35390, 35423), 'openmoc.LocalCoords', 'openmoc.LocalCoords', (['x', 'y', 'zcoord'], {}), '(x, y, zcoord)\n', (35409, 35423), False, 'import openmoc\n'), ((35654, 35670), 'numpy.isnan', 'np.isnan', (['fsr_id'], {}), '(fsr_id)\n', (35662, 35670), True, 'import numpy as np\n'), ((37693, 37732), 'numpy.arange', 'np.arange', (['(1)', '(iramsolver._num_modes + 1)'], {}), '(1, iramsolver._num_modes + 1)\n', (37702, 37732), True, 'import numpy as np\n'), ((38913, 38943), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['eigenvec'], {}), '(eigenvec)\n', (38933, 38943), True, 'import numpy as np\n'), ((39096, 39112), 'numpy.abs', 'np.abs', (['eigenvec'], {}), '(eigenvec)\n', (39102, 39112), True, 'import numpy as np\n'), ((32367, 32485), 'matplotlib.pyplot.loglog', 'plt.loglog', (['group_bounds[group:group + 2]', '([fluxes[group]] * 2)'], {'linewidth': '(3)', 'c': '"""b"""', 'label': '"""openmoc"""', 'linestyle': '"""-"""'}), "(group_bounds[group:group + 2], [fluxes[group]] * 2, linewidth=3,\n c='b', label='openmoc', linestyle='-')\n", (32377, 32485), True, 'import matplotlib.pyplot as plt\n'), ((32518, 32635), 'matplotlib.pyplot.plot', 'plt.plot', (['group_bounds[group:group + 2]', '([fluxes[group]] * 2)'], {'linewidth': '(3)', 'c': '"""b"""', 'label': '"""openmoc"""', 'linestyle': '"""-"""'}), "(group_bounds[group:group + 2], [fluxes[group]] * 2, linewidth=3, c\n ='b', label='openmoc', linestyle='-')\n", (32526, 32635), True, 'import matplotlib.pyplot as plt\n'), ((38960, 38977), 'numpy.real', 'np.real', (['eigenvec'], {}), '(eigenvec)\n', (38967, 38977), True, 'import numpy as np\n'), ((15749, 15781), 'matplotlib.markers.MarkerStyle', 'matplotlib.markers.MarkerStyle', ([], {}), '()\n', (15779, 15781), False, 'import matplotlib\n'), ((32731, 32824), 'matplotlib.pyplot.loglog', 'plt.loglog', (['([group_bounds[group + 1]] * 2)', 'fluxes[group:group + 2]'], {'c': '"""b"""', 'linestyle': '"""--"""'}), "([group_bounds[group + 1]] * 2, fluxes[group:group + 2], c='b',\n linestyle='--')\n", (32741, 32824), True, 'import matplotlib.pyplot as plt\n'), ((32861, 32952), 'matplotlib.pyplot.plot', 'plt.plot', (['([group_bounds[group + 1]] * 2)', 'fluxes[group:group + 2]'], {'c': '"""b"""', 'linestyle': '"""--"""'}), "([group_bounds[group + 1]] * 2, fluxes[group:group + 2], c='b',\n linestyle='--')\n", (32869, 32952), True, 'import matplotlib.pyplot as plt\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Determine screen gamma using motion-nulling method
of <NAME> Smith, 1994, Vision Research, 34, 2727-2740
A similar system had been used early for chromatic isoluminance:
Anstis SM, <NAME>. A minimum motion technique for judging equiluminance.
In: Sharpe MJD & LT Colour vision: Psychophysics and physiology. London: Academic Press; 1983. pp. 66-77.
Instructions: on each trial press the up/down cursor keys depending on
the apparent direction of motion of the bars.
"""
from __future__ import absolute_import, division, print_function
from builtins import next
from builtins import range
from psychopy import visual, core, event, gui, data
from psychopy.tools.filetools import fromFile, toFile
from psychopy.visual import filters
import numpy as num
import time
try:
# try to load previous info
info = fromFile('info_gamma.pickle')
print(info)
except Exception:
# if no file use some defaults
info = {}
info['lumModNoise'] = 0.5
info['lumModLum'] = 0.1
info['contrastModNoise'] = 1.0
info['observer'] = ''
info['highGamma'] = 3.0
info['lowGamma'] = 0.8
info['nTrials'] = 50
dlg = gui.DlgFromDict(info)
# save to a file for future use (ie storing as defaults)
if dlg.OK:
toFile('info_gamma.pickle', info)
else:
core.quit() # user cancelled. quit
print(info)
info['timeStr']=time.strftime("%b_%d_%H%M", time.localtime())
nFrames = 3
cyclesTime = 2
cyclesSpace = 2
pixels = 128
win = visual.Window((1024, 768), units='pix', allowGUI=True, bitsMode=None)
visual.TextStim(win, text='building stimuli').draw()
win.flip()
globalClock = core.Clock()
# for luminance modulated noise
noiseMatrix = num.random.randint(0, 2, [pixels, pixels]) # * noiseContrast
noiseMatrix = noiseMatrix * 2.0-1 # into range -1: 1
stimFrames = []; lumGratings=[]
# create the 4 frames of the sequence (luminance and contrast modulated noise in quadrature)
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=0))
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0 / pixels, ori=90,
tex= (noiseMatrix * info['lumModNoise'] + lumGratings[0] * info['lumModLum'])
))
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=90) / 2.0 + 0.5)
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0/pixels, ori=90,
tex= (noiseMatrix * info['contrastModNoise'] * lumGratings[1])
))
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=180))
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0/pixels, ori=90,
tex= (noiseMatrix * info['lumModNoise'] + lumGratings[2] * info['lumModLum'])
))
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=270) / 2.0 + 0.5)
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0/pixels, ori=90,
tex= (noiseMatrix * info['contrastModNoise'] * lumGratings[3])
))
stairCases = []
# two staircases - one from the top, one from below - to average
stairCases.append(data.StairHandler(startVal=info['highGamma'], nTrials=info['nTrials'],
stepSizes=[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05], stepType='lin',
nUp=1, nDown=1))
stairCases.append(data.StairHandler(startVal=info['lowGamma'], nTrials=info['nTrials'],
stepSizes=[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05], stepType='lin',
nUp=1, nDown=1))
def getResponse(direction):
"""if subject said up when direction was up ( + 1) then increase gamma
Otherwise, decrease gamma"""
event.clearEvents() # clear the event buffer to start with
while 1: # forever until we return
for key in event.getKeys():
# quit
if key in ['escape', 'q']:
win.close()
# win.bits.reset()
core.quit()
# valid response - check to see if correct
elif key in ['down', 'up']:
if ((key in ['down'] and direction == -1) or
(key in ['up'] and direction == +1)):
return 0
else:
return 1
else:
print("hit DOWN or UP (or Esc) (You hit %s)" %key)
def presentStimulus(direction):
"""Present stimulus drifting in a given direction (for low gamma)
where:
direction = + 1(up) or -1(down)
"""
win.fps()
startPhase = num.random.random()
if direction == 1:
frameIndices = num.arange(0, 4)
else:
frameIndices = num.arange(3, -1, -1)
for cycles in range(cyclesTime):
# cycle through the 4 frames
for ii in frameIndices:
thisStim = stimFrames[ii]
thisStim.setPhase(startPhase)
for n in range(nFrames):
# present for several constant frames (TF)
thisStim.draw()
win.flip()
# then blank the screen
win.flip()
# run the staircase
for trialN in range(info['nTrials']):
for stairCase in stairCases:
thisGamma = next(stairCase)
t = globalClock.getTime()
win.gamma = [thisGamma, thisGamma, thisGamma]
direction = num.random.randint(0, 2) * 2-1 # a random number -1 or 1
presentStimulus(direction)
ans = getResponse(direction)
stairCase.addData(ans)
win.flip()
core.wait(0.5)
win.close()
# save data
fileName = gui.fileSaveDlg('.', '%s_%s' %(info['observer'], info['timeStr']))
stairCases[1].saveAsPickle(fileName + 'hi')
stairCases[1].saveAsText(fileName + 'hi')
stairCases[0].saveAsPickle(fileName + 'lo')
stairCases[0].saveAsText(fileName + 'lo')
print('That took %.1fmins' % (globalClock.getTime() / 60.0))
core.quit()
# The contents of this file are in the public domain.
|
[
"numpy.random.randint",
"numpy.arange",
"psychopy.tools.filetools.toFile",
"psychopy.event.clearEvents",
"psychopy.gui.DlgFromDict",
"builtins.range",
"psychopy.event.getKeys",
"psychopy.tools.filetools.fromFile",
"builtins.next",
"psychopy.visual.Window",
"psychopy.core.quit",
"time.localtime",
"psychopy.data.StairHandler",
"psychopy.gui.fileSaveDlg",
"psychopy.core.Clock",
"psychopy.core.wait",
"psychopy.visual.TextStim",
"psychopy.visual.GratingStim",
"numpy.random.random",
"psychopy.visual.filters.makeGrating"
] |
[((1183, 1204), 'psychopy.gui.DlgFromDict', 'gui.DlgFromDict', (['info'], {}), '(info)\n', (1198, 1204), False, 'from psychopy import visual, core, event, gui, data\n'), ((1495, 1564), 'psychopy.visual.Window', 'visual.Window', (['(1024, 768)'], {'units': '"""pix"""', 'allowGUI': '(True)', 'bitsMode': 'None'}), "((1024, 768), units='pix', allowGUI=True, bitsMode=None)\n", (1508, 1564), False, 'from psychopy import visual, core, event, gui, data\n'), ((1645, 1657), 'psychopy.core.Clock', 'core.Clock', ([], {}), '()\n', (1655, 1657), False, 'from psychopy import visual, core, event, gui, data\n'), ((1705, 1747), 'numpy.random.randint', 'num.random.randint', (['(0)', '(2)', '[pixels, pixels]'], {}), '(0, 2, [pixels, pixels])\n', (1723, 1747), True, 'import numpy as num\n'), ((5136, 5158), 'builtins.range', 'range', (["info['nTrials']"], {}), "(info['nTrials'])\n", (5141, 5158), False, 'from builtins import range\n'), ((5512, 5526), 'psychopy.core.wait', 'core.wait', (['(0.5)'], {}), '(0.5)\n', (5521, 5526), False, 'from psychopy import visual, core, event, gui, data\n'), ((5564, 5631), 'psychopy.gui.fileSaveDlg', 'gui.fileSaveDlg', (['"""."""', "('%s_%s' % (info['observer'], info['timeStr']))"], {}), "('.', '%s_%s' % (info['observer'], info['timeStr']))\n", (5579, 5631), False, 'from psychopy import visual, core, event, gui, data\n'), ((5866, 5877), 'psychopy.core.quit', 'core.quit', ([], {}), '()\n', (5875, 5877), False, 'from psychopy import visual, core, event, gui, data\n'), ((865, 894), 'psychopy.tools.filetools.fromFile', 'fromFile', (['"""info_gamma.pickle"""'], {}), "('info_gamma.pickle')\n", (873, 894), False, 'from psychopy.tools.filetools import fromFile, toFile\n'), ((1277, 1310), 'psychopy.tools.filetools.toFile', 'toFile', (['"""info_gamma.pickle"""', 'info'], {}), "('info_gamma.pickle', info)\n", (1283, 1310), False, 'from psychopy.tools.filetools import fromFile, toFile\n'), ((1321, 1332), 'psychopy.core.quit', 'core.quit', ([], {}), '()\n', (1330, 1332), False, 'from psychopy import visual, core, event, gui, data\n'), ((1414, 1430), 'time.localtime', 'time.localtime', ([], {}), '()\n', (1428, 1430), False, 'import time\n'), ((1966, 2018), 'psychopy.visual.filters.makeGrating', 'filters.makeGrating', (['pixels', '(0)', 'cyclesSpace'], {'phase': '(0)'}), '(pixels, 0, cyclesSpace, phase=0)\n', (1985, 2018), False, 'from psychopy.visual import filters\n'), ((2038, 2219), 'psychopy.visual.GratingStim', 'visual.GratingStim', (['win'], {'texRes': 'pixels', 'mask': '"""circle"""', 'size': '(pixels * 2)', 'sf': '(1.0 / pixels)', 'ori': '(90)', 'tex': "(noiseMatrix * info['lumModNoise'] + lumGratings[0] * info['lumModLum'])"}), "(win, texRes=pixels, mask='circle', size=pixels * 2, sf=\n 1.0 / pixels, ori=90, tex=noiseMatrix * info['lumModNoise'] + \n lumGratings[0] * info['lumModLum'])\n", (2056, 2219), False, 'from psychopy import visual, core, event, gui, data\n'), ((2343, 2508), 'psychopy.visual.GratingStim', 'visual.GratingStim', (['win'], {'texRes': 'pixels', 'mask': '"""circle"""', 'size': '(pixels * 2)', 'sf': '(1.0 / pixels)', 'ori': '(90)', 'tex': "(noiseMatrix * info['contrastModNoise'] * lumGratings[1])"}), "(win, texRes=pixels, mask='circle', size=pixels * 2, sf=\n 1.0 / pixels, ori=90, tex=noiseMatrix * info['contrastModNoise'] *\n lumGratings[1])\n", (2361, 2508), False, 'from psychopy import visual, core, event, gui, data\n'), ((2546, 2600), 'psychopy.visual.filters.makeGrating', 'filters.makeGrating', (['pixels', '(0)', 'cyclesSpace'], {'phase': '(180)'}), '(pixels, 0, cyclesSpace, phase=180)\n', (2565, 2600), False, 'from psychopy.visual import filters\n'), ((2620, 2801), 'psychopy.visual.GratingStim', 'visual.GratingStim', (['win'], {'texRes': 'pixels', 'mask': '"""circle"""', 'size': '(pixels * 2)', 'sf': '(1.0 / pixels)', 'ori': '(90)', 'tex': "(noiseMatrix * info['lumModNoise'] + lumGratings[2] * info['lumModLum'])"}), "(win, texRes=pixels, mask='circle', size=pixels * 2, sf=\n 1.0 / pixels, ori=90, tex=noiseMatrix * info['lumModNoise'] + \n lumGratings[2] * info['lumModLum'])\n", (2638, 2801), False, 'from psychopy import visual, core, event, gui, data\n'), ((2924, 3089), 'psychopy.visual.GratingStim', 'visual.GratingStim', (['win'], {'texRes': 'pixels', 'mask': '"""circle"""', 'size': '(pixels * 2)', 'sf': '(1.0 / pixels)', 'ori': '(90)', 'tex': "(noiseMatrix * info['contrastModNoise'] * lumGratings[3])"}), "(win, texRes=pixels, mask='circle', size=pixels * 2, sf=\n 1.0 / pixels, ori=90, tex=noiseMatrix * info['contrastModNoise'] *\n lumGratings[3])\n", (2942, 3089), False, 'from psychopy import visual, core, event, gui, data\n'), ((3208, 3372), 'psychopy.data.StairHandler', 'data.StairHandler', ([], {'startVal': "info['highGamma']", 'nTrials': "info['nTrials']", 'stepSizes': '[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05]', 'stepType': '"""lin"""', 'nUp': '(1)', 'nDown': '(1)'}), "(startVal=info['highGamma'], nTrials=info['nTrials'],\n stepSizes=[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05], stepType='lin',\n nUp=1, nDown=1)\n", (3225, 3372), False, 'from psychopy import visual, core, event, gui, data\n'), ((3400, 3563), 'psychopy.data.StairHandler', 'data.StairHandler', ([], {'startVal': "info['lowGamma']", 'nTrials': "info['nTrials']", 'stepSizes': '[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05]', 'stepType': '"""lin"""', 'nUp': '(1)', 'nDown': '(1)'}), "(startVal=info['lowGamma'], nTrials=info['nTrials'],\n stepSizes=[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05], stepType='lin',\n nUp=1, nDown=1)\n", (3417, 3563), False, 'from psychopy import visual, core, event, gui, data\n'), ((3714, 3733), 'psychopy.event.clearEvents', 'event.clearEvents', ([], {}), '()\n', (3731, 3733), False, 'from psychopy import visual, core, event, gui, data\n'), ((4577, 4596), 'numpy.random.random', 'num.random.random', ([], {}), '()\n', (4594, 4596), True, 'import numpy as num\n'), ((4734, 4751), 'builtins.range', 'range', (['cyclesTime'], {}), '(cyclesTime)\n', (4739, 4751), False, 'from builtins import range\n'), ((1565, 1610), 'psychopy.visual.TextStim', 'visual.TextStim', (['win'], {'text': '"""building stimuli"""'}), "(win, text='building stimuli')\n", (1580, 1610), False, 'from psychopy import visual, core, event, gui, data\n'), ((3834, 3849), 'psychopy.event.getKeys', 'event.getKeys', ([], {}), '()\n', (3847, 3849), False, 'from psychopy import visual, core, event, gui, data\n'), ((4643, 4659), 'numpy.arange', 'num.arange', (['(0)', '(4)'], {}), '(0, 4)\n', (4653, 4659), True, 'import numpy as num\n'), ((4693, 4714), 'numpy.arange', 'num.arange', (['(3)', '(-1)', '(-1)'], {}), '(3, -1, -1)\n', (4703, 4714), True, 'import numpy as num\n'), ((5213, 5228), 'builtins.next', 'next', (['stairCase'], {}), '(stairCase)\n', (5217, 5228), False, 'from builtins import next\n'), ((2258, 2311), 'psychopy.visual.filters.makeGrating', 'filters.makeGrating', (['pixels', '(0)', 'cyclesSpace'], {'phase': '(90)'}), '(pixels, 0, cyclesSpace, phase=90)\n', (2277, 2311), False, 'from psychopy.visual import filters\n'), ((2838, 2892), 'psychopy.visual.filters.makeGrating', 'filters.makeGrating', (['pixels', '(0)', 'cyclesSpace'], {'phase': '(270)'}), '(pixels, 0, cyclesSpace, phase=270)\n', (2857, 2892), False, 'from psychopy.visual import filters\n'), ((4923, 4937), 'builtins.range', 'range', (['nFrames'], {}), '(nFrames)\n', (4928, 4937), False, 'from builtins import range\n'), ((3988, 3999), 'psychopy.core.quit', 'core.quit', ([], {}), '()\n', (3997, 3999), False, 'from psychopy import visual, core, event, gui, data\n'), ((5338, 5362), 'numpy.random.randint', 'num.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (5356, 5362), True, 'import numpy as num\n')]
|
'''
Code of 'Searching Central Difference Convolutional Networks for Face Anti-Spoofing'
By <NAME> & <NAME>, 2019
If you use the code, please cite:
@inproceedings{yu2020searching,
title={Searching Central Difference Convolutional Networks for Face Anti-Spoofing},
author={<NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME>},
booktitle= {CVPR},
year = {2020}
}
Only for research purpose, and commercial use is not allowed.
MIT License
Copyright (c) 2020
'''
import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def get_file_list(read_path):
'''
获取文件夹下图片的地址
:param read_path:
:return:
'''
path = read_path
dirs = os.listdir(path)
floder_len = len(dirs)
file_name_list = []
for i in range(floder_len):
# 设置路径
floder = dirs[i]
floder_path = path + "/" + floder
# 如果路径下是文件,那么就再次读取
if os.path.isdir(floder_path):
file_one = os.listdir(floder_path)
file_len_one = len(file_one)
for j in range(file_len_one):
# 读取视频
floder_path_one = floder_path + "/" + file_one[j]
if os.path.isdir(floder_path_one):
file_two = os.listdir(floder_path_one)
file_len_two = len(file_two)
for k in range(file_len_two):
floder_path_two = floder_path_one + "/" + file_two[k]
if os.path.isdir(floder_path_two):
file_three = os.listdir(floder_path_two)
file_len_three = len(file_three)
for m in range(file_len_three):
floder_path_three = floder_path_two + "/" + file_three[m]
file_name_list.append(floder_path_three)
else:
file_name_list.append(floder_path_two)
else:
file_name_list.append(floder_path_one)
# 如果路径下,没有文件夹,直接是文件,就加入进来
else:
file_name_list.append(floder_path)
return file_name_list
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum += val * n
self.cnt += n
self.avg = self.sum / self.cnt
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def get_threshold(score_file):
with open(score_file, 'r') as file:
lines = file.readlines()
data = []
count = 0.0
num_real = 0.0
num_fake = 0.0
for line in lines:
count += 1
tokens = line.split()
angle = float(tokens[0])
# pdb.set_trace()
type = int(tokens[1])
data.append({'map_score': angle, 'label': type})
if type == 1:
num_real += 1
else:
num_fake += 1
min_error = count # account ACER (or ACC)
min_threshold = 0.0
min_ACC = 0.0
min_ACER = 0.0
min_APCER = 0.0
min_BPCER = 0.0
for d in data:
threshold = d['map_score']
type1 = len([s for s in data if s['map_score'] <= threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > threshold and s['label'] == 0])
ACC = 1 - (type1 + type2) / count
APCER = type2 / num_fake
BPCER = type1 / num_real
ACER = (APCER + BPCER) / 2.0
if ACER < min_error:
min_error = ACER
min_threshold = threshold
min_ACC = ACC
min_ACER = ACER
min_APCER = APCER
min_BPCER = min_BPCER
# print(min_error, min_threshold)
return min_threshold, min_ACC, min_APCER, min_BPCER, min_ACER
def test_threshold_based(threshold, score_file):
with open(score_file, 'r') as file:
lines = file.readlines()
data = []
count = 0.0
num_real = 0.0
num_fake = 0.0
for line in lines:
count += 1
tokens = line.split()
angle = float(tokens[0])
type = int(tokens[1])
data.append({'map_score': angle, 'label': type})
if type == 1:
num_real += 1
else:
num_fake += 1
type1 = len([s for s in data if s['map_score'] <= threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > threshold and s['label'] == 0])
ACC = 1 - (type1 + type2) / count
APCER = type2 / num_fake
BPCER = type1 / num_real
ACER = (APCER + BPCER) / 2.0
return ACC, APCER, BPCER, ACER
def get_err_threhold(fpr, tpr, threshold):
RightIndex = (tpr + (1 - fpr) - 1);
right_index = np.argmax(RightIndex)
best_th = threshold[right_index]
err = fpr[right_index]
differ_tpr_fpr_1 = tpr + fpr - 1.0
right_index = np.argmin(np.abs(differ_tpr_fpr_1))
best_th = threshold[right_index]
err = fpr[right_index]
# print(err, best_th)
return err, best_th
# def performances(dev_scores, dev_labels, test_scores, test_labels):
def performances(map_score_test_filename):
val_threshold = 0.4
# test
with open(map_score_test_filename, 'r') as file2:
lines = file2.readlines()
test_scores = []
test_labels = []
data = []
count = 0.0
num_real = 0.0
num_fake = 0.0
for line in lines:
count += 1
tokens = line.split()
score = tokens[0]
score = score[:-1]
score = score[1:]
score = float(score)
label = tokens[1]
label = label[:-1]
label = label[1:]
label = int(label)
test_scores.append(score)
test_labels.append(label)
data.append({'map_score': score, 'label': label})
if label == 1:
num_real += 1
else:
num_fake += 1
# test based on val_threshold
type1 = len([s for s in data if s['map_score'] <= val_threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > val_threshold and s['label'] == 0])
test_ACC = 1 - (type1 + type2) / count
test_APCER = type2 / num_fake
test_BPCER = type1 / num_real
test_ACER = (test_APCER + test_BPCER) / 2.0
# test based on test_threshold
fpr_test, tpr_test, threshold_test = roc_curve(test_labels, test_scores, pos_label=1)
err_test, best_test_threshold = get_err_threhold(fpr_test, tpr_test, threshold_test)
type1 = len([s for s in data if s['map_score'] <= best_test_threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > best_test_threshold and s['label'] == 0])
test_threshold_ACC = 1 - (type1 + type2) / count
test_threshold_APCER = type2 / num_fake
test_threshold_BPCER = type1 / num_real
test_threshold_ACER = (test_threshold_APCER + test_threshold_BPCER) / 2.0
return test_ACC, test_APCER, test_BPCER, test_ACER, test_threshold_ACER
def performances_SiW_EER(map_score_val_filename):
# val
with open(map_score_val_filename, 'r') as file:
lines = file.readlines()
val_scores = []
val_labels = []
data = []
count = 0.0
num_real = 0.0
num_fake = 0.0
for line in lines:
count += 1
tokens = line.split()
score = float(tokens[0])
label = int(tokens[1])
val_scores.append(score)
val_labels.append(label)
data.append({'map_score': score, 'label': label})
if label == 1:
num_real += 1
else:
num_fake += 1
fpr, tpr, threshold = roc_curve(val_labels, val_scores, pos_label=1)
val_err, val_threshold = get_err_threhold(fpr, tpr, threshold)
type1 = len([s for s in data if s['map_score'] <= val_threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > val_threshold and s['label'] == 0])
val_ACC = 1 - (type1 + type2) / count
val_APCER = type2 / num_fake
val_BPCER = type1 / num_real
val_ACER = (val_APCER + val_BPCER) / 2.0
return val_threshold, val_ACC, val_APCER, val_BPCER, val_ACER
def performances_SiWM_EER(map_score_val_filename):
# val
with open(map_score_val_filename, 'r') as file:
lines = file.readlines()
val_scores = []
val_labels = []
data = []
count = 0.0
num_real = 0.0
num_fake = 0.0
for line in lines:
count += 1
tokens = line.split()
score = float(tokens[0])
label = int(tokens[1])
val_scores.append(score)
val_labels.append(label)
data.append({'map_score': score, 'label': label})
if label == 1:
num_real += 1
else:
num_fake += 1
fpr, tpr, threshold = roc_curve(val_labels, val_scores, pos_label=1)
val_err, val_threshold = get_err_threhold(fpr, tpr, threshold)
type1 = len([s for s in data if s['map_score'] <= val_threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > val_threshold and s['label'] == 0])
val_ACC = 1 - (type1 + type2) / count
val_APCER = type2 / num_fake
val_BPCER = type1 / num_real
val_ACER = (val_APCER + val_BPCER) / 2.0
return val_threshold, val_err, val_ACC, val_APCER, val_BPCER, val_ACER
def get_err_threhold_CASIA_Replay(fpr, tpr, threshold):
RightIndex = (tpr + (1 - fpr) - 1);
right_index = np.argmax(RightIndex)
best_th = threshold[right_index]
err = fpr[right_index]
differ_tpr_fpr_1 = tpr + fpr - 1.0
right_index = np.argmin(np.abs(differ_tpr_fpr_1))
best_th = threshold[right_index]
err = fpr[right_index]
# print(err, best_th)
return err, best_th, right_index
def performances_CASIA_Replay(map_score_val_filename):
# val
with open(map_score_val_filename, 'r') as file:
lines = file.readlines()
val_scores = []
val_labels = []
data = []
count = 0.0
num_real = 0.0
num_fake = 0.0
for line in lines:
count += 1
tokens = line.split()
score = tokens[0]
score = score[:-1]
score = score[1:]
score = float(score)
label = tokens[1]
label = label[:-1]
label = label[1:]
label = int(label)
val_scores.append(score)
val_labels.append(label)
data.append({'map_score': score, 'label': label})
if label == 1:
num_real += 1
else:
num_fake += 1
fpr, tpr, threshold = roc_curve(val_labels, val_scores, pos_label=1)
val_err, val_threshold, right_index = get_err_threhold_CASIA_Replay(fpr, tpr, threshold)
type1 = len([s for s in data if s['map_score'] <= val_threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > val_threshold and s['label'] == 0])
val_ACC = 1 - (type1 + type2) / count
FRR = 1 - tpr # FRR = 1 - TPR
HTER = (fpr + FRR) / 2.0 # error recognition rate & reject recognition rate
return val_ACC, fpr[right_index], FRR[right_index], HTER[right_index]
def performances_ZeroShot(map_score_val_filename):
# val
with open(map_score_val_filename, 'r') as file:
lines = file.readlines()
val_scores = []
val_labels = []
data = []
count = 0.0
num_real = 0.0
num_fake = 0.0
for line in lines:
count += 1
tokens = line.split()
score = float(tokens[0])
label = int(tokens[1])
val_scores.append(score)
val_labels.append(label)
data.append({'map_score': score, 'label': label})
if label == 1:
num_real += 1
else:
num_fake += 1
fpr, tpr, threshold = roc_curve(val_labels, val_scores, pos_label=1)
auc_val = metrics.auc(fpr, tpr)
val_err, val_threshold, right_index = get_err_threhold_CASIA_Replay(fpr, tpr, threshold)
type1 = len([s for s in data if s['map_score'] <= val_threshold and s['label'] == 1])
type2 = len([s for s in data if s['map_score'] > val_threshold and s['label'] == 0])
val_ACC = 1 - (type1 + type2) / count
FRR = 1 - tpr # FRR = 1 - TPR
HTER = (fpr + FRR) / 2.0 # error recognition rate & reject recognition rate
return val_ACC, auc_val, HTER[right_index]
def count_parameters_in_MB(model):
return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if "auxiliary" not in name) / 1e6
def save_checkpoint(state, is_best, save):
filename = os.path.join(save, 'checkpoint.pth.tar')
torch.save(state, filename)
if is_best:
best_filename = os.path.join(save, 'model_best.pth.tar')
shutil.copyfile(filename, best_filename)
def save(model, model_path):
torch.save(model.state_dict(), model_path)
def load(model, model_path):
model.load_state_dict(torch.load(model_path))
def drop_path(x, drop_prob):
if drop_prob > 0.:
keep_prob = 1. - drop_prob
mask = Variable(torch.cuda.FloatTensor(x.size(0), 1, 1, 1, 1).bernoulli_(keep_prob))
x.div_(keep_prob)
x.mul_(mask)
return x
def create_exp_dir(path, scripts_to_save=None):
if not os.path.exists(path):
os.mkdir(path)
print('Experiment dir : {}'.format(path))
if scripts_to_save is not None:
os.mkdir(os.path.join(path, 'scripts'))
for script in scripts_to_save:
dst_file = os.path.join(path, 'scripts', os.path.basename(script))
shutil.copyfile(script, dst_file)
|
[
"os.mkdir",
"numpy.abs",
"sklearn.metrics.roc_curve",
"numpy.argmax",
"os.path.isdir",
"os.path.basename",
"torch.load",
"os.path.exists",
"torch.save",
"sklearn.metrics.auc",
"shutil.copyfile",
"os.path.join",
"os.listdir"
] |
[((876, 892), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (886, 892), False, 'import os\n'), ((5255, 5276), 'numpy.argmax', 'np.argmax', (['RightIndex'], {}), '(RightIndex)\n', (5264, 5276), True, 'import numpy as np\n'), ((6862, 6910), 'sklearn.metrics.roc_curve', 'roc_curve', (['test_labels', 'test_scores'], {'pos_label': '(1)'}), '(test_labels, test_scores, pos_label=1)\n', (6871, 6910), False, 'from sklearn.metrics import roc_curve, auc\n'), ((8120, 8166), 'sklearn.metrics.roc_curve', 'roc_curve', (['val_labels', 'val_scores'], {'pos_label': '(1)'}), '(val_labels, val_scores, pos_label=1)\n', (8129, 8166), False, 'from sklearn.metrics import roc_curve, auc\n'), ((9267, 9313), 'sklearn.metrics.roc_curve', 'roc_curve', (['val_labels', 'val_scores'], {'pos_label': '(1)'}), '(val_labels, val_scores, pos_label=1)\n', (9276, 9313), False, 'from sklearn.metrics import roc_curve, auc\n'), ((9907, 9928), 'numpy.argmax', 'np.argmax', (['RightIndex'], {}), '(RightIndex)\n', (9916, 9928), True, 'import numpy as np\n'), ((11002, 11048), 'sklearn.metrics.roc_curve', 'roc_curve', (['val_labels', 'val_scores'], {'pos_label': '(1)'}), '(val_labels, val_scores, pos_label=1)\n', (11011, 11048), False, 'from sklearn.metrics import roc_curve, auc\n'), ((12191, 12237), 'sklearn.metrics.roc_curve', 'roc_curve', (['val_labels', 'val_scores'], {'pos_label': '(1)'}), '(val_labels, val_scores, pos_label=1)\n', (12200, 12237), False, 'from sklearn.metrics import roc_curve, auc\n'), ((12252, 12273), 'sklearn.metrics.auc', 'metrics.auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (12263, 12273), False, 'from sklearn import metrics\n'), ((12965, 13005), 'os.path.join', 'os.path.join', (['save', '"""checkpoint.pth.tar"""'], {}), "(save, 'checkpoint.pth.tar')\n", (12977, 13005), False, 'import os\n'), ((13010, 13037), 'torch.save', 'torch.save', (['state', 'filename'], {}), '(state, filename)\n', (13020, 13037), False, 'import torch\n'), ((1098, 1124), 'os.path.isdir', 'os.path.isdir', (['floder_path'], {}), '(floder_path)\n', (1111, 1124), False, 'import os\n'), ((5410, 5434), 'numpy.abs', 'np.abs', (['differ_tpr_fpr_1'], {}), '(differ_tpr_fpr_1)\n', (5416, 5434), True, 'import numpy as np\n'), ((10062, 10086), 'numpy.abs', 'np.abs', (['differ_tpr_fpr_1'], {}), '(differ_tpr_fpr_1)\n', (10068, 10086), True, 'import numpy as np\n'), ((13078, 13118), 'os.path.join', 'os.path.join', (['save', '"""model_best.pth.tar"""'], {}), "(save, 'model_best.pth.tar')\n", (13090, 13118), False, 'import os\n'), ((13127, 13167), 'shutil.copyfile', 'shutil.copyfile', (['filename', 'best_filename'], {}), '(filename, best_filename)\n', (13142, 13167), False, 'import shutil\n'), ((13303, 13325), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (13313, 13325), False, 'import torch\n'), ((13630, 13650), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (13644, 13650), False, 'import os\n'), ((13660, 13674), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (13668, 13674), False, 'import os\n'), ((1149, 1172), 'os.listdir', 'os.listdir', (['floder_path'], {}), '(floder_path)\n', (1159, 1172), False, 'import os\n'), ((13775, 13804), 'os.path.join', 'os.path.join', (['path', '"""scripts"""'], {}), "(path, 'scripts')\n", (13787, 13804), False, 'import os\n'), ((13936, 13969), 'shutil.copyfile', 'shutil.copyfile', (['script', 'dst_file'], {}), '(script, dst_file)\n', (13951, 13969), False, 'import shutil\n'), ((1364, 1394), 'os.path.isdir', 'os.path.isdir', (['floder_path_one'], {}), '(floder_path_one)\n', (1377, 1394), False, 'import os\n'), ((13898, 13922), 'os.path.basename', 'os.path.basename', (['script'], {}), '(script)\n', (13914, 13922), False, 'import os\n'), ((1427, 1454), 'os.listdir', 'os.listdir', (['floder_path_one'], {}), '(floder_path_one)\n', (1437, 1454), False, 'import os\n'), ((1659, 1689), 'os.path.isdir', 'os.path.isdir', (['floder_path_two'], {}), '(floder_path_two)\n', (1672, 1689), False, 'import os\n'), ((1732, 1759), 'os.listdir', 'os.listdir', (['floder_path_two'], {}), '(floder_path_two)\n', (1742, 1759), False, 'import os\n')]
|
import numpy as _np
import pandas as _pd
import matplotlib.pyplot as _plt
from src.plot_helpers.matplotlib_helpers\
import range_axis_ticks as _range_axis_ticks
def plot_value_by_element(df, xaxis, element_col, value_col, ax, cmap,
alpha=1.0, lw=1.0,
x_intervals=None, x_fmt=None):
'''
Plot values by each element in the column element_col in df on ax.
Can specify linewidth (lw), alpha of lines and colormap to use (cmap).
The number of x-axis intervals can be specified, it it is, provide x_fmt
Will only plot where value > 0 for given datetime
Args:
df: DataFrane
xaxis: xaxis column name in df
element_col: element column name in df
value_col: value column name in df
ax: matplotlib Axes object
cmap: matplotlib.pyplot.cm colourmap object
alpha (float, 0-1): plot alpha
lw (float): linewidth of line plots
x_intervals (int, optional, need x_fmt): number of x-axis intervals
x_fmt (matplotlib Formatter, optional, need x_intervals): formatter
Returns:
Axis with plot of elements
'''
unique_elements = df[element_col].drop_duplicates()
cmap = iter(cmap(_np.linspace(0, 1, len(unique_elements))))
for element, colour in zip(unique_elements, cmap):
filtered_val = df.loc[df[element_col] == element, [xaxis, value_col]]
if abs(filtered_val[value_col].sum()) > 0:
ax.plot(filtered_val[xaxis],
filtered_val[value_col],
label=element,
alpha=alpha, linewidth=lw,
color=colour)
if x_intervals is not None:
ax = _range_axis_ticks(ax, 'x', x_intervals, fmt=x_fmt)
ax.tick_params(axis='x', labelrotation=90, labelsize=8)
return ax
def find_nonzero_category(df, category_col, value_col):
'''
Returns a unique list of categories in category col.
Each category returned has a non-zero sum in the value_col.
Args:
df (pandas DataFrame): DataFrame to use
category_col (str): col within df to use to find non-zero categories
value_col (str): col within df to assess whether category is non-zero
Returns:
Sorted list of categories
'''
cat_types = set(df[category_col])
plot_types = []
for cat in cat_types:
df_cat_val = df.loc[df[category_col] == cat, value_col]
if df_cat_val.sum() > 0:
plot_types.append(cat)
return sorted(plot_types)
def plot_nonzero_elements_by_category(ax, df, xaxis_col, yaxis_col,
element_col, category, category_col,
cmap=None, lw=1.0, alpha=1.0):
'''
Plot x and y axis cols on ax for each unique element
that satisfies a given category value.
Args:
ax (matplotlib Axes object): axis to plot on
df (pandas DataFrame): dataframe to use
xaxis_col (str): x-axis col name
yaxis_col (str): y-axis col name
element_col (str): col name used to identify individual elements
category (str): isolate elements that are under this category
category_col (str): col name in df used to filter on category
cmap (matplotlib.pyplot.cm, optional): colormap
lw (float, optional): linewidth
alpha (float, optional): plot alpha
Returns:
Axis with plotted elements tha meet category criteria
Dataframe with categories filtered
'''
category_df = df.loc[df[category_col] == category, :]
elements = set(category_df[element_col])
if cmap is not None:
colors = iter(cmap(_np.linspace(0, 1, len(elements))))
else:
colors = iter(_plt.cm.tab10(0, 1, len(elements)))
# plot line for each element where yaxis_col > 0 for datetime range
for element, color in zip(sorted(elements), colors):
element_df = category_df.loc[category_df[element_col] == element, :]
if element_df[yaxis_col].sum() > 0:
ax.plot(element_df[xaxis_col], element_df[yaxis_col],
label=element, color=color, linewidth=lw)
return ax, category_df
def nofb(df, datetime_col=None):
'''
Creates two series with the limits of the NEM normal operating
frequency band.
Args:
df (pandas DataFrame): DataFrame length to copy for NOFB series
datetime_col (str, optional): default is to assume DatetimeIndex,
if this is not the case, supply
datetime_col
Returns:
Tuple of Series corresponding to (upper NOFB, lower NOFB)
'''
if datetime_col:
lower = _np.ones(df[datetime_col].shape) * 49.85
upper = _np.ones(df[datetime_col].shape) * 50.15
index = df[datetime_col]
else:
lower = _np.ones(df.index.shape) * 49.85
upper = _np.ones(df.index.shape) * 50.15
index = df.index
return (_pd.Series(data=upper, index=index),
_pd.Series(data=lower, index=index))
def nofb_plot(nofb_function, axis, lw=1.0, alpha=1.0, style='y--'):
'''
Plots NOFB. Adds label to one of the plotted series.
Args:
nofb_function (func): nofb function with args supplied
axis (matplotlib Axes): Axis to plot on
lw (float, optional): plot linewidth
alpha(float, optional): plot alpha
style (str): matplotlib style, refer to pyplot.plot docs
Returns:
Axis with NOFB plotted
'''
upper, lower = nofb_function
axis.plot(upper, style, label='NOFB', linewidth=lw, alpha=alpha)
axis.plot(lower, style, linewidth=lw, alpha=alpha)
return axis
def stacked_bar_subplots(df, figsize, cmap,
xaxis_col, values_col,
subplots_list, subplot_col,
stacked_list, stacked_col,
label_add, ax_title_add):
'''
Plot stacked bar charts across a range of subplots
Args:
df (pd.DataFrame): DataFrame to plot, with releveant *_cols
figsize (tuple): size in inches for figure
cmap (plt.cmap): object to determine color palette for stacked elements
xaxis_col (str): name of col in df to use as xticks
values_col (str): name of col in df to plot values
subplots_list (list): list to use as basis for separating subplots
subplot_col (str); name of col in df to separate data for each subplot
stacked_list (list): list of elements to stack in each subplot
stacked_col (str): name of col in df to obtain series to stack
label_add (str): generic str to add to the end of each stacked el label
ax_title_add (str): generic str to add to end of ax title
Returns:
Fig, Ax
'''
fig, ax = _plt.subplots(len(subplots_list), 1,
figsize=figsize, sharex=True)
x_labels = df[xaxis_col].drop_duplicates().tolist()
x_tix = _np.arange(len(x_labels))
colormap = _plt.get_cmap(cmap)
colors = colormap(_np.linspace(0, 1, len(stacked_list)))
plot_colors = {el: colors[i] for i, el in enumerate(stacked_list)}
for i, subplot_el in enumerate(subplots_list):
y_base = _np.zeros_like(x_tix)
subplot_df = df.query(f'{subplot_col}==@subplot_el')
for el in stacked_list:
rev = subplot_df.query(f'{stacked_col}==@el')
ax[i].bar(x_tix, rev[values_col], bottom=y_base,
color=plot_colors[el],
label=f'{el} {label_add}')
y_base = _np.add(y_base, rev[values_col].tolist())
ax[i].set_title(f'{subplot_el} {ax_title_add}')
return fig, ax
|
[
"numpy.zeros_like",
"matplotlib.pyplot.get_cmap",
"numpy.ones",
"src.plot_helpers.matplotlib_helpers.range_axis_ticks",
"pandas.Series"
] |
[((7095, 7114), 'matplotlib.pyplot.get_cmap', '_plt.get_cmap', (['cmap'], {}), '(cmap)\n', (7108, 7114), True, 'import matplotlib.pyplot as _plt\n'), ((1726, 1776), 'src.plot_helpers.matplotlib_helpers.range_axis_ticks', '_range_axis_ticks', (['ax', '"""x"""', 'x_intervals'], {'fmt': 'x_fmt'}), "(ax, 'x', x_intervals, fmt=x_fmt)\n", (1743, 1776), True, 'from src.plot_helpers.matplotlib_helpers import range_axis_ticks as _range_axis_ticks\n'), ((5031, 5066), 'pandas.Series', '_pd.Series', ([], {'data': 'upper', 'index': 'index'}), '(data=upper, index=index)\n', (5041, 5066), True, 'import pandas as _pd\n'), ((5080, 5115), 'pandas.Series', '_pd.Series', ([], {'data': 'lower', 'index': 'index'}), '(data=lower, index=index)\n', (5090, 5115), True, 'import pandas as _pd\n'), ((7316, 7337), 'numpy.zeros_like', '_np.zeros_like', (['x_tix'], {}), '(x_tix)\n', (7330, 7337), True, 'import numpy as _np\n'), ((4754, 4786), 'numpy.ones', '_np.ones', (['df[datetime_col].shape'], {}), '(df[datetime_col].shape)\n', (4762, 4786), True, 'import numpy as _np\n'), ((4811, 4843), 'numpy.ones', '_np.ones', (['df[datetime_col].shape'], {}), '(df[datetime_col].shape)\n', (4819, 4843), True, 'import numpy as _np\n'), ((4911, 4935), 'numpy.ones', '_np.ones', (['df.index.shape'], {}), '(df.index.shape)\n', (4919, 4935), True, 'import numpy as _np\n'), ((4960, 4984), 'numpy.ones', '_np.ones', (['df.index.shape'], {}), '(df.index.shape)\n', (4968, 4984), True, 'import numpy as _np\n')]
|
"""
This files only purpose is to pretty print the given map.
Input to printer is a map, the path the robot took and a planned path
if there is no path the robot took or planned path, they args can be left
printer(map, rob_path, planned_path)
result is nothing.
is saves the file in this folder. the name is by default test.png
(this two things could be changed if wanted.
"""
import numpy as np
from PIL import Image
def printer(m, rob_path=[], planned_path=[]):
maxV = m.maxV()
minV = m.lowestV()
x_range = maxV[0] + abs(minV[0])
y_range = maxV[1] + abs(minV[1])
arr = np.zeros([x_range +1,y_range + 1])
for i in m.d:
if(m.d[i]):
arr[(i[0]+ abs(minV[0]), i[1] + abs(minV[1]))] = 255
else:
arr[(i[0]+ abs(minV[0]), i[1] + abs(minV[1]))] = 125
image = Image.fromarray(arr)
image = image.convert("L")
pixels = image.load()
for i in rob_path:
pixels[i] = 0
for i in planned_path:
pixels[i] = (50)
#if image.size[0] >= int(m.rob.x_pos.value) + m.lowX and image.size[1] >= int(m.rob.y_pos.value) + m.lowY :
#pixels[(int(m.rob.x_pos.value) + m.lowX , int(m.rob.y_pos.value) + m.lowY)] = 200
image = image.resize([350,350],Image.NEAREST)
filename = "test.png"
image.save(filename)
|
[
"PIL.Image.fromarray",
"numpy.zeros"
] |
[((600, 636), 'numpy.zeros', 'np.zeros', (['[x_range + 1, y_range + 1]'], {}), '([x_range + 1, y_range + 1])\n', (608, 636), True, 'import numpy as np\n'), ((831, 851), 'PIL.Image.fromarray', 'Image.fromarray', (['arr'], {}), '(arr)\n', (846, 851), False, 'from PIL import Image\n')]
|
#%% Import
import sys
import re
import math
import string
import time
from pathlib import Path
import numpy as np
import pandas as pd
import string
import pickle
from scipy.sparse import hstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics.pairwise import cosine_distances
import spacy
from gensim.models import KeyedVectors
from nltk.tokenize import word_tokenize
#%% Constants
PATH_PROJ = Path(__file__).parent
PATH_DATA = PATH_PROJ / 'lib' / 'data'
PATH_MODELS = PATH_PROJ / 'lib' / 'models'
sys.path.append(str(PATH_PROJ))
# timer
start_time = time.time()
print("Start loading...")
#%% Load
# list of punctuation marks
punctuations = string.punctuation
# Create spacy word2vec and list of stopwords
nlp = spacy.load('en_core_web_sm')
stop_words = spacy.lang.en.stop_words.STOP_WORDS
# load classifier
with open(str(PATH_MODELS/"RFClassifier.pkl"), 'rb') as f:
clf = pickle.load(f)
# load vectorizer
with open(str(PATH_MODELS/'TFIDFVectorizer_lemma.pkl'), 'rb') as f:
v_lemma = pickle.load(f)
with open(str(PATH_MODELS/'TFIDFVectorizer_keyword.pkl'), 'rb') as f:
v_keyword = pickle.load(f)
with open(str(PATH_MODELS/'TFIDFVectorizer_noun.pkl'), 'rb') as f:
v_noun = pickle.load(f)
with open(str(PATH_MODELS/'TFIDFVectorizer_verb.pkl'), 'rb') as f:
v_verb = pickle.load(f)
# load intent list
with open(str(PATH_MODELS/'intent_list.pkl'), 'rb') as f:
intent_list = pickle.load(f)
# load clustering centres
with open(str(PATH_MODELS/'dict_cluster.pkl'), 'rb') as f:
dict_cluster = pickle.load(f)
# load idf
with open(str(PATH_MODELS/'idf.pkl'), 'rb') as f:
idf = pickle.load(f)
# load intent2index
with open(str(PATH_MODELS/'intent2index.pkl'), 'rb') as f:
intent2index = pickle.load(f)
# load keyword_list_lemma
with open(str(PATH_MODELS/'keyword_list_lemma.pkl'), 'rb') as f:
keyword_list_lemma = pickle.load(f)
EMBEDDING_FILE = str(PATH_MODELS / 'GoogleNews-vectors-negative300.bin.gz')
word2vec = KeyedVectors.load_word2vec_format(EMBEDDING_FILE, binary=True)
duration= time.time() - start_time
print(f"all pickles loaded, using {duration} sec")
#%% Pipeline
def get_intent_nlp_clustering(query):
"""
return a dataframe df
columns: pred_seq, intent_class, intent_string, pred_prob
rows: top 3 prediciton, example for first row: 1, 0, Promotions, 0.66
"""
# setup timer
start = time.time()
#%% pipeline
# convert question to dataframe
df = pd.DataFrame()
df = pd.DataFrame(columns=['query'])
df.loc[0] = [query]
# preprocessing test query
df['query'] = df['query'].apply(clean_text)
df['query'] = df['query'].apply(nltk_tokenize)
df['query'] = df['query'].apply(lambda x:' '.join([token.lemma_ for token in nlp(x) if token.lemma_ not in stop_words]))
df['query'] = df['query'].str.lower()
# get nlp features
df = get_nlp_features(df, keyword_list_lemma)
# get clustering matrix
df_cluster = get_distance_matrix_idf(df, intent_list, dict_cluster, word2vec, idf)
# get top 3 clusters
top_3 = get_top_3(df_cluster, intent_list)
# print(top_3)
# get inputs for RF classifier
top_clusters_cols = ['clusters_1', 'clusters_2', 'clusters_3']
# get input vector for RFClassifier
X_in = add_nlp_vec(top_3, v_lemma, v_keyword, v_noun, v_verb, top_clusters_cols)
# get prediction proba
probs = clf.predict_proba(X_in)
# get index for top 3 prediction by proba
ind = np.argsort(probs, axis=1)[:,-3:]
# save probability
proba = probs[0][ind[0]]
# save predicitons as dataframe
best_3 = pd.DataFrame(ind,columns=['top3','top2','top1'])
best_3['top1'] = clf.classes_[best_3['top1']]
best_3['top2'] = clf.classes_[best_3['top2']]
best_3['top3'] = clf.classes_[best_3['top3']]
best_3['top3_prob'] = proba[0]
best_3['top2_prob'] = proba[1]
best_3['top1_prob'] = proba[2]
# get index to intent dictionary from intent2index
index2intent = {y:x for x,y in intent2index.items()}
# get class name of top predictions
best_3['top1_name'] = best_3['top1'].apply(get_target_name, index2intent=index2intent)
best_3['top2_name'] = best_3['top2'].apply(get_target_name, index2intent=index2intent)
best_3['top3_name'] = best_3['top3'].apply(get_target_name, index2intent=index2intent)
# output prediction
top1 = best_3.at[0,'top1_name']
top2 = best_3.at[0,'top2_name']
top3 = best_3.at[0,'top3_name']
top1_prob = best_3.at[0,'top1_prob']
top2_prob = best_3.at[0,'top2_prob']
top3_prob = best_3.at[0,'top3_prob']
# print(f'For sentence:\n{query}\n')
# print(f'Top 1 prediction intent is {top1} with probability {100*top1_prob:.2f}%')
# print(f'Top 2 prediction intent is {top2} with probability {100*top2_prob:.2f}%')
# print(f'Top 3 prediction intent is {top3} with probability {100*top3_prob:.2f}%')
top1_class = best_3.at[0,'top1']
top2_class = best_3.at[0,'top2']
top3_class = best_3.at[0,'top3']
# convert to output
df = pd.DataFrame([
[1, top1_class, top1, top1_prob],
[2, top2_class, top2, top2_prob],
[3, top3_class, top3, top3_prob]
], columns=['pred_seq', 'intent_class', 'intent', 'pred_prob'])
inference_time = time.time() - start
print("inference_time", inference_time)
output = process_output(df)
return output
def process_output(df):
""" Process DataFrame to output format
Return:
internal_model_results = {'intent': [1,2,3]}
"""
result_list = []
# get mapping
df_map = pd.read_csv(str(PATH_DATA/'intent_index.csv'))
dict_map = df_map.set_index('Intent')['Label'].to_dict()
# get list of intents
for i in range(1,4):
intent = df.loc[df['pred_seq'] == i]['intent'].values[0]
intent_label = dict_map[intent]
result_list.append(intent_label)
return result_list
#%% utilities
def get_nlp_features(df, keyword_list_lemma):
""" Get keyword features from dataframe """
data = df.copy()
data['lemma'] = data['query'].apply(lambda x:' '.join([token.lemma_ for token in nlp(x) if token.lemma_ not in stop_words]))
data['keyword'] = data['lemma'].apply(lambda x: list(set([token.lemma_ for token in nlp(x) if token.lemma_ in keyword_list_lemma])))
data['noun'] = data['query'].apply(lambda x: list(set([token.lemma_ for token in nlp(x) if token.pos_ in ['NOUN','PROPN'] and token.lemma_ not in stop_words])))
data['verb'] = data['query'].apply(lambda x: list(set([token.lemma_ for token in nlp(x) if token.pos_ in ['VERB'] and token.lemma_ not in stop_words])))
data['noun'] = data['noun'].apply(lambda x: ' '.join([w for w in x]))
data['verb'] = data['verb'].apply(lambda x: ' '.join([w for w in x]))
data['keyword'] = data['keyword'].apply(lambda x: ' '.join([w for w in x]))
return data
def get_distance_matrix_idf(df_test, intent_list, dict_cluster, word2vec, idf):
""" Get distance for each query to every intent center
Args:
df_test (pd.DataFrame): input test dataframe with intent and query
intent_list (list): list of intents to loop through
dict_cluster (dict): dictionary of cluster centres
word2vec (dict): word embeddings dictionary
idf (dict): idf of each words
Returns:
result (pd.DataFrame): distance matrix for each query, lowest distance intent idealy should match label
"""
df = df_test.copy()
for intent in intent_list:
# distance = cosine_similarity(sentence embedding, intent cluster centre embedding)
df[intent] = df['query'].apply(lambda x: cosine_distances(get_sentence_vec(x, word2vec, idf).reshape(1,-1),
dict_cluster[intent].reshape(1,-1)).item())
return df
def get_sentence_vec(sentence, word2vec, idf=None):
""" Get embedding of sentence by using word2vec embedding of words
If idf is provided, the sentence is the weighted embedding by
SUM( embedding[word] x idf[word] )
Args:
sentence (str): input sentence
word2vec (dict): loaded word2vec model from Gensim
idf (dict, optional): inverse document frequency of words in all queries
Returns:
emb (np.array): 300-dimentions embedding of sentence
"""
words = sentence.split()
words = [word for word in words if word in word2vec.vocab]
# if no word in word2vec vocab, return 0x300 embedding
if len(words)==0:
return np.zeros((300,), dtype='float32')
# use mean if no idf provided
if idf is None:
emb = word2vec[words].mean(axis=0)
else:
# get all idf of words, if new word is not in idf, assign 0.0 weights
idf_series = np.array([idf.get(word, 0.0) for word in words])
# change shape to 1 x num_of_words
idf_series = idf_series.reshape(1, -1)
# use matrix multiplication to get weighted word vector sum for sentence embeddings
emb = np.matmul(idf_series, word2vec[words]).reshape(-1)
return emb
def clean_text(text):
""" Basic text cleaning
1. lowercase
2. remove special characters
"""
text = text.lower()
text = re.sub(r'[^a-z0-9\s]', '', text)
return text
def nltk_tokenize(text):
""" tokenize text using NLTK and join back as sentence"""
# import nltk
# nltk.download('punkt')
return ' '.join(word_tokenize(text))
def get_top_3(data, intent_list):
data = data.copy()
cluster_cols = intent_list.copy()
data['clusters_top3'] = data.apply(lambda x: np.argsort(x[cluster_cols].values)[:3].tolist(), axis=1)
top_clusters_cols = pd.DataFrame(data['clusters_top3'].values.tolist(),columns = ['clusters_1','clusters_2','clusters_3']).reset_index(drop=True)
data = data.reset_index(drop=True)
data = pd.concat([data,top_clusters_cols], axis=1)
data.drop(columns = 'clusters_top3', inplace=True)
data.drop(columns = cluster_cols, inplace=True)
# print(data.head())
return data
def add_nlp_vec(df, v_lemma, v_keyword, v_noun, v_verb, top_clusters_cols):
""" Transform NLP features to vector for input X using TFIDF """
x_test_lemma = v_lemma.transform(df['lemma'])
x_test_keyword = v_keyword.transform(df['keyword'])
x_test_noun = v_noun.transform(df['noun'])
x_test_verb = v_verb.transform(df['verb'])
# combine all features
x_test_combined = hstack((x_test_lemma,
x_test_keyword,
x_test_noun,
x_test_verb,
df[top_clusters_cols].values),format='csr')
x_test_combined_columns = v_lemma.get_feature_names()+\
v_keyword.get_feature_names()+\
v_noun.get_feature_names()+\
v_verb.get_feature_names()+\
top_clusters_cols
x_test_combined = pd.DataFrame(x_test_combined.toarray())
x_test_combined.columns = x_test_combined_columns
return x_test_combined
def get_target_name(index, index2intent):
return index2intent[index]
|
[
"pandas.DataFrame",
"numpy.zeros",
"time.time",
"numpy.argsort",
"spacy.load",
"pathlib.Path",
"pickle.load",
"scipy.sparse.hstack",
"gensim.models.KeyedVectors.load_word2vec_format",
"numpy.matmul",
"re.sub",
"pandas.concat",
"nltk.tokenize.word_tokenize"
] |
[((644, 655), 'time.time', 'time.time', ([], {}), '()\n', (653, 655), False, 'import time\n'), ((806, 834), 'spacy.load', 'spacy.load', (['"""en_core_web_sm"""'], {}), "('en_core_web_sm')\n", (816, 834), False, 'import spacy\n'), ((2050, 2112), 'gensim.models.KeyedVectors.load_word2vec_format', 'KeyedVectors.load_word2vec_format', (['EMBEDDING_FILE'], {'binary': '(True)'}), '(EMBEDDING_FILE, binary=True)\n', (2083, 2112), False, 'from gensim.models import KeyedVectors\n'), ((486, 500), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (490, 500), False, 'from pathlib import Path\n'), ((972, 986), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (983, 986), False, 'import pickle\n'), ((1088, 1102), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1099, 1102), False, 'import pickle\n'), ((1189, 1203), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1200, 1203), False, 'import pickle\n'), ((1284, 1298), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1295, 1298), False, 'import pickle\n'), ((1379, 1393), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1390, 1393), False, 'import pickle\n'), ((1490, 1504), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1501, 1504), False, 'import pickle\n'), ((1610, 1624), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1621, 1624), False, 'import pickle\n'), ((1697, 1711), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1708, 1711), False, 'import pickle\n'), ((1811, 1825), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1822, 1825), False, 'import pickle\n'), ((1943, 1957), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1954, 1957), False, 'import pickle\n'), ((2124, 2135), 'time.time', 'time.time', ([], {}), '()\n', (2133, 2135), False, 'import time\n'), ((2472, 2483), 'time.time', 'time.time', ([], {}), '()\n', (2481, 2483), False, 'import time\n'), ((2547, 2561), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2559, 2561), True, 'import pandas as pd\n'), ((2571, 2602), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['query']"}), "(columns=['query'])\n", (2583, 2602), True, 'import pandas as pd\n'), ((3696, 3747), 'pandas.DataFrame', 'pd.DataFrame', (['ind'], {'columns': "['top3', 'top2', 'top1']"}), "(ind, columns=['top3', 'top2', 'top1'])\n", (3708, 3747), True, 'import pandas as pd\n'), ((5135, 5320), 'pandas.DataFrame', 'pd.DataFrame', (['[[1, top1_class, top1, top1_prob], [2, top2_class, top2, top2_prob], [3,\n top3_class, top3, top3_prob]]'], {'columns': "['pred_seq', 'intent_class', 'intent', 'pred_prob']"}), "([[1, top1_class, top1, top1_prob], [2, top2_class, top2,\n top2_prob], [3, top3_class, top3, top3_prob]], columns=['pred_seq',\n 'intent_class', 'intent', 'pred_prob'])\n", (5147, 5320), True, 'import pandas as pd\n'), ((9397, 9429), 're.sub', 're.sub', (['"""[^a-z0-9\\\\s]"""', '""""""', 'text'], {}), "('[^a-z0-9\\\\s]', '', text)\n", (9403, 9429), False, 'import re\n'), ((10026, 10070), 'pandas.concat', 'pd.concat', (['[data, top_clusters_cols]'], {'axis': '(1)'}), '([data, top_clusters_cols], axis=1)\n', (10035, 10070), True, 'import pandas as pd\n'), ((10625, 10738), 'scipy.sparse.hstack', 'hstack', (['(x_test_lemma, x_test_keyword, x_test_noun, x_test_verb, df[\n top_clusters_cols].values)'], {'format': '"""csr"""'}), "((x_test_lemma, x_test_keyword, x_test_noun, x_test_verb, df[\n top_clusters_cols].values), format='csr')\n", (10631, 10738), False, 'from scipy.sparse import hstack\n'), ((3560, 3585), 'numpy.argsort', 'np.argsort', (['probs'], {'axis': '(1)'}), '(probs, axis=1)\n', (3570, 3585), True, 'import numpy as np\n'), ((5381, 5392), 'time.time', 'time.time', ([], {}), '()\n', (5390, 5392), False, 'import time\n'), ((8680, 8713), 'numpy.zeros', 'np.zeros', (['(300,)'], {'dtype': '"""float32"""'}), "((300,), dtype='float32')\n", (8688, 8713), True, 'import numpy as np\n'), ((9601, 9620), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['text'], {}), '(text)\n', (9614, 9620), False, 'from nltk.tokenize import word_tokenize\n'), ((9170, 9208), 'numpy.matmul', 'np.matmul', (['idf_series', 'word2vec[words]'], {}), '(idf_series, word2vec[words])\n', (9179, 9208), True, 'import numpy as np\n'), ((9768, 9802), 'numpy.argsort', 'np.argsort', (['x[cluster_cols].values'], {}), '(x[cluster_cols].values)\n', (9778, 9802), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
# =============================================================================
# 2mmn40 week 3 report
# version 2017-12-03 afternoon
# BA
#
#
# for BA: Make sure to run in directory
# C:\Users\20165263\Dropbox\tue\2mmn40\src
#
# =============================================================================
import numpy as np
import matplotlib.pyplot as plt
# Objective: simulate a diatomic bond. So we're just integrating f=ma over t.
# To integrate f=ma, we need f, m, v0 and q0.
# f is obtained from potentials. f = -grad u
# m, v0, x0 are all given.
# Data structure required: molecule geometry. So, a list of lists of molecules.
# Each molecule needs to have a mass, an x0, a v0, and explicitly
### part 1: diatomic molecule
#molecule parameters
bondList = [[1],[0]]
kbond = 1.0
rbond = 1.0
m = np.array([1.0, 1.0])
#simulation parameters: choice of integrator
# 0 - forward euler
# 1 - verlet
# 2 - velocity verlet
integrator = 0
maxsteps = 1000
# take a small enough timestep
dt = min(np.sqrt( kbond/m )) /100
#initial values
q0 = np.array([[0.0, 0.1, -0.1],
[1.01, 0.9, 0.95]])
v0 = np.array([[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0]])
#initialize system state
q = q0.copy()
v = v0.copy()
#find distance: r and dr
dr = q - q[:, np.newaxis]
r = np.linalg.norm(dr, axis=2)
# find bond forces
# will throw a RuntimeWarning due to the dividing by zero along diagonal elements of r.
# However, nan_to_num converts those nan's to zero in the result, so ignore the warning.
# A particle cannot exert a force on itself, so that makes sense
fbond = np.nan_to_num( -kbond * dr * (rbond - r[:,:,np.newaxis]) / r[:,:,np.newaxis])
ftotal = np.sum(fbond,axis=1)
#integrate a single step:
if integrator == 0:
q += dt*v + dt**2 /(2*m[:,np.newaxis]) *ftotal
v += dt/m[:,np.newaxis] *ftotal
elif integrator == 1:
#Verlet integration step
q += 0
elif integrator == 2:
#Velocity Verlect integration step
q += 0
else:
raise ('Unkown integrator selected')
|
[
"numpy.sum",
"numpy.nan_to_num",
"numpy.linalg.norm",
"numpy.array",
"numpy.sqrt"
] |
[((836, 856), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (844, 856), True, 'import numpy as np\n'), ((1078, 1125), 'numpy.array', 'np.array', (['[[0.0, 0.1, -0.1], [1.01, 0.9, 0.95]]'], {}), '([[0.0, 0.1, -0.1], [1.01, 0.9, 0.95]])\n', (1086, 1125), True, 'import numpy as np\n'), ((1147, 1191), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])\n', (1155, 1191), True, 'import numpy as np\n'), ((1318, 1344), 'numpy.linalg.norm', 'np.linalg.norm', (['dr'], {'axis': '(2)'}), '(dr, axis=2)\n', (1332, 1344), True, 'import numpy as np\n'), ((1615, 1700), 'numpy.nan_to_num', 'np.nan_to_num', (['(-kbond * dr * (rbond - r[:, :, np.newaxis]) / r[:, :, np.newaxis])'], {}), '(-kbond * dr * (rbond - r[:, :, np.newaxis]) / r[:, :, np.newaxis]\n )\n', (1628, 1700), True, 'import numpy as np\n'), ((1702, 1723), 'numpy.sum', 'np.sum', (['fbond'], {'axis': '(1)'}), '(fbond, axis=1)\n', (1708, 1723), True, 'import numpy as np\n'), ((1031, 1049), 'numpy.sqrt', 'np.sqrt', (['(kbond / m)'], {}), '(kbond / m)\n', (1038, 1049), True, 'import numpy as np\n')]
|
"""
Heuristic agents for various OpenAI Gym environments. The agent policies, in
this case, are deterministic functions, and often handcrafted or found by
non-gradient optimization algorithms, such as evolutionary strategies.
Many of the heuristic policies were adapted from the following source:
```
@book{xiao2022,
title = {Reinforcement Learning: Theory and {Python} Implementation},
author = {<NAME>}
publisher = {Springer Nature},
}
```
"""
from typing import Dict
import numpy as np
import torch
from ilpyt.agents.base_agent import BaseAgent
class LunarLanderContinuousHeuristicAgent(BaseAgent):
"""
Heuristic policy for the OpenAI Gym LunarLanderContinuous-v2 environment.
Adapted from the OpenAI Gym repository:
https://github.com/openai/gym/blob/master/gym/envs/box2d/lunar_lander.py
"""
def initialize(self) -> None:
"""
Pass. Heuristic agents do not require any initialization."
"""
pass
def step(self, state: torch.Tensor) -> np.ndarray:
"""
Find best action for the given state.
Parameters
----------
state: torch.Tensor
state tensor, of size (batch_size, 8) with attributes
[horizontal coordinate, vertical coordinate, horizontal speed,
vertical speed, angle, angular speed, first leg contact,
second leg contact]
Returns
-------
np.ndarray:
selected actions, of size (batch_size, 2)
"""
batch_size = len(state)
angle_targ = (
state[:, 0] * 0.5 + state[:, 2] * 1.0
) # angle point towards center
angle_targ = torch.clip(angle_targ, -0.4, 0.4)
hover_targ = 0.55 * torch.abs(state[:, 0]) # target y proportional to
# horizontal offset
angle = (angle_targ - state[:, 4]) * 0.5 - (state[:, 5]) * 1.0
hover = (hover_targ - state[:, 1]) * 0.5 - (state[:, 3]) * 0.5
for i in range(batch_size):
if state[i, 6] or state[i, 7]: # legs have contact
angle[i] = 0
hover[i] = -(state[i, 3]) * 0.5 # override to reduce fall speed
a = torch.stack([hover * 20 - 1, -angle * 20], dim=-1)
a = torch.clamp(a, -1, +1)
return a.cpu().numpy()
def update(self, batch: Dict[str, torch.Tensor]) -> Dict[str, float]:
"""
Pass. Heuristic agents do not update their agent policies.
"""
return {}
class LunarLanderHeuristicAgent(BaseAgent):
"""
Heuristic policy for the OpenAI Gym LunarLander-v2 environment.
Adapted from the book 'Reinforcement Learning: Theory and Python Implementation':
https://github.com/openai/gym/blob/master/gym/envs/box2d/lunar_lander.py
"""
def initialize(self):
"""
Pass. Heuristic agents do not require any initialization."
"""
pass
def step(self, state: torch.Tensor):
"""
Find best action for the given state.
Parameters
----------
state (torch.Tensor):
state tensor, of size (batch_size, 8) with attributes
[horizontal coordinate, vertical coordinate, horizontal speed,
vertical speed, angle, angular speed, first leg contact,
second leg contact]
Returns
-------
np.ndarray:
selected actions, of size (batch_size, action_shape)
"""
batch_size = len(state)
angle_targ = (
state[:, 0] * 0.5 + state[:, 2] * 1.0
) # angle point towards center
angle_targ = torch.clip(angle_targ, -0.4, 0.4)
hover_targ = 0.55 * torch.abs(state[:, 0]) # target y proportional to
# horizontal offset
angle = (angle_targ - state[:, 4]) * 0.5 - (state[:, 5]) * 1.0
hover = (hover_targ - state[:, 1]) * 0.5 - (state[:, 3]) * 0.5
for i in range(batch_size):
if state[i, 6] or state[i, 7]: # legs have contact
angle[i] = 0
hover[i] = -(state[i, 3]) * 0.5 # override to reduce fall speed
a = np.zeros(batch_size, dtype=np.uint8)
for i in range(batch_size):
if hover[i] > torch.abs(angle[i]) and hover[i] > 0.05:
a[i] = 2
elif angle[i] < -0.05:
a[i] = 3
elif angle[i] > +0.05:
a[i] = 1
return a
def update(self, batch: Dict[str, torch.Tensor]) -> Dict[str, float]:
"""
Pass. Heuristic agents do not update their agent policies.
"""
return {}
class CartPoleHeuristicAgent(BaseAgent):
"""
Heuristic agent for the OpenAI Gym CartPole-v0 environment.
Adapted from the book 'Reinforcement Learning: Theory and Python Implementation':
https://github.com/ZhiqingXiao/OpenAIGymSolution
"""
def initialize(self):
"""
Pass. Heuristic agents do not require any initialization."
"""
pass
def step(self, state: torch.Tensor) -> np.ndarray:
"""
Find best action for the given state. The overall policy followed by the
CartPole agent: push right when 3*angle + angle_velocity > 0.
Parameters
----------
state: torch.Tensor
state tensor of size (batch_size, 4) with attributes
[cart position, cart velocity, pole angle, pole velocity at tip]
Returns
-------
np.ndarray:
action, of shape (batch_size, ) where 0= push cart to left, 1 = push cart to right
"""
angle, angle_velocity = state[:, 2], state[:, 3]
a = (3 * angle + angle_velocity) > 0
return a.cpu().long().numpy()
def update(self, batch: Dict[str, torch.Tensor]) -> Dict[str, float]:
"""
Pass. Heuristic agents do not update their agent policies.
"""
return {}
class MountainCarHeuristicAgent(BaseAgent):
"""
Fixed deterministic policy for the OpenAI gym MountainCar-v0 environment.
Adapted from the book 'Reinforcement Learning: Theory and Python Implementation':
https://github.com/ZhiqingXiao/OpenAIGymSolution
"""
def initialize(self):
"""
Pass. Heuristic agents do not require any initialization."
"""
pass
def step(self, state: torch.Tensor) -> np.ndarray:
"""
Find best action for the given state. Push right when satisfying a
certain condition; otherwise push left.
Parameters
----------
state: torch.Tensor
state tensor of size (batch_size, 2) with attributes
[position, velocity]
Returns
-------
np.ndarray:
discrete action of shape (batch_size, ) where
0 = push left, 1 = no push, 2 = push right
"""
actions = []
positions, velocities = state[:, 0], state[:, 1]
for (position, velocity) in zip(positions, velocities):
lb = min(
-0.09 * (position + 0.25) ** 2 + 0.03,
0.3 * (position + 0.9) ** 4 - 0.008,
)
ub = -0.07 * (position + 0.38) ** 2 + 0.07
if lb < velocity < ub:
action = 2 # push right
else:
action = 0 # push left
actions.append(action)
return actions
def update(self, batch: Dict[str, torch.Tensor]) -> Dict[str, float]:
"""
Pass. Heuristic agents do not update their agent policies.
"""
return {}
class MountainCarContinuousHeuristicAgent(BaseAgent):
"""
Heuristic agent for the OpenAI Gym MountainCarContinuous-v0 environment.
Adapted from the book 'Reinforcement Learning: Theory and Python Implementation':
https://github.com/ZhiqingXiao/OpenAIGymSolution
"""
def initialize(self):
"""
Pass. Heuristic agents do not require any initialization."
"""
pass
def step(self, state: torch.Tensor) -> np.ndarray:
"""
Find best action for the given state. Push right when satisfying a
certain condition; otherwise push left.
Parameters
----------
state: torch.Tensor
state tensor of size (batch_size, 2) with attributes
[position, velocity]
Returns
-------
np.ndarray:
continuous action of shape (batch_size, ) - pushing the car to the
left or to the right
"""
positions, velocities = state[:, 0], state[:, 1]
actions = []
for (position, velocity) in zip(positions, velocities):
if position > -4 * velocity or position < 13 * velocity - 0.6:
force = 1.0
else:
force = -1.0
actions.append(
[
force,
]
)
return actions
def update(self, batch: Dict[str, torch.Tensor]) -> Dict[str, float]:
"""
Pass. Heuristic agents do not update their agent policies.
"""
return {}
|
[
"torch.stack",
"numpy.zeros",
"torch.clip",
"torch.clamp",
"torch.abs"
] |
[((1686, 1719), 'torch.clip', 'torch.clip', (['angle_targ', '(-0.4)', '(0.4)'], {}), '(angle_targ, -0.4, 0.4)\n', (1696, 1719), False, 'import torch\n'), ((2194, 2244), 'torch.stack', 'torch.stack', (['[hover * 20 - 1, -angle * 20]'], {'dim': '(-1)'}), '([hover * 20 - 1, -angle * 20], dim=-1)\n', (2205, 2244), False, 'import torch\n'), ((2257, 2279), 'torch.clamp', 'torch.clamp', (['a', '(-1)', '(+1)'], {}), '(a, -1, +1)\n', (2268, 2279), False, 'import torch\n'), ((3630, 3663), 'torch.clip', 'torch.clip', (['angle_targ', '(-0.4)', '(0.4)'], {}), '(angle_targ, -0.4, 0.4)\n', (3640, 3663), False, 'import torch\n'), ((4138, 4174), 'numpy.zeros', 'np.zeros', (['batch_size'], {'dtype': 'np.uint8'}), '(batch_size, dtype=np.uint8)\n', (4146, 4174), True, 'import numpy as np\n'), ((1748, 1770), 'torch.abs', 'torch.abs', (['state[:, 0]'], {}), '(state[:, 0])\n', (1757, 1770), False, 'import torch\n'), ((3692, 3714), 'torch.abs', 'torch.abs', (['state[:, 0]'], {}), '(state[:, 0])\n', (3701, 3714), False, 'import torch\n'), ((4237, 4256), 'torch.abs', 'torch.abs', (['angle[i]'], {}), '(angle[i])\n', (4246, 4256), False, 'import torch\n')]
|
import numpy as np
import tensorflow as tf
from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch, lstm, lnlstm, sample
class CnnPolicy(object):
def __init__(self, sess, ob_space, ac_space, nenv, nsteps, nstack, reuse=False):
nbatch = nenv*nsteps
#nh, nw, nc = ob_space.shape
nh,nw,nc = 1,1,2
ob_shape = (nbatch, nh, nw, nc*nstack)
nact = ac_space.n
X = tf.placeholder(tf.uint8, shape=[nbatch,nh,nw,nc*nstack]) #obs
with tf.variable_scope("model", reuse=reuse):
h = conv(tf.cast(X, tf.float32)/255., 'c1', nf=32, rf=1, stride=1, init_scale=np.sqrt(2))
h2 = conv(h, 'c2', nf=64, rf=1, stride=1, init_scale=np.sqrt(2))
h3 = conv(h2, 'c3', nf=64, rf=1, stride=1, init_scale=np.sqrt(2))
h3 = conv_to_fc(h3)
h4 = fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2))
pi = fc(h4, 'pi', nact, act=lambda x:x)
vf = fc(h4, 'v', 1, act=lambda x:x)
""" The part of the model that predicts the progress through the
environment we don't actually have to predict the number of frames.
Could just have a monotonically increasing prediction. This is
enough to enforce that the model learns an order to the states that
corresponds to progress."""
progressf = fc(h4, 'progress', 1, act=lambda x:x) # default act is relu
v0 = vf[:, 0]
progress0 = progressf[:, 0]
a0 = sample(pi)
self.initial_state = [] #not stateful
def step(ob, *_args, **_kwargs):
a, v, p = sess.run([a0, v0, progress0], {X:ob})
return a, v, [], p #[] is a dummy state
def value(ob, *_args, **_kwargs):
return sess.run(v0, {X:ob})
self.X = X
self.pi = pi
self.vf = vf
self.step = step
self.value = value
self.progress = progress0
|
[
"baselines.a2c.utils.sample",
"tensorflow.variable_scope",
"tensorflow.placeholder",
"tensorflow.cast",
"baselines.a2c.utils.conv_to_fc",
"baselines.a2c.utils.fc",
"numpy.sqrt"
] |
[((435, 496), 'tensorflow.placeholder', 'tf.placeholder', (['tf.uint8'], {'shape': '[nbatch, nh, nw, nc * nstack]'}), '(tf.uint8, shape=[nbatch, nh, nw, nc * nstack])\n', (449, 496), True, 'import tensorflow as tf\n'), ((1515, 1525), 'baselines.a2c.utils.sample', 'sample', (['pi'], {}), '(pi)\n', (1521, 1525), False, 'from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch, lstm, lnlstm, sample\n'), ((510, 549), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""model"""'], {'reuse': 'reuse'}), "('model', reuse=reuse)\n", (527, 549), True, 'import tensorflow as tf\n'), ((825, 839), 'baselines.a2c.utils.conv_to_fc', 'conv_to_fc', (['h3'], {}), '(h3)\n', (835, 839), False, 'from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch, lstm, lnlstm, sample\n'), ((919, 954), 'baselines.a2c.utils.fc', 'fc', (['h4', '"""pi"""', 'nact'], {'act': '(lambda x: x)'}), "(h4, 'pi', nact, act=lambda x: x)\n", (921, 954), False, 'from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch, lstm, lnlstm, sample\n'), ((972, 1003), 'baselines.a2c.utils.fc', 'fc', (['h4', '"""v"""', '(1)'], {'act': '(lambda x: x)'}), "(h4, 'v', 1, act=lambda x: x)\n", (974, 1003), False, 'from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch, lstm, lnlstm, sample\n'), ((1383, 1421), 'baselines.a2c.utils.fc', 'fc', (['h4', '"""progress"""', '(1)'], {'act': '(lambda x: x)'}), "(h4, 'progress', 1, act=lambda x: x)\n", (1385, 1421), False, 'from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch, lstm, lnlstm, sample\n'), ((572, 594), 'tensorflow.cast', 'tf.cast', (['X', 'tf.float32'], {}), '(X, tf.float32)\n', (579, 594), True, 'import tensorflow as tf\n'), ((641, 651), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (648, 651), True, 'import numpy as np\n'), ((718, 728), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (725, 728), True, 'import numpy as np\n'), ((796, 806), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (803, 806), True, 'import numpy as np\n'), ((890, 900), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (897, 900), True, 'import numpy as np\n')]
|
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import unittest
import numpy as np
from openvino.tools.mo.middle.dequantize_linear_resolver import DequantizeLinearResolver
from openvino.tools.mo.front.common.partial_infer.utils import int64_array
from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs
from unit_tests.utils.graph import build_graph
from generator import generator, generate
nodes1_attributes = {
'input': {'kind': 'op', 'op': 'AnyOp'},
'input_data': {'kind': 'data', 'shape': None},
'dequantize': {'kind': 'op', 'op': 'DequantizeLinear', 'axis': 1},
'dequantize_data': {'kind': 'data', 'shape': None},
'scale_param_dq': {'kind': 'op', 'type': 'Const', 'op': 'Const'},
'scale_param_dq_data': {'kind': 'data', 'shape': None},
'zerop_param_dq': {'kind': 'op', 'type': 'Const', 'op': 'Const'},
'zerop_param_dq_data': {'kind': 'data', 'shape': None},
'out': {'kind': 'op', 'op': 'AnyOp'},
'out_data': {'kind': 'data', 'shape': None},
'result': {'kind': 'op', 'op': 'Result'},
}
nodes_ref_attributes = {
'input': {'kind': 'op', 'op': 'AnyOp'},
'input_data': {'kind': 'data', 'shape': None},
'cast': {'kind': 'op', 'op': 'Cast', 'type': 'Convert'},
'cast_data': {'kind': 'data', 'shape': None},
'sub': {'kind': 'op', 'op': 'Sub', 'type': 'Subtract'},
'sub_data': {'kind': 'data', 'shape': None},
'mul': {'kind': 'op', 'op': 'Mul', 'type': 'Multiply'},
'mul_data': {'kind': 'data', 'shape': None},
'scale_param_dq': {'kind': 'op', 'type': 'Const', 'op': 'Const'},
'scale_param_dq_data': {'kind': 'data', 'shape': None},
'zerop_param_dq': {'kind': 'op', 'type': 'Const', 'op': 'Const'},
'zerop_param_dq_data': {'kind': 'data', 'shape': None},
'out': {'kind': 'op', 'op': 'AnyOp'},
'out_data': {'kind': 'data', 'shape': None},
'result': {'kind': 'op', 'op': 'Result'},
'sub_reshape_const': {'kind': 'op', 'type': 'Const', 'op': 'Const'},
'sub_reshape_const_data': {'kind': 'data', 'shape': None},
'sub_reshape': {'kind': 'op', 'type': 'Reshape', 'op': 'Reshape'},
'sub_reshape_data': {'kind': 'data', 'shape': None},
'mul_reshape_const': {'kind': 'op', 'type': 'Const', 'op': 'Const'},
'mul_reshape_const_data': {'kind': 'data', 'shape': None},
'mul_reshape': {'kind': 'op', 'type': 'Reshape', 'op': 'Reshape'},
'mul_reshape_data': {'kind': 'data', 'shape': None},
}
class TestDequantizeLinearResolver(unittest.TestCase):
def test_dequantize(self):
graph = build_graph(nodes1_attributes,
[('input', 'input_data'),
('input_data', 'dequantize'),
('dequantize', 'dequantize_data'),
('scale_param_dq', 'scale_param_dq_data'),
('zerop_param_dq', 'zerop_param_dq_data'),
('scale_param_dq_data', 'dequantize'),
('zerop_param_dq_data', 'dequantize'),
('dequantize_data', 'out'),
('out', 'out_data'),
('out_data', 'result'),
],
{'input_data': {'shape': int64_array([1, 3, 224, 224])},
'scale_param_dq': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
'scale_param_dq_data': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
'zerop_param_dq': {'shape': np.array([]), 'value': np.uint8(0)},
'zerop_param_dq_data': {'shape': np.array([]), 'value': np.uint8(0)},
}, nodes_with_edges_only=True)
graph_ref = build_graph(nodes_ref_attributes,
[('input', 'input_data'),
('input_data', 'cast'),
('cast', 'cast_data'),
('cast_data', 'sub'),
('zerop_param_dq', 'zerop_param_dq_data'),
('zerop_param_dq_data', 'sub'),
('sub', 'sub_data'),
('sub_data', 'mul'),
('scale_param_dq', 'scale_param_dq_data'),
('scale_param_dq_data', 'mul'),
('mul', 'mul_data'),
('mul_data', 'out'),
('out', 'out_data'),
('out_data', 'result'),
],
{'input_data': {'shape': int64_array([1, 3, 224, 224])},
'scale_param_dq': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
'scale_param_dq_data': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
'zerop_param_dq': {'shape': np.array([]), 'value': np.uint8(0)},
'zerop_param_dq_data': {'shape': np.array([]), 'value': np.uint8(0)},
}, nodes_with_edges_only=True)
graph.stage = 'middle'
DequantizeLinearResolver().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, graph_ref, 'out', check_op_attrs=True)
self.assertTrue(flag, resp)
def test_dequantize_no_zerop(self):
graph = build_graph(nodes1_attributes,
[('input', 'input_data'),
('input_data', 'dequantize'),
('dequantize', 'dequantize_data'),
('scale_param_dq', 'scale_param_dq_data'),
('scale_param_dq_data', 'dequantize'),
('dequantize', 'dequantize_data'),
('dequantize_data', 'out'),
('out', 'out_data'),
('out_data', 'result'),
],
{'input_data': {'shape': int64_array([1, 3, 224, 224])},
'scale_param_dq': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
'scale_param_dq_data': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
}, nodes_with_edges_only=True)
graph_ref = build_graph(nodes_ref_attributes,
[('input', 'input_data'),
('input_data', 'cast'),
('cast', 'cast_data'),
('cast_data', 'mul'),
('scale_param_dq', 'scale_param_dq_data'),
('scale_param_dq_data', 'mul'),
('mul', 'mul_data'),
('mul_data', 'out'),
('out', 'out_data'),
('out_data', 'result'),
],
{'input_data': {'shape': int64_array([1, 3, 224, 224])},
'scale_param_dq': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
'scale_param_dq_data': {'shape': np.array([]), 'value': np.float32(1.0 / 255)},
}, nodes_with_edges_only=True)
graph.stage = 'middle'
DequantizeLinearResolver().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, graph_ref, 'out', check_op_attrs=True)
self.assertTrue(flag, resp)
@generator
class TestDequantizeWithAxis(unittest.TestCase):
@generate(*[(int64_array([1, 3, 4, 4]), np.array([2, 3, 4, 5], dtype=np.float32),
np.array([2, 3, 4, 5], dtype=np.uint8), int64_array([1, 1, 4, 1]), 2),
(int64_array([1, 3, 4, 4]), int64_array([2, 3, 4, 5]),
np.array([2, 3, 4, 5], dtype=np.uint8), int64_array([1, 3, 1, 1]), 1),
(int64_array([2, 3, 4, 4]), int64_array([2, 3, 4, 5]),
np.array([2, 3, 4, 5], dtype=np.uint8), int64_array([2, 1, 1, 1]), 0),
(int64_array([1, 3, 4, 4]), int64_array([2, 3, 4, 5]),
np.array([2, 3, 4, 5], dtype=np.uint8), int64_array([1, 1, 4, 1]), -2),
(int64_array([1, 3, 4, 4]), int64_array([2, 3, 4, 5]),
np.array([2, 3, 4, 5], dtype=np.uint8), int64_array([1, 1, 1, 4]), -1),
(int64_array([1, 3, 4, 4]), int64_array([2, 3, 4, 5]),
np.array([2, 3, 4, 5], dtype=np.int32), int64_array([1, 1, 4, 1]), 2),
(int64_array([1, 3, 4, 4]), int64_array([2, 3, 4, 5]),
np.array([2, 3, 4, 5], dtype=np.int32), int64_array([1, 3, 1, 1]), 1),
(int64_array([2, 3, 4, 4]), int64_array([2, 3, 4, 5]),
np.array([2, 3, 4, 5], dtype=np.int32), int64_array([2, 1, 1, 1]), 0),
])
def test_dequantize_with_axis(self, input_shape, scale_param_value, zero_param_value, target_shape, axis):
graph = build_graph(nodes1_attributes,
[('input', 'input_data'),
('input_data', 'dequantize'),
('dequantize', 'dequantize_data'),
('scale_param_dq', 'scale_param_dq_data'),
('zerop_param_dq', 'zerop_param_dq_data'),
('scale_param_dq_data', 'dequantize'),
('zerop_param_dq_data', 'dequantize'),
('dequantize_data', 'out'),
('out', 'out_data'),
('out_data', 'result'),
],
{'input_data': {'shape': input_shape},
'dequantize': {'axis': axis},
'scale_param_dq': {'shape': scale_param_value.shape,
'value': scale_param_value},
'scale_param_dq_data': {'shape': scale_param_value.shape,
'value': scale_param_value},
'zerop_param_dq': {'shape': zero_param_value.shape,
'value': zero_param_value},
'zerop_param_dq_data': {'shape': zero_param_value.shape,
'value': zero_param_value},
}, nodes_with_edges_only=True)
graph_ref = build_graph(nodes_ref_attributes,
[('input', 'input_data'),
('input_data', 'cast'),
('cast', 'cast_data'),
('cast_data', 'sub'),
('zerop_param_dq', 'zerop_param_dq_data'),
('zerop_param_dq_data', 'sub_reshape'),
('sub_reshape_const', 'sub_reshape_const_data'),
('sub_reshape_const_data', 'sub_reshape'),
('sub_reshape', 'sub_reshape_data'),
('sub_reshape_data', 'sub'),
('sub', 'sub_data'),
('sub_data', 'mul'),
('scale_param_dq', 'scale_param_dq_data'),
('scale_param_dq_data', 'mul_reshape'),
('mul_reshape_const', 'mul_reshape_const_data'),
('mul_reshape_const_data', 'mul_reshape'),
('mul_reshape', 'mul_reshape_data'),
('mul_reshape_data', 'mul'),
('mul', 'mul_data'),
('mul_data', 'out'),
('out', 'out_data'),
('out_data', 'result'),
],
{'input_data': {'shape': input_shape},
'scale_param_dq': {'shape': scale_param_value.shape,
'value': scale_param_value},
'scale_param_dq_data': {'shape': scale_param_value.shape,
'value': scale_param_value},
'zerop_param_dq': {'shape': zero_param_value.shape,
'value': zero_param_value},
'zerop_param_dq_data': {'shape': zero_param_value.shape,
'value': zero_param_value},
'sub_reshape_const_data': {'shape': target_shape.shape, 'value': target_shape},
'mul_reshape_const_data': {'shape': target_shape.shape, 'value': target_shape},
}, nodes_with_edges_only=True)
graph.stage = 'middle'
DequantizeLinearResolver().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, graph_ref, 'out', check_op_attrs=True)
self.assertTrue(flag, resp)
|
[
"openvino.tools.mo.front.common.partial_infer.utils.int64_array",
"numpy.uint8",
"openvino.tools.mo.utils.ir_engine.compare_graphs.compare_graphs",
"unit_tests.utils.graph.build_graph",
"numpy.float32",
"openvino.tools.mo.middle.dequantize_linear_resolver.DequantizeLinearResolver",
"numpy.array"
] |
[((5432, 5492), 'openvino.tools.mo.utils.ir_engine.compare_graphs.compare_graphs', 'compare_graphs', (['graph', 'graph_ref', '"""out"""'], {'check_op_attrs': '(True)'}), "(graph, graph_ref, 'out', check_op_attrs=True)\n", (5446, 5492), False, 'from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs\n'), ((7722, 7782), 'openvino.tools.mo.utils.ir_engine.compare_graphs.compare_graphs', 'compare_graphs', (['graph', 'graph_ref', '"""out"""'], {'check_op_attrs': '(True)'}), "(graph, graph_ref, 'out', check_op_attrs=True)\n", (7736, 7782), False, 'from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs\n'), ((9315, 10156), 'unit_tests.utils.graph.build_graph', 'build_graph', (['nodes1_attributes', "[('input', 'input_data'), ('input_data', 'dequantize'), ('dequantize',\n 'dequantize_data'), ('scale_param_dq', 'scale_param_dq_data'), (\n 'zerop_param_dq', 'zerop_param_dq_data'), ('scale_param_dq_data',\n 'dequantize'), ('zerop_param_dq_data', 'dequantize'), (\n 'dequantize_data', 'out'), ('out', 'out_data'), ('out_data', 'result')]", "{'input_data': {'shape': input_shape}, 'dequantize': {'axis': axis},\n 'scale_param_dq': {'shape': scale_param_value.shape, 'value':\n scale_param_value}, 'scale_param_dq_data': {'shape': scale_param_value.\n shape, 'value': scale_param_value}, 'zerop_param_dq': {'shape':\n zero_param_value.shape, 'value': zero_param_value},\n 'zerop_param_dq_data': {'shape': zero_param_value.shape, 'value':\n zero_param_value}}"], {'nodes_with_edges_only': '(True)'}), "(nodes1_attributes, [('input', 'input_data'), ('input_data',\n 'dequantize'), ('dequantize', 'dequantize_data'), ('scale_param_dq',\n 'scale_param_dq_data'), ('zerop_param_dq', 'zerop_param_dq_data'), (\n 'scale_param_dq_data', 'dequantize'), ('zerop_param_dq_data',\n 'dequantize'), ('dequantize_data', 'out'), ('out', 'out_data'), (\n 'out_data', 'result')], {'input_data': {'shape': input_shape},\n 'dequantize': {'axis': axis}, 'scale_param_dq': {'shape':\n scale_param_value.shape, 'value': scale_param_value},\n 'scale_param_dq_data': {'shape': scale_param_value.shape, 'value':\n scale_param_value}, 'zerop_param_dq': {'shape': zero_param_value.shape,\n 'value': zero_param_value}, 'zerop_param_dq_data': {'shape':\n zero_param_value.shape, 'value': zero_param_value}},\n nodes_with_edges_only=True)\n", (9326, 10156), False, 'from unit_tests.utils.graph import build_graph\n'), ((10854, 12237), 'unit_tests.utils.graph.build_graph', 'build_graph', (['nodes_ref_attributes', "[('input', 'input_data'), ('input_data', 'cast'), ('cast', 'cast_data'), (\n 'cast_data', 'sub'), ('zerop_param_dq', 'zerop_param_dq_data'), (\n 'zerop_param_dq_data', 'sub_reshape'), ('sub_reshape_const',\n 'sub_reshape_const_data'), ('sub_reshape_const_data', 'sub_reshape'), (\n 'sub_reshape', 'sub_reshape_data'), ('sub_reshape_data', 'sub'), ('sub',\n 'sub_data'), ('sub_data', 'mul'), ('scale_param_dq',\n 'scale_param_dq_data'), ('scale_param_dq_data', 'mul_reshape'), (\n 'mul_reshape_const', 'mul_reshape_const_data'), (\n 'mul_reshape_const_data', 'mul_reshape'), ('mul_reshape',\n 'mul_reshape_data'), ('mul_reshape_data', 'mul'), ('mul', 'mul_data'),\n ('mul_data', 'out'), ('out', 'out_data'), ('out_data', 'result')]", "{'input_data': {'shape': input_shape}, 'scale_param_dq': {'shape':\n scale_param_value.shape, 'value': scale_param_value},\n 'scale_param_dq_data': {'shape': scale_param_value.shape, 'value':\n scale_param_value}, 'zerop_param_dq': {'shape': zero_param_value.shape,\n 'value': zero_param_value}, 'zerop_param_dq_data': {'shape':\n zero_param_value.shape, 'value': zero_param_value},\n 'sub_reshape_const_data': {'shape': target_shape.shape, 'value':\n target_shape}, 'mul_reshape_const_data': {'shape': target_shape.shape,\n 'value': target_shape}}"], {'nodes_with_edges_only': '(True)'}), "(nodes_ref_attributes, [('input', 'input_data'), ('input_data',\n 'cast'), ('cast', 'cast_data'), ('cast_data', 'sub'), ('zerop_param_dq',\n 'zerop_param_dq_data'), ('zerop_param_dq_data', 'sub_reshape'), (\n 'sub_reshape_const', 'sub_reshape_const_data'), (\n 'sub_reshape_const_data', 'sub_reshape'), ('sub_reshape',\n 'sub_reshape_data'), ('sub_reshape_data', 'sub'), ('sub', 'sub_data'),\n ('sub_data', 'mul'), ('scale_param_dq', 'scale_param_dq_data'), (\n 'scale_param_dq_data', 'mul_reshape'), ('mul_reshape_const',\n 'mul_reshape_const_data'), ('mul_reshape_const_data', 'mul_reshape'), (\n 'mul_reshape', 'mul_reshape_data'), ('mul_reshape_data', 'mul'), ('mul',\n 'mul_data'), ('mul_data', 'out'), ('out', 'out_data'), ('out_data',\n 'result')], {'input_data': {'shape': input_shape}, 'scale_param_dq': {\n 'shape': scale_param_value.shape, 'value': scale_param_value},\n 'scale_param_dq_data': {'shape': scale_param_value.shape, 'value':\n scale_param_value}, 'zerop_param_dq': {'shape': zero_param_value.shape,\n 'value': zero_param_value}, 'zerop_param_dq_data': {'shape':\n zero_param_value.shape, 'value': zero_param_value},\n 'sub_reshape_const_data': {'shape': target_shape.shape, 'value':\n target_shape}, 'mul_reshape_const_data': {'shape': target_shape.shape,\n 'value': target_shape}}, nodes_with_edges_only=True)\n", (10865, 12237), False, 'from unit_tests.utils.graph import build_graph\n'), ((13527, 13587), 'openvino.tools.mo.utils.ir_engine.compare_graphs.compare_graphs', 'compare_graphs', (['graph', 'graph_ref', '"""out"""'], {'check_op_attrs': '(True)'}), "(graph, graph_ref, 'out', check_op_attrs=True)\n", (13541, 13587), False, 'from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs\n'), ((5349, 5375), 'openvino.tools.mo.middle.dequantize_linear_resolver.DequantizeLinearResolver', 'DequantizeLinearResolver', ([], {}), '()\n', (5373, 5375), False, 'from openvino.tools.mo.middle.dequantize_linear_resolver import DequantizeLinearResolver\n'), ((7639, 7665), 'openvino.tools.mo.middle.dequantize_linear_resolver.DequantizeLinearResolver', 'DequantizeLinearResolver', ([], {}), '()\n', (7663, 7665), False, 'from openvino.tools.mo.middle.dequantize_linear_resolver import DequantizeLinearResolver\n'), ((13444, 13470), 'openvino.tools.mo.middle.dequantize_linear_resolver.DequantizeLinearResolver', 'DequantizeLinearResolver', ([], {}), '()\n', (13468, 13470), False, 'from openvino.tools.mo.middle.dequantize_linear_resolver import DequantizeLinearResolver\n'), ((3310, 3339), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 224, 224]'], {}), '([1, 3, 224, 224])\n', (3321, 3339), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3399, 3411), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3407, 3411), True, 'import numpy as np\n'), ((3422, 3443), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (3432, 3443), True, 'import numpy as np\n'), ((3508, 3520), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3516, 3520), True, 'import numpy as np\n'), ((3531, 3552), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (3541, 3552), True, 'import numpy as np\n'), ((3612, 3624), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3620, 3624), True, 'import numpy as np\n'), ((3635, 3646), 'numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (3643, 3646), True, 'import numpy as np\n'), ((3711, 3723), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3719, 3723), True, 'import numpy as np\n'), ((3734, 3745), 'numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (3742, 3745), True, 'import numpy as np\n'), ((4791, 4820), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 224, 224]'], {}), '([1, 3, 224, 224])\n', (4802, 4820), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((4884, 4896), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4892, 4896), True, 'import numpy as np\n'), ((4907, 4928), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (4917, 4928), True, 'import numpy as np\n'), ((4997, 5009), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5005, 5009), True, 'import numpy as np\n'), ((5020, 5041), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (5030, 5041), True, 'import numpy as np\n'), ((5105, 5117), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5113, 5117), True, 'import numpy as np\n'), ((5128, 5139), 'numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (5136, 5139), True, 'import numpy as np\n'), ((5208, 5220), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5216, 5220), True, 'import numpy as np\n'), ((5231, 5242), 'numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (5239, 5242), True, 'import numpy as np\n'), ((6243, 6272), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 224, 224]'], {}), '([1, 3, 224, 224])\n', (6254, 6272), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6332, 6344), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6340, 6344), True, 'import numpy as np\n'), ((6355, 6376), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (6365, 6376), True, 'import numpy as np\n'), ((6441, 6453), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6449, 6453), True, 'import numpy as np\n'), ((6464, 6485), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (6474, 6485), True, 'import numpy as np\n'), ((7282, 7311), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 224, 224]'], {}), '([1, 3, 224, 224])\n', (7293, 7311), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7375, 7387), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (7383, 7387), True, 'import numpy as np\n'), ((7398, 7419), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (7408, 7419), True, 'import numpy as np\n'), ((7488, 7500), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (7496, 7500), True, 'import numpy as np\n'), ((7511, 7532), 'numpy.float32', 'np.float32', (['(1.0 / 255)'], {}), '(1.0 / 255)\n', (7521, 7532), True, 'import numpy as np\n'), ((7897, 7922), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 4, 4]'], {}), '([1, 3, 4, 4])\n', (7908, 7922), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7924, 7964), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.float32'}), '([2, 3, 4, 5], dtype=np.float32)\n', (7932, 7964), True, 'import numpy as np\n'), ((7983, 8021), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.uint8'}), '([2, 3, 4, 5], dtype=np.uint8)\n', (7991, 8021), True, 'import numpy as np\n'), ((8023, 8048), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 1, 4, 1]'], {}), '([1, 1, 4, 1])\n', (8034, 8048), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8071, 8096), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 4, 4]'], {}), '([1, 3, 4, 4])\n', (8082, 8096), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8098, 8123), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (8109, 8123), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8142, 8180), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.uint8'}), '([2, 3, 4, 5], dtype=np.uint8)\n', (8150, 8180), True, 'import numpy as np\n'), ((8182, 8207), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 1, 1]'], {}), '([1, 3, 1, 1])\n', (8193, 8207), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8230, 8255), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 4]'], {}), '([2, 3, 4, 4])\n', (8241, 8255), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8257, 8282), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (8268, 8282), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8301, 8339), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.uint8'}), '([2, 3, 4, 5], dtype=np.uint8)\n', (8309, 8339), True, 'import numpy as np\n'), ((8341, 8366), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 1, 1, 1]'], {}), '([2, 1, 1, 1])\n', (8352, 8366), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8389, 8414), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 4, 4]'], {}), '([1, 3, 4, 4])\n', (8400, 8414), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8416, 8441), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (8427, 8441), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8460, 8498), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.uint8'}), '([2, 3, 4, 5], dtype=np.uint8)\n', (8468, 8498), True, 'import numpy as np\n'), ((8500, 8525), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 1, 4, 1]'], {}), '([1, 1, 4, 1])\n', (8511, 8525), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8549, 8574), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 4, 4]'], {}), '([1, 3, 4, 4])\n', (8560, 8574), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8576, 8601), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (8587, 8601), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8620, 8658), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.uint8'}), '([2, 3, 4, 5], dtype=np.uint8)\n', (8628, 8658), True, 'import numpy as np\n'), ((8660, 8685), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 1, 1, 4]'], {}), '([1, 1, 1, 4])\n', (8671, 8685), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8709, 8734), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 4, 4]'], {}), '([1, 3, 4, 4])\n', (8720, 8734), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8736, 8761), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (8747, 8761), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8780, 8818), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.int32'}), '([2, 3, 4, 5], dtype=np.int32)\n', (8788, 8818), True, 'import numpy as np\n'), ((8820, 8845), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 1, 4, 1]'], {}), '([1, 1, 4, 1])\n', (8831, 8845), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8868, 8893), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 4, 4]'], {}), '([1, 3, 4, 4])\n', (8879, 8893), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8895, 8920), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (8906, 8920), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((8939, 8977), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.int32'}), '([2, 3, 4, 5], dtype=np.int32)\n', (8947, 8977), True, 'import numpy as np\n'), ((8979, 9004), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3, 1, 1]'], {}), '([1, 3, 1, 1])\n', (8990, 9004), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((9027, 9052), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 4]'], {}), '([2, 3, 4, 4])\n', (9038, 9052), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((9054, 9079), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (9065, 9079), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((9098, 9136), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {'dtype': 'np.int32'}), '([2, 3, 4, 5], dtype=np.int32)\n', (9106, 9136), True, 'import numpy as np\n'), ((9138, 9163), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 1, 1, 1]'], {}), '([2, 1, 1, 1])\n', (9149, 9163), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n')]
|
import numpy as np
import imageio
import matplotlib.pyplot as plt
import random
import sys
import argparse
from numba import jit,jitclass,prange
from numba import int64,float64
'''
Suceptible-Infected-Removed (SIR) [012]
'''
def press(event,obj):
sys.stdout.flush()
if event.key == 'q':
if obj.save:
imageio.mimsave(obj.save_dir+obj.save_name,
obj.images,fps=30)
sys.exit(0)
spec = [('sizGrid',int64[:]),('spdConstant',float64),
('sizHuman',float64),('simTime',int64),('infR',float64),
('infP',float64),('rmT',int64),('rmP',float64),
('loc',float64[:]),('spd',float64[:]),('state',int64[:])]
@jitclass(spec)
class model:
def __init__(self,sizGrid=10,spdK=.15,
sizHuman=100,simT=1000000,
infR=.2,infP=.05,rmT=50,rmP=.1,
save=False,save_dir=None,save_name=None):
# Constant
self.sizGrid = sizGrid
self.spdConstant = spdK
self.sizHuman = sizHuman
self.simTime = simT
self.infR,self.infP = infR,infP
self.rmT,self.rmP = rmT,rmP
# Location and Speed
self.loc = self.sizGrid*np.random.uniform(0,1,
(self.sizHuman,2))
self.spd = self.spdConstant*np.random.normal(0,1,
(self.sizHuman,2))
# Infect and Remove Record
# 1st: Infect (bol), 2nd: Remove (bol), 3rd: Infect Period
self.state = np.zeros((self.sizHuman,3))
self.state[np.random.randint(0,self.sizHuman),0] = 1
# Plot attribute
self.fig = plt.figure(figsize=(10,5))
self.fig.canvas.mpl_connect('key_press_event',lambda event:press(event,self))
plt.ion()
self.t = 0
# store SIR
self.sS,self.sI,self.sR = [],[],[]
# images
self.images = []
self.save,self.save_dir,self.save_name = save,save_dir,save_name
def updatePlot(self):
ax = plt.gca(); ax.clear()
ax1 = plt.subplot(1,2,1)
ax1.clear()
rmvBol = self.state[:,1]==1
ax1.scatter(self.loc[rmvBol,0],self.loc[rmvBol,1],c='b')
infectBol = [False if rmvBol[i]==True else (self.state[i,0]==1) for i in range(self.state.shape[0])]
ax1.scatter(self.loc[infectBol,0],self.loc[infectBol,1],c='r')
susceptBol = (self.state[:,0]==0)&(self.state[:,1]==0)
ax1.scatter(self.loc[susceptBol==1,0],self.loc[susceptBol==1,1],c='g')
plt.xlim([0,self.sizGrid])
plt.ylim([0,self.sizGrid])
plt.title('Iteration {}'.format(self.t))
ax2 = plt.subplot(1,2,2)
ax2.clear()
S,I,R = np.sum(susceptBol),np.sum(infectBol),np.sum(rmvBol)
self.sS.append(S); self.sI.append(I); self.sR.append(R)
ax2.plot(self.sS,'g',label='susceptible')
ax2.annotate('{}'.format(S),(self.t,S))
ax2.plot(self.sI,'r',label='infectious')
ax2.annotate('{}'.format(I),(self.t,I))
ax2.plot(self.sR,'b',label='recovered')
ax2.annotate('{}'.format(R),(self.t,R))
plt.ylabel('Number')
plt.xlabel('Iterations')
ax2.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),shadow=True, ncol=3)
plt.show()
self.fig.canvas.draw()
image = np.frombuffer(self.fig.canvas.tostring_rgb(),dtype='uint8')
image = image.reshape(self.fig.canvas.get_width_height()[::-1]+(3,))
self.fig.canvas.flush_events()
return image
def updateLocSpd(self):
self.t+=1
self.loc += self.spd
flipx = (self.loc[:,0]<=0) | (self.loc[:,0]>=self.sizGrid)
flipy = (self.loc[:,1]<=0) | (self.loc[:,1]>=self.sizGrid)
self.spd[:,0][flipx] *= -1
self.spd[:,1][flipy] *= -1
def updateInfect(self):
infect = self.state[:,0]==1
rmv = self.state[:,1]==1
infectLoc = self.loc[infect,:]
for i in range(infectLoc.shape[0]):
tmpdist = np.linalg.norm(self.loc-infectLoc[i,:],axis=1)
potential = (tmpdist<=self.infR)
potentialP = np.random.uniform(0,1,self.sizHuman)
newInfectbol = potential*potentialP >= (1-self.infP)
infect[newInfectbol] = 1
for i in range(len(infect)):
if rmv[i] == True: infect[i] = False
self.state[:,0] = infect
self.state[:,2][infect==1] += 1
def updateRemove(self):
infect = self.state[:,0]==1
infectPeriodbol = self.state[:,2]*infect >= self.rmT
potentialP = np.random.uniform(0,1,self.sizHuman)
newRmvbol = potentialP*infectPeriodbol >= (1-self.rmP)
self.state[:,0][newRmvbol] = 0
self.state[:,1][newRmvbol] = 1
def simulate(self):
while self.t < self.simTime:
if self.t%1 == 0:
image = self.updatePlot()
if self.save:
self.images.append(image)
self.updateLocSpd()
self.updateInfect()
self.updateRemove()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Suceptible-Infectious-Removed Model')
parser.add_argument('--infR',type=float,default=.2,help='Infectious Radius')
parser.add_argument('--infP',type=float,default=.05,help='Infectious Probability')
parser.add_argument('--rmT',type=int,default=50,help='Recovered Period')
parser.add_argument('--rmP',type=float,default=.1,help='Recovered probability')
parser.add_argument('--simT',type=int,default=100000,help='simulation epochs')
parser.add_argument('--save',type=bool,default=False,help='save mode')
parser.add_argument('--save-dir',type=str,default='/home/yui/Documents/outputs/',help='save path')
parser.add_argument('--save-name',type=str,default='SIR.gif',help='save gif name')
args = parser.parse_args()
model_kwargs = {
'infR':args.infR,'infP':args.infP,
'rmT':args.rmT,'rmP':args.rmP,'simT':args.simT}
modelCov = model(**model_kwargs)
modelCov.simulate()
|
[
"numpy.sum",
"argparse.ArgumentParser",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"sys.stdout.flush",
"numpy.linalg.norm",
"numpy.random.normal",
"matplotlib.pyplot.gca",
"imageio.mimsave",
"matplotlib.pyplot.show",
"numba.jitclass",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.ylabel",
"sys.exit",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlim",
"numpy.random.uniform",
"numpy.zeros",
"matplotlib.pyplot.xlabel"
] |
[((674, 688), 'numba.jitclass', 'jitclass', (['spec'], {}), '(spec)\n', (682, 688), False, 'from numba import jit, jitclass, prange\n'), ((251, 269), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (267, 269), False, 'import sys\n'), ((5019, 5093), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Suceptible-Infectious-Removed Model"""'}), "(description='Suceptible-Infectious-Removed Model')\n", (5042, 5093), False, 'import argparse\n'), ((419, 430), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (427, 430), False, 'import sys\n'), ((1436, 1464), 'numpy.zeros', 'np.zeros', (['(self.sizHuman, 3)'], {}), '((self.sizHuman, 3))\n', (1444, 1464), True, 'import numpy as np\n'), ((1569, 1596), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (1579, 1596), True, 'import matplotlib.pyplot as plt\n'), ((1690, 1699), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1697, 1699), True, 'import matplotlib.pyplot as plt\n'), ((1936, 1945), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1943, 1945), True, 'import matplotlib.pyplot as plt\n'), ((1981, 2001), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (1992, 2001), True, 'import matplotlib.pyplot as plt\n'), ((2451, 2478), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, self.sizGrid]'], {}), '([0, self.sizGrid])\n', (2459, 2478), True, 'import matplotlib.pyplot as plt\n'), ((2486, 2513), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, self.sizGrid]'], {}), '([0, self.sizGrid])\n', (2494, 2513), True, 'import matplotlib.pyplot as plt\n'), ((2577, 2597), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (2588, 2597), True, 'import matplotlib.pyplot as plt\n'), ((3047, 3067), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number"""'], {}), "('Number')\n", (3057, 3067), True, 'import matplotlib.pyplot as plt\n'), ((3076, 3100), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iterations"""'], {}), "('Iterations')\n", (3086, 3100), True, 'import matplotlib.pyplot as plt\n'), ((3197, 3207), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3205, 3207), True, 'import matplotlib.pyplot as plt\n'), ((4495, 4533), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'self.sizHuman'], {}), '(0, 1, self.sizHuman)\n', (4512, 4533), True, 'import numpy as np\n'), ((328, 393), 'imageio.mimsave', 'imageio.mimsave', (['(obj.save_dir + obj.save_name)', 'obj.images'], {'fps': '(30)'}), '(obj.save_dir + obj.save_name, obj.images, fps=30)\n', (343, 393), False, 'import imageio\n'), ((1162, 1205), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(self.sizHuman, 2)'], {}), '(0, 1, (self.sizHuman, 2))\n', (1179, 1205), True, 'import numpy as np\n'), ((1256, 1298), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(self.sizHuman, 2)'], {}), '(0, 1, (self.sizHuman, 2))\n', (1272, 1298), True, 'import numpy as np\n'), ((2632, 2650), 'numpy.sum', 'np.sum', (['susceptBol'], {}), '(susceptBol)\n', (2638, 2650), True, 'import numpy as np\n'), ((2651, 2668), 'numpy.sum', 'np.sum', (['infectBol'], {}), '(infectBol)\n', (2657, 2668), True, 'import numpy as np\n'), ((2669, 2683), 'numpy.sum', 'np.sum', (['rmvBol'], {}), '(rmvBol)\n', (2675, 2683), True, 'import numpy as np\n'), ((3933, 3983), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.loc - infectLoc[i, :])'], {'axis': '(1)'}), '(self.loc - infectLoc[i, :], axis=1)\n', (3947, 3983), True, 'import numpy as np\n'), ((4050, 4088), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'self.sizHuman'], {}), '(0, 1, self.sizHuman)\n', (4067, 4088), True, 'import numpy as np\n'), ((1483, 1518), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.sizHuman'], {}), '(0, self.sizHuman)\n', (1500, 1518), True, 'import numpy as np\n')]
|
import numpy as np
def custom_image_generator(generator, directory, class_names, batch_size=16, target_size=(512, 512),
color_mode="grayscale", class_mode="binary", mean=None, std=None, cam=False, verbose=0):
"""
In paper chap 3.1:
we downscale the images to 1024x1024 and normalize based
on the mean and standard deviation of images in the
ImageNet training set
"""
if mean is None:
mean = np.mean(np.array([0.485, 0.456, 0.406]))
if std is None:
std = np.mean(np.array([0.229, 0.1024, 0.225]))
iterator = generator.flow_from_directory(directory=directory,
target_size=target_size,
color_mode=color_mode,
class_mode=class_mode,
batch_size=batch_size)
# class index -> xxxx|xxxx
class_indices_reversed = dict((v, k) for k, v in iterator.class_indices.items())
#print(iterator.class_indices)
stepi = 1
for batch_x, batch_y in iterator:
batch_y_multilabel = []
if(verbose > 0):
print("** Generating batch for step {} {}".format(stepi, batch_y))
stepi += 1
for i in range(batch_y.shape[0]):
# class index -> xxxx|xxxx -> one hot
one_hot_vec = label2vec(class_indices_reversed[batch_y[i]], class_names)
if(verbose > 1):
print(one_hot_vec)
batch_y_multilabel.append(one_hot_vec)
# now shape is (batch#, 14)
batch_y_multilabel = np.array(batch_y_multilabel)
# make the output [y1, y2, y3 ... y14] where yx shape is (batch#, 1)
if cam:
yield (batch_x - mean) / std, [np.array(y) for y in batch_y_multilabel.T.tolist()], batch_x
else:
yield (batch_x - mean) / std, [np.array(y) for y in batch_y_multilabel.T.tolist()]
def label2vec(label, class_names):
vec = np.zeros(len(class_names))
if label == "No Finding":
return vec
labels = label.split("|")
for l in labels:
vec[class_names.index(l)] = 1
return vec
|
[
"numpy.array"
] |
[((1637, 1665), 'numpy.array', 'np.array', (['batch_y_multilabel'], {}), '(batch_y_multilabel)\n', (1645, 1665), True, 'import numpy as np\n'), ((465, 496), 'numpy.array', 'np.array', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (473, 496), True, 'import numpy as np\n'), ((540, 572), 'numpy.array', 'np.array', (['[0.229, 0.1024, 0.225]'], {}), '([0.229, 0.1024, 0.225])\n', (548, 572), True, 'import numpy as np\n'), ((1802, 1813), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1810, 1813), True, 'import numpy as np\n'), ((1920, 1931), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1928, 1931), True, 'import numpy as np\n')]
|
import numpy as np
import Levenshtein as Lev
def cer_calculate(s1, s2, no_spaces=False):
"""
Computes the Character Error Rate, defined as the edit distance.
Arguments:
s1 (string): space-separated sentence
s2 (string): space-separated sentence
"""
if no_spaces:
s1, s2, = s1.replace(' ', ''), s2.replace(' ', '')
return min(len(s1), Lev.distance(s1, s2)) / len(s1)
def compute_accuracy(ground_truth, predictions, mode='full_sequence'):
"""
Computes accuracy
:param ground_truth:
:param predictions:
:param display: Whether to print values to stdout
:param mode: if 'per_char' is selected then
single_label_accuracy = correct_predicted_char_nums_of_single_sample / single_label_char_nums
avg_label_accuracy = sum(single_label_accuracy) / label_nums
if 'full_sequence' is selected then
single_label_accuracy = 1 if the prediction result is exactly the same as label else 0
avg_label_accuracy = sum(single_label_accuracy) / label_nums
:return: avg_label_accuracy
"""
avg_accuracy = 0
if mode == 'per_char':
accuracy = []
for index, label in enumerate(ground_truth):
prediction = predictions[index]
total_count = len(label)
correct_count = 0
try:
for i, tmp in enumerate(label):
if tmp == prediction[i]:
correct_count += 1
except IndexError:
continue
finally:
try:
accuracy.append(correct_count / total_count)
except ZeroDivisionError:
if len(prediction) == 0:
accuracy.append(1)
else:
accuracy.append(0)
avg_accuracy = np.mean(np.array(accuracy).astype(np.float32), axis=0)
elif mode == 'full_sequence':
try:
correct_count = 0
for index, label in enumerate(ground_truth):
prediction = predictions[index]
if prediction == label:
correct_count += 1
avg_accuracy = correct_count / len(ground_truth)
except ZeroDivisionError:
if not predictions:
avg_accuracy = 1
else:
avg_accuracy = 0
elif mode == 'CER':
cer_list = []
for index, label in enumerate(ground_truth):
prediction = predictions[index]
cer = cer_calculate(label, prediction)
cer_list.append(cer)
avg_accuracy = np.mean(np.array(cer_list).astype(np.float32), axis=0)
else:
raise NotImplementedError('Other accuracy compute mode has not been implemented')
return avg_accuracy
|
[
"Levenshtein.distance",
"numpy.array"
] |
[((384, 404), 'Levenshtein.distance', 'Lev.distance', (['s1', 's2'], {}), '(s1, s2)\n', (396, 404), True, 'import Levenshtein as Lev\n'), ((1917, 1935), 'numpy.array', 'np.array', (['accuracy'], {}), '(accuracy)\n', (1925, 1935), True, 'import numpy as np\n'), ((2694, 2712), 'numpy.array', 'np.array', (['cer_list'], {}), '(cer_list)\n', (2702, 2712), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 10:43:18 2019
@author: nevalaio
"""
import ee
import time
import datetime
import satelliteTools as st
import pandas as pd
from geetools import batch, tools
import numpy as np
ee.Initialize()
#----------------- Sentinel-2 -------------------------------------
def S2_getBandData_within_bbox_single_feature(S2_timseries_dataframe, aoi_shp, AOI_id_property,AOI_id, bufferdist, datestart, dateend):
bands= ['B3', 'B4','B5','B6','B7','B8A','B11','B12'] #]
# properties = ['cos(View_Zenith)', 'cos(Sun_Zenith)', 'cos(Rel_Azimuth)']
start = time.time()
image_list = {}
crs_list = {}
key = AOI_id
full_assetids = "COPERNICUS/S2_SR/" + S2_timseries_dataframe[key]['assetid']
image_list[key] = [ee.Image(a) for a in full_assetids]
crs_list[key] = [crs for crs in S2_timseries_dataframe[key]['crs']][0]
attributes = st.getShapeAtrrtibutesWithIdentifier(aoi_shp, AOI_id_property)
feature = ee.Feature(ee.Geometry.Polygon(st.wkt2coordinates(attributes[key]['geometry'])),\
{'name':key, 'image_list':image_list[key], 'crs':crs_list[key]})
if bufferdist:
bbox = ee.Feature(feature.geometry().buffer(bufferdist).bounds(0.1,feature.get("crs")))
else:
bbox = ee.Feature(feature.geometry().bounds(0.1,feature.get("crs")))
imageCollection = ee.ImageCollection.fromImages(feature.get("image_list"))\
.filterBounds(bbox.geometry())\
.filterDate(datestart,dateend)\
.select(bands)
# imageCollection = imageCollection.map(S2_addNDVI) #lisää ja laske indeksejä tässä?
def S2_getBandData_image_single_feature(img):
img = img.clip(bbox.geometry())
productid = img.get('PRODUCT_ID')
assetid = img.get('assetid')
tileid = img.get('MGRS_TILE')
system_index = img.get('system:index')
sun_azimuth = img.get('MEAN_SOLAR_AZIMUTH_ANGLE')
sun_zenith = img.get('MEAN_SOLAR_ZENITH_ANGLE')
view_azimuth = ee.Array([img.get('MEAN_INCIDENCE_AZIMUTH_ANGLE_%s'%b) for b in bands]).reduce(ee.Reducer.mean(), [0]).get([0])
view_zenith = ee.Array([img.get('MEAN_INCIDENCE_ZENITH_ANGLE_%s'%b) for b in bands]).reduce(ee.Reducer.mean(), [0]).get([0])
img = img.resample('bilinear').reproject(crs=feature.get("crs"), scale=10)
# get the lat lon and add the ndvi
image_grid = ee.Image.pixelCoordinates(ee.Projection(feature.get("crs")))\
.addBands([img.select(b) for b in bands])
# apply reducer to list
image_grid = image_grid.reduceRegion(
reducer=ee.Reducer.toList(),
geometry=bbox.geometry(),
maxPixels=1e8,
scale=10)
# get data into arrays
x_coords = ee.Array(image_grid.get("x"))
y_coords = ee.Array(image_grid.get("y"))
# band_data = []
# [band_data.extend(b,ee.Array(image_grid.get("%s"%b))) for b in bands[:-1]]
band_data = {b:ee.Array(image_grid.get("%s"%b)) for b in bands}
# NDVI_array = ee.Array(image_grid.get("NDVI"))
# B6_array = ee.Array(image_grid.get("B6"))
# perform LAI et al. computation possibly here!
tmpfeature = ee.Feature(ee.Geometry.Point([0,0]))\
.set('productid', productid)\
.set('system_index',system_index)\
.set('assetid', assetid)\
.set('tileid', tileid)\
.set('crs', feature.get("crs"))\
.set('sun_zenith',sun_zenith)\
.set('sun_azimuth',sun_azimuth)\
.set('view_zenith',view_zenith)\
.set('view_azimuth',view_azimuth)\
.set('x_coords', x_coords)\
.set('y_coords', y_coords)\
.set(band_data)
return tmpfeature
S2_single_feature_data = imageCollection.map(S2_getBandData_image_single_feature).getInfo()
end = time.time()
total_time = end - start
print ("Processsing time in seconds %s"%total_time)
return S2_single_feature_data
def S2_getBandData_within_aoi_single_feature(S2_timseries_dataframe, aoi_shp, AOI_id_property,AOI_id, datestart, dateend):
bands= ['B3', 'B4','B5','B6','B7','B8A','B11','B12'] #]
# properties = ['cos(View_Zenith)', 'cos(Sun_Zenith)', 'cos(Rel_Azimuth)']
start = time.time()
image_list = {}
crs_list = {}
key = AOI_id
full_assetids = "COPERNICUS/S2_SR/" + S2_timseries_dataframe[key]['assetid']
image_list[key] = [ee.Image(a) for a in full_assetids]
crs_list[key] = [crs for crs in S2_timseries_dataframe[key]['crs']][0]
attributes = st.getShapeAtrrtibutesWithIdentifier(aoi_shp, AOI_id_property)
feature = ee.Feature(ee.Geometry.Polygon(st.wkt2coordinates(attributes[key]['geometry'])),\
{'name':key, 'image_list':image_list[key], 'crs':crs_list[key]})
geom = feature.geometry(0.1,feature.get("crs"))
imageCollection = ee.ImageCollection.fromImages(feature.get("image_list"))\
.filterBounds(geom)\
.filterDate(datestart,dateend)\
.select(bands)
# imageCollection = imageCollection.map(S2_addNDVI) #lisää ja laske indeksejä tässä?
def S2_getBandData_image_single_feature(img):
img = img.clip(geom)
productid = img.get('PRODUCT_ID')
assetid = img.get('assetid')
tileid = img.get('MGRS_TILE')
system_index = img.get('system:index')
sun_azimuth = img.get('MEAN_SOLAR_AZIMUTH_ANGLE')
sun_zenith = img.get('MEAN_SOLAR_ZENITH_ANGLE')
view_azimuth = ee.Array([img.get('MEAN_INCIDENCE_AZIMUTH_ANGLE_%s'%b) for b in bands]).reduce(ee.Reducer.mean(), [0]).get([0])
view_zenith = ee.Array([img.get('MEAN_INCIDENCE_ZENITH_ANGLE_%s'%b) for b in bands]).reduce(ee.Reducer.mean(), [0]).get([0])
img = img.resample('bilinear').reproject(crs=feature.get("crs"), scale=10)
# get the lat lon and add the ndvi
image_grid = ee.Image.pixelCoordinates(ee.Projection(feature.get("crs")))\
.addBands([img.select(b) for b in bands])
# apply reducer to list
image_grid = image_grid.reduceRegion(
reducer=ee.Reducer.toList(),
geometry=geom,
maxPixels=1e8,
scale=10)
# get data into arrays
x_coords = ee.Array(image_grid.get("x"))
y_coords = ee.Array(image_grid.get("y"))
# band_data = []
# [band_data.extend(b,ee.Array(image_grid.get("%s"%b))) for b in bands[:-1]]
band_data = {b:ee.Array(image_grid.get("%s"%b)) for b in bands}
# NDVI_array = ee.Array(image_grid.get("NDVI"))
# B6_array = ee.Array(image_grid.get("B6"))
# perform LAI et al. computation possibly here!
tmpfeature = ee.Feature(ee.Geometry.Point([0,0]))\
.set('productid', productid)\
.set('system_index',system_index)\
.set('assetid', assetid)\
.set('tileid', tileid)\
.set('crs', feature.get("crs"))\
.set('sun_zenith',sun_zenith)\
.set('sun_azimuth',sun_azimuth)\
.set('view_zenith',view_zenith)\
.set('view_azimuth',view_azimuth)\
.set('x_coords', x_coords)\
.set('y_coords', y_coords)\
.set(band_data)
return tmpfeature
S2_single_feature_data = imageCollection.map(S2_getBandData_image_single_feature).getInfo()
end = time.time()
total_time = end - start
print ("Processsing time in seconds %s"%total_time)
return S2_single_feature_data
def S2_getBandData_single_feature_to_dict(featureDict):
featureCollection_dict = {}
for farm, featureCollection in featureDict.items():
featureCollection_dict[farm]= {'Date': []}
featureCollection_dict[farm].update({prop:[] for prop in featureCollection['features'][0]['properties'].keys()})
for featnum in range(len(featureCollection['features'])):
productid = featureCollection['features'][featnum]['properties']['productid']
date = st.sentinelTitle2Datetime(productid)
featureCollection_dict[farm]['Date'].append(date)
for prop in featureCollection['features'][featnum]['properties'].keys():
if prop is not 'Date':
featureCollection_dict[farm][prop].append(featureCollection['features'][featnum]['properties'][prop])
return featureCollection_dict
def featureCollection_dict_to_dataframes(featureCollection_dict,props):
dataframes = {}
for key, item in featureCollection_dict.items():
# dataframes[key] = pd.DataFrame({'Date': item['Date'],
# 'lai': list(np.mean(np.array(item['lai']), axis = 1)) ,
# 'lai_std': list(np.std(np.array(item['lai']), axis = 1)) })
dataframes[key] = pd.DataFrame({'Date': item['Date']})
for prop in props:
dataframes[key][prop] = list(np.mean(np.array(item[prop]), axis = 1))
dataframes[key][prop+'_std'] = list(np.std(np.array(item['lai']), axis = 1))
return dataframes
def S2_getBandData(S2_timseries_dataframe, aoi_shp, AOI_id_property, bufferdist, datestart, dateend):
bands= ['B3', 'B4','B5','B6','B7','B8A','B11','B12'] #]
# properties = ['cos(View_Zenith)', 'cos(Sun_Zenith)', 'cos(Rel_Azimuth)']
start = time.time()
image_list = {}
crs_list = {}
for key, item in S2_timseries_dataframe.items():
full_assetids = "COPERNICUS/S2_SR/" + item['assetid']
image_list[key] = [ee.Image(a) for a in full_assetids]
crs_list[key] = [crs for crs in item['crs']][0]
attributes = st.getShapeAtrrtibutesWithIdentifier(aoi_shp, AOI_id_property)
features = [ee.Feature(ee.Geometry.Polygon(st.wkt2coordinates(attributes[key]['geometry'])),\
{'name':key, 'image_list':image_list[key], 'crs':crs_list[key]}) for key,item in S2_timseries_dataframe.items()]
featureCollection = ee.FeatureCollection(features)
def S2_getBandData_feature(feature):
if bufferdist:
bbox = ee.Feature(feature.geometry().buffer(bufferdist).bounds(0.1,feature.get("crs")))
else:
bbox = ee.Feature(feature.geometry().bounds(0.1,feature.get("crs")))
imageCollection = ee.ImageCollection.fromImages(feature.get("image_list"))\
.filterBounds(bbox.geometry())\
.filterDate(datestart,dateend)\
.select(bands)
# imageCollection = imageCollection.map(S2_addNDVI) #lisää ja laske indeksejä tässä?
def S2_getBandData_image(img):
img = img.clip(bbox.geometry())
productid = img.get('PRODUCT_ID')
assetid = img.get('assetid')
tileid = img.get('MGRS_TILE')
system_index = img.get('system:index')
sun_azimuth = img.get('MEAN_SOLAR_AZIMUTH_ANGLE')
sun_zenith = img.get('MEAN_SOLAR_ZENITH_ANGLE')
view_azimuth = ee.Array([img.get('MEAN_INCIDENCE_AZIMUTH_ANGLE_%s'%b) for b in bands]).reduce(ee.Reducer.mean(), [0])
view_zenith = ee.Array([img.get('MEAN_INCIDENCE_ZENITH_ANGLE_%s'%b) for b in bands]).reduce(ee.Reducer.mean(), [0])
img = img.resample('bilinear').reproject(crs=feature.get("crs"), scale=10)
# get the lat lon and add the ndvi
image_grid = ee.Image.pixelCoordinates(ee.Projection(feature.get("crs")))\
.addBands([img.select(b) for b in bands])
# apply reducer to list
image_grid = image_grid.reduceRegion(
reducer=ee.Reducer.toList(),
geometry=bbox.geometry(),
maxPixels=1e8,
scale=10)
# get data into arrays
x_coords = ee.Array(image_grid.get("x"))
y_coords = ee.Array(image_grid.get("y"))
# band_data = []
# [band_data.extend(b,ee.Array(image_grid.get("%s"%b))) for b in bands[:-1]]
band_data = {b:ee.Array(image_grid.get("%s"%b)) for b in bands}
# NDVI_array = ee.Array(image_grid.get("NDVI"))
# B6_array = ee.Array(image_grid.get("B6"))
# perform LAI et al. computation possibly here!
tmpfeature = ee.Feature(ee.Geometry.Point([0,0]))\
.set('productid', productid)\
.set('system_index',system_index)\
.set('assetid', assetid)\
.set('tileid', tileid)\
.set('crs', feature.get("crs"))\
.set('sun_zenith',sun_zenith)\
.set('sun_azimuth',sun_azimuth)\
.set('view_zenith',view_zenith)\
.set('view_azimuth',view_azimuth)\
.set('x_coords', x_coords)\
.set('y_coords', y_coords)\
.set(band_data)
return tmpfeature
S2_image_data = imageCollection.map(S2_getBandData_image)
return feature.set('productid',S2_image_data.aggregate_array('productid'))\
.set('system_index', S2_image_data.aggregate_array('system_index'))\
.set('assetid',S2_image_data.aggregate_array('assetid'))\
.set('tileid',S2_image_data.aggregate_array('tileid'))\
.set('crs',S2_image_data.aggregate_array('crs'))\
.set('x_coords',S2_image_data.aggregate_array('x_coords'))\
.set('y_coords',S2_image_data.aggregate_array('y_coords'))\
.set('sun_zenith',S2_image_data.aggregate_array('sun_zenith'))\
.set('sun_azimuth',S2_image_data.aggregate_array('sun_azimuth'))\
.set('view_zenith',S2_image_data.aggregate_array('view_zenith'))\
.set('view_azimuth',S2_image_data.aggregate_array('view_azimuth'))\
.set({b:S2_image_data.aggregate_array(b) for b in bands})
featureCollection = featureCollection.map(S2_getBandData_feature).getInfo()
end = time.time()
total_time = end - start
print ("Processsing time in seconds %s"%total_time)
return featureCollection
def S2_addNDVI(image):
ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
return image.addBands(ndvi)
def S2_computeNDVItimeseries(AOI_shp,AOI_id_property,datestart, dateend):
start = time.time()
#aoi_shp = "/home/nevalaio/Dropbox/Työura/FMI/CARBO/analysis/ruukki_blocks_wgs84.shp"
attributes = st.getShapeAtrrtibutesWithIdentifier(AOI_shp,AOI_id_property)
features = [ee.Feature(ee.Geometry.Polygon(st.wkt2coordinates(item['geometry'])), {'name':key}) for key,item in attributes.items()]
featureCollection = ee.FeatureCollection(features)
def S2_computeNDVItimeseries_feature(feature):
area = feature.geometry()
collection = ee.ImageCollection("COPERNICUS/S2_SR").filterBounds(area)\
.filterDate(datestart,dateend)\
.select(['B8','B4','SCL'])
collection = collection.map(S2_addNDVI)
def S2_computeNDVItimeseries_image(img):
# ndvi = ee.Image(img.select(['NDVI']))
# scl = ee.Image(img.select(['SCL']))
productid = img.get('PRODUCT_ID')
assetid = img.id()
tileid = img.get('MGRS_TILE')
system_index = img.get('system:index')
proj = img.select("B8").projection()
# get the lat lon and add the ndvi
# latlon = ee.Image.pixelLonLat().addBands([scl,ndvi])
# apply reducer to list
img = img.reduceRegion(
reducer=ee.Reducer.toList(),
geometry=area,
maxPixels=1e8,
scale=10)
# get data into arrays
classdata = ee.Array(ee.Algorithms.If(img.get("SCL"),ee.Array(img.get("SCL")),ee.Array([0])))
ndvidata = ee.Array(ee.Algorithms.If(img.get("NDVI"),ee.Array(img.get("NDVI")),ee.Array([-9999])))
classmask = classdata.eq(0).add(classdata.eq(1).add(classdata.eq(3).add(classdata.eq(7)\
.add(classdata.eq(8).add(classdata.eq(9)\
.add(classdata.eq(10).add(classdata.eq(11)\
)))))))
badcount = classmask.reduce(ee.Reducer.sum(),[0])
totalcount = classmask.length()
goodcount = totalcount.get([0])
# ndvidata_masked = ndvidata.mask(classmask.Not())
mean = ndvidata.reduce(ee.Reducer.mean(),[0]).get([0])
std = ndvidata.reduce(ee.Reducer.stdDev(),[0]).get([0])
qualityUncertainty = badcount.divide(totalcount).get([0])
tmpfeature = ee.Feature(ee.Geometry.Point([0,0]))\
.set('productid', productid)\
.set('system_index',system_index)\
.set('assetid', assetid)\
.set('tileid', tileid)\
.set('projection', proj)\
.set('sample_n', goodcount)\
.set('ndvi_mean',mean)\
.set('ndvi_std',std)\
.set('quality_uncertainty',qualityUncertainty)
return tmpfeature
ndvi_timeseries = collection.map(S2_computeNDVItimeseries_image)
return feature.set('productid',ndvi_timeseries.aggregate_array('productid'))\
.set('system_index', ndvi_timeseries.aggregate_array('system_index'))\
.set('assetid',ndvi_timeseries.aggregate_array('assetid'))\
.set('tileid',ndvi_timeseries.aggregate_array('tileid'))\
.set('projection',ndvi_timeseries.aggregate_array('projection'))\
.set('sample_n',ndvi_timeseries.aggregate_array('sample_n'))\
.set('ndvi_mean',ndvi_timeseries.aggregate_array('ndvi_mean'))\
.set('ndvi_std',ndvi_timeseries.aggregate_array('ndvi_std'))\
.set('quality_uncertainty',ndvi_timeseries.aggregate_array('quality_uncertainty'))
featureCollection = featureCollection.map(S2_computeNDVItimeseries_feature).getInfo()
end = time.time()
total_time = end - start
print ("Processsing time in seconds %s"%total_time)
return featureCollection
def S2_getTimeseriesQualityInformation(AOI_shp,AOI_id_property,datestart, dateend):
start = time.time()
attributes = st.getShapeAtrrtibutesWithIdentifier(AOI_shp,AOI_id_property)
features = [ee.Feature(ee.Geometry.Polygon(st.wkt2coordinates(item['geometry'])), {'name':key}) for key,item in attributes.items()]
featureCollection = ee.FeatureCollection(features)
def S2_getTimeseriesQualityInformation_feature(feature):
area = feature.geometry()
collection = ee.ImageCollection("COPERNICUS/S2_SR").filterBounds(area)\
.filterDate(datestart,dateend)\
.select(['SCL'])
def S2_getTimeseriesQualityInformation_image(img):
productid = img.get('PRODUCT_ID')
assetid = img.id()
tileid = img.get('MGRS_TILE')
system_index = img.get('system:index')
proj = img.select("SCL").projection()
# apply reducer to list
img = img.reduceRegion(
reducer=ee.Reducer.toList(),
geometry=area,
maxPixels=1e8,
scale=10)
# get data into arrays
classdata = ee.Array(ee.Algorithms.If(img.get("SCL"),ee.Array(img.get("SCL")),ee.Array([0])))
classmask = classdata.eq(0).add(classdata.eq(1).add(classdata.eq(3).add(classdata.eq(7)\
.add(classdata.eq(8).add(classdata.eq(9)\
.add(classdata.eq(10).add(classdata.eq(11)\
)))))))
badcount = classmask.reduce(ee.Reducer.sum(),[0])
totalcount = classmask.length()
goodcount = totalcount.get([0])
qualityUncertainty = badcount.divide(totalcount).get([0])
tmpfeature = ee.Feature(ee.Geometry.Point([0,0]))\
.set('productid', productid)\
.set('system_index',system_index)\
.set('assetid', assetid)\
.set('tileid', tileid)\
.set('projection', proj)\
.set('sample_n', goodcount)\
.set('quality_uncertainty',qualityUncertainty)
return tmpfeature
QI_timeseries = collection.map(S2_getTimeseriesQualityInformation_image)
return feature.set('productid',QI_timeseries.aggregate_array('productid'))\
.set('system_index', QI_timeseries.aggregate_array('system_index'))\
.set('assetid',QI_timeseries.aggregate_array('assetid'))\
.set('tileid',QI_timeseries.aggregate_array('tileid'))\
.set('projection',QI_timeseries.aggregate_array('projection'))\
.set('sample_n',QI_timeseries.aggregate_array('sample_n'))\
.set('quality_uncertainty',QI_timeseries.aggregate_array('quality_uncertainty'))
featureCollection = featureCollection.map(S2_getTimeseriesQualityInformation_feature).getInfo()
end = time.time()
total_time = end - start
print ("Processsing time in seconds %s"%total_time)
return featureCollection
def S2_featureCollection2Dataframe(featureCollection):
dataframes = {}
for featnum in range(len(featureCollection['features'])):
featureCollection_dict = {}
key = featureCollection['features'][featnum]['properties']['name']
productid = featureCollection['features'][featnum]['properties']['productid']
projections = featureCollection['features'][featnum]['properties']['projection']
crs = [d['crs'] for d in projections]
dates = [st.sentinelTitle2Datetime(d) for d in productid]
featureCollection_dict.update({'Date': dates, 'crs': crs})
for prop, data in featureCollection['features'][featnum]['properties'].items():
if prop not in ['Date','crs','projection']:
featureCollection_dict.update({prop: data})
dataframes[key] = pd.DataFrame(featureCollection_dict)
return dataframes
def S2_NDVIfeatureCollection2Dataframe(featureCollection):
dataframes = {}
for featnum in range(len(featureCollection['features'])):
key = featureCollection['features'][featnum]['properties']['name']
productid = featureCollection['features'][featnum]['properties']['productid']
# dates = [datetime.datetime.strptime(d.split('_')[1], '%Y%m%dT%H%M%S') for d in dataid]
projections = featureCollection['features'][featnum]['properties']['projection']
crs = [d['crs'] for d in projections]
dates = [st.sentinelTitle2Datetime(d) for d in productid]
featureCollection_dict= {'Date': dates,
'productid': productid,
'system_index': featureCollection['features'][featnum]['properties']['system_index'],
'assetid': featureCollection['features'][featnum]['properties']['assetid'],
'tileid': featureCollection['features'][featnum]['properties']['tileid'],
'crs': crs,
'sample_n': featureCollection['features'][featnum]['properties']['sample_n'],
'ndvi_mean': featureCollection['features'][featnum]['properties']['ndvi_mean'],
'ndvi_std': featureCollection['features'][featnum]['properties']['ndvi_std'],
'quality_uncertainty': featureCollection['features'][featnum]['properties']['quality_uncertainty']
}
dataframes[key] = pd.DataFrame(featureCollection_dict, columns= ['Date','productid','system_index','assetid','tileid','crs','sample_n','ndvi_mean','ndvi_std','quality_uncertainty'])
return dataframes
def S2_exportImageCollection(assetIDs, aoi):
assetIDs = ["COPERNICUS/S2_SR/" + a for a in assetIDs]
images = [ee.Image(assetid) for assetid in assetIDs]
imageCollection = ee.ImageCollection(images)
aoi = ee.Feature(ee.Geometry.Polygon(st.wkt2coordinates(aoi)))
batch.imagecollection.toDrive(imageCollection, 'FOLDER', region=tools.geometry.getRegion(aoi), scale=10, verbose=True)
#----------------- LANDSAT-8 -------------------------------------
def L8_addNDVI(image):
ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI')
return image.addBands(ndvi)
def L8_computeNDVItimeseries(AOI_shp,AOI_id_property,datestart, dateend):
start = time.time()
attributes = st.getShapeAtrrtibutesWithIdentifier(AOI_shp,AOI_id_property)
features = [ee.Feature(ee.Geometry.Polygon(st.wkt2coordinates(item['geometry'])), {'name':key}) for key,item in attributes.items()]
featureCollection = ee.FeatureCollection(features)
def L8_comuteNDVItimeseries_feature(feature):
area = feature.geometry()
collection = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR").filterBounds(area)\
.filterDate(datestart,dateend)\
.select(['B5','B4','pixel_qa'])
collection = collection.map(L8_addNDVI)
def L8_computeNDVItimeseries_image(img):
# ndvi = ee.Image(img.select(['NDVI']))
dataid = img.get('LANDSAT_ID')
sensingtime = img.get('SENSING_TIME')
# qa = ee.Image(img.select(['pixel_qa']))
# get the lat lon and add the ndvi
# latlon = ee.Image.pixelLonLat().addBands([qa, ndvi])
# apply reducer to list
img = img.reduceRegion(
reducer=ee.Reducer.toList(),
geometry=area,
maxPixels=1e8,
scale=30);
# get data into arrays
classdata = ee.Array(ee.Algorithms.If(img.get("pixel_qa"),ee.Array(img.get("pixel_qa")),ee.Array([0])))
ndvidata = ee.Array(ee.Algorithms.If(img.get("NDVI"),ee.Array(img.get("NDVI")),ee.Array([-9999])))
# classdata = ee.Array(latlon.get("pixel_qa"))
# ndvidata = ee.Array(latlon.get("NDVI"))
mean = ndvidata.reduce(ee.Reducer.mean(),[0]).get([0])
std = ndvidata.reduce(ee.Reducer.stdDev(),[0]).get([0])
classmask = classdata.eq(322).Or(classdata.eq(386)).Not()
badcount = classmask.reduce(ee.Reducer.sum(),[0])
totalcount = classmask.length()
qualityUncertainty = badcount.divide(totalcount).get([0])
tmpfeature = ee.Feature(ee.Geometry.Point([0,0]))\
.set('dataid',dataid)\
.set('sensing_time', sensingtime)\
.set('ndvi_mean',mean)\
.set('ndvi_std',std)\
.set('quality_uncertainty',qualityUncertainty)
return tmpfeature
ndvi_timeseries = collection.map(L8_computeNDVItimeseries_image)
return feature.set('dataid',ndvi_timeseries.aggregate_array('dataid'))\
.set('sensing_time',ndvi_timeseries.aggregate_array('sensing_time'))\
.set('ndvi_mean',ndvi_timeseries.aggregate_array('ndvi_mean'))\
.set('ndvi_std',ndvi_timeseries.aggregate_array('ndvi_std'))\
.set('quality_uncertainty',ndvi_timeseries.aggregate_array('quality_uncertainty'))
featureCollection = featureCollection.map(L8_comuteNDVItimeseries_feature).getInfo()
end = time.time()
total_time = end - start
print ("Processsing time in seconds %s"%total_time)
return featureCollection
def L8_featureCollection2Dataframe(L8_featureCollection):
dataframes = {}
for featnum in range(len(L8_featureCollection['features'])):
key = L8_featureCollection['features'][featnum]['properties']['name']
dataid = L8_featureCollection['features'][featnum]['properties']['dataid']
dates = [datetime.datetime.strptime(d.split('.')[0], '%Y-%m-%dT%H:%M:%S') for d in L8_featureCollection['features'][featnum]['properties']['sensing_time']]
featureCollection_dict= {'Date': dates,
'dataid':dataid,
'ndvi_mean':L8_featureCollection['features'][featnum]['properties']['ndvi_mean'],
'ndvi_std':L8_featureCollection['features'][featnum]['properties']['ndvi_std'],
'quality_uncertainty':L8_featureCollection['features'][featnum]['properties']['quality_uncertainty']
}
dataframes[key] = pd.DataFrame(featureCollection_dict, columns= ['Date','dataid','ndvi_mean','ndvi_std','quality_uncertainty'])
return dataframes
|
[
"pandas.DataFrame",
"satelliteTools.sentinelTitle2Datetime",
"ee.Reducer.stdDev",
"satelliteTools.getShapeAtrrtibutesWithIdentifier",
"satelliteTools.wkt2coordinates",
"ee.Reducer.toList",
"ee.FeatureCollection",
"ee.ImageCollection",
"ee.Image",
"time.time",
"geetools.tools.geometry.getRegion",
"ee.Reducer.mean",
"ee.Array",
"numpy.array",
"ee.Geometry.Point",
"ee.Reducer.sum",
"ee.Initialize"
] |
[((249, 264), 'ee.Initialize', 'ee.Initialize', ([], {}), '()\n', (262, 264), False, 'import ee\n'), ((625, 636), 'time.time', 'time.time', ([], {}), '()\n', (634, 636), False, 'import time\n'), ((930, 992), 'satelliteTools.getShapeAtrrtibutesWithIdentifier', 'st.getShapeAtrrtibutesWithIdentifier', (['aoi_shp', 'AOI_id_property'], {}), '(aoi_shp, AOI_id_property)\n', (966, 992), True, 'import satelliteTools as st\n'), ((4186, 4197), 'time.time', 'time.time', ([], {}), '()\n', (4195, 4197), False, 'import time\n'), ((4596, 4607), 'time.time', 'time.time', ([], {}), '()\n', (4605, 4607), False, 'import time\n'), ((4901, 4963), 'satelliteTools.getShapeAtrrtibutesWithIdentifier', 'st.getShapeAtrrtibutesWithIdentifier', (['aoi_shp', 'AOI_id_property'], {}), '(aoi_shp, AOI_id_property)\n', (4937, 4963), True, 'import satelliteTools as st\n'), ((7975, 7986), 'time.time', 'time.time', ([], {}), '()\n', (7984, 7986), False, 'import time\n'), ((9929, 9940), 'time.time', 'time.time', ([], {}), '()\n', (9938, 9940), False, 'import time\n'), ((10244, 10306), 'satelliteTools.getShapeAtrrtibutesWithIdentifier', 'st.getShapeAtrrtibutesWithIdentifier', (['aoi_shp', 'AOI_id_property'], {}), '(aoi_shp, AOI_id_property)\n', (10280, 10306), True, 'import satelliteTools as st\n'), ((10569, 10599), 'ee.FeatureCollection', 'ee.FeatureCollection', (['features'], {}), '(features)\n', (10589, 10599), False, 'import ee\n'), ((14843, 14854), 'time.time', 'time.time', ([], {}), '()\n', (14852, 14854), False, 'import time\n'), ((15176, 15187), 'time.time', 'time.time', ([], {}), '()\n', (15185, 15187), False, 'import time\n'), ((15300, 15362), 'satelliteTools.getShapeAtrrtibutesWithIdentifier', 'st.getShapeAtrrtibutesWithIdentifier', (['AOI_shp', 'AOI_id_property'], {}), '(AOI_shp, AOI_id_property)\n', (15336, 15362), True, 'import satelliteTools as st\n'), ((15527, 15557), 'ee.FeatureCollection', 'ee.FeatureCollection', (['features'], {}), '(features)\n', (15547, 15557), False, 'import ee\n'), ((19171, 19182), 'time.time', 'time.time', ([], {}), '()\n', (19180, 19182), False, 'import time\n'), ((19405, 19416), 'time.time', 'time.time', ([], {}), '()\n', (19414, 19416), False, 'import time\n'), ((19439, 19501), 'satelliteTools.getShapeAtrrtibutesWithIdentifier', 'st.getShapeAtrrtibutesWithIdentifier', (['AOI_shp', 'AOI_id_property'], {}), '(AOI_shp, AOI_id_property)\n', (19475, 19501), True, 'import satelliteTools as st\n'), ((19661, 19691), 'ee.FeatureCollection', 'ee.FeatureCollection', (['features'], {}), '(features)\n', (19681, 19691), False, 'import ee\n'), ((22558, 22569), 'time.time', 'time.time', ([], {}), '()\n', (22567, 22569), False, 'import time\n'), ((25674, 25700), 'ee.ImageCollection', 'ee.ImageCollection', (['images'], {}), '(images)\n', (25692, 25700), False, 'import ee\n'), ((26172, 26183), 'time.time', 'time.time', ([], {}), '()\n', (26181, 26183), False, 'import time\n'), ((26201, 26263), 'satelliteTools.getShapeAtrrtibutesWithIdentifier', 'st.getShapeAtrrtibutesWithIdentifier', (['AOI_shp', 'AOI_id_property'], {}), '(AOI_shp, AOI_id_property)\n', (26237, 26263), True, 'import satelliteTools as st\n'), ((26423, 26453), 'ee.FeatureCollection', 'ee.FeatureCollection', (['features'], {}), '(features)\n', (26443, 26453), False, 'import ee\n'), ((29227, 29238), 'time.time', 'time.time', ([], {}), '()\n', (29236, 29238), False, 'import time\n'), ((796, 807), 'ee.Image', 'ee.Image', (['a'], {}), '(a)\n', (804, 807), False, 'import ee\n'), ((4767, 4778), 'ee.Image', 'ee.Image', (['a'], {}), '(a)\n', (4775, 4778), False, 'import ee\n'), ((9396, 9432), 'pandas.DataFrame', 'pd.DataFrame', (["{'Date': item['Date']}"], {}), "({'Date': item['Date']})\n", (9408, 9432), True, 'import pandas as pd\n'), ((23551, 23587), 'pandas.DataFrame', 'pd.DataFrame', (['featureCollection_dict'], {}), '(featureCollection_dict)\n', (23563, 23587), True, 'import pandas as pd\n'), ((25303, 25482), 'pandas.DataFrame', 'pd.DataFrame', (['featureCollection_dict'], {'columns': "['Date', 'productid', 'system_index', 'assetid', 'tileid', 'crs',\n 'sample_n', 'ndvi_mean', 'ndvi_std', 'quality_uncertainty']"}), "(featureCollection_dict, columns=['Date', 'productid',\n 'system_index', 'assetid', 'tileid', 'crs', 'sample_n', 'ndvi_mean',\n 'ndvi_std', 'quality_uncertainty'])\n", (25315, 25482), True, 'import pandas as pd\n'), ((25609, 25626), 'ee.Image', 'ee.Image', (['assetid'], {}), '(assetid)\n', (25617, 25626), False, 'import ee\n'), ((30415, 30531), 'pandas.DataFrame', 'pd.DataFrame', (['featureCollection_dict'], {'columns': "['Date', 'dataid', 'ndvi_mean', 'ndvi_std', 'quality_uncertainty']"}), "(featureCollection_dict, columns=['Date', 'dataid', 'ndvi_mean',\n 'ndvi_std', 'quality_uncertainty'])\n", (30427, 30531), True, 'import pandas as pd\n'), ((1038, 1085), 'satelliteTools.wkt2coordinates', 'st.wkt2coordinates', (["attributes[key]['geometry']"], {}), "(attributes[key]['geometry'])\n", (1056, 1085), True, 'import satelliteTools as st\n'), ((5009, 5056), 'satelliteTools.wkt2coordinates', 'st.wkt2coordinates', (["attributes[key]['geometry']"], {}), "(attributes[key]['geometry'])\n", (5027, 5056), True, 'import satelliteTools as st\n'), ((8609, 8645), 'satelliteTools.sentinelTitle2Datetime', 'st.sentinelTitle2Datetime', (['productid'], {}), '(productid)\n', (8634, 8645), True, 'import satelliteTools as st\n'), ((10126, 10137), 'ee.Image', 'ee.Image', (['a'], {}), '(a)\n', (10134, 10137), False, 'import ee\n'), ((23188, 23216), 'satelliteTools.sentinelTitle2Datetime', 'st.sentinelTitle2Datetime', (['d'], {}), '(d)\n', (23213, 23216), True, 'import satelliteTools as st\n'), ((24175, 24203), 'satelliteTools.sentinelTitle2Datetime', 'st.sentinelTitle2Datetime', (['d'], {}), '(d)\n', (24200, 24203), True, 'import satelliteTools as st\n'), ((25742, 25765), 'satelliteTools.wkt2coordinates', 'st.wkt2coordinates', (['aoi'], {}), '(aoi)\n', (25760, 25765), True, 'import satelliteTools as st\n'), ((25836, 25865), 'geetools.tools.geometry.getRegion', 'tools.geometry.getRegion', (['aoi'], {}), '(aoi)\n', (25860, 25865), False, 'from geetools import batch, tools\n'), ((2818, 2837), 'ee.Reducer.toList', 'ee.Reducer.toList', ([], {}), '()\n', (2835, 2837), False, 'import ee\n'), ((6618, 6637), 'ee.Reducer.toList', 'ee.Reducer.toList', ([], {}), '()\n', (6635, 6637), False, 'import ee\n'), ((10354, 10401), 'satelliteTools.wkt2coordinates', 'st.wkt2coordinates', (["attributes[key]['geometry']"], {}), "(attributes[key]['geometry'])\n", (10372, 10401), True, 'import satelliteTools as st\n'), ((11785, 11802), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (11800, 11802), False, 'import ee\n'), ((11913, 11930), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (11928, 11930), False, 'import ee\n'), ((15414, 15450), 'satelliteTools.wkt2coordinates', 'st.wkt2coordinates', (["item['geometry']"], {}), "(item['geometry'])\n", (15432, 15450), True, 'import satelliteTools as st\n'), ((17340, 17356), 'ee.Reducer.sum', 'ee.Reducer.sum', ([], {}), '()\n', (17354, 17356), False, 'import ee\n'), ((19548, 19584), 'satelliteTools.wkt2coordinates', 'st.wkt2coordinates', (["item['geometry']"], {}), "(item['geometry'])\n", (19566, 19584), True, 'import satelliteTools as st\n'), ((21113, 21129), 'ee.Reducer.sum', 'ee.Reducer.sum', ([], {}), '()\n', (21127, 21129), False, 'import ee\n'), ((26310, 26346), 'satelliteTools.wkt2coordinates', 'st.wkt2coordinates', (["item['geometry']"], {}), "(item['geometry'])\n", (26328, 26346), True, 'import satelliteTools as st\n'), ((28132, 28148), 'ee.Reducer.sum', 'ee.Reducer.sum', ([], {}), '()\n', (28146, 28148), False, 'import ee\n'), ((2261, 2278), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (2276, 2278), False, 'import ee\n'), ((2394, 2411), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (2409, 2411), False, 'import ee\n'), ((6061, 6078), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (6076, 6078), False, 'import ee\n'), ((6194, 6211), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (6209, 6211), False, 'import ee\n'), ((9509, 9529), 'numpy.array', 'np.array', (['item[prop]'], {}), '(item[prop])\n', (9517, 9529), True, 'import numpy as np\n'), ((9597, 9618), 'numpy.array', 'np.array', (["item['lai']"], {}), "(item['lai'])\n", (9605, 9618), True, 'import numpy as np\n'), ((12364, 12383), 'ee.Reducer.toList', 'ee.Reducer.toList', ([], {}), '()\n', (12381, 12383), False, 'import ee\n'), ((16530, 16549), 'ee.Reducer.toList', 'ee.Reducer.toList', ([], {}), '()\n', (16547, 16549), False, 'import ee\n'), ((16779, 16792), 'ee.Array', 'ee.Array', (['[0]'], {}), '([0])\n', (16787, 16792), False, 'import ee\n'), ((16886, 16903), 'ee.Array', 'ee.Array', (['[-9999]'], {}), '([-9999])\n', (16894, 16903), False, 'import ee\n'), ((20414, 20433), 'ee.Reducer.toList', 'ee.Reducer.toList', ([], {}), '()\n', (20431, 20433), False, 'import ee\n'), ((20663, 20676), 'ee.Array', 'ee.Array', (['[0]'], {}), '([0])\n', (20671, 20676), False, 'import ee\n'), ((27384, 27403), 'ee.Reducer.toList', 'ee.Reducer.toList', ([], {}), '()\n', (27401, 27403), False, 'import ee\n'), ((27623, 27636), 'ee.Array', 'ee.Array', (['[0]'], {}), '([0])\n', (27631, 27636), False, 'import ee\n'), ((27730, 27747), 'ee.Array', 'ee.Array', (['[-9999]'], {}), '([-9999])\n', (27738, 27747), False, 'import ee\n'), ((17548, 17565), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (17563, 17565), False, 'import ee\n'), ((17614, 17633), 'ee.Reducer.stdDev', 'ee.Reducer.stdDev', ([], {}), '()\n', (17631, 17633), False, 'import ee\n'), ((27922, 27939), 'ee.Reducer.mean', 'ee.Reducer.mean', ([], {}), '()\n', (27937, 27939), False, 'import ee\n'), ((27988, 28007), 'ee.Reducer.stdDev', 'ee.Reducer.stdDev', ([], {}), '()\n', (28005, 28007), False, 'import ee\n'), ((15674, 15712), 'ee.ImageCollection', 'ee.ImageCollection', (['"""COPERNICUS/S2_SR"""'], {}), "('COPERNICUS/S2_SR')\n", (15692, 15712), False, 'import ee\n'), ((19818, 19856), 'ee.ImageCollection', 'ee.ImageCollection', (['"""COPERNICUS/S2_SR"""'], {}), "('COPERNICUS/S2_SR')\n", (19836, 19856), False, 'import ee\n'), ((26578, 26622), 'ee.ImageCollection', 'ee.ImageCollection', (['"""LANDSAT/LC08/C01/T1_SR"""'], {}), "('LANDSAT/LC08/C01/T1_SR')\n", (26596, 26622), False, 'import ee\n'), ((28317, 28342), 'ee.Geometry.Point', 'ee.Geometry.Point', (['[0, 0]'], {}), '([0, 0])\n', (28334, 28342), False, 'import ee\n'), ((21343, 21368), 'ee.Geometry.Point', 'ee.Geometry.Point', (['[0, 0]'], {}), '([0, 0])\n', (21360, 21368), False, 'import ee\n'), ((17767, 17792), 'ee.Geometry.Point', 'ee.Geometry.Point', (['[0, 0]'], {}), '([0, 0])\n', (17784, 17792), False, 'import ee\n'), ((3522, 3547), 'ee.Geometry.Point', 'ee.Geometry.Point', (['[0, 0]'], {}), '([0, 0])\n', (3539, 3547), False, 'import ee\n'), ((7311, 7336), 'ee.Geometry.Point', 'ee.Geometry.Point', (['[0, 0]'], {}), '([0, 0])\n', (7328, 7336), False, 'import ee\n'), ((13116, 13141), 'ee.Geometry.Point', 'ee.Geometry.Point', (['[0, 0]'], {}), '([0, 0])\n', (13133, 13141), False, 'import ee\n')]
|
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
"""In this script are all modules required for the generator and discriminator"""
### Helper Functions ###
def make_mlp(dim_list, activation_list, batch_norm=False, dropout=0):
"""
Generates MLP network:
Parameters
----------
dim_list : list, list of number for each layer
activation_list : list, list containing activation function for each layer
batch_norm : boolean, use batchnorm at each layer, default: False
dropout : float [0, 1], dropout probability applied on each layer (except last layer)
Returns
-------
nn.Sequential with layers
"""
layers = []
index = 0
for dim_in, dim_out in zip(dim_list[:-1], dim_list[1:]):
activation = activation_list[index]
layers.append(nn.Linear(dim_in, dim_out))
if batch_norm:
layers.append(nn.BatchNorm1d(dim_out))
if activation == 'relu':
layers.append(nn.ReLU())
elif activation == 'tanh':
layers.append(nn.Tanh())
elif activation == 'leakyrelu':
layers.append(nn.LeakyReLU())
elif activation == 'sigmoid':
layers.append(nn.Sigmoid())
if dropout > 0 and index < len(dim_list) - 2:
layers.append(nn.Dropout(p=dropout))
index += 1
return nn.Sequential(*layers)
### Convolutional Blocks and U-NET CNN ###
class Conv_Blocks(nn.Module):
def __init__(self, input_dim, output_dim, filter_size=3, batch_norm=False, non_lin="tanh", dropout=0.,
first_block=False, last_block=False, skip_connection=False):
super(Conv_Blocks, self).__init__()
self.skip_connection = skip_connection
self.last_block = last_block
self.first_block = first_block
self.Block = nn.Sequential()
self.Block.add_module("Conv_1", nn.Conv2d(input_dim, output_dim, filter_size, 1, 1))
if batch_norm:
self.Block.add_module("BN_1", nn.BatchNorm2d(output_dim))
if non_lin == "tanh":
self.Block.add_module("NonLin_1", nn.Tanh())
elif non_lin == "relu":
self.Block.add_module("NonLin_1", nn.ReLU())
elif non_lin == "leakyrelu":
self.Block.add_module("NonLin_1", nn.LeakyReLU())
else:
assert False, "non_lin = {} not valid: 'tanh', 'relu', 'leakyrelu'".format(non_lin)
self.Block.add_module("Pool", nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1), ceil_mode=False))
if dropout > 0:
self.Block.add_module("Drop", nn.Dropout2d(dropout))
def forward(self, x, ):
if self.skip_connection:
if not self.first_block:
x, skip_con_list = x
else:
skip_con_list = []
x = self.Block(x)
if self.skip_connection:
if not self.last_block:
skip_con_list.append(x)
x = [x, skip_con_list]
return x
class UpConv_Blocks(nn.Module):
def __init__(self, input_dim, output_dim, filter=4, padding=1, first_block=False, last_block=False,
batch_norm=False, non_lin="relu", dropout=0, skip_connection=False):
super(UpConv_Blocks, self).__init__()
self.Block = nn.Sequential()
self.skip_connection = skip_connection
self.first_block = first_block
self.last_block = last_block
if self.skip_connection and not self.first_block:
ouput_dim_conv = input_dim
input_dim *= 2
else:
ouput_dim_conv = output_dim
self.Block.add_module("UpConv", nn.ConvTranspose2d(input_dim, output_dim, filter, 2, padding))
if not last_block:
if batch_norm:
self.Block.add_module("BN_up", nn.BatchNorm2d(output_dim))
if non_lin == "tanh":
self.Block.add_module("NonLin_up", nn.Tanh())
elif non_lin == "relu":
self.Block.add_module("NonLin_up", nn.ReLU())
elif non_lin == "leakyrelu":
self.Block.add_module("NonLin_up", nn.LeakyReLU())
if dropout > 0:
self.Block.add_module("Drop_up", nn.Dropout2d(dropout))
def forward(self, x, ):
if self.skip_connection:
x, skip_con_list = x
if not self.first_block:
x = torch.cat((x, skip_con_list.pop(-1)), -3)
x = self.Block(x)
if self.skip_connection and not self.last_block:
x = [x, skip_con_list]
return x
class CNN(nn.Module):
def __init__(self,
social_pooling=False,
channels_cnn=4,
mlp=32,
encoder_h_dim=16,
insert_trajectory=False,
need_decoder=False,
PhysFeature=False,
grid_size_in=32,
grid_size_out=32,
num_layers=3,
dropout=0.,
batch_norm=False,
non_lin_cnn="tanh",
in_channels=3,
skip_connection=False,
):
super(CNN, self).__init__()
self.__dict__.update(locals())
self.bottleneck_dim = int(grid_size_in / 2 ** (num_layers - 1)) ** 2
num_layers_dec = int(num_layers + ((grid_size_out - grid_size_in) / grid_size_out))
self.encoder = nn.Sequential()
layer_out = channels_cnn
self.encoder.add_module("ConvBlock_1", Conv_Blocks(in_channels, channels_cnn,
dropout=dropout,
batch_norm=batch_norm,
non_lin=self.non_lin_cnn,
first_block=True,
skip_connection=self.skip_connection
))
layer_in = layer_out
for layer in np.arange(2, num_layers + 1):
if layer != num_layers:
layer_out = layer_in * 2
last_block = False
else:
layer_out = layer_in
last_block = True
self.encoder.add_module("ConvBlock_%s" % layer,
Conv_Blocks(layer_in, layer_out,
dropout=dropout,
batch_norm=batch_norm,
non_lin=self.non_lin_cnn,
skip_connection=self.skip_connection,
last_block=last_block
))
layer_in = layer_out
self.bootleneck_channel = layer_out
if self.need_decoder:
self.decoder = nn.Sequential()
layer_in = layer_out
for layer in range(1, num_layers_dec + 1):
first_block = False
extra_d = 0
layer_in = layer_out
last_block = False
filter = 4
padding = 1
if layer == 1:
if self.insert_trajectory:
extra_d = 1
first_block = True
layer_out = layer_in
else:
layer_out = int(layer_in / 2.)
if layer == num_layers_dec:
layer_out = 1
last_block = True
padding = 0
filter = 3
self.decoder.add_module("UpConv_%s" % layer,
UpConv_Blocks(int(layer_in + extra_d),
layer_out,
first_block=first_block,
filter=filter,
padding=padding,
dropout=dropout,
batch_norm=batch_norm,
non_lin=self.non_lin_cnn,
skip_connection=self.skip_connection,
last_block=last_block))
if self.insert_trajectory:
self.traj2cnn = make_mlp(
dim_list=[encoder_h_dim, mlp, self.bottleneck_dim],
activation_list=["tanh", "tanh"],
)
self.init_weights()
def init_weights(self):
def init_kaiming(m):
if type(m) in [nn.Conv2d, nn.ConvTranspose2d]:
torch.nn.init.kaiming_normal_(m.weight, mode='fan_in')
m.bias.data.fill_(0.01)
# if type(m) in [nn.ConvTranspose2d]:
# torch.nn.init.kaiming_normal_(m.weight, mode='fan_in')
# m.bias.data.fill_(50)
def init_xavier(m):
if type(m) == [nn.Conv2d, nn.ConvTranspose2d]:
torch.nn.init.xavier_uniform(m.weight)
m.bias.data.fill_(0.01)
if self.non_lin_cnn in ['relu', 'leakyrelu']:
self.apply(init_kaiming)
elif self.non_lin_cnn == "tanh":
self.apply(init_xavier)
else:
assert False, "non_lin not valid for initialisation"
def forward(self, image, traj_h=torch.empty(1), pool_h=torch.empty(1)):
output = {}
enc = self.encoder(image)
if self.PhysFeature:
# enc_out = self.leakyrelu(self.encoder_out(enc))
# enc_out = enc_out.permute(1, 0, 2, 3).view(1, enc_out.size(0), -1)
output.update(Features=enc)
if self.need_decoder:
if self.skip_connection:
batch, c, w, h = enc[0].size()
in_decoder, skip_con_list = enc
else:
batch, c, w, h = enc.size()
in_decoder = enc
if self.insert_trajectory:
traj_enc = self.traj2cnn(traj_h)
traj_enc = traj_enc.view(batch, 1, w, h)
in_decoder = torch.cat((traj_enc, in_decoder), 1)
if self.social_pooling:
social_enc = self.social_states(pool_h)
social_enc = social_enc.view(batch, 1, w, h)
in_decoder = torch.cat((social_enc, in_decoder), 1)
if self.skip_connection: in_decoder = [in_decoder, skip_con_list]
dec = self.decoder(in_decoder)
output.update(PosMap=dec)
return output
class MotionEncoder(nn.Module):
"""MotionEncoder extracts dynamic features of the past trajectory and consists of an encoding LSTM network"""
def __init__(self,
encoder_h_dim=64,
input_dim=2,
embedding_dim=16,
dropout=0.0):
""" Initialize MotionEncoder.
Parameters.
encoder_h_dim (int) - - dimensionality of hidden state
input_dim (int) - - input dimensionality of spatial coordinates
embedding_dim (int) - - dimensionality spatial embedding
dropout (float) - - dropout in LSTM layer
"""
super(MotionEncoder, self).__init__()
self.encoder_h_dim = encoder_h_dim
self.embedding_dim = embedding_dim
self.input_dim = input_dim
if embedding_dim:
self.spatial_embedding = nn.Linear(input_dim, embedding_dim)
self.encoder = nn.LSTM(embedding_dim, encoder_h_dim)
else:
self.encoder = nn.LSTM(input_dim, encoder_h_dim)
def init_hidden(self, batch, obs_traj):
return (
torch.zeros(1, batch, self.encoder_h_dim).to(obs_traj),
torch.zeros(1, batch, self.encoder_h_dim).to(obs_traj)
)
def forward(self, obs_traj, state_tuple=None):
""" Calculates forward pass of MotionEncoder
Parameters:
obs_traj (tensor) - - Tensor of shape (obs_len, batch, 2)
state_tuple (tuple of tensors) - - Tuple with hidden state (1, batch, encoder_h_dim) and cell state tensor (1, batch, encoder_h_dim)
Returns:
output (tensor) - - Output of LSTM netwok for all time steps (obs_len, batch, encoder_h_dim)
final_h (tensor) - - Final hidden state of LSTM network (1, batch, encoder_h_dim)
"""
# Encode observed Trajectory
batch = obs_traj.size(1)
if not state_tuple:
state_tuple = self.init_hidden(batch, obs_traj)
if self.embedding_dim:
obs_traj = self.spatial_embedding(obs_traj)
output, state = self.encoder(obs_traj, state_tuple)
final_h = state[0]
return output, final_h
class VisualNetwork(nn.Module):
"""VisualNetwork is the parent class for the attention and goal networks generating the CNN"""
def __init__(self,
decoder_h_dim=128,
dropout=0.0,
batch_norm=False,
mlp_dim=32,
img_scaling=0.25,
final_embedding_dim=4,
grid_size_in=16,
grid_size_out=16,
num_layers=1,
batch_norm_cnn=True,
non_lin_cnn="relu",
img_type="local_image",
skip_connection=False,
channels_cnn=4,
social_pooling=False,
**kwargs):
super(VisualNetwork, self).__init__()
self.__dict__.update(locals())
def init_cnn(self):
self.CNN = CNN(social_pooling=self.social_pooling,
channels_cnn=self.channels_cnn,
encoder_h_dim=self.decoder_h_dim,
mlp=self.mlp_dim,
insert_trajectory=True,
need_decoder=self.need_decoder,
PhysFeature=self.PhysFeature,
grid_size_in=self.grid_size_in,
grid_size_out=self.grid_size_out,
dropout=self.dropout,
batch_norm=self.batch_norm_cnn,
non_lin_cnn=self.non_lin_cnn,
num_layers=self.num_layers,
in_channels=4,
skip_connection=self.skip_connection
)
### Visual Attention ###
class AttentionNetwork(VisualNetwork):
def __init__(self,
noise_attention_dim=8,
**kwargs
):
super(AttentionNetwork, self).__init__()
VisualNetwork.__init__(self, **kwargs)
self.__dict__.update(locals())
self.PhysFeature = True
self.skip_connection = False
self.need_decoder = False
self.init_cnn()
self.final_embedding = self.CNN.bottleneck_dim + self.noise_attention_dim
attention_dims = [self.CNN.bootleneck_channel, self.mlp_dim, 1]
activation = ['leakyrelu', None]
self.cnn_attention = make_mlp(
attention_dims,
activation_list=activation, )
def get_noise(self, batch_size, type="gauss"):
"""
Create noise vector:
Parameters
----------
batchsize : int, length of noise vector
noise_type: str, 'uniform' or 'gaussian' noise
Returns
-------
Random noise vector
"""
if type == "gauss":
return torch.randn((1, batch_size, self.noise_attention_dim))
elif type == "uniform":
rand_num = torch.rand((1, batch_size, self.noise_attention_dim))
return rand_num
else:
raise ValueError('Unrecognized noise type "%s"' % noise_type)
class AttentionRoutingModule(AttentionNetwork):
def __init__(self,
**kwargs):
super(AttentionNetwork, self).__init__()
AttentionNetwork.__init__(self, **kwargs)
self.__dict__.update(locals())
self.img_patch = Patch_gen(img_scaling=self.img_scaling,
grid_size=self.grid_size_in,
type_img=self.img_type)
self.init_cnn()
def forward(self, scene_img, last_pos, h, noise=torch.Tensor()):
img_patch = self.img_patch.get_patch(scene_img, last_pos)
visual_features = self.CNN(img_patch, h)["Features"].permute(0, 2, 3, 1)
batch_size, hh, w, c = visual_features.size()
visual_features = visual_features.view(batch_size, -1, c)
attention_scores = self.cnn_attention(visual_features)
attention_vec = attention_scores.softmax(dim=1).squeeze(2).unsqueeze(0)
if self.noise_attention_dim > 0:
if len(noise) == 0:
noise = self.get_noise(batch_size)
else:
assert noise.size(-1) != self.noise_attention_dim, "dimension of noise {} not valid".format(
noise.size())
x = torch.cat((attention_vec, noise.to(attention_vec)), dim=2)
return x, attention_vec, img_patch, noise
class AttentionGlobal(AttentionNetwork):
"""Alternative Visual Attention to GoalModule"""
def __init__(self, **kwargs):
super(AttentionNetwork, self).__init__()
AttentionNetwork.__init__(self, **kwargs)
self.__dict__.update(locals())
self.init_cnn()
def forward(self, features, h, noise=torch.Tensor()):
visual_features = self.CNN(features, h)["Features"].permute(0, 2, 3, 1)
batch_size, hh, w, c = visual_features.size()
visual_features = visual_features.view(batch_size, -1, c)
attention_scores = self.cnn_attention(visual_features)
attention_vec = attention_scores.softmax(dim=1).squeeze(2).unsqueeze(0)
if self.noise_attention_dim > 0:
if len(noise) == 0:
noise = self.get_noise(batch_size)
else:
assert noise.size(-1) != self.noise_attention_dim, "dimension of noise {} not valid".format(
noise.size())
x = torch.cat((attention_vec, noise.to(attention_vec)), dim=2)
return x, attention_vec, noise
### GOAL Module ###
class GoalGlobal(VisualNetwork):
def __init__(self,
temperature=1, # temperature of the gumbel sampling
force_hard=True, # mode of the gumbel sampling
**kwargs):
super(GoalGlobal, self).__init__()
VisualNetwork.__init__(self, **kwargs)
self.__dict__.update(locals())
self.PhysFeature = False
self.need_decoder = True
self.init_cnn()
self.gumbelsampler = GumbelSampler(
temp=self.temperature,
grid_size_out=self.grid_size_out,
force_hard=force_hard,
scaling=self.img_scaling)
def forward(self, features, h, pool_h=torch.empty(1)):
cnn_out = self.CNN(features, h, pool_h)
final_pos, final_pos_map_decoder, final_pos_map, y_softmax, y_scores = self.gumbelsampler(cnn_out)
return final_pos, final_pos_map_decoder, final_pos_map, y_softmax, y_scores
class RoutingModule(nn.Module):
"""RoutingModule is part of TrajectoryGenerator and generates the prediction for each time step.
The MotionDecoder consists of a LSTM network and a local goal network or attention network"""
def __init__(
self,
seq_len=12,
input_dim=2,
decoder_h_dim=128,
embedding_dim=64,
dropout=0.0,
batch_norm=False,
mlp_dim=32,
img_scaling_local=0.25,
final_embedding_dim_rm=4,
rm_vis_type="attention",
grid_size_rm=8,
dropout_cnn_rm=0.0,
num_layers_rm=3,
non_lin_cnn_rm="relu",
force_hard_rm=True,
temperature_rm=1,
batch_norm_cnn_rm=False,
noise_attention_dim_rm=True,
skip_connection_rm=False,
channels_cnn_rm=4,
global_vis_type="goal"):
"""Initialise Motion Decoder network
Parameters.
seq_len (int) - - Prediction length of trajectory
input_dim (int) - - input / output dimensionality of spatial coordinates
decoder_h_dim (int) - - hidden state dimenstion of decoder LSTM
embedding_dim (int) - - dimensionality spatial embedding
dropout (float) - - dropout
final_embedding_dim (int) - - embedding for final position estimate
mlp_dim (int) - - bottleneck dimensionality of mlp networks
PhysAtt (bool) - - depreciated. should not be used
device (torch.device) - - Choose device: cpu or gpu (cuda)
batch_norm (bool) - - if true, applies batch norm in mlp networks
img_scaling (float) - - ratio [m/px] between real and pixel space
grid_size (int) - - defines size of image path in goal / attention network (grid size is 2xgrid_size +1 )
decoder_type ("goal", "attention", none) - -
"""
super(RoutingModule, self).__init__()
self.__dict__.update(locals())
if self.rm_vis_type:
if self.rm_vis_type == "attention":
self.rm_attention = AttentionRoutingModule(
channels_cnn=self.channels_cnn_rm,
decoder_h_dim=self.decoder_h_dim,
dropout=self.dropout_cnn_rm,
mlp_dim=self.mlp_dim,
img_scaling=self.img_scaling_local,
grid_size_in=self.grid_size_rm,
grid_size_out=self.grid_size_rm,
num_layers=self.num_layers_rm,
batch_norm_cnn=self.batch_norm_cnn_rm,
non_lin_cnn=self.non_lin_cnn_rm,
final_embedding_dim=final_embedding_dim_rm,
noise_attention_dim=self.noise_attention_dim_rm,
skip_connection=self.skip_connection_rm)
self.final_embedding_dim_rm = self.rm_attention.final_embedding
self.output_dim = self.decoder_h_dim + self.final_embedding_dim_rm
elif not self.rm_vis_type:
self.output_dim = self.decoder_h_dim
else:
assert False, "`{}` not valid for `decoder_type`: Choose `goal`, 'attention`, or none".format(decoder_type)
self.final_output = make_mlp(
[self.output_dim, self.mlp_dim, self.input_dim],
activation_list=["relu", None],
dropout=dropout,
batch_norm=self.batch_norm)
self.spatial_embedding = nn.Linear(self.input_dim, self.embedding_dim)
if self.global_vis_type == "goal":
self.input_dim_decoder = self.self.embedding_dim * 2 + 1
else:
self.input_dim_decoder = self.embedding_dim
self.decoder = nn.LSTM(self.input_dim_decoder, self.decoder_h_dim)
def forward(self, last_pos, rel_pos, state_tuple, dist_to_goal=0, scene_img=None):
""" Calculates forward pass of MotionDecoder
Parameters:
obs_traj (tensor) - - Tensor of shape (obs_len, batch, 2)
state_tuple (tuple of tensors) - - Tuple with hidden state (1, batch, encoder_h_dim) and cell state tensor (1, batch, encoder_h_dim)
Returns:
output (tensor) - - Output of LSTM netwok for all time steps (obs_len, batch, encoder_h_dim)
final_h (tensor) - - Final hidden state of LSTM network (1, batch, encoder_h_dim)
"""
batch_size = rel_pos.size(0)
pred_traj_fake_rel = []
pred_traj_fake = []
softmax_list = []
final_pos_list = []
img_patch_list = []
final_pos_map_decoder_list = []
for t in range(self.seq_len):
decoder_input = self.spatial_embedding(rel_pos)
decoder_input = decoder_input.view(1, batch_size, self.embedding_dim)
if self.global_vis_type != "none":
distance_embeding = self.spatial_embedding(dist_to_goal)
time_tensor = -1 + 2 * torch.ones(1, decoder_input.size(1), 1) * t / self.seq_len
time_tensor = time_tensor.to(decoder_input)
decoder_input = torch.cat((decoder_input, distance_embeding, time_tensor), -1)
output, state_tuple = self.decoder(decoder_input, state_tuple)
if self.rm_vis_type == "attention":
final_emb, y_softmax, img_patch, noise = self.rm_attention(scene_img, last_pos, state_tuple[0])
else:
final_emb = torch.Tensor([]).to(state_tuple[0])
img_patch = []
input_final = torch.cat((state_tuple[0], final_emb), 2)
img_patch_list.append(img_patch)
# rel_pos = final_pos[0]
rel_pos = self.final_output(input_final)
rel_pos = rel_pos.squeeze(0)
curr_pos = rel_pos + last_pos
dist_to_goal = dist_to_goal - rel_pos
pred_traj_fake_rel.append(rel_pos.clone().view(batch_size, -1))
pred_traj_fake.append(curr_pos.clone().view(batch_size, -1))
last_pos = curr_pos
pred_traj_fake_rel = torch.stack(pred_traj_fake_rel, dim=0)
pred_traj_fake = torch.stack(pred_traj_fake, dim=0)
output = {"out_xy": pred_traj_fake,
"out_dxdy": pred_traj_fake_rel,
"h": state_tuple[0]}
if self.rm_vis_type == "attention":
output.update({"image_patches": torch.stack(img_patch_list, dim=0)})
return output
class EncoderPrediction(nn.Module):
"""Part of Discriminator"""
def __init__(
self, input_dim=2,
encoder_h_dim_d=128,
embedding_dim=64,
dropout=0.0,
channels_cnn=4,
grid_size=16,
num_layers_cnn=2,
batch_norm_cnn=True,
batch_norm=False,
dropout_cnn=0,
mlp_dim=32,
image_scaling=0.5,
non_lin_cnn='tanh',
visual_features = False):
super().__init__()
self.__dict__.update(locals())
del self.self
self.bottleneck_dim = int(grid_size / 2 ** (num_layers_cnn - 1)) ** 2 * channels_cnn * 2 ** (num_layers_cnn - 2)
activation = ['leakyrelu', None]
in_channels = 4
self.bottleneck_dim = int(grid_size / 2 ** (num_layers_cnn - 1)) ** 2
self.encoder_out = nn.Conv2d(channels_cnn * 2 ** (num_layers_cnn - 2), 1, kernel_size=(1, 1), stride=1)
self.leakyrelu = nn.LeakyReLU()
self.inputFeatures = make_mlp(
[self.embedding_dim + self.bottleneck_dim, mlp_dim, self.embedding_dim],
activation_list=['leakyrelu', None],
dropout=dropout)
self.encoder = nn.LSTM(self.embedding_dim, self.encoder_h_dim_d, dropout=dropout)
if self.visual_features:
self.CNN = CNN(channels_cnn=self.channels_cnn,
encoder_h_dim=self.encoder_h_dim_d,
mlp=self.mlp_dim,
need_decoder=False,
PhysFeature=True,
insert_trajectory=False,
grid_size_in=self.grid_size,
num_layers=self.num_layers_cnn,
dropout=self.dropout_cnn,
batch_norm=batch_norm_cnn,
non_lin_cnn=self.non_lin_cnn,
in_channels=in_channels,
)
self.spatial_embedding = nn.Linear(2, self.embedding_dim)
real_classifier_dims = [self.encoder_h_dim_d, mlp_dim, 1]
self.real_classifier = make_mlp(
real_classifier_dims,
activation_list=activation,
dropout=dropout)
def init_hidden(self, batch, obs_traj):
return (torch.zeros(1, batch, self.encoder_h_dim_d).to(obs_traj),
torch.zeros(1, batch, self.encoder_h_dim_d).to(obs_traj))
def forward(self, dxdy, img_patch, state_tuple):
"""
Inputs:
- last_pos: Tensor of shape (batch, 2)
- last_pos_rel: Tensor of shape (batch, 2)
- state_tuple: (hh, ch) each tensor of shape (num_layers, batch, h_dim)
Output:
- pred_traj_fake_rel: tensor of shape (self.seq_len, batch, 2)
- pred_traj_fake: tensor of shape (self.seq_len, batch, 2)
- state_tuple[0]: final hidden state
"""
embedded_pos = self.spatial_embedding(dxdy)
if self.visual_features:
l, batch, c, x, y = img_patch.size()
img_patch = img_patch.reshape(l * batch, c, x, y)
cnn_out = self.CNN(img_patch)
visual_features = self.leakyrelu(self.encoder_out(cnn_out["Features"]))
visual_features = visual_features.view(l, batch, -1)
encoder_input = torch.cat((embedded_pos, visual_features), -1)
encoder_input = self.inputFeatures(encoder_input)
else:
encoder_input = embedded_pos
output, input_classifier = self.encoder(encoder_input, state_tuple)
dynamic_score = self.real_classifier(input_classifier[0])
return dynamic_score
class get_gumbel_map(nn.Module):
def __init__(self, grid_size):
super(get_gumbel_map, self).__init__()
x = torch.arange(0, grid_size * 2 + 1)
x = x.unsqueeze(1)
X = x.repeat(1, grid_size * 2 + 1)
x1 = X - grid_size
x2 = x1.T
x1 = x1.unsqueeze(2)
x2 = x2.unsqueeze(2)
self.gumbel_map = torch.cat((x2, x1), 2).view(1, -1, 2)
def forward(self, batch_size):
gumbel_map = self.gumbel_map.repeat(batch_size, 1, 1).float()
gumbel_map = gumbel_map + torch.rand_like(gumbel_map)
return gumbel_map
### Gumbel Sampling ###
class GumbelSampler(nn.Module):
def __init__(self,
temp=1,
grid_size_out=16,
scaling=0.5,
force_hard=True,
):
super(GumbelSampler, self).__init__()
self.temp = temp
self.grid_size_out = grid_size_out
self.scaling = scaling
self.gumbelsoftmax = GumbelSoftmax(temp=self.temp)
self.gumbel_map = get_gumbel_map(grid_size=self.grid_size_out)
self.force_hard = force_hard
def forward(self, cnn_out):
"""
:param cnn_out:
:type cnn_out:
:return:
final_pos: Tensor with probability for each position
final_pos_map: final_pos tensor reshaped
y_softmax_gumbel: tensor with gumbel probabilities
y_softmax: tensor with probabilites
:rtype:
"""
batch_size, c, hh, w = cnn_out["PosMap"].size()
gumbel_map = self.gumbel_map(batch_size).to(cnn_out["PosMap"])
y_scores = cnn_out["PosMap"].view(batch_size, -1)
final_pos_map, y_softmax_gumbel, y_softmax = self.gumbelsoftmax(y_scores, force_hard=self.force_hard)
final_pos = torch.sum(gumbel_map * final_pos_map.unsqueeze(2), 1).unsqueeze(0)
final_pos_map = final_pos_map.view(batch_size, c, hh, w)
y_softmax_gumbel = y_softmax_gumbel.view(batch_size, c, hh, w)
y_softmax = y_softmax.view(batch_size, c, hh, w)
final_pos = final_pos * self.scaling
return final_pos, final_pos_map, y_softmax_gumbel, y_softmax, y_scores
class Patch_gen():
def __init__(self, img_scaling=0.5,
grid_size=16,
type_img="small_image",
):
self.__dict__.update(locals())
def get_patch(self, scene_image, last_pos):
scale = 1. / self.img_scaling
last_pos_np = last_pos.detach().cpu().numpy()
image_list = []
for k in range(len(scene_image)):
image = scene_image[k][self.type_img]
center = last_pos_np[k] * scale
x_center, y_center = center.astype(int)
cropped_img = image.crop(
(int(x_center - self.grid_size), int(y_center - self.grid_size), int(x_center + self.grid_size + 1),
int(y_center + self.grid_size + 1)))
cropped_img = -1 + torch.from_numpy(np.array(cropped_img) * 1.) * 2. / 256
position = torch.zeros((1, self.grid_size * 2 + 1, self.grid_size * 2 + 1, 1))
position[0, self.grid_size, self.grid_size, 0] = 1.
image = torch.cat((cropped_img.float().unsqueeze(0), position), dim=3)
image = image.permute(0, 3, 1, 2)
image_list.append(image.clone())
img = torch.cat(image_list)
img = img.to(last_pos)
return img
"""
Gumbel Softmax Sampler
Requires 2D input [batchsize, number of categories]
Does not support sinlge binary category. Use two dimensions with softmax instead.
"""
class GumbelSoftmax(nn.Module):
def __init__(self, hard=False, temp=None):
super(GumbelSoftmax, self).__init__()
self.hard = hard
self.gpu = False
self.temp = temp
def cuda(self):
self.gpu = True
def cpu(self):
self.gpu = False
def sample_gumbel(self, shape, eps=1e-10):
"""Sample from Gumbel(0, 1)"""
noise = torch.rand(shape)
noise.add_(eps).log_().neg_()
noise.add_(eps).log_().neg_()
if self.gpu:
return Variable(noise).cuda()
else:
return Variable(noise)
def sample_gumbel_like(self, template_tensor, eps=1e-10):
uniform_samples_tensor = template_tensor.clone().uniform_()
gumble_samples_tensor = - torch.log(eps - torch.log(uniform_samples_tensor + eps))
return gumble_samples_tensor
def gumbel_softmax_sample(self, alpha, temperature, eps=1e-10):
""" Draw a sample from the Gumbel-Softmax distribution"""
dim = len(alpha.size()) - 1
gumble_samples_tensor = self.sample_gumbel_like(alpha.data)
gumble_trick_log_prob_samples = alpha + gumble_samples_tensor
gumble_log_temp = gumble_trick_log_prob_samples / temperature
max_gumble, _ = gumble_log_temp.max(1)
soft_samples_gumble = F.softmax(gumble_log_temp - max_gumble.unsqueeze(1), dim)
soft_samples_gumble = torch.max(soft_samples_gumble, torch.ones_like(soft_samples_gumble).to(alpha) * eps)
soft_samples = F.softmax(alpha, dim)
return soft_samples_gumble, soft_samples
def gumbel_softmax(self, logits, temperature, hard=False):
"""Sample from the Gumbel-Softmax distribution and optionally discretize.
Args:
logits: [batch_size, n_class] unnormalized log-probs
temperature: non-negative scalar
hard: if True, take argmax, but differentiate w.r.t. soft sample y
Returns:
[batch_size, n_class] sample from the Gumbel-Softmax distribution.
If hard=True, then the returned sample will be one-hot, otherwise it will
be a probabilitiy distribution that sums to 1 across classes
"""
soft_samples_gumble, soft_samples = self.gumbel_softmax_sample(logits, temperature)
if hard:
_, max_value_indexes = soft_samples_gumble.data.max(1, keepdim=True)
y_hard = logits.data.clone().zero_().scatter_(1, max_value_indexes, 1)
y = y_hard - soft_samples_gumble.data + soft_samples_gumble
else:
y = soft_samples_gumble
return y, soft_samples_gumble, soft_samples
def forward(self, alpha, temp=None, force_hard=False):
if not temp:
if self.temp:
temp = self.temp
else:
temp = 1
if self.training and not force_hard:
return self.gumbel_softmax(alpha, temperature=temp, hard=False)
else:
return self.gumbel_softmax(alpha, temperature=temp, hard=True)
if __name__ == "__main__":
print("Test Encoder")
print(MotionEncoder())
print("Test Decoder")
print(RoutingModule())
print("Test AttentionRoutingModule")
print(AttentionRoutingModule())
print("Test AttentionGlobal")
print(AttentionGlobal())
print("Test GoalGlobal")
print(GoalGlobal() )
print("Test Encoder Discriminator")
print(EncoderPrediction())
|
[
"torch.nn.Dropout",
"torch.empty",
"torch.cat",
"torch.randn",
"torch.rand_like",
"numpy.arange",
"torch.arange",
"torch.nn.init.kaiming_normal_",
"torch.nn.init.xavier_uniform",
"torch.Tensor",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LSTM",
"torch.log",
"torch.nn.Dropout2d",
"torch.nn.Tanh",
"torch.nn.Conv2d",
"torch.nn.BatchNorm1d",
"torch.nn.BatchNorm2d",
"torch.rand",
"torch.nn.MaxPool2d",
"torch.nn.LeakyReLU",
"torch.nn.Sigmoid",
"torch.ones_like",
"torch.nn.ReLU",
"torch.stack",
"torch.nn.ConvTranspose2d",
"torch.nn.Sequential",
"torch.nn.functional.softmax",
"numpy.array"
] |
[((1379, 1401), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (1392, 1401), True, 'import torch.nn as nn\n'), ((1850, 1865), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (1863, 1865), True, 'import torch.nn as nn\n'), ((3321, 3336), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (3334, 3336), True, 'import torch.nn as nn\n'), ((5461, 5476), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (5474, 5476), True, 'import torch.nn as nn\n'), ((6126, 6154), 'numpy.arange', 'np.arange', (['(2)', '(num_layers + 1)'], {}), '(2, num_layers + 1)\n', (6135, 6154), True, 'import numpy as np\n'), ((9693, 9707), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (9704, 9707), False, 'import torch\n'), ((9716, 9730), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (9727, 9730), False, 'import torch\n'), ((16600, 16614), 'torch.Tensor', 'torch.Tensor', ([], {}), '()\n', (16612, 16614), False, 'import torch\n'), ((17771, 17785), 'torch.Tensor', 'torch.Tensor', ([], {}), '()\n', (17783, 17785), False, 'import torch\n'), ((19230, 19244), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (19241, 19244), False, 'import torch\n'), ((23135, 23180), 'torch.nn.Linear', 'nn.Linear', (['self.input_dim', 'self.embedding_dim'], {}), '(self.input_dim, self.embedding_dim)\n', (23144, 23180), True, 'import torch.nn as nn\n'), ((23389, 23440), 'torch.nn.LSTM', 'nn.LSTM', (['self.input_dim_decoder', 'self.decoder_h_dim'], {}), '(self.input_dim_decoder, self.decoder_h_dim)\n', (23396, 23440), True, 'import torch.nn as nn\n'), ((25747, 25785), 'torch.stack', 'torch.stack', (['pred_traj_fake_rel'], {'dim': '(0)'}), '(pred_traj_fake_rel, dim=0)\n', (25758, 25785), False, 'import torch\n'), ((25811, 25845), 'torch.stack', 'torch.stack', (['pred_traj_fake'], {'dim': '(0)'}), '(pred_traj_fake, dim=0)\n', (25822, 25845), False, 'import torch\n'), ((27024, 27112), 'torch.nn.Conv2d', 'nn.Conv2d', (['(channels_cnn * 2 ** (num_layers_cnn - 2))', '(1)'], {'kernel_size': '(1, 1)', 'stride': '(1)'}), '(channels_cnn * 2 ** (num_layers_cnn - 2), 1, kernel_size=(1, 1),\n stride=1)\n', (27033, 27112), True, 'import torch.nn as nn\n'), ((27134, 27148), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (27146, 27148), True, 'import torch.nn as nn\n'), ((27376, 27442), 'torch.nn.LSTM', 'nn.LSTM', (['self.embedding_dim', 'self.encoder_h_dim_d'], {'dropout': 'dropout'}), '(self.embedding_dim, self.encoder_h_dim_d, dropout=dropout)\n', (27383, 27442), True, 'import torch.nn as nn\n'), ((28181, 28213), 'torch.nn.Linear', 'nn.Linear', (['(2)', 'self.embedding_dim'], {}), '(2, self.embedding_dim)\n', (28190, 28213), True, 'import torch.nn as nn\n'), ((29977, 30011), 'torch.arange', 'torch.arange', (['(0)', '(grid_size * 2 + 1)'], {}), '(0, grid_size * 2 + 1)\n', (29989, 30011), False, 'import torch\n'), ((33247, 33268), 'torch.cat', 'torch.cat', (['image_list'], {}), '(image_list)\n', (33256, 33268), False, 'import torch\n'), ((33884, 33901), 'torch.rand', 'torch.rand', (['shape'], {}), '(shape)\n', (33894, 33901), False, 'import torch\n'), ((35002, 35023), 'torch.nn.functional.softmax', 'F.softmax', (['alpha', 'dim'], {}), '(alpha, dim)\n', (35011, 35023), True, 'import torch.nn.functional as F\n'), ((842, 868), 'torch.nn.Linear', 'nn.Linear', (['dim_in', 'dim_out'], {}), '(dim_in, dim_out)\n', (851, 868), True, 'import torch.nn as nn\n'), ((1906, 1957), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_dim', 'output_dim', 'filter_size', '(1)', '(1)'], {}), '(input_dim, output_dim, filter_size, 1, 1)\n', (1915, 1957), True, 'import torch.nn as nn\n'), ((2477, 2563), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2, 2)', 'stride': '(2, 2)', 'dilation': '(1, 1)', 'ceil_mode': '(False)'}), '(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1), ceil_mode=\n False)\n', (2489, 2563), True, 'import torch.nn as nn\n'), ((3679, 3740), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['input_dim', 'output_dim', 'filter', '(2)', 'padding'], {}), '(input_dim, output_dim, filter, 2, padding)\n', (3697, 3740), True, 'import torch.nn as nn\n'), ((7040, 7055), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (7053, 7055), True, 'import torch.nn as nn\n'), ((11713, 11748), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'embedding_dim'], {}), '(input_dim, embedding_dim)\n', (11722, 11748), True, 'import torch.nn as nn\n'), ((11776, 11813), 'torch.nn.LSTM', 'nn.LSTM', (['embedding_dim', 'encoder_h_dim'], {}), '(embedding_dim, encoder_h_dim)\n', (11783, 11813), True, 'import torch.nn as nn\n'), ((11855, 11888), 'torch.nn.LSTM', 'nn.LSTM', (['input_dim', 'encoder_h_dim'], {}), '(input_dim, encoder_h_dim)\n', (11862, 11888), True, 'import torch.nn as nn\n'), ((15813, 15867), 'torch.randn', 'torch.randn', (['(1, batch_size, self.noise_attention_dim)'], {}), '((1, batch_size, self.noise_attention_dim))\n', (15824, 15867), False, 'import torch\n'), ((25222, 25263), 'torch.cat', 'torch.cat', (['(state_tuple[0], final_emb)', '(2)'], {}), '((state_tuple[0], final_emb), 2)\n', (25231, 25263), False, 'import torch\n'), ((29511, 29557), 'torch.cat', 'torch.cat', (['(embedded_pos, visual_features)', '(-1)'], {}), '((embedded_pos, visual_features), -1)\n', (29520, 29557), False, 'import torch\n'), ((30392, 30419), 'torch.rand_like', 'torch.rand_like', (['gumbel_map'], {}), '(gumbel_map)\n', (30407, 30419), False, 'import torch\n'), ((32925, 32992), 'torch.zeros', 'torch.zeros', (['(1, self.grid_size * 2 + 1, self.grid_size * 2 + 1, 1)'], {}), '((1, self.grid_size * 2 + 1, self.grid_size * 2 + 1, 1))\n', (32936, 32992), False, 'import torch\n'), ((919, 942), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['dim_out'], {}), '(dim_out)\n', (933, 942), True, 'import torch.nn as nn\n'), ((1003, 1012), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1010, 1012), True, 'import torch.nn as nn\n'), ((1326, 1347), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout'}), '(p=dropout)\n', (1336, 1347), True, 'import torch.nn as nn\n'), ((2024, 2050), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['output_dim'], {}), '(output_dim)\n', (2038, 2050), True, 'import torch.nn as nn\n'), ((2128, 2137), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (2135, 2137), True, 'import torch.nn as nn\n'), ((2626, 2647), 'torch.nn.Dropout2d', 'nn.Dropout2d', (['dropout'], {}), '(dropout)\n', (2638, 2647), True, 'import torch.nn as nn\n'), ((8975, 9029), 'torch.nn.init.kaiming_normal_', 'torch.nn.init.kaiming_normal_', (['m.weight'], {'mode': '"""fan_in"""'}), "(m.weight, mode='fan_in')\n", (9004, 9029), False, 'import torch\n'), ((9329, 9367), 'torch.nn.init.xavier_uniform', 'torch.nn.init.xavier_uniform', (['m.weight'], {}), '(m.weight)\n', (9357, 9367), False, 'import torch\n'), ((10438, 10474), 'torch.cat', 'torch.cat', (['(traj_enc, in_decoder)', '(1)'], {}), '((traj_enc, in_decoder), 1)\n', (10447, 10474), False, 'import torch\n'), ((10659, 10697), 'torch.cat', 'torch.cat', (['(social_enc, in_decoder)', '(1)'], {}), '((social_enc, in_decoder), 1)\n', (10668, 10697), False, 'import torch\n'), ((15924, 15977), 'torch.rand', 'torch.rand', (['(1, batch_size, self.noise_attention_dim)'], {}), '((1, batch_size, self.noise_attention_dim))\n', (15934, 15977), False, 'import torch\n'), ((24782, 24844), 'torch.cat', 'torch.cat', (['(decoder_input, distance_embeding, time_tensor)', '(-1)'], {}), '((decoder_input, distance_embeding, time_tensor), -1)\n', (24791, 24844), False, 'import torch\n'), ((30214, 30236), 'torch.cat', 'torch.cat', (['(x2, x1)', '(2)'], {}), '((x2, x1), 2)\n', (30223, 30236), False, 'import torch\n'), ((1075, 1084), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1082, 1084), True, 'import torch.nn as nn\n'), ((2217, 2226), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2224, 2226), True, 'import torch.nn as nn\n'), ((3843, 3869), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['output_dim'], {}), '(output_dim)\n', (3857, 3869), True, 'import torch.nn as nn\n'), ((3956, 3965), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (3963, 3965), True, 'import torch.nn as nn\n'), ((4250, 4271), 'torch.nn.Dropout2d', 'nn.Dropout2d', (['dropout'], {}), '(dropout)\n', (4262, 4271), True, 'import torch.nn as nn\n'), ((11964, 12005), 'torch.zeros', 'torch.zeros', (['(1)', 'batch', 'self.encoder_h_dim'], {}), '(1, batch, self.encoder_h_dim)\n', (11975, 12005), False, 'import torch\n'), ((12032, 12073), 'torch.zeros', 'torch.zeros', (['(1)', 'batch', 'self.encoder_h_dim'], {}), '(1, batch, self.encoder_h_dim)\n', (12043, 12073), False, 'import torch\n'), ((26069, 26103), 'torch.stack', 'torch.stack', (['img_patch_list'], {'dim': '(0)'}), '(img_patch_list, dim=0)\n', (26080, 26103), False, 'import torch\n'), ((28486, 28529), 'torch.zeros', 'torch.zeros', (['(1)', 'batch', 'self.encoder_h_dim_d'], {}), '(1, batch, self.encoder_h_dim_d)\n', (28497, 28529), False, 'import torch\n'), ((28560, 28603), 'torch.zeros', 'torch.zeros', (['(1)', 'batch', 'self.encoder_h_dim_d'], {}), '(1, batch, self.encoder_h_dim_d)\n', (28571, 28603), False, 'import torch\n'), ((34271, 34310), 'torch.log', 'torch.log', (['(uniform_samples_tensor + eps)'], {}), '(uniform_samples_tensor + eps)\n', (34280, 34310), False, 'import torch\n'), ((1152, 1166), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (1164, 1166), True, 'import torch.nn as nn\n'), ((2311, 2325), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (2323, 2325), True, 'import torch.nn as nn\n'), ((4054, 4063), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4061, 4063), True, 'import torch.nn as nn\n'), ((25128, 25144), 'torch.Tensor', 'torch.Tensor', (['[]'], {}), '([])\n', (25140, 25144), False, 'import torch\n'), ((34925, 34961), 'torch.ones_like', 'torch.ones_like', (['soft_samples_gumble'], {}), '(soft_samples_gumble)\n', (34940, 34961), False, 'import torch\n'), ((1232, 1244), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (1242, 1244), True, 'import torch.nn as nn\n'), ((4157, 4171), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (4169, 4171), True, 'import torch.nn as nn\n'), ((32862, 32883), 'numpy.array', 'np.array', (['cropped_img'], {}), '(cropped_img)\n', (32870, 32883), True, 'import numpy as np\n')]
|
"""Tools for generating maps from a text search."""
import geopy as gp
import numpy as np
import matplotlib.pyplot as plt
import warnings
from .tile import howmany, bounds2raster, bounds2img, _sm2ll, _calculate_zoom
from .plotting import INTERPOLATION, ZOOM, add_attribution
from . import providers
from ._providers import TileProvider
# Set user ID for Nominatim
_val = np.random.randint(1000000)
_default_user_agent = f"contextily_user_{_val}"
class Place(object):
"""Geocode a place by name and get its map.
This allows you to search for a name (e.g., city, street, country) and
grab map and location data from the internet.
Parameters
----------
search : string
The location to be searched.
zoom : int or None
[Optional. Default: None]
The level of detail to include in the map. Higher levels mean more
tiles and thus longer download time. If None, the zoom level will be
automatically determined.
path : str or None
[Optional. Default: None]
Path to a raster file that will be created after getting the place map.
If None, no raster file will be downloaded.
zoom_adjust : int or None
[Optional. Default: None]
The amount to adjust a chosen zoom level if it is chosen automatically.
source : contextily.providers object or str
[Optional. Default: Stamen Terrain web tiles]
The tile source: web tile provider or path to local file. The web tile
provider can be in the form of a `contextily.providers` object or a
URL. The placeholders for the XYZ in the URL need to be `{x}`, `{y}`,
`{z}`, respectively. For local file paths, the file is read with
`rasterio` and all bands are loaded into the basemap.
IMPORTANT: tiles are assumed to be in the Spherical Mercator
projection (EPSG:3857), unless the `crs` keyword is specified.
url : str [DEPRECATED]
[Optional. Default: 'http://tile.stamen.com/terrain/{z}/{x}/{y}.png']
Source url for web tiles, or path to local file. If
local, the file is read with `rasterio` and all
bands are loaded into the basemap.
geocoder : geopy.geocoders
[Optional. Default: geopy.geocoders.Nominatim()] Geocoder method to process `search`
Attributes
----------
geocode : geopy object
The result of calling ``geopy.geocoders.Nominatim`` with ``search`` as input.
s : float
The southern bbox edge.
n : float
The northern bbox edge.
e : float
The eastern bbox edge.
w : float
The western bbox edge.
im : ndarray
The image corresponding to the map of ``search``.
bbox : list
The bounding box of the returned image, expressed in lon/lat, with the
following order: [minX, minY, maxX, maxY]
bbox_map : tuple
The bounding box of the returned image, expressed in Web Mercator, with the
following order: [minX, minY, maxX, maxY]
"""
def __init__(
self,
search,
zoom=None,
path=None,
zoom_adjust=None,
source=None,
url=None,
geocoder=gp.geocoders.Nominatim(user_agent=_default_user_agent),
):
self.path = path
if url is not None and source is None:
warnings.warn(
'The "url" option is deprecated. Please use the "source"'
" argument instead.",
FutureWarning,
stacklevel=2,
)
source = url
elif url is not None and source is not None:
warnings.warn(
'The "url" argument is deprecated. Please use the "source"'
' argument. Do not supply a "url" argument. It will be ignored.',
FutureWarning,
stacklevel=2,
)
if source is None:
source = providers.Stamen.Terrain
self.source = source
self.zoom_adjust = zoom_adjust
# Get geocoded values
resp = geocoder.geocode(search)
bbox = np.array([float(ii) for ii in resp.raw["boundingbox"]])
if "display_name" in resp.raw.keys():
place = resp.raw["display_name"]
elif "address" in resp.raw.keys():
place = resp.raw["address"]
else:
place = search
self.place = place
self.search = search
self.s, self.n, self.w, self.e = bbox
self.bbox = [self.w, self.s, self.e, self.n] # So bbox is standard
self.latitude = resp.latitude
self.longitude = resp.longitude
self.geocode = resp
# Get map params
self.zoom = (
_calculate_zoom(self.w, self.s, self.e, self.n) if zoom is None else zoom
)
self.zoom = int(self.zoom)
if self.zoom_adjust is not None:
self.zoom += zoom_adjust
self.n_tiles = howmany(self.w, self.s, self.e, self.n, self.zoom, verbose=False)
# Get the map
self._get_map()
def _get_map(self):
kwargs = {"ll": True}
if self.source is not None:
kwargs["source"] = self.source
try:
if isinstance(self.path, str):
im, bbox = bounds2raster(
self.w, self.s, self.e, self.n, self.path, zoom=self.zoom, **kwargs
)
else:
im, bbox = bounds2img(
self.w, self.s, self.e, self.n, self.zoom, **kwargs
)
except Exception as err:
raise ValueError(
"Could not retrieve map with parameters: {}, {}, {}, {}, zoom={}\n{}\nError: {}".format(
self.w, self.s, self.e, self.n, self.zoom, kwargs, err
)
)
self.im = im
self.bbox_map = bbox
return im, bbox
def plot(self, ax=None, zoom=ZOOM, interpolation=INTERPOLATION, attribution=None):
"""
Plot a `Place` object
...
Parameters
----------
ax : AxesSubplot
Matplotlib axis with `x_lim` and `y_lim` set in Web
Mercator (EPSG=3857). If not provided, a new
12x12 figure will be set and the name of the place
will be added as title
zoom : int/'auto'
[Optional. Default='auto'] Level of detail for the
basemap. If 'auto', if calculates it automatically.
Ignored if `source` is a local file.
interpolation : str
[Optional. Default='bilinear'] Interpolation
algorithm to be passed to `imshow`. See
`matplotlib.pyplot.imshow` for further details.
attribution : str
[Optional. Defaults to attribution specified by the source of the map tiles]
Text to be added at the bottom of the axis. This
defaults to the attribution of the provider specified
in `source` if available. Specify False to not
automatically add an attribution, or a string to pass
a custom attribution.
Returns
-------
ax : AxesSubplot
Matplotlib axis with `x_lim` and `y_lim` set in Web
Mercator (EPSG=3857) containing the basemap
Examples
--------
>>> lvl = ctx.Place('Liverpool')
>>> lvl.plot()
"""
im = self.im
bbox = self.bbox_map
title = None
axisoff = False
if ax is None:
fig, ax = plt.subplots(figsize=(12, 12))
title = self.place
axisoff = True
ax.imshow(im, extent=bbox, interpolation=interpolation)
ax.set(xlabel="X", ylabel="Y")
if isinstance(self.source, (dict, TileProvider)) and attribution is None:
attribution = self.source.get("attribution")
if attribution:
add_attribution(ax, attribution)
if title is not None:
ax.set(title=title)
if axisoff:
ax.set_axis_off()
return ax
def __repr__(self):
s = "Place : {} | n_tiles: {} | zoom : {} | im : {}".format(
self.place, self.n_tiles, self.zoom, self.im.shape[:2]
)
return s
def plot_map(
place, bbox=None, title=None, ax=None, axis_off=True, latlon=True, attribution=None
):
"""Plot a map of the given place.
Parameters
----------
place : instance of Place or ndarray
The map to plot. If an ndarray, this must be an image corresponding
to a map. If an instance of ``Place``, the extent of the image and name
will be inferred from the bounding box.
ax : instance of matplotlib Axes object or None
The axis on which to plot. If None, one will be created.
axis_off : bool
Whether to turn off the axis border and ticks before plotting.
attribution : str
[Optional. Default to standard `ATTRIBUTION`] Text to be added at the
bottom of the axis.
Returns
-------
ax : instance of matplotlib Axes object or None
The axis on the map is plotted.
"""
warnings.warn(
(
"The method `plot_map` is deprecated and will be removed from the"
" library in future versions. Please use either `add_basemap` or"
" the internal method `Place.plot`"
),
DeprecationWarning,
)
if not isinstance(place, Place):
im = place
bbox = bbox
title = title
else:
im = place.im
if bbox is None:
bbox = place.bbox_map
if latlon is True:
# Convert w, s, e, n into lon/lat
w, e, s, n = bbox
w, s = _sm2ll(w, s)
e, n = _sm2ll(e, n)
bbox = [w, e, s, n]
title = place.place if title is None else title
if ax is None:
fig, ax = plt.subplots(figsize=(15, 15))
ax.imshow(im, extent=bbox)
ax.set(xlabel="X", ylabel="Y")
if title is not None:
ax.set(title=title)
if attribution:
add_attribution(ax, attribution)
if axis_off is True:
ax.set_axis_off()
return ax
|
[
"warnings.warn",
"numpy.random.randint",
"matplotlib.pyplot.subplots",
"geopy.geocoders.Nominatim"
] |
[((373, 399), 'numpy.random.randint', 'np.random.randint', (['(1000000)'], {}), '(1000000)\n', (390, 399), True, 'import numpy as np\n'), ((9145, 9352), 'warnings.warn', 'warnings.warn', (['"""The method `plot_map` is deprecated and will be removed from the library in future versions. Please use either `add_basemap` or the internal method `Place.plot`"""', 'DeprecationWarning'], {}), "(\n 'The method `plot_map` is deprecated and will be removed from the library in future versions. Please use either `add_basemap` or the internal method `Place.plot`'\n , DeprecationWarning)\n", (9158, 9352), False, 'import warnings\n'), ((3185, 3239), 'geopy.geocoders.Nominatim', 'gp.geocoders.Nominatim', ([], {'user_agent': '_default_user_agent'}), '(user_agent=_default_user_agent)\n', (3207, 3239), True, 'import geopy as gp\n'), ((9927, 9957), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(15, 15)'}), '(figsize=(15, 15))\n', (9939, 9957), True, 'import matplotlib.pyplot as plt\n'), ((3332, 3461), 'warnings.warn', 'warnings.warn', (['"""The "url" option is deprecated. Please use the "source" argument instead."""', 'FutureWarning'], {'stacklevel': '(2)'}), '(\n \'The "url" option is deprecated. Please use the "source" argument instead.\'\n , FutureWarning, stacklevel=2)\n', (3345, 3461), False, 'import warnings\n'), ((7541, 7571), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (7553, 7571), True, 'import matplotlib.pyplot as plt\n'), ((3624, 3799), 'warnings.warn', 'warnings.warn', (['"""The "url" argument is deprecated. Please use the "source" argument. Do not supply a "url" argument. It will be ignored."""', 'FutureWarning'], {'stacklevel': '(2)'}), '(\n \'The "url" argument is deprecated. Please use the "source" argument. Do not supply a "url" argument. It will be ignored.\'\n , FutureWarning, stacklevel=2)\n', (3637, 3799), False, 'import warnings\n')]
|
#!/usr/bin/env python
# Copyright (c) 2017, DIANA-HEP
# 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 the copyright holder 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 copy
import numbers
import functools
import numpy
import oamap.generator
import oamap.operations
import oamap.proxy
import oamap.schema
import oamap.util
class SingleThreadExecutor(object):
class PseudoFuture(object):
def __init__(self, result):
self._result = result
def result(self, timeout=None):
return self._result
def done(self):
return True
def exception(self, timeout=None):
raise NotImplementedError
def traceback(self, timeout=None):
raise NotImplementedError
def submit(self, fcn, *args, **kwargs):
args = tuple(x.result() if isinstance(x, self.PseudoFuture) else x for x in args)
kwargs = dict((n, x.result() if isinstance(x, self.PseudoFuture) else x) for n, x in kwargs.items())
return self.PseudoFuture(fcn(*args, **kwargs))
class Operation(object):
def __init__(self, name, args, kwargs, function):
self._name = name
self._args = args
self._kwargs = kwargs
self._function = function
def __repr__(self):
return "<{0} {1} {2} {3}>".format(self.__class__.__name__, self._name, repr(self._args), repr(self._kwargs))
def __str__(self):
return ".{0}({1}{2})".format(self._name, ", ".join(repr(x) for x in self._args), "".join(", {0}={1}".format(n, repr(x)) for n, x in self._kwargs.items()))
@property
def name(self):
return self._name
@property
def args(self):
return self._args
@property
def kwargs(self):
return self._kwargs
@property
def function(self):
return self._function
def apply(self, data):
return self._function(*((data,) + self._args), **self._kwargs)
class Recasting(Operation): pass
class Transformation(Operation): pass
class Action(Operation): pass
class Operable(object):
def __init__(self):
self._operations = ()
@staticmethod
def update_operations():
def newrecasting(name, function):
@functools.wraps(function)
def recasting(self, *args, **kwargs):
out = self.__class__.__new__(self.__class__)
Operable.__init__(out)
out.__dict__ = self.__dict__.copy()
out._operations = self._operations + (Recasting(name, args, kwargs, function),)
return out
return recasting
def newtransformation(name, function):
@functools.wraps(function)
def transformation(self, *args, **kwargs):
out = self.__class__.__new__(self.__class__)
Operable.__init__(out)
out.__dict__ = self.__dict__.copy()
out._operations = self._operations + (Transformation(name, args, kwargs, function),)
return out
return transformation
def newaction(name, function):
@functools.wraps(function)
def action(self, *args, **kwargs):
try:
combiner = kwargs.pop("combiner")
except KeyError:
combiner = function.combiner
out = self.__class__.__new__(self.__class__)
Operable.__init__(out)
out.__dict__ = self.__dict__.copy()
out._operations = self._operations + (Action(name, args, kwargs, function),)
return out.act(combiner)
return action
for n, x in oamap.operations.recastings.items():
setattr(Operable, n, oamap.util.MethodType(newrecasting(n, x), None, Operable))
for n, x in oamap.operations.transformations.items():
setattr(Operable, n, oamap.util.MethodType(newtransformation(n, x), None, Operable))
for n, x in oamap.operations.actions.items():
setattr(Operable, n, oamap.util.MethodType(newaction(n, x), None, Operable))
def _nooperations(self):
return len(self._operations) == 0
def _notransformations(self):
return all(isinstance(x, Recasting) for x in self._operations)
Operable.update_operations()
class _Data(Operable):
def __init__(self, name, schema, backends, executor, extension=None, packing=None, doc=None, metadata=None):
super(_Data, self).__init__()
self._name = name
self._schema = schema
self._backends = backends
self._executor = executor
self._extension = extension
self._packing = packing
self._doc = doc
self._metadata = metadata
self._cachedobject = None
def __repr__(self):
return "<Data {0}>{1}".format(repr(self._name), "".join(str(x) for x in self._operations))
def __str__(self):
return "<Data {0}>{1}".format(repr(self._name), "".join("\n " + str(x) for x in self._operations))
@property
def name(self):
return self._name
@property
def schema(self):
return self._schema.deepcopy()
@property
def extension(self):
return self._extension
@property
def packing(self):
return self._packing
@property
def doc(self):
return self._doc
@property
def metadata(self):
return self._metadata
def arrays(self):
return DataArrays(self._backends)
def transform(self, name, namespace, update):
if self._nooperations():
return [SingleThreadExecutor.PseudoFuture(update(self))]
elif self._notransformations():
result = self()
for operation in self._operations:
result = operation.apply(result)
if isinstance(result, oamap.proxy.ListProxy):
out = Dataset(name, result._generator.schema, self._backends, self._executor, [0, len(result)], extension=self._extension, packing=None, doc=self._doc, metadata=self._metadata)
else:
out = Data(name, result._generator.schema, self._backends, self._executor, extension=self._extension, packing=None, doc=self._doc, metadata=self._metadata)
return [SingleThreadExecutor.PseudoFuture(update(out))]
else:
def task(name, dataset, namespace, update):
result = dataset()
for operation in dataset._operations:
result = operation.apply(result)
backend = dataset._backends[namespace]
schema, roles2arrays = oamap.operations._DualSource.collect(result._generator.namedschema(), result._arrays, namespace, backend.prefix(name), backend.delimiter())
active = backend.instantiate(0)
if hasattr(active, "putall"):
active.putall(roles2arrays)
else:
for n, x in roles2arrays.items():
active[str(n)] = x
if isinstance(result, oamap.proxy.ListProxy):
out = Dataset(name, schema, dataset._backends, dataset._executor, [0, len(result)], extension=dataset._extension, packing=None, doc=dataset._doc, metadata=dataset._metadata)
else:
out = Data(name, schema, dataset._backends, dataset._executor, extension=dataset._extension, packing=None, doc=dataset._doc, metadata=dataset._metadata)
return update(out)
return [self._executor.submit(task, name, self, namespace, update)]
def act(self, combiner):
def task(dataset):
result = dataset()
for operation in dataset._operations:
result = operation.apply(result)
return result
return combiner([self._executor.submit(task, self)])
class Data(_Data):
def __call__(self):
if self._cachedobject is None:
if self._extension is None:
extension = oamap.util.import_module("oamap.extension.common")
elif isinstance(self._extension, basestring):
extension = oamap.util.import_module(self._extension)
else:
extension = [oamap.util.import_module(x) for x in self._extension]
self._cachedobject = self._schema(self.arrays(), extension=extension, packing=self._packing)
return self._cachedobject
class DataArrays(object):
def __init__(self, backends):
self._backends = backends
self._active = {}
self._partitionid = 0
def _toplevel(self, out, filtered):
return filtered
def getall(self, roles):
out = {}
for namespace, backend in self._backends.items():
filtered = self._toplevel(out, [x for x in roles if x.namespace == namespace])
if len(filtered) > 0:
active = self._active.get(namespace, None)
if active is None:
active = self._active[namespace] = backend.instantiate(self._partitionid)
if hasattr(active, "getall"):
out.update(active.getall(filtered))
else:
for x in roles:
out[x] = active[str(x)]
return out
def close(self):
for namespace, active in self._active.items():
if hasattr(active, "close"):
active.close()
self._active[namespace] = None
class Dataset(_Data):
def __init__(self, name, schema, backends, executor, offsets, extension=None, packing=None, doc=None, metadata=None):
if not isinstance(schema, oamap.schema.List):
raise TypeError("Dataset must have a list schema, not\n\n {0}".format(schema.__repr__(indent=" ")))
super(Dataset, self).__init__(name, schema, backends, executor, extension=extension, packing=packing, doc=doc, metadata=metadata)
if not isinstance(offsets, numpy.ndarray):
try:
if not all(isinstance(x, (numbers.Integral, numpy.integer)) and x >= 0 for x in offsets):
raise TypeError
except TypeError:
raise TypeError("offsets must be an iterable of non-negative integers")
offsets = numpy.array(offsets, dtype=numpy.int64)
if len(offsets.shape) != 1:
raise ValueError("offsets must be one-dimensional")
if len(offsets) < 2 or offsets[0] != 0:
raise ValueError("offsets must have at least two items, and the first one must be zero")
if not numpy.all(offsets[:-1] <= offsets[1:]):
raise ValueError("offsets must be monotonically increasing")
self._offsets = offsets
self._cachedpartition = None
def __repr__(self):
return "<Dataset {0} {1} partitions {2} entries>{3}".format(repr(self._name), self.numpartitions, self.numentries, "".join(str(x) for x in self._operations))
def __str__(self):
return "<Dataset {0} {1} partitions {2} entries>{3}".format(repr(self._name), self.numpartitions, self.numentries, "".join("\n " + str(x) for x in self._operations))
@property
def offsets(self):
return self._offsets.tolist()
@property
def starts(self):
return self._offsets[:-1].tolist()
@property
def stops(self):
return self._offsets[1:].tolist()
@property
def partitions(self):
return zip(self.start, self.stop)
@property
def numpartitions(self):
return len(self._offsets) - 1
@property
def numentries(self):
return int(self._offsets[-1])
def partition(self, partitionid):
if self._cachedpartition != partitionid:
self._cachedpartition = partitionid
if self._extension is None:
extension = oamap.util.import_module("oamap.extension.common")
elif isinstance(self._extension, basestring):
extension = oamap.util.import_module(self._extension)
else:
extension = [oamap.util.import_module(x) for x in self._extension]
self._cachedobject = self._schema(self.arrays(partitionid), extension=extension, packing=self._packing)
return self._cachedobject
def __iter__(self):
for partitionid in range(self.numpartitions):
for i in range(self._offsets[partitionid], self._offsets[partitionid + 1]):
yield self[i]
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = oamap.util.slice2sss(index, self.numentries)
partitionid = max(0, min(numpy.searchsorted(self._offsets, start, side="right") - 1, self.numpartitions - 1))
localstart = start - self._offsets[partitionid]
localstop = stop - self._offsets[partitionid]
if localstop < -1 or localstop > (self._offsets[partitionid + 1] - self._offsets[partitionid]):
raise IndexError("slice spans multiple partitions")
out = self.partition(partitionid)
out._whence = localstart
out._stride = step
# out._length = int(math.ceil(float(abs(localstop - localstart)) / abs(step)))
d, m = divmod(abs(localstart - localstop), abs(step))
out._length = d + (1 if m != 0 else 0)
return out
else:
normindex = index if index >= 0 else index + self.numentries
if not 0 <= normindex < self.numentries:
raise IndexError("index {0} out of range for {1} entries".format(index, self.numentries))
partitionid = numpy.searchsorted(self._offsets, normindex, side="right") - 1
localindex = normindex - self._offsets[partitionid]
return self.partition(partitionid)[localindex]
def arrays(self, partitionid):
normid = partitionid if partitionid >= 0 else partitionid + self.numpartitions
if not 0 <= normid < self.numpartitions:
raise IndexError("partitionid {0} out of range for {1} partitions".format(partitionid, self.numpartitions))
startsrole = oamap.generator.StartsRole(self._schema._get_starts("object", "-"), self._schema.namespace, None)
stopsrole = oamap.generator.StopsRole(self._schema._get_stops("object", "-"), self._schema.namespace, None)
startsrole.stops = stopsrole
stopsrole.starts = startsrole
return DatasetArrays(normid, startsrole, stopsrole, self._offsets[normid + 1] - self._offsets[normid], self._backends)
def transform(self, name, namespace, update):
if self._nooperations():
return [SingleThreadExecutor.PseudoFuture(update(self))]
elif self._notransformations():
result = self.partition(0)
for operation in self._operations:
result = operation.apply(result)
if isinstance(result, oamap.proxy.ListProxy):
out = Dataset(name, result._generator.schema, self._backends, self._executor, self._offsets, extension=self._extension, packing=None, doc=self._doc, metadata=self._metadata)
else:
out = Data(name, result._generator.schema, self._backends, self._executor, extension=self._extension, packing=None, doc=self._doc, metadata=self._metadata)
return [SingleThreadExecutor.PseudoFuture(update(out))]
else:
def task(name, dataset, namespace, partitionid):
result = dataset.partition(partitionid)
for operation in dataset._operations:
result = operation.apply(result)
backend = dataset._backends[namespace]
schema, roles2arrays = oamap.operations._DualSource.collect(result._generator.namedschema(), result._arrays, namespace, backend.prefix(name), backend.delimiter())
active = backend.instantiate(partitionid)
if hasattr(active, "putall"):
active.putall(roles2arrays)
else:
for n, x in roles2arrays.items():
active[str(n)] = x
if isinstance(result, oamap.proxy.ListProxy):
return schema, len(result)
else:
return schema, 1
tasks = [self._executor.submit(task, name, self, namespace, i) for i in range(self.numpartitions)]
def collect(name, dataset, results, update):
if isinstance(results[0], tuple) and len(results[0]) == 2 and isinstance(results[0][0], oamap.schema.Schema):
offsets = numpy.cumsum([0] + [numentries for schema, numentries in results], dtype=numpy.int64)
schema = results[0][0]
else:
offsets = numpy.cumsum([0] + [x.result()[1] for x in results], dtype=numpy.int64)
schema = results[0].result()[0]
if isinstance(schema, oamap.schema.List):
out = Dataset(name, schema, dataset._backends, dataset._executor, offsets, extension=dataset._extension, packing=None, doc=dataset._doc, metadata=dataset._metadata)
else:
out = Data(name, schema, dataset._backends, dataset._executor, extension=dataset._extension, packing=None, doc=dataset._doc, metadata=dataset._metadata)
return update(out)
tasks.append(self._executor.submit(collect, name, self, tuple(tasks), update))
return tasks
def act(self, combiner):
def task(dataset, partitionid):
result = dataset.partition(partitionid)
for operation in dataset._operations:
result = operation.apply(result)
return result
return combiner([self._executor.submit(task, self, i) for i in range(self.numpartitions)])
class DatasetArrays(DataArrays):
def __init__(self, partitionid, startsrole, stopsrole, numentries, backends):
super(DatasetArrays, self).__init__(backends)
self._partitionid = partitionid
self._startsrole = startsrole
self._stopsrole = stopsrole
self._numentries = numentries
def _toplevel(self, out, filtered):
try:
index = filtered.index(self._startsrole)
except ValueError:
pass
else:
del filtered[index]
out[self._startsrole] = numpy.array([0], dtype=oamap.generator.ListGenerator.posdtype)
try:
index = filtered.index(self._stopsrole)
except ValueError:
pass
else:
del filtered[index]
out[self._stopsrole] = numpy.array([self._numentries], dtype=oamap.generator.ListGenerator.posdtype)
return filtered
|
[
"numpy.searchsorted",
"numpy.cumsum",
"numpy.array",
"functools.wraps",
"numpy.all"
] |
[((3620, 3645), 'functools.wraps', 'functools.wraps', (['function'], {}), '(function)\n', (3635, 3645), False, 'import functools\n'), ((4061, 4086), 'functools.wraps', 'functools.wraps', (['function'], {}), '(function)\n', (4076, 4086), False, 'import functools\n'), ((4509, 4534), 'functools.wraps', 'functools.wraps', (['function'], {}), '(function)\n', (4524, 4534), False, 'import functools\n'), ((11761, 11800), 'numpy.array', 'numpy.array', (['offsets'], {'dtype': 'numpy.int64'}), '(offsets, dtype=numpy.int64)\n', (11772, 11800), False, 'import numpy\n'), ((12065, 12103), 'numpy.all', 'numpy.all', (['(offsets[:-1] <= offsets[1:])'], {}), '(offsets[:-1] <= offsets[1:])\n', (12074, 12103), False, 'import numpy\n'), ((19925, 19987), 'numpy.array', 'numpy.array', (['[0]'], {'dtype': 'oamap.generator.ListGenerator.posdtype'}), '([0], dtype=oamap.generator.ListGenerator.posdtype)\n', (19936, 19987), False, 'import numpy\n'), ((20179, 20256), 'numpy.array', 'numpy.array', (['[self._numentries]'], {'dtype': 'oamap.generator.ListGenerator.posdtype'}), '([self._numentries], dtype=oamap.generator.ListGenerator.posdtype)\n', (20190, 20256), False, 'import numpy\n'), ((15136, 15194), 'numpy.searchsorted', 'numpy.searchsorted', (['self._offsets', 'normindex'], {'side': '"""right"""'}), "(self._offsets, normindex, side='right')\n", (15154, 15194), False, 'import numpy\n'), ((14137, 14191), 'numpy.searchsorted', 'numpy.searchsorted', (['self._offsets', 'start'], {'side': '"""right"""'}), "(self._offsets, start, side='right')\n", (14155, 14191), False, 'import numpy\n'), ((18127, 18217), 'numpy.cumsum', 'numpy.cumsum', (['([0] + [numentries for schema, numentries in results])'], {'dtype': 'numpy.int64'}), '([0] + [numentries for schema, numentries in results], dtype=\n numpy.int64)\n', (18139, 18217), False, 'import numpy\n')]
|
def load_data(logfile=None):
import datetime
import time
import numpy as np
import csv
from datetime import datetime
from keras.preprocessing.sequence import pad_sequences
vocabulary = list()
csvfile = open(logfile, 'r')
if "receipt" in logfile: # For Receipt Dataset
logreader = csv.reader(csvfile, delimiter=',')
elif "helpdesk" in logfile:
logreader = csv.reader(csvfile, delimiter=';') # For Helpdesk Dataset
next(logreader, None) # skip the headers
lastcase = ''
casestarttime = None
lasteventtime = None
firstLine = True
lines = [] #these are all the activity seq
timeseqs = [] #time sequences (differences between two events)
trace_start_list = []
numcases = 0
max_length = 0
trace_start_index = 0
for row in logreader:
if "receipt" in logfile: # For Receipt Dataset
t = datetime.strptime(row[2], "%Y-%m-%d %H:%M:%S.%f")
elif "helpdesk" in logfile:
t = datetime.strptime(row[2], "%d.%m.%Y-%H:%M:%S") # For Helpdesk Dataset
if row[0]!=lastcase: #'lastcase' is to save the last executed case for the loop
casestarttime = t
lasteventtime = t
lastcase = row[0]
if not firstLine:
lines.append(line)
timeseqs.append(times)
if len(line) > max_length:
max_length = len(line)
line = []
times = []
numcases += 1
if trace_start_index != 0:
trace_start_index-=1 # To remove index for last case which is not counted as a prefix
trace_start_list.append(trace_start_index)
elif trace_start_index == 0:
trace_start_list.append(trace_start_index)
if row[1] not in vocabulary:
vocabulary.append(row[1])
line.append(row[1])
timesincelastevent = t - lasteventtime
timediff = 86400 * timesincelastevent.days + timesincelastevent.seconds + timesincelastevent.microseconds/1000000
# +1 avoid zero
times.append(timediff+1)
lasteventtime = t
firstLine = False
trace_start_index+=1
lines.append(line)
timeseqs.append(times)
vocabulary = {key: idx for idx, key in enumerate(vocabulary)}
divisor = np.mean([item for sublist in timeseqs for item in sublist]) #average time between events
numcases += 1
print("Num cases: ", numcases)
elems_per_fold = int(round(numcases/3))
if len(line) > max_length:
max_length = len(line)
X = []
X1 = []
y = []
y_t = []
categorical_features_name = []
categorical_features_time = []
max_length = 0
prefix_sizes = []
seqs = 0
vocab = set()
count = 0
for seq, time in zip(lines, timeseqs):
code = []
code.append(vocabulary[seq[0]])
code1 = []
code1.append(np.log(time[0]+1))
vocab.add(seq[0])
for i in range(1,len(seq)):
prefix_sizes.append(len(code))
if len(code)>max_length:
max_length = len(code)
# Building Activity Names and Time from Index for Explainability part
sub_feature_name = []
sub_feature_time = []
vocabulary_clone = vocabulary.copy()
for j in code[:]:
for name, index in vocabulary_clone.items():
if index == j:
sub_feature_name.append(name)
sub_feature_time.append("Time corresponding to "+name)
categorical_features_name.append(sub_feature_name)
categorical_features_time.append(sub_feature_time)
X.append(code[:])
X1.append(code1[:])
y.append(vocabulary[seq[i]])
y_t.append(time[i]/divisor)
code.append(vocabulary[seq[i]])
code1.append(np.log(time[i]+1))
seqs += 1
vocab.add(seq[i])
prefix_sizes = np.array(prefix_sizes)
print("Num sequences:", seqs)
vocab_size = len(vocab)
X = np.array(X)
X1 = np.array(X1)
y = np.array(y)
y_t = np.array(y_t)
categorical_features_name = np.array(categorical_features_name)
categorical_features_time = np.array(categorical_features_time)
y_unique = np.unique(y)
dict_y = {}
i = 0
for el in y_unique:
dict_y[el] = i
i += 1
for i in range(len(y)):
y[i] = dict_y[y[i]]
y_unique = np.unique(y, return_counts=True)
print("Classes: ", y_unique)
n_classes = y_unique[0].shape[0]
# Establishing vocabulary for classes by removing non-predicatable class from vocabulary (For Helpdesk Dataset)
rebel = int
vocabulary_class = {}
# Finding where the class occurs which is not to be predicted
for key,value in enumerate(dict_y):
if (key!=value):
rebel = key
break
# deleting that class from dictionary
for name in vocabulary_clone.copy():
if (vocabulary_clone[name] == rebel):
vocabulary_clone.pop(name)
vocabulary_class = vocabulary_clone.copy()
for index,name in enumerate(vocabulary_class.copy()):
vocabulary_class[name] = index
# padding
padded_X = pad_sequences(X, maxlen=max_length, padding='pre', dtype='float64')
padded_X1 = pad_sequences(X1, maxlen=max_length, padding='pre', dtype='float64')
padded_features = pad_sequences(categorical_features_name, maxlen=max_length, padding='pre', dtype=object, value="Zero Padded Feature") #Padding feature name for Padded feature
padded_features_time = pad_sequences(categorical_features_time, maxlen=max_length, padding='pre', dtype=object, value="Zero Padded Feature") #Padding feature time for Padded feature
return ( (padded_X, padded_X1), (y, y_t), vocab_size, max_length, n_classes, divisor, prefix_sizes, vocabulary, vocabulary_class, padded_features, padded_features_time, categorical_features_name, trace_start_list)
|
[
"csv.reader",
"numpy.log",
"keras.preprocessing.sequence.pad_sequences",
"datetime.datetime.strptime",
"numpy.mean",
"numpy.array",
"numpy.unique"
] |
[((2377, 2436), 'numpy.mean', 'np.mean', (['[item for sublist in timeseqs for item in sublist]'], {}), '([item for sublist in timeseqs for item in sublist])\n', (2384, 2436), True, 'import numpy as np\n'), ((4099, 4121), 'numpy.array', 'np.array', (['prefix_sizes'], {}), '(prefix_sizes)\n', (4107, 4121), True, 'import numpy as np\n'), ((4193, 4204), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (4201, 4204), True, 'import numpy as np\n'), ((4214, 4226), 'numpy.array', 'np.array', (['X1'], {}), '(X1)\n', (4222, 4226), True, 'import numpy as np\n'), ((4235, 4246), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (4243, 4246), True, 'import numpy as np\n'), ((4257, 4270), 'numpy.array', 'np.array', (['y_t'], {}), '(y_t)\n', (4265, 4270), True, 'import numpy as np\n'), ((4304, 4339), 'numpy.array', 'np.array', (['categorical_features_name'], {}), '(categorical_features_name)\n', (4312, 4339), True, 'import numpy as np\n'), ((4372, 4407), 'numpy.array', 'np.array', (['categorical_features_time'], {}), '(categorical_features_time)\n', (4380, 4407), True, 'import numpy as np\n'), ((4424, 4436), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (4433, 4436), True, 'import numpy as np\n'), ((4596, 4628), 'numpy.unique', 'np.unique', (['y'], {'return_counts': '(True)'}), '(y, return_counts=True)\n', (4605, 4628), True, 'import numpy as np\n'), ((5384, 5451), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['X'], {'maxlen': 'max_length', 'padding': '"""pre"""', 'dtype': '"""float64"""'}), "(X, maxlen=max_length, padding='pre', dtype='float64')\n", (5397, 5451), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((5468, 5536), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['X1'], {'maxlen': 'max_length', 'padding': '"""pre"""', 'dtype': '"""float64"""'}), "(X1, maxlen=max_length, padding='pre', dtype='float64')\n", (5481, 5536), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((5559, 5680), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['categorical_features_name'], {'maxlen': 'max_length', 'padding': '"""pre"""', 'dtype': 'object', 'value': '"""Zero Padded Feature"""'}), "(categorical_features_name, maxlen=max_length, padding='pre',\n dtype=object, value='Zero Padded Feature')\n", (5572, 5680), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((5745, 5866), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['categorical_features_time'], {'maxlen': 'max_length', 'padding': '"""pre"""', 'dtype': 'object', 'value': '"""Zero Padded Feature"""'}), "(categorical_features_time, maxlen=max_length, padding='pre',\n dtype=object, value='Zero Padded Feature')\n", (5758, 5866), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((331, 365), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (341, 365), False, 'import csv\n'), ((420, 454), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""";"""'}), "(csvfile, delimiter=';')\n", (430, 454), False, 'import csv\n'), ((919, 968), 'datetime.datetime.strptime', 'datetime.strptime', (['row[2]', '"""%Y-%m-%d %H:%M:%S.%f"""'], {}), "(row[2], '%Y-%m-%d %H:%M:%S.%f')\n", (936, 968), False, 'from datetime import datetime\n'), ((2975, 2994), 'numpy.log', 'np.log', (['(time[0] + 1)'], {}), '(time[0] + 1)\n', (2981, 2994), True, 'import numpy as np\n'), ((1022, 1068), 'datetime.datetime.strptime', 'datetime.strptime', (['row[2]', '"""%d.%m.%Y-%H:%M:%S"""'], {}), "(row[2], '%d.%m.%Y-%H:%M:%S')\n", (1039, 1068), False, 'from datetime import datetime\n'), ((3995, 4014), 'numpy.log', 'np.log', (['(time[i] + 1)'], {}), '(time[i] + 1)\n', (4001, 4014), True, 'import numpy as np\n')]
|
from path import Path
import cv2
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
root =Path('/home/roit/aws/aprojects/xdr94_mono2/mc_test_gt')
out_p = Path('./plasma_gt')
out_p.mkdir_p()
files = root.files()
def main():
cnt=0
for item in tqdm(files):
img = cv2.imread(item)
img =255- cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
img = img/np.mean(img)
plt.imsave(out_p/item.stem+'.png',img,cmap='plasma')
cnt+=1
pass
if __name__ == '__main__':
main()
|
[
"tqdm.tqdm",
"cv2.cvtColor",
"cv2.imread",
"path.Path",
"numpy.mean",
"matplotlib.pyplot.imsave"
] |
[((112, 167), 'path.Path', 'Path', (['"""/home/roit/aws/aprojects/xdr94_mono2/mc_test_gt"""'], {}), "('/home/roit/aws/aprojects/xdr94_mono2/mc_test_gt')\n", (116, 167), False, 'from path import Path\n'), ((176, 195), 'path.Path', 'Path', (['"""./plasma_gt"""'], {}), "('./plasma_gt')\n", (180, 195), False, 'from path import Path\n'), ((273, 284), 'tqdm.tqdm', 'tqdm', (['files'], {}), '(files)\n', (277, 284), False, 'from tqdm import tqdm\n'), ((301, 317), 'cv2.imread', 'cv2.imread', (['item'], {}), '(item)\n', (311, 317), False, 'import cv2\n'), ((412, 470), 'matplotlib.pyplot.imsave', 'plt.imsave', (["(out_p / item.stem + '.png')", 'img'], {'cmap': '"""plasma"""'}), "(out_p / item.stem + '.png', img, cmap='plasma')\n", (422, 470), True, 'import matplotlib.pyplot as plt\n'), ((336, 373), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2GRAY'], {}), '(img, cv2.COLOR_RGB2GRAY)\n', (348, 373), False, 'import cv2\n'), ((391, 403), 'numpy.mean', 'np.mean', (['img'], {}), '(img)\n', (398, 403), True, 'import numpy as np\n')]
|
"""
General purpose rational polynomial tools
"""
__classification__ = "UNCLASSIFIED"
__author__ = "<NAME>"
import logging
from typing import List, Sequence
import numpy
from numpy.polynomial import polynomial
from scipy.linalg import lstsq, LinAlgError
from sarpy.compliance import SarpyError
logger = logging.getLogger(__name__)
class SarpyRatPolyError(SarpyError):
"""A custom exception class for rational polynomial fitting errors."""
#################
# helper functions
def _get_num_variables(coeff_list):
"""
Determine the number of variables by inspection of the coefficient list
Parameters
----------
coeff_list : Sequence
Returns
-------
int
"""
variables = None
for entry in coeff_list:
if isinstance(entry, int):
if variables is None:
variables = 1
elif variables != 1:
raise ValueError('Entry order mismatch')
else:
if variables is None:
variables = len(entry)
elif variables != len(entry):
raise ValueError('Entry order mismatch')
if variables is None:
raise ValueError('Unable to determine the number of variables')
return variables
def _map_list_to_poly_matrix(coeffs, coeff_list):
"""
Maps the coefficients and coefficient listing to corresponding
numpy polynomial coefficient matrix.
Parameters
----------
coeffs : Sequence
coeff_list : Sequence
Returns
-------
coefficient_array : numpy.ndarray
"""
variables = _get_num_variables(coeff_list)
matrix_shape = []
for i in range(variables):
matrix_shape.append(max(entry[i] for entry in coeff_list)+1)
coefficient_array = numpy.zeros(tuple(matrix_shape), dtype='float64')
for i, entry in enumerate(coeff_list):
coefficient_array[entry] = coeffs[i]
return coefficient_array
def get_default_coefficient_ordering(variables, order):
"""
Gets a sensible coefficient ordering of a polynomial of given number of
variables and order.
Parameters
----------
variables : int
order : int
Returns
-------
coefficient_list : List[tuple]
List of the form `[(exponent 0, exponent 1, ...)]`, determining the ordering
of monomial terms in the associated multivariable polynomial.
"""
variables = int(variables)
order = int(order)
if variables < 1:
raise ValueError('variables must be at least 1')
if order < 1:
raise ValueError('order must be at least 1')
shape_details = tuple([order + 1 for _ in range(variables)])
coefficient_list = []
for index in numpy.ndindex(shape_details):
total_exponent = sum(index)
if total_exponent <= order:
coefficient_list.append(index)
return coefficient_list
###################
# base rational polynomial fitting functions
def rational_poly_fit_1d(x, data, coeff_list, cond=None):
"""
Fits a one variable rational polynomial according to the input coefficient
listing order.
Parameters
----------
x : numpy.ndarray
data : numpy.ndarray
coeff_list : List
cond : None|float
Passed through to :func:`scipy.linalg.lstsq`.
"""
if coeff_list[0] not in [0, (0, )]:
raise ValueError(
'The first entry of coeff_list is required to be the constant term `0`')
if not (x.size == data.size):
raise ValueError('Size mismatch among data entries')
x = x.flatten()
data = data.flatten()
# Enforcing that the denominator has constant term 1,
# P(x)/(1 + Q(x)) = d ->
# P(x) - d*Q(x) = d
# This can be formulated as a strictly linear problem A*t = d
A = numpy.empty((x.size, 2*len(coeff_list) - 1), dtype=numpy.float64)
for i, entry in enumerate(coeff_list):
if not (isinstance(entry, int) or (isinstance(entry, tuple) and len(entry) == 1 and isinstance(entry[0], int))):
raise TypeError('coeff_list must be a list of integers or length 1 tuples of ints')
if isinstance(entry, tuple):
entry = entry[0]
u = 1
if entry > 0:
u *= numpy.power(x, entry)
A[:, i] = u
if i > 0:
A[:, i+len(coeff_list) - 1] = -u*data
# perform least squares fit
try:
sol, residuals, rank, sing_values = lstsq(A, data, cond=cond)
except LinAlgError as e:
raise SarpyRatPolyError(str(e))
#if len(residuals) != 0:
residuals /= float(x.size)
logger.info(
'Performed rational polynomial fit, got\n\t'
'residuals {}\n\t'
'rank {}\n\t'
'singular values {}'.format(residuals, rank, sing_values))
numerator = numpy.zeros((len(coeff_list), ), dtype='float64')
denominator = numpy.zeros((len(coeff_list), ), dtype='float64')
denominator[0] = 1.0
numerator[:] = sol[:len(coeff_list)]
denominator[1:] = sol[len(coeff_list):]
return numerator, denominator
def rational_poly_fit_2d(x, y, data, coeff_list, cond=None):
"""
Fits a two variable rational polynomial according to the input coefficient
listing order.
Parameters
----------
x : numpy.ndarray
y : numpy.ndarray
data : numpy.ndarray
coeff_list : List
cond : None|float
Passed through to :func:`scipy.linalg.lstsq`.
"""
if coeff_list[0] != (0, 0):
raise ValueError(
'The first entry of coeff_list is required to be the constant term `(0, 0)`')
if not (x.size == y.size and x.size == data.size):
raise ValueError('Size mismatch among data entries')
x = x.flatten()
y = y.flatten()
data = data.flatten()
# Enforcing that the denominator has constant term 1,
# P(x, y)/(1 + Q(x, y)) = d ->
# P(x, y) - d*Q(x, y) = d
# This can be formulated as a strictly linear problem A*t = d
A = numpy.empty((x.size, 2 * len(coeff_list) - 1), dtype=numpy.float64)
for i, entry in enumerate(coeff_list):
if len(entry) != 2:
raise TypeError('coeff_list must be a list of tuples of length 2')
u = 1
if entry[0] > 0:
u *= numpy.power(x, entry[0])
if entry[1] > 0:
u *= numpy.power(y, entry[1])
A[:, i] = u
if i > 0:
A[:, i + len(coeff_list) - 1] = -u*data
# perform least squares fit
try:
sol, residuals, rank, sing_values = lstsq(A, data, cond=cond)
except LinAlgError as e:
raise SarpyRatPolyError(str(e))
# if len(residuals) != 0:
residuals /= float(x.size)
logger.info(
'Performed rational polynomial fit, got\n\t'
'residuals {}\n\t'
'rank {}\n\t'
'singular values {}'.format(residuals, rank, sing_values))
numerator = numpy.zeros((len(coeff_list),), dtype='float64')
denominator = numpy.zeros((len(coeff_list),), dtype='float64')
denominator[0] = 1.0
numerator[:] = sol[:len(coeff_list)]
denominator[1:] = sol[len(coeff_list):]
return numerator, denominator
def rational_poly_fit_3d(x, y, z, data, coeff_list, cond=None):
"""
Fits a three variable rational polynomial according to the input coefficient
listing order.
Parameters
----------
x : numpy.ndarray
y : numpy.ndarray
z : numpy.ndarray
data : numpy.ndarray
coeff_list : List
cond : None|float
Passed through to :func:`scipy.linalg.lstsq`.
"""
if coeff_list[0] != (0, 0, 0):
raise ValueError(
'The first entry of coeff_list is required to be the constant term `(0, 0, 0)`')
if not (x.size == y.size and x.size == z.size and x.size == data.size):
raise ValueError('Size mismatch among data entries')
x = x.flatten()
y = y.flatten()
z = z.flatten()
data = data.flatten()
# Enforcing that the denominator has constant term 1,
# P(x, y, z)/(1 + Q(x, y, z)) = d ->
# P(x, y, z) - d*Q(x, y, z) = d
# This can be formulated as a strictly linear problem A*t = d
A = numpy.empty((x.size, 2*len(coeff_list) - 1), dtype=numpy.float64)
for i, entry in enumerate(coeff_list):
if len(entry) != 3:
raise TypeError('coeff_list must be a list of tuples of length 3')
u = 1
if entry[0] > 0:
u *= numpy.power(x, entry[0])
if entry[1] > 0:
u *= numpy.power(y, entry[1])
if entry[2] > 0:
u *= numpy.power(z, entry[2])
A[:, i] = u
if i > 0:
A[:, i + len(coeff_list) - 1] = -u*data
# perform least squares fit
try:
sol, residuals, rank, sing_values = lstsq(A, data, cond=cond)
except LinAlgError as e:
raise SarpyRatPolyError(str(e))
#if len(residuals) != 0:
residuals /= float(x.size)
logger.info(
'Performed rational polynomial fit, got\n\t'
'residuals {}\n\t'
'rank {}\n\t'
'singular values {}'.format(residuals, rank, sing_values))
numerator = numpy.zeros((len(coeff_list),), dtype='float64')
denominator = numpy.zeros((len(coeff_list),), dtype='float64')
denominator[0] = 1.0
numerator[:] = sol[:len(coeff_list)]
denominator[1:] = sol[len(coeff_list):]
return numerator, denominator
####################
# rational polynomial definition
class RationalPolynomial(object):
r"""
A basic rational polynomial implementation. This assumes the data model
`input_data -> output_data` via the relation
.. math::
X = (x, y, ...) & = (input\_data - input\_offset)/input\_scale \\
(output\_data - output\_offset)/output\_scale & = Data = numerator(X)/denominator(X) \\
output\_data & = (numerator(X)/denominator(X))*output_scale + output\_offset
This object is callable, and acts as the evaluation function after construction.
That is, suppose we have
.. code::
rational_poly = RationalPolynomial(...) # suppose constructed as 2 variables
output_0 = rational_poly([x, y]) # pass in the two variables as a single array
output_1 = rational_poly(x, y) # pass in the two variables individually
# output_0 and output_1 should be identical
output_fail = rational_poly(x, y, z)
# this raises an exception for mismatch with the number of variables
"""
__slots__ = (
'_numerator', '_denominator', '_coeff_list', '_variables', '_input_offsets', '_input_scales',
'_output_offset', '_output_scale', '_numerator_array', '_denominator_array')
def __init__(self, numerator, denominator, coeff_list, input_offsets, input_scales, output_offset, output_scale):
"""
Parameters
----------
numerator : Sequence|numpy.ndarray
denominator : Sequence|numpy.ndarray
coeff_list : Sequence
input_offsets : Sequence
input_scales : Sequence
output_offset : float
output_scale : float
"""
self._coeff_list = coeff_list
self._variables = _get_num_variables(coeff_list)
if self._variables not in [1, 2, 3]:
raise ValueError('Functionality allows only 1, 2, or 3 variables.')
if len(numerator) != len(self._coeff_list):
raise ValueError('numerator must be the same length as coeff_list')
self._numerator = numerator
if len(denominator) != len(self._coeff_list):
raise ValueError('denominator must be the same length as coeff_list')
self._denominator = denominator
if len(input_offsets) != self._variables:
raise ValueError('The input_offsets must be the same length as the number of variables')
self._input_offsets = input_offsets
if len(input_scales) != self._variables:
raise ValueError('The input_scale must be the same length as the number of variables')
self._input_scales = input_scales
self._output_offset = float(output_offset)
self._output_scale = float(output_scale)
self._numerator_array = _map_list_to_poly_matrix(numerator, coeff_list)
self._denominator_array = _map_list_to_poly_matrix(denominator, coeff_list)
@property
def variables(self):
"""
The number of independent variables.
Returns
-------
int
"""
return self._variables
@property
def coefficient_list(self):
"""
The coefficient list.
Returns
-------
Sequence
"""
return self._coeff_list
@property
def numerator(self):
"""
The numerator coefficients.
Returns
-------
Sequence
"""
return self._numerator
@property
def denominator(self):
"""
The denominator coefficients.
Returns
-------
Sequence
"""
return self._denominator
def __call__(self, *input_variables):
def ensure_the_type(data):
if isinstance(data, (numpy.number, int, float, numpy.ndarray)):
return data
else:
return numpy.array(data)
if len(input_variables) not in [1, self.variables]:
raise ValueError('Got an unexpected number of input arguments')
if len(input_variables) == 1:
separate = False
inp_vars = ensure_the_type(input_variables[0])
else:
separate = True
inp_vars = [ensure_the_type(entry) for entry in input_variables]
# todo: should we evaluate the viability of the input?
if self.variables == 1:
x = (inp_vars - self._input_offsets[0])/self._input_scales[0]
value = polynomial.polyval(x, self._numerator_array) / \
polynomial.polyval(x, self._denominator_array)
elif self.variables == 2:
if separate:
x = (inp_vars[0] - self._input_offsets[0])/self._input_scales[0]
y = (inp_vars[1] - self._input_offsets[1])/self._input_scales[1]
else:
if inp_vars.shape[-1] != 2:
raise ValueError(
'Final dimension of input data ({}) must match the number '
'of variables ({}).'.format(inp_vars.shape, self.variables))
x = (inp_vars[..., 0] - self._input_offsets[0])/self._input_scales[0]
y = (inp_vars[..., 1] - self._input_offsets[1])/self._input_scales[1]
value = polynomial.polyval2d(x, y, self._numerator_array) / \
polynomial.polyval2d(x, y, self._denominator_array)
elif self.variables == 3:
if separate:
x = (inp_vars[0] - self._input_offsets[0])/self._input_scales[0]
y = (inp_vars[1] - self._input_offsets[1])/self._input_scales[1]
z = (inp_vars[2] - self._input_offsets[2])/self._input_scales[2]
else:
if inp_vars.shape[-1] != 3:
raise ValueError(
'Final dimension of input data ({}) must match the number '
'of variables ({}).'.format(inp_vars.shape, self.variables))
x = (inp_vars[..., 0] - self._input_offsets[0])/self._input_scales[0]
y = (inp_vars[..., 1] - self._input_offsets[1])/self._input_scales[1]
z = (inp_vars[..., 2] - self._input_offsets[2]) / self._input_scales[2]
value = polynomial.polyval3d(x, y, z, self._numerator_array) / \
polynomial.polyval3d(x, y, z, self._denominator_array)
else:
raise ValueError('More than 3 variables is unsupported')
return value*self._output_scale + self._output_offset
def _get_scale_and_offset(array):
# type: (numpy.ndarray) -> (float, float)
min_value = numpy.min(array)
max_value = numpy.max(array)
scale_value = 0.5*(max_value - min_value)
offset_value = 0.5*(max_value + min_value)
return offset_value, scale_value
def get_rational_poly_1d(x, data, coeff_list=None, order=None, cond=None):
"""
Gets the RationalPolynomial instance that comes from fitting the provided data.
Parameters
----------
x : numpy.ndarray
data : numpy.ndarray
coeff_list : None|Sequence
order : None|int
cond : None|float
Passed through to :func:`scipy.linalg.lstsq`.
"""
if (coeff_list is None and order is None) or \
(coeff_list is not None and order is not None):
raise ValueError('Exact one of coeff_list and order must be provided.')
if order is not None:
coeff_list = get_default_coefficient_ordering(1, int(order))
if _get_num_variables(coeff_list) != 1:
raise ValueError('The number of variables defined by the coefficient list must be 1.')
scale_x, offset_x = _get_scale_and_offset(x)
scale_data, offset_data = _get_scale_and_offset(data)
numerator, denominator = rational_poly_fit_1d(
(x-offset_x)/scale_x,
(data-offset_data)/scale_data, coeff_list, cond=cond)
return RationalPolynomial(
numerator, denominator, coeff_list,
(offset_x, ), (scale_x, ),
offset_data, scale_data)
def get_rational_poly_2d(x, y, data, coeff_list=None, order=None, cond=None):
"""
Gets the RationalPolynomial instance that comes from fitting the provided data.
Parameters
----------
x : numpy.ndarray
y : numpy.ndarray
data : numpy.ndarray
coeff_list : None|Sequence
order : None|int
cond : None|float
Passed through to :func:`scipy.linalg.lstsq`.
"""
if (coeff_list is None and order is None) or \
(coeff_list is not None and order is not None):
raise ValueError('Exact one of coeff_list and order must be provided.')
if order is not None:
coeff_list = get_default_coefficient_ordering(2, int(order))
if _get_num_variables(coeff_list) != 2:
raise ValueError('The number of variables defined by the coefficient list must be 2.')
scale_x, offset_x = _get_scale_and_offset(x)
scale_y, offset_y = _get_scale_and_offset(y)
scale_data, offset_data = _get_scale_and_offset(data)
numerator, denominator = rational_poly_fit_2d(
(x-offset_x)/scale_x, (y-offset_y)/scale_y,
(data-offset_data)/scale_data, coeff_list, cond=cond)
return RationalPolynomial(
numerator, denominator, coeff_list,
(offset_x, offset_y), (scale_x, scale_y),
offset_data, scale_data)
def get_rational_poly_3d(x, y, z, data, coeff_list=None, order=None, cond=None):
"""
Gets the RationalPolynomial instance that comes from fitting the provided data.
Parameters
----------
x : numpy.ndarray
y : numpy.ndarray
z : numpy.ndarray
data : numpy.ndarray
coeff_list : None|Sequence
order : None|int
cond : None|float
Passed through to :func:`scipy.linalg.lstsq`.
"""
if (coeff_list is None and order is None) or \
(coeff_list is not None and order is not None):
raise ValueError('Exact one of coeff_list and order must be provided.')
if order is not None:
coeff_list = get_default_coefficient_ordering(3, int(order))
if _get_num_variables(coeff_list) != 3:
raise ValueError('The number of variables defined by the coefficient list must be 3.')
scale_x, offset_x = _get_scale_and_offset(x)
scale_y, offset_y = _get_scale_and_offset(y)
scale_z, offset_z = _get_scale_and_offset(z)
scale_data, offset_data = _get_scale_and_offset(data)
numerator, denominator = rational_poly_fit_3d(
(x-offset_x)/scale_x, (y-offset_y)/scale_y, (z-offset_z)/scale_z,
(data-offset_data)/scale_data, coeff_list, cond=cond)
return RationalPolynomial(
numerator, denominator, coeff_list,
(offset_x, offset_y, offset_z), (scale_x, scale_y, scale_z),
offset_data, scale_data)
####################
# collective rational polynomial function
class CombinedRationalPolynomial(object):
"""
Assemble a collection of RationalPolynomial objects with the same number of variables
into a single multi-variable output object.
"""
__slots__ = ('_collection', )
def __init__(self, *collection):
if len(collection) == 1 and isinstance(collection[0], (list, tuple)):
collection = collection[0]
if len(collection) < 2:
raise ValueError('This requires more than a single input')
coll = []
variables = None
for entry in collection:
if not isinstance(entry, RationalPolynomial):
raise TypeError(
'Every input must be an instance of RationalPolynomial,\n\t'
'got type `{}`'.format(type(entry)))
if variables is None:
variables = entry.variables
elif variables != entry.variables:
raise TypeError(
'Every input must be an instance of RationalPolynomial with\n\t'
'the same number of variables, got type `{}` and `{}`'.format(variables, entry.variables))
coll.append(entry)
self._collection = tuple(coll)
def __call__(self, *args, combine=True):
out = tuple([entry(*args) for entry in self._collection])
if combine:
return numpy.stack(out, axis=-1)
else:
return out
|
[
"numpy.stack",
"numpy.ndindex",
"numpy.power",
"numpy.polynomial.polynomial.polyval2d",
"numpy.polynomial.polynomial.polyval3d",
"numpy.max",
"numpy.min",
"numpy.array",
"numpy.polynomial.polynomial.polyval",
"scipy.linalg.lstsq",
"logging.getLogger"
] |
[((308, 335), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (325, 335), False, 'import logging\n'), ((2705, 2733), 'numpy.ndindex', 'numpy.ndindex', (['shape_details'], {}), '(shape_details)\n', (2718, 2733), False, 'import numpy\n'), ((15941, 15957), 'numpy.min', 'numpy.min', (['array'], {}), '(array)\n', (15950, 15957), False, 'import numpy\n'), ((15974, 15990), 'numpy.max', 'numpy.max', (['array'], {}), '(array)\n', (15983, 15990), False, 'import numpy\n'), ((4421, 4446), 'scipy.linalg.lstsq', 'lstsq', (['A', 'data'], {'cond': 'cond'}), '(A, data, cond=cond)\n', (4426, 4446), False, 'from scipy.linalg import lstsq, LinAlgError\n'), ((6495, 6520), 'scipy.linalg.lstsq', 'lstsq', (['A', 'data'], {'cond': 'cond'}), '(A, data, cond=cond)\n', (6500, 6520), False, 'from scipy.linalg import lstsq, LinAlgError\n'), ((8719, 8744), 'scipy.linalg.lstsq', 'lstsq', (['A', 'data'], {'cond': 'cond'}), '(A, data, cond=cond)\n', (8724, 8744), False, 'from scipy.linalg import lstsq, LinAlgError\n'), ((4225, 4246), 'numpy.power', 'numpy.power', (['x', 'entry'], {}), '(x, entry)\n', (4236, 4246), False, 'import numpy\n'), ((6227, 6251), 'numpy.power', 'numpy.power', (['x', 'entry[0]'], {}), '(x, entry[0])\n', (6238, 6251), False, 'import numpy\n'), ((6294, 6318), 'numpy.power', 'numpy.power', (['y', 'entry[1]'], {}), '(y, entry[1])\n', (6305, 6318), False, 'import numpy\n'), ((8384, 8408), 'numpy.power', 'numpy.power', (['x', 'entry[0]'], {}), '(x, entry[0])\n', (8395, 8408), False, 'import numpy\n'), ((8451, 8475), 'numpy.power', 'numpy.power', (['y', 'entry[1]'], {}), '(y, entry[1])\n', (8462, 8475), False, 'import numpy\n'), ((8518, 8542), 'numpy.power', 'numpy.power', (['z', 'entry[2]'], {}), '(z, entry[2])\n', (8529, 8542), False, 'import numpy\n'), ((21516, 21541), 'numpy.stack', 'numpy.stack', (['out'], {'axis': '(-1)'}), '(out, axis=-1)\n', (21527, 21541), False, 'import numpy\n'), ((13213, 13230), 'numpy.array', 'numpy.array', (['data'], {}), '(data)\n', (13224, 13230), False, 'import numpy\n'), ((13803, 13847), 'numpy.polynomial.polynomial.polyval', 'polynomial.polyval', (['x', 'self._numerator_array'], {}), '(x, self._numerator_array)\n', (13821, 13847), False, 'from numpy.polynomial import polynomial\n'), ((13868, 13914), 'numpy.polynomial.polynomial.polyval', 'polynomial.polyval', (['x', 'self._denominator_array'], {}), '(x, self._denominator_array)\n', (13886, 13914), False, 'from numpy.polynomial import polynomial\n'), ((14597, 14646), 'numpy.polynomial.polynomial.polyval2d', 'polynomial.polyval2d', (['x', 'y', 'self._numerator_array'], {}), '(x, y, self._numerator_array)\n', (14617, 14646), False, 'from numpy.polynomial import polynomial\n'), ((14667, 14718), 'numpy.polynomial.polynomial.polyval2d', 'polynomial.polyval2d', (['x', 'y', 'self._denominator_array'], {}), '(x, y, self._denominator_array)\n', (14687, 14718), False, 'from numpy.polynomial import polynomial\n'), ((15570, 15622), 'numpy.polynomial.polynomial.polyval3d', 'polynomial.polyval3d', (['x', 'y', 'z', 'self._numerator_array'], {}), '(x, y, z, self._numerator_array)\n', (15590, 15622), False, 'from numpy.polynomial import polynomial\n'), ((15643, 15697), 'numpy.polynomial.polynomial.polyval3d', 'polynomial.polyval3d', (['x', 'y', 'z', 'self._denominator_array'], {}), '(x, y, z, self._denominator_array)\n', (15663, 15697), False, 'from numpy.polynomial import polynomial\n')]
|
import math
import numpy as np
from download_mnist import load
import operator
import time
# classify using kNN
# x_train = np.load('../x_train.npy')
# y_train = np.load('../y_train.npy')
# x_test = np.load('../x_test.npy')
# y_test = np.load('../y_test.npy')
x_train, y_train, x_test, y_test = load()
x_train = x_train.reshape(60000,28,28)
x_test = x_test.reshape(10000,28,28)
x_train = x_train.astype(float)
x_test = x_test.astype(float)
# print(y_test[0:10])
def kNNClassify(newInput, dataSet, labels, k):
result=[]
########################
# Input your code here #
########################
test_len = len(newInput)
train_len= len(dataSet)
dist=np.zeros((test_len,train_len))
for i in range(test_len):
for j in range(train_len):
d= np.linalg.norm(dataSet[j]-newInput[i])
dist[i,j] = d
# print(dist)
# print(labels)
for i in range(test_len):
votes = np.zeros(10)
x= np.argsort(dist[i])[:k]
# print(x)
for i in range(len(x)):
num_label = labels[x[i]]
# print(num_label)
votes[num_label]+=1
# print(votes)
result.append(np.argmax(votes))
####################
# End of your code #
####################
return result
start_time = time.time()
outputlabels=kNNClassify(x_test[0:20],x_train,y_train,12)
print(outputlabels)
result = y_test[0:20] - outputlabels
result = (1 - np.count_nonzero(result)/len(outputlabels))
print ("---classification accuracy for knn on mnist: %s ---" %result)
print ("---execution time: %s seconds ---" % (time.time() - start_time))
|
[
"numpy.count_nonzero",
"numpy.argmax",
"download_mnist.load",
"numpy.zeros",
"time.time",
"numpy.argsort",
"numpy.linalg.norm"
] |
[((311, 317), 'download_mnist.load', 'load', ([], {}), '()\n', (315, 317), False, 'from download_mnist import load\n'), ((1385, 1396), 'time.time', 'time.time', ([], {}), '()\n', (1394, 1396), False, 'import time\n'), ((709, 740), 'numpy.zeros', 'np.zeros', (['(test_len, train_len)'], {}), '((test_len, train_len))\n', (717, 740), True, 'import numpy as np\n'), ((989, 1001), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (997, 1001), True, 'import numpy as np\n'), ((1530, 1554), 'numpy.count_nonzero', 'np.count_nonzero', (['result'], {}), '(result)\n', (1546, 1554), True, 'import numpy as np\n'), ((823, 863), 'numpy.linalg.norm', 'np.linalg.norm', (['(dataSet[j] - newInput[i])'], {}), '(dataSet[j] - newInput[i])\n', (837, 863), True, 'import numpy as np\n'), ((1014, 1033), 'numpy.argsort', 'np.argsort', (['dist[i]'], {}), '(dist[i])\n', (1024, 1033), True, 'import numpy as np\n'), ((1247, 1263), 'numpy.argmax', 'np.argmax', (['votes'], {}), '(votes)\n', (1256, 1263), True, 'import numpy as np\n'), ((1692, 1703), 'time.time', 'time.time', ([], {}), '()\n', (1701, 1703), False, 'import time\n')]
|
import argparse
import os
import random
import sys
from pathlib import Path
import numpy as np
import toml
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader, DistributedSampler
sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..", ".."))) # without installation, add /path/to/Audio-ZEN
import audio_zen.loss as loss
from audio_zen.utils import initialize_module
def entry(rank, config, resume, only_validation):
torch.manual_seed(config["meta"]["seed"]) # For both CPU and GPU
np.random.seed(config["meta"]["seed"])
random.seed(config["meta"]["seed"])
torch.cuda.set_device(rank)
# Initialize the process group
# The environment variables necessary to initialize a Torch process group are provided to you by this module,
# and no need for you to pass ``RANK`` manually.
torch.distributed.init_process_group(backend="nccl")
print(f"{rank + 1} process initialized.")
# The DistributedSampler will split the dataset into the several cross-process parts.
# On the contrary, setting "Sampler=None, shuffle=True", each GPU will get all data in the whole dataset.
train_dataset = initialize_module(config["train_dataset"]["path"], args=config["train_dataset"]["args"])
sampler = DistributedSampler(dataset=train_dataset, rank=rank, shuffle=True)
train_dataloader = DataLoader(
dataset=train_dataset,
sampler=sampler,
shuffle=False,
**config["train_dataset"]["dataloader"],
)
valid_dataloader = DataLoader(
dataset=initialize_module(config["validation_dataset"]["path"], args=config["validation_dataset"]["args"]),
num_workers=0,
batch_size=1
)
model = initialize_module(config["model"]["path"], args=config["model"]["args"])
optimizer = torch.optim.Adam(
params=model.parameters(),
lr=config["optimizer"]["lr"],
betas=(config["optimizer"]["beta1"], config["optimizer"]["beta2"])
)
loss_function = getattr(loss, config["loss_function"]["name"])(**config["loss_function"]["args"])
trainer_class = initialize_module(config["trainer"]["path"], initialize=False)
trainer = trainer_class(
dist=dist,
rank=rank,
config=config,
resume=resume,
only_validation=only_validation,
model=model,
loss_function=loss_function,
optimizer=optimizer,
train_dataloader=train_dataloader,
validation_dataloader=valid_dataloader
)
trainer.train()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="FullSubNet")
parser.add_argument("-C", "--configuration", required=True, default="recipes/etri_drone1/fullsubnet/train.toml", type=str, help="Configuration (*.toml).")
parser.add_argument("-R", "--resume", action="store_true", help="Resume the experiment from latest checkpoint.")
parser.add_argument("-V", "--only_validation", action="store_true", help="Only run validation, which is used for debugging.")
parser.add_argument("-P", "--preloaded_model_path", type=str, help="Path of the *.pth file of a model.")
args = parser.parse_args()
local_rank = int(os.environ["LOCAL_RANK"])
#local_rank = 0
if args.preloaded_model_path:
assert not args.resume, "The 'resume' conflicts with the 'preloaded_model_path'."
config_path = Path(args.configuration).expanduser().absolute()
configuration = toml.load(config_path.as_posix())
# append the parent dir of the config path to python's context
# /path/to/recipes/dns_interspeech_2020/exp/'
sys.path.append(config_path.parent.as_posix())
configuration["meta"]["experiment_name"], _ = os.path.splitext(os.path.basename(args.configuration))
configuration["meta"]["config_path"] = args.configuration
configuration["meta"]["preloaded_model_path"] = args.preloaded_model_path
entry(local_rank, configuration, args.resume, args.only_validation)
|
[
"numpy.random.seed",
"torch.distributed.init_process_group",
"torch.utils.data.DataLoader",
"argparse.ArgumentParser",
"os.path.basename",
"torch.manual_seed",
"torch.utils.data.DistributedSampler",
"pathlib.Path",
"random.seed",
"audio_zen.utils.initialize_module",
"torch.cuda.set_device",
"os.path.join"
] |
[((470, 511), 'torch.manual_seed', 'torch.manual_seed', (["config['meta']['seed']"], {}), "(config['meta']['seed'])\n", (487, 511), False, 'import torch\n'), ((540, 578), 'numpy.random.seed', 'np.random.seed', (["config['meta']['seed']"], {}), "(config['meta']['seed'])\n", (554, 578), True, 'import numpy as np\n'), ((583, 618), 'random.seed', 'random.seed', (["config['meta']['seed']"], {}), "(config['meta']['seed'])\n", (594, 618), False, 'import random\n'), ((623, 650), 'torch.cuda.set_device', 'torch.cuda.set_device', (['rank'], {}), '(rank)\n', (644, 650), False, 'import torch\n'), ((858, 910), 'torch.distributed.init_process_group', 'torch.distributed.init_process_group', ([], {'backend': '"""nccl"""'}), "(backend='nccl')\n", (894, 910), False, 'import torch\n'), ((1178, 1271), 'audio_zen.utils.initialize_module', 'initialize_module', (["config['train_dataset']['path']"], {'args': "config['train_dataset']['args']"}), "(config['train_dataset']['path'], args=config[\n 'train_dataset']['args'])\n", (1195, 1271), False, 'from audio_zen.utils import initialize_module\n'), ((1281, 1347), 'torch.utils.data.DistributedSampler', 'DistributedSampler', ([], {'dataset': 'train_dataset', 'rank': 'rank', 'shuffle': '(True)'}), '(dataset=train_dataset, rank=rank, shuffle=True)\n', (1299, 1347), False, 'from torch.utils.data import DataLoader, DistributedSampler\n'), ((1372, 1483), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_dataset', 'sampler': 'sampler', 'shuffle': '(False)'}), "(dataset=train_dataset, sampler=sampler, shuffle=False, **config[\n 'train_dataset']['dataloader'])\n", (1382, 1483), False, 'from torch.utils.data import DataLoader, DistributedSampler\n'), ((1733, 1805), 'audio_zen.utils.initialize_module', 'initialize_module', (["config['model']['path']"], {'args': "config['model']['args']"}), "(config['model']['path'], args=config['model']['args'])\n", (1750, 1805), False, 'from audio_zen.utils import initialize_module\n'), ((2119, 2181), 'audio_zen.utils.initialize_module', 'initialize_module', (["config['trainer']['path']"], {'initialize': '(False)'}), "(config['trainer']['path'], initialize=False)\n", (2136, 2181), False, 'from audio_zen.utils import initialize_module\n'), ((2583, 2632), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""FullSubNet"""'}), "(description='FullSubNet')\n", (2606, 2632), False, 'import argparse\n'), ((247, 287), 'os.path.join', 'os.path.join', (['__file__', '""".."""', '""".."""', '""".."""'], {}), "(__file__, '..', '..', '..')\n", (259, 287), False, 'import os\n'), ((3731, 3767), 'os.path.basename', 'os.path.basename', (['args.configuration'], {}), '(args.configuration)\n', (3747, 3767), False, 'import os\n'), ((1570, 1673), 'audio_zen.utils.initialize_module', 'initialize_module', (["config['validation_dataset']['path']"], {'args': "config['validation_dataset']['args']"}), "(config['validation_dataset']['path'], args=config[\n 'validation_dataset']['args'])\n", (1587, 1673), False, 'from audio_zen.utils import initialize_module\n'), ((3391, 3415), 'pathlib.Path', 'Path', (['args.configuration'], {}), '(args.configuration)\n', (3395, 3415), False, 'from pathlib import Path\n')]
|
# -----------------------------------------------------------------------------
# @author:
# <NAME>
# @brief:
# generate the videos into the same directory
# -----------------------------------------------------------------------------
import env_wrapper
import numpy as np
import argparse
import glob
import cv2
import os
# import matplotlib.pyplot as plt
if __name__ == '__main__':
'''
@brief:
Either plot the directory, or simply one npy file
'''
parser = argparse.ArgumentParser(description="Plot results from a dir")
parser.add_argument(
"-i",
"--file_name",
type=str,
required=True,
help="The directory of the summary file"
)
parser.add_argument(
"-s",
"--size",
type=int,
required=False,
default=480
)
args = parser.parse_args()
# file list
if args.file_name.endswith('.npy'):
candidate_list = [args.file_name]
else:
candidate_list = glob.glob(os.path.join(args.file_name, '*.npy'))
# make the environment
env_name = os.path.abspath(candidate_list[0]).split('/')[-2].split('_20')[0]
args.task = env_name.replace('IM', '') # use the original environment
env, is_deepmind_env = env_wrapper.make_env(
args=args, rand_seed=1, allow_monitor=0
)
for candidate in candidate_list:
# process each environment
data = np.load(candidate)
if os.path.exists(candidate.replace('.npy', '.mp4')):
continue
video = cv2.VideoWriter(
candidate.replace('.npy', '.mp4'),
cv2.VideoWriter_fourcc(*'mp4v'),
40,
(args.size * 2, args.size)
)
env.reset()
for i_frame in range(len(data)):
with env.env.physics.reset_context():
if 'fish' in args.task:
# set the target position
env.env.physics.named.model.geom_pos['target', 'x'] = \
data[i_frame][-2]
env.env.physics.named.model.geom_pos['target', 'y'] = \
data[i_frame][-1]
env.env.physics.data.qpos[:] = data[i_frame][:-2]
else:
env.env.physics.data.qpos[:] = data[i_frame]
image = np.hstack(
[env.env.physics.render(args.size, args.size, camera_id=0),
env.env.physics.render(args.size, args.size, camera_id=1)]
)
# rgb to bgr
image = image[:, :, [2, 1, 0]]
video.write(image)
video.release()
|
[
"numpy.load",
"os.path.abspath",
"argparse.ArgumentParser",
"cv2.VideoWriter_fourcc",
"env_wrapper.make_env",
"os.path.join"
] |
[((509, 571), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Plot results from a dir"""'}), "(description='Plot results from a dir')\n", (532, 571), False, 'import argparse\n'), ((1282, 1343), 'env_wrapper.make_env', 'env_wrapper.make_env', ([], {'args': 'args', 'rand_seed': '(1)', 'allow_monitor': '(0)'}), '(args=args, rand_seed=1, allow_monitor=0)\n', (1302, 1343), False, 'import env_wrapper\n'), ((1446, 1464), 'numpy.load', 'np.load', (['candidate'], {}), '(candidate)\n', (1453, 1464), True, 'import numpy as np\n'), ((1032, 1069), 'os.path.join', 'os.path.join', (['args.file_name', '"""*.npy"""'], {}), "(args.file_name, '*.npy')\n", (1044, 1069), False, 'import os\n'), ((1641, 1672), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (1663, 1672), False, 'import cv2\n'), ((1114, 1148), 'os.path.abspath', 'os.path.abspath', (['candidate_list[0]'], {}), '(candidate_list[0])\n', (1129, 1148), False, 'import os\n')]
|
import copy
import itertools
import re
from typing import Any, Callable, Dict, Generator, Iterator, List, Optional, Union
import numpy as np
import torch
from omegaconf import DictConfig
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import IterableDataset
from classy.data.data_drivers import ClassySample, DataDriver
from classy.utils.commons import add_noise_to_value, chunks, flatten
from classy.utils.log import get_project_logger
from classy.utils.vocabulary import Vocabulary
logger = get_project_logger(__name__)
def batchify(tensors: List[torch.Tensor], padding_value: int) -> torch.Tensor:
return pad_sequence(tensors, batch_first=True, padding_value=padding_value)
def batchify_matrices(tensors: List[torch.Tensor], padding_value: int) -> torch.Tensor:
x = max([t.shape[0] for t in tensors])
y = max([t.shape[1] for t in tensors])
out_matrix = torch.zeros((len(tensors), x, y))
out_matrix += padding_value
for i, tensor in enumerate(tensors):
out_matrix[i][0 : tensor.shape[0], 0 : tensor.shape[1]] = tensor
return out_matrix
class BaseDataset(IterableDataset):
@staticmethod
def requires_vocab() -> bool:
return True
@staticmethod
def fit_vocabulary(samples: Iterator[ClassySample]) -> Vocabulary:
raise NotImplementedError
@classmethod
def adapt_dataset_from(cls, training_dataset: DictConfig, setting: str):
if setting == "validation":
validation_dataset = copy.deepcopy(training_dataset)
validation_dataset["materialize"] = True
validation_dataset["for_inference"] = True
return validation_dataset
elif setting == "prediction":
prediction_dataset = copy.deepcopy(training_dataset)
prediction_dataset["_target_"] = re.sub(
".from_file$", ".from_samples", prediction_dataset["_target_"]
)
prediction_dataset["min_length"] = -1
prediction_dataset["max_length"] = -1
prediction_dataset["for_inference"] = True
return prediction_dataset
else:
raise ValueError(
f"Setting {setting} not supported. Choose between [validation, prediction] or change config."
)
@classmethod
def from_file(
cls,
path: Union[str, Dict[str, DataDriver]],
data_driver: Optional[DataDriver] = None,
vocabulary: Vocabulary = None,
**kwargs,
) -> "BaseDataset":
dataset_bundle: Dict[str, Any] = (
{path: data_driver} if type(path) == str else path
)
if vocabulary is None and cls.requires_vocab():
# vocabulary fitting here
logger.info("Fitting vocabulary")
vocabulary = cls.fit_vocabulary(
itertools.chain(
*[dd.read_from_path(p) for p, dd in dataset_bundle.items()]
)
)
logger.info("Vocabulary fitting completed")
return cls(
samples_iterator=lambda: itertools.chain(
*[dd.read_from_path(p) for p, dd in dataset_bundle.items()]
),
vocabulary=vocabulary,
**kwargs,
)
@classmethod
def from_samples(
cls,
samples: Iterator[ClassySample],
vocabulary: Vocabulary,
**kwargs,
):
return cls(samples_iterator=lambda: samples, vocabulary=vocabulary, **kwargs)
def __init__(
self,
samples_iterator: Callable[[], Iterator[ClassySample]],
vocabulary: Vocabulary,
fields_batchers: Optional[Dict[str, Union[None, Callable[[list], Any]]]],
for_inference: bool,
batch_size: Optional[int] = None,
tokens_per_batch: Optional[int] = None,
max_batch_size: Optional[int] = None,
batching_fields: Optional[List[str]] = None,
section_size: Optional[int] = None,
prebatch: bool = False,
materialize: bool = False,
drop_last: bool = False,
min_length: int = -1,
max_length: int = -1,
):
super().__init__()
self.samples_iterator = samples_iterator
self.vocabulary = vocabulary
self.fields_batcher = fields_batchers
self.prebatch, self.section_size = prebatch, section_size
self.materialize = materialize
self.drop_last = drop_last
self.min_length, self.max_length = min_length, max_length
self.for_inference = for_inference
self.batch_size = batch_size
self.tokens_per_batch, self.max_batch_size, self.batching_fields = (
tokens_per_batch,
max_batch_size,
batching_fields,
)
assert bool(self.batch_size is not None) or bool(
self.tokens_per_batch is not None
), f"Either batch_size or tokens_per_batch must be provided, but found {batch_size} and {tokens_per_batch}"
if self.batch_size is not None:
if max_batch_size is not None:
logger.warning(
f"max_batch_size has no meaning when not using token batching"
)
else:
assert len(batching_fields) > 0, "At least 1 batching field is required"
if self.tokens_per_batch < self.max_length:
logger.warning(
f"Token batch size {self.tokens_per_batch} < max length {self.max_length}. This might result in batches with only 1 sample that contain more token than the specified token batch size"
)
# used to store the materialized dataset
self._dataset_store = None
if materialize:
logger.warning("Materializing dataset.")
self.materialize_dataset()
def dataset_iterator_func(self):
raise NotImplementedError
def prebatch_elements(self, dataset_elements: List):
sorting_fn = (
lambda elem: add_noise_to_value(
sum(len(elem[k]) for k in self.batching_fields), noise_param=0.1
)
if not self.for_inference
else sum(len(elem[k]) for k in self.batching_fields)
)
dataset_elements = sorted(dataset_elements, key=sorting_fn)
ds = list(chunks(dataset_elements, 512))
np.random.shuffle(ds)
return flatten(ds)
def materialize_dataset(self) -> None:
if self._dataset_store is not None:
logger.info("The dataset is already materialized skipping materialization")
return
logger.info("Starting dataset materialization")
self._dataset_store = list(self.dataset_iterator_func())
logger.info("Materialization completed")
def materialize_batches(
self, dataset_elements: List[Dict[str, Any]]
) -> Generator[Dict[str, Any], None, None]:
if self.prebatch:
dataset_elements = self.prebatch_elements(dataset_elements)
current_batch = []
# function that creates a batch from the 'current_batch' list
def output_batch() -> Dict[str, Any]:
batch_dict = dict()
de_values_by_field = {
fn: [de[fn] for de in current_batch if fn in de]
for fn in self.fields_batcher
}
# in case you provide fields batchers but in the batch there are no elements for that field
de_values_by_field = {
fn: fvs for fn, fvs in de_values_by_field.items() if len(fvs) > 0
}
assert len(set([len(v) for v in de_values_by_field.values()]))
# todo: maybe we should report the user about possible fields filtering due to "None" instances
de_values_by_field = {
fn: fvs
for fn, fvs in de_values_by_field.items()
if all([fv is not None for fv in fvs])
}
for field_name, field_values in de_values_by_field.items():
field_batch = (
self.fields_batcher[field_name](field_values)
if self.fields_batcher[field_name] is not None
else field_values
)
batch_dict[field_name] = field_batch
return batch_dict
max_len_discards, min_len_discards = 0, 0
should_token_batch = self.batch_size is None
for de in dataset_elements:
if (
should_token_batch
and self.max_batch_size != -1
and len(current_batch) == self.max_batch_size
) or (not should_token_batch and len(current_batch) == self.batch_size):
yield output_batch()
current_batch = []
# todo support max length (and min length) as dicts
too_long_fields = [
k
for k in de
if self.max_length != -1
and torch.is_tensor(de[k])
and len(de[k]) > self.max_length
]
if len(too_long_fields) > 0:
max_len_discards += 1
continue
too_short_fields = [
k
for k in de
if self.min_length != -1
and torch.is_tensor(de[k])
and len(de[k]) < self.min_length
]
if len(too_short_fields) > 0:
min_len_discards += 1
continue
if should_token_batch:
de_len = sum(len(de[k]) for k in self.batching_fields)
future_max_len = max(
de_len,
max(
[
sum(len(bde[k]) for k in self.batching_fields)
for bde in current_batch
],
default=0,
),
)
future_tokens_per_batch = future_max_len * (len(current_batch) + 1)
if (
len(current_batch) > 0
and future_tokens_per_batch >= self.tokens_per_batch
):
yield output_batch()
current_batch = []
current_batch.append(de)
if len(current_batch) != 0 and not self.drop_last:
yield output_batch()
if max_len_discards > 0:
if self.for_inference:
logger.warning(
f"WARNING: Inference mode is True but {max_len_discards} samples longer than max length were "
f"found. The {max_len_discards} samples will be DISCARDED. If you are doing some kind of evaluation"
f", this can INVALIDATE results. This might happen if the max length was not set to -1 or if the "
f"sample length exceeds the maximum length supported by the current model."
)
else:
logger.warning(
f"During iteration, {max_len_discards} elements were "
f"discarded since longer than max length {self.max_length}"
)
if min_len_discards > 0:
if self.for_inference:
logger.warning(
f"WARNING: Inference mode is True but {min_len_discards} samples shorter than min length were "
f"found. The {min_len_discards} samples will be DISCARDED. If you are doing some kind of evaluation"
f", this can INVALIDATE results. This might happen if the min length was not set to -1 or if the "
f"sample length is shorter than the minimum length supported by the current model."
)
else:
logger.warning(
f"During iteration, {min_len_discards} elements were "
f"discarded since shorter than min length {self.min_length}"
)
def __iter__(self):
dataset_iterator = (
self.dataset_iterator_func()
if self._dataset_store is None
else self._dataset_store
)
current_dataset_elements = []
i = None
for i, dataset_elem in enumerate(dataset_iterator, start=1):
if (
self.section_size is not None
and len(current_dataset_elements) == self.section_size
):
for batch in self.materialize_batches(current_dataset_elements):
yield batch
current_dataset_elements = []
current_dataset_elements.append(dataset_elem)
if i % 50_000 == 0:
logger.info(f"Processed: {i} number of elements")
if len(current_dataset_elements) != 0:
for batch in self.materialize_batches(current_dataset_elements):
yield batch
if i is not None:
logger.info(f"Dataset finished: {i} number of elements processed")
else:
logger.warning("Dataset empty")
|
[
"copy.deepcopy",
"classy.utils.commons.flatten",
"classy.utils.commons.chunks",
"re.sub",
"torch.nn.utils.rnn.pad_sequence",
"torch.is_tensor",
"classy.utils.log.get_project_logger",
"numpy.random.shuffle"
] |
[((514, 542), 'classy.utils.log.get_project_logger', 'get_project_logger', (['__name__'], {}), '(__name__)\n', (532, 542), False, 'from classy.utils.log import get_project_logger\n'), ((635, 703), 'torch.nn.utils.rnn.pad_sequence', 'pad_sequence', (['tensors'], {'batch_first': '(True)', 'padding_value': 'padding_value'}), '(tensors, batch_first=True, padding_value=padding_value)\n', (647, 703), False, 'from torch.nn.utils.rnn import pad_sequence\n'), ((6329, 6350), 'numpy.random.shuffle', 'np.random.shuffle', (['ds'], {}), '(ds)\n', (6346, 6350), True, 'import numpy as np\n'), ((6366, 6377), 'classy.utils.commons.flatten', 'flatten', (['ds'], {}), '(ds)\n', (6373, 6377), False, 'from classy.utils.commons import add_noise_to_value, chunks, flatten\n'), ((1497, 1528), 'copy.deepcopy', 'copy.deepcopy', (['training_dataset'], {}), '(training_dataset)\n', (1510, 1528), False, 'import copy\n'), ((6290, 6319), 'classy.utils.commons.chunks', 'chunks', (['dataset_elements', '(512)'], {}), '(dataset_elements, 512)\n', (6296, 6319), False, 'from classy.utils.commons import add_noise_to_value, chunks, flatten\n'), ((1746, 1777), 'copy.deepcopy', 'copy.deepcopy', (['training_dataset'], {}), '(training_dataset)\n', (1759, 1777), False, 'import copy\n'), ((1823, 1893), 're.sub', 're.sub', (['""".from_file$"""', '""".from_samples"""', "prediction_dataset['_target_']"], {}), "('.from_file$', '.from_samples', prediction_dataset['_target_'])\n", (1829, 1893), False, 'import re\n'), ((8963, 8985), 'torch.is_tensor', 'torch.is_tensor', (['de[k]'], {}), '(de[k])\n', (8978, 8985), False, 'import torch\n'), ((9294, 9316), 'torch.is_tensor', 'torch.is_tensor', (['de[k]'], {}), '(de[k])\n', (9309, 9316), False, 'import torch\n')]
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
# In[3]:
def process_kfold(model, X_titanic_df, y_titanic_df, folds=5):
kfold = KFold(n_splits=folds)
scores = []
for iter_count , (train_index, test_index) in enumerate(kfold.split(X_titanic_df)):
X_train, X_test = X_titanic_df.values[train_index], X_titanic_df.values[test_index]
y_train, y_test = y_titanic_df.values[train_index], y_titanic_df.values[test_index]
model.fit(X_train, y_train)
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)
scores.append(accuracy)
print("KFold {0} Accuracy: {1:.4f}".format(iter_count, accuracy))
mean_score = np.mean(scores)
print("Average Accuracy: {0:.4f}".format(mean_score))
# In[4]:
def processing(X_train, X_test, y_train, X_titanic_df, y_titanic_df, algorithm='dtc'):
predict_ret = np.empty([1, 1])
if algorithm == 'dtc':
dtc = DecisionTreeClassifier()
dtc.fit(X_train, y_train)
predict_ret = dtc.predict(X_test)
# process_kfold(dtc, X_titanic_df, y_titanic_df)
elif algorithm == 'rfc':
rfc = RandomForestClassifier()
rfc.fit(X_train, y_train)
predict_ret = rfc.predict(X_test)
# process_kfold(rfc, X_titanic_df, y_titanic_df)
elif algorithm == 'lr':
lr = RandomForestClassifier()
lr.fit(X_train, y_train)
predict_ret = lr.predict(X_test)
# process_kfold(lr, X_titanic_df, y_titanic_df)
return predict_ret
# In[ ]:
|
[
"sklearn.ensemble.RandomForestClassifier",
"numpy.empty",
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.KFold",
"sklearn.tree.DecisionTreeClassifier",
"numpy.mean"
] |
[((408, 429), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'folds'}), '(n_splits=folds)\n', (413, 429), False, 'from sklearn.model_selection import KFold\n'), ((986, 1001), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (993, 1001), True, 'import numpy as np\n'), ((1184, 1200), 'numpy.empty', 'np.empty', (['[1, 1]'], {}), '([1, 1])\n', (1192, 1200), True, 'import numpy as np\n'), ((821, 856), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'predictions'], {}), '(y_test, predictions)\n', (835, 856), False, 'from sklearn.metrics import accuracy_score\n'), ((1247, 1271), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (1269, 1271), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((1448, 1472), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (1470, 1472), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((1647, 1671), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (1669, 1671), False, 'from sklearn.ensemble import RandomForestClassifier\n')]
|
from PIL import Image
import pandas as pd
import numpy as np
import time
import os
import random
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from config import CONFIG
def parse_config():
assets_path = os.path.join(currentdir, 'assets')
for layer in CONFIG:
layer_path = os.path.join(assets_path, layer['directory'])
traits = sorted([trait for trait in os.listdir(layer_path) if trait[0] != '.'])
# 如果不需要图层,请在特性数组的开头添加一个“None”
if not layer['required']:
traits = [None] + traits
if layer['rarity_weights'] is None:
rarities = [1 for x in traits]
elif layer['rarity_weights'] == 'random':
rarities = [random.random() for x in traits]
elif type(layer['rarity_weights'] == 'list'):
assert len(traits) == len(layer['rarity_weights']), "确保您拥有当前数量的稀有权重"
rarities = layer['rarity_weights']
else:
raise ValueError("稀有权重无效")
rarities = get_weighted_rarities(rarities)
layer['rarity_weights'] = rarities
layer['cum_rarity_weights'] = np.cumsum(rarities)
print( layer['cum_rarity_weights'])
layer['traits'] = traits
def get_weighted_rarities(arr):
return np.array(arr)/ sum(arr)
def generate_single_image(filepaths, output_filename=None):
bg = Image.open(os.path.join(currentdir, 'assets', filepaths[0]))
for filepath in filepaths[1:]:
img = Image.open(os.path.join(currentdir, 'assets', filepath))
bg.paste(img, (0,0), img)
if output_filename is not None:
bg.save(output_filename)
else:
if not os.path.exists(os.path.join('output', 'single_images')):
os.makedirs(os.path.join('output', 'single_images'))
bg.save(os.path.join('output', 'single_images', str(int(time.time())) + '.png'))
def get_total_combinations():
total = 1
for layer in CONFIG:
total = total * len(layer['traits'])
return total
def select_index(cum_rarities, rand):
cum_rarities = [0] + list(cum_rarities)
for i in range(len(cum_rarities) - 1):
if rand >= cum_rarities[i] and rand <= cum_rarities[i+1]:
return i
return None
def generate_trait_set_from_config():
trait_set = []
trait_paths = []
for layer in CONFIG:
traits, cum_rarities = layer['traits'], layer['cum_rarity_weights']
print(layer['id'],traits, layer['rarity_weights'])
rand_num = random.random()
idx = select_index(cum_rarities, rand_num)
trait_set.append(traits[idx])
if traits[idx] is not None:
trait_path = os.path.join(layer['directory'], traits[idx])
trait_paths.append(trait_path)
return trait_set, trait_paths
def generate_images(edition, count, drop_dup=True):
rarity_table = {}
for layer in CONFIG:
rarity_table[layer['name']] = []
op_path = os.path.join('output', 'edition ' + str(edition), 'images')
zfill_count = len(str(count - 1))
if not os.path.exists(op_path):
os.makedirs(op_path)
for n in range(count):
image_name = str(n).zfill(zfill_count) + '.png'
trait_sets, trait_paths = generate_trait_set_from_config()
generate_single_image(trait_paths, os.path.join(op_path, image_name))
for idx, trait in enumerate(trait_sets):
if trait is not None:
rarity_table[CONFIG[idx]['name']].append(trait[: -1 * len('.png')])
else:
rarity_table[CONFIG[idx]['name']].append('none')
rarity_table = pd.DataFrame(rarity_table).drop_duplicates()
print("生成第 %i 张图片, %i张不同" % (count, rarity_table.shape[0]))
if drop_dup:
img_tb_removed = sorted(list(set(range(count)) - set(rarity_table.index)))
print("移除 %i 张图片..." % (len(img_tb_removed)))
for i in img_tb_removed:
os.remove(os.path.join(op_path, str(i).zfill(zfill_count) + '.png'))
for idx, img in enumerate(sorted(os.listdir(op_path))):
os.rename(os.path.join(op_path, img), os.path.join(op_path, str(idx).zfill(zfill_count) + '.png'))
rarity_table = rarity_table.reset_index()
rarity_table = rarity_table.drop('index', axis=1)
return rarity_table
def main():
print("检查素材...")
parse_config()
tot_comb = get_total_combinations()
print("您可以创建总共%i个不同的NFT" % (tot_comb))
print("您希望创建多少个NFT?输入一个大于0的数字:")
while True:
num_avatars = int(input())
if num_avatars > 0:
break
print("您想把这些NFT命名为:")
edition_name = input()
print("开始生成...")
rt = generate_images(edition_name, num_avatars)
print("保存元数据...")
rt.to_csv(os.path.join('output', 'edition ' + str(edition_name), 'metadata.csv'))
print("生成成功!")
# Run the main function
main()
|
[
"pandas.DataFrame",
"warnings.simplefilter",
"os.makedirs",
"os.path.exists",
"time.time",
"numpy.cumsum",
"random.random",
"numpy.array",
"inspect.currentframe",
"os.path.join",
"os.listdir"
] |
[((216, 278), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (237, 278), False, 'import warnings\n'), ((346, 380), 'os.path.join', 'os.path.join', (['currentdir', '"""assets"""'], {}), "(currentdir, 'assets')\n", (358, 380), False, 'import os\n'), ((427, 472), 'os.path.join', 'os.path.join', (['assets_path', "layer['directory']"], {}), "(assets_path, layer['directory'])\n", (439, 472), False, 'import os\n'), ((1232, 1251), 'numpy.cumsum', 'np.cumsum', (['rarities'], {}), '(rarities)\n', (1241, 1251), True, 'import numpy as np\n'), ((1373, 1386), 'numpy.array', 'np.array', (['arr'], {}), '(arr)\n', (1381, 1386), True, 'import numpy as np\n'), ((1479, 1527), 'os.path.join', 'os.path.join', (['currentdir', '"""assets"""', 'filepaths[0]'], {}), "(currentdir, 'assets', filepaths[0])\n", (1491, 1527), False, 'import os\n'), ((2611, 2626), 'random.random', 'random.random', ([], {}), '()\n', (2624, 2626), False, 'import random\n'), ((3182, 3205), 'os.path.exists', 'os.path.exists', (['op_path'], {}), '(op_path)\n', (3196, 3205), False, 'import os\n'), ((3215, 3235), 'os.makedirs', 'os.makedirs', (['op_path'], {}), '(op_path)\n', (3226, 3235), False, 'import os\n'), ((173, 195), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (193, 195), False, 'import inspect\n'), ((1589, 1633), 'os.path.join', 'os.path.join', (['currentdir', '"""assets"""', 'filepath'], {}), "(currentdir, 'assets', filepath)\n", (1601, 1633), False, 'import os\n'), ((2780, 2825), 'os.path.join', 'os.path.join', (["layer['directory']", 'traits[idx]'], {}), "(layer['directory'], traits[idx])\n", (2792, 2825), False, 'import os\n'), ((3430, 3463), 'os.path.join', 'os.path.join', (['op_path', 'image_name'], {}), '(op_path, image_name)\n', (3442, 3463), False, 'import os\n'), ((3734, 3760), 'pandas.DataFrame', 'pd.DataFrame', (['rarity_table'], {}), '(rarity_table)\n', (3746, 3760), True, 'import pandas as pd\n'), ((1778, 1817), 'os.path.join', 'os.path.join', (['"""output"""', '"""single_images"""'], {}), "('output', 'single_images')\n", (1790, 1817), False, 'import os\n'), ((1844, 1883), 'os.path.join', 'os.path.join', (['"""output"""', '"""single_images"""'], {}), "('output', 'single_images')\n", (1856, 1883), False, 'import os\n'), ((4157, 4176), 'os.listdir', 'os.listdir', (['op_path'], {}), '(op_path)\n', (4167, 4176), False, 'import os\n'), ((4202, 4228), 'os.path.join', 'os.path.join', (['op_path', 'img'], {}), '(op_path, img)\n', (4214, 4228), False, 'import os\n'), ((517, 539), 'os.listdir', 'os.listdir', (['layer_path'], {}), '(layer_path)\n', (527, 539), False, 'import os\n'), ((832, 847), 'random.random', 'random.random', ([], {}), '()\n', (845, 847), False, 'import random\n'), ((1949, 1960), 'time.time', 'time.time', ([], {}), '()\n', (1958, 1960), False, 'import time\n')]
|
import common as com
import matplotlib.pyplot as plt
import os
import numpy as np
def get_xy(file):
import csv
import numpy as np
x = []
y = []
with open(file, 'r') as fh:
open_file = csv.reader(fh, delimiter='\t')
for line in open_file:
x_ = line[0]
y_ = line[1]
x_ = float(x_)
y_ = float(y_)
x.append(x_)
y.append(y_)
return x, y
def get_errors(file):
import csv
import numpy as np
err = []
with open(file, 'r') as fh:
open_file = csv.reader(fh, delimiter='\t')
for line in open_file:
err_ = line[2]
err_ = float(err_)
err.append(err_)
return err
def make_plot(plt, x, y, format_, config, hysteresis=False):
if hysteresis:
try:
hyst_legend = config['legend']
except:
hyst_legend = True
com.plot_hysteresis(plt, x, y, format=format_, legend=hyst_legend)
else:
plt.plot(x, y, format_)
if __name__ == '__main__':
com.print_running_message(__file__)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', action='store', dest='input', help='input path')
parser.add_argument('-c', '--config', action='store', dest='config', help='config path')
parser.add_argument('-o', '--output', action='store', dest='output', help='output path')
args = parser.parse_args()
# input
input_path = args.input
if input_path is None:
input_path = com.get_path('Input')
if not os.path.isfile(input_path):
print('{} is not a valid input file.'.format(input_path))
input_path = com.get_path('Input')
input_file = input_path
input_dir = os.path.split(input_file)[0]
# output
output_path = args.output
if output_path is None:
output_path = input_dir
# config
config_path = args.config
if config_path is None:
config_path = com.get_path('Config')
if not os.path.isfile(config_path):
print('{} is not a valid config file.'.format(config_path))
config_path = com.get_path('Config')
config = com.read_yaml(config_path)
# read data
x, y = get_xy(input_file)
try:
normalize = config['norm']
if normalize:
print('Normalizing data.')
y = np.asarray(y)
y = com.normalize(y)
except:
pass
# # dummy data
# x = range(0,10)
# y = np.asarray(x) ** 3
# plotting
plt.figure(1)
try:
format_ = config['format']
except:
format_ = '-'
try:
hysteresis = config['hysteresis']
except:
hysteresis = False
make_plot(plt, x, y, format_, config, hysteresis=hysteresis)
try:
plottwo = config['plottwo']
except:
plottwo = False
if plottwo:
try:
input_file2 = config['plottwofp']
except:
input_file2 = None
if input_file2 is None:
input_file2 = com.get_path('Second input')
x2, y2 = get_xy(input_file2)
make_plot(plt, x2, y2, format_, config, hysteresis=hysteresis)
# TODO: Combine these statements to fix color
try:
error_provided_in_file = config['errorprovided']
except:
error_provided_in_file = False
if error_provided_in_file:
errors = get_errors(input_file)
plt.errorbar(x, y, yerr=errors, fmt='b{}'.format(format_))
if plottwo:
errors2 = get_errors(input_file2)
plt.errorbar(x2, y2, yerr=errors2, fmt='b{}'.format(format_))
try:
yerror = config['yerror']
except:
yerror = None
if yerror is not None: # TODO: Allow x error
plt.errorbar(x, y, yerr=yerror, fmt='b{}'.format(format_))
# FORMATTING
try:
grid = config['grid']
if grid:
plt.grid(b=True, which='major', color='0.50', linestyle='-')
plt.grid(b=True, which='minor', color='0.25', linestyle='--')
except:
pass
try:
biglabels = config['biglabels']
except:
biglabels = False
if biglabels:
from matplotlib import rc
font = {'size': 20}
rc('font', **font)
try:
title = config['title']
except:
title = None
if title is not None:
plt.title(title)
try:
xlabel = config['xlabel']
except:
xlabel = None
if xlabel is not None:
plt.xlabel(xlabel)
try:
ylabel = config['ylabel']
except:
ylabel = None
if ylabel is not None:
plt.ylabel(ylabel)
try:
fitline = config['fitline']
except:
fitline = False
if fitline:
# include line
try:
a_ = config['a']
b_ = config['b']
x0, xspan = config['linerange']
except:
a_ = None
b_ = None
x0 = None
xspan = None
print('Could not fit line. Please provide `a` and `b` for y = ax + b in `config.yaml`.')
if a_ is not None and b_ is not None:
if x0 is None:
x0 = 0
if xspan is None:
xspan = 100
x_ = range(x0, xspan, 1)
x_ = np.asarray(x_)
y_ = a_ * x_ + b_
plt.plot(x_, y_, color='b')
plt.axvline(0, color='k')
try:
fitline2 = config['fitline2']
except:
fitline2 = False
if fitline2:
# include line
try:
a2_ = config['a2']
b2_ = config['b2']
x20, x2span = config['linerange2']
except:
a2_ = None
b2_ = None
x20 = None
x2span = None
print('Could not fit line. Please provide `a2` and `b2` for y2 = a2x2 + b2 in `config.yaml`.')
if a2_ is not None and b2_ is not None:
if x20 is None:
x20 = 0
if x2span is None:
x2span = 100
x2_ = range(x20, x2span, 1)
x2_ = np.asarray(x2_)
y2_ = a2_ * x2_ + b2_
plt.plot(x2_, y2_, color='b')
plt.axvline(0, color='k')
# fit exponential
try:
fitexp = config['fitexp']
except:
fitexp = False
if fitexp:
try:
a_ = config['a']
b_ = config['b']
x0, xspan = config['linerange']
except:
a_ = None
b_ = None
x0 = None
xspan = None
print('Could not fit line. Please provide `a` and `b` for y = ax + b in `config.yaml`.')
if a_ is not None and b_ is not None:
if x0 is None:
x0 = 0
if xspan is None:
xspan = 100
x_ = range(x0, xspan, 1)
x_ = np.asarray(x_)
y_ = a_ * np.exp(b_ * x_)
plt.plot(x_, y_, color='b')
plt.axvline(0, color='k')
# output
try:
outname = config['outname']
outexts = config['outexts']
except:
outname = 'graph'
outexts = ['.png', '.svg']
for ext in outexts:
outfile = '{}{}'.format(outname, ext)
com.saveplot(plt, output_path, outfile, printmessage=True)
plt.show()
|
[
"matplotlib.pyplot.title",
"matplotlib.rc",
"csv.reader",
"argparse.ArgumentParser",
"matplotlib.pyplot.figure",
"os.path.isfile",
"numpy.exp",
"common.plot_hysteresis",
"matplotlib.pyplot.axvline",
"common.saveplot",
"common.get_path",
"matplotlib.pyplot.show",
"common.normalize",
"common.read_yaml",
"numpy.asarray",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.plot",
"common.print_running_message",
"matplotlib.pyplot.xlabel",
"os.path.split"
] |
[((1114, 1149), 'common.print_running_message', 'com.print_running_message', (['__file__'], {}), '(__file__)\n', (1139, 1149), True, 'import common as com\n'), ((1187, 1212), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1210, 1212), False, 'import argparse\n'), ((2263, 2289), 'common.read_yaml', 'com.read_yaml', (['config_path'], {}), '(config_path)\n', (2276, 2289), True, 'import common as com\n'), ((2641, 2654), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (2651, 2654), True, 'import matplotlib.pyplot as plt\n'), ((7590, 7600), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7598, 7600), True, 'import matplotlib.pyplot as plt\n'), ((224, 254), 'csv.reader', 'csv.reader', (['fh'], {'delimiter': '"""\t"""'}), "(fh, delimiter='\\t')\n", (234, 254), False, 'import csv\n'), ((597, 627), 'csv.reader', 'csv.reader', (['fh'], {'delimiter': '"""\t"""'}), "(fh, delimiter='\\t')\n", (607, 627), False, 'import csv\n'), ((966, 1032), 'common.plot_hysteresis', 'com.plot_hysteresis', (['plt', 'x', 'y'], {'format': 'format_', 'legend': 'hyst_legend'}), '(plt, x, y, format=format_, legend=hyst_legend)\n', (985, 1032), True, 'import common as com\n'), ((1053, 1076), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', 'format_'], {}), '(x, y, format_)\n', (1061, 1076), True, 'import matplotlib.pyplot as plt\n'), ((1618, 1639), 'common.get_path', 'com.get_path', (['"""Input"""'], {}), "('Input')\n", (1630, 1639), True, 'import common as com\n'), ((1652, 1678), 'os.path.isfile', 'os.path.isfile', (['input_path'], {}), '(input_path)\n', (1666, 1678), False, 'import os\n'), ((1769, 1790), 'common.get_path', 'com.get_path', (['"""Input"""'], {}), "('Input')\n", (1781, 1790), True, 'import common as com\n'), ((1837, 1862), 'os.path.split', 'os.path.split', (['input_file'], {}), '(input_file)\n', (1850, 1862), False, 'import os\n'), ((2070, 2092), 'common.get_path', 'com.get_path', (['"""Config"""'], {}), "('Config')\n", (2082, 2092), True, 'import common as com\n'), ((2105, 2132), 'os.path.isfile', 'os.path.isfile', (['config_path'], {}), '(config_path)\n', (2119, 2132), False, 'import os\n'), ((2226, 2248), 'common.get_path', 'com.get_path', (['"""Config"""'], {}), "('Config')\n", (2238, 2248), True, 'import common as com\n'), ((4402, 4420), 'matplotlib.rc', 'rc', (['"""font"""'], {}), "('font', **font)\n", (4404, 4420), False, 'from matplotlib import rc\n'), ((4535, 4551), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (4544, 4551), True, 'import matplotlib.pyplot as plt\n'), ((4670, 4688), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (4680, 4688), True, 'import matplotlib.pyplot as plt\n'), ((4807, 4825), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (4817, 4825), True, 'import matplotlib.pyplot as plt\n'), ((7524, 7582), 'common.saveplot', 'com.saveplot', (['plt', 'output_path', 'outfile'], {'printmessage': '(True)'}), '(plt, output_path, outfile, printmessage=True)\n', (7536, 7582), True, 'import common as com\n'), ((2468, 2481), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (2478, 2481), True, 'import numpy as np\n'), ((2499, 2515), 'common.normalize', 'com.normalize', (['y'], {}), '(y)\n', (2512, 2515), True, 'import common as com\n'), ((3169, 3197), 'common.get_path', 'com.get_path', (['"""Second input"""'], {}), "('Second input')\n", (3181, 3197), True, 'import common as com\n'), ((4056, 4116), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""major"""', 'color': '"""0.50"""', 'linestyle': '"""-"""'}), "(b=True, which='major', color='0.50', linestyle='-')\n", (4064, 4116), True, 'import matplotlib.pyplot as plt\n'), ((4130, 4191), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""minor"""', 'color': '"""0.25"""', 'linestyle': '"""--"""'}), "(b=True, which='minor', color='0.25', linestyle='--')\n", (4138, 4191), True, 'import matplotlib.pyplot as plt\n'), ((5500, 5514), 'numpy.asarray', 'np.asarray', (['x_'], {}), '(x_)\n', (5510, 5514), True, 'import numpy as np\n'), ((5559, 5586), 'matplotlib.pyplot.plot', 'plt.plot', (['x_', 'y_'], {'color': '"""b"""'}), "(x_, y_, color='b')\n", (5567, 5586), True, 'import matplotlib.pyplot as plt\n'), ((5600, 5625), 'matplotlib.pyplot.axvline', 'plt.axvline', (['(0)'], {'color': '"""k"""'}), "(0, color='k')\n", (5611, 5625), True, 'import matplotlib.pyplot as plt\n'), ((6331, 6346), 'numpy.asarray', 'np.asarray', (['x2_'], {}), '(x2_)\n', (6341, 6346), True, 'import numpy as np\n'), ((6395, 6424), 'matplotlib.pyplot.plot', 'plt.plot', (['x2_', 'y2_'], {'color': '"""b"""'}), "(x2_, y2_, color='b')\n", (6403, 6424), True, 'import matplotlib.pyplot as plt\n'), ((6438, 6463), 'matplotlib.pyplot.axvline', 'plt.axvline', (['(0)'], {'color': '"""k"""'}), "(0, color='k')\n", (6449, 6463), True, 'import matplotlib.pyplot as plt\n'), ((7133, 7147), 'numpy.asarray', 'np.asarray', (['x_'], {}), '(x_)\n', (7143, 7147), True, 'import numpy as np\n'), ((7200, 7227), 'matplotlib.pyplot.plot', 'plt.plot', (['x_', 'y_'], {'color': '"""b"""'}), "(x_, y_, color='b')\n", (7208, 7227), True, 'import matplotlib.pyplot as plt\n'), ((7241, 7266), 'matplotlib.pyplot.axvline', 'plt.axvline', (['(0)'], {'color': '"""k"""'}), "(0, color='k')\n", (7252, 7266), True, 'import matplotlib.pyplot as plt\n'), ((7171, 7186), 'numpy.exp', 'np.exp', (['(b_ * x_)'], {}), '(b_ * x_)\n', (7177, 7186), True, 'import numpy as np\n')]
|
"""
Tests of noise input.
"""
import unittest
import numpy as np
from chspy import CubicHermiteSpline
from neurolib.models.aln import ALNModel
from neurolib.utils.stimulus import (
ConcatenatedStimulus,
ExponentialInput,
LinearRampInput,
OrnsteinUhlenbeckProcess,
RectifiedInput,
SinusoidalInput,
SquareInput,
StepInput,
SummedStimulus,
WienerProcess,
ZeroInput,
)
TESTING_TIME = 5.3
DURATION = 10
DT = 0.1
STIM_START = 2
STIM_END = 8
SHAPE = (2, int(DURATION / DT))
class TestCubicSplines(unittest.TestCase):
RESULT_SPLINES = np.array([-0.214062, -0.215043])
RESULT_ARRAY = np.array([0.193429, 0.073445])
def test_splines(self):
dW = WienerProcess(n=2, seed=42).as_cubic_splines(duration=DURATION, dt=DT)
self.assertTrue(isinstance(dW, CubicHermiteSpline))
np.testing.assert_allclose(self.RESULT_SPLINES, dW.get_state(TESTING_TIME), atol=1e-05)
def test_arrays(self):
dW = WienerProcess(n=2, seed=42).as_array(duration=DURATION, dt=DT)
self.assertTrue(isinstance(dW, np.ndarray))
time_idx = np.around(TESTING_TIME / DT).astype(int)
np.testing.assert_allclose(self.RESULT_ARRAY, dW[:, time_idx], atol=1e-05)
def test_shift_start_time(self):
SHIFT = 5.0
dW = WienerProcess(n=2, seed=42).as_cubic_splines(duration=DURATION, dt=DT, shift_start_time=SHIFT)
self.assertTrue(isinstance(dW, CubicHermiteSpline))
self.assertEqual(dW[0].time, SHIFT + DT)
np.testing.assert_allclose(self.RESULT_SPLINES, dW.get_state(TESTING_TIME + SHIFT), atol=1e-05)
class TestToModel(unittest.TestCase):
def test_single_node(self):
model = ALNModel()
model.params["duration"] = 2 * 1000
stim = SinusoidalInput(amplitude=1.0, frequency=1.0)
model_stim = stim.to_model(model)
model.params["ext_exc_current"] = model_stim
model.run()
self.assertTrue(isinstance(model_stim, np.ndarray))
self.assertTupleEqual(model_stim.shape, (1, int(model.params["duration"] / model.params["dt"])))
def test_multi_node_multi_stim(self):
model = ALNModel(Cmat=np.random.rand(5, 5), Dmat=np.zeros((5, 5)))
model.params["duration"] = 2 * 1000
stim = SinusoidalInput(amplitude=1.0, frequency=1.0)
model_stim = stim.to_model(model)
model.params["ext_exc_current"] = model_stim
model.run()
self.assertTrue(isinstance(model_stim, np.ndarray))
self.assertTupleEqual(model_stim.shape, (5, int(model.params["duration"] / model.params["dt"])))
class TestZeroInput(unittest.TestCase):
def test_generate_input(self):
nn = ZeroInput(n=2, seed=42).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(nn, np.ndarray))
self.assertTupleEqual(nn.shape, SHAPE)
np.testing.assert_allclose(nn, np.zeros(SHAPE))
def test_get_params(self):
nn = ZeroInput(n=2, seed=42)
params = nn.get_params()
params.pop("type")
self.assertDictEqual(params, {"n": 2, "seed": 42})
def test_set_params(self):
nn = ZeroInput(n=2, seed=42)
UPDATE = {"seed": 635}
nn.update_params(UPDATE)
params = nn.get_params()
params.pop("type")
self.assertDictEqual(params, {"n": 2, "seed": 42, **UPDATE})
class TestWienerProcess(unittest.TestCase):
def test_generate_input(self):
dW = WienerProcess(n=2, seed=42).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(dW, np.ndarray))
self.assertTupleEqual(dW.shape, SHAPE)
def test_get_params(self):
dW = WienerProcess(n=2, seed=42)
params = dW.get_params()
params.pop("type")
self.assertDictEqual(params, {"n": 2, "seed": 42})
def test_set_params(self):
dW = WienerProcess(n=2, seed=42)
UPDATE = {"seed": 6152, "n": 5}
dW.update_params(UPDATE)
params = dW.get_params()
params.pop("type")
self.assertDictEqual(params, {"n": 2, "seed": 42, **UPDATE})
class TestOrnsteinUhlenbeckProcess(unittest.TestCase):
def test_generate_input(self):
ou = OrnsteinUhlenbeckProcess(
mu=3.0,
sigma=0.1,
tau=2 * DT,
n=2,
seed=42,
).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ou, np.ndarray))
self.assertTupleEqual(ou.shape, SHAPE)
def test_get_params(self):
ou = OrnsteinUhlenbeckProcess(
mu=3.0,
sigma=0.1,
tau=2 * DT,
n=2,
seed=42,
)
params = ou.get_params()
params.pop("type")
self.assertDictEqual(params, {"n": 2, "seed": 42, "mu": 3.0, "sigma": 0.1, "tau": 2 * DT})
def test_set_params(self):
ou = OrnsteinUhlenbeckProcess(
mu=3.0,
sigma=0.1,
tau=2 * DT,
n=2,
seed=42,
)
UPDATE = {"mu": 2.3, "seed": 12}
ou.update_params(UPDATE)
params = ou.get_params()
params.pop("type")
self.assertDictEqual(params, {"n": 2, "seed": 42, "mu": 3.0, "sigma": 0.1, "tau": 2 * DT, **UPDATE})
class TestStepInput(unittest.TestCase):
STEP_SIZE = 2.3
def test_generate_input(self):
step = StepInput(
step_size=self.STEP_SIZE,
n=2,
seed=42,
).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(step, np.ndarray))
self.assertTupleEqual(step.shape, SHAPE)
np.testing.assert_allclose(step, self.STEP_SIZE)
def test_start_end_input(self):
step = StepInput(
start=STIM_START,
end=STIM_END,
step_size=self.STEP_SIZE,
n=2,
seed=42,
).as_array(duration=DURATION, dt=DT)
np.testing.assert_allclose(step[:, : int(STIM_START / DT)], 0.0)
np.testing.assert_allclose(step[:, int(STIM_END / DT) :], 0.0)
class TestSinusoidalInput(unittest.TestCase):
AMPLITUDE = 2.3
FREQUENCY = 1000.0
def test_generate_input(self):
sin = SinusoidalInput(
amplitude=self.AMPLITUDE, frequency=self.FREQUENCY, n=2, seed=42, dc_bias=True
).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(sin, np.ndarray))
self.assertTupleEqual(sin.shape, SHAPE)
np.testing.assert_almost_equal(np.mean(sin, axis=1), np.array(2 * [self.AMPLITUDE]))
def test_start_end_input(self):
sin = SinusoidalInput(
start=STIM_START,
end=STIM_END,
amplitude=self.AMPLITUDE,
frequency=self.FREQUENCY,
n=2,
seed=42,
).as_array(duration=DURATION, dt=DT)
np.testing.assert_allclose(sin[:, : int(STIM_START / DT)], 0.0)
np.testing.assert_allclose(sin[:, int(STIM_END / DT) :], 0.0)
def test_get_params(self):
sin = SinusoidalInput(
start=STIM_START,
end=STIM_END,
amplitude=self.AMPLITUDE,
frequency=self.FREQUENCY,
n=2,
seed=42,
)
params = sin.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"frequency": self.FREQUENCY,
"amplitude": self.AMPLITUDE,
"start": STIM_START,
"dc_bias": False,
"end": STIM_END,
},
)
def test_set_params(self):
sin = SinusoidalInput(
start=STIM_START,
end=STIM_END,
amplitude=self.AMPLITUDE,
frequency=self.FREQUENCY,
n=2,
seed=42,
)
UPDATE = {"amplitude": 43.0, "seed": 12, "start": "None"}
sin.update_params(UPDATE)
params = sin.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"frequency": self.FREQUENCY,
"amplitude": self.AMPLITUDE,
"dc_bias": False,
"end": STIM_END,
**UPDATE,
"start": None,
},
)
class TestSquareInput(unittest.TestCase):
AMPLITUDE = 2.3
FREQUENCY = 20.0
def test_generate_input(self):
sq = SquareInput(
amplitude=self.AMPLITUDE,
frequency=self.FREQUENCY,
n=2,
seed=42,
).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(sq, np.ndarray))
self.assertTupleEqual(sq.shape, SHAPE)
np.testing.assert_almost_equal(np.mean(sq, axis=1), np.array(2 * [self.AMPLITUDE]))
def test_start_end_input(self):
sq = SquareInput(
start=STIM_START,
end=STIM_END,
amplitude=self.AMPLITUDE,
frequency=self.FREQUENCY,
n=2,
seed=42,
).as_array(duration=DURATION, dt=DT)
np.testing.assert_allclose(sq[:, : int(STIM_START / DT)], 0.0)
np.testing.assert_allclose(sq[:, int(STIM_END / DT) :], 0.0)
def test_get_params(self):
sq = SquareInput(
start=STIM_START,
end=STIM_END,
amplitude=self.AMPLITUDE,
frequency=self.FREQUENCY,
n=2,
seed=42,
)
params = sq.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"frequency": self.FREQUENCY,
"amplitude": self.AMPLITUDE,
"start": STIM_START,
"end": STIM_END,
"dc_bias": False,
},
)
def test_set_params(self):
sq = SquareInput(
start=STIM_START,
end=STIM_END,
amplitude=self.AMPLITUDE,
frequency=self.FREQUENCY,
n=2,
seed=42,
)
UPDATE = {"amplitude": 43.0, "seed": 12, "start": "None"}
sq.update_params(UPDATE)
params = sq.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"frequency": self.FREQUENCY,
"amplitude": self.AMPLITUDE,
"end": STIM_END,
"dc_bias": False,
**UPDATE,
"start": None,
},
)
class TestLinearRampInput(unittest.TestCase):
INP_MAX = 5.0
RAMP_LENGTH = 2.0
def test_generate_input(self):
ramp = LinearRampInput(
inp_max=self.INP_MAX,
ramp_length=self.RAMP_LENGTH,
n=2,
seed=42,
).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ramp, np.ndarray))
self.assertTupleEqual(ramp.shape, SHAPE)
np.testing.assert_equal(np.max(ramp, axis=1), np.array(2 * [self.INP_MAX]))
np.testing.assert_equal(np.min(ramp, axis=1), np.array(2 * [0.25]))
def test_start_end_input(self):
ramp = LinearRampInput(
start=STIM_START,
end=STIM_END,
inp_max=self.INP_MAX,
ramp_length=self.RAMP_LENGTH,
n=2,
seed=42,
).as_array(duration=DURATION, dt=DT)
np.testing.assert_allclose(ramp[:, : int(STIM_START / DT)], 0.0)
np.testing.assert_allclose(ramp[:, int(STIM_END / DT) :], 0.0)
def test_get_params(self):
ramp = LinearRampInput(
start=STIM_START,
end=STIM_END,
inp_max=self.INP_MAX,
ramp_length=self.RAMP_LENGTH,
n=2,
seed=42,
)
params = ramp.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"inp_max": self.INP_MAX,
"ramp_length": self.RAMP_LENGTH,
"start": STIM_START,
"end": STIM_END,
},
)
def test_set_params(self):
ramp = LinearRampInput(
start=STIM_START,
end=STIM_END,
inp_max=self.INP_MAX,
ramp_length=self.RAMP_LENGTH,
n=2,
seed=42,
)
UPDATE = {"inp_max": 41.0, "seed": 12}
ramp.update_params(UPDATE)
params = ramp.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"inp_max": self.INP_MAX,
"ramp_length": self.RAMP_LENGTH,
"start": STIM_START,
"end": STIM_END,
**UPDATE,
},
)
class TestExponentialInput(unittest.TestCase):
INP_MAX = 5.0
EXP_COEF = 30.0
EXP_TYPE = "rise"
def test_generate_input_rise(self):
exp_rise = ExponentialInput(
inp_max=self.INP_MAX,
exp_type="rise",
n=2,
seed=42,
).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(exp_rise, np.ndarray))
self.assertTupleEqual(exp_rise.shape, SHAPE)
np.testing.assert_almost_equal(np.max(exp_rise, axis=1), np.array(2 * [self.INP_MAX]))
self.assertTrue(np.all(np.diff(exp_rise) >= 0))
def test_generate_input_decay(self):
exp_decay = ExponentialInput(
inp_max=self.INP_MAX,
exp_type="decay",
n=2,
seed=42,
).generate_input(duration=DURATION, dt=DT)
self.assertTrue(isinstance(exp_decay, np.ndarray))
self.assertTupleEqual(exp_decay.shape, SHAPE)
self.assertTrue(np.all(np.diff(exp_decay) <= 0))
def test_start_end_input(self):
exp_rise = ExponentialInput(
start=STIM_START,
end=STIM_END,
inp_max=self.INP_MAX,
n=2,
seed=42,
).as_array(duration=DURATION, dt=DT)
np.testing.assert_allclose(exp_rise[:, : int(STIM_START / DT)], 0.0)
np.testing.assert_allclose(exp_rise[:, int(STIM_END / DT) :], 0.0)
def test_get_params(self):
exp_rise = ExponentialInput(
start=STIM_START,
end=STIM_END,
inp_max=self.INP_MAX,
n=2,
seed=42,
)
params = exp_rise.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"inp_max": self.INP_MAX,
"exp_coef": self.EXP_COEF,
"exp_type": self.EXP_TYPE,
"start": STIM_START,
"end": STIM_END,
},
)
def test_set_params(self):
exp_rise = ExponentialInput(
start=STIM_START,
end=STIM_END,
inp_max=self.INP_MAX,
n=2,
seed=42,
)
UPDATE = {"inp_max": 41.0, "seed": 12}
exp_rise.update_params(UPDATE)
params = exp_rise.get_params()
params.pop("type")
self.assertDictEqual(
params,
{
"n": 2,
"seed": 42,
"inp_max": self.INP_MAX,
"exp_coef": self.EXP_COEF,
"exp_type": self.EXP_TYPE,
"start": STIM_START,
"end": STIM_END,
**UPDATE,
},
)
class TestSummedStimulus(unittest.TestCase):
def _create_input(self):
ou = OrnsteinUhlenbeckProcess(mu=0.1, sigma=0.02, tau=2.0, n=2)
sq = SquareInput(amplitude=0.2, frequency=50, n=2, start=5)
sin = SinusoidalInput(amplitude=0.1, frequency=100, n=2, start=2)
step = StepInput(step_size=0.5, n=2, start=7)
return sq + (sin + step + ou)
def test_init(self):
summed = self._create_input()
self.assertEqual(len(summed), 4)
self.assertTrue(isinstance(summed, SummedStimulus))
self.assertEqual(summed.n, 2)
self.assertEqual(len(summed.inputs), 4)
def test_set_n(self):
summed = self._create_input()
self.assertEqual(summed.n, 2)
ts = summed.as_array(duration=DURATION, dt=DT)
self.assertEqual(ts.shape[0], 2)
summed.n = 5
self.assertEqual(summed.n, 5)
ts = summed.as_array(duration=DURATION, dt=DT)
self.assertEqual(ts.shape[0], 5)
def test_generate_input(self):
summed = self._create_input()
ts = summed.as_array(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ts, np.ndarray))
self.assertTupleEqual(ts.shape, SHAPE)
ts = summed.as_cubic_splines(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ts, CubicHermiteSpline))
def test_get_params(self):
summed = self._create_input()
params = summed.get_params()
self.assertTrue(isinstance(params, dict))
self.assertEqual(len(params), 1 + len(summed.inputs))
for i, process in enumerate(summed):
self.assertDictEqual(process.get_params(), params[f"input_{i}"])
def test_update_params(self):
summed = self._create_input()
UPDATE_DICT = {f"input_{i}": {"n": 3} for i in range(len(summed))}
summed.update_params(UPDATE_DICT)
self.assertEqual(summed.n, 3)
class TestConcatenatedStimulus(unittest.TestCase):
def _create_input(self):
ou = OrnsteinUhlenbeckProcess(mu=0.1, sigma=0.02, tau=2.0, n=2)
sq = SquareInput(amplitude=0.2, frequency=20.0, n=2)
sin = SinusoidalInput(amplitude=0.1, frequency=10.0, n=2)
step = StepInput(step_size=0.5, n=2)
return ou & (sq & sin & step)
def test_init(self):
conc = self._create_input()
self.assertEqual(len(conc), 4)
self.assertTrue(isinstance(conc, ConcatenatedStimulus))
self.assertEqual(conc.n, 2)
self.assertEqual(len(conc.inputs), 4)
def test_set_n(self):
conc = self._create_input()
self.assertEqual(conc.n, 2)
ts = conc.as_array(duration=DURATION, dt=DT)
self.assertEqual(ts.shape[0], 2)
conc.n = 5
self.assertEqual(conc.n, 5)
ts = conc.as_array(duration=DURATION, dt=DT)
self.assertEqual(ts.shape[0], 5)
def test_generate_input(self):
conc = self._create_input()
ts = conc.as_array(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ts, np.ndarray))
self.assertTupleEqual(ts.shape, SHAPE)
ts = conc.as_cubic_splines(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ts, CubicHermiteSpline))
def test_get_params(self):
conc = self._create_input()
params = conc.get_params()
self.assertTrue(isinstance(params, dict))
self.assertEqual(len(params), 1 + len(conc.inputs))
for i, process in enumerate(conc):
self.assertDictEqual(process.get_params(), params[f"input_{i}"])
def test_update_params(self):
conc = self._create_input()
UPDATE_DICT = {f"input_{i}": {"n": 3} for i in range(len(conc))}
conc.update_params(UPDATE_DICT)
self.assertEqual(conc.n, 3)
class TestBeastInput(unittest.TestCase):
def _create_input(self):
ou = OrnsteinUhlenbeckProcess(mu=0.1, sigma=0.02, tau=2.0, n=2)
sq = SquareInput(amplitude=0.2, frequency=20.0, n=2)
sin = SinusoidalInput(amplitude=0.1, frequency=10.0, n=2)
step = StepInput(step_size=0.5, n=2)
return (sq + sin) & (step + ou)
def test_init(self):
beast = self._create_input()
self.assertEqual(len(beast), 2)
self.assertTrue(isinstance(beast, ConcatenatedStimulus))
for process in beast:
self.assertTrue(isinstance(process, SummedStimulus))
self.assertEqual(beast.n, 2)
def test_set_n(self):
beast = self._create_input()
self.assertEqual(beast.n, 2)
ts = beast.as_array(duration=DURATION, dt=DT)
self.assertEqual(ts.shape[0], 2)
beast.n = 5
self.assertEqual(beast.n, 5)
ts = beast.as_array(duration=DURATION, dt=DT)
self.assertEqual(ts.shape[0], 5)
def test_generate_input(self):
beast = self._create_input()
ts = beast.as_array(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ts, np.ndarray))
self.assertTupleEqual(ts.shape, SHAPE)
ts = beast.as_cubic_splines(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ts, CubicHermiteSpline))
def test_get_params(self):
beast = self._create_input()
params = beast.get_params()
self.assertTrue(isinstance(params, dict))
self.assertEqual(len(params), 1 + len(beast.inputs))
for i, process in enumerate(beast):
self.assertDictEqual(process.get_params(), params[f"input_{i}"])
class TestRectifiedInput(unittest.TestCase):
def test_init(self):
rect = RectifiedInput(0.2, n=2)
self.assertTrue(isinstance(rect, ConcatenatedStimulus))
self.assertEqual(len(rect), 5)
self.assertEqual(rect.n, 2)
def test_generate(self):
rect = RectifiedInput(0.2, n=2)
ts = rect.as_array(DURATION, DT)
self.assertTrue(isinstance(ts, np.ndarray))
self.assertTupleEqual(ts.shape, SHAPE)
ts = rect.as_cubic_splines(duration=DURATION, dt=DT)
self.assertTrue(isinstance(ts, CubicHermiteSpline))
if __name__ == "__main__":
unittest.main()
|
[
"neurolib.utils.stimulus.RectifiedInput",
"neurolib.utils.stimulus.StepInput",
"neurolib.utils.stimulus.SinusoidalInput",
"neurolib.utils.stimulus.OrnsteinUhlenbeckProcess",
"numpy.around",
"numpy.mean",
"neurolib.utils.stimulus.LinearRampInput",
"unittest.main",
"neurolib.utils.stimulus.ExponentialInput",
"numpy.max",
"neurolib.utils.stimulus.WienerProcess",
"numpy.testing.assert_allclose",
"numpy.min",
"neurolib.models.aln.ALNModel",
"neurolib.utils.stimulus.ZeroInput",
"neurolib.utils.stimulus.SquareInput",
"numpy.zeros",
"numpy.diff",
"numpy.array",
"numpy.random.rand"
] |
[((580, 612), 'numpy.array', 'np.array', (['[-0.214062, -0.215043]'], {}), '([-0.214062, -0.215043])\n', (588, 612), True, 'import numpy as np\n'), ((632, 662), 'numpy.array', 'np.array', (['[0.193429, 0.073445]'], {}), '([0.193429, 0.073445])\n', (640, 662), True, 'import numpy as np\n'), ((21803, 21818), 'unittest.main', 'unittest.main', ([], {}), '()\n', (21816, 21818), False, 'import unittest\n'), ((1156, 1230), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['self.RESULT_ARRAY', 'dW[:, time_idx]'], {'atol': '(1e-05)'}), '(self.RESULT_ARRAY, dW[:, time_idx], atol=1e-05)\n', (1182, 1230), True, 'import numpy as np\n'), ((1698, 1708), 'neurolib.models.aln.ALNModel', 'ALNModel', ([], {}), '()\n', (1706, 1708), False, 'from neurolib.models.aln import ALNModel\n'), ((1768, 1813), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'amplitude': '(1.0)', 'frequency': '(1.0)'}), '(amplitude=1.0, frequency=1.0)\n', (1783, 1813), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((2271, 2316), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'amplitude': '(1.0)', 'frequency': '(1.0)'}), '(amplitude=1.0, frequency=1.0)\n', (2286, 2316), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((2952, 2975), 'neurolib.utils.stimulus.ZeroInput', 'ZeroInput', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (2961, 2975), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((3140, 3163), 'neurolib.utils.stimulus.ZeroInput', 'ZeroInput', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (3149, 3163), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((3664, 3691), 'neurolib.utils.stimulus.WienerProcess', 'WienerProcess', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (3677, 3691), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((3856, 3883), 'neurolib.utils.stimulus.WienerProcess', 'WienerProcess', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (3869, 3883), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((4517, 4586), 'neurolib.utils.stimulus.OrnsteinUhlenbeckProcess', 'OrnsteinUhlenbeckProcess', ([], {'mu': '(3.0)', 'sigma': '(0.1)', 'tau': '(2 * DT)', 'n': '(2)', 'seed': '(42)'}), '(mu=3.0, sigma=0.1, tau=2 * DT, n=2, seed=42)\n', (4541, 4586), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((4862, 4931), 'neurolib.utils.stimulus.OrnsteinUhlenbeckProcess', 'OrnsteinUhlenbeckProcess', ([], {'mu': '(3.0)', 'sigma': '(0.1)', 'tau': '(2 * DT)', 'n': '(2)', 'seed': '(42)'}), '(mu=3.0, sigma=0.1, tau=2 * DT, n=2, seed=42)\n', (4886, 4931), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((5608, 5656), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['step', 'self.STEP_SIZE'], {}), '(step, self.STEP_SIZE)\n', (5634, 5656), True, 'import numpy as np\n'), ((7006, 7123), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, amplitude=self.AMPLITUDE,\n frequency=self.FREQUENCY, n=2, seed=42)\n', (7021, 7123), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((7645, 7762), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, amplitude=self.AMPLITUDE,\n frequency=self.FREQUENCY, n=2, seed=42)\n', (7660, 7762), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((9325, 9438), 'neurolib.utils.stimulus.SquareInput', 'SquareInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, amplitude=self.AMPLITUDE,\n frequency=self.FREQUENCY, n=2, seed=42)\n', (9336, 9438), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((9958, 10071), 'neurolib.utils.stimulus.SquareInput', 'SquareInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, amplitude=self.AMPLITUDE,\n frequency=self.FREQUENCY, n=2, seed=42)\n', (9969, 10071), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((11725, 11842), 'neurolib.utils.stimulus.LinearRampInput', 'LinearRampInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'inp_max': 'self.INP_MAX', 'ramp_length': 'self.RAMP_LENGTH', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, inp_max=self.INP_MAX,\n ramp_length=self.RAMP_LENGTH, n=2, seed=42)\n', (11740, 11842), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((12332, 12449), 'neurolib.utils.stimulus.LinearRampInput', 'LinearRampInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'inp_max': 'self.INP_MAX', 'ramp_length': 'self.RAMP_LENGTH', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, inp_max=self.INP_MAX,\n ramp_length=self.RAMP_LENGTH, n=2, seed=42)\n', (12347, 12449), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((14454, 14542), 'neurolib.utils.stimulus.ExponentialInput', 'ExponentialInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'inp_max': 'self.INP_MAX', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, inp_max=self.INP_MAX, n=2,\n seed=42)\n', (14470, 14542), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((15065, 15153), 'neurolib.utils.stimulus.ExponentialInput', 'ExponentialInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'inp_max': 'self.INP_MAX', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, inp_max=self.INP_MAX, n=2,\n seed=42)\n', (15081, 15153), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((15826, 15884), 'neurolib.utils.stimulus.OrnsteinUhlenbeckProcess', 'OrnsteinUhlenbeckProcess', ([], {'mu': '(0.1)', 'sigma': '(0.02)', 'tau': '(2.0)', 'n': '(2)'}), '(mu=0.1, sigma=0.02, tau=2.0, n=2)\n', (15850, 15884), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((15898, 15952), 'neurolib.utils.stimulus.SquareInput', 'SquareInput', ([], {'amplitude': '(0.2)', 'frequency': '(50)', 'n': '(2)', 'start': '(5)'}), '(amplitude=0.2, frequency=50, n=2, start=5)\n', (15909, 15952), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((15967, 16026), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'amplitude': '(0.1)', 'frequency': '(100)', 'n': '(2)', 'start': '(2)'}), '(amplitude=0.1, frequency=100, n=2, start=2)\n', (15982, 16026), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((16042, 16080), 'neurolib.utils.stimulus.StepInput', 'StepInput', ([], {'step_size': '(0.5)', 'n': '(2)', 'start': '(7)'}), '(step_size=0.5, n=2, start=7)\n', (16051, 16080), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((17740, 17798), 'neurolib.utils.stimulus.OrnsteinUhlenbeckProcess', 'OrnsteinUhlenbeckProcess', ([], {'mu': '(0.1)', 'sigma': '(0.02)', 'tau': '(2.0)', 'n': '(2)'}), '(mu=0.1, sigma=0.02, tau=2.0, n=2)\n', (17764, 17798), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((17812, 17859), 'neurolib.utils.stimulus.SquareInput', 'SquareInput', ([], {'amplitude': '(0.2)', 'frequency': '(20.0)', 'n': '(2)'}), '(amplitude=0.2, frequency=20.0, n=2)\n', (17823, 17859), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((17874, 17925), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'amplitude': '(0.1)', 'frequency': '(10.0)', 'n': '(2)'}), '(amplitude=0.1, frequency=10.0, n=2)\n', (17889, 17925), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((17941, 17970), 'neurolib.utils.stimulus.StepInput', 'StepInput', ([], {'step_size': '(0.5)', 'n': '(2)'}), '(step_size=0.5, n=2)\n', (17950, 17970), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((19582, 19640), 'neurolib.utils.stimulus.OrnsteinUhlenbeckProcess', 'OrnsteinUhlenbeckProcess', ([], {'mu': '(0.1)', 'sigma': '(0.02)', 'tau': '(2.0)', 'n': '(2)'}), '(mu=0.1, sigma=0.02, tau=2.0, n=2)\n', (19606, 19640), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((19654, 19701), 'neurolib.utils.stimulus.SquareInput', 'SquareInput', ([], {'amplitude': '(0.2)', 'frequency': '(20.0)', 'n': '(2)'}), '(amplitude=0.2, frequency=20.0, n=2)\n', (19665, 19701), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((19716, 19767), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'amplitude': '(0.1)', 'frequency': '(10.0)', 'n': '(2)'}), '(amplitude=0.1, frequency=10.0, n=2)\n', (19731, 19767), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((19783, 19812), 'neurolib.utils.stimulus.StepInput', 'StepInput', ([], {'step_size': '(0.5)', 'n': '(2)'}), '(step_size=0.5, n=2)\n', (19792, 19812), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((21274, 21298), 'neurolib.utils.stimulus.RectifiedInput', 'RectifiedInput', (['(0.2)'], {'n': '(2)'}), '(0.2, n=2)\n', (21288, 21298), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((21483, 21507), 'neurolib.utils.stimulus.RectifiedInput', 'RectifiedInput', (['(0.2)'], {'n': '(2)'}), '(0.2, n=2)\n', (21497, 21507), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((2890, 2905), 'numpy.zeros', 'np.zeros', (['SHAPE'], {}), '(SHAPE)\n', (2898, 2905), True, 'import numpy as np\n'), ((6481, 6501), 'numpy.mean', 'np.mean', (['sin'], {'axis': '(1)'}), '(sin, axis=1)\n', (6488, 6501), True, 'import numpy as np\n'), ((6503, 6533), 'numpy.array', 'np.array', (['(2 * [self.AMPLITUDE])'], {}), '(2 * [self.AMPLITUDE])\n', (6511, 6533), True, 'import numpy as np\n'), ((8809, 8828), 'numpy.mean', 'np.mean', (['sq'], {'axis': '(1)'}), '(sq, axis=1)\n', (8816, 8828), True, 'import numpy as np\n'), ((8830, 8860), 'numpy.array', 'np.array', (['(2 * [self.AMPLITUDE])'], {}), '(2 * [self.AMPLITUDE])\n', (8838, 8860), True, 'import numpy as np\n'), ((11122, 11142), 'numpy.max', 'np.max', (['ramp'], {'axis': '(1)'}), '(ramp, axis=1)\n', (11128, 11142), True, 'import numpy as np\n'), ((11144, 11172), 'numpy.array', 'np.array', (['(2 * [self.INP_MAX])'], {}), '(2 * [self.INP_MAX])\n', (11152, 11172), True, 'import numpy as np\n'), ((11206, 11226), 'numpy.min', 'np.min', (['ramp'], {'axis': '(1)'}), '(ramp, axis=1)\n', (11212, 11226), True, 'import numpy as np\n'), ((11228, 11248), 'numpy.array', 'np.array', (['(2 * [0.25])'], {}), '(2 * [0.25])\n', (11236, 11248), True, 'import numpy as np\n'), ((13489, 13513), 'numpy.max', 'np.max', (['exp_rise'], {'axis': '(1)'}), '(exp_rise, axis=1)\n', (13495, 13513), True, 'import numpy as np\n'), ((13515, 13543), 'numpy.array', 'np.array', (['(2 * [self.INP_MAX])'], {}), '(2 * [self.INP_MAX])\n', (13523, 13543), True, 'import numpy as np\n'), ((705, 732), 'neurolib.utils.stimulus.WienerProcess', 'WienerProcess', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (718, 732), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((973, 1000), 'neurolib.utils.stimulus.WienerProcess', 'WienerProcess', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (986, 1000), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((1107, 1135), 'numpy.around', 'np.around', (['(TESTING_TIME / DT)'], {}), '(TESTING_TIME / DT)\n', (1116, 1135), True, 'import numpy as np\n'), ((1302, 1329), 'neurolib.utils.stimulus.WienerProcess', 'WienerProcess', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (1315, 1329), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((2167, 2187), 'numpy.random.rand', 'np.random.rand', (['(5)', '(5)'], {}), '(5, 5)\n', (2181, 2187), True, 'import numpy as np\n'), ((2194, 2210), 'numpy.zeros', 'np.zeros', (['(5, 5)'], {}), '((5, 5))\n', (2202, 2210), True, 'import numpy as np\n'), ((2687, 2710), 'neurolib.utils.stimulus.ZeroInput', 'ZeroInput', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (2696, 2710), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((3451, 3478), 'neurolib.utils.stimulus.WienerProcess', 'WienerProcess', ([], {'n': '(2)', 'seed': '(42)'}), '(n=2, seed=42)\n', (3464, 3478), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((4191, 4260), 'neurolib.utils.stimulus.OrnsteinUhlenbeckProcess', 'OrnsteinUhlenbeckProcess', ([], {'mu': '(3.0)', 'sigma': '(0.1)', 'tau': '(2 * DT)', 'n': '(2)', 'seed': '(42)'}), '(mu=3.0, sigma=0.1, tau=2 * DT, n=2, seed=42)\n', (4215, 4260), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((5359, 5408), 'neurolib.utils.stimulus.StepInput', 'StepInput', ([], {'step_size': 'self.STEP_SIZE', 'n': '(2)', 'seed': '(42)'}), '(step_size=self.STEP_SIZE, n=2, seed=42)\n', (5368, 5408), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((5709, 5794), 'neurolib.utils.stimulus.StepInput', 'StepInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'step_size': 'self.STEP_SIZE', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, step_size=self.STEP_SIZE, n=2,\n seed=42)\n', (5718, 5794), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((6182, 6281), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)', 'dc_bias': '(True)'}), '(amplitude=self.AMPLITUDE, frequency=self.FREQUENCY, n=2,\n seed=42, dc_bias=True)\n', (6197, 6281), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((6586, 6703), 'neurolib.utils.stimulus.SinusoidalInput', 'SinusoidalInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, amplitude=self.AMPLITUDE,\n frequency=self.FREQUENCY, n=2, seed=42)\n', (6601, 6703), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((8493, 8570), 'neurolib.utils.stimulus.SquareInput', 'SquareInput', ([], {'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)'}), '(amplitude=self.AMPLITUDE, frequency=self.FREQUENCY, n=2, seed=42)\n', (8504, 8570), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((8912, 9025), 'neurolib.utils.stimulus.SquareInput', 'SquareInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'amplitude': 'self.AMPLITUDE', 'frequency': 'self.FREQUENCY', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, amplitude=self.AMPLITUDE,\n frequency=self.FREQUENCY, n=2, seed=42)\n', (8923, 9025), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((10805, 10890), 'neurolib.utils.stimulus.LinearRampInput', 'LinearRampInput', ([], {'inp_max': 'self.INP_MAX', 'ramp_length': 'self.RAMP_LENGTH', 'n': '(2)', 'seed': '(42)'}), '(inp_max=self.INP_MAX, ramp_length=self.RAMP_LENGTH, n=2,\n seed=42)\n', (10820, 10890), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((11302, 11419), 'neurolib.utils.stimulus.LinearRampInput', 'LinearRampInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'inp_max': 'self.INP_MAX', 'ramp_length': 'self.RAMP_LENGTH', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, inp_max=self.INP_MAX,\n ramp_length=self.RAMP_LENGTH, n=2, seed=42)\n', (11317, 11419), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((13169, 13238), 'neurolib.utils.stimulus.ExponentialInput', 'ExponentialInput', ([], {'inp_max': 'self.INP_MAX', 'exp_type': '"""rise"""', 'n': '(2)', 'seed': '(42)'}), "(inp_max=self.INP_MAX, exp_type='rise', n=2, seed=42)\n", (13185, 13238), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((13663, 13733), 'neurolib.utils.stimulus.ExponentialInput', 'ExponentialInput', ([], {'inp_max': 'self.INP_MAX', 'exp_type': '"""decay"""', 'n': '(2)', 'seed': '(42)'}), "(inp_max=self.INP_MAX, exp_type='decay', n=2, seed=42)\n", (13679, 13733), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((14060, 14148), 'neurolib.utils.stimulus.ExponentialInput', 'ExponentialInput', ([], {'start': 'STIM_START', 'end': 'STIM_END', 'inp_max': 'self.INP_MAX', 'n': '(2)', 'seed': '(42)'}), '(start=STIM_START, end=STIM_END, inp_max=self.INP_MAX, n=2,\n seed=42)\n', (14076, 14148), False, 'from neurolib.utils.stimulus import ConcatenatedStimulus, ExponentialInput, LinearRampInput, OrnsteinUhlenbeckProcess, RectifiedInput, SinusoidalInput, SquareInput, StepInput, SummedStimulus, WienerProcess, ZeroInput\n'), ((13576, 13593), 'numpy.diff', 'np.diff', (['exp_rise'], {}), '(exp_rise)\n', (13583, 13593), True, 'import numpy as np\n'), ((13978, 13996), 'numpy.diff', 'np.diff', (['exp_decay'], {}), '(exp_decay)\n', (13985, 13996), True, 'import numpy as np\n')]
|
import os
import cv2
import sys
import time
import collections
import torch
import argparse
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from config import *
from torch.autograd import Variable
from torch.utils import data
from dataLoader import TestLoader
import fpn_resnet as models
#import fpn_resnet_dcn as models
# c++ version pse based on opencv 3+
from pse import pse
# python pse
# from pypse import pse as pypse
import glob
import shutil
#import onnx
USE_TF = False
class Detector():
def __init__(self, model_path):
# init Model
#self._model = torch.jit.load(model_path)
#self._model = onnx.load(model_path)
self._model = models.resnet50(pretrained=True, num_classes=7, scale=1)
print(len(list(self._model.parameters())))
print(self._model.conv1.weight)
return
for param in self._model.parameters():
param.requires_grad = False
if torch.cuda.is_available() and GPU:
self._model = self._model.cuda()
else:
self._model = self._model.cpu()
if os.path.isfile(model_path):
checkpoint = torch.load(model_path, map_location=lambda storage, loc: storage)
d = collections.OrderedDict()
for key, value in checkpoint['state_dict'].items():
tmp = key[7:]
d[tmp] = value
self._model.load_state_dict(d)
else:
print("No checkpoint found at '{}'".format(model_path))
self._model.eval()
example = torch.rand(1, 3, 800, 800)
example = Variable(example.cuda())
#torch.onnx.export(self._model, example, "model.proto", verbose=True)
traced_script_module = torch.jit.trace(self._model, (example))
traced_script_module.save("./model.pt")
def detect(self, img):
startTime0 = time.time()
self.bboxes = []
data_loader = TestLoader(img, long_size=DETE_IMG_SIZE)
test_loader = torch.utils.data.DataLoader(
data_loader,
batch_size=1,
shuffle=False,
num_workers=2,
drop_last=True)
for idx, (scale, img) in enumerate(test_loader):
if torch.cuda.is_available() and GPU:
#img = Variable(img.cuda(), volatile=True)
img = Variable(img.cuda())
else:
#img = Variable(img.cpu(), volatile=True)
img = Variable(img.cpu())
#org_img = org_img.numpy().astype('uint8')[0]
#text_box = org_img.copy()
outputs = self._model(img)
score = torch.sigmoid(outputs[:, 0, :, :])
outputs = (torch.sign(outputs - DETE_BINARY_TH) + 1) / 2
text = outputs[:, 0, :, :]
kernels = outputs[:, 0:7, :, :] * text
score = score.data.cpu().numpy()[0].astype(np.float32)
text = text.data.cpu().numpy()[0].astype(np.uint8)
kernels = kernels.data.cpu().numpy()[0].astype(np.uint8)
cv2.imwrite("./7.jpg", kernels[0]*255)
#cv2.imwrite("./6.jpg", kernels[1]*255)
#cv2.imwrite("./5.jpg", kernels[2]*255)
#cv2.imwrite("./4.jpg", kernels[3]*255)
#cv2.imwrite("./3.jpg", kernels[4]*255)
#cv2.imwrite("./2.jpg", kernels[5]*255)
#cv2.imwrite("./1.jpg", kernels[6]*255)
if USE_TF:
mask_res, label_values = pse(kernels, 5.0)
mask_res = np.array(mask_res)
mask_res_resized = cv2.resize(mask_res, (mask_res.shape[1], mask_res.shape[0]), interpolation=cv2.INTER_NEAREST)
boxes = []
for label_value in label_values:
#(y,x)
points = np.argwhere(mask_res_resized==label_value)
points = points[:, (1,0)]
rect = cv2.minAreaRect(points)
box = cv2.boxPoints(rect) / (scale, scale)
box = box.astype('int32')
self.bboxes.append(box.reshape(-1))
return
# c++ version pse
pred = pse(kernels, 5.0)
# python version pse
# pred = pypse(kernels, 5.0)
if(len(pred) == 0):
continue
self.bboxes = pred
#print(self.bboxes, scale)
#self.bboxes = self.bboxes / scale
#self.bboxes = self.bboxes.astype('int32').tolist()
# label = pred
# label_num = np.max(label) + 1
# whereup = 0
# startTime = time.time()
# for i in range(1, label_num):
# startTime1 = time.time()
# points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1]
# whereup = whereup + time.time() - startTime1
# if points.shape[0] < DETE_MIN_AREA:
# continue
# score_i = np.mean(score[label == i])
# if score_i < DETE_MIN_SCORE:
# continue
# #if i == 2:
# #print(points)
# rect = cv2.minAreaRect(points)
# bbox = cv2.boxPoints(rect) / (scale/2, scale/2)
# bbox = bbox.astype('int32')
# self.bboxes.append(bbox.reshape(-1))
print("Later:", time.time() - startTime)
print("Total:", time.time() - startTime0)
#print(bboxes)
def draw_bbox(img, bboxes, output_path):
for bbox in bboxes:
cv2.drawContours(img, [bbox.reshape(4, 2)], -1, (0, 255, 0), 2)
cv2.imwrite(output_path, img)
if __name__ == '__main__':
output_Path = "./TestResult/"
if os.path.exists(output_Path):
shutil.rmtree(output_Path)
os.makedirs(output_Path)
model_path = "./checkpoints/checkpoint.pth.tar"
#model_path = "./model.pt"
dete_line = Detector(model_path)
imgList = glob.glob(os.path.join("./TestImgs/", "*.jpg"))
startTime = time.time()
for img_path in imgList:
print(img_path)
img = cv2.imread(img_path)
if torch.cuda.is_available() and GPU:
torch.cuda.synchronize()
start = time.time()
dete_line.detect(img)
fileSave = output_Path + os.path.split(img_path)[1]
draw_bbox(img, dete_line.bboxes, fileSave)
if torch.cuda.is_available() and GPU:
torch.cuda.synchronize()
end = time.time()
print("Time is {0}s".format(end - start))
print("Total is {0}s".format(time.time() - startTime))
|
[
"torch.cuda.synchronize",
"os.path.isfile",
"cv2.boxPoints",
"cv2.minAreaRect",
"shutil.rmtree",
"os.path.join",
"torch.utils.data.DataLoader",
"cv2.imwrite",
"torch.load",
"os.path.exists",
"torch.sign",
"cv2.resize",
"torch.jit.trace",
"fpn_resnet.resnet50",
"torch.cuda.is_available",
"torch.rand",
"numpy.argwhere",
"os.makedirs",
"dataLoader.TestLoader",
"time.time",
"cv2.imread",
"torch.sigmoid",
"numpy.array",
"pse.pse",
"collections.OrderedDict",
"os.path.split"
] |
[((5724, 5753), 'cv2.imwrite', 'cv2.imwrite', (['output_path', 'img'], {}), '(output_path, img)\n', (5735, 5753), False, 'import cv2\n'), ((5827, 5854), 'os.path.exists', 'os.path.exists', (['output_Path'], {}), '(output_Path)\n', (5841, 5854), False, 'import os\n'), ((5895, 5919), 'os.makedirs', 'os.makedirs', (['output_Path'], {}), '(output_Path)\n', (5906, 5919), False, 'import os\n'), ((6128, 6139), 'time.time', 'time.time', ([], {}), '()\n', (6137, 6139), False, 'import time\n'), ((698, 754), 'fpn_resnet.resnet50', 'models.resnet50', ([], {'pretrained': '(True)', 'num_classes': '(7)', 'scale': '(1)'}), '(pretrained=True, num_classes=7, scale=1)\n', (713, 754), True, 'import fpn_resnet as models\n'), ((1110, 1136), 'os.path.isfile', 'os.path.isfile', (['model_path'], {}), '(model_path)\n', (1124, 1136), False, 'import os\n'), ((1575, 1601), 'torch.rand', 'torch.rand', (['(1)', '(3)', '(800)', '(800)'], {}), '(1, 3, 800, 800)\n', (1585, 1601), False, 'import torch\n'), ((1754, 1791), 'torch.jit.trace', 'torch.jit.trace', (['self._model', 'example'], {}), '(self._model, example)\n', (1769, 1791), False, 'import torch\n'), ((1904, 1915), 'time.time', 'time.time', ([], {}), '()\n', (1913, 1915), False, 'import time\n'), ((1963, 2003), 'dataLoader.TestLoader', 'TestLoader', (['img'], {'long_size': 'DETE_IMG_SIZE'}), '(img, long_size=DETE_IMG_SIZE)\n', (1973, 2003), False, 'from dataLoader import TestLoader\n'), ((2026, 2130), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['data_loader'], {'batch_size': '(1)', 'shuffle': '(False)', 'num_workers': '(2)', 'drop_last': '(True)'}), '(data_loader, batch_size=1, shuffle=False,\n num_workers=2, drop_last=True)\n', (2053, 2130), False, 'import torch\n'), ((5864, 5890), 'shutil.rmtree', 'shutil.rmtree', (['output_Path'], {}), '(output_Path)\n', (5877, 5890), False, 'import shutil\n'), ((6074, 6110), 'os.path.join', 'os.path.join', (['"""./TestImgs/"""', '"""*.jpg"""'], {}), "('./TestImgs/', '*.jpg')\n", (6086, 6110), False, 'import os\n'), ((6207, 6227), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (6217, 6227), False, 'import cv2\n'), ((6340, 6351), 'time.time', 'time.time', ([], {}), '()\n', (6349, 6351), False, 'import time\n'), ((6596, 6607), 'time.time', 'time.time', ([], {}), '()\n', (6605, 6607), False, 'import time\n'), ((960, 985), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (983, 985), False, 'import torch\n'), ((1163, 1228), 'torch.load', 'torch.load', (['model_path'], {'map_location': '(lambda storage, loc: storage)'}), '(model_path, map_location=lambda storage, loc: storage)\n', (1173, 1228), False, 'import torch\n'), ((1245, 1270), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (1268, 1270), False, 'import collections\n'), ((2674, 2708), 'torch.sigmoid', 'torch.sigmoid', (['outputs[:, 0, :, :]'], {}), '(outputs[:, 0, :, :])\n', (2687, 2708), False, 'import torch\n'), ((3081, 3121), 'cv2.imwrite', 'cv2.imwrite', (['"""./7.jpg"""', '(kernels[0] * 255)'], {}), "('./7.jpg', kernels[0] * 255)\n", (3092, 3121), False, 'import cv2\n'), ((4219, 4236), 'pse.pse', 'pse', (['kernels', '(5.0)'], {}), '(kernels, 5.0)\n', (4222, 4236), False, 'from pse import pse\n'), ((6248, 6273), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6271, 6273), False, 'import torch\n'), ((6299, 6323), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (6321, 6323), False, 'import torch\n'), ((6506, 6531), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6529, 6531), False, 'import torch\n'), ((6557, 6581), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (6579, 6581), False, 'import torch\n'), ((2261, 2286), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2284, 2286), False, 'import torch\n'), ((3496, 3513), 'pse.pse', 'pse', (['kernels', '(5.0)'], {}), '(kernels, 5.0)\n', (3499, 3513), False, 'from pse import pse\n'), ((3541, 3559), 'numpy.array', 'np.array', (['mask_res'], {}), '(mask_res)\n', (3549, 3559), True, 'import numpy as np\n'), ((3595, 3693), 'cv2.resize', 'cv2.resize', (['mask_res', '(mask_res.shape[1], mask_res.shape[0])'], {'interpolation': 'cv2.INTER_NEAREST'}), '(mask_res, (mask_res.shape[1], mask_res.shape[0]), interpolation=\n cv2.INTER_NEAREST)\n', (3605, 3693), False, 'import cv2\n'), ((6416, 6439), 'os.path.split', 'os.path.split', (['img_path'], {}), '(img_path)\n', (6429, 6439), False, 'import os\n'), ((6691, 6702), 'time.time', 'time.time', ([], {}), '()\n', (6700, 6702), False, 'import time\n'), ((2732, 2768), 'torch.sign', 'torch.sign', (['(outputs - DETE_BINARY_TH)'], {}), '(outputs - DETE_BINARY_TH)\n', (2742, 2768), False, 'import torch\n'), ((3821, 3865), 'numpy.argwhere', 'np.argwhere', (['(mask_res_resized == label_value)'], {}), '(mask_res_resized == label_value)\n', (3832, 3865), True, 'import numpy as np\n'), ((3937, 3960), 'cv2.minAreaRect', 'cv2.minAreaRect', (['points'], {}), '(points)\n', (3952, 3960), False, 'import cv2\n'), ((5466, 5477), 'time.time', 'time.time', ([], {}), '()\n', (5475, 5477), False, 'import time\n'), ((5519, 5530), 'time.time', 'time.time', ([], {}), '()\n', (5528, 5530), False, 'import time\n'), ((3987, 4006), 'cv2.boxPoints', 'cv2.boxPoints', (['rect'], {}), '(rect)\n', (4000, 4006), False, 'import cv2\n')]
|
# ===================================================================================== #
# Module for solving Ising models exactly.
#
# Distributed with ConIII.
#
# NOTE: This code needs cleanup.
#
# Author : <NAME>, <EMAIL>
# ===================================================================================== #
#
# MIT License
#
# Copyright (c) 2019 <NAME>, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import numpy as np
import mpmath as mp
import scipy.special as ss
from itertools import combinations
import sys
np.set_printoptions(threshold=sys.maxsize)
def write_eqns(n, sym, corrTermsIx, suffix='', high_prec=False):
"""Create strings for writing out the equations and then write them to file.
TODO: This code needs some cleanup.
Parameters
----------
n : int
number of spins
sym : int
value of 1 will use {-1,1} formulation, 0 means {0,1}
corrTermsIx : list of ndarrays
Allows specification of arbitrary correlations to constrain using an index based
structure. These should be index arrays as would be returned by np.where that
specify which correlations to write down. Each consecutive array should specify
a matrix of sequentially increasing dimension.
[Nx1, NxN, NxNxN, ...]
suffix : str, ''
high_prec : bool, False
"""
import re
assert sym in [0,1], "sym argument must be 0 or 1."
abc = '<KEY>'
expterms = [] # 2**N exponential corrTermsIx
binstates = [] # all binary states as strings
signs = [] # coefficient for all numerator terms when computing correlations
br = "[]"
ix0 = 0
# default suffix for high precision files
if high_prec:
suffix += '_hp'
# Collect all corrTermsIx in the partition function.
for state in range(2**n):
binstates.append("{0:b}".format(state))
if len(binstates[state])<n:
binstates[state] = "0"*(n-len(binstates[state])) + binstates[state]
expterms.append( '' )
# Get corrTermsIx corresponding to each of the ith order term.
if sym:
for i in range(len(corrTermsIx)):
expterms[state] += get_terms11(corrTermsIx[i], abc[i], binstates[state], br, ix0)
else:
for i in range(len(corrTermsIx)):
expterms[state] += get_terms01(corrTermsIx[i], abc[i], binstates[state], br, ix0)
expterms[state] = re.sub(r'\+0\+','+', expterms[state])
expterms[state] = re.sub(r'\)\+0',')', expterms[state])
expterms[state] += ', '
# Collect all terms with corresponding prefix in the equation to solve.
for state in range(2**n):
for i in range(len(corrTermsIx)):
if state==0:
signs.append([])
# Get corrTermsIx corresponding to each of the ith order term.
if sym:
signs_ = _compute_signs(corrTermsIx[i], expterms[state], binstates[state])
else:
signs_ = _compute_signs(corrTermsIx[i], expterms[state], binstates[state], False)
# expand the length of signs if we haven't reached those constraints yet before
if len(signs[i])<signs_.size:
for j in range(signs_.size-len(signs[i])):
signs[i].append(np.zeros(0, dtype=int))
for j in range(signs_.size):
signs[i][j] = np.append(signs[i][j], signs_[j])
Z = ''.join(expterms)
# Account for fact that symmetric Python had inverted the order of the states.
if sym:
extra = '\n Pout = Pout[::-1]'
else:
extra = ''
# write to files
write_py(n, sym, corrTermsIx, signs, expterms, Z,
extra=extra,
suffix=suffix,
high_prec=high_prec)
def write_py(n, sym, contraintTermsIx, signs, expterms, Z,
extra='',
suffix='',
high_prec=False):
"""
Write out Ising equations for Python.
Parameters
----------
n : int
System size.
contraintTermsIx : list of str
signs : list of ndarray
Sign for each term in the numerator when computing correlations.
expterms : list of str
Every single energy term.
Z : str
Energies for all states that will be put into partition function.
extra : str, ''
any extra lines to add at the end
suffix : str, ''
high_prec : bool, False
If True, write version that uses mpmath for high precision calculations.
"""
import time
import os
abc = 'HJKLMNOPQRSTUVWXYZABCDE'
fname = 'ising_eqn/ising_eqn_%d%s.py'%(n,suffix)
print("Generating file ./%s"%fname)
if not os.path.isdir('./ising_eqn'):
os.makedirs('./ising_eqn')
f = open(fname,'w')
# insert license
try:
license = open('LICENSE.txt','r').readlines()
for el in license:
el = '# '+el
f.write(el)
f.write('\n')
except FileNotFoundError:
print("License file not found...")
f.write("# Equations for %d-spin Ising model.\n\n"%n)
f.write("# ")
f.write(time.strftime("Written on %Y/%m/%d.")+"\n")
if high_prec:
f.write("from numpy import zeros, array, prod\n")
f.write("from ..enumerate import mp_fast_logsumexp as fast_logsumexp\n")
f.write("from mpmath import exp, isnan\n\n")
else:
f.write("from numpy import zeros, exp, array, prod, isnan\n")
f.write("from ..enumerate import fast_logsumexp\n\n")
# Keep these as string because they need to grow in the loop and then can just be
# added all at once at the end.
fargs = "def calc_observables(params):\n"
if high_prec:
vardec = ' Cout = zeros(('+str(sum([len(i) for i in signs]))+'), dtype=object)\n' # string of variable declarations
else:
vardec = ' Cout = zeros(('+str(sum([len(i) for i in signs]))+'))\n' # string of variable declarations
eqns = '' # string of equations to compute
ix = np.hstack(( 0, np.cumsum([len(i) for i in signs]) ))
for i in range(len(contraintTermsIx)):
vardec += ' '+abc[i]+' = params['+str(ix[i])+':'+str(ix[i+1])+']\n'
if sym:
k = 0
for i in range(len(contraintTermsIx)):
for j in range(len(signs[i])):
eqns += (" num = fast_logsumexp(energyTerms, "+
str(signs[i][j]).replace('1 ','1,').replace('1\n','1,\n')+
")\n Cout["+str(k)+"] = exp( num[0] - logZ ) * num[1]\n")
k += 1
else:
k = 0
for i in range(len(contraintTermsIx)):
for j in range(len(signs[i])):
eqns += (" num = fast_logsumexp(energyTerms, "+
str(signs[i][j]).replace('0 ','0,').replace('1 ','1,').replace('0\n','0,\n').replace('1\n','1,\n')+
")\n Cout["+str(k)+"] = exp( num[0] - logZ ) * num[1]\n")
k += 1
# Write out correlation terms
f.write(fargs)
f.write((" \"\"\"\n Give all parameters concatenated into one array from lowest to highest order.\n"+
" Returns all correlations.\n \"\"\"\n"))
f.write(vardec)
_write_energy_terms(f, Z)
f.write(eqns)
if high_prec:
f.write(" for i in range(Cout.size):\n if isnan(Cout[i]):\n Cout[i] = 0.\n")
else:
f.write(" Cout[isnan(Cout)] = 0.\n")
f.write(" return(Cout)\n\n")
# Write equations for probabilities of all states.
#f.write("def p("+string.join([i+"," for i in abc[:len(contraintTermsIx)]])+"):\n")
f.write("def p(params):\n")
f.write((" \"\"\"\n Give all parameters concatenated into one array from lowest to highest order.\n"+
" Returns probabilities of all configurations.\n \"\"\"\n"))
f.write(vardec)
# Output variable decs and put params into explicit parameters.
ix = np.hstack(( 0, np.cumsum([len(i) for i in signs]) ))
vardec = ''
for i in range(len(contraintTermsIx)):
vardec += ' '+abc[i]+' = params['+str(ix[i])+':'+str(ix[i+1])+']\n'
if high_prec:
vardec += ' Pout = zeros(('+str(2**n)+'), dtype=object)\n' # string of variable declarations
else:
vardec += ' Pout = zeros(('+str(2**n)+'))\n' # string of variable declarations
f.write(vardec)
_write_energy_terms(f, Z)
# each probability equation
for i in range(len(expterms)):
f.write(' Pout['+str(i)+'] = exp( '+expterms[i][:-2]+' - logZ )\n')
f.write(extra)
f.write("\n return(Pout)\n")
f.close()
def _write_energy_terms(f, Z):
"""Split expression for energy terms for each term in Z into multiple lines and write
out nicely into file.
Parameters
----------
f : file
Z : list of str
Energy terms to write out.
"""
f.write(' energyTerms = array([')
i=0
while i<len(Z):
iend=i+100
# end line on a +
while iend<len(Z) and Z[iend-1]!='+':
iend+=1
if iend>=len(Z):
# ignore comma at end of line
f.write(' '+Z[i:-1]+'])\n logZ = fast_logsumexp(energyTerms)[0]\n')
else:
f.write(' '+Z[i:iend]+'\n')
i=iend
def _compute_signs(subix, expterm, binstate, sym=True):
"""Iterate through terms that belong in the numerator for each constraint and keep
track of the sign of those terms.
Parameters
----------
subix : list
expterm : list of str
binstate : list of str
sym : bool, True
Returns
-------
ndarray
Sign of each exponential term in numerator.
"""
if len(subix)==0:
return
if sym:
downSpin = -1
signs = np.ones(len(subix[0]), dtype=int)
for i in range(len(subix[0])):
if np.mod( sum([binstate[k[i]]=="1" for k in subix]),2 ):
signs[i] = downSpin
else:
downSpin = 0
signs = np.ones(len(subix[0]), dtype=int)
for i in range(len(subix[0])):
if np.mod( any([binstate[k[i]]=="0" for k in subix]),2 ):
signs[i] = downSpin
return signs
def get_terms11(subix, prefix, binstate, br, ix0):
"""
Specific to {-1,1}.
"""
j = 0
s = ''
if len(subix)==0:
return s
for i in range(len(subix[0])):
if np.mod( sum([binstate[k[j]]=="1" for k in subix]),2 ):
s += '-'
else:
s += '+'
s += prefix+br[0]+str(j+ix0)+br[1]
j += 1
return s
def get_terms01(subix, prefix, binstate, br, ix0):
"""
Specific to {0,1}.
"""
j = 0
s = ''
if len(subix)==0:
return s
for i in range(len(subix[0])):
if np.all( [binstate[k[j]]=="1" for k in subix] ):
s += '+'+prefix+br[0]+str(j+ix0)+br[1]
j += 1
if s=='':
s = '+0'
return s
def get_terms(subix, prefix, binstate, br, ix0):
"""
Spins are put in explicitly
"""
j = 0
s = ''
if len(subix)==0:
return s
for i in range(len(subix[0])):
s += '+'+prefix+br[0]+str(j+ix0)+br[1]
for k in range(len(subix)):
s += '*s'+br[0]+str(subix[k][i])+br[1]
j += 1
if s=='':
s = '+0'
return s
def get_3idx(n):
"""Get binary 3D matrix with truth values where index values correspond to the index
of all possible ijk parameters. We can do this by recognizing that the pattern along
each plane in the third dimension is like the upper triangle pattern that just moves
up and over by one block each cut lower into the box.
"""
b = np.zeros((n,n,n))
c = np.triu(np.ones((n-1,n-1))==1,1)
for i in range(n-1):
# shunt this diagonal matrix over every descent into a lower plane in the box
# the plane xz
if i==0:
b[i,(1+i):,(1+i):] = c
else:
b[i,(1+i):,(1+i):] = c[:-i,:-i]
return b
def get_nidx(k, n):
"""
Get the kth order indices corresponding to all the states in which k elements
are firing up out of n spins. The ordering correspond to that returned by
bin_states().
One can check this code for correctness by comparing with get_3idx()
>>>>>
print where(exact.get_3idx(4))
print where(exact.get_nidx(3,4))
<<<<<
"""
if k==n:
return np.reshape(list(range(n)),(n,1))
elif k<n:
allStates = bin_states(n)
statesix = np.sum(allStates,1)==k
ix = []
for s in allStates[statesix,:]:
j = 0
for i in np.argwhere(s==1).flatten():
if len(ix)<(j+1):
ix.append([])
ix[j].append(i)
j += 1
return np.array(ix)[:,::-1] # make sure last idx increases first
def pairwise(n, sym=0, **kwargs):
"""Wrapper for writing pairwise maxent model (Ising) files.
Parameters
----------
n : int
System size.
sym : int, 0
Can be 0 or 1.
**kwargs
Returns
-------
None
"""
assert sym==0 or sym==1
print("Writing equations for pairwise Ising model with %d spins."%n)
if sym:
write_eqns(n, sym, [np.where(np.ones((n))==1),
np.where(np.triu(np.ones((n,n)),k=1)==1)],
suffix='_sym',
**kwargs)
else:
write_eqns(n, sym, [np.where(np.ones((n))==1),
np.where(np.triu(np.ones((n,n)),k=1)==1)],
**kwargs)
def triplet(n, sym=0, **kwargs):
"""Wrapper for writing triplet-order maxent model.
Parameters
----------
n : int
System size.
sym : int, 0
Can be 0 or 1.
**kwargs
Returns
-------
None
"""
assert sym==0 or sym==1
print("Writing equations for Ising model with triplet interactions and %d spins."%n)
if sym:
write_eqns(n,sym,[(range(n),),
list(zip(*list(combinations(range(n),2)))),
list(zip(*list(combinations(range(n),3))))],
suffix='_sym_triplet',
**kwargs)
else:
write_eqns(n,sym,[(range(n),),
list(zip(*list(combinations(range(n),2)))),
list(zip(*list(combinations(range(n),3))))],
suffix='_triplet',
**kwargs)
def _write_matlab(n, terms, fitterms, expterms, Z, suffix=''):
"""
DEPRECATED: code here for future referencing
Write out equations to solve for matlab.
"""
import time
abc = 'HJKLMNOPQRSTUVWXYZABCDE'
vardec = ''
# Write function to solve to file.
f = open('ising_eqn_%d%s.m'%(n,suffix),'w')
f.write("% Equations of %d-spin Ising model.\n\n"%n)
f.write(time.strftime("%Y/%m/%d")+"\n")
f.write("% Give each set of parameters concatenated into one array.\n\n")
# Keep these as string because they need to grow in the loop and then can just be
# added all at once at the end.
f.write("function Cout = calc_observables(params)\n")
f.write('\tCout = zeros('+str(sum([len(i) for i in fitterms]))+',1);\n') # string of variable declarations
eqns = '' # string of equations to compute
ix = np.hstack(( 0,np.cumsum([len(i) for i in fitterms]) ))+1
for i in range(len(terms)):
vardec += '\t'+abc[i]+' = params('+str(ix[i])+':'+str(ix[i+1]-1)+');\n'
k = 0
for i in range(len(terms)):
for j in range(len(fitterms[i])):
eqns += "\tCout("+str(k+1)+") = ("+fitterms[i][j]+")/Z;\n"
k += 1
f.write(vardec)
f.write("\tZ = "+Z+";\n")
f.write(eqns)
f.close()
g = open('probs'+str(n)+'.m','w')
g.write("% File for getting the probabilities of Ising model.\n% ")
g.write(time.strftime("%Y/%m/%d")+"\n")
# Write equations for probabilities of all states.
g.write("function Pout = p(params)\n")
g.write(vardec)
g.write(' Pout = zeros('+str(2**n)+',1);\n') # string of variable declarations
g.write(' Z = '+Z+';\n')
for i in range(len(expterms)):
g.write(' Pout('+str(i+1)+') = '+expterms[i]+'/Z;\n')
g.close()
def fast_logsumexp(X, coeffs=None):
"""Simplified version of logsumexp to do correlation calculation in Ising equation
files. Scipy's logsumexp can be around 10x slower in comparison.
Parameters
----------
X : ndarray
Terms inside logs.
coeffs : ndarray
Factors in front of exponentials.
Returns
-------
float
Value of magnitude of quantity inside log (the sum of exponentials).
float
Sign.
"""
Xmx = max(X)
if coeffs is None:
y = np.exp(X-Xmx).sum()
else:
y = np.exp(X-Xmx).dot(coeffs)
if y<0:
return np.log(np.abs(y))+Xmx, -1.
return np.log(y)+Xmx, 1.
def mp_fast_logsumexp(X, coeffs=None):
"""fast_logsumexp for high precision numbers using mpmath.
Parameters
----------
X : ndarray
Terms inside logs.
coeffs : ndarray
Factors in front of exponentials.
Returns
-------
float
Value of magnitude of quantity inside log (the sum of exponentials).
float
Sign.
"""
Xmx = max(X)
if coeffs is None:
y = sum(map(mp.exp, X-Xmx))
else:
y = np.array(coeffs).dot(list(map(mp.exp, X-Xmx)))
if y<0:
return mp.log(abs(y))+Xmx, -1.
return mp.log(y)+Xmx, 1.
if __name__=='__main__':
"""When run with Python, this will write the equations for the Ising model
into file ising_eqn_[n][_sym] where n will be replaced by the system size
and the suffix '_sym' is included if the equations are written in the
{-1,+1} basis.
To write the Ising model equations for a system of size 3 in the {0,1} basis, call
>>> python enumerate.py 3
For the {-1,1} basis, call
>>> python enumerate.py 3 1
To include triplet order interactions, include a 3 at the very end
>>> python enumerate.py 3 0 3
To write high precision, include an '-hp=true' as the last argument.
>>> python enumerate.py 3 0 3 -hp=true
"""
import sys
args = [i for i in sys.argv if '-'!=i[0]]
kwargs = [i for i in sys.argv if '-'==i[0]]
n = int(args[1])
if len(args)==2:
sym = 0
order = 2
elif len(args)==3:
sym = int(args[2])
assert sym==0 or sym==1
order = 2
elif len(args)==4:
sym = int(args[2])
order = int(args[3])
else:
raise Exception("Unrecognized arguments.")
# parse kwargs
if len(kwargs):
if '-hp='==kwargs[0][:4]:
if kwargs[0][4:].lower()=='true':
high_prec = True
elif kwargs[0][4:].lower()=='false':
high_prec = False
else:
raise Exception("Unrecognized value for hp.")
else:
high_prec = False
else:
# default kwargs
high_prec = False
if order==2:
pairwise(n, sym, high_prec=high_prec)
elif order==3:
triplet(n, sym, high_prec=high_prec)
else:
raise NotImplementedError("Only order up to 3 implemented for this convenient interface.")
|
[
"numpy.set_printoptions",
"numpy.sum",
"os.makedirs",
"numpy.log",
"numpy.abs",
"os.path.isdir",
"mpmath.log",
"numpy.zeros",
"time.strftime",
"numpy.ones",
"numpy.append",
"numpy.array",
"numpy.exp",
"numpy.argwhere",
"re.sub",
"numpy.all"
] |
[((1545, 1587), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'sys.maxsize'}), '(threshold=sys.maxsize)\n', (1564, 1587), True, 'import numpy as np\n'), ((12751, 12770), 'numpy.zeros', 'np.zeros', (['(n, n, n)'], {}), '((n, n, n))\n', (12759, 12770), True, 'import numpy as np\n'), ((3451, 3490), 're.sub', 're.sub', (['"""\\\\+0\\\\+"""', '"""+"""', 'expterms[state]'], {}), "('\\\\+0\\\\+', '+', expterms[state])\n", (3457, 3490), False, 'import re\n'), ((3515, 3554), 're.sub', 're.sub', (['"""\\\\)\\\\+0"""', '""")"""', 'expterms[state]'], {}), "('\\\\)\\\\+0', ')', expterms[state])\n", (3521, 3554), False, 'import re\n'), ((5717, 5745), 'os.path.isdir', 'os.path.isdir', (['"""./ising_eqn"""'], {}), "('./ising_eqn')\n", (5730, 5745), False, 'import os\n'), ((5755, 5781), 'os.makedirs', 'os.makedirs', (['"""./ising_eqn"""'], {}), "('./ising_eqn')\n", (5766, 5781), False, 'import os\n'), ((11838, 11886), 'numpy.all', 'np.all', (["[(binstate[k[j]] == '1') for k in subix]"], {}), "([(binstate[k[j]] == '1') for k in subix])\n", (11844, 11886), True, 'import numpy as np\n'), ((6150, 6187), 'time.strftime', 'time.strftime', (['"""Written on %Y/%m/%d."""'], {}), "('Written on %Y/%m/%d.')\n", (6163, 6187), False, 'import time\n'), ((12785, 12808), 'numpy.ones', 'np.ones', (['(n - 1, n - 1)'], {}), '((n - 1, n - 1))\n', (12792, 12808), True, 'import numpy as np\n'), ((15954, 15979), 'time.strftime', 'time.strftime', (['"""%Y/%m/%d"""'], {}), "('%Y/%m/%d')\n", (15967, 15979), False, 'import time\n'), ((16962, 16987), 'time.strftime', 'time.strftime', (['"""%Y/%m/%d"""'], {}), "('%Y/%m/%d')\n", (16975, 16987), False, 'import time\n'), ((18012, 18021), 'numpy.log', 'np.log', (['y'], {}), '(y)\n', (18018, 18021), True, 'import numpy as np\n'), ((18628, 18637), 'mpmath.log', 'mp.log', (['y'], {}), '(y)\n', (18634, 18637), True, 'import mpmath as mp\n'), ((4419, 4452), 'numpy.append', 'np.append', (['signs[i][j]', 'signs_[j]'], {}), '(signs[i][j], signs_[j])\n', (4428, 4452), True, 'import numpy as np\n'), ((13581, 13601), 'numpy.sum', 'np.sum', (['allStates', '(1)'], {}), '(allStates, 1)\n', (13587, 13601), True, 'import numpy as np\n'), ((13866, 13878), 'numpy.array', 'np.array', (['ix'], {}), '(ix)\n', (13874, 13878), True, 'import numpy as np\n'), ((17878, 17893), 'numpy.exp', 'np.exp', (['(X - Xmx)'], {}), '(X - Xmx)\n', (17884, 17893), True, 'import numpy as np\n'), ((17920, 17935), 'numpy.exp', 'np.exp', (['(X - Xmx)'], {}), '(X - Xmx)\n', (17926, 17935), True, 'import numpy as np\n'), ((18518, 18534), 'numpy.array', 'np.array', (['coeffs'], {}), '(coeffs)\n', (18526, 18534), True, 'import numpy as np\n'), ((17981, 17990), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (17987, 17990), True, 'import numpy as np\n'), ((4324, 4346), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': 'int'}), '(0, dtype=int)\n', (4332, 4346), True, 'import numpy as np\n'), ((13699, 13718), 'numpy.argwhere', 'np.argwhere', (['(s == 1)'], {}), '(s == 1)\n', (13710, 13718), True, 'import numpy as np\n'), ((14342, 14352), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (14349, 14352), True, 'import numpy as np\n'), ((14541, 14551), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (14548, 14551), True, 'import numpy as np\n'), ((14405, 14420), 'numpy.ones', 'np.ones', (['(n, n)'], {}), '((n, n))\n', (14412, 14420), True, 'import numpy as np\n'), ((14604, 14619), 'numpy.ones', 'np.ones', (['(n, n)'], {}), '((n, n))\n', (14611, 14619), 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.