code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
"""Testing visualization.interpolation."""
import numpy as np
import plonk
from .stubdata.interpolation_arrays import (
scalar_cross_section,
scalar_projection,
vector_cross_section,
vector_projection,
)
N = 10
XX = np.ones(N)
YY = np.ones(N)
ZZ = np.ones(N)
HH = np.ones(N)
WW = np.ones(N)
MM = np.ones(N)
S_DATA = np.ones(N)
X_DATA = np.ones(N)
Y_DATA = np.ones(N)
EXTENT = (0, 1, 0, 1)
PIX = (10, 10)
ZSLICE = 0.5
def test_scalar_interpolation_projection():
"""Test projection interpolation."""
im = plonk.visualize.interpolation.scalar_interpolation(
data=S_DATA,
x_position=XX,
y_position=YY,
z_position=ZZ,
extent=EXTENT,
smoothing_length=HH,
particle_mass=MM,
number_of_pixels=PIX,
)
np.testing.assert_allclose(im, scalar_projection, rtol=1e-5)
def test_scalar_interpolation_cross_section():
"""Test cross section interpolation."""
im = plonk.visualize.interpolation.scalar_interpolation(
data=S_DATA,
x_position=XX,
y_position=YY,
z_position=ZZ,
extent=EXTENT,
smoothing_length=HH,
particle_mass=MM,
number_of_pixels=PIX,
cross_section=ZSLICE,
)
np.testing.assert_allclose(im, scalar_cross_section, rtol=1e-5)
def test_vector_interpolation_projection():
"""Test projection interpolation."""
vec = plonk.visualize.interpolation.vector_interpolation(
x_data=X_DATA,
y_data=Y_DATA,
x_position=XX,
y_position=YY,
z_position=ZZ,
extent=EXTENT,
smoothing_length=HH,
particle_mass=MM,
number_of_pixels=PIX,
)
np.testing.assert_allclose(vec, vector_projection, rtol=1e-5)
def test_vector_interpolation_cross_section():
"""Test cross section interpolation."""
vec = plonk.visualize.interpolation.vector_interpolation(
x_data=X_DATA,
y_data=Y_DATA,
x_position=XX,
y_position=YY,
z_position=ZZ,
extent=EXTENT,
smoothing_length=HH,
particle_mass=MM,
number_of_pixels=PIX,
cross_section=ZSLICE,
)
np.testing.assert_allclose(vec, vector_cross_section, rtol=1e-5)
| [
"numpy.testing.assert_allclose",
"plonk.visualize.interpolation.vector_interpolation",
"numpy.ones",
"plonk.visualize.interpolation.scalar_interpolation"
] | [((237, 247), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (244, 247), True, 'import numpy as np\n'), ((253, 263), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (260, 263), True, 'import numpy as np\n'), ((269, 279), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (276, 279), True, 'import numpy as np\n'), ((285, 295), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (292, 295), True, 'import numpy as np\n'), ((301, 311), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (308, 311), True, 'import numpy as np\n'), ((317, 327), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (324, 327), True, 'import numpy as np\n'), ((338, 348), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (345, 348), True, 'import numpy as np\n'), ((358, 368), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (365, 368), True, 'import numpy as np\n'), ((378, 388), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (385, 388), True, 'import numpy as np\n'), ((536, 729), 'plonk.visualize.interpolation.scalar_interpolation', 'plonk.visualize.interpolation.scalar_interpolation', ([], {'data': 'S_DATA', 'x_position': 'XX', 'y_position': 'YY', 'z_position': 'ZZ', 'extent': 'EXTENT', 'smoothing_length': 'HH', 'particle_mass': 'MM', 'number_of_pixels': 'PIX'}), '(data=S_DATA, x_position=\n XX, y_position=YY, z_position=ZZ, extent=EXTENT, smoothing_length=HH,\n particle_mass=MM, number_of_pixels=PIX)\n', (586, 729), False, 'import plonk\n'), ((797, 858), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['im', 'scalar_projection'], {'rtol': '(1e-05)'}), '(im, scalar_projection, rtol=1e-05)\n', (823, 858), True, 'import numpy as np\n'), ((960, 1175), 'plonk.visualize.interpolation.scalar_interpolation', 'plonk.visualize.interpolation.scalar_interpolation', ([], {'data': 'S_DATA', 'x_position': 'XX', 'y_position': 'YY', 'z_position': 'ZZ', 'extent': 'EXTENT', 'smoothing_length': 'HH', 'particle_mass': 'MM', 'number_of_pixels': 'PIX', 'cross_section': 'ZSLICE'}), '(data=S_DATA, x_position=\n XX, y_position=YY, z_position=ZZ, extent=EXTENT, smoothing_length=HH,\n particle_mass=MM, number_of_pixels=PIX, cross_section=ZSLICE)\n', (1010, 1175), False, 'import plonk\n'), ((1251, 1315), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['im', 'scalar_cross_section'], {'rtol': '(1e-05)'}), '(im, scalar_cross_section, rtol=1e-05)\n', (1277, 1315), True, 'import numpy as np\n'), ((1412, 1622), 'plonk.visualize.interpolation.vector_interpolation', 'plonk.visualize.interpolation.vector_interpolation', ([], {'x_data': 'X_DATA', 'y_data': 'Y_DATA', 'x_position': 'XX', 'y_position': 'YY', 'z_position': 'ZZ', 'extent': 'EXTENT', 'smoothing_length': 'HH', 'particle_mass': 'MM', 'number_of_pixels': 'PIX'}), '(x_data=X_DATA, y_data=\n Y_DATA, x_position=XX, y_position=YY, z_position=ZZ, extent=EXTENT,\n smoothing_length=HH, particle_mass=MM, number_of_pixels=PIX)\n', (1462, 1622), False, 'import plonk\n'), ((1698, 1760), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['vec', 'vector_projection'], {'rtol': '(1e-05)'}), '(vec, vector_projection, rtol=1e-05)\n', (1724, 1760), True, 'import numpy as np\n'), ((1863, 2099), 'plonk.visualize.interpolation.vector_interpolation', 'plonk.visualize.interpolation.vector_interpolation', ([], {'x_data': 'X_DATA', 'y_data': 'Y_DATA', 'x_position': 'XX', 'y_position': 'YY', 'z_position': 'ZZ', 'extent': 'EXTENT', 'smoothing_length': 'HH', 'particle_mass': 'MM', 'number_of_pixels': 'PIX', 'cross_section': 'ZSLICE'}), '(x_data=X_DATA, y_data=\n Y_DATA, x_position=XX, y_position=YY, z_position=ZZ, extent=EXTENT,\n smoothing_length=HH, particle_mass=MM, number_of_pixels=PIX,\n cross_section=ZSLICE)\n', (1913, 2099), False, 'import plonk\n'), ((2179, 2244), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['vec', 'vector_cross_section'], {'rtol': '(1e-05)'}), '(vec, vector_cross_section, rtol=1e-05)\n', (2205, 2244), True, 'import numpy as np\n')] |
import os.path
import numpy
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.normalization import local_response_normalization
from tflearn.layers.estimator import regression
import tensorflow as tf
import errno
'''
Here I write how I had to assemble 2 models with the same shape in tflearn
I had to repeat the same code with different variable names so that tensorflow didn't have any errors
'''
'''
Alexnet:
References:
- <NAME>, <NAME> & <NAME>. ImageNet
Classification with Deep Convolutional Neural Networks. NIPS, 2012.
- 17 Category Flower Dataset. <NAME> and <NAME>.
Links:
- [AlexNet Paper](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)
- [Flower Dataset (17)](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/)
Tflearn code referenced from
https://github.com/tflearn/tflearn/blob/master/examples/images/alexnet.py
'''
def getProjectFolder():
ProjectFolder = os.path.join(os.path.expanduser('~'),'my_project')
return ProjectFolder
def MakeLogFile(filename):
halfpath=os.path.join(getProjectFolder(), 'logs')
fullpath = os.path.join(halfpath, filename)
return fullpath
def MakeModelPath(filename):
halfpath=os.path.join(getProjectFolder(), 'models')
fullpath = os.path.join(halfpath, filename)
return fullpath
def getDataPath(mode = 'grayscale_resize_1to10', which = 'first'):
if which == 'first' or which == 'second':
data_path = os.path.join(getProjectFolder(),'Videos', 'numpy', '{}_{}class_vector.npy'.format(mode, which))
else:
raise ValueError('Invalid which = {}'.format(which))
return data_path
# get X, Y, test_x, test_y ready
def ReadyData(data, test_size = 1000, do_shuffle=True):
if do_shuffle:
numpy.random.shuffle(data)
train_data = data[:-test_size]
test_data = data[-test_size:]
X,Y = zip(*train_data)
test_x, test_y = zip(*test_data)
X = numpy.array(list(X))
Y = numpy.array(list(Y))
test_x = numpy.array(list(test_x))
test_y = numpy.array(list(test_y))
return X,Y,test_x,test_y
# Load X, Y, test_x, test_y
def LoadData(mode = 'grayscale_resize_1to10', which='first', split_test=True, test_size=1000, do_shuffle=True):
print("Loading numpy array from file")
# ## Load after first time
input_path = getDataPath(mode= mode, which=which)
if os.path.exists(input_path):
data = numpy.load(input_path)
print("Done")
if split_test:
X,Y,test_x,test_y = ReadyData(data, test_size=test_size, do_shuffle=do_shuffle)
return X,Y,test_x,test_y
else:
return data
else:
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path)
### To check the tensorboard log
def print_log_instructions():
print("To be able to see Tensorboard in your local machine after training on a server")
print(" 1. exit current server session")
print(" 2. connect again with the following command:")
print(" ssh -L 16006:127.0.0.1:6006 -p [port] [user]@[server]")
print(" 3. execute in terminal")
print(" tensorboard --logdir='{}'".format(MakeLogFile('')))
print(" 4. on local machine, open browser on:")
print(" http://127.0.0.1:16006")
#### Model defining
## I have to set the network with different variable names or tensorflow has errors
def Convolutional_Model_Alexnet_first(img_height,img_width,color_channels, n_classes, run_id='', first_graph=tf.Graph()):
# data size
pixels = img_height*img_width
batch_size = 64
# pool window sizes
pool_1_window_size = 3
pool_2_window_size = 3
pool_3_window_size = 3
# conv window sizes
conv_1_window_size = 11
conv_2_window_size = 5
conv_3_1_window_size = 3
conv_3_2_window_size = 3
conv_3_3_window_size = 3
# pool stride sizes
pool_1_strides = 2
pool_2_strides = 2
pool_3_strides = 2
# conv stride sizes
conv_1_strides = 4
conv_2_strides = None #Default
conv_3_1_strides = None #Default
conv_3_2_strides = None #Default
conv_3_3_strides = None #Default
# compressed data size
compressed_img_height = img_height/pool_1_window_size/pool_2_window_size
compressed_img_width = img_width/pool_1_window_size/pool_2_window_size
# nodes
n_nodes_conv_layer_1 = 96
n_nodes_conv_layer_2 = 256
n_nodes_conv_layer_3_1 = 384
n_nodes_conv_layer_3_2 = 384
n_nodes_conv_layer_3_3 = 256
n_nodes_fc_layer_4 = 4096
n_nodes_fc_layer_5 = 4096
# input changes for fully connected
n_inputs_fc_layer_3 = compressed_img_width*compressed_img_height*n_nodes_conv_layer_2
#
with first_graph.as_default():
# Input Layer
first_convnet = input_data(shape=[None,img_width,img_height,color_channels], name='{}_input'.format(run_id)) # name should be different between models
# Convolution - Pool Layer 1
first_convnet = conv_2d(first_convnet, n_nodes_conv_layer_1, conv_1_window_size, strides=conv_1_strides, activation='relu')
first_convnet = max_pool_2d(first_convnet, pool_1_window_size, strides=pool_1_strides)
first_convnet = local_response_normalization(first_convnet)
# Convolution - Pool Layer 2
first_convnet = conv_2d(first_convnet, n_nodes_conv_layer_2, conv_2_window_size, activation='relu')
first_convnet = max_pool_2d(first_convnet, pool_2_window_size, strides=pool_2_strides)
first_convnet = local_response_normalization(first_convnet)
# 3 Convolutions 1 Pool Layer 3
first_convnet = conv_2d(first_convnet, n_nodes_conv_layer_3_1, conv_3_1_window_size, activation='relu')
first_convnet = conv_2d(first_convnet, n_nodes_conv_layer_3_2, conv_3_2_window_size, activation='relu')
first_convnet = conv_2d(first_convnet, n_nodes_conv_layer_3_3, conv_3_3_window_size, activation='relu')
first_convnet = max_pool_2d(first_convnet, pool_3_window_size, strides=pool_3_strides)
first_convnet = local_response_normalization(first_convnet)
# Fully connected layer 4
first_convnet = fully_connected(first_convnet, n_nodes_fc_layer_4, activation='tanh')
first_convnet = dropout(first_convnet, 0.5) # 50% keep rate
# Fully connected layer 4
first_convnet = fully_connected(first_convnet, n_nodes_fc_layer_5, activation='tanh')
first_convnet = dropout(first_convnet, 0.5) # 50% keep rate
###
# Output layer
first_convnet = fully_connected(first_convnet, n_classes, activation='softmax')
first_convnet = regression(
first_convnet,
optimizer='momentum',
learning_rate=0.001,
loss='categorical_crossentropy',
name='{}_targets'.format(run_id) # name should be different between models
)
# Set the model to follow this network
# tensorboard_verbose = 0: Loss, Accuracy (Best Speed)
tensorboard_log = MakeLogFile('')
first_model = tflearn.DNN(first_convnet, tensorboard_dir=tensorboard_log)
return first_model, first_graph
#### Model defining
## I have to set the network with different variable names or tensorflow has errors
def Convolutional_Model_Alexnet_second(img_height,img_width,color_channels, n_classes, run_id='', second_graph=tf.Graph()):
# data size
pixels = img_height*img_width
batch_size = 64
# pool window sizes
pool_1_window_size = 3
pool_2_window_size = 3
pool_3_window_size = 3
# conv window sizes
conv_1_window_size = 11
conv_2_window_size = 5
conv_3_1_window_size = 3
conv_3_2_window_size = 3
conv_3_3_window_size = 3
# pool stride sizes
pool_1_strides = 2
pool_2_strides = 2
pool_3_strides = 2
# conv stride sizes
conv_1_strides = 4
conv_2_strides = None #Default
conv_3_1_strides = None #Default
conv_3_2_strides = None #Default
conv_3_3_strides = None #Default
# compressed data size
compressed_img_height = img_height/pool_1_window_size/pool_2_window_size
compressed_img_width = img_width/pool_1_window_size/pool_2_window_size
# nodes
n_nodes_conv_layer_1 = 96
n_nodes_conv_layer_2 = 256
n_nodes_conv_layer_3_1 = 384
n_nodes_conv_layer_3_2 = 384
n_nodes_conv_layer_3_3 = 256
n_nodes_fc_layer_4 = 4096
n_nodes_fc_layer_5 = 4096
# input changes for fully connected
n_inputs_fc_layer_3 = compressed_img_width*compressed_img_height*n_nodes_conv_layer_2
#
with second_graph.as_default():
# Input Layer
second_convnet = input_data(shape=[None,img_width,img_height,color_channels], name='{}_input'.format(run_id)) # name should be different between models
# Convolution - Pool Layer 1
second_convnet = conv_2d(second_convnet, n_nodes_conv_layer_1, conv_1_window_size, strides=conv_1_strides, activation='relu')
second_convnet = max_pool_2d(second_convnet, pool_1_window_size, strides=pool_1_strides)
second_convnet = local_response_normalization(second_convnet)
# Convolution - Pool Layer 2
second_convnet = conv_2d(second_convnet, n_nodes_conv_layer_2, conv_2_window_size, activation='relu')
second_convnet = max_pool_2d(second_convnet, pool_2_window_size, strides=pool_2_strides)
second_convnet = local_response_normalization(second_convnet)
# 3 Convolutions 1 Pool Layer 3
second_convnet = conv_2d(second_convnet, n_nodes_conv_layer_3_1, conv_3_1_window_size, activation='relu')
second_convnet = conv_2d(second_convnet, n_nodes_conv_layer_3_2, conv_3_2_window_size, activation='relu')
second_convnet = conv_2d(second_convnet, n_nodes_conv_layer_3_3, conv_3_3_window_size, activation='relu')
second_convnet = max_pool_2d(second_convnet, pool_3_window_size, strides=pool_3_strides)
second_convnet = local_response_normalization(second_convnet)
# Fully connected layer 4
second_convnet = fully_connected(second_convnet, n_nodes_fc_layer_4, activation='tanh')
second_convnet = dropout(second_convnet, 0.5) # 50% keep rate
# Fully connected layer 4
second_convnet = fully_connected(second_convnet, n_nodes_fc_layer_5, activation='tanh')
second_convnet = dropout(second_convnet, 0.5) # 50% keep rate
###
# Output layer
second_convnet = fully_connected(second_convnet, n_classes, activation='softmax')
second_convnet = regression(
second_convnet,
optimizer='momentum',
learning_rate=0.001,
loss='categorical_crossentropy',
name='{}_targets'.format(run_id) # name should be different between models
)
# Set the model to follow this network
# tensorboard_verbose = 0: Loss, Accuracy (Best Speed)
tensorboard_log = MakeLogFile('')
second_model = tflearn.DNN(second_convnet, tensorboard_dir=tensorboard_log)
return second_model, second_graph
def Train(mode = 'grayscale_resize_1to10', which = 'first', first_graph=tf.Graph(), second_graph=tf.Graph()):
# Train any amount of 10x epochs so it gets to at least 15 mins error #
## Data reorganize
X,Y,test_x,test_y = LoadData(mode = mode, which=which)
# X and test_x have the shape (sample_size, img_height, img_width, color_channels) from OpenCV.
# Mine is Grayscale, so the shape is actually (sample_size, img_height, img_width)
# Y and test_y are OneHot encoded so have the shape (sample_size, n_classes)
img_height = len(X[0])
img_width = len(X[0][0])
if type(X[0][0][0])==type(numpy.array([])):
color_channels = len(X[0][0][0])
else:
color_channels = 1
# tensorflow needs the input to be width first and height second, backwards from what OpenCV outputs
X = numpy.transpose(X, [0,2,1])
test_x = numpy.transpose(test_x, [0,2,1])
X = X.reshape([-1,img_width,img_height,color_channels])
test_x = test_x.reshape([-1,img_width,img_height,color_channels])
n_classes = len(Y[0])
##
version = 1
times_run = 1
times_10x = 1
batch_size = None
model_name = 'Your_model_name_{}_{}class__v{}'.format(mode, which, version)
run_id = '{}_run{}'.format(model_name,times_run)
while os.path.exists(os.path.join(MakeLogFile(''), run_id)):
times_run += 1
run_id = '{}_run{}'.format(model_name,times_run)
model_path = os.path.abspath(MakeModelPath('',server=True)+'/{0}/{0}.tfl'.format(run_id))
model_dir = os.path.abspath(MakeModelPath('',server=True)+'/{0}'.format(run_id))
if which == 'first':
first_model, first_graph = Convolutional_Model_Alexnet_first(img_height,img_width,color_channels,n_classes=n_classes,run_id=run_id, first_graph=first_graph)
with first_graph.as_default():
first_model.fit(
{'{}_input'.format(run_id): X},
{'{}_targets'.format(run_id): Y},
n_epoch=5,
validation_set=({'{}_input'.format(run_id):test_x},{'{}_targets'.format(run_id):test_y}),
show_metric=True,
batch_size=batch_size,
shuffle=False,
snapshot_step=None,
run_id=run_id
)
first_model.save(model_path)
elif which == 'second':
second_model, second_graph = Convolutional_Model_Alexnet_second(img_height,img_width,color_channels,n_classes=n_classes,run_id=run_id, second_graph=second_graph)
with second_graph.as_default():
second_model.fit(
{'{}_input'.format(run_id): X},
{'{}_targets'.format(run_id): Y},
n_epoch=5,
validation_set=({'{}_input'.format(run_id):test_x},{'{}_targets'.format(run_id):test_y}),
show_metric=True,
batch_size=batch_size,
shuffle=False,
snapshot_step=None,
run_id=run_id
)
second_model.save(model_path)
print_log_instructions()
def main():
mode = 'grayscale_resize_1to10'
first_graph = tf.Graph()
second_graph = tf.Graph()
Train(which='first', first_graph=first_graph)
Train(which='second', second_graph=second_graph)
if __name__ == '__main__':
main()
| [
"tflearn.layers.conv.conv_2d",
"numpy.load",
"tflearn.layers.core.fully_connected",
"numpy.transpose",
"tflearn.layers.conv.max_pool_2d",
"tflearn.layers.core.dropout",
"tflearn.layers.normalization.local_response_normalization",
"tflearn.DNN",
"numpy.array",
"tensorflow.Graph",
"numpy.random.sh... | [((3623, 3633), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (3631, 3633), True, 'import tensorflow as tf\n'), ((7489, 7499), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (7497, 7499), True, 'import tensorflow as tf\n'), ((11252, 11262), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (11260, 11262), True, 'import tensorflow as tf\n'), ((11277, 11287), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (11285, 11287), True, 'import tensorflow as tf\n'), ((12011, 12040), 'numpy.transpose', 'numpy.transpose', (['X', '[0, 2, 1]'], {}), '(X, [0, 2, 1])\n', (12026, 12040), False, 'import numpy\n'), ((12053, 12087), 'numpy.transpose', 'numpy.transpose', (['test_x', '[0, 2, 1]'], {}), '(test_x, [0, 2, 1])\n', (12068, 12087), False, 'import numpy\n'), ((14324, 14334), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (14332, 14334), True, 'import tensorflow as tf\n'), ((14354, 14364), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (14362, 14364), True, 'import tensorflow as tf\n'), ((1884, 1910), 'numpy.random.shuffle', 'numpy.random.shuffle', (['data'], {}), '(data)\n', (1904, 1910), False, 'import numpy\n'), ((2528, 2550), 'numpy.load', 'numpy.load', (['input_path'], {}), '(input_path)\n', (2538, 2550), False, 'import numpy\n'), ((5092, 5204), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['first_convnet', 'n_nodes_conv_layer_1', 'conv_1_window_size'], {'strides': 'conv_1_strides', 'activation': '"""relu"""'}), "(first_convnet, n_nodes_conv_layer_1, conv_1_window_size, strides=\n conv_1_strides, activation='relu')\n", (5099, 5204), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((5224, 5294), 'tflearn.layers.conv.max_pool_2d', 'max_pool_2d', (['first_convnet', 'pool_1_window_size'], {'strides': 'pool_1_strides'}), '(first_convnet, pool_1_window_size, strides=pool_1_strides)\n', (5235, 5294), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((5319, 5362), 'tflearn.layers.normalization.local_response_normalization', 'local_response_normalization', (['first_convnet'], {}), '(first_convnet)\n', (5347, 5362), False, 'from tflearn.layers.normalization import local_response_normalization\n'), ((5424, 5512), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['first_convnet', 'n_nodes_conv_layer_2', 'conv_2_window_size'], {'activation': '"""relu"""'}), "(first_convnet, n_nodes_conv_layer_2, conv_2_window_size, activation\n ='relu')\n", (5431, 5512), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((5532, 5602), 'tflearn.layers.conv.max_pool_2d', 'max_pool_2d', (['first_convnet', 'pool_2_window_size'], {'strides': 'pool_2_strides'}), '(first_convnet, pool_2_window_size, strides=pool_2_strides)\n', (5543, 5602), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((5627, 5670), 'tflearn.layers.normalization.local_response_normalization', 'local_response_normalization', (['first_convnet'], {}), '(first_convnet)\n', (5655, 5670), False, 'from tflearn.layers.normalization import local_response_normalization\n'), ((5735, 5826), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['first_convnet', 'n_nodes_conv_layer_3_1', 'conv_3_1_window_size'], {'activation': '"""relu"""'}), "(first_convnet, n_nodes_conv_layer_3_1, conv_3_1_window_size,\n activation='relu')\n", (5742, 5826), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((5847, 5938), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['first_convnet', 'n_nodes_conv_layer_3_2', 'conv_3_2_window_size'], {'activation': '"""relu"""'}), "(first_convnet, n_nodes_conv_layer_3_2, conv_3_2_window_size,\n activation='relu')\n", (5854, 5938), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((5959, 6050), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['first_convnet', 'n_nodes_conv_layer_3_3', 'conv_3_3_window_size'], {'activation': '"""relu"""'}), "(first_convnet, n_nodes_conv_layer_3_3, conv_3_3_window_size,\n activation='relu')\n", (5966, 6050), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((6071, 6141), 'tflearn.layers.conv.max_pool_2d', 'max_pool_2d', (['first_convnet', 'pool_3_window_size'], {'strides': 'pool_3_strides'}), '(first_convnet, pool_3_window_size, strides=pool_3_strides)\n', (6082, 6141), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((6166, 6209), 'tflearn.layers.normalization.local_response_normalization', 'local_response_normalization', (['first_convnet'], {}), '(first_convnet)\n', (6194, 6209), False, 'from tflearn.layers.normalization import local_response_normalization\n'), ((6268, 6337), 'tflearn.layers.core.fully_connected', 'fully_connected', (['first_convnet', 'n_nodes_fc_layer_4'], {'activation': '"""tanh"""'}), "(first_convnet, n_nodes_fc_layer_4, activation='tanh')\n", (6283, 6337), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((6362, 6389), 'tflearn.layers.core.dropout', 'dropout', (['first_convnet', '(0.5)'], {}), '(first_convnet, 0.5)\n', (6369, 6389), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((6464, 6533), 'tflearn.layers.core.fully_connected', 'fully_connected', (['first_convnet', 'n_nodes_fc_layer_5'], {'activation': '"""tanh"""'}), "(first_convnet, n_nodes_fc_layer_5, activation='tanh')\n", (6479, 6533), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((6558, 6585), 'tflearn.layers.core.dropout', 'dropout', (['first_convnet', '(0.5)'], {}), '(first_convnet, 0.5)\n', (6565, 6585), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((6661, 6724), 'tflearn.layers.core.fully_connected', 'fully_connected', (['first_convnet', 'n_classes'], {'activation': '"""softmax"""'}), "(first_convnet, n_classes, activation='softmax')\n", (6676, 6724), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((7177, 7236), 'tflearn.DNN', 'tflearn.DNN', (['first_convnet'], {'tensorboard_dir': 'tensorboard_log'}), '(first_convnet, tensorboard_dir=tensorboard_log)\n', (7188, 7236), False, 'import tflearn\n'), ((8961, 9074), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['second_convnet', 'n_nodes_conv_layer_1', 'conv_1_window_size'], {'strides': 'conv_1_strides', 'activation': '"""relu"""'}), "(second_convnet, n_nodes_conv_layer_1, conv_1_window_size, strides=\n conv_1_strides, activation='relu')\n", (8968, 9074), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((9095, 9166), 'tflearn.layers.conv.max_pool_2d', 'max_pool_2d', (['second_convnet', 'pool_1_window_size'], {'strides': 'pool_1_strides'}), '(second_convnet, pool_1_window_size, strides=pool_1_strides)\n', (9106, 9166), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((9192, 9236), 'tflearn.layers.normalization.local_response_normalization', 'local_response_normalization', (['second_convnet'], {}), '(second_convnet)\n', (9220, 9236), False, 'from tflearn.layers.normalization import local_response_normalization\n'), ((9299, 9387), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['second_convnet', 'n_nodes_conv_layer_2', 'conv_2_window_size'], {'activation': '"""relu"""'}), "(second_convnet, n_nodes_conv_layer_2, conv_2_window_size,\n activation='relu')\n", (9306, 9387), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((9409, 9480), 'tflearn.layers.conv.max_pool_2d', 'max_pool_2d', (['second_convnet', 'pool_2_window_size'], {'strides': 'pool_2_strides'}), '(second_convnet, pool_2_window_size, strides=pool_2_strides)\n', (9420, 9480), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((9506, 9550), 'tflearn.layers.normalization.local_response_normalization', 'local_response_normalization', (['second_convnet'], {}), '(second_convnet)\n', (9534, 9550), False, 'from tflearn.layers.normalization import local_response_normalization\n'), ((9616, 9708), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['second_convnet', 'n_nodes_conv_layer_3_1', 'conv_3_1_window_size'], {'activation': '"""relu"""'}), "(second_convnet, n_nodes_conv_layer_3_1, conv_3_1_window_size,\n activation='relu')\n", (9623, 9708), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((9730, 9822), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['second_convnet', 'n_nodes_conv_layer_3_2', 'conv_3_2_window_size'], {'activation': '"""relu"""'}), "(second_convnet, n_nodes_conv_layer_3_2, conv_3_2_window_size,\n activation='relu')\n", (9737, 9822), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((9844, 9936), 'tflearn.layers.conv.conv_2d', 'conv_2d', (['second_convnet', 'n_nodes_conv_layer_3_3', 'conv_3_3_window_size'], {'activation': '"""relu"""'}), "(second_convnet, n_nodes_conv_layer_3_3, conv_3_3_window_size,\n activation='relu')\n", (9851, 9936), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((9958, 10029), 'tflearn.layers.conv.max_pool_2d', 'max_pool_2d', (['second_convnet', 'pool_3_window_size'], {'strides': 'pool_3_strides'}), '(second_convnet, pool_3_window_size, strides=pool_3_strides)\n', (9969, 10029), False, 'from tflearn.layers.conv import conv_2d, max_pool_2d\n'), ((10055, 10099), 'tflearn.layers.normalization.local_response_normalization', 'local_response_normalization', (['second_convnet'], {}), '(second_convnet)\n', (10083, 10099), False, 'from tflearn.layers.normalization import local_response_normalization\n'), ((10159, 10229), 'tflearn.layers.core.fully_connected', 'fully_connected', (['second_convnet', 'n_nodes_fc_layer_4'], {'activation': '"""tanh"""'}), "(second_convnet, n_nodes_fc_layer_4, activation='tanh')\n", (10174, 10229), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((10255, 10283), 'tflearn.layers.core.dropout', 'dropout', (['second_convnet', '(0.5)'], {}), '(second_convnet, 0.5)\n', (10262, 10283), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((10359, 10429), 'tflearn.layers.core.fully_connected', 'fully_connected', (['second_convnet', 'n_nodes_fc_layer_5'], {'activation': '"""tanh"""'}), "(second_convnet, n_nodes_fc_layer_5, activation='tanh')\n", (10374, 10429), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((10455, 10483), 'tflearn.layers.core.dropout', 'dropout', (['second_convnet', '(0.5)'], {}), '(second_convnet, 0.5)\n', (10462, 10483), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((10560, 10624), 'tflearn.layers.core.fully_connected', 'fully_connected', (['second_convnet', 'n_classes'], {'activation': '"""softmax"""'}), "(second_convnet, n_classes, activation='softmax')\n", (10575, 10624), False, 'from tflearn.layers.core import input_data, dropout, fully_connected\n'), ((11080, 11140), 'tflearn.DNN', 'tflearn.DNN', (['second_convnet'], {'tensorboard_dir': 'tensorboard_log'}), '(second_convnet, tensorboard_dir=tensorboard_log)\n', (11091, 11140), False, 'import tflearn\n'), ((11802, 11817), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (11813, 11817), False, 'import numpy\n')] |
import numpy as np
import logging as log
import networkx as nx
from sklearn.decomposition import PCA, IncrementalPCA
from sklearn.preprocessing import StandardScaler
from sklearn.random_projection import SparseRandomProjection
from sklearn.ensemble import ExtraTreesClassifier, \
RandomForestClassifier, \
AdaBoostClassifier,\
GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.cluster import MiniBatchKMeans
from sklearn.linear_model import SGDClassifier
from ..lib._spencoding import _sp_labels
from ..lib.spencoding import spmeans, sphist, spstats
from ..lib.spgraph import aggregate_neighbors
from ..lib._qpbo import solve_binary, solve_aexpansion
from ..core import DataModel
DM = DataModel.instance()
def obtain_classifier(clf_p):
if clf_p['clf'] == 'ensemble':
mode = 'ensemble'
if clf_p['type'] == 'rf':
clf = RandomForestClassifier(n_estimators=clf_p['n_estimators'],
max_depth=clf_p['max_depth'],
n_jobs=clf_p['n_jobs'])
elif clf_p['type'] == 'erf':
clf = ExtraTreesClassifier(n_estimators=clf_p['n_estimators'],
max_depth=clf_p['max_depth'],
n_jobs=clf_p['n_jobs'])
elif clf_p['type'] == 'ada':
clf = AdaBoostClassifier(n_estimators=clf_p['n_estimators'],
learning_rate=clf_p['learning_rate'])
else:
clf = GradientBoostingClassifier(n_estimators=clf_p['n_estimators'],
max_depth=clf_p['max_depth'],
learning_rate=clf_p['learning_rate'],
subsample=clf_p['subsample'])
elif clf_p['clf'] == 'svm':
mode = 'svm'
clf = SVC(C=clf_p['C'], gamma=clf_p['gamma'], kernel=clf_p['kernel'],
probability=True)
elif clf_p['clf'] == 'sgd':
mode = 'sgd'
clf = SGDClassifier(loss=clf_p['loss'], penalty=clf_p['penalty'],
alpha=clf_p['alpha'], n_iter=clf_p['n_iter'])
else:
raise Exception('Classifier not supported')
return clf, mode
def compute_supervoxel_descriptor(supervoxels, descriptors, desc_type, desc_bins):
'Mean' 'Quantized' 'Textons' 'Covar' 'Sigma Set'
if desc_type == 'Mean':
return spmeans(descriptors, supervoxels)
elif desc_type == 'Covar':
return spstats(descriptors, supervoxels, mode='add', norm=None)
elif desc_type == 'Sigma Set':
return spstats(descriptors, supervoxels, mode='add', sigmaset=True, norm=None)
if desc_type == 'Textons':
log.info('+ Applying PCA')
descriptors = IncrementalPCA(batch_size=100).fit_transform(descriptors)
log.info('+ Quantizing descriptors')
cluster = MiniBatchKMeans(n_clusters=desc_bins, batch_size=100).fit_predict(descriptors)
return sphist(cluster.astype(np.int32), supervoxels, nbins=desc_bins)
def extract_descriptors(supervoxels=None, features=None,
projection=None, desc_type=None, desc_bins=None,
nh_order=None, sp_edges=None):
total = len(features)
log.info('+ Reserving memory for {} features'.format(total))
descriptors = np.zeros(DM.region_shape() + (total,), np.float32)
for i in range(total):
log.info(' * Loading feature {}'.format(features[i]))
descriptors[..., i] = DM.load_slices(features[i])
sp = None
mask = None
if supervoxels is not None:
log.info('+ Loading supervoxels')
sp = DM.load_slices(supervoxels)
if sp.min() < 0:
raise Exception('Supervoxels need to be recomputed for this ROI')
descriptors.shape = (-1, total)
num_sv = DM.attr(supervoxels, 'num_supervoxels')
mask = np.zeros(num_sv, np.bool)
mask[sp.ravel()] = True
log.info('+ Computing descriptors: {} ({})'.format(desc_type, desc_bins))
descriptors = compute_supervoxel_descriptor(sp, descriptors,
desc_type, desc_bins)
nh_order = int(nh_order)
if nh_order > 0:
log.info('+ Loading edges into memory')
edges = DM.load_ds(sp_edges)
log.info('+ Filtering edges for selected ROI')
idx = mask[edges[:, 0]] & mask[edges[:, 1]]
edges = edges[idx]
log.info('+ Aggregating neighbour features')
G = nx.Graph()
G.add_edges_from(edges)
descriptors = aggregate_neighbors(descriptors, G, mode='append',
norm='mean', order=nh_order)
descriptors = descriptors[mask]
return descriptors, sp, mask
def predict_proba(y_data=None, p_data=None, train=False, append=False,
level_params=None, desc_params=None,
clf_params=None, ref_params=None,
out_labels=None, out_confidence=None):
log.info("+ Extracting descriptors: {}".format(desc_params))
X, supervoxels, svmask = extract_descriptors(**desc_params)
full_svmask = svmask.copy()
if level_params['plevel'] is not None:
parent_labels = DM.load_slices(p_data)
mask = parent_labels == level_params['plabel']
else:
mask = None
if train:
clf, mode = obtain_classifier(clf_params)
log.info("+ Creating classifier: {}".format(clf_params))
log.info("+ Loading labels")
labels = DM.load_slices(y_data)
else:
if DM.has_classifier():
log.info("+ Getting existing classifier")
clf = DM.get_classifier_from_model()
else:
log.error("For some reason, no previous classifier exists!")
return
if mask is not None:
mask = mask.astype(np.int16)
mask = np.bincount(supervoxels.ravel(), weights=mask.ravel() * 2 - 1) > 0
mask = mask[svmask]
mask.shape = -1
if supervoxels is not None:
nsp = DM.attr(desc_params['supervoxels'], 'num_supervoxels')
log.info('+ Extracting supervoxel labels')
if train:
nlbl = DM.attr(y_data, 'label').max() + 1
labels = _sp_labels(supervoxels.ravel(), labels.ravel(), nsp, nlbl, 0)
y = labels
y.shape = -1
if mask is not None:
idx_train = (y > -1) & mask
else:
idx_train = (y > -1)
X_train = X[idx_train]
y_train = y[idx_train]
log.info("+ Initial X_train shape {}".format(X_train.shape))
log.info("+ Initial y_train shape {}".format(y_train.shape))
if append and DM.has_training_data():
previous_X, previous_y = DM.get_training_data()
X_train = np.append(previous_X, X_train, axis=0)
y_train = np.append(previous_y, y_train)
log.info("+ Appended X_train shape {}".format(X_train.shape))
log.info("+ Appended y_train shape {}".format(y_train.shape))
DM.add_training_data(X_train, y_train)
if clf is not None:
_train_classifier(clf, X_train, y_train,
project=desc_params['projection'])
log.info('+ Adding classifier to data model')
DM.add_classifier_to_model(clf, clf_params)
elif clf is None:
log.error("No Classifier found!")
return None
return predict_and_save(X, clf, full_svmask, nsp, out_confidence, out_labels, supervoxels, ref_params, mask, svmask)
def predict_and_save(X, clf, full_svmask, nsp, out_confidence, out_labels, supervoxels, ref_params, mask, svmask):
result = classifier_predict(X, clf)
probs = result['probs']
labels = np.asarray(list(set(np.unique(result['class'][supervoxels])) - set([-1])), np.int32)
pred = result['class']
if supervoxels is not None:
if ref_params['ref_type'] != 'None':
log.info('+ Remapping supervoxels')
svmap = np.full(nsp, -1, supervoxels.dtype)
svmap[full_svmask] = np.arange(svmask.sum())
log.info('+ Extracting graph')
refine_lamda = ref_params['lambda']
edges = DM.load_ds(ref_params['sp_edges'])
edge_weights = DM.load_ds(ref_params['sp_eweights'])
mean_weights = edge_weights.mean()
edge_weights = np.minimum(edge_weights, mean_weights) / mean_weights
log.info('+ Remapping edges')
idx = full_svmask[edges[:, 0]] & full_svmask[edges[:, 1]]
edges = edges[idx]
edges[:, 0] = svmap[edges[:, 0]]
edges[:, 1] = svmap[edges[:, 1]]
edge_weights = edge_weights[idx]
log.info(' * Unary potentials')
unary = (-np.ma.log(probs)).filled()
unary = unary.astype(np.float32)
mapping = np.zeros(pred.max() + 1, np.int32)
mapping[labels] = np.arange(labels.size)
idx = np.where(pred > -1)[0]
col = mapping[pred[idx]]
unary[idx, col] = 0
pairwise = edge_weights.astype(np.float32)
log.info(' * Pairwise potentials')
if ref_params['ref_type'] == 'Appearance':
log.info('+ Extracting descriptive weights')
dists = np.sqrt(np.sum((X[edges[:, 0]] - X[edges[:, 1]]) ** 2, axis=1))
pairwise *= np.exp(-dists.mean() * dists)
log.debug(" * Shapes: {}, {}, {}, {}".format(unary.shape, pairwise.shape,
edges.shape, edge_weights.shape))
log.debug(" * Edges: min: {}, max: {}".format(edges.min(0), edges.max(0)))
log.debug(" * Unary: min: {}, max: {}, mean: {}"
.format(unary.min(0), unary.max(0), unary.mean(0)))
log.debug(" * Pairwise: min: {}, max: {}, mean: {}"
.format(pairwise.min(), pairwise.max(), pairwise.mean()))
log.info('+ Refining labels')
label_cost = np.ones((labels.size, labels.size), np.float32)
label_cost[np.diag_indices_from(label_cost)] = 0
label_cost *= refine_lamda
if label_cost.shape[0] == 2:
refined = solve_binary(edges, unary, pairwise, label_cost)
else:
refined = solve_aexpansion(edges, unary, pairwise, label_cost)
pred[mask] = labels[refined[mask]]
if mask is not None:
pred[~mask] = -1
#conf[~mask] = -1
else:
pass # TODO pixel refinement
log.info('+ Mapping predictions and probabilities back to pixels')
pred_map = np.empty(nsp, dtype=result['class'].dtype)
conf_map = np.empty(nsp, dtype=result['probs'].dtype)
# Get a list of label classes since when labels have been deleted some will be missing
label_classes = np.unique(result['class'])
# Make a dict mapping from label to sequential numbers beginning from 0
dict_map = dict(zip(label_classes, range(len(label_classes))))
# Slice each list of confidences with the corresponding predicted class
# to return the confidence for that class
conf_result = list(map(lambda x, y: x[dict_map[y]], result['probs'], result['class']))
pred_map[full_svmask] = result['class']
conf_map[full_svmask] = conf_result
if mask is not None:
pred_map[~mask] = -1
conf_map[~mask] = -1
pred = pred_map[supervoxels]
conf = conf_map[supervoxels]
pred.shape = DM.region_shape()
conf.shape = DM.region_shape()
log.info('+ Saving results to disk')
DM.create_empty_dataset(out_labels, shape=DM.data_shape, dtype=pred.dtype)
DM.write_slices(out_labels, pred, params=dict(labels=labels, active=True))
DM.create_empty_dataset(out_confidence, shape=DM.data_shape, dtype=conf.dtype)
DM.write_slices(out_confidence, conf, params=dict(labels=labels, active=True))
return out_labels, out_confidence, labels
def _train_classifier(clf, X_train, y_train, rnd=42, project=None):
if project is not None and project != 'None':
log.info('+ Projecting features')
if project == 'random_projection':
log.info(' * Sparse Random Projection')
proj = SparseRandomProjection(n_components=X_train.shape[1], random_state=rnd)
elif project == 'standard':
log.info(' * Standard Projection')
proj = StandardScaler()
elif project == 'pca':
log.info(' * Principle Component Analysis')
proj = IncrementalPCA(batch_size=100)
elif project == 'random_pca':
log.info(' * Randomized Principle Component Analysis')
proj = PCA(n_components=X_train.shape[1], svd_solver='randomized', whiten=True, random_state=rnd)
else:
log.error('Projection {} not available'.format(project))
return
X_train = proj.fit_transform(X_train)
log.info('+ Training classifier')
clf.fit(X_train, y_train)
def classifier_predict(X, clf):
result = {}
log.info('+ Predicting labels')
result['class'] = clf.predict(X)
result['probs'] = clf.predict_proba(X)
return result
| [
"sklearn.cluster.MiniBatchKMeans",
"numpy.diag_indices_from",
"sklearn.preprocessing.StandardScaler",
"numpy.sum",
"numpy.empty",
"numpy.ones",
"numpy.ma.log",
"sklearn.random_projection.SparseRandomProjection",
"numpy.arange",
"sklearn.svm.SVC",
"numpy.unique",
"numpy.full",
"logging.error"... | [((2959, 2995), 'logging.info', 'log.info', (['"""+ Quantizing descriptors"""'], {}), "('+ Quantizing descriptors')\n", (2967, 2995), True, 'import logging as log\n'), ((11985, 12021), 'logging.info', 'log.info', (['"""+ Saving results to disk"""'], {}), "('+ Saving results to disk')\n", (11993, 12021), True, 'import logging as log\n'), ((13370, 13403), 'logging.info', 'log.info', (['"""+ Training classifier"""'], {}), "('+ Training classifier')\n", (13378, 13403), True, 'import logging as log\n'), ((13487, 13518), 'logging.info', 'log.info', (['"""+ Predicting labels"""'], {}), "('+ Predicting labels')\n", (13495, 13518), True, 'import logging as log\n'), ((2847, 2873), 'logging.info', 'log.info', (['"""+ Applying PCA"""'], {}), "('+ Applying PCA')\n", (2855, 2873), True, 'import logging as log\n'), ((3734, 3767), 'logging.info', 'log.info', (['"""+ Loading supervoxels"""'], {}), "('+ Loading supervoxels')\n", (3742, 3767), True, 'import logging as log\n'), ((4025, 4050), 'numpy.zeros', 'np.zeros', (['num_sv', 'np.bool'], {}), '(num_sv, np.bool)\n', (4033, 4050), True, 'import numpy as np\n'), ((5667, 5695), 'logging.info', 'log.info', (['"""+ Loading labels"""'], {}), "('+ Loading labels')\n", (5675, 5695), True, 'import logging as log\n'), ((6294, 6336), 'logging.info', 'log.info', (['"""+ Extracting supervoxel labels"""'], {}), "('+ Extracting supervoxel labels')\n", (6302, 6336), True, 'import logging as log\n'), ((10929, 10995), 'logging.info', 'log.info', (['"""+ Mapping predictions and probabilities back to pixels"""'], {}), "('+ Mapping predictions and probabilities back to pixels')\n", (10937, 10995), True, 'import logging as log\n'), ((11015, 11057), 'numpy.empty', 'np.empty', (['nsp'], {'dtype': "result['class'].dtype"}), "(nsp, dtype=result['class'].dtype)\n", (11023, 11057), True, 'import numpy as np\n'), ((11077, 11119), 'numpy.empty', 'np.empty', (['nsp'], {'dtype': "result['probs'].dtype"}), "(nsp, dtype=result['probs'].dtype)\n", (11085, 11119), True, 'import numpy as np\n'), ((11239, 11265), 'numpy.unique', 'np.unique', (["result['class']"], {}), "(result['class'])\n", (11248, 11265), True, 'import numpy as np\n'), ((12521, 12554), 'logging.info', 'log.info', (['"""+ Projecting features"""'], {}), "('+ Projecting features')\n", (12529, 12554), True, 'import logging as log\n'), ((963, 1080), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': "clf_p['n_estimators']", 'max_depth': "clf_p['max_depth']", 'n_jobs': "clf_p['n_jobs']"}), "(n_estimators=clf_p['n_estimators'], max_depth=clf_p[\n 'max_depth'], n_jobs=clf_p['n_jobs'])\n", (985, 1080), False, 'from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier\n'), ((1982, 2068), 'sklearn.svm.SVC', 'SVC', ([], {'C': "clf_p['C']", 'gamma': "clf_p['gamma']", 'kernel': "clf_p['kernel']", 'probability': '(True)'}), "(C=clf_p['C'], gamma=clf_p['gamma'], kernel=clf_p['kernel'], probability\n =True)\n", (1985, 2068), False, 'from sklearn.svm import SVC\n'), ((3010, 3063), 'sklearn.cluster.MiniBatchKMeans', 'MiniBatchKMeans', ([], {'n_clusters': 'desc_bins', 'batch_size': '(100)'}), '(n_clusters=desc_bins, batch_size=100)\n', (3025, 3063), False, 'from sklearn.cluster import MiniBatchKMeans\n'), ((4379, 4418), 'logging.info', 'log.info', (['"""+ Loading edges into memory"""'], {}), "('+ Loading edges into memory')\n", (4387, 4418), True, 'import logging as log\n'), ((4473, 4519), 'logging.info', 'log.info', (['"""+ Filtering edges for selected ROI"""'], {}), "('+ Filtering edges for selected ROI')\n", (4481, 4519), True, 'import logging as log\n'), ((4620, 4664), 'logging.info', 'log.info', (['"""+ Aggregating neighbour features"""'], {}), "('+ Aggregating neighbour features')\n", (4628, 4664), True, 'import logging as log\n'), ((4681, 4691), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (4689, 4691), True, 'import networkx as nx\n'), ((5790, 5831), 'logging.info', 'log.info', (['"""+ Getting existing classifier"""'], {}), "('+ Getting existing classifier')\n", (5798, 5831), True, 'import logging as log\n'), ((5907, 5967), 'logging.error', 'log.error', (['"""For some reason, no previous classifier exists!"""'], {}), "('For some reason, no previous classifier exists!')\n", (5916, 5967), True, 'import logging as log\n'), ((8245, 8280), 'logging.info', 'log.info', (['"""+ Remapping supervoxels"""'], {}), "('+ Remapping supervoxels')\n", (8253, 8280), True, 'import logging as log\n'), ((8301, 8336), 'numpy.full', 'np.full', (['nsp', '(-1)', 'supervoxels.dtype'], {}), '(nsp, -1, supervoxels.dtype)\n', (8308, 8336), True, 'import numpy as np\n'), ((8407, 8437), 'logging.info', 'log.info', (['"""+ Extracting graph"""'], {}), "('+ Extracting graph')\n", (8415, 8437), True, 'import logging as log\n'), ((8747, 8776), 'logging.info', 'log.info', (['"""+ Remapping edges"""'], {}), "('+ Remapping edges')\n", (8755, 8776), True, 'import logging as log\n'), ((9026, 9058), 'logging.info', 'log.info', (['""" * Unary potentials"""'], {}), "(' * Unary potentials')\n", (9034, 9058), True, 'import logging as log\n'), ((9240, 9262), 'numpy.arange', 'np.arange', (['labels.size'], {}), '(labels.size)\n', (9249, 9262), True, 'import numpy as np\n'), ((9441, 9476), 'logging.info', 'log.info', (['""" * Pairwise potentials"""'], {}), "(' * Pairwise potentials')\n", (9449, 9476), True, 'import logging as log\n'), ((10301, 10330), 'logging.info', 'log.info', (['"""+ Refining labels"""'], {}), "('+ Refining labels')\n", (10309, 10330), True, 'import logging as log\n'), ((10356, 10403), 'numpy.ones', 'np.ones', (['(labels.size, labels.size)', 'np.float32'], {}), '((labels.size, labels.size), np.float32)\n', (10363, 10403), True, 'import numpy as np\n'), ((12610, 12650), 'logging.info', 'log.info', (['""" * Sparse Random Projection"""'], {}), "(' * Sparse Random Projection')\n", (12618, 12650), True, 'import logging as log\n'), ((12670, 12741), 'sklearn.random_projection.SparseRandomProjection', 'SparseRandomProjection', ([], {'n_components': 'X_train.shape[1]', 'random_state': 'rnd'}), '(n_components=X_train.shape[1], random_state=rnd)\n', (12692, 12741), False, 'from sklearn.random_projection import SparseRandomProjection\n'), ((1213, 1328), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'n_estimators': "clf_p['n_estimators']", 'max_depth': "clf_p['max_depth']", 'n_jobs': "clf_p['n_jobs']"}), "(n_estimators=clf_p['n_estimators'], max_depth=clf_p[\n 'max_depth'], n_jobs=clf_p['n_jobs'])\n", (1233, 1328), False, 'from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier\n'), ((2149, 2259), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {'loss': "clf_p['loss']", 'penalty': "clf_p['penalty']", 'alpha': "clf_p['alpha']", 'n_iter': "clf_p['n_iter']"}), "(loss=clf_p['loss'], penalty=clf_p['penalty'], alpha=clf_p[\n 'alpha'], n_iter=clf_p['n_iter'])\n", (2162, 2259), False, 'from sklearn.linear_model import SGDClassifier\n'), ((2896, 2926), 'sklearn.decomposition.IncrementalPCA', 'IncrementalPCA', ([], {'batch_size': '(100)'}), '(batch_size=100)\n', (2910, 2926), False, 'from sklearn.decomposition import PCA, IncrementalPCA\n'), ((7031, 7069), 'numpy.append', 'np.append', (['previous_X', 'X_train'], {'axis': '(0)'}), '(previous_X, X_train, axis=0)\n', (7040, 7069), True, 'import numpy as np\n'), ((7096, 7126), 'numpy.append', 'np.append', (['previous_y', 'y_train'], {}), '(previous_y, y_train)\n', (7105, 7126), True, 'import numpy as np\n'), ((7510, 7555), 'logging.info', 'log.info', (['"""+ Adding classifier to data model"""'], {}), "('+ Adding classifier to data model')\n", (7518, 7555), True, 'import logging as log\n'), ((8680, 8718), 'numpy.minimum', 'np.minimum', (['edge_weights', 'mean_weights'], {}), '(edge_weights, mean_weights)\n', (8690, 8718), True, 'import numpy as np\n'), ((9281, 9300), 'numpy.where', 'np.where', (['(pred > -1)'], {}), '(pred > -1)\n', (9289, 9300), True, 'import numpy as np\n'), ((9548, 9592), 'logging.info', 'log.info', (['"""+ Extracting descriptive weights"""'], {}), "('+ Extracting descriptive weights')\n", (9556, 9592), True, 'import logging as log\n'), ((10427, 10459), 'numpy.diag_indices_from', 'np.diag_indices_from', (['label_cost'], {}), '(label_cost)\n', (10447, 10459), True, 'import numpy as np\n'), ((12790, 12825), 'logging.info', 'log.info', (['""" * Standard Projection"""'], {}), "(' * Standard Projection')\n", (12798, 12825), True, 'import logging as log\n'), ((12845, 12861), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (12859, 12861), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1457, 1554), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {'n_estimators': "clf_p['n_estimators']", 'learning_rate': "clf_p['learning_rate']"}), "(n_estimators=clf_p['n_estimators'], learning_rate=clf_p[\n 'learning_rate'])\n", (1475, 1554), False, 'from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier\n'), ((1619, 1789), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'n_estimators': "clf_p['n_estimators']", 'max_depth': "clf_p['max_depth']", 'learning_rate': "clf_p['learning_rate']", 'subsample': "clf_p['subsample']"}), "(n_estimators=clf_p['n_estimators'], max_depth=\n clf_p['max_depth'], learning_rate=clf_p['learning_rate'], subsample=\n clf_p['subsample'])\n", (1645, 1789), False, 'from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier\n'), ((7662, 7695), 'logging.error', 'log.error', (['"""No Classifier found!"""'], {}), "('No Classifier found!')\n", (7671, 7695), True, 'import logging as log\n'), ((8064, 8103), 'numpy.unique', 'np.unique', (["result['class'][supervoxels]"], {}), "(result['class'][supervoxels])\n", (8073, 8103), True, 'import numpy as np\n'), ((9625, 9679), 'numpy.sum', 'np.sum', (['((X[edges[:, 0]] - X[edges[:, 1]]) ** 2)'], {'axis': '(1)'}), '((X[edges[:, 0]] - X[edges[:, 1]]) ** 2, axis=1)\n', (9631, 9679), True, 'import numpy as np\n'), ((12905, 12949), 'logging.info', 'log.info', (['""" * Principle Component Analysis"""'], {}), "(' * Principle Component Analysis')\n", (12913, 12949), True, 'import logging as log\n'), ((12969, 12999), 'sklearn.decomposition.IncrementalPCA', 'IncrementalPCA', ([], {'batch_size': '(100)'}), '(batch_size=100)\n', (12983, 12999), False, 'from sklearn.decomposition import PCA, IncrementalPCA\n'), ((9081, 9097), 'numpy.ma.log', 'np.ma.log', (['probs'], {}), '(probs)\n', (9090, 9097), True, 'import numpy as np\n'), ((13050, 13105), 'logging.info', 'log.info', (['""" * Randomized Principle Component Analysis"""'], {}), "(' * Randomized Principle Component Analysis')\n", (13058, 13105), True, 'import logging as log\n'), ((13125, 13219), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'X_train.shape[1]', 'svd_solver': '"""randomized"""', 'whiten': '(True)', 'random_state': 'rnd'}), "(n_components=X_train.shape[1], svd_solver='randomized', whiten=True,\n random_state=rnd)\n", (13128, 13219), False, 'from sklearn.decomposition import PCA, IncrementalPCA\n')] |
"""Check that functions can handle scalar input"""
from typing import Callable, Union
import hypothesis
import numpy as np
import pytest
from hypothesis.strategies import floats, integers, one_of
from numpy.testing import assert_array_almost_equal
import bottleneck as bn # noqa: F401
from .util import get_functions
int64_iinfo = np.iinfo(np.int64)
scalars = one_of(
[integers(min_value=int64_iinfo.min, max_value=int64_iinfo.max), floats()]
)
@hypothesis.given(scalar=scalars)
@pytest.mark.parametrize(
"func",
get_functions("reduce") + get_functions("nonreduce_axis"),
ids=lambda x: x.__name__,
)
def test_scalar_input(
func: Callable[[np.array], Union[int, float, np.array]], scalar: Union[int, float]
) -> None:
"""Test that bn.xxx gives the same output as bn.slow.xxx for scalar input."""
if func.__name__ in ("partition", "argpartition", "push"):
return
func0 = eval("bn.slow.%s" % func.__name__)
msg = "\nfunc %s | input %s\n"
actual_raised = False
desired_raised = False
try:
actual = func(scalar)
except ValueError:
actual_raised = True
try:
desired = func0(scalar)
except ValueError:
desired_raised = True
if desired_raised or actual_raised:
assert actual_raised and desired_raised
else:
err_msg = msg % (func.__name__, scalar)
assert_array_almost_equal(actual, desired, err_msg=err_msg)
| [
"numpy.iinfo",
"hypothesis.strategies.floats",
"hypothesis.given",
"numpy.testing.assert_array_almost_equal",
"hypothesis.strategies.integers"
] | [((336, 354), 'numpy.iinfo', 'np.iinfo', (['np.int64'], {}), '(np.int64)\n', (344, 354), True, 'import numpy as np\n'), ((459, 491), 'hypothesis.given', 'hypothesis.given', ([], {'scalar': 'scalars'}), '(scalar=scalars)\n', (475, 491), False, 'import hypothesis\n'), ((380, 442), 'hypothesis.strategies.integers', 'integers', ([], {'min_value': 'int64_iinfo.min', 'max_value': 'int64_iinfo.max'}), '(min_value=int64_iinfo.min, max_value=int64_iinfo.max)\n', (388, 442), False, 'from hypothesis.strategies import floats, integers, one_of\n'), ((444, 452), 'hypothesis.strategies.floats', 'floats', ([], {}), '()\n', (450, 452), False, 'from hypothesis.strategies import floats, integers, one_of\n'), ((1383, 1442), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['actual', 'desired'], {'err_msg': 'err_msg'}), '(actual, desired, err_msg=err_msg)\n', (1408, 1442), False, 'from numpy.testing import assert_array_almost_equal\n')] |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import random
from handleXml import handleXml
import os
def img_resize(image):
height, width = image.shape[0], image.shape[1]
# 设置新的图片分辨率框架
multi=round(random.random()*2) + 1
# print(multi)
width_new = width*multi
height_new = height*multi
# 判断图片的长宽比率
if width / height >= width_new / height_new:
img_new = cv2.resize(image, (width_new, int(height * width_new / width)))
else:
img_new = cv2.resize(image, (int(width * height_new / height), height_new))
return img_new
def pole(image):
GrayImage=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
ret,thresh1=cv2.threshold(GrayImage,250,255,cv2.THRESH_BINARY)
return thresh1
def generatePadding(minPadding,maxPadding):
top=random.randint(minPadding,maxPadding)
bottom=maxPadding-top
left=random.randint(minPadding,maxPadding)
right=maxPadding-left
return [top,bottom,left,right]
def getOriginalPadding(image):
image=np.array(image)
top=0
bottom=0
left=0
right=0
willBreak=False
for rowIndex in range(0,len(image)):
for column in image[rowIndex]:
if column != 255:
top=rowIndex
willBreak=True
break
if willBreak==True:
break
willBreak=False
for rowIndex in range(0,len(image)):
for column in image[-rowIndex-1]:
if column != 255:
bottom=rowIndex
willBreak=True
break
if willBreak==True:
break
willBreak=False
image=np.transpose(image)
for columnIndex in range(0,len(image)):
for row in image[columnIndex]:
if row != 255:
left=columnIndex
willBreak=True
break
if willBreak==True:
break
willBreak=False
for columnIndex in range(0,len(image)):
for row in image[-columnIndex-1]:
if row != 255:
right=columnIndex
willBreak=True
break
if willBreak==True:
break
return [top,bottom,left,right]
imgPath='D:\\imgProcess\\train_multi_en_JPEGImages'
xmlPath='D:\\imgProcess\\train_multi_en_Annotations'
imgOutputPath='D:\\imgProcess\\train_multi_en_JPEGImages_output'
#获取该目录下所有文件,存入列表中
imgList=os.listdir(imgPath)
xmlHandler=handleXml(imgPath,xmlPath)
for i in imgList:
#设置旧文件名(就是路径+文件名)
# oldname=path+ os.sep + i # os.sep添加系统分隔符
name=i.split('.')[0]
#设置新文件名
# newname=path + os.sep +name+'.jpg'
# os.rename(oldname,newname) #用os模块中的rename方法对文件改名
# print(oldname,'======>',newname)
# 读图
data = np.fromfile(f'{imgPath}\\{i}', dtype=np.uint8) #先用numpy把图片文件存入内存:data,把图片数据看做是纯字节数据
img = cv2.imdecode(data, cv2.IMREAD_COLOR) #从内存数据读入图片
# img=cv2.imread(f'{imgPath}\\{i}')
# print(f'{imgPath}\\{i}')
# 分辨率+
img=img_resize(img)
# 二值化
img=pole(img)
img_height,img_width=img.shape
# 获取原图padding
res=getOriginalPadding(img)
# print(res)
top,bottom,left,right=generatePadding(30,200)
# (上, 下) (左, 右) (上左, 右下)
# 添加背景padding
img=np.pad(img,((top,bottom),(left,right)),'constant',constant_values = (255,255))
# label坐标
coord={
'xmin':left+res[2],
'ymin':top+res[0],
'xmax':left+img_width-res[3],
'ymax':top+img_height-res[1],
}
# 写入XML
# label=name[0]
label=i.split('_')
label=label[0]+'_'+label[1]
xmlHandler.writeXml(i,coord,label)
# 写入新图片
# cv2.imwrite(f'{imgOutputPath}\\{i}', img)
cv2.imencode('.jpg',img)[1].tofile(f'{imgOutputPath}\\{i}') | [
"numpy.pad",
"handleXml.handleXml",
"random.randint",
"cv2.cvtColor",
"numpy.fromfile",
"cv2.threshold",
"cv2.imdecode",
"numpy.transpose",
"random.random",
"numpy.array",
"cv2.imencode",
"os.listdir"
] | [((2407, 2426), 'os.listdir', 'os.listdir', (['imgPath'], {}), '(imgPath)\n', (2417, 2426), False, 'import os\n'), ((2439, 2466), 'handleXml.handleXml', 'handleXml', (['imgPath', 'xmlPath'], {}), '(imgPath, xmlPath)\n', (2448, 2466), False, 'from handleXml import handleXml\n'), ((624, 663), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (636, 663), False, 'import cv2\n'), ((679, 732), 'cv2.threshold', 'cv2.threshold', (['GrayImage', '(250)', '(255)', 'cv2.THRESH_BINARY'], {}), '(GrayImage, 250, 255, cv2.THRESH_BINARY)\n', (692, 732), False, 'import cv2\n'), ((803, 841), 'random.randint', 'random.randint', (['minPadding', 'maxPadding'], {}), '(minPadding, maxPadding)\n', (817, 841), False, 'import random\n'), ((876, 914), 'random.randint', 'random.randint', (['minPadding', 'maxPadding'], {}), '(minPadding, maxPadding)\n', (890, 914), False, 'import random\n'), ((1017, 1032), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (1025, 1032), True, 'import numpy as np\n'), ((1636, 1655), 'numpy.transpose', 'np.transpose', (['image'], {}), '(image)\n', (1648, 1655), True, 'import numpy as np\n'), ((2764, 2810), 'numpy.fromfile', 'np.fromfile', (['f"""{imgPath}\\\\{i}"""'], {'dtype': 'np.uint8'}), "(f'{imgPath}\\\\{i}', dtype=np.uint8)\n", (2775, 2810), True, 'import numpy as np\n'), ((2859, 2895), 'cv2.imdecode', 'cv2.imdecode', (['data', 'cv2.IMREAD_COLOR'], {}), '(data, cv2.IMREAD_COLOR)\n', (2871, 2895), False, 'import cv2\n'), ((3253, 3341), 'numpy.pad', 'np.pad', (['img', '((top, bottom), (left, right))', '"""constant"""'], {'constant_values': '(255, 255)'}), "(img, ((top, bottom), (left, right)), 'constant', constant_values=(\n 255, 255))\n", (3259, 3341), True, 'import numpy as np\n'), ((232, 247), 'random.random', 'random.random', ([], {}), '()\n', (245, 247), False, 'import random\n'), ((3690, 3715), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'img'], {}), "('.jpg', img)\n", (3702, 3715), False, 'import cv2\n')] |
import numpy as np
def alogsumexp(logarray, axis=0):
"""
Calculate the sum of an array of values which are in log space. If an axis is
specified, the sum across this axis is given.
Parameters
----------
logarray: array
An array of log values to be summed.
axis: int, optional
Axis to sum across.
Returns
-------
Either a float corresponding to the log of summed values, or the vector of
sums across a specific axis.
"""
with np.errstate(invalid='ignore', divide='ignore'): # turn off warnings about dividing by zeros.
shp = list(logarray.shape)
shp[axis] = 1
maxvals = logarray.max(axis=axis)
sumarray = np.log(np.sum(np.exp(logarray - maxvals.reshape(shp)), axis = axis)) + maxvals
if not isinstance(sumarray, float):
sumarray[np.isnan(sumarray)] = np.log(0)
return sumarray
| [
"numpy.isnan",
"numpy.log",
"numpy.errstate"
] | [((504, 550), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""', 'divide': '"""ignore"""'}), "(invalid='ignore', divide='ignore')\n", (515, 550), True, 'import numpy as np\n'), ((891, 900), 'numpy.log', 'np.log', (['(0)'], {}), '(0)\n', (897, 900), True, 'import numpy as np\n'), ((869, 887), 'numpy.isnan', 'np.isnan', (['sumarray'], {}), '(sumarray)\n', (877, 887), True, 'import numpy as np\n')] |
# Python 3.5.2 |Anaconda 4.2.0 (64-bit)|
# -*- coding: utf-8 -*-
"""
Last edited: 2017-09-13
Author: <NAME> (<EMAIL>)
Forked by: <NAME> (<EMAIL>)
Description: Implements the Detector, i.e. the key object in the Spatial BOCD
software. This object takes in the Data & its dimensions, the CP prior,
a set of probability models, the priors over this probability model collection,
and a model prior probability over each of the models in the collection.
"""
import numpy as np
import scipy
from scipy import misc
import time
from BVAR_NIG_DPD import BVARNIGDPD
from BVAR_NIG import BVARNIG
class Detector:
"""key object in the Spatial BOCD
software. This object takes in the Data & its dimensions, a set of
probability models and their priors, and a model prior probability
over each of the models in the collection/universe, and a CP prior.
Attributes:
data: float numpy array;
a SxS spatial lattice with T time points and thus of
dimension SxSxT
model_universe: ProbabilityModel numpy array;
the collection of models
that might fit a given segment. All children of the
ProbabilityModel parent class
model_prior: float numpy array;
a prior vector giving the prior belief for each entry
in the *model_universe* numpy array. If model_prior[i-1] = p,
then we have prior belief p that the i-th model is the generating
process for a given segment
cp_model: CpModel object;
the CP model, usually specified as a geometric distribution
over the time points.
Q: int;
the number of entries in the model_universe numpy array
T, S1, S2: int;
the dimensions of the spatial lattice (S1, S2) and the time (T),
provided that the data is not put in as data stream
predictive_probs: float numpy array;
stores the predictive probs at each time point for each lattice
point and for each potential model
growth_probs: float numpy array;
stores the probability of the run lengths being r = 1,2,..., t at
time point t.
cp_probs: float numpy array;
stores the probability of the run lengt being r=0 at time point t
evidence: float numpy array;
stores the evidence (posterior probability) of having observed
all values of the data up until time point t at each time point t
run_length_distr: float numpy array;
stores the run-length distribution for r=0,1,...,t at each time
point t.
"""
def __init__(self, data, model_universe, model_prior, cp_model,
S1, S2, T, exo_data=None, num_exo_vars=None, threshold=None,
store_rl = False, store_mrl = False, trim_type = "keep_K",
notifications = 50,
save_performance_indicators=False,
training_period = 200,
generalized_bayes_rld = False, #'kullback_leibler', 'power_divergence'
alpha_rld = None,
alpha_rld_learning = False,
alpha_param_learning = False,
alpha_param = None,
#SGD-updating of alpha_param and alpha_rld in case we use DPD
loss_der_rld_learning = None,
loss_param_learning = None,
step_size_rld_learning = None,
step_size_param_learning = None,
eps_param_learning = None,
alpha_param_opt_t=100,
alpha_rld_opt_t = 100):
#add arguments: save_negative_log_likelihood, training_period
"""construct the Detector with the multi-dimensional numpy array
*data*. E.g., if you have a SxS spatial lattice with T time points,
then *data* will be SxSxT. The argument *model_universe* will provide
you with a numpy array of ProbabilityModel objects, each of which is
associated with a model that could fit the data and allows for online
bayesian CP detection. The *model_prior* is a numpy array of floats,
summing to one such that the i-th entry corresponds to the prior belief
that the i-th model occurs in a segment. Lastly, *cp_model* is an
object of class CpModel that stores all properties about the CP prior,
i.e. the probability of one occuring at every time point.
"""
#DEBUG: initialize correctly
self.gradient = 0.0
"""store the inputs into object"""
self.data = data.reshape(T, S1*S2)
self.model_universe = model_universe
self.model_prior = model_prior
self.cp_model = cp_model
if isinstance(model_universe, list):
self.Q = int(len(model_universe))
else:
self.Q = model_universe.shape[0]
self.T, self.S1, self.S2 = T, S1, S2
self.threshold = threshold
self.store_rl, self.store_mrl = store_rl, store_mrl
self.not_all_initialized = True
#self.MAP_first_reached = True
self.m_star_old = 0
self.first_model_initialized = False
self.trim_type = trim_type #other option: "threshold"
self.notifications = notifications
self.save_performance_indicators = save_performance_indicators
self.training_period = training_period
self.negative_log_likelihood = []
self.negative_log_likelihood_fixed_pars = []
self.MSE = []
self.MAE = []
"""Take care of exogeneous variables"""
#DEBUG: At this point, assumes that we have an obs. for each location
# at later stage, might want to group areas and have only one
# exo observation per group per variable
if exo_data is not None:
self.exo_data = exo_data.reshape(T, S1*S2, num_exo_vars)
else:
self.exo_data = exo_data
self.num_exo_vars = num_exo_vars
"""create internal data structures for most recent computed objects"""
self.evidence = -np.inf
self.MAP = None
self.y_pred_mean = np.zeros(shape=(self.S1, self.S2))
self.y_pred_var = np.zeros(shape = (self.S1*self.S2, self.S1*self.S2))
"""create internal data structures for all computed objects"""
self.model_and_run_length_log_distr = (-np.inf *
np.ones(shape = (self.Q, self.T+1)))
self.storage_run_length_log_distr = [] #np.zeros(shape=(self.T+1, self.T+1))
self.storage_model_and_run_length_log_distr = []
self.storage_all_retained_run_lengths = []
self.storage_mean = np.zeros(shape = (self.T, self.S1, self.S2))
self.storage_var = np.zeros((self.T, self.S1*self.S2))
#np.zeros(shape = (self.T, self.S1*self.S2,
# self.S1*self.S2))
self.storage_log_evidence = -np.inf * np.ones(shape = self.T)
#DEBUG: I have changed code s.t. log_MAP_storage grows
#self.log_MAP_storage = -np.inf * np.ones(self.T)
#Note: has two entries at time t=1, for r = 0 and r>0
self.log_MAP_storage = np.array([0,0])#np.array([0,0])
self.CPs = [[]] * self.T
self.MAP_segmentation = [np.array([[],[]])]
#self.segment_log_densities = np.zeros(shape = (self.Q, self.T) )
"""store the smallest & largest lag length"""
self.smallest_lag_length = 99999
for model in self.model_universe:
if model.has_lags:
self.smallest_lag_length = min(self.smallest_lag_length,
model.lag_length)
else:
self.smallest_lag_length = 0
self.max_lag_length = 0
for model in self.model_universe:
if model.has_lags:
self.max_lag_length = max(self.max_lag_length,
model.lag_length)
"""STEP 3: If we are in a generalized Bayes setting, modify each model
object accordingly"""
"""STEP 3.1: If we use DPD for parameter inference and we want to
optimize the alpha paramter across all models, set the initial value
of alpha_param using either detector-input or the first model's val"""
self.alpha_param_learning = alpha_param_learning
if ((alpha_param is not None) and alpha_param_learning == "together"):
self.alpha_param = alpha_param
self.gradient_alpha_param_count = 0
self.gradient_alpha_param = 0
elif alpha_param_learning == "together":
self.alpha_param = self.model_universe[0].alpha_param
self.gradient_alpha_param_count = 0
self.gradient_alpha_param = 0
print("WARNING! You are using DPD for parameter inference " +
"and want to optimize alpha_param across all models, " +
"but you have not specified an initial value in the " +
"detector object. The alpha_param of the first " +
"model in the model universe was chosen instead")
"""STEP 3.2: Set whether we do alpha_param learning inside models.
Next, set alpha_param for all models that are DPD in case we do
joint optimization across all models. """
if ((alpha_param_learning == "individual") or
alpha_param_learning == "together"):
if alpha_param_learning == "individual":
self.gradient_alpha_param_count = np.zeros(self.Q)
self.gradient_alpha_param = np.zeros(self.Q)
"""Set the alpha_param learning attribute for DPD models"""
for model in self.model_universe:
if isinstance(model, BVARNIGDPD):
model.alpha_param_learning = True
"""Set the initial alpha_param value. This ensures that
the optimization step makes sense."""
if alpha_param_learning == "together":
model.alpha_param = self.alpha_param
self.alpha_param_opt_t = alpha_param_opt_t
self.alpha_rld_opt_t = alpha_rld_opt_t
self.alpha_opt_count = 0
"""STEP 3.3: Set all phantities relating to Run-length distribution
robustification using DPD"""
self.alpha_rld_learning = alpha_rld_learning
self.generalized_bayes_rld = generalized_bayes_rld
self.alpha_rld = alpha_rld
self.alpha_list = []
if generalized_bayes_rld == "power_divergence": #or generalized_bayes is True:
for model in self.model_universe:
model.generalized_bayes_rld = "power_divergence"
model.alpha_rld = self.alpha_rld
model.alpha_rld_learning = (
self.alpha_rld_learning)
self.jlp_scale = None #initialize the scaling of log probs
self.gradient_alpha_rld_count = 0
self.gradient_alpha_rld = 0
"""STEP 3.4: Read in all the SGD-related functions generating stepsize,
epsilon (for finite differences) and the loss function"""
"""STEP 3.4.1: Default choices for our functions"""
self.C = 1.0
if (loss_der_rld_learning is None):
loss_der_rld_learning = Detector.bounded_absolute_loss_derivative
elif (loss_der_rld_learning == "squared_loss" or
loss_der_rld_learning == "squared_loss_derivative"):
loss_der_rld_learning = Detector.squared_loss_derivative
elif (loss_der_rld_learning == "absolute_loss" or
loss_der_rld_learning == "absolute_loss_derivative"):
loss_der_rld_learning = Detector.absolute_loss_derivative
if loss_param_learning is None:
loss_param_learning = Detector.bounded_absolute_loss
elif loss_param_learning == "squared_loss":
loss_param_learning = Detector.squared_loss
elif loss_param_learning == "absolute_loss":
loss_param_learning = Detector.absolute_loss
if step_size_rld_learning is None:
step_size_rld_learning = Detector.step_size_gen_rld
if step_size_param_learning is None:
step_size_param_learning = Detector.step_size_gen_rld
if eps_param_learning is None:
eps_param_learning = Detector.eps_gen
"""STEP 3.4.2: Set the Detector attribute functions """
self.loss_der_rld_learning = loss_der_rld_learning
self.loss_param_learning = loss_param_learning
#DEBUG: Get some default functions here that make sense!
self.step_size_rld_learning = step_size_rld_learning
self.step_size_param_learning = step_size_param_learning
if step_size_param_learning is None:
self.step_size_param_learning = (
Detector.default_step_size_param_learning)
self.eps_param_learning = eps_param_learning
self.all_retained_run_lengths = np.array([], dtype=int)
def reinstantiate(self, new_model_universe):
"""clone this detector """
"""STEP 1: Copy all contents of this detector"""
data, model_universe = self.data, new_model_universe
model_prior, cp_model = self.model_prior, self.cp_model
S1, S2, T = self.S1, self.S2, self.T
exo_data, num_exo_vars = self.exo_data, self.num_exo_vars
threshold = self.threshold
store_rl, store_mrl = self.store_rl, self.store_mrl
trim_type, notifications = self.trim_type, self.notifications
save_performance_indicators = self.save_performance_indicators
training_period = self.training_period
#DEBUG: Needs updating.
"""STEP 2: Create the new detector, and return it"""
new_detector = Detector(data, model_universe, model_prior, cp_model,
S1, S2, T, exo_data, num_exo_vars, threshold,
store_rl, store_mrl, trim_type,
notifications,
save_performance_indicators,
training_period)
return new_detector
def run(self, start=None, stop=None):
"""Start running the Detector from *start* to *stop*, usually from
the first to the last observation (i.e. default).
"""
"""set start and stop if not supplied"""
if start is None:
start = 1
if stop is None:
stop = self.T
"""run the detector"""
time_start = time.clock()
time2 = 0.0
for t in range(start-1, stop-1):
if t % self.notifications == 0 and time2 != 0.0:
print("Processing observation #" + str(int(t)))
print("Last iteration took " + str(time.clock() - time2) +
" seconds")
time2 = time.clock()
self.next_run(self.data[t,:], t+1)
self.execution_time = time.clock() - time_start
def next_run(self, y, t):
"""for a new observation *y* at time *t*, run the entire algorithm
and compute all quantities at the ProbabilityModel object and the
Detector object layer necessary
NOTE: The data structures in the ProbabilityModel objects grow from
size t-1 (or t, for the sufficient statistics) to size t (or t+1)
during 'next_run'. #DEBUG: To be added: check if prior_mean, prior_var, ... are S1xS2. If
# they are not, assume that they are provided in vector and
# full covariance matrix form & compress them into internal form
"""
"""STEP 1: If t==1, initialize *joint_probabilities* and the
predictive distributions.
If t>1, update the *joint_probabilities* of (y_{1:t}, r_t =r|q_t =q)
for all q in the model universe as well as the predictive
distributions associated with each model.
Note: Calls functions 'update_joint_log_probabilities' and
'update_predictive_distributions'. The latter function is on
ProbabilityModel level, and calls 'evaluate_predictive_log_distr'
from the Model level. If we are interested in retrieving the
negative log likelihood, the
'one_step_ahead_predictive_log_probs' are also retrieved there."""
"""If we want the fixed-parameter NLL, we need to compute and store it
before we update the joint log prob"""
#if(self.save_performance_indicators and t>self.training_period):
#self.compute_negative_log_likelihood_fixed_pars(y,t) #these need to
#INSERT: alpha_param update here!
"""For all parameter-DPD models in our model universe, first update
their value of alpha_param"""
if self.max_lag_length + 3 < t and self.alpha_param_opt_t < t:
#only do if MAP has changed last iteration!
#DEBUG: Version of Code used for paper results!
if t > 3:
if self.CPs[t-2][-1][0] != self.CPs[t-3][-1][0]:
self.alpha_opt_count = self.alpha_opt_count + 1
self.update_alpha_param(y,self.alpha_opt_count, True)
else:
#I.e., do not update if the CPs have not changed.
self.update_alpha_param(y,self.alpha_opt_count, False)
# if t > 3:
# #if self.CPs[t-2][-1][0] != self.CPs[t-3][-1][0]:
# self.alpha_opt_count = self.alpha_opt_count + 1
# self.update_alpha_param(y,self.alpha_opt_count, True)
#else:
#I.e., do not update if the CPs have not changed.
# self.update_alpha_param(y,self.alpha_opt_count, False)
self.update_all_joint_log_probabilities(y, t)
"""STEP 1+: If we want to save the negative log likelihood, do it here
because the run-length and model distro is not yet updated, but we
already have all the evaluated log probs y_t|y_{1:t-1},r_t-1,m_t-1"""
if(self.save_performance_indicators and t>self.training_period):
#DEBUG: Implement function
self.save_negative_log_likelihood(t)
#self.save_negative_log_likelihood_fixed_pars(t)
self.save_MSE(y,t)
"""STEP 2: Collect the model-specific evidences and update the overall
evidence by summing them up. 'update_evidence' is a simple wrapper
function for convenience"""
self.update_log_evidence()
"""STEP 3: Trim the run-length distributions in each model. Next,
update the distributions (q_t=q, r_t=r|y_{1:t}) for each
run-length r and each model in the model universe q, store the
result in *self.model_and_run_length_distr*"""
self.trim_run_length_log_distributions(t)
#self.update_model_and_run_length_log_distribution(t)
self.update_run_length_log_distribution(t) #this is stored on detector level
#and computed from the model objects
#DEBUG: This was meant to provide numerical stability, but doesn't work
# if (not self.not_all_initialized and
# self.generalized_bayes_rld == "power_divergence"):
# self.rescale_DPD_run_length_log_distribution(t) #avoid numerical issues
"""STEP 5: Using the results from STEP 3, obtain a prediction for the
next spatial lattice slice, which you preferably should either store,
output, or write to some location"""
if not self.not_all_initialized:
self.prediction_y(y, t)
self.storage(t)
"""STEP 8: Update alpha if you do power-divergence based inference.
Only start doing this once all models have been initialized"""
if ((not self.not_all_initialized) and
self.generalized_bayes_rld == "power_divergence" and
self.alpha_rld_learning and
self.alpha_rld_opt_t < t):
#only do this step if MAP CP has changed!
if t >= 3:
if self.CPs[t-2][-1][0] != self.CPs[t-3][-1][0]:
#alpha opt count already updated in param update
#self.alpha_opt_count = self.alpha_opt_count + 1
self.update_alpha_rld(y,self.alpha_opt_count,True)
else:
self.update_alpha_rld(y,self.alpha_opt_count,False)
"""STEP 4: Check if all models have been initialized. This only needs
to be checked for BVAR models. If they have all been initialized last
round (i.e., self.not_all_initialized = False), then there is never any
need to check in any of the succeeding rounds again"""
if self.not_all_initialized:
count_total, count_init = 0,0
for model in self.model_universe:
if model.has_lags:
if (t - model.lag_length >=1):
count_total += 1
count_init += 1
else:
count_total +=1
if count_total > count_init:
self.not_all_initialized = True
else:
self.not_all_initialized = False
"""STEP 6: Using the results from STEP 3, obtain a MAP for the
most likely segmentation & models per segment using the algorithm of
Fearnhead & Liu (2007)"""
#if not self.not_all_initialized:
self.MAP_estimate(t)
#NEEDS FURTHER INVESTIGATION
"""STEP 7: For each model in the model universe, update the priors to
be the posterior expectation/variance"""
if not self.not_all_initialized:
self.update_priors(t)
def rescale_DPD_run_length_log_distribution(self, t):
"""STEP 1: Compute the mean of all joint log probs (note that since
they are computed with the DPD, they will be positive!)"""
if self.jlp_scale is None:
log_scale_new = (np.max([model.joint_log_probabilities
for model in self.model_universe]) - 1)
# log_scale_new = max(1.0, scipy.misc.logsumexp([
# model.joint_log_probabilities
# for model in self.model_universe]) - 1)
rescaler_for_old_obs = None
else:
log_scale_old = self.jlp_scale
# max_ = (np.max([model.joint_log_probabilities
# for model in self.model_universe]) - 1)
min_ = (np.min([model.joint_log_probabilities
for model in self.model_universe]) - 1)
# mean_ = ((1.0/(self.Q + len(self.all_retained_run_lengths))) *
# scipy.misc.logsumexp([model.joint_log_probabilities
# for model in self.model_universe]))
# log_scale_new = scipy.misc.logsumexp(
# [model.joint_log_probabilities
# for model in self.model_universe])
log_scale_new = min_ #0.5 * max(max_-min_, 2) #min(log_scale_old,
# (np.max([model.joint_log_probabilities
# for model in self.model_universe]) - 1))
# log_scale_new = max(1.0, scipy.misc.logsumexp([model.joint_log_probabilities
# for model in self.model_universe]))
rescaler_for_old_obs = log_scale_old - log_scale_new
# -1 = nothing will be negative
# only applied to most recent obs = np.log(scale_old/scale_new)
self.jlp_scale = log_scale_new
# log_scale_new = scipy.misc.logsumexp([model.joint_log_probabilities
# for model in self.model_universe])
# """STEP 2: Use this mean to rescale all of them"""
#for model in self.model_universe:
#probabilitiy level call
#model.rescale_DPD_run_length_distribution(log_scale_new,
# None, #rescaler_for_old_obs, #rescaler_for_old_obs, #rescaler_for_old_obs,
# t)
def update_alpha_param(self, y, t, update=True):
"""Use the posterior expectation for alpha + eps and alpha - eps to
approximate the gradient for Loss(PredError(alpha)) w.r.t. alpha.
If alpha_param_learning = individual, then you optimize each DPD model
independently. If learning = together, optimize together"""
"""STEP 1: If we learn jointly over all DPD models, get their model
posterior probabilities s.t. we can get
E[y_t|y_1:t-1, alpha_t-1 + eps] = sum(
E[y_t|y_1:t-1, m_t-1, alpha_t-1 + eps]) *
P(m_t-1|y_1:t-1,alpha_t-1 + eps)
)
where we have stored P(m_t-1|y_1:t-1,alpha_t-1 + eps) from before"""
if self.alpha_param_learning == "together":
"""STEP 1A: If we optimize alpha_param over all models"""
#number_DPD_models = 0
eps = self.eps_gen(t-1) #as the eps is from the previous iteration
DPD_model_indices = []
list_model_log_evidences_p_eps = []
list_model_log_evidences_m_eps = []
list_post_mean_p_eps = []
list_post_mean_m_eps = []
"""STEP 1A.1: count number of DPD models and retrieve both their
model evidences and posterior expectations"""
for (m, model) in zip(range(0, self.Q), self.model_universe):
if isinstance(model, BVARNIGDPD):
"""retrieve P(m_t-1, y_1:t-1|alpha_t-1 +/- eps)"""
list_model_log_evidences_p_eps.append(
model.model_log_evidence_p_eps)
list_model_log_evidences_m_eps.append(
model.model_log_evidence_m_eps)
"""retrieve E[y_t|m_t-1, y_1:t-1, alpha_t-1 +/- eps]"""
list_post_mean_p_eps.append(model.
post_mean_p_eps)
list_post_mean_m_eps.append(model.
post_mean_m_eps)
"""get index of this DPD model"""
DPD_model_indices.append(m)
"""STEP 1A.2: compute the posterior means for alpha +/- eps"""
"""STEP 1A.2.1: Get the model posteriors for alpha +/- eps"""
total_evidence_p_eps = scipy.misc.logsumexp(
list_model_log_evidences_p_eps)
total_evidence_m_eps = scipy.misc.logsumexp(
list_model_log_evidences_m_eps)
model_posteriors_p_eps = np.exp(
np.array(list_model_log_evidences_p_eps)
- total_evidence_p_eps)
model_posteriors_m_eps = np.exp(
np.array(list_model_log_evidences_m_eps)
- total_evidence_m_eps)
"""STEP 1A.2.2: Get the posterior mean"""
post_mean_p_eps = (np.array(list_post_mean_p_eps)
* model_posteriors_p_eps[:,np.newaxis])
post_mean_m_eps = (np.array(list_post_mean_m_eps)
* model_posteriors_m_eps[:,np.newaxis])
"""STEP 1A.3: Compute predictive loss and take gradient step"""
#DEBUG: use more general loss functions
loss_p_eps = self.loss_param_learning(post_mean_p_eps -
y.flatten(), self.C)
loss_m_eps = self.loss_param_learning(post_mean_m_eps -
y.flatten(), self.C)
self.gradient_alpha_param = (self.gradient_alpha_param +
(loss_p_eps - loss_m_eps)/(2*eps))
#DEBUG: Use more general step sizes
self.gradient_alpha_param_count = (self.gradient_alpha_param_count
+ 1)
#bound alpha_param between pow(10,-10) and 10
if update:
step_size = self.step_size_param_learning(t)
#abs_increment = min(abs(step_size * self.gradient_alpha_param),
# 0.05)
abs_increment = min(0.1,
step_size *
(1.0/self.gradient_alpha_param_count)*
self.gradient_alpha_param)
self.alpha_param = min(
max(
pow(10,-10),
self.alpha_param -
abs_increment *
np.sign(self.gradient_alpha_param) #step_size * gradient_alpha_param
),
10.0
)
self.gradient_alpha_param = 0
self.gradient_alpha_param_count = 0
#print("detector alpha param", self.alpha_param)
"""STEP 1A.4: For each DPD model, update alpha_param"""
for m in DPD_model_indices:
self.model_universe[m].alpha_param = self.alpha_param
self.model_universe[m].alpha_param_list.append(
self.alpha_param)
elif self.alpha_param_learning == "individual":
"""STEP 1B: If we optimize alpha_param individually"""
for (m, model) in zip(range(0, self.Q), self.model_universe):
if isinstance(model, BVARNIGDPD):
#eps = self.eps_gen(t-1)
#DEBUG: use more general loss functions
loss_p_eps = np.sum(np.abs(model.post_mean_p_eps -
y.flatten()))
loss_m_eps = np.sum(np.abs(model.post_mean_m_eps -
y.flatten()))
self.gradient_alpha_param[m] = (self.gradient_alpha_param[m] +
(loss_p_eps - loss_m_eps)/
(2 * model.eps))
self.gradient_alpha_param_count[m] = (
self.gradient_alpha_param_count[m]+ 1)
#bound alpha_param between pow(10,-10) and 10
#scale the step size by model complexity to counteract
#higher variance for more complex models
if update:
#print("PARAM gradient size:", self.gradient_alpha_param[m]/self.gradient_alpha_param_count[m])
step_size = self.step_size_param_learning(t)
abs_increment = min(0.1,
step_size *
(1.0/self.gradient_alpha_param_count[m])*
self.gradient_alpha_param[m])
model.alpha_param = min(
max(
pow(10,-10),
model.alpha_param -
abs_increment *
np.sign(self.gradient_alpha_param[m]) #step_size * gradient_alpha_param
),
10.0
)
# model.alpha_param = min(
# max(
# pow(10,-10),
# model.alpha_param
# + step_size * (1.0/(model.num_regressors+1)) *
# self.gradient_alpha_param[m]
# ),
# 10.0
# )
#print("model alpha param", model.alpha_param)
model.alpha_param_list.append(model.alpha_param)
self.gradient_alpha_param[m] = 0
self.gradient_alpha_param_count[m] = 0
def update_run_length_log_distribution(self, t):
"""This function aggregates the models' individual model and run-length
log probability appropriately s.t. we end up with the proper run-length
log distribution for which the recursions are shown in Fearnhead & Liu"""
"""STEP 1: Get all growth probabilities & the CP probability"""
"""STEP 1.1: Get all models that have been initialized"""
indices_initialized_models = []
for (m, model) in zip(range(0, self.Q), self.model_universe):
"""if the model has no lags, give it 'lag 1'"""
if model.has_lags:
model_lag = model.lag_length
else:
model_lag = 0
"""if the model already contains joint_log_probabilities, use it"""
if model_lag < t: #debug: model_lag =< t?
indices_initialized_models.append(m)
num_initialized = int(len(indices_initialized_models))
"""Check if this is the first time we have an initialized model. If so,
we need to initialize the quantity self.run_length_log_distr. If we
have no initialized model yet, leave the function immediately"""
if (not self.first_model_initialized) and num_initialized > 0:
"""initialize run-length distro s.t. we can work with it"""
self.first_model_initialized = True
self.run_length_log_distr = 0 # log(1) = 0
elif (not self.first_model_initialized):
"""skip the rest of the function"""
return None
"""STEP 1.3: For all initialized models, retrieve the run lengths and
aggregate them all into *all_run_lengths*"""
has_both = False #boolean. If we have run lengths for t-1 and >t-1, flag
all_run_lengths = np.array([])
for model in self.model_universe[indices_initialized_models]:
"""Get all run lengths retained across models"""
all_run_lengths = np.union1d(all_run_lengths,
model.retained_run_lengths)
"""if we have the run-lengths for t-1 and >t-1, flag up and later
place one index twice into the all_run_lengths"""
if model.retained_run_lengths[-1] == model.retained_run_lengths[-2]:
has_both = True
"""Add run length for >t-1 if necessary"""
if has_both:
all_run_lengths = np.append(all_run_lengths, t)#all_run_lengths[-1])
"""make sure that the run-lengths we retain can be used to access
the array elements that we want."""
all_run_lengths = all_run_lengths.astype(int)
"""STEP 1.4: Create the model and run-length distr s.t. we have no
zero mass entries"""
length_rls = int(len(all_run_lengths))
model_rl_log_distributions = (-np.inf) * np.ones((
self.Q, length_rls))
"""STEP 1.5: loop over the initialized models, and fill in the model
and run-length distro"""
for index in indices_initialized_models:
model = self.model_universe[index]
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths = np.in1d(
all_run_lengths, model.retained_run_lengths)
"""If the current model has retained run length r>t-1, set it
to t."""
if (model.retained_run_lengths[-1] == model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[
-1] = True
"""get P(r_t,m_t|y_1:t) = P(r_t,m_t,y_1:t)/P(y_1:t)"""
model_rl_log_distributions[index,
model_indices_indicators_relative_to_all_run_lengths] = (
model.joint_log_probabilities - self.log_evidence )
#+ np.log(priors_initialized_models[m]))
"""STEP 1.4: we need to sum over the columns (i.e. the models).
One needs log sum exp for this, since all is stored in log form.
P(r_t|y_1:t) = \sum_m P(r_t,m_t|y_1:t)"""
run_length_log_distr = misc.logsumexp(
model_rl_log_distributions, axis=0)
"""STEP 2: Store to object, and if all run lengths are to be stored,
also store it to another object"""
self.model_and_run_length_log_distr = model_rl_log_distributions
self.run_length_log_distr = run_length_log_distr
self.all_retained_run_lengths = all_run_lengths
"""STEP 3: Store it if needed"""
if self.store_mrl or self.store_rl:
self.storage_all_retained_run_lengths.append(
self.all_retained_run_lengths)
if self.store_rl:
self.storage_run_length_log_distr.append(self.run_length_log_distr)
if self.store_mrl:
self.storage_model_and_run_length_log_distr.append(
self.model_and_run_length_log_distr)
#IMPLEMENTED FOR ALL SUBCLASSES IF predictive_probabilities WORK IN SUBLCASS
# update_joint_probabilities WORK
def update_all_joint_log_probabilities(self, y, t):
"""Let the individual objects in *model_universe* compute their growth
and CP probabilities, via 'update_joint_probabilities' in each.
The strucutre is: (1) update the joint log probs (or initialize the
model if first observation), which is done by calling probability model
functions, and (2) update the predictive probabilities using the
new observation y, which is done differently in each model object.
"""
"""STEP 0: Get which of the models are or will be
initialized at t for redistributing the model prior later. """
index_initialized = []
for (m,model) in zip(range(0,self.Q),self.model_universe):
if model.has_lags and ((t+1) - model.lag_length >= 1):
index_initialized.append(m)
elif not model.has_lags:
index_initialized.append(m)
prior_rescaling_factor = np.sum(self.model_prior[index_initialized])
#if not self.first_model_initialized:
#we need the initial run-length distro
"""If we need to do hyperparameter learning for the generalized
Bayesian case (e.g., learning alpha for Power divergence)"""
"""Initialize these quantities. If we enter the next if-statement, they
might be changed"""
log_model_posteriors_der_m = None
log_model_posteriors_der_sign_m = None
log_CP_evidence_der = None
log_CP_evidence_der_sign = None
if (self.generalized_bayes_rld == "power_divergence"
and self.alpha_rld_learning
and t>1):
#DEBUG: Need to be computed from all models
"""Compute the model posterior derivative w.r.t. alpha
(in log form)"""
"""Check if at least one model is already initialized"""
at_least_one_model_initialized = np.any([(model.has_lags and
((t) - model.lag_length)>1) or ( not model.has_lags )
for model in self.model_universe])
if at_least_one_model_initialized:
"""collect all derivatives of all models as well as the
joint probabilities of all models. Sum over models per run-
length afterwards"""
all_log_probs = -np.inf*np.ones(
(self.Q, np.size(self.all_retained_run_lengths)))
all_log_alpha_derivatives = -np.inf*np.ones(
(self.Q, np.size(self.all_retained_run_lengths)))
all_log_alpha_derivatives_sign = np.zeros(
(self.Q, np.size(self.all_retained_run_lengths)))
for m, model in zip(range(0,self.Q), self.model_universe):
#DEBUG: Unclear if the log derivatives joint log probs
# are going to be one entry too many (for r=0)
#DEBUG: Indexing!
"""Only retrieve quantities of models that have seen data
already"""
warmed_up = ((model.has_lags and ((t) - model.lag_length)>1) or
( not model.has_lags ))
if warmed_up:
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths=(
np.in1d(self.all_retained_run_lengths,
model.retained_run_lengths))
if (model.retained_run_lengths[-1] ==
model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[-1] = True
# print('rl', np.size(model_indices_indicators_relative_to_all_run_lengths))
# print(model_indices_indicators_relative_to_all_run_lengths)
# print(self.all_retained_run_lengths)
# print('jlp', np.size(model.joint_log_probabilities))
# print('alp', np.size(all_log_probs[m,:]))
#DEBUG: The initial log_alpha_derivative_joint_probs
# has to be in the right size relative to lag l.
#DEBUG: Initialized to None, so initialize it when you
# arrive here the first time by checking if = None
"""Check if they have been initialized already. If not,
we need to do that now"""
if (model.log_alpha_derivatives_joint_probabilities
is None):
num_needed = np.sum(
model_indices_indicators_relative_to_all_run_lengths)
model.log_alpha_derivatives_joint_probabilities = (
-np.inf * np.ones(num_needed))
model.log_alpha_derivatives_joint_probabilities_sign = (
np.ones(num_needed))
"""fill retrieved values into relevant position"""
all_log_alpha_derivatives[m,
model_indices_indicators_relative_to_all_run_lengths]=(
model.log_alpha_derivatives_joint_probabilities )
all_log_alpha_derivatives_sign[m,
model_indices_indicators_relative_to_all_run_lengths]=(
model.log_alpha_derivatives_joint_probabilities_sign)
#DEBUG: it seems that we don't have enough retained
# indices in the relative ones
all_log_probs[m,
model_indices_indicators_relative_to_all_run_lengths]=(
model.joint_log_probabilities)
"""sum over the models for each run-length, needed for the
derivative of P(m_t|m_t-1, r_t-1, y_1:t-1), see (4) in
handwritten notes. Dimension is Rx1"""
model_sums_derivatives, model_sums_derivatives_sign = (
scipy.misc.logsumexp(
a = all_log_alpha_derivatives,
b = all_log_alpha_derivatives_sign,
return_sign = True,
axis=0
))
model_sums = scipy.misc.logsumexp(
a = all_log_probs,
axis = 0
)
"""Get the two expressions that added together give you the
derivative of the joint probabilities in log-form"""
#Debug: In expr_1, we have MxR - M, make sure dimensions
# match. expr_2 has dimension R
#DEBUG: check expr_2 and fix the dimension
expr_1 = all_log_alpha_derivatives - model_sums
sign_1 = all_log_alpha_derivatives_sign
expr_2 = -2* model_sums + model_sums_derivatives + all_log_probs
sign_2 = (-1) * model_sums_derivatives_sign
#print("expr_1", expr_1)
#print("expr_2", expr_2)
# print("sign_1", sign_1.shape)
# print("sign_2", sign_2.shape)
expr, sign = scipy.misc.logsumexp(
a = np.array([expr_1, expr_2]),
b = np.array([sign_1, sign_2 *
np.ones(self.Q)[:,np.newaxis]]),
return_sign = True,
axis=0
)
#Note: We only have the growth-probabilities in here!
# the CP probability derivatives are computed below!
log_model_posteriors_der = expr
log_model_posteriors_der_sign = sign
"""Compute the CP evidence derivative w.r.t. alpha
(in log form). It turns out that the computation decomposes
s.t. we have
derivative(one-step-pred) * CP_evidence * q(m_t) +
one-step-pred * derivative(CP_evidence) * q(m_t).
Since we don't want to deal with the one-step-ahead
predictives here, all we need to do is compute
derivative(CP_evidence) and pass it on. The full
computation is then done when we update the probs."""
#DEBUG: Where does the evidence come from?
#DEBUG: Unclear what we compute here and inside probability_model!
_1, _2 = misc.logsumexp(
a = np.log(self.cp_model.hazard_vector(1, t)) +
all_log_alpha_derivatives, # +
#self.log_evidence,
b = all_log_alpha_derivatives_sign,
return_sign = True)
log_CP_evidence_der = _1
log_CP_evidence_der_sign = _2
# else:
# log_model_posteriors_der_m = None
# log_model_posteriors_der_sign_m = None
# log_CP_evidence_der = None
# log_CP_evidence_der_sign = None
#q = 0
for (m,model) in zip(range(0,self.Q),self.model_universe):
"""STEP 1: Check if it is the first observation, and initialize the
joint distributions in each model object if so"""
#DEBUG: t is t-1!
initialization_required = False
if model.has_lags and ((t) - model.lag_length == 1):
initialization_required = True
elif (not model.has_lags) and t == 1:
initialization_required = True
if initialization_required:
"""This command gives an initialization of (i) the
*joint_probabilities*, (ii) the predictive distributions (i.e.,
the sufficient statistics), and (iii) the *model_evidence*
of each model."""
"""NOTE: We need to initialize BVAR at time t-lag_length!"""
if model.has_lags or isinstance(model, BVARNIG):
"""If we have a BVAR model, we need to pass data of
sufficient lag length to the initialization."""
#DEBUG: exo_selection in correct dimension? What is dim of
# exo_data?
#DEBUG: exo data assumed to be contemporaneous!
"""STEP I: Get endogeneous data"""
X_endo = self.data[:model.lag_length+1,:]
Y_2 = self.data[model.lag_length+1,:]
"""STEP II: Get exogeneous data (if needed)"""
if model.exo_bool:
X_exo = self.exo_data[model.lag_length,
model.exo_selection,:]
X_exo_2 = self.exo_data[model.lag_length+1,
model.exo_selection,:]
else:
X_exo = X_exo_2 = None
"""STEP III: Use exo and endo data to initialize model"""
#new_prior = self.model_prior[m]/np.sum(self.)
model.initialization(X_endo, X_exo, Y_2, X_exo_2,
self.cp_model,
self.model_prior[m]/prior_rescaling_factor)
else:
"""Otherwise, just pass the first observation"""
#DEBUG: CONSTANT FITTING ADAPTION
# if isinstance(model, BVARNIG):
# """STEP I: Get endogeneous data"""
# X_endo = self.data[:model.lag_length+1,:]
# Y_2 = self.data[model.lag_length+1,:]
# """STEP II: Get exogeneous data (if needed)"""
# if model.exo_bool:
# X_exo = self.exo_data[model.lag_length,
# model.exo_selection,:]
# X_exo_2 = self.exo_data[model.lag_length+1,
# model.exo_selection,:]
# else:
# X_exo = X_exo_2 = None
# model.initialization(None, X_exo, Y_2, X_exo_2,
# self.cp_model,
# self.model_prior[m]/prior_rescaling_factor)
#else:
model.initialization(y, self.cp_model,
self.model_prior[m])
else:
"""Make sure that we only modify joint_log_probs & predictive
distributions for BVAR models for which t is large enough to
cover the lag length."""
#DEBUG: Use x_exo if BVAR
"""STEP 1: Within each ProbabilityModel object, compute its
joint probabilities, i.e. the growth- & CP-probabilities
associated with the model"""
#"""get P(r_t,m_t|y_1:t) = P(r_t,m_t,y_1:t)/P(y_1:t)"""
#model_rl_log_distributions[index,
# model_indices_indicators_relative_to_all_run_lengths] = (
# model.joint_log_probabilities -self.log_evidence )
# #+ np.log(priors_initialized_models[m]))
"""model_and_run_length_log_distr stores run-lengths for
ALL models, so it will have -np.inf entries at
run-lengths retained for other models. That's why we need
to access its retained run lengths"""
warmed_up = ((model.has_lags and ((t) - model.lag_length)>1) or
( not model.has_lags ))
#warmed_up_plus_one = (
# (model.has_lags and ((t) - model.lag_length)>2) or
# ( not model.has_lags and t > 1))
if warmed_up:
#print("self.model_and_run_length_log_distr[m,:] ",
# self.model_and_run_length_log_distr)
#print("self.run_length_log_distr ",
# self.run_length_log_distr)
#print("t ", t)
#print("lag length ", model.lag_length)
#print("joint log probs ", model.joint_log_probabilities)
#DEBUG: Incorrect! Alignment of run-length and mrl distro
# does not hold!
log_model_posteriors = (
self.model_and_run_length_log_distr[m,:] -
self.run_length_log_distr)
log_model_posteriors = log_model_posteriors[np.where(
log_model_posteriors> -np.inf)]
#print("log model posteriors: ", log_model_posteriors)
"""the log CP evidence is computed using the joint probs
as well as the hazard function/cp model"""
#DEBUG: needs to take into account vector-form of hazard
# vector for more complicated hazard functions
#print("log evidence", self.log_evidence)
#print("model log evidences:", [m.model_log_evidence for m in self.model_universe])
#print("joint log probs", model.joint_log_probabilities)
#print("hazard", np.log(self.cp_model.hazard_vector(1, t)))
log_CP_evidence = misc.logsumexp(
np.log(self.cp_model.hazard_vector(1, t)) +
self.model_and_run_length_log_distr +
self.log_evidence)
#model.joint_log_probabilities)
#print("log CP evidence:", log_CP_evidence)
if (self.generalized_bayes_rld == "power_divergence"
and self.alpha_rld_learning):
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths=(
np.in1d(self.all_retained_run_lengths,
model.retained_run_lengths))
if (model.retained_run_lengths[-1] ==
model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[-1] = True
"""Retrieve m-th entry of the calculated quantities"""
log_model_posteriors_der_m = (
log_model_posteriors_der[m,
model_indices_indicators_relative_to_all_run_lengths])
log_model_posteriors_der_sign_m = (
log_model_posteriors_der_sign[m,
model_indices_indicators_relative_to_all_run_lengths])
#DEBUG: needs to be one-dimensional!
#log_CP_evidence_der_m = (log_CP_evidence_der[m])
#log_CP_evidence_der_sign_m = (
# log_CP_evidence_der_sign[m])
"""NOTE: If it is a BVAR model, we need the exogeneous vars,
and we also need to make sure that lag < t"""
if(model.has_lags and ((t) - model.lag_length)>1):
"""NOTE: This needs to be adjusted once we allow for
exogeneous variables"""
#We want the model posteriors to be passed in only from
#this model!
#DEBUG: Add a function for alpha_param learning step here.
# Needs to happen before the joint log probs are
# updated (as then, we can already use the new alpha
# for the new joint log probs). Make it a probability
# model level function that does nothing by default,
# unless you extend it in your subclass.
if (t - model.lag_length)>2 and self.alpha_param_opt_t <= t:
#DEBUG: This calls aDPD_joint_log_prob_updater, which
# in turns calls the integral computation.
model.alpha_param_gradient_computation(y=y, t=t,
cp_model = self.cp_model,
model_prior =
self.model_prior[m]/prior_rescaling_factor,
log_model_posteriors = log_model_posteriors,
log_CP_evidence = log_CP_evidence,
eps = self.eps_param_learning(t))
model.update_joint_log_probabilities(
y=y,t=t, cp_model = self.cp_model,
model_prior =
self.model_prior[m]/prior_rescaling_factor,
log_model_posteriors = log_model_posteriors,
log_CP_evidence = log_CP_evidence,
log_model_posteriors_der = log_model_posteriors_der_m,
log_model_posteriors_der_sign =
log_model_posteriors_der_sign_m,
log_CP_evidence_der = log_CP_evidence_der,
log_CP_evidence_der_sign = log_CP_evidence_der_sign,
do_general_bayesian_hyperparameter_optimization = (
warmed_up))
#DEBUG: CONSTANT FITTING ADAPTION
elif( not model.has_lags ):
"""NOTE: This does not allow for exogeneous variables"""
#impose condition s.t. BVAR is not called
if t > 2 and self.alpha_param_opt_t <= t:
model.alpha_param_gradient_computation(y=y, t=t,
cp_model = self.cp_model,
model_prior =
self.model_prior[m]/prior_rescaling_factor,
log_model_posteriors = log_model_posteriors,
log_CP_evidence = log_CP_evidence,
eps = self.eps_param_learning(t))
model.update_joint_log_probabilities(
y=y,t=t, cp_model = self.cp_model,
model_prior =
self.model_prior[m]/prior_rescaling_factor,
log_model_posteriors = log_model_posteriors,
log_CP_evidence = log_CP_evidence,
log_model_posteriors_der = log_model_posteriors_der_m,
log_model_posteriors_der_sign =
log_model_posteriors_der_sign_m,
log_CP_evidence_der = log_CP_evidence_der,
log_CP_evidence_der_sign = log_CP_evidence_der_sign,
do_general_bayesian_hyperparameter_optimization = (
warmed_up))
"""STEP 2: Update the predictive probabilities for each model
inside the associated ProbabilityModel object. These are
used in the 'update_joint_probabilities' call for the next
observation. In the case of NaiveModel and other conjugate
models, this step amounts to updating the sufficient
statistics associated with the model"""
"""NOTE: If it is a BVAR model, we need the exogeneous vars,
and we also need to make sure that lag < t"""
#DEBUG: CONSTANT FITTING ADAPTION
if(model.has_lags and ((t) - model.lag_length)>1):
y_tm1 = self.data[t-2,:]
if model.exo_bool:
x_exo_t = self.exo_data[t,model.exo_selection,:]
x_exo_tp1 = self.exo_data[t+1,model.exo_selection,:]
else:
x_exo_t = x_exo_tp1 = None
if isinstance(model, BVARNIGDPD):
"""If BVARNIGDPD model, we need the CP probability to
obtain the prior weights in the SGD step"""
model.update_predictive_distributions(y, y_tm1,
x_exo_t, x_exo_tp1, t, self.cp_model.hazard(0))
else:
"""If not DPD model, we don't need CP probability"""
model.update_predictive_distributions(y, y_tm1,
x_exo_t, x_exo_tp1, t)
elif(not model.has_lags):
if isinstance(model, BVARNIG):
"""If it is a BVARNIG model, call the more complicated
functions"""
y_tm1 = self.data[t-2,:]
if model.exo_bool:
x_exo_t = self.exo_data[t,model.exo_selection,:]
x_exo_tp1 = self.exo_data[t+1,
model.exo_selection,:]
else:
x_exo_t = x_exo_tp1 = None
if isinstance(model, BVARNIGDPD):
"""If BVARNIGDPD model, we need the CP probability
to obtain the prior weights in the SGD step"""
model.update_predictive_distributions(y, y_tm1,
x_exo_t, x_exo_tp1, t, \
self.cp_model.hazard(0))
else:
"""If not DPD model, we don't need CP probability"""
model.update_predictive_distributions(y, y_tm1,
x_exo_t, x_exo_tp1, t)
else:
model.update_predictive_distributions(y, t)
def update_alpha_rld(self,y,t, update=True):
"""Using a loss function that can be specified as input, update alpha
using stochastic gradient descent"""
"""STEP 1: Retrieve the logs of the alpha-derivatives in each model"""
num_run_lengths = int(len(self.all_retained_run_lengths))
all_log_alpha_derivatives = -np.inf*np.ones(
(self.Q, num_run_lengths))
all_log_alpha_derivatives_sign = np.zeros(
(self.Q, num_run_lengths))
all_log_probs = -np.inf*np.ones(
(self.Q, num_run_lengths))
#all_log_one_step_preds = -np.inf*np.ones((self.Q, num_run_lengths))
for m, model in zip(range(0,self.Q), self.model_universe):
#DEBUG: Unclear if the log derivatives joint log probs
# are going to be one entry too many (for r=0)
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths = np.in1d(
self.all_retained_run_lengths, model.retained_run_lengths)
"""If the current model has retained run length r>t-1, set it
to t."""
if (model.retained_run_lengths[-1] == model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[
-1] = True
all_log_alpha_derivatives[m,
model_indices_indicators_relative_to_all_run_lengths] = (
model.log_alpha_derivatives_joint_probabilities )
all_log_alpha_derivatives_sign[m,
model_indices_indicators_relative_to_all_run_lengths] = (
model.log_alpha_derivatives_joint_probabilities_sign)
all_log_probs[m,
model_indices_indicators_relative_to_all_run_lengths] = (
model.joint_log_probabilities)
#needed if we base loss on P(y_t|y_1:t-1) PROLBEM: This happens AFTER the update, i.e.
#we have our mrld updated, but the old predictives
#all_log_one_step_preds[m,
# model_indices_indicators_relative_to_all_run_lengths] = (
# model.one_step_ahead_predictive_log_probs)
#r0_log_prob
"""STEP 2: Sum over all the joint log probs' derivatives"""
sum_derivatives, sum_derivatives_sign = scipy.misc.logsumexp(
a = all_log_alpha_derivatives,
b = all_log_alpha_derivatives_sign,
return_sign = True)
"""STEP 3: obtain the log of the gradient of P(r_t, m_t|y_1:t).
NOTE: np.abs(term_1_sign) gives you all the run-length entries per
model that are non-zero, so multiplying by it ensure we leave zero
entries zero!"""
term_1 = all_log_alpha_derivatives - self.log_evidence
term_1_sign = all_log_alpha_derivatives_sign
term_2 = sum_derivatives - 2.0*self.log_evidence + all_log_probs
term_2_sign = (-1) * sum_derivatives_sign * np.abs(term_1_sign)
run_length_and_model_log_der, run_length_and_model_log_der_sign = (
scipy.misc.logsumexp(
a = np.array([term_1, np.abs(term_1_sign) * term_2]),
b = np.array([term_1_sign, term_2_sign]),
return_sign = True,
axis = 0
))
"""STEP 4: Lastly, get the gradient of the posterior expectation
NOTE: This need not be the gradient. We could equivalently use any
posterior property Q that can be computed for each (r_t, m_t) in closed
form (i.e. we get a weighted posterior using the MRLD(r,m) * Q(r,m))"""
if True: #self.loss_type == "posterior_expectation":
"""STEP 4.1: Get the deviation from posterior expectation"""
resid = self.y_pred_mean.flatten() - y.flatten()
#self.y_pred_var
"""STEP 4.2: Get the derivative of the posterior expectation"""
post_mean_der = np.zeros(shape=(self.S1 * self.S2))
for (m, model) in zip(range(0, self.Q), self.model_universe):
"""Get the number of stored run lengths for this model"""
num_rl = np.size(model.retained_run_lengths)
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths = np.in1d(
self.all_retained_run_lengths, model.retained_run_lengths)
"""If the current model has retained run length r>t-1, set it
to t."""
if (model.retained_run_lengths[-1] == model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[
-1] = True
"""weighing expectation with model & run-length probabilities'
derivatives"""
post_mean_der = (post_mean_der +
np.sum(
np.reshape(model.get_posterior_expectation(t),
newshape = (num_rl, self.S1 * self.S2)) *
#overflow in exp!
(np.exp(run_length_and_model_log_der[m,
model_indices_indicators_relative_to_all_run_lengths]) *
run_length_and_model_log_der_sign[m,
model_indices_indicators_relative_to_all_run_lengths])
[:,np.newaxis],
axis = 0)
)
if False: #self.loss_type = "posterior_expectation"
post_prob_log = -np.inf
post_prob_der_log = -np.inf
post_prob_der_log_sign = 1.0
for (m, model) in zip(range(0, self.Q), self.model_universe):
"""Get the number of stored run lengths for this model"""
num_rl = np.size(model.retained_run_lengths)
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths = np.in1d(
self.all_retained_run_lengths, model.retained_run_lengths)
"""If the current model has retained run length r>t-1, set it
to t."""
if (model.retained_run_lengths[-1] == model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[
-1] = True
#DEBUG: Just done to ensure that we finish, root problem unclear
if (np.sum(model_indices_indicators_relative_to_all_run_lengths)
> np.size(model.one_step_ahead_predictive_log_probs)):
one_steps = np.insert(model.one_step_ahead_predictive_log_probs,
0, model.r0_log_prob)
else:
one_steps = model.one_step_ahead_predictive_log_probs
"""rlm log:"""
# print("mrl", self.model_and_run_length_log_distr[m][
# model_indices_indicators_relative_to_all_run_lengths].shape)
# print("one steps", one_steps.shape)
sum_ = scipy.misc.logsumexp(
a = np.array([
self.model_and_run_length_log_distr[m][
model_indices_indicators_relative_to_all_run_lengths],
one_steps
]))
post_prob_log = scipy.misc.logsumexp(
a = np.array([post_prob_log, sum_])
)
"""rlm log derivative"""
sum_, sign_ = scipy.misc.logsumexp(
a = np.array([
run_length_and_model_log_der[m,
model_indices_indicators_relative_to_all_run_lengths],
one_steps
]),
b = np.array([
run_length_and_model_log_der_sign[m,
model_indices_indicators_relative_to_all_run_lengths],
np.ones(num_rl)]),
return_sign = True)
post_prob_der_log, post_prob_der_log_sign = scipy.misc.logsumexp(
a = np.array([post_prob_der_log, sum_]),
b = np.array([post_prob_der_log_sign, sign_]),
return_sign = True)
# rlm_log_der = (np.exp(run_length_and_model_log_der[m,
# model_indices_indicators_relative_to_all_run_lengths])*
# run_length_and_model_log_der_sign[m,
# model_indices_indicators_relative_to_all_run_lengths])
# """rlm log""" #probably should leave everything in log form
# rlm_log = self.model_and_run_length_log_distr[m,
# model_indices_indicators_relative_to_all_run_lengths]
# post_prob= (post_prob +
# np.exp(model.one_step_ahead_predictive_log_probs) *
# np.exp(rlm_log))
# post_prob_der = (post_prob_der +
# np.exp(model.one_step_ahead_predictive_log_probs) *
# np.exp(rlm_log_der))
#resid = post_prob_log
"""STEP 4.3: Plug both into the loss to get the gradient"""
self.gradient_alpha_rld = (self.gradient_alpha_rld +
self.loss_der_rld_learning(resid.flatten(),
post_mean_der.flatten(),
self.C)
)
self.gradient_alpha_rld_count = self.gradient_alpha_rld_count + 1
# alpha_gradient = self.loss_der_rld_learning(resid.flatten(),
# post_mean_der.flatten(),
# self.C)
#DEBUG: Make constant steps
"""Note: Set number of observations you make before taking a gradient
step, i.e. we estimate the gradient with k observations"""
#k=1
"""STEP 4.4: Gradient descent step"""
#relative = pow(10, -1) * 5 * np.abs(self.alpha)
#t_eff = len(self.alpha_list) #number of updates
#C_1, C_2= 1, 1000 #C_1*((C_2+1)/(t_eff+C_2)) #ad hoc C_1 * np.exp(-C_2 * t)#
step_size = self.step_size_gen(t=t)#, alpha=self.alpha_rld)
min_increment, max_increment = 0.0000, 5/self.T #5/self.T #0.001
#grad_sign = np.sign(alpha_gradient)
min_alpha, max_alpha = pow(10,-5), 5
"""Note: this will simply be equal to alpha_gradient for standard
SGD, where we take a step at each obs"""
#self.gradient = self.gradient + (1.0/k)*alpha_gradient
if update:
#print("RLD gradient size:", self.gradient_alpha_rld/self.gradient_alpha_rld_count)
#print("gradient ", self.gradient)
"""Update step"""
#NOTE: Since our loss functions have MINIMA we want to find, we need to
# do gradient DESCENT, not ASCENT! (for log probability,
# we do need to do ascent though)
#DEBUG: bound the gradient step to avoid chaotic behaviour
grad_sign = np.sign(self.gradient_alpha_rld)
increment = max(min(max_increment,
step_size *
np.abs(self.gradient_alpha_rld) *
(1.0/ self.gradient_alpha_rld_count)),
min_increment)
self.alpha_rld = min(
max(self.alpha_rld - increment*grad_sign, min_alpha),
max_alpha)
self.alpha_list.append(self.alpha_rld)
"""STEP 4.5: Update the alphas inside the model objects"""
for model in self.model_universe:
#DEBUG: once we change alpha name in detector, we nee to
# do the same in models, too
model.alpha_rld = self.alpha_rld
self.gradient_alpha_rld_count = 0
self.gradient_alpha_rld = 0
@staticmethod
def step_size_gen(t, alpha = None):
"""gives you sequence 1/n"""
if alpha is not None:
g0 = min(alpha, 1.0)#pow(10,-10) #2*(alpha)
lamb = 10# max(2.0, alpha) #pow(10,10) #1.0 - alpha
step_size = g0/(1.0 + g0 * lamb * t)
return step_size
else:
g0 = 3.0 #pow(10,-10) #2*(alpha)
lamb = 0.5 # max(2.0, alpha) #pow(10,10) #1.0 - alpha
step_size = g0/(1.0 + g0 * lamb * t)
return step_size
#return pow(t, -1)
# if alpha is None:
# return (pow(t, -1))
# else:
# return (alpha*pow(t, -1))
@staticmethod
def step_size_gen_rld(t, alpha = None):
#slowly decreasing magnitude, but small step sizes
g0 = 0.05
lamb = 0.5
step_size = g0/(1.0 + g0 * lamb * t)
return step_size
@staticmethod
def eps_gen(t):
"""gives you sequence (n)^-0.25"""
return pow(t, -0.25)
@staticmethod
def squared_loss(resid,C):
"""multivariate squared loss function. Univariate output."""
return 0.5*np.sum(np.power(resid, 2))
@staticmethod
def absolute_loss(resid,C):
"""just returns the absolute loss, i.e. sum( |Y_pred - Y_t|_i )"""
return np.sum(np.abs(resid))
@staticmethod
def biweight_loss(resid, C):
"""Get biweight loss"""
smallerC = np.where(resid < C)
biggerC = int(len(resid) - len(smallerC))
return(0.5*np.sum(np.power(resid[smallerC],2))+ 0.5*biggerC*pow(C,2))
@staticmethod
def bounded_absolute_loss(resid, C):
"""Get biweight loss"""
smallerC = np.where(resid < C)
biggerC = int(len(resid) - len(smallerC))
return(np.sum(np.abs(resid[smallerC]))+ biggerC*C)
@staticmethod
def squared_loss_derivative(resid, post_mean_der,C):
"""Gives the deriative of sum((resid)^2) wrt alpha_rld"""
return(np.sum(2 * resid * post_mean_der))
@staticmethod
def absolute_loss_derivative(resid, post_mean_der,C):
"""returns deriative of sum(|resid|) wrt alpha_rld"""
return(np.sum(np.sign(resid) * post_mean_der))
@staticmethod
def biweight_loss_derivative(resid, post_mean_der, C):
"""gives derivative of the huber loss with constant C"""
smallerC = np.where(resid < C)
#note: Where resid > C, there we have a flat loss, i.e. gradient=0
return(np.sum(2 * resid[smallerC] * post_mean_der[smallerC]))
@staticmethod
def bounded_absolute_loss_derivative(resid, post_mean_der, C):
"""gives derivative of the huber loss with constant C"""
smallerC = np.where(resid < C)
#note: Where resid > C, there we have a flat loss, i.e. gradient=0
return(np.sum(np.abs(resid[smallerC]* post_mean_der[smallerC])))
#step_size_gen eps_gen
# @staticmethod
# def log_loss_derivative(log_prob):
# """returns 1/x"""
# return 1.0/np.exp(log_prob)
def save_negative_log_likelihood(self,t):
"""Get the negative log likelihood if you want to store it"""
#DEBUG: Unclear why model and run length log distr has different length
# Maybe because of trimming?
all_one_step_ahead_lklhoods_weighted = [
(self.model_universe[m].one_step_ahead_predictive_log_probs +
self.model_and_run_length_log_distr[m,
self.model_and_run_length_log_distr[m,:]> -np.inf])
#self.model_universe[m].retained_run_lengths])
#np.where(self.model_and_run_length_log_distr[m,:]> -np.inf)])
for m in range(0, self.Q)]
summed_up = -misc.logsumexp([item for entry in
all_one_step_ahead_lklhoods_weighted for item in entry])
self.negative_log_likelihood.append(summed_up)
#logsumexp
def compute_negative_log_likelihood_fixed_pars(self, y,t):
"""For comparison with GP, fix sigma^2 at the MAP when doing the
one-step-ahead prediction. Just compute them, store them later once
the run-length distro is updated"""
for (m,model) in zip(range(0, self.Q), self.model_universe):
if model.has_lags: #I.e., BVAR family
#do stuff differently, retrieve
model.save_NLL_fixed_pars(y,t)
def save_negative_log_likelihood_fixed_pars(self, t):
"""For comparison with GP, fix sigma^2 at the MAP when doing the
one-step-ahead prediction."""
all_one_step_ahead_lklhoods_weighted = [
(self.model_universe[m].one_step_ahead_predictive_log_probs_fixed_pars +
self.model_and_run_length_log_distr[m,
self.model_and_run_length_log_distr[m,:]> -np.inf])
for m in range(0, self.Q)]
#self.model_universe[m].retained_run_lengths])
#np.where(self.model_and_run_length_log_distr[m,:]> -np.inf)])
summed_up = -misc.logsumexp([item for entry in
all_one_step_ahead_lklhoods_weighted for item in entry])
self.negative_log_likelihood_fixed_pars.append(summed_up)
def save_MSE(self,y,t):
"""Get the MSE at t and store it"""
#DEBUG: Much more natural to do when we already compute posterior expectation...
#self.y_pred_mean - y
# DEBUG = True
# if (DEBUG and pow(self.y_pred_mean - y.reshape(self.S1, self.S2),2) > 25
# and isinstance(self.model_universe[0], BVARNIGDPD)):
# model = self.model_universe[0]
# all_exp = model.get_posterior_expectation(t)
# map_ = np.argmax(self.model_and_run_length_log_distr)
# max_rl = model.retained_run_lengths[map_]
# print("t = ", t)
# print("run length distro max at", max_rl)
# print("expectation at map", all_exp[map_])
# print("params at map", model.a_rt[map_], model.b_rt[map_], model.beta_rt[map_,:], model.L_rt[map_,:,:])
self.MSE.append(pow(self.y_pred_mean - y.reshape(self.S1, self.S2),2))
self.MAE.append(abs(self.y_pred_mean - y.reshape(self.S1, self.S2)))
#IMPLEMENTED FOR ALL SUBCLASSES IF model_evidence UPDATED CORRECTLY IN SUBLCASS
def update_log_evidence(self):
"""Sum up all the model-specific evidences from the submodels"""
self.log_evidence = scipy.misc.logsumexp([model.model_log_evidence
for model in self.model_universe])
#DEBUG: Not needed!
def update_model_and_run_length_log_distribution(self, t):
"""Using the updated evidence, calculate the distribution of the
run-lengths and models jointly by accessing each model in order to
retrieve the joint probabilities. These are then scaled by 1/evidence
and the result is stored as the new *model_and_run_length_distr*
NOTE: If one does NOT compute the MAP, then it is more efficient not to
store this quantity, and rather compute it directly when the next
observation y is predicted!
"""
"""For each model object in model_universe, get the associated
*joint_probabilities* np arrays, divide them by *self.evidence*
and store the result. Notice that at time t, we will have t+1 entries
in the joint_probabilities for r=0,1,...t-1, >t-1"""
"""STEP 1: Get the longest non-zero run-length. Keep in mind that we
may have r=t-1 and r>t-1, but both are stored as same run-length!"""
r_max, r_max2= 0,0
for q in range(0, self.Q):
retained_q = self.model_universe[q].retained_run_lengths
"""STEP 1.1: Check if in model q, we have a larger maximum
run-length than in previous models"""
r_max2 = max(np.max(retained_q), r_max)
if r_max2 >= r_max:
r_max = r_max2
"""STEP 1.2: If a new maximum was found, check if one retains
both r=t-1 and r>t-1 in this model. If so, advance r_max"""
if ((retained_q.shape[0]>1) and (retained_q[-1] ==
retained_q[-2])):
r_max = r_max + 1
#r_max = np.max( [model.retained_run_lengths
# for model in self.model_universe])
"""STEP 2: Initialize the model-and-run-length log distribution"""
self.model_and_run_length_log_distr = (-np.inf *
np.ones(shape=(self.Q, r_max + 1))) #Easier: t+1
"""STEP 3: Where relevant, fill it in"""
for i in range(0, self.Q):
"""STEP 3.1: Get the retained run-lengths"""
model = self.model_universe[i]
retained = model.retained_run_lengths
if ((retained.shape[0]>1) and (retained[-1] == retained[-2])):
retained = np.copy(model.retained_run_lengths)
retained[-1] = retained[-1] + 1
"""STEP 3.2: Update the model-and-run-length-log-distribution
corresponding to the current model being processed"""
#DEBUG: Make sure that BVARNIG just has -inf, -inf in there.
self.model_and_run_length_log_distr[i,retained]=(
model.joint_log_probabilities - model.model_log_evidence)
"""STEP 4: If we want to store the run-length distribution at each
time point, do so here"""
if self.store_mrl:
#DEBUG: Needs implementation!
print("storage for model-and-run-length log distr not implemented")
#DEBUG: Make sure you call posterior expectation + variance for BVAR only
# once suff. t for pred. achieved. I.e., we want 0-probability
# assigned to BVAR-predictions before suff. lag length
def prediction_y(self,y, t):
"""Using the information of all potential models and run-lengths,
make a prediction about the next observation. In particular,
you want the MAP/Expected value as well as the standard deviation/
variance to put CIs around your predicted value"""
"""for each model in the model universe, extract the posterior
expectation and the posterior variance for each run length,
weighted by model_and_run_length_distr, and sum them up.
This yields the posterior mean and posterior variance under
model uncertainty"""
#Q: Start prediction only once ALL models initialized?
#A: seems to be the correct way.
post_mean , post_var = (np.zeros(shape=(self.S1, self.S2)),
np.zeros(shape=(self.S1*self.S2, self.S1*self.S2)))
for (m, model) in zip(range(0, self.Q), self.model_universe):
"""simple reweighting of the means of each (q,r) combination by
the appropriate probability distribution"""
"""Get the number of stored run lengths for this model"""
num_rl = np.size(model.retained_run_lengths)
#DEBUG: I want to circumvent the exp-conversion!
# Callable via LogSumExp.logsumexp(...)
"""weighing expectation with model & run-length probabilities"""
post_mean = (post_mean +
np.sum(
np.reshape(model.get_posterior_expectation(t),
newshape = (num_rl, self.S1, self.S2)) *
np.exp(model.joint_log_probabilities -
self.log_evidence)[:,np.newaxis, np.newaxis],
axis = 0))
"""weighing the variance with model & run-length probabilities"""
post_var = (post_var +
np.sum(
np.reshape(model.get_posterior_variance(t),
newshape = (num_rl, self.S1*self.S2,
self.S1*self.S2)) *
np.exp(model.joint_log_probabilities -
self.log_evidence)[:, np.newaxis,np.newaxis],
axis = 0) )
"""lastly, store the new posterior mean & variance in the relevant
object"""
self.y_pred_mean, self.y_pred_var = post_mean, post_var
def storage(self, t):
"""helper function, just stores y_pred into storage_mean & storage_var
so that we can always access the last computed quantity"""
#Q: Best to only store it once all models initialized?
#A: Probably best (and easiest)
self.storage_mean[t-1, :, :] = self.y_pred_mean
#self.storage_var[t-1, :, :] = self.y_pred_var
self.storage_var[t-1, :] = np.diag(self.y_pred_var)
self.storage_log_evidence[t-1] = self.log_evidence
def trim_run_length_log_distributions(self, t):
"""Trim the distributions within each model object by calling a trimmer
on all model objects in the model universe. Pass the threshold down"""
for model in self.model_universe:
#NOTE: Would be ideal to implement this on probability_model level!
if model.has_lags:
if model.lag_length<t:
model.trim_run_length_log_distrbution(t, self.threshold,
self.trim_type)
else:
model.trim_run_length_log_distrbution(t, self.threshold,
self.trim_type)
#DEBUG: Relocate to probability_model
def update_priors(self, t):
"""update the priors for each model in the model universe, provided
that the boolean auto_prior_update is true"""
for (m, model) in zip(range(0,self.Q), self.model_universe):
if model.auto_prior_update == True:
"""We need to weigh quantities acc. to rld"""
model_specific_rld = (self.model_and_run_length_log_distr[m,:] -
misc.logsumexp(self.model_and_run_length_log_distr[m,:]))
model.prior_update(t, model_specific_rld)
def MAP_estimate(self, t):
"""Using the information of all potential models and run-lengths,
get the MAP segmentation & model estimate.
"""
"""STEP 1: get all quantities we need for one iteration of the MAP
segmentation. *log_MAP_current* and *log_MAP_proposed* will track the
values of MAP_t. The *initializer* bool will indicate if the highest
current MAP_t value as from initialization or a recursive update.
*r_cand*,*m* is the run-length/model associated with log_MAP_proposed,
and *r_star*, *m_star* hold the optimal run-length/model at the end
of the current iteration"""
log_MAP_current, log_MAP_proposed = -np.inf, -np.inf #-9999999, -9999999
initializer, CP_initialization = False, False
CP_proposed = [-99, -99]
r_cand, r_star = -99,-99
m, m_star = 0, self.m_star_old
"""STEP 1.5: I need a different version of 'all run lengths' than
the one used for mrl distro"""
all_rl = np.array([])
for model in self.model_universe:
all_rl = np.union1d(all_rl, model.retained_run_lengths)
if model.retained_run_lengths[-1] == model.retained_run_lengths[-2]:
#DEBUG: changed r_more from '+1' to 't'
#r_more = np.array([model.retained_run_lengths[-1]+1])
r_more = np.array([t])
all_rl = np.union1d(all_rl, r_more)
all_rl = all_rl.astype(int)
"""STEP 2: Loop over the model universe and check for each model if the
*log_MAP_proposed* quantity implied by that model will beat the current
maximum achieved."""
for (m,model) in zip(range(0, self.Q), self.model_universe):
if model.has_lags:
model_lag = model.lag_length
else:
#DEBUG: changed model lag
#model_lag = 1
#DEBUG: CONSTANT FITTING ADAPTION
model_lag = 0
"""STEP 2.1: If you have model_lag = t, this means that the model
is initialized at this time point t, implying that *initializer*
is set to True and you only check run-lengths 0 and <0.
NOTE: If model_lag>t, then you just skip the round altogether."""
if model_lag+1 == t:
initializer = True
log_MAP_0 = model.joint_log_probabilities[0] #+
#np.log(self.model_prior[m]))#r=0
log_MAP_larger_0 = model.joint_log_probabilities[1] #+
#np.log(self.model_prior[m]))#r<0
if log_MAP_0 > log_MAP_larger_0:
r_cand = 0 #t-1
log_MAP_proposed = log_MAP_0
else:
r_cand = t+1 #t
log_MAP_proposed = log_MAP_larger_0
"""STEP 2.2: If you have model_lag < t, the model has already been
initialized. This means the *initializer* is set to False and you
check all run-lengths stored inside the model object"""
if model_lag+1 < t:
initializer = False
#log_densities = -np.inf*np.ones(t)
"""Get log densities s.t. we have one entry for every retained
run length (and thus for every log MAP storage entry)"""
log_densities = -np.inf*np.ones(np.size(all_rl))
#self.all_retained_run_lengths))
"""Get the run-lengths as indices. If we store r=t-1 and r>t-1
at once, make sure that this is captured in the object."""
model_run_lengths = model.retained_run_lengths.copy() #+ model_lag - 1
if model_run_lengths[-1] == model_run_lengths[-2]:
#DEBUG: changed from '+1' to 't'
model_run_lengths[-1] = t #model_run_lengths[-1]+1
#print("model rl after mod:", model_run_lengths)
#all_rl = self.all_retained_run_lengths.copy()
#if (all_rl[-1] == all_rl[-2]):
# all_rl[-1] = all_rl[-1] + 1
"""All run-lengths that are kept of the current model are
stored away in the correct entry of log_densities"""
index_indicators = np.in1d(all_rl,
model_run_lengths)
#DEBUG: Renormalized version
log_densities[index_indicators] = (
model.joint_log_probabilities
- self.log_evidence)
"""Solve the maximization problem"""
MAP_factor = np.flipud(self.log_MAP_storage)[all_rl]
candidates = (log_densities + MAP_factor)
#DEBUG: MAP factor replaces t-r_all-2 accessing
#(
#self.log_MAP_storage[t-all_rl-2]))#self.all_retained_run_lengths-2])) #self.all_retained_run_lengths])) #[model.retained_run_lengths]) )
log_MAP_proposed = np.max(candidates)
#DEBUG: Unclear hat happens if this selects r>t-1!
#DEBUG: self.all_retained_run_lengths instead (?)
r_cand = (all_rl)[np.argmax( candidates )]
#if r_cand = t, then set r_cand = t-1
if r_cand == t-1:
r_cand = t-2
if r_cand == t:
r_cand = t-1
"""STEP 2.3: If the highest MAP_t value that could be achieved
with the current model is higher than that of any previous models,
store the new maximum"""
if log_MAP_proposed > log_MAP_current:
log_MAP_current = log_MAP_proposed
CP_initialization = initializer
m_star = m
r_star = r_cand
CP_proposed = [t-r_star,m_star]
m += 1
"""STEP 3: Record the new CP and model if any. I.e., store the new
MAP-maximum in log format and append to the list of CPs and models"""
#DEBUG: Now, we just append a value.
self.log_MAP_storage = np.append(self.log_MAP_storage, log_MAP_current)#[t-1] = log_MAP_current #problem log map storage
#indices are not aligned with the run-lengths?!
if CP_initialization: #or (t == r_star + self.model_universe[m_star].lag_length + 1):
"""STEP 3.1: If we choose a model that has just been initialized,
replace the entry of CPs at the relevant position if necessary."""
#self.CPs.append([CP_proposed])
self.CPs[t-1] = [CP_proposed]
elif log_MAP_current > -np.inf: #-9999999:
#DEBUG: This makes no sense. We append a new model only if the lag
# length and
"""We are at time t=1,2,3... and e want to get the segmentations
from before time t, i.e. from times t-1, t-2, ..., with run-
length r_t via t-r_t, where r_t=0,1,2... Now note that we hence
have to access the optimal segmentation for time [(t-1) - r_t],
which is stored at index [(t-1) - r_t - 1] = t-r_t-2."""
"""STEP 3.2: If we choose the same model as in the last time period
with the new run-length being 1+old run-length, then we don't want
to have a new list but just copy the last one. If we choose a
completely different model, we want to overwrite CPs."""
if (r_star == self.r_star_old + 1 and m_star == self.m_star_old):
self.CPs[t-1] = self.CPs[t-2]
else:
self.CPs[t-1] = self.CPs[t-2 - r_star].copy() + [CP_proposed]
self.r_star_old = r_star
self.m_star_old = m_star
@staticmethod
def default_step_size_param_learning(t, alpha = None):
"""Used if no other learning rate specified"""
if alpha is None:
return (pow(t, -1))
else:
return (alpha*pow(t, -1))
| [
"numpy.sum",
"numpy.abs",
"numpy.argmax",
"numpy.ones",
"numpy.exp",
"numpy.diag",
"numpy.copy",
"numpy.power",
"time.clock",
"numpy.insert",
"numpy.append",
"numpy.max",
"scipy.misc.logsumexp",
"numpy.union1d",
"numpy.size",
"numpy.flipud",
"numpy.min",
"numpy.zeros",
"numpy.any... | [((6248, 6282), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.S1, self.S2)'}), '(shape=(self.S1, self.S2))\n', (6256, 6282), True, 'import numpy as np\n'), ((6310, 6364), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.S1 * self.S2, self.S1 * self.S2)'}), '(shape=(self.S1 * self.S2, self.S1 * self.S2))\n', (6318, 6364), True, 'import numpy as np\n'), ((6805, 6847), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.T, self.S1, self.S2)'}), '(shape=(self.T, self.S1, self.S2))\n', (6813, 6847), True, 'import numpy as np\n'), ((6877, 6914), 'numpy.zeros', 'np.zeros', (['(self.T, self.S1 * self.S2)'], {}), '((self.T, self.S1 * self.S2))\n', (6885, 6914), True, 'import numpy as np\n'), ((7334, 7350), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (7342, 7350), True, 'import numpy as np\n'), ((13306, 13329), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (13314, 13329), True, 'import numpy as np\n'), ((14896, 14908), 'time.clock', 'time.clock', ([], {}), '()\n', (14906, 14908), False, 'import time\n'), ((34693, 34705), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (34701, 34705), True, 'import numpy as np\n'), ((37086, 37136), 'scipy.misc.logsumexp', 'misc.logsumexp', (['model_rl_log_distributions'], {'axis': '(0)'}), '(model_rl_log_distributions, axis=0)\n', (37100, 37136), False, 'from scipy import misc\n'), ((39070, 39113), 'numpy.sum', 'np.sum', (['self.model_prior[index_initialized]'], {}), '(self.model_prior[index_initialized])\n', (39076, 39113), True, 'import numpy as np\n'), ((63759, 63794), 'numpy.zeros', 'np.zeros', (['(self.Q, num_run_lengths)'], {}), '((self.Q, num_run_lengths))\n', (63767, 63794), True, 'import numpy as np\n'), ((65674, 65780), 'scipy.misc.logsumexp', 'scipy.misc.logsumexp', ([], {'a': 'all_log_alpha_derivatives', 'b': 'all_log_alpha_derivatives_sign', 'return_sign': '(True)'}), '(a=all_log_alpha_derivatives, b=\n all_log_alpha_derivatives_sign, return_sign=True)\n', (65694, 65780), False, 'import scipy\n'), ((77164, 77183), 'numpy.where', 'np.where', (['(resid < C)'], {}), '(resid < C)\n', (77172, 77183), True, 'import numpy as np\n'), ((77423, 77442), 'numpy.where', 'np.where', (['(resid < C)'], {}), '(resid < C)\n', (77431, 77442), True, 'import numpy as np\n'), ((77709, 77742), 'numpy.sum', 'np.sum', (['(2 * resid * post_mean_der)'], {}), '(2 * resid * post_mean_der)\n', (77715, 77742), True, 'import numpy as np\n'), ((78112, 78131), 'numpy.where', 'np.where', (['(resid < C)'], {}), '(resid < C)\n', (78120, 78131), True, 'import numpy as np\n'), ((78222, 78275), 'numpy.sum', 'np.sum', (['(2 * resid[smallerC] * post_mean_der[smallerC])'], {}), '(2 * resid[smallerC] * post_mean_der[smallerC])\n', (78228, 78275), True, 'import numpy as np\n'), ((78451, 78470), 'numpy.where', 'np.where', (['(resid < C)'], {}), '(resid < C)\n', (78459, 78470), True, 'import numpy as np\n'), ((82278, 82364), 'scipy.misc.logsumexp', 'scipy.misc.logsumexp', (['[model.model_log_evidence for model in self.model_universe]'], {}), '([model.model_log_evidence for model in self.\n model_universe])\n', (82298, 82364), False, 'import scipy\n'), ((88765, 88789), 'numpy.diag', 'np.diag', (['self.y_pred_var'], {}), '(self.y_pred_var)\n', (88772, 88789), True, 'import numpy as np\n'), ((91253, 91265), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (91261, 91265), True, 'import numpy as np\n'), ((96665, 96713), 'numpy.append', 'np.append', (['self.log_MAP_storage', 'log_MAP_current'], {}), '(self.log_MAP_storage, log_MAP_current)\n', (96674, 96713), True, 'import numpy as np\n'), ((6547, 6582), 'numpy.ones', 'np.ones', ([], {'shape': '(self.Q, self.T + 1)'}), '(shape=(self.Q, self.T + 1))\n', (6554, 6582), True, 'import numpy as np\n'), ((7095, 7116), 'numpy.ones', 'np.ones', ([], {'shape': 'self.T'}), '(shape=self.T)\n', (7102, 7116), True, 'import numpy as np\n'), ((7432, 7450), 'numpy.array', 'np.array', (['[[], []]'], {}), '([[], []])\n', (7440, 7450), True, 'import numpy as np\n'), ((15225, 15237), 'time.clock', 'time.clock', ([], {}), '()\n', (15235, 15237), False, 'import time\n'), ((15325, 15337), 'time.clock', 'time.clock', ([], {}), '()\n', (15335, 15337), False, 'import time\n'), ((27091, 27143), 'scipy.misc.logsumexp', 'scipy.misc.logsumexp', (['list_model_log_evidences_p_eps'], {}), '(list_model_log_evidences_p_eps)\n', (27111, 27143), False, 'import scipy\n'), ((27200, 27252), 'scipy.misc.logsumexp', 'scipy.misc.logsumexp', (['list_model_log_evidences_m_eps'], {}), '(list_model_log_evidences_m_eps)\n', (27220, 27252), False, 'import scipy\n'), ((34867, 34922), 'numpy.union1d', 'np.union1d', (['all_run_lengths', 'model.retained_run_lengths'], {}), '(all_run_lengths, model.retained_run_lengths)\n', (34877, 34922), True, 'import numpy as np\n'), ((35333, 35362), 'numpy.append', 'np.append', (['all_run_lengths', 't'], {}), '(all_run_lengths, t)\n', (35342, 35362), True, 'import numpy as np\n'), ((35767, 35796), 'numpy.ones', 'np.ones', (['(self.Q, length_rls)'], {}), '((self.Q, length_rls))\n', (35774, 35796), True, 'import numpy as np\n'), ((36155, 36207), 'numpy.in1d', 'np.in1d', (['all_run_lengths', 'model.retained_run_lengths'], {}), '(all_run_lengths, model.retained_run_lengths)\n', (36162, 36207), True, 'import numpy as np\n'), ((40088, 40202), 'numpy.any', 'np.any', (['[(model.has_lags and t - model.lag_length > 1 or not model.has_lags) for\n model in self.model_universe]'], {}), '([(model.has_lags and t - model.lag_length > 1 or not model.has_lags) for\n model in self.model_universe])\n', (40094, 40202), True, 'import numpy as np\n'), ((63666, 63700), 'numpy.ones', 'np.ones', (['(self.Q, num_run_lengths)'], {}), '((self.Q, num_run_lengths))\n', (63673, 63700), True, 'import numpy as np\n'), ((63844, 63878), 'numpy.ones', 'np.ones', (['(self.Q, num_run_lengths)'], {}), '((self.Q, num_run_lengths))\n', (63851, 63878), True, 'import numpy as np\n'), ((64311, 64377), 'numpy.in1d', 'np.in1d', (['self.all_retained_run_lengths', 'model.retained_run_lengths'], {}), '(self.all_retained_run_lengths, model.retained_run_lengths)\n', (64318, 64377), True, 'import numpy as np\n'), ((66330, 66349), 'numpy.abs', 'np.abs', (['term_1_sign'], {}), '(term_1_sign)\n', (66336, 66349), True, 'import numpy as np\n'), ((67334, 67367), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.S1 * self.S2)'}), '(shape=self.S1 * self.S2)\n', (67342, 67367), True, 'import numpy as np\n'), ((74773, 74805), 'numpy.sign', 'np.sign', (['self.gradient_alpha_rld'], {}), '(self.gradient_alpha_rld)\n', (74780, 74805), True, 'import numpy as np\n'), ((77042, 77055), 'numpy.abs', 'np.abs', (['resid'], {}), '(resid)\n', (77048, 77055), True, 'import numpy as np\n'), ((78568, 78617), 'numpy.abs', 'np.abs', (['(resid[smallerC] * post_mean_der[smallerC])'], {}), '(resid[smallerC] * post_mean_der[smallerC])\n', (78574, 78617), True, 'import numpy as np\n'), ((79502, 79596), 'scipy.misc.logsumexp', 'misc.logsumexp', (['[item for entry in all_one_step_ahead_lklhoods_weighted for item in entry]'], {}), '([item for entry in all_one_step_ahead_lklhoods_weighted for\n item in entry])\n', (79516, 79596), False, 'from scipy import misc\n'), ((80818, 80912), 'scipy.misc.logsumexp', 'misc.logsumexp', (['[item for entry in all_one_step_ahead_lklhoods_weighted for item in entry]'], {}), '([item for entry in all_one_step_ahead_lklhoods_weighted for\n item in entry])\n', (80832, 80912), False, 'from scipy import misc\n'), ((84408, 84442), 'numpy.ones', 'np.ones', ([], {'shape': '(self.Q, r_max + 1)'}), '(shape=(self.Q, r_max + 1))\n', (84415, 84442), True, 'import numpy as np\n'), ((86577, 86611), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.S1, self.S2)'}), '(shape=(self.S1, self.S2))\n', (86585, 86611), True, 'import numpy as np\n'), ((86626, 86680), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.S1 * self.S2, self.S1 * self.S2)'}), '(shape=(self.S1 * self.S2, self.S1 * self.S2))\n', (86634, 86680), True, 'import numpy as np\n'), ((86984, 87019), 'numpy.size', 'np.size', (['model.retained_run_lengths'], {}), '(model.retained_run_lengths)\n', (86991, 87019), True, 'import numpy as np\n'), ((91329, 91375), 'numpy.union1d', 'np.union1d', (['all_rl', 'model.retained_run_lengths'], {}), '(all_rl, model.retained_run_lengths)\n', (91339, 91375), True, 'import numpy as np\n'), ((9754, 9770), 'numpy.zeros', 'np.zeros', (['self.Q'], {}), '(self.Q)\n', (9762, 9770), True, 'import numpy as np\n'), ((9815, 9831), 'numpy.zeros', 'np.zeros', (['self.Q'], {}), '(self.Q)\n', (9823, 9831), True, 'import numpy as np\n'), ((22549, 22621), 'numpy.max', 'np.max', (['[model.joint_log_probabilities for model in self.model_universe]'], {}), '([model.joint_log_probabilities for model in self.model_universe])\n', (22555, 22621), True, 'import numpy as np\n'), ((23076, 23148), 'numpy.min', 'np.min', (['[model.joint_log_probabilities for model in self.model_universe]'], {}), '([model.joint_log_probabilities for model in self.model_universe])\n', (23082, 23148), True, 'import numpy as np\n'), ((27655, 27685), 'numpy.array', 'np.array', (['list_post_mean_p_eps'], {}), '(list_post_mean_p_eps)\n', (27663, 27685), True, 'import numpy as np\n'), ((27789, 27819), 'numpy.array', 'np.array', (['list_post_mean_m_eps'], {}), '(list_post_mean_m_eps)\n', (27797, 27819), True, 'import numpy as np\n'), ((44593, 44707), 'scipy.misc.logsumexp', 'scipy.misc.logsumexp', ([], {'a': 'all_log_alpha_derivatives', 'b': 'all_log_alpha_derivatives_sign', 'return_sign': '(True)', 'axis': '(0)'}), '(a=all_log_alpha_derivatives, b=\n all_log_alpha_derivatives_sign, return_sign=True, axis=0)\n', (44613, 44707), False, 'import scipy\n'), ((44857, 44902), 'scipy.misc.logsumexp', 'scipy.misc.logsumexp', ([], {'a': 'all_log_probs', 'axis': '(0)'}), '(a=all_log_probs, axis=0)\n', (44877, 44902), False, 'import scipy\n'), ((66559, 66595), 'numpy.array', 'np.array', (['[term_1_sign, term_2_sign]'], {}), '([term_1_sign, term_2_sign])\n', (66567, 66595), True, 'import numpy as np\n'), ((67561, 67596), 'numpy.size', 'np.size', (['model.retained_run_lengths'], {}), '(model.retained_run_lengths)\n', (67568, 67596), True, 'import numpy as np\n'), ((67747, 67813), 'numpy.in1d', 'np.in1d', (['self.all_retained_run_lengths', 'model.retained_run_lengths'], {}), '(self.all_retained_run_lengths, model.retained_run_lengths)\n', (67754, 67813), True, 'import numpy as np\n'), ((69278, 69313), 'numpy.size', 'np.size', (['model.retained_run_lengths'], {}), '(model.retained_run_lengths)\n', (69285, 69313), True, 'import numpy as np\n'), ((69464, 69530), 'numpy.in1d', 'np.in1d', (['self.all_retained_run_lengths', 'model.retained_run_lengths'], {}), '(self.all_retained_run_lengths, model.retained_run_lengths)\n', (69471, 69530), True, 'import numpy as np\n'), ((76870, 76888), 'numpy.power', 'np.power', (['resid', '(2)'], {}), '(resid, 2)\n', (76878, 76888), True, 'import numpy as np\n'), ((77515, 77538), 'numpy.abs', 'np.abs', (['resid[smallerC]'], {}), '(resid[smallerC])\n', (77521, 77538), True, 'import numpy as np\n'), ((77909, 77923), 'numpy.sign', 'np.sign', (['resid'], {}), '(resid)\n', (77916, 77923), True, 'import numpy as np\n'), ((83738, 83756), 'numpy.max', 'np.max', (['retained_q'], {}), '(retained_q)\n', (83744, 83756), True, 'import numpy as np\n'), ((84854, 84889), 'numpy.copy', 'np.copy', (['model.retained_run_lengths'], {}), '(model.retained_run_lengths)\n', (84861, 84889), True, 'import numpy as np\n'), ((91621, 91634), 'numpy.array', 'np.array', (['[t]'], {}), '([t])\n', (91629, 91634), True, 'import numpy as np\n'), ((91664, 91690), 'numpy.union1d', 'np.union1d', (['all_rl', 'r_more'], {}), '(all_rl, r_more)\n', (91674, 91690), True, 'import numpy as np\n'), ((94690, 94724), 'numpy.in1d', 'np.in1d', (['all_rl', 'model_run_lengths'], {}), '(all_rl, model_run_lengths)\n', (94697, 94724), True, 'import numpy as np\n'), ((95461, 95479), 'numpy.max', 'np.max', (['candidates'], {}), '(candidates)\n', (95467, 95479), True, 'import numpy as np\n'), ((27335, 27375), 'numpy.array', 'np.array', (['list_model_log_evidences_p_eps'], {}), '(list_model_log_evidences_p_eps)\n', (27343, 27375), True, 'import numpy as np\n'), ((27477, 27517), 'numpy.array', 'np.array', (['list_model_log_evidences_m_eps'], {}), '(list_model_log_evidences_m_eps)\n', (27485, 27517), True, 'import numpy as np\n'), ((69966, 70026), 'numpy.sum', 'np.sum', (['model_indices_indicators_relative_to_all_run_lengths'], {}), '(model_indices_indicators_relative_to_all_run_lengths)\n', (69972, 70026), True, 'import numpy as np\n'), ((70050, 70100), 'numpy.size', 'np.size', (['model.one_step_ahead_predictive_log_probs'], {}), '(model.one_step_ahead_predictive_log_probs)\n', (70057, 70100), True, 'import numpy as np\n'), ((70135, 70209), 'numpy.insert', 'np.insert', (['model.one_step_ahead_predictive_log_probs', '(0)', 'model.r0_log_prob'], {}), '(model.one_step_ahead_predictive_log_probs, 0, model.r0_log_prob)\n', (70144, 70209), True, 'import numpy as np\n'), ((77260, 77288), 'numpy.power', 'np.power', (['resid[smallerC]', '(2)'], {}), '(resid[smallerC], 2)\n', (77268, 77288), True, 'import numpy as np\n'), ((90072, 90129), 'scipy.misc.logsumexp', 'misc.logsumexp', (['self.model_and_run_length_log_distr[m, :]'], {}), '(self.model_and_run_length_log_distr[m, :])\n', (90086, 90129), False, 'from scipy import misc\n'), ((95067, 95098), 'numpy.flipud', 'np.flipud', (['self.log_MAP_storage'], {}), '(self.log_MAP_storage)\n', (95076, 95098), True, 'import numpy as np\n'), ((95664, 95685), 'numpy.argmax', 'np.argmax', (['candidates'], {}), '(candidates)\n', (95673, 95685), True, 'import numpy as np\n'), ((40835, 40873), 'numpy.size', 'np.size', (['self.all_retained_run_lengths'], {}), '(self.all_retained_run_lengths)\n', (40842, 40873), True, 'import numpy as np\n'), ((41632, 41698), 'numpy.in1d', 'np.in1d', (['self.all_retained_run_lengths', 'model.retained_run_lengths'], {}), '(self.all_retained_run_lengths, model.retained_run_lengths)\n', (41639, 41698), True, 'import numpy as np\n'), ((45876, 45902), 'numpy.array', 'np.array', (['[expr_1, expr_2]'], {}), '([expr_1, expr_2])\n', (45884, 45902), True, 'import numpy as np\n'), ((53591, 53631), 'numpy.where', 'np.where', (['(log_model_posteriors > -np.inf)'], {}), '(log_model_posteriors > -np.inf)\n', (53599, 53631), True, 'import numpy as np\n'), ((55045, 55111), 'numpy.in1d', 'np.in1d', (['self.all_retained_run_lengths', 'model.retained_run_lengths'], {}), '(self.all_retained_run_lengths, model.retained_run_lengths)\n', (55052, 55111), True, 'import numpy as np\n'), ((70657, 70777), 'numpy.array', 'np.array', (['[self.model_and_run_length_log_distr[m][\n model_indices_indicators_relative_to_all_run_lengths], one_steps]'], {}), '([self.model_and_run_length_log_distr[m][\n model_indices_indicators_relative_to_all_run_lengths], one_steps])\n', (70665, 70777), True, 'import numpy as np\n'), ((70955, 70986), 'numpy.array', 'np.array', (['[post_prob_log, sum_]'], {}), '([post_prob_log, sum_])\n', (70963, 70986), True, 'import numpy as np\n'), ((71130, 71242), 'numpy.array', 'np.array', (['[run_length_and_model_log_der[m,\n model_indices_indicators_relative_to_all_run_lengths], one_steps]'], {}), '([run_length_and_model_log_der[m,\n model_indices_indicators_relative_to_all_run_lengths], one_steps])\n', (71138, 71242), True, 'import numpy as np\n'), ((71710, 71745), 'numpy.array', 'np.array', (['[post_prob_der_log, sum_]'], {}), '([post_prob_der_log, sum_])\n', (71718, 71745), True, 'import numpy as np\n'), ((71771, 71812), 'numpy.array', 'np.array', (['[post_prob_der_log_sign, sign_]'], {}), '([post_prob_der_log_sign, sign_])\n', (71779, 71812), True, 'import numpy as np\n'), ((93742, 93757), 'numpy.size', 'np.size', (['all_rl'], {}), '(all_rl)\n', (93749, 93757), True, 'import numpy as np\n'), ((40567, 40605), 'numpy.size', 'np.size', (['self.all_retained_run_lengths'], {}), '(self.all_retained_run_lengths)\n', (40574, 40605), True, 'import numpy as np\n'), ((40702, 40740), 'numpy.size', 'np.size', (['self.all_retained_run_lengths'], {}), '(self.all_retained_run_lengths)\n', (40709, 40740), True, 'import numpy as np\n'), ((43016, 43076), 'numpy.sum', 'np.sum', (['model_indices_indicators_relative_to_all_run_lengths'], {}), '(model_indices_indicators_relative_to_all_run_lengths)\n', (43022, 43076), True, 'import numpy as np\n'), ((43375, 43394), 'numpy.ones', 'np.ones', (['num_needed'], {}), '(num_needed)\n', (43382, 43394), True, 'import numpy as np\n'), ((66507, 66526), 'numpy.abs', 'np.abs', (['term_1_sign'], {}), '(term_1_sign)\n', (66513, 66526), True, 'import numpy as np\n'), ((74931, 74962), 'numpy.abs', 'np.abs', (['self.gradient_alpha_rld'], {}), '(self.gradient_alpha_rld)\n', (74937, 74962), True, 'import numpy as np\n'), ((87461, 87518), 'numpy.exp', 'np.exp', (['(model.joint_log_probabilities - self.log_evidence)'], {}), '(model.joint_log_probabilities - self.log_evidence)\n', (87467, 87518), True, 'import numpy as np\n'), ((87994, 88051), 'numpy.exp', 'np.exp', (['(model.joint_log_probabilities - self.log_evidence)'], {}), '(model.joint_log_probabilities - self.log_evidence)\n', (88000, 88051), True, 'import numpy as np\n'), ((29341, 29375), 'numpy.sign', 'np.sign', (['self.gradient_alpha_param'], {}), '(self.gradient_alpha_param)\n', (29348, 29375), True, 'import numpy as np\n'), ((43233, 43252), 'numpy.ones', 'np.ones', (['num_needed'], {}), '(num_needed)\n', (43240, 43252), True, 'import numpy as np\n'), ((71545, 71560), 'numpy.ones', 'np.ones', (['num_rl'], {}), '(num_rl)\n', (71552, 71560), True, 'import numpy as np\n'), ((15146, 15158), 'time.clock', 'time.clock', ([], {}), '()\n', (15156, 15158), False, 'import time\n'), ((68532, 68629), 'numpy.exp', 'np.exp', (['run_length_and_model_log_der[m,\n model_indices_indicators_relative_to_all_run_lengths]'], {}), '(run_length_and_model_log_der[m,\n model_indices_indicators_relative_to_all_run_lengths])\n', (68538, 68629), True, 'import numpy as np\n'), ((45998, 46013), 'numpy.ones', 'np.ones', (['self.Q'], {}), '(self.Q)\n', (46005, 46013), True, 'import numpy as np\n'), ((31946, 31983), 'numpy.sign', 'np.sign', (['self.gradient_alpha_param[m]'], {}), '(self.gradient_alpha_param[m])\n', (31953, 31983), True, 'import numpy as np\n')] |
import json
from PIL import Image, ImageDraw, ImageFont
from PIL import ImagePath
import os
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats.stats import pearsonr
import pandas as pd
import sys
from matplotlib.backends.backend_pdf import PdfPages
import explore as ex
def get_font(fontsize=40):
"""Attempts to retrieve a reasonably-looking TTF font from the system.
We don't make much of an effort, but it's what we can reasonably do without
incorporating additional dependencies for this task.
"""
if sys.platform == 'win32':
font_names = ['Arial']
elif sys.platform in ['linux', 'linux2']:
font_names = ['DejaVuSans-Bold', 'DroidSans-Bold']
elif sys.platform == 'darwin':
font_names = ['Menlo', 'Helvetica']
font = None
for font_name in font_names:
try:
font = ImageFont.truetype(font_name,fontsize)
break
except IOError:
continue
return font
def makeMask(size,tups):
black = Image.new('1', im.size)
imd = ImageDraw.Draw(black)
imd.polygon(tups,fill="white",outline="white")
return(np.array(black))
res = []
pats = os.listdir("PreviewImages")
pats = [pat for pat in pats if "." not in pat]
pixthresh = 0
font = ImageFont.truetype("LEMONMILK-Regular.otf",75)
for pat in pats:
print(pat)
annotationfiles = os.listdir(os.path.join("PreviewImages",pat,"geojson_annotations"))
annotationfiles = [f for f in annotationfiles if ".geojson" in f]
imdir = os.path.join("PreviewImages",pat)
files = os.listdir(imdir)
ims = [f for f in files if (".jpg" in f) and ("_Q." not in f)]
im = Image.open(os.path.join(imdir,ims[0]))
allblack = Image.new('L', im.size)
imdall = ImageDraw.Draw(allblack)
for annotationfile in annotationfiles:
annroot = annotationfile.replace(".geojson","")
anndir = os.path.join("PreviewImages",pat,annroot)
if not os.path.exists(anndir):
os.mkdir(anndir)
black = Image.new('L', im.size)
red = Image.new('L', im.size)
with open(os.path.join("PreviewImages",pat,"geojson_annotations",annotationfile)) as f:
data = json.load(f)
Nann = len(data["features"])
coordvec = []
for f in range(0,Nann):
blob = data["features"][f]["geometry"]
if blob["type"] == "LineString":
coords = blob["coordinates"]
if blob["type"] == "Polygon":
coords = blob["coordinates"][0]
coordvec.append(coords)
tups = [tuple(coord) for coord in coords]
mask = makeMask(im.size,tups)
# Let's have a look at raw data in multipage tiff files
fnames = []
for root,subdir,files in os.walk(os.path.join("MultiTIFFs",pat)):
for fnm in files:
if ".tiff" in fnm:
fnames.append(os.path.join(root,fnm))
if len(fnames)>1:
print("Error: More than one .tiff file found for "+pat)
break
images,metals,unsorted_labels = ex.parseMultiTIFF(fnames[0])
labdict = {lab:i for i,lab in enumerate(unsorted_labels)}
labels = sorted(unsorted_labels, key=str.casefold)
area = np.sum(mask)
corrs = np.zeros((len(unsorted_labels),len(unsorted_labels)))
fig = plt.figure(constrained_layout=True, figsize=(25*0.75, 15*0.75), dpi=100)
for l,label in enumerate(labels):
i = labdict[label]
chanpix = images[i,:,:]
allpix = chanpix[mask]
qmax = 0.95
eps = 0.5
pixtqm = np.quantile(chanpix[mask],qmax)
pixtqa = np.quantile(chanpix,qmax)
# Write log intensity histogram to .pdf
mlabel = "log("+label+"+0.5)"
print("Plotting histogram: "+pat+" "+annroot+'_{:04d} '.format(f)+label)
sp = plt.subplot(6,10,l+1)
ldat = np.log(allpix+eps)
n, bins, patches = plt.hist(ldat, bins = np.linspace(-1,12,131), range=[np.log(pixthresh+eps),np.max(np.log(chanpix+eps))],density=True, facecolor='g', alpha=0.75, figure=fig,log=True)
changebin = 1+5+np.argmax(np.abs(np.diff(n[5:])))
pixtadapt = np.exp(bins[changebin])-eps
nadapt = n[changebin]
l = plt.axvline(np.log(np.ceil(pixthresh+eps)),color="red",linestyle="dashed")
l2 = plt.axvline(np.log(np.ceil(pixtadapt+eps)),color=(0,0,1,0.25),linestyle="dashed")
l3 = plt.axvline(np.log(np.ceil(pixtqm+eps)), color="pink",linestyle="dashed")
l4 = plt.axvline(np.log(np.ceil(pixtqa+eps)), color="orange",linestyle="dashed")
pt = plt.xlabel(mlabel,figure=fig)
tx = plt.text(1.05*np.log(np.ceil(pixtadapt+eps)),0.3*np.max(n),str(round(np.log(np.ceil(pixtadapt+eps)),3)),color="blue",ha="left")
pixthresh = pixtadapt
maskp = np.logical_and(mask,chanpix > pixthresh)
pospix = chanpix[maskp]
mean = np.mean(pospix)
median = np.median(pospix)
mean_all = np.mean(allpix)
median_all = np.median(allpix)
posarea = np.sum(maskp)
posfrac = float(posarea)/float(area)
for l2,label2 in enumerate(labels):
j = labdict[label2]
pospix2 = images[j,:,:][maskp]
corrs[i,j] = np.corrcoef(pospix,pospix2)[0,1]
summ = {
"image":pat,
"annotation_file":annotationfile,
"roi_number":f,
"label":label2,
"area":area,
"mean_intensity_pos_signal":mean,
"median_intensity_pos_signal":median,
"mean_intensity_all_pixels":mean_all,
"median_intensity_all_pixels":median_all,
"pos_area":posarea,
"pos_fraction":posfrac
}
res.append(summ)
st = fig.suptitle(pat+" "+annroot+'_{:04d} '.format(f), fontsize=14)
plt.savefig(os.path.join(anndir,pat+"_"+annroot+'_{:04d}.png'.format(f)),dpi=400)
print("Writing correlation matrix to file: "+'{:04d}'.format(f))
df = pd.DataFrame(corrs,columns=labels,index=labels)
df.to_csv(os.path.join(anndir,pat+"_"+annroot+"_CorrelationMatrix_"+'ROI{:04d}'.format(f)+".csv"))
# Convert to long format
b = np.tile(df.columns, len(df.index))
a = np.repeat(df.index, len(df.columns))
c = df.values.ravel()
df_long = pd.DataFrame({'label_a':a, 'label_b':b, 'correlation':c})
df_long = df_long[df_long.label_a!=df_long.label_b]
df_long = df_long.sort_values("correlation",ascending=False)
df_long.to_csv(os.path.join(anndir,pat+"_"+annroot+"_CorrelationsRanked_"+'ROI{:04d}'.format(f)+".csv"), index=False)
for lab in labels:
i = labdict[lab]
for j,coords in enumerate(coordvec):
tups = [tuple(coord) for coord in coords]
imdall.polygon(tups,fill="white",outline="white")
filename = pat+"_"+lab+".jpg"
arr = np.array(images[i,:,:])
posim = Image.fromarray(np.array((arr>pixthresh)*255,dtype=np.uint8),mode="L")
im = Image.open(os.path.join(imdir,filename))
maskp = np.logical_and(mask,images[i,:,:]>pixthresh)
imrgb = im.convert("RGB")
R, G, B = imrgb.split()
empty = Image.fromarray(np.zeros(posim.size[::-1],dtype=np.uint8),mode="L")
newImage = Image.merge("RGB", (posim,empty,allblack))
imd2 = ImageDraw.Draw(newImage)
for j,coords in enumerate(coordvec):
mid = np.average(coords,axis=0)
imd2.text((int(round(mid[0])),int(round(mid[1]))),'{:04d}'.format(j),fill="white",font=font)
newImage.save(os.path.join(anndir,annroot+"_"+filename))
outres = pd.DataFrame(res)
outres.to_csv(os.path.join("PreviewImages","ROI_summaries.csv"),index=False)
| [
"os.mkdir",
"PIL.Image.new",
"numpy.sum",
"matplotlib.pyplot.figure",
"numpy.mean",
"explore.parseMultiTIFF",
"numpy.exp",
"os.path.join",
"PIL.Image.merge",
"pandas.DataFrame",
"os.path.exists",
"numpy.max",
"numpy.linspace",
"PIL.ImageDraw.Draw",
"numpy.average",
"numpy.ceil",
"num... | [((1175, 1202), 'os.listdir', 'os.listdir', (['"""PreviewImages"""'], {}), "('PreviewImages')\n", (1185, 1202), False, 'import os\n'), ((1272, 1319), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""LEMONMILK-Regular.otf"""', '(75)'], {}), "('LEMONMILK-Regular.otf', 75)\n", (1290, 1319), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((8366, 8383), 'pandas.DataFrame', 'pd.DataFrame', (['res'], {}), '(res)\n', (8378, 8383), True, 'import pandas as pd\n'), ((1023, 1046), 'PIL.Image.new', 'Image.new', (['"""1"""', 'im.size'], {}), "('1', im.size)\n", (1032, 1046), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1057, 1078), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['black'], {}), '(black)\n', (1071, 1078), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1141, 1156), 'numpy.array', 'np.array', (['black'], {}), '(black)\n', (1149, 1156), True, 'import numpy as np\n'), ((1526, 1560), 'os.path.join', 'os.path.join', (['"""PreviewImages"""', 'pat'], {}), "('PreviewImages', pat)\n", (1538, 1560), False, 'import os\n'), ((1572, 1589), 'os.listdir', 'os.listdir', (['imdir'], {}), '(imdir)\n', (1582, 1589), False, 'import os\n'), ((1721, 1744), 'PIL.Image.new', 'Image.new', (['"""L"""', 'im.size'], {}), "('L', im.size)\n", (1730, 1744), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1758, 1782), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['allblack'], {}), '(allblack)\n', (1772, 1782), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((8398, 8448), 'os.path.join', 'os.path.join', (['"""PreviewImages"""', '"""ROI_summaries.csv"""'], {}), "('PreviewImages', 'ROI_summaries.csv')\n", (8410, 8448), False, 'import os\n'), ((1386, 1443), 'os.path.join', 'os.path.join', (['"""PreviewImages"""', 'pat', '"""geojson_annotations"""'], {}), "('PreviewImages', pat, 'geojson_annotations')\n", (1398, 1443), False, 'import os\n'), ((1678, 1705), 'os.path.join', 'os.path.join', (['imdir', 'ims[0]'], {}), '(imdir, ims[0])\n', (1690, 1705), False, 'import os\n'), ((1904, 1947), 'os.path.join', 'os.path.join', (['"""PreviewImages"""', 'pat', 'annroot'], {}), "('PreviewImages', pat, annroot)\n", (1916, 1947), False, 'import os\n'), ((2030, 2053), 'PIL.Image.new', 'Image.new', (['"""L"""', 'im.size'], {}), "('L', im.size)\n", (2039, 2053), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2068, 2091), 'PIL.Image.new', 'Image.new', (['"""L"""', 'im.size'], {}), "('L', im.size)\n", (2077, 2091), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((866, 905), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_name', 'fontsize'], {}), '(font_name, fontsize)\n', (884, 905), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1961, 1983), 'os.path.exists', 'os.path.exists', (['anndir'], {}), '(anndir)\n', (1975, 1983), False, 'import os\n'), ((1997, 2013), 'os.mkdir', 'os.mkdir', (['anndir'], {}), '(anndir)\n', (2005, 2013), False, 'import os\n'), ((2207, 2219), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2216, 2219), False, 'import json\n'), ((3147, 3175), 'explore.parseMultiTIFF', 'ex.parseMultiTIFF', (['fnames[0]'], {}), '(fnames[0])\n', (3164, 3175), True, 'import explore as ex\n'), ((3328, 3340), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (3334, 3340), True, 'import numpy as np\n'), ((3433, 3509), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'constrained_layout': '(True)', 'figsize': '(25 * 0.75, 15 * 0.75)', 'dpi': '(100)'}), '(constrained_layout=True, figsize=(25 * 0.75, 15 * 0.75), dpi=100)\n', (3443, 3509), True, 'import matplotlib.pyplot as plt\n'), ((6586, 6635), 'pandas.DataFrame', 'pd.DataFrame', (['corrs'], {'columns': 'labels', 'index': 'labels'}), '(corrs, columns=labels, index=labels)\n', (6598, 6635), True, 'import pandas as pd\n'), ((6944, 7004), 'pandas.DataFrame', 'pd.DataFrame', (["{'label_a': a, 'label_b': b, 'correlation': c}"], {}), "({'label_a': a, 'label_b': b, 'correlation': c})\n", (6956, 7004), True, 'import pandas as pd\n'), ((7571, 7596), 'numpy.array', 'np.array', (['images[i, :, :]'], {}), '(images[i, :, :])\n', (7579, 7596), True, 'import numpy as np\n'), ((7764, 7813), 'numpy.logical_and', 'np.logical_and', (['mask', '(images[i, :, :] > pixthresh)'], {}), '(mask, images[i, :, :] > pixthresh)\n', (7778, 7813), True, 'import numpy as np\n'), ((7994, 8038), 'PIL.Image.merge', 'Image.merge', (['"""RGB"""', '(posim, empty, allblack)'], {}), "('RGB', (posim, empty, allblack))\n", (8005, 8038), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((8056, 8080), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['newImage'], {}), '(newImage)\n', (8070, 8080), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2110, 2183), 'os.path.join', 'os.path.join', (['"""PreviewImages"""', 'pat', '"""geojson_annotations"""', 'annotationfile'], {}), "('PreviewImages', pat, 'geojson_annotations', annotationfile)\n", (2122, 2183), False, 'import os\n'), ((2811, 2842), 'os.path.join', 'os.path.join', (['"""MultiTIFFs"""', 'pat'], {}), "('MultiTIFFs', pat)\n", (2823, 2842), False, 'import os\n'), ((3758, 3790), 'numpy.quantile', 'np.quantile', (['chanpix[mask]', 'qmax'], {}), '(chanpix[mask], qmax)\n', (3769, 3790), True, 'import numpy as np\n'), ((3815, 3841), 'numpy.quantile', 'np.quantile', (['chanpix', 'qmax'], {}), '(chanpix, qmax)\n', (3826, 3841), True, 'import numpy as np\n'), ((4062, 4087), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(6)', '(10)', '(l + 1)'], {}), '(6, 10, l + 1)\n', (4073, 4087), True, 'import matplotlib.pyplot as plt\n'), ((4107, 4127), 'numpy.log', 'np.log', (['(allpix + eps)'], {}), '(allpix + eps)\n', (4113, 4127), True, 'import numpy as np\n'), ((4898, 4928), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['mlabel'], {'figure': 'fig'}), '(mlabel, figure=fig)\n', (4908, 4928), True, 'import matplotlib.pyplot as plt\n'), ((5140, 5181), 'numpy.logical_and', 'np.logical_and', (['mask', '(chanpix > pixthresh)'], {}), '(mask, chanpix > pixthresh)\n', (5154, 5181), True, 'import numpy as np\n'), ((5248, 5263), 'numpy.mean', 'np.mean', (['pospix'], {}), '(pospix)\n', (5255, 5263), True, 'import numpy as np\n'), ((5289, 5306), 'numpy.median', 'np.median', (['pospix'], {}), '(pospix)\n', (5298, 5306), True, 'import numpy as np\n'), ((5334, 5349), 'numpy.mean', 'np.mean', (['allpix'], {}), '(allpix)\n', (5341, 5349), True, 'import numpy as np\n'), ((5379, 5396), 'numpy.median', 'np.median', (['allpix'], {}), '(allpix)\n', (5388, 5396), True, 'import numpy as np\n'), ((5423, 5436), 'numpy.sum', 'np.sum', (['maskp'], {}), '(maskp)\n', (5429, 5436), True, 'import numpy as np\n'), ((7631, 7680), 'numpy.array', 'np.array', (['((arr > pixthresh) * 255)'], {'dtype': 'np.uint8'}), '((arr > pixthresh) * 255, dtype=np.uint8)\n', (7639, 7680), True, 'import numpy as np\n'), ((7714, 7743), 'os.path.join', 'os.path.join', (['imdir', 'filename'], {}), '(imdir, filename)\n', (7726, 7743), False, 'import os\n'), ((7919, 7961), 'numpy.zeros', 'np.zeros', (['posim.size[::-1]'], {'dtype': 'np.uint8'}), '(posim.size[::-1], dtype=np.uint8)\n', (7927, 7961), True, 'import numpy as np\n'), ((8152, 8178), 'numpy.average', 'np.average', (['coords'], {'axis': '(0)'}), '(coords, axis=0)\n', (8162, 8178), True, 'import numpy as np\n'), ((8313, 8359), 'os.path.join', 'os.path.join', (['anndir', "(annroot + '_' + filename)"], {}), "(anndir, annroot + '_' + filename)\n", (8325, 8359), False, 'import os\n'), ((4421, 4444), 'numpy.exp', 'np.exp', (['bins[changebin]'], {}), '(bins[changebin])\n', (4427, 4444), True, 'import numpy as np\n'), ((4183, 4207), 'numpy.linspace', 'np.linspace', (['(-1)', '(12)', '(131)'], {}), '(-1, 12, 131)\n', (4194, 4207), True, 'import numpy as np\n'), ((4526, 4550), 'numpy.ceil', 'np.ceil', (['(pixthresh + eps)'], {}), '(pixthresh + eps)\n', (4533, 4550), True, 'import numpy as np\n'), ((4622, 4646), 'numpy.ceil', 'np.ceil', (['(pixtadapt + eps)'], {}), '(pixtadapt + eps)\n', (4629, 4646), True, 'import numpy as np\n'), ((4725, 4746), 'numpy.ceil', 'np.ceil', (['(pixtqm + eps)'], {}), '(pixtqm + eps)\n', (4732, 4746), True, 'import numpy as np\n'), ((4820, 4841), 'numpy.ceil', 'np.ceil', (['(pixtqa + eps)'], {}), '(pixtqa + eps)\n', (4827, 4841), True, 'import numpy as np\n'), ((4998, 5007), 'numpy.max', 'np.max', (['n'], {}), '(n)\n', (5004, 5007), True, 'import numpy as np\n'), ((5700, 5728), 'numpy.corrcoef', 'np.corrcoef', (['pospix', 'pospix2'], {}), '(pospix, pospix2)\n', (5711, 5728), True, 'import numpy as np\n'), ((2955, 2978), 'os.path.join', 'os.path.join', (['root', 'fnm'], {}), '(root, fnm)\n', (2967, 2978), False, 'import os\n'), ((4214, 4237), 'numpy.log', 'np.log', (['(pixthresh + eps)'], {}), '(pixthresh + eps)\n', (4220, 4237), True, 'import numpy as np\n'), ((4376, 4390), 'numpy.diff', 'np.diff', (['n[5:]'], {}), '(n[5:])\n', (4383, 4390), True, 'import numpy as np\n'), ((4970, 4994), 'numpy.ceil', 'np.ceil', (['(pixtadapt + eps)'], {}), '(pixtadapt + eps)\n', (4977, 4994), True, 'import numpy as np\n'), ((4243, 4264), 'numpy.log', 'np.log', (['(chanpix + eps)'], {}), '(chanpix + eps)\n', (4249, 4264), True, 'import numpy as np\n'), ((5025, 5049), 'numpy.ceil', 'np.ceil', (['(pixtadapt + eps)'], {}), '(pixtadapt + eps)\n', (5032, 5049), True, 'import numpy as np\n')] |
from typing import List, Dict, Set, Optional
import numpy as np
from pyitlib import discrete_random_variable as drv
class CSScorer:
"""
computes category-separation:
a measure of how close next-word probability distributions for one category are to those of another
"""
def __init__(self,
) -> None:
pass
def calc_score(self,
ps: np.ndarray,
qs: np.ndarray,
metric: str = 'js', # 'xe' is faster than 'js' but not normalized
max_rows: int = 32,
) -> float:
"""
measure bits divergence of a set of next-word predictions from another set of next-word predictions
note: when using cross-entropy, argument ordering matters:
"p" is a true probability distribution
"q" is an approximation
note:
computation of divergence checks for NaNs. this is done in 2 ways, slow or fast, depending on dtype:
if dtype is float64, fast check is performed (float32 results in slow check)
the slow check is much slower and should be avoided.
"""
assert np.ndim(ps) == 2
assert np.ndim(qs) == 2
assert ps.shape == qs.shape
assert np.sum(qs[0]).round(1).item() == 1.0, np.sum(qs[0]).round(1).item()
if ps.dtype != np.float64 or qs.dtype != np.float64:
raise TypeError('To aovid slow NaN check, cast input to CSScorer.calc_score to float64.')
if max_rows < len(qs):
print(f'Randomly sampling input because max_rows={max_rows} < num rows in input={len(qs)}', flush=True)
ps = ps[np.random.choice(len(ps), size=max_rows, replace=False)]
qs = qs[np.random.choice(len(qs), size=max_rows, replace=False)]
if metric == 'xe':
return drv.entropy_cross_pmf(ps, qs, base=2, cartesian_product=True).mean()
elif metric == 'js':
return drv.divergence_jensenshannon_pmf(ps, qs, base=2, cartesian_product=True).mean()
else:
raise AttributeError('Invalid arg to "metric".') | [
"pyitlib.discrete_random_variable.divergence_jensenshannon_pmf",
"numpy.ndim",
"numpy.sum",
"pyitlib.discrete_random_variable.entropy_cross_pmf"
] | [((1190, 1201), 'numpy.ndim', 'np.ndim', (['ps'], {}), '(ps)\n', (1197, 1201), True, 'import numpy as np\n'), ((1222, 1233), 'numpy.ndim', 'np.ndim', (['qs'], {}), '(qs)\n', (1229, 1233), True, 'import numpy as np\n'), ((1871, 1932), 'pyitlib.discrete_random_variable.entropy_cross_pmf', 'drv.entropy_cross_pmf', (['ps', 'qs'], {'base': '(2)', 'cartesian_product': '(True)'}), '(ps, qs, base=2, cartesian_product=True)\n', (1892, 1932), True, 'from pyitlib import discrete_random_variable as drv\n'), ((1328, 1341), 'numpy.sum', 'np.sum', (['qs[0]'], {}), '(qs[0])\n', (1334, 1341), True, 'import numpy as np\n'), ((1988, 2060), 'pyitlib.discrete_random_variable.divergence_jensenshannon_pmf', 'drv.divergence_jensenshannon_pmf', (['ps', 'qs'], {'base': '(2)', 'cartesian_product': '(True)'}), '(ps, qs, base=2, cartesian_product=True)\n', (2020, 2060), True, 'from pyitlib import discrete_random_variable as drv\n'), ((1290, 1303), 'numpy.sum', 'np.sum', (['qs[0]'], {}), '(qs[0])\n', (1296, 1303), True, 'import numpy as np\n')] |
from __future__ import division
import os, scipy.io
import re
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import glob
import cv2
import argparse
from PIL import Image
from utils import *
parser = argparse.ArgumentParser(description='Testing')
parser.add_argument('--model', dest='model', type=str, default='finetune', help='model type')
parser.add_argument('--gpu_id', dest='gpu_id', type=int, default=0, help='gpu id')
parser.add_argument('--output_dir', type=str, default='./results/finetune/', help='output path')
parser.add_argument('--vis_data', type=bool, default=False, help='whether to visualize noisy and gt data')
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id)
isp = torch.load('isp/ISP_CNN.pth').cuda()
model = torch.load('model/finetune.pth').cuda()
iso_list = [1600,3200,6400,12800,25600]
for iso in iso_list:
print('processing iso={}'.format(iso))
if not os.path.isdir(args.output_dir+'ISO{}'.format(iso)):
os.makedirs(args.output_dir+'ISO{}'.format(iso))
f = open('{}_model_test_psnr_and_ssim_on_iso{}.txt'.format(args.model, iso), 'w')
context = 'ISO{}'.format(iso) + '\n'
f.write(context)
scene_avg_raw_psnr = 0
scene_avg_raw_ssim = 0
scene_avg_srgb_psnr = 0
scene_avg_srgb_ssim = 0
for scene_id in range(7,11+1):
context = 'scene{}'.format(scene_id) + '\n'
f.write(context)
frame_avg_raw_psnr = 0
frame_avg_raw_ssim = 0
frame_avg_srgb_psnr = 0
frame_avg_srgb_ssim = 0
for i in range(1,7+1):
frame_list = []
for j in range(-1,2):
if (i+j)<1:
raw = cv2.imread('./data/CRVD_data/scene{}/ISO{}/frame1_noisy0.tiff'.format(scene_id, iso),-1)
input_full = np.expand_dims(pack_gbrg_raw(raw), axis=0)
frame_list.append(input_full)
elif (i+j)>7:
raw = cv2.imread('./data/CRVD_data/scene{}/ISO{}/frame7_noisy0.tiff'.format(scene_id, iso),-1)
input_full = np.expand_dims(pack_gbrg_raw(raw), axis=0)
frame_list.append(input_full)
else:
raw = cv2.imread('./data/CRVD_data/scene{}/ISO{}/frame{}_noisy0.tiff'.format(scene_id, iso, i+j),-1)
input_full = np.expand_dims(pack_gbrg_raw(raw), axis=0)
frame_list.append(input_full)
input_data = np.concatenate(frame_list, axis=3)
test_result = test_big_size_raw(input_data, model, patch_h = 256, patch_w = 256, patch_h_overlap = 64, patch_w_overlap = 64)
test_result = depack_gbrg_raw(test_result)
test_gt = cv2.imread('./data/CRVD_data/scene{}/ISO{}/frame{}_clean_and_slightly_denoised.tiff'.format(scene_id, iso, i),-1).astype(np.float32)
test_gt = (test_gt-240)/(2**12-1-240)
test_raw_psnr = compare_psnr(test_gt,(np.uint16(test_result*(2**12-1-240)+240).astype(np.float32)-240)/(2**12-1-240), data_range=1.0)
test_raw_ssim = compute_ssim_for_packed_raw(test_gt, (np.uint16(test_result*(2**12-1-240)+240).astype(np.float32)-240)/(2**12-1-240))
print('scene {} frame{} test raw psnr : {}, test raw ssim : {} '.format(scene_id, i, test_raw_psnr, test_raw_ssim))
context = 'raw psnr/ssim: {}/{}'.format(test_raw_psnr,test_raw_ssim) + '\n'
f.write(context)
frame_avg_raw_psnr += test_raw_psnr
frame_avg_raw_ssim += test_raw_ssim
output = test_result*(2**12-1-240)+240
save_result = Image.fromarray(np.uint16(output))
save_result.save(args.output_dir+'ISO{}/scene{}_frame{}_denoised_raw.tiff'.format(iso, scene_id, i))
noisy_raw_frame = preprocess(input_data[:,:,:,4:8])
noisy_srgb_frame = postprocess(isp(noisy_raw_frame))[0]
if args.vis_data:
cv2.imwrite(args.output_dir+'ISO{}/scene{}_frame{}_noisy_sRGB.png'.format(iso, scene_id, i), np.uint8(noisy_srgb_frame*255))
denoised_raw_frame = preprocess(np.expand_dims(pack_gbrg_raw(output),axis=0))
denoised_srgb_frame = postprocess(isp(denoised_raw_frame))[0]
cv2.imwrite(args.output_dir+'ISO{}/scene{}_frame{}_denoised_sRGB.png'.format(iso, scene_id, i), np.uint8(denoised_srgb_frame*255))
gt_raw_frame = np.expand_dims(pack_gbrg_raw(test_gt*(2**12-1-240)+240), axis=0)
gt_srgb_frame = postprocess(isp(preprocess(gt_raw_frame)))[0]
if args.vis_data:
cv2.imwrite(args.output_dir+'ISO{}/scene{}_frame{}_gt_sRGB.png'.format(iso, scene_id, i), np.uint8(gt_srgb_frame*255))
test_srgb_psnr = compare_psnr(np.uint8(gt_srgb_frame*255).astype(np.float32)/255, np.uint8(denoised_srgb_frame*255).astype(np.float32)/255, data_range=1.0)
test_srgb_ssim = compare_ssim(np.uint8(gt_srgb_frame*255).astype(np.float32)/255, np.uint8(denoised_srgb_frame*255).astype(np.float32)/255, data_range=1.0, multichannel=True)
print('scene {} frame{} test srgb psnr : {}, test srgb ssim : {} '.format(scene_id, i, test_srgb_psnr, test_srgb_ssim))
context = 'srgb psnr/ssim: {}/{}'.format(test_srgb_psnr,test_srgb_ssim) + '\n'
f.write(context)
frame_avg_srgb_psnr += test_srgb_psnr
frame_avg_srgb_ssim += test_srgb_ssim
frame_avg_raw_psnr = frame_avg_raw_psnr/7
frame_avg_raw_ssim = frame_avg_raw_ssim/7
frame_avg_srgb_psnr = frame_avg_srgb_psnr/7
frame_avg_srgb_ssim = frame_avg_srgb_ssim/7
context = 'frame average raw psnr:{},frame average raw ssim:{}'.format(frame_avg_raw_psnr,frame_avg_raw_ssim) + '\n'
f.write(context)
context = 'frame average srgb psnr:{},frame average srgb ssim:{}'.format(frame_avg_srgb_psnr,frame_avg_srgb_ssim) + '\n'
f.write(context)
scene_avg_raw_psnr += frame_avg_raw_psnr
scene_avg_raw_ssim += frame_avg_raw_ssim
scene_avg_srgb_psnr += frame_avg_srgb_psnr
scene_avg_srgb_ssim += frame_avg_srgb_ssim
scene_avg_raw_psnr = scene_avg_raw_psnr/5
scene_avg_raw_ssim = scene_avg_raw_ssim/5
scene_avg_srgb_psnr = scene_avg_srgb_psnr/5
scene_avg_srgb_ssim = scene_avg_srgb_ssim/5
context = 'scene average raw psnr:{},scene frame average raw ssim:{}'.format(scene_avg_raw_psnr,scene_avg_raw_ssim) + '\n'
f.write(context)
context = 'scene average srgb psnr:{},scene frame average srgb ssim:{}'.format(scene_avg_srgb_psnr,scene_avg_srgb_ssim) + '\n'
f.write(context)
| [
"numpy.uint8",
"argparse.ArgumentParser",
"torch.load",
"numpy.uint16",
"numpy.concatenate"
] | [((236, 282), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Testing"""'}), "(description='Testing')\n", (259, 282), False, 'import argparse\n'), ((753, 782), 'torch.load', 'torch.load', (['"""isp/ISP_CNN.pth"""'], {}), "('isp/ISP_CNN.pth')\n", (763, 782), False, 'import torch\n'), ((803, 835), 'torch.load', 'torch.load', (['"""model/finetune.pth"""'], {}), "('model/finetune.pth')\n", (813, 835), False, 'import torch\n'), ((2502, 2536), 'numpy.concatenate', 'np.concatenate', (['frame_list'], {'axis': '(3)'}), '(frame_list, axis=3)\n', (2516, 2536), True, 'import numpy as np\n'), ((3698, 3715), 'numpy.uint16', 'np.uint16', (['output'], {}), '(output)\n', (3707, 3715), True, 'import numpy as np\n'), ((4407, 4442), 'numpy.uint8', 'np.uint8', (['(denoised_srgb_frame * 255)'], {}), '(denoised_srgb_frame * 255)\n', (4415, 4442), True, 'import numpy as np\n'), ((4102, 4134), 'numpy.uint8', 'np.uint8', (['(noisy_srgb_frame * 255)'], {}), '(noisy_srgb_frame * 255)\n', (4110, 4134), True, 'import numpy as np\n'), ((4745, 4774), 'numpy.uint8', 'np.uint8', (['(gt_srgb_frame * 255)'], {}), '(gt_srgb_frame * 255)\n', (4753, 4774), True, 'import numpy as np\n'), ((4817, 4846), 'numpy.uint8', 'np.uint8', (['(gt_srgb_frame * 255)'], {}), '(gt_srgb_frame * 255)\n', (4825, 4846), True, 'import numpy as np\n'), ((4869, 4904), 'numpy.uint8', 'np.uint8', (['(denoised_srgb_frame * 255)'], {}), '(denoised_srgb_frame * 255)\n', (4877, 4904), True, 'import numpy as np\n'), ((4985, 5014), 'numpy.uint8', 'np.uint8', (['(gt_srgb_frame * 255)'], {}), '(gt_srgb_frame * 255)\n', (4993, 5014), True, 'import numpy as np\n'), ((5037, 5072), 'numpy.uint8', 'np.uint8', (['(denoised_srgb_frame * 255)'], {}), '(denoised_srgb_frame * 255)\n', (5045, 5072), True, 'import numpy as np\n'), ((3003, 3053), 'numpy.uint16', 'np.uint16', (['(test_result * (2 ** 12 - 1 - 240) + 240)'], {}), '(test_result * (2 ** 12 - 1 - 240) + 240)\n', (3012, 3053), True, 'import numpy as np\n'), ((3165, 3215), 'numpy.uint16', 'np.uint16', (['(test_result * (2 ** 12 - 1 - 240) + 240)'], {}), '(test_result * (2 ** 12 - 1 - 240) + 240)\n', (3174, 3215), True, 'import numpy as np\n')] |
#!/usr/bin/python
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from keras.models import Sequential
from keras.layers import LSTM,Dense, GRU
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
import os
import math
# Input data files are available in the "data/" directory.
# split the data into training and test
split_ratio = 0.95
# how many previous days as input
steps = 20
# how many inputs
num_input =5
symbol = '^GSPC'
scl = MinMaxScaler()
def scale_data(myinput):
result = myinput
# passed in myinput is dataGrid.Series and needs to be convered to list first
result = result.tolist()
# MinMaxScaler needs 2D array so just change it from n to (n,1)
# for reshape, number of elements must be exactly the same
result = np.reshape(result, (len(result), 1))
# nornalize the data
result = scl.fit_transform(result)
return result
def main_multi_files():
global num_input
#list files from data
path = './data'
common_start_date = ''
files = []
filelist = os.listdir(path)
for file in filelist:
if '.csv' in file:
files.append(file)
# print(file)
df = pd.read_csv('./data/' + file, usecols = ["Date"])
mydate = df.Date[0]
if mydate > common_start_date:
common_start_date = mydate
print(common_start_date)
print("number of files %d"%(len(files)))
# use pandas to read csv file
# result is a 2D data structure with labels
data = pd.read_csv('./data/' + symbol + '.csv')
data = data[data.Date >= common_start_date]
open2 = scale_data(data.Open)
high = scale_data(data.High)
low = scale_data(data.Low)
volume = scale_data(data.Volume)
dates = data.Date
dates = dates.tolist()
lenth_GRPC = len(data.AdjClose)
print("lenth_GRPC = %d"%(lenth_GRPC))
mydata = []
for file in files:
if ("^GSPC" in file) == False:
df = pd.read_csv('./data/' + file, usecols = ["Date","AdjClose"])
df = df[df.Date >= common_start_date]
myclose = scale_data(df.AdjClose)
if len(myclose) != lenth_GRPC:
print("%s, len = %d"%(file, len(myclose)))
mydata.append(myclose)
adjclose = scale_data(data.AdjClose)
lenth_otherclose = len(mydata)
num_input = num_input + lenth_otherclose
print("num_input=%d"%(num_input))
num_elements_one_input = steps * num_input
# process the data to input and output
# X is input, 1D with n * steps * num_input elements
# y is output, 1D with n elements
#X, y = processData(adjclose, steps)
X, y, z = processData_multi(open2, high, low, volume, adjclose, steps, dates, mydata)
# split the data into 90% for train and testing
# split_point has to be an integer so use //
splity = int(len(y) * split_ratio)
# remember that for each output element there are num_elements_one_input
splitx = int(splity * num_elements_one_input)
# :splitx = [0, splitx), splitx: = [splitx, len(X))
X_train, X_test = X[:splitx], X[splitx:]
y_train,y_test = y[:splity],y[splity:]
Z_test = z[splity:]
#print first data slice
print(X_train.shape[0])
print(X_test.shape[0])
print(y_train.shape[0])
print(y_test.shape[0])
print(X_train[0])
print(X_test[0])
#Build the model
model = Sequential()
model.add(LSTM(256,input_shape=(steps,num_input)))
# Dense is for output layer
model.add(Dense(1))
# optimizer is the gradient descent algorithm
# mse is the most popular loss function
model.compile(optimizer='adam',loss='mse')
# reshape input from 1D array to 3D so model can use
X_train = X_train.reshape((len(X_train) // num_elements_one_input, steps, num_input))
X_test = X_test.reshape((len(X_test) // num_elements_one_input, steps, num_input))
# train the model
model.fit(X_train,y_train,epochs=10,validation_data=(X_test,y_test),shuffle=False)
# train completed, let's do predict
y_predicted = model.predict(X_test)
# how is predicted comapred with actual?
# we also want to see first half and second half test score
testScore, testScore2, testScore3 = mean_absolute_percentage_error(y_test, y_predicted)
print('Test Score: %.2f MAPE' % (testScore)) # Root Mean Square Error,
print('Test Score 2: %.2f MAPE' % (testScore2))
print('Test Score 3: %.2f MAPE' % (testScore3))
# draw it
# y_test and y_predicted are still in 0 - 1 so we need to call inverse_transform
# to change them into real prices
# as before, scl needs to work on 2D,
# reshape(-1, 1) will do the trick, -1 means it will calculate for us
line1, = plt.plot(Z_test, scl.inverse_transform(y_test.reshape(-1,1)), marker='d', label='Actual')
line2, = plt.plot(Z_test, scl.inverse_transform(y_predicted.reshape(-1,1)), marker='o', label='Predicted')
plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})
plt.show()
def processData_multi(open1, high1, low1, volume1, close1, lb, dates1, othercloses):
X,Y,Z = [],[],[]
for i in range(len(close1)-lb):
for j in range(lb):
X.append(open1[i+j])
X.append(high1[i+j])
X.append(low1[i+j])
X.append(volume1[i+j])
X.append(close1[i+j])
lenth_other_symbols = len(othercloses)
for k in range(lenth_other_symbols):
otherclose = othercloses[k]
lenth_num_dates = len(otherclose)
X.append(otherclose[i+j])
Y.append(close1[(i+lb)])
Z.append(dates1[(i+lb)])
return np.array(X),np.array(Y),np.array(Z)
def mean_absolute_percentage_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
diff = []
diff2 = []
diff3 = []
for i in range(len(y_true)):
#print("%.3f, %.3f, %.3f"%(y_true[i], y_pred[i], np.abs((y_true[i] - y_pred[i]) / y_true[i])))
diff.append(np.abs((y_true[i] - y_pred[i]) / y_true[i]))
if i < len(y_true)/2:
diff2.append(np.abs((y_true[i] - y_pred[i]) / y_true[i]))
else:
diff3.append(np.abs((y_true[i] - y_pred[i]) / y_true[i]))
#return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
mymean = np.mean(diff)
mymean2 = np.mean(diff2)
mymean3 = np.mean(diff3)
return mymean * 100, mymean2 * 100, mymean3 * 100
if __name__ == '__main__':
main_multi_files()
| [
"matplotlib.pyplot.show",
"numpy.abs",
"pandas.read_csv",
"keras.layers.LSTM",
"sklearn.preprocessing.MinMaxScaler",
"numpy.mean",
"keras.layers.Dense",
"numpy.array",
"keras.models.Sequential",
"matplotlib.legend_handler.HandlerLine2D",
"os.listdir"
] | [((578, 592), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (590, 592), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((1168, 1184), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1178, 1184), False, 'import os\n'), ((1649, 1689), 'pandas.read_csv', 'pd.read_csv', (["('./data/' + symbol + '.csv')"], {}), "('./data/' + symbol + '.csv')\n", (1660, 1689), True, 'import pandas as pd\n'), ((3527, 3539), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3537, 3539), False, 'from keras.models import Sequential\n'), ((5138, 5148), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5146, 5148), True, 'import matplotlib.pyplot as plt\n'), ((6457, 6470), 'numpy.mean', 'np.mean', (['diff'], {}), '(diff)\n', (6464, 6470), True, 'import numpy as np\n'), ((6485, 6499), 'numpy.mean', 'np.mean', (['diff2'], {}), '(diff2)\n', (6492, 6499), True, 'import numpy as np\n'), ((6514, 6528), 'numpy.mean', 'np.mean', (['diff3'], {}), '(diff3)\n', (6521, 6528), True, 'import numpy as np\n'), ((3554, 3595), 'keras.layers.LSTM', 'LSTM', (['(256)'], {'input_shape': '(steps, num_input)'}), '(256, input_shape=(steps, num_input))\n', (3558, 3595), False, 'from keras.layers import LSTM, Dense, GRU\n'), ((3642, 3650), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (3647, 3650), False, 'from keras.layers import LSTM, Dense, GRU\n'), ((5800, 5811), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (5808, 5811), True, 'import numpy as np\n'), ((5812, 5823), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (5820, 5823), True, 'import numpy as np\n'), ((5824, 5835), 'numpy.array', 'np.array', (['Z'], {}), '(Z)\n', (5832, 5835), True, 'import numpy as np\n'), ((5916, 5932), 'numpy.array', 'np.array', (['y_true'], {}), '(y_true)\n', (5924, 5932), True, 'import numpy as np\n'), ((5934, 5950), 'numpy.array', 'np.array', (['y_pred'], {}), '(y_pred)\n', (5942, 5950), True, 'import numpy as np\n'), ((1312, 1359), 'pandas.read_csv', 'pd.read_csv', (["('./data/' + file)"], {'usecols': "['Date']"}), "('./data/' + file, usecols=['Date'])\n", (1323, 1359), True, 'import pandas as pd\n'), ((2096, 2155), 'pandas.read_csv', 'pd.read_csv', (["('./data/' + file)"], {'usecols': "['Date', 'AdjClose']"}), "('./data/' + file, usecols=['Date', 'AdjClose'])\n", (2107, 2155), True, 'import pandas as pd\n'), ((6151, 6194), 'numpy.abs', 'np.abs', (['((y_true[i] - y_pred[i]) / y_true[i])'], {}), '((y_true[i] - y_pred[i]) / y_true[i])\n', (6157, 6194), True, 'import numpy as np\n'), ((5105, 5131), 'matplotlib.legend_handler.HandlerLine2D', 'HandlerLine2D', ([], {'numpoints': '(4)'}), '(numpoints=4)\n', (5118, 5131), False, 'from matplotlib.legend_handler import HandlerLine2D\n'), ((6251, 6294), 'numpy.abs', 'np.abs', (['((y_true[i] - y_pred[i]) / y_true[i])'], {}), '((y_true[i] - y_pred[i]) / y_true[i])\n', (6257, 6294), True, 'import numpy as np\n'), ((6335, 6378), 'numpy.abs', 'np.abs', (['((y_true[i] - y_pred[i]) / y_true[i])'], {}), '((y_true[i] - y_pred[i]) / y_true[i])\n', (6341, 6378), True, 'import numpy as np\n')] |
import numpy as np
from megaverse.megaverse_env import MegaverseEnv
env = MegaverseEnv(
'ObstaclesHard',
num_envs=2, num_agents_per_env=2,
num_simulation_threads=4, use_vulkan=True,
params={},
)
env.reset()
while True:
actions = [env.action_space.sample() for _ in range(env.num_agents)]
obs, rewards, dones, infos = env.step(actions)
if np.any(dones):
break
env.render()
env.close()
| [
"numpy.any",
"megaverse.megaverse_env.MegaverseEnv"
] | [((76, 197), 'megaverse.megaverse_env.MegaverseEnv', 'MegaverseEnv', (['"""ObstaclesHard"""'], {'num_envs': '(2)', 'num_agents_per_env': '(2)', 'num_simulation_threads': '(4)', 'use_vulkan': '(True)', 'params': '{}'}), "('ObstaclesHard', num_envs=2, num_agents_per_env=2,\n num_simulation_threads=4, use_vulkan=True, params={})\n", (88, 197), False, 'from megaverse.megaverse_env import MegaverseEnv\n'), ((369, 382), 'numpy.any', 'np.any', (['dones'], {}), '(dones)\n', (375, 382), True, 'import numpy as np\n')] |
import numpy as np
from .helpers import *
from .instance import *
def evaluate_EA():
list_instances = get_list_instance_name()
instance = Instance(config, 'Pixelcopter') # task 8 bit
arr = np.asarray(instance.results_by_tasks)
best_result = arr # task 8bit max
# best_result = np.sort(best_result, axis = -1)
print (best_result.shape)
results = []
for best in best_result:
result = []
for el in best:
re = []
for tmp in el:
if(len(re) <= tmp[3]):
re.append([])
re[int(tmp[3])].append(tmp)
result.append(re)
result = np.asarray(result)
print (result.shape)
result = result[:,:,:,2]
results.append(result)
results = np.asarray(results)
convergence_train(results)
compare_final_score(results) # if use to evaluate rl problem
# compare mfea2 & sgd
def compare_mfea2_sgd(method_id):
instance = Instance(config, 'nbit_10_1') # task 8 bit
result_mfea2_8bit = np.asarray(instance.results_subtask(instance_id=24, method_id=3))
result_sgd_8bit = np.asarray(instance.results_subtask(instance_id=1, method_id=method_id))
result_mfea2_8bit = result_mfea2_8bit[result_mfea2_8bit[:, 5] <= 200000]
result_mfea2_8bit = group_result(result_mfea2_8bit, 3)
result_sgd_8bit = group_result(result_sgd_8bit, 3)
result_mfea2_8bit = result_mfea2_8bit[:,:, [2,5]]
result_sgd_8bit = result_sgd_8bit[:,:, [2,5]]
result = (result_mfea2_8bit, result_sgd_8bit)
XRange = [_[0][:, [1]].T for _ in result]
convergence(result, ['MFEA2', 'SGD'], XRange)
def mfea2_rmp(method_id):
instance = Instance(config, 'breastCancer') # task 8 bit
result_mfea2_8bit = np.asarray(instance.results_rmp(method_id=method_id))
print (result_mfea2_8bit.shape)
result_mfea2_8bit = group_result_by_index(re=result_mfea2_8bit, index=0, number_of_el=3, margin=10)
print (result_mfea2_8bit.shape)
results = []
for ins in result_mfea2_8bit:
result = group_result_by_index(ins, index=5, number_of_el=29, margin=0)
results.append(result)
results = np.asarray(results)[:,:,:, [2,3]]
rmp_results = results[0, :, :, 1]
rmp = []
for r in rmp_results:
tmp_results = [tmp.split(' - ') for tmp in r]
rmp.append(tmp_results)
re = []
for r in rmp:
tasks = [[] for _ in range(3)]
for tmp in r:
tasks[0].append(float(tmp[0]))
tasks[1].append(float(tmp[1]))
tasks[2].append(float(tmp[2]))
re.append(tasks)
re = np.asarray(re)
print (results.shape, re.shape)
print (re[:10, :])
final_results = (results[0, :, :, 0], results[1, :, :, 0], results[2, :, :, 0], re[:, 0, :], re[:, 1, :], re[:, 2, :])
XRange = [[np.arange(1000)] for _ in final_results]
convergence(final_results, ['TASK1', 'TASK2', 'TASK3', 'RMP1-2', 'RMP1-3', 'RMP2-3'], XRange)
| [
"numpy.asarray",
"numpy.arange"
] | [((204, 241), 'numpy.asarray', 'np.asarray', (['instance.results_by_tasks'], {}), '(instance.results_by_tasks)\n', (214, 241), True, 'import numpy as np\n'), ((789, 808), 'numpy.asarray', 'np.asarray', (['results'], {}), '(results)\n', (799, 808), True, 'import numpy as np\n'), ((2631, 2645), 'numpy.asarray', 'np.asarray', (['re'], {}), '(re)\n', (2641, 2645), True, 'import numpy as np\n'), ((663, 681), 'numpy.asarray', 'np.asarray', (['result'], {}), '(result)\n', (673, 681), True, 'import numpy as np\n'), ((2166, 2185), 'numpy.asarray', 'np.asarray', (['results'], {}), '(results)\n', (2176, 2185), True, 'import numpy as np\n'), ((2843, 2858), 'numpy.arange', 'np.arange', (['(1000)'], {}), '(1000)\n', (2852, 2858), True, 'import numpy as np\n')] |
# Load movies from Kafka, generate embeddings of movie titles with BERT, then save embeddings to
# redis and HDFS.
import os
import subprocess
from time import localtime, strftime
import numpy as np
import redis
import tensorflow_hub as hub
import tensorflow_text as text
from kafka import KafkaConsumer
HDFS_PATH_MOVIE_EMBEDDINGS="hdfs:///sparrow_recsys/movie-embeddings/"
HDFS_MOVIE_EMBEDDING_BATCH_SIZE=3
REDIS_SERVER="localhost"
REDIS_PORT=6379
KAFKA_SERVERS="localhost:9092"
REDIS_KEY_MOVIE_EMBEDDING_VERSION="sparrow_recsys:version:me"
REDIS_KEY_PREFIX_MOVIE_EMBEDDING="sparrow_recsys:me"
tfhub_handle_preprocess = "https://hub.tensorflow.google.cn/tensorflow/bert_en_uncased_preprocess/3"
tfhub_handle_encoder = "https://hub.tensorflow.google.cn/tensorflow/small_bert/bert_en_uncased_L-4_H-128_A-2/2"
bert_preprocess_model = hub.KerasLayer(tfhub_handle_preprocess)
bert_model = hub.KerasLayer(tfhub_handle_encoder)
current_batch_size = 0
def process_movies(movies: []):
# get embeddings
movie_ids = list(map(lambda x: int(x.decode('utf-8')), movies[:, 0]))
movie_titles = movies[:, 1]
text_preprocessed = bert_preprocess_model(movie_titles)
bert_results = bert_model(text_preprocessed)
movie_embeddings = list(map(lambda embeddings: ','.join(list(map(lambda f: str(f), embeddings.numpy()))), bert_results["pooled_output"]))
movie_embeddings = list(zip(movie_ids, movie_embeddings))
# remove duplicates
movie_embeddings = dict(sorted(dict(movie_embeddings).items()))
movie_embeddings = list(movie_embeddings.items())
# save to file
tmp_file_name = 'kafka-movie-embeddings.csv'
with open(tmp_file_name, 'a') as tmp_file:
list(map(lambda x: tmp_file.write(f"{x[0]}\t{x[1]}\n"), movie_embeddings))
tmp_file.close()
# save to redis
r = redis.Redis(host=REDIS_SERVER, port=REDIS_PORT)
version = r.get(REDIS_KEY_MOVIE_EMBEDDING_VERSION)
if version is None:
version = strftime("%Y%m%d%H%M%S", localtime())
r.set(REDIS_KEY_MOVIE_EMBEDDING_VERSION, version)
print(f"Redis movie embedding version is updated to: {version}")
else:
version = version.decode('utf-8')
print(f"Using existing movie embedding version in redis: {version}")
movie_embeddings_redis = list(map(
lambda x: (f"{REDIS_KEY_PREFIX_MOVIE_EMBEDDING}:{version}:{x[0]}", x[1]),
movie_embeddings))
r.mset(dict(movie_embeddings_redis))
global current_batch_size
current_batch_size += len(movies)
if current_batch_size >= HDFS_MOVIE_EMBEDDING_BATCH_SIZE:
# save to HDFS
batch_id=strftime("%Y%m%d%H%M%S", localtime())
if os.path.isfile(tmp_file_name):
subprocess.Popen(["hadoop", "fs", "-mkdir", "-p",
f"{HDFS_PATH_MOVIE_EMBEDDINGS}{batch_id}/"], stdout=subprocess.PIPE).communicate()
subprocess.Popen(["hadoop", "fs", "-put", f"./{tmp_file_name}",
f"{HDFS_PATH_MOVIE_EMBEDDINGS}{batch_id}/part-0"], stdout=subprocess.PIPE).communicate()
print(f"{current_batch_size} movie embeddings are uploaded to HDFS: {HDFS_PATH_MOVIE_EMBEDDINGS}{batch_id}/")
os.remove(tmp_file_name)
current_batch_size = 0
# load movies from kafka
consumer = KafkaConsumer('sparrow-recsys-new-movie',
group_id='sparrow_recsys.bert',
bootstrap_servers=KAFKA_SERVERS,
auto_offset_reset='latest')
for msg in consumer:
print(msg.value)
movies = []
movie_str = msg.value
movie_info = movie_str.split(b"\t")
if len(movie_info) == 3:
movies.append(movie_info)
movies = np.array(movies)
process_movies(movies)
| [
"redis.Redis",
"os.remove",
"subprocess.Popen",
"tensorflow_hub.KerasLayer",
"os.path.isfile",
"numpy.array",
"time.localtime",
"kafka.KafkaConsumer"
] | [((865, 904), 'tensorflow_hub.KerasLayer', 'hub.KerasLayer', (['tfhub_handle_preprocess'], {}), '(tfhub_handle_preprocess)\n', (879, 904), True, 'import tensorflow_hub as hub\n'), ((919, 955), 'tensorflow_hub.KerasLayer', 'hub.KerasLayer', (['tfhub_handle_encoder'], {}), '(tfhub_handle_encoder)\n', (933, 955), True, 'import tensorflow_hub as hub\n'), ((3406, 3544), 'kafka.KafkaConsumer', 'KafkaConsumer', (['"""sparrow-recsys-new-movie"""'], {'group_id': '"""sparrow_recsys.bert"""', 'bootstrap_servers': 'KAFKA_SERVERS', 'auto_offset_reset': '"""latest"""'}), "('sparrow-recsys-new-movie', group_id='sparrow_recsys.bert',\n bootstrap_servers=KAFKA_SERVERS, auto_offset_reset='latest')\n", (3419, 3544), False, 'from kafka import KafkaConsumer\n'), ((1881, 1928), 'redis.Redis', 'redis.Redis', ([], {'host': 'REDIS_SERVER', 'port': 'REDIS_PORT'}), '(host=REDIS_SERVER, port=REDIS_PORT)\n', (1892, 1928), False, 'import redis\n'), ((2760, 2789), 'os.path.isfile', 'os.path.isfile', (['tmp_file_name'], {}), '(tmp_file_name)\n', (2774, 2789), False, 'import os\n'), ((3833, 3849), 'numpy.array', 'np.array', (['movies'], {}), '(movies)\n', (3841, 3849), True, 'import numpy as np\n'), ((2056, 2067), 'time.localtime', 'localtime', ([], {}), '()\n', (2065, 2067), False, 'from time import localtime, strftime\n'), ((2735, 2746), 'time.localtime', 'localtime', ([], {}), '()\n', (2744, 2746), False, 'from time import localtime, strftime\n'), ((3303, 3327), 'os.remove', 'os.remove', (['tmp_file_name'], {}), '(tmp_file_name)\n', (3312, 3327), False, 'import os\n'), ((2804, 2926), 'subprocess.Popen', 'subprocess.Popen', (["['hadoop', 'fs', '-mkdir', '-p', f'{HDFS_PATH_MOVIE_EMBEDDINGS}{batch_id}/']"], {'stdout': 'subprocess.PIPE'}), "(['hadoop', 'fs', '-mkdir', '-p',\n f'{HDFS_PATH_MOVIE_EMBEDDINGS}{batch_id}/'], stdout=subprocess.PIPE)\n", (2820, 2926), False, 'import subprocess\n'), ((2981, 3123), 'subprocess.Popen', 'subprocess.Popen', (["['hadoop', 'fs', '-put', f'./{tmp_file_name}',\n f'{HDFS_PATH_MOVIE_EMBEDDINGS}{batch_id}/part-0']"], {'stdout': 'subprocess.PIPE'}), "(['hadoop', 'fs', '-put', f'./{tmp_file_name}',\n f'{HDFS_PATH_MOVIE_EMBEDDINGS}{batch_id}/part-0'], stdout=subprocess.PIPE)\n", (2997, 3123), False, 'import subprocess\n')] |
#!/usr/bin/env python
'''
NOTE: This uses the alannlp PyTorch implementation of Elmo!
Process a line corpus and convert text to elmo embeddings, save as json array of sentence vectors.
This expects the sents corpus which has fields title, article, domains. and treates
title as the first sentence, then splits the article sentences. The domains are ignored
'''
import argparse
import os
import json
import math
import torch
from transformers import BertTokenizer, BertModel
import readability
import re
import numpy as np
from scipy import stats
import pandas as pd
from collections import Counter
import warnings
warnings.filterwarnings('ignore')
def normalization(df):
x = np.nan_to_num(stats.zscore(df))
return x
def extract_readability_features(text):
text = re.sub(r'\.', '.\n', text)
text = re.sub(r'\?', '?\n', text)
text = re.sub(r'!', '!\n', text)
features = dict(readability.getmeasures(text, lang='en'))
result = {}
for d in features:
result.update(features[d])
del result['paragraphs']
result = pd.Series(result)
return result
def extract_NRC_features(x, sentic_df):
# tokens = re.sub('[^a-zA-Z]', ' ', x).split()
tokens = x.split()
tokens = Counter(tokens)
df = pd.DataFrame.from_dict(tokens, orient='index', columns=['count'])
merged_df = pd.merge(df, sentic_df, left_index=True, right_index=True)
for col in merged_df.columns[1:]:
merged_df[col] *= merged_df["count"]
result = merged_df.sum()
result /= result["count"]
result = result.iloc[1:]
return result
configs = {
"small": "elmo_2x1024_128_2048cnn_1xhighway_options.json",
"medium": "elmo_2x2048_256_2048cnn_1xhighway_options.json",
"original5b": "elmo_2x4096_512_2048cnn_2xhighway_5.5B_options.json",
"original": "elmo_2x4096_512_2048cnn_2xhighway_options.json"
}
models = {
"small": "elmo_2x1024_128_2048cnn_1xhighway_weights.hdf5",
"medium": "elmo_2x2048_256_2048cnn_1xhighway_weights.hdf5",
"original5b": "elmo_2x4096_512_2048cnn_2xhighway_5.5B_weights.hdf5",
"original": "elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5"
}
n_hl = 12
hidden_dim = 768
MODEL = (BertModel, BertTokenizer, 'bert-base-uncased')
model_class, tokenizer_class, pretrained_weights = MODEL
model = model_class.from_pretrained(pretrained_weights, output_hidden_states=True) # output_attentions=False
tokenizer = tokenizer_class.from_pretrained(pretrained_weights, do_lower_case=True)
NRC_path1 = "data/NRC-Emotion-Lexicon.xlsx"
NRC_df1 = pd.read_excel(NRC_path1, index_col=0)
NRC_path2 = "data/NRC-VAD-Lexicon.txt"
NRC_df2 = pd.read_csv(NRC_path2, index_col=['Word'], sep='\t')
if torch.cuda.is_available():
DEVICE = torch.device("cuda")
print('GPU found (', torch.cuda.get_device_name(torch.cuda.current_device()), ')')
torch.cuda.set_device(torch.cuda.current_device())
print('num device avail: ', torch.cuda.device_count())
else:
DEVICE = torch.device('cpu')
print('running on cpu')
if __name__ == '__main__':
default_m = "original"
parser = argparse.ArgumentParser()
parser.add_argument("infile", type=str, help="Input file, should be in sent1 format")
parser.add_argument("outfile", type=str, help="Output file, contains standard cols 0.3, plus json vectors")
parser.add_argument("-b", type=int, default=50, help="Batchsize (50)")
parser.add_argument("-l", type=int, default=1000, help="Log every (1000)")
parser.add_argument("--maxtoks", type=int, default=200, help="Maximum number of tokens per sentence to use (200)")
parser.add_argument("--maxsents", type=int, default=200,
help="Maximum number of sentences per article to use (200)")
parser.add_argument("-m", type=str, default=default_m,
help="Model (small, medium, original, original5b ({})".format(default_m))
parser.add_argument("-g", action='store_true', help="Use the GPU (default: don't)")
parser.add_argument("--concat", action='store_true', help="Concatenate representations instead of averaging")
args = parser.parse_args()
outfile = args.outfile
infile = args.infile
batchsize = args.b
every = args.l
# use_gpu = args.g
# model = os.path.join("elmo", models[args.m])
config = os.path.join("elmo", configs[args.m])
concat = args.concat
maxtoks = args.maxtoks
maxsents = args.maxsents
print("Loading model {}...".format(args.m))
# elmo = ElmoEmbedder(options_file=config, weight_file=model, cuda_device=device)
# elmo = ElmoTokenEmbedder(options_file=config, weight_file=model)
token_len = []
input_id = []
token_length = 50
print("Processing lines...")
with open(infile, "rt", encoding="utf8") as inp:
nlines = 0
with open(outfile, "wt", encoding="utf8") as outp:
for line in inp:
#print('new line')
fields = line.split("\t")
title = fields[5]
tmp = fields[4]
tmp = tmp.split(" <splt> ")[:maxsents]
sents = [title]
sents.extend(tmp)
# now processes the sents in batches
outs = []
# unlike the tensorflow version we can have dynamic batch sizes here!
print(f'line no:{fields[0]},sents len:{len(sents)}')
print(math.ceil(len(sents) / batchsize))
for batchnr in range(math.ceil(len(sents) / batchsize)):
print("next batch")
avg = []
fromidx = batchnr * batchsize
toidx = (batchnr + 1) * batchsize
actualtoidx = min(len(sents), toidx)
# print("Batch: from=",fromidx,"toidx=",toidx,"actualtoidx=",actualtoidx)
sentsbat = sents[fromidx:actualtoidx]
# print("len of sentsbat:",len(sentsbat))
# print("len of sentsbat:",len(sentsbat[0]))
sentsbatch = [(" ").join(s.split()[:maxtoks]) for s in sentsbat]
# print("len of sentsbatch:",len(sentsbatch))
# print("len of sentsbatch:",len(sentsbatch[0]))
print('sensbatch len:', len(sentsbatch))
for s in sentsbatch:
if len(s) == 0:
s.append("") # otherwise we get a shape (3,0,dims) result
#print("checkpoint0")
for sentence in sentsbatch:
# q=[]
input_id = []
#print(sentence)
tokens = tokenizer.tokenize(sentence)
#print("checkpoint 0.1")
token_len.append(len(tokens))
token_ids = tokenizer.encode(tokens, add_special_tokens=True, max_length=token_length,
pad_to_max_length=True)
input_id.append(token_ids)
input_ids = torch.from_numpy(np.array(input_id)).long()
#print("checkpoint 1")
# print(input_ids)
#print("checkpoint 1.1")
bert_output = model(input_ids)
tmph = []
for ii in range(n_hl):
tmph.append((bert_output[2][ii + 1].detach().numpy()).mean(axis=1))
# hidden_features.append(np.array(tmph))
alphaW = np.full([n_hl], 1 / n_hl)
hidden_features = np.einsum('k,kij->ij', alphaW, tmph)
#print(hidden_features.shape)
#print(hidden_features[0].shape)
#try:
#read = extract_readability_features(sentence)
#read_feat = normalization(read)
#except ValueError:
#print(f'value Error with {sentence}')
#read_feat = [0]*31
#emotion = extract_NRC_features(sentence, NRC_df1)
#vad = extract_NRC_features(sentence, NRC_df2)
#feat = np.append(hidden_features[0],read_feat)
#feat = np.append(feat,list(emotion))
#feat = np.append(feat,list(vad))
#print(len(hidden_features), len(hidden_features[0]))
#print(hidden_features[0].shape,feat.shape)
#print("checkpoint 2")
avg.append(hidden_features[0])
#print("checkpoint3")
outs.extend(avg)
print(len(outs))
# print("Result lines:", len(outs))
outs = [a.tolist() for a in outs]
if not outs:
print('empty')
# outs=[-0.02828037366271019, -0.02817110197308163, -0.02776097149277727, -0.028012847527861595, -0.028245604364201427, -0.02613477672760685, -0.027191620552912354, -0.026653081954767305, -0.027391517146800954, -0.027306203187132876]
print(fields[0], fields[1], fields[2], fields[3], json.dumps(outs), sep="\t", file=outp)
print('line done')
nlines += 1
if nlines % every == 0:
print("Processed lines:", nlines)
print("Total processed lines")
| [
"argparse.ArgumentParser",
"pandas.read_csv",
"numpy.einsum",
"json.dumps",
"torch.cuda.device_count",
"torch.device",
"torch.cuda.current_device",
"os.path.join",
"numpy.full",
"pandas.merge",
"collections.Counter",
"re.sub",
"pandas.DataFrame.from_dict",
"scipy.stats.zscore",
"pandas.r... | [((616, 649), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (639, 649), False, 'import warnings\n'), ((2526, 2563), 'pandas.read_excel', 'pd.read_excel', (['NRC_path1'], {'index_col': '(0)'}), '(NRC_path1, index_col=0)\n', (2539, 2563), True, 'import pandas as pd\n'), ((2613, 2665), 'pandas.read_csv', 'pd.read_csv', (['NRC_path2'], {'index_col': "['Word']", 'sep': '"""\t"""'}), "(NRC_path2, index_col=['Word'], sep='\\t')\n", (2624, 2665), True, 'import pandas as pd\n'), ((2670, 2695), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2693, 2695), False, 'import torch\n'), ((779, 805), 're.sub', 're.sub', (['"""\\\\."""', '""".\n"""', 'text'], {}), "('\\\\.', '.\\n', text)\n", (785, 805), False, 'import re\n'), ((817, 843), 're.sub', 're.sub', (['"""\\\\?"""', '"""?\n"""', 'text'], {}), "('\\\\?', '?\\n', text)\n", (823, 843), False, 'import re\n'), ((855, 879), 're.sub', 're.sub', (['"""!"""', '"""!\n"""', 'text'], {}), "('!', '!\\n', text)\n", (861, 879), False, 'import re\n'), ((1059, 1076), 'pandas.Series', 'pd.Series', (['result'], {}), '(result)\n', (1068, 1076), True, 'import pandas as pd\n'), ((1223, 1238), 'collections.Counter', 'Counter', (['tokens'], {}), '(tokens)\n', (1230, 1238), False, 'from collections import Counter\n'), ((1248, 1313), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['tokens'], {'orient': '"""index"""', 'columns': "['count']"}), "(tokens, orient='index', columns=['count'])\n", (1270, 1313), True, 'import pandas as pd\n'), ((1330, 1388), 'pandas.merge', 'pd.merge', (['df', 'sentic_df'], {'left_index': '(True)', 'right_index': '(True)'}), '(df, sentic_df, left_index=True, right_index=True)\n', (1338, 1388), True, 'import pandas as pd\n'), ((2710, 2730), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (2722, 2730), False, 'import torch\n'), ((2952, 2971), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2964, 2971), False, 'import torch\n'), ((3069, 3094), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3092, 3094), False, 'import argparse\n'), ((4288, 4325), 'os.path.join', 'os.path.join', (['"""elmo"""', 'configs[args.m]'], {}), "('elmo', configs[args.m])\n", (4300, 4325), False, 'import os\n'), ((696, 712), 'scipy.stats.zscore', 'stats.zscore', (['df'], {}), '(df)\n', (708, 712), False, 'from scipy import stats\n'), ((901, 941), 'readability.getmeasures', 'readability.getmeasures', (['text'], {'lang': '"""en"""'}), "(text, lang='en')\n", (924, 941), False, 'import readability\n'), ((2844, 2871), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (2869, 2871), False, 'import torch\n'), ((2905, 2930), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (2928, 2930), False, 'import torch\n'), ((2783, 2810), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (2808, 2810), False, 'import torch\n'), ((9408, 9424), 'json.dumps', 'json.dumps', (['outs'], {}), '(outs)\n', (9418, 9424), False, 'import json\n'), ((7609, 7634), 'numpy.full', 'np.full', (['[n_hl]', '(1 / n_hl)'], {}), '([n_hl], 1 / n_hl)\n', (7616, 7634), True, 'import numpy as np\n'), ((7677, 7713), 'numpy.einsum', 'np.einsum', (['"""k,kij->ij"""', 'alphaW', 'tmph'], {}), "('k,kij->ij', alphaW, tmph)\n", (7686, 7713), True, 'import numpy as np\n'), ((7113, 7131), 'numpy.array', 'np.array', (['input_id'], {}), '(input_id)\n', (7121, 7131), True, 'import numpy as np\n')] |
import tellurium as te
import numpy
# Coherent Type I Genetic Network, noise filter
rr = te.loada ('''
$G2 -> P2; Vmax2*P1^4/(Km1 + P1^4);
P2 -> $w; k1*P2;
$G3 -> P3; Vmax3*P1^4*P2^4/(Km1 + P1^4*P2^4);
P3 -> $w; k1*P3;
Vmax2 = 1; Vmax3 = 1;
Km1 = 0.5; k1 = 0.1;
P1 = 0; P2 = 0; P3 = 0;
''')
rr.getSteadyStateValues()
print (rr.getFloatingSpeciesConcentrations())
# Pulse width
# Set to 1 for no effect
# Set to 4 for full effect
width = 1
rr.P1 = 0.3
m1 = rr.simulate(0, 10, 100, ["time", "P1", "P3"])
rr.P1 = 0.7 # input stimulus
m2 = rr.simulate(10, 10 + width, 100, ["time", "P1", "P3"])
rr.P1 = 0.3
m3 = rr.simulate(10 + width, 40, 100, ["time", "P1", "P3"])
m = numpy.vstack((m1, m2))
result = numpy.vstack((m, m3))
te.plotWithLegend(rr, result)
| [
"tellurium.loada",
"numpy.vstack",
"tellurium.plotWithLegend"
] | [((90, 337), 'tellurium.loada', 'te.loada', (['"""\n $G2 -> P2; Vmax2*P1^4/(Km1 + P1^4);\n P2 -> $w; k1*P2;\n $G3 -> P3; Vmax3*P1^4*P2^4/(Km1 + P1^4*P2^4);\n P3 -> $w; k1*P3;\n\n Vmax2 = 1; Vmax3 = 1;\n Km1 = 0.5; k1 = 0.1;\n P1 = 0; P2 = 0; P3 = 0;\n"""'], {}), '(\n """\n $G2 -> P2; Vmax2*P1^4/(Km1 + P1^4);\n P2 -> $w; k1*P2;\n $G3 -> P3; Vmax3*P1^4*P2^4/(Km1 + P1^4*P2^4);\n P3 -> $w; k1*P3;\n\n Vmax2 = 1; Vmax3 = 1;\n Km1 = 0.5; k1 = 0.1;\n P1 = 0; P2 = 0; P3 = 0;\n"""\n )\n', (98, 337), True, 'import tellurium as te\n'), ((707, 729), 'numpy.vstack', 'numpy.vstack', (['(m1, m2)'], {}), '((m1, m2))\n', (719, 729), False, 'import numpy\n'), ((739, 760), 'numpy.vstack', 'numpy.vstack', (['(m, m3)'], {}), '((m, m3))\n', (751, 760), False, 'import numpy\n'), ((761, 790), 'tellurium.plotWithLegend', 'te.plotWithLegend', (['rr', 'result'], {}), '(rr, result)\n', (778, 790), True, 'import tellurium as te\n')] |
import numpy as np
import pandas as pd
import colorsys
from scipy import interpolate
import matplotlib.patches as mpatches
from matplotlib import pyplot as plt
def _avg_silhouette(x):
"""
Создает симметричный граф
"""
return -x.sum(axis=1) / 2
def _wiggle_silhouette(x):
"""
Минимизирует дисперсию производных
"""
n = x.shape[1]
return -(np.arange(n, 0, -1) * x).sum(axis=1) / (n + 1)
def _weighted_wiggle_silhouette(x):
"""
Минимизирует взвешенную дисперсию производных (веса по толщине слоев)
"""
if x.shape[0] < 3:
# проблемы с интерполяцией производных
return _avg_silhouette(x)
# Считаем аппроксимацию производных
diffs = np.zeros(x.shape)
diffs[1:-1] = (x[2:] - x[:-2]) / 2
diffs[0] = (-3 * x[0] + 4 * x[1] - x[2]) / 2
diffs[-1] = (x[-3] - 4 * x[-2] + 3 * x[-1]) / 2
norm = x.sum(axis=1)
norm = -1 / norm
# Производная нижнего края
g_diff = np.zeros((x.shape[0]))
for i in range(x.shape[1]):
g_diff += (0.5 * diffs[:, i] + diffs[:, :i].sum(axis=1)) * x[:, i]
g_diff *= norm
# Численно интегрируем
g = [_wiggle_silhouette(x[:1])[0]]
for i in range(1, x.shape[0]):
g.append(g[-1] + (g_diff[i - 1] + g_diff[i]) * 0.5)
return np.array(g)
_silhouette = {
'avg': _avg_silhouette,
'wiggle': _wiggle_silhouette,
'weighted_wiggle': _weighted_wiggle_silhouette,
}
def _inside_out_ordering(x):
weighted = np.array(x)
for i in range(x.shape[1]):
weighted[:, i] *= i
weighted = weighted.sum(axis=0)
order = list(np.argsort(weighted))
result = []
for i in order:
result.append(i)
result = result[::-1]
return result
def _identity_ordering(x):
return range(x.shape[1])
_ordering = {
'inside_out': _inside_out_ordering
}
class StreamGraph:
def __init__(self, silhouette='weighted_wiggle', ordering='inside_out'):
assert silhouette in _silhouette
self._silhouette = _silhouette[silhouette]
assert ordering is None or ordering in _ordering
if ordering is None:
self._order_func = _identity_ordering
else:
self._order_func = _ordering[ordering]
def draw(self, x, colors=None, texts=None):
if isinstance(x, pd.DataFrame):
assert texts is None
texts = [str(t) for t in x.columns]
im, colors = self.draw_im(x, colors=colors)
f, (ax1, ax2) = plt.subplots(1, 2, sharey='none', sharex='none')
plt.xticks([])
plt.yticks([])
ax1.imshow(im)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_adjustable('box')
plt.setp(ax1.spines.values(), color=(1, 1, 1))
plt.setp(ax2.spines.values(), color=(1, 1, 1))
if texts is not None:
patches = [mpatches.Patch(color=c, label=texts[i]) for i, c in enumerate(colors)]
legend = ax2.legend(handles=patches)
ax2.set_adjustable('box')
ax2.set_aspect(5)
plt.show()
def draw_im(self, x, im_size=None, colors=None):
x = self._prepare_data(x)
x, permutation = self._reorder(x)
if im_size is None:
im_size = (512, 1024)
if colors is None:
colors = self.create_colors(x)
else:
colors = [colors[i] for i in permutation]
intervals = self._intervals(x)
intervals = self._interpolate(intervals, im_size[1])
return self._fill_image(im_size, intervals, colors), self._back_order(permutation, colors)
def create_colors(self, x):
x = self._prepare_data(x)
hue_range = (30 / 360, 300 / 360)
sums = x.sum(axis=0)
sums /= np.max(sums)
hsv = [(self._value_to_range(i / len(sums), hue_range),
self._value_to_range(v, (0.5, 1)),
0.75) for i, v in enumerate(sums)]
rgb = [colorsys.hsv_to_rgb(*v) for v in hsv]
return rgb
def _back_order(self, permutation, values):
original_order = [0 for _ in permutation]
for i, pos in enumerate(permutation):
original_order[pos] = i
return [values[i] for i in original_order]
def _reorder(self, x):
permutation = self._order_func(x)
x = np.transpose([x[:, i] for i in permutation])
return x, permutation
def _intervals(self, x):
result = np.zeros((x.shape[1] + 1, x.shape[0]))
result[0] = self._silhouette(x)
for i in range(x.shape[1]):
result[i + 1] = result[i] + x[:, i]
result -= result.min()
result /= result.max()
return result
def _interpolate(self, intervals, width):
result = np.zeros((intervals.shape[0], width))
target_x = np.linspace(0, intervals.shape[1], width)
source_x = np.arange(intervals.shape[1])
for i in range(intervals.shape[0]):
spline = interpolate.splrep(source_x, intervals[i])
result[i] = interpolate.splev(target_x, spline)
return result
def _fill_image(self, im_size, intervals, colors):
assert intervals.shape[1] == im_size[1]
assert len(colors) + 1 == intervals.shape[0]
intervals -= intervals.min()
intervals /= intervals.max()
intervals *= im_size[0]
im = np.ones((*im_size, 3))
for x in range(intervals.shape[1]):
for i, (start, end) in enumerate(zip(intervals[:-1, x], intervals[1:, x])):
start = int(start)
end = int(end)
start = max(0, start)
end = min(im.shape[0], end)
im[start:end, x] = colors[i]
return im
def _value_to_range(self, value, range):
start, stop = range
return start + value * (stop - start)
def _prepare_data(self, x):
if isinstance(x, pd.DataFrame):
x = x.values
x = np.array(x, np.float)
assert len(x.shape) == 2
return x
| [
"scipy.interpolate.splrep",
"matplotlib.pyplot.show",
"colorsys.hsv_to_rgb",
"matplotlib.pyplot.yticks",
"numpy.zeros",
"numpy.transpose",
"numpy.ones",
"numpy.argsort",
"numpy.max",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"scipy.interpolate.splev",
"matplotlib.patches.Patch",
"... | [((712, 729), 'numpy.zeros', 'np.zeros', (['x.shape'], {}), '(x.shape)\n', (720, 729), True, 'import numpy as np\n'), ((962, 982), 'numpy.zeros', 'np.zeros', (['x.shape[0]'], {}), '(x.shape[0])\n', (970, 982), True, 'import numpy as np\n'), ((1284, 1295), 'numpy.array', 'np.array', (['g'], {}), '(g)\n', (1292, 1295), True, 'import numpy as np\n'), ((1476, 1487), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1484, 1487), True, 'import numpy as np\n'), ((1601, 1621), 'numpy.argsort', 'np.argsort', (['weighted'], {}), '(weighted)\n', (1611, 1621), True, 'import numpy as np\n'), ((2484, 2532), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'sharey': '"""none"""', 'sharex': '"""none"""'}), "(1, 2, sharey='none', sharex='none')\n", (2496, 2532), True, 'from matplotlib import pyplot as plt\n'), ((2541, 2555), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (2551, 2555), True, 'from matplotlib import pyplot as plt\n'), ((2564, 2578), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (2574, 2578), True, 'from matplotlib import pyplot as plt\n'), ((3049, 3059), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3057, 3059), True, 'from matplotlib import pyplot as plt\n'), ((3743, 3755), 'numpy.max', 'np.max', (['sums'], {}), '(sums)\n', (3749, 3755), True, 'import numpy as np\n'), ((4308, 4352), 'numpy.transpose', 'np.transpose', (['[x[:, i] for i in permutation]'], {}), '([x[:, i] for i in permutation])\n', (4320, 4352), True, 'import numpy as np\n'), ((4430, 4468), 'numpy.zeros', 'np.zeros', (['(x.shape[1] + 1, x.shape[0])'], {}), '((x.shape[1] + 1, x.shape[0]))\n', (4438, 4468), True, 'import numpy as np\n'), ((4741, 4778), 'numpy.zeros', 'np.zeros', (['(intervals.shape[0], width)'], {}), '((intervals.shape[0], width))\n', (4749, 4778), True, 'import numpy as np\n'), ((4798, 4839), 'numpy.linspace', 'np.linspace', (['(0)', 'intervals.shape[1]', 'width'], {}), '(0, intervals.shape[1], width)\n', (4809, 4839), True, 'import numpy as np\n'), ((4859, 4888), 'numpy.arange', 'np.arange', (['intervals.shape[1]'], {}), '(intervals.shape[1])\n', (4868, 4888), True, 'import numpy as np\n'), ((5355, 5377), 'numpy.ones', 'np.ones', (['(*im_size, 3)'], {}), '((*im_size, 3))\n', (5362, 5377), True, 'import numpy as np\n'), ((5951, 5972), 'numpy.array', 'np.array', (['x', 'np.float'], {}), '(x, np.float)\n', (5959, 5972), True, 'import numpy as np\n'), ((3937, 3960), 'colorsys.hsv_to_rgb', 'colorsys.hsv_to_rgb', (['*v'], {}), '(*v)\n', (3956, 3960), False, 'import colorsys\n'), ((4954, 4996), 'scipy.interpolate.splrep', 'interpolate.splrep', (['source_x', 'intervals[i]'], {}), '(source_x, intervals[i])\n', (4972, 4996), False, 'from scipy import interpolate\n'), ((5021, 5056), 'scipy.interpolate.splev', 'interpolate.splev', (['target_x', 'spline'], {}), '(target_x, spline)\n', (5038, 5056), False, 'from scipy import interpolate\n'), ((2853, 2892), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'c', 'label': 'texts[i]'}), '(color=c, label=texts[i])\n', (2867, 2892), True, 'import matplotlib.patches as mpatches\n'), ((379, 398), 'numpy.arange', 'np.arange', (['n', '(0)', '(-1)'], {}), '(n, 0, -1)\n', (388, 398), True, 'import numpy as np\n')] |
import pygame
from pygame.color import THECOLORS
from pygame.locals import *
from pygame import sprite
from pygame.draw import *
import math
import random
import time
from pykinect import nui
from pykinect.nui import JointId, SkeletonTrackingState
import ctypes
import thread
from numpy import interp
KINECTEVENT = pygame.USEREVENT
video_display = False
kinect = nui.Runtime()
kinect.skeleton_engine.enabled = True
screen_lock = thread.allocate()
def get_screen_size():
user32 = ctypes.windll.user32
return user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
def surface_to_array(surface):
buffer_interface = surface.get_buffer()
address = ctypes.c_void_p()
size = Py_ssize_t()
_PyObject_AsWriteBuffer(buffer_interface,
ctypes.byref(address), ctypes.byref(size))
bytes = (ctypes.c_byte * size.value).from_address(address.value)
bytes.object = buffer_interface
return bytes
def draw_skeletons(skeletons):
for index, data in enumerate(skeletons):
# draw the Head
HeadPos = skeleton_to_depth_image(data.SkeletonPositions[JointId.Head], dispInfo.current_w, dispInfo.current_h)
draw_skeleton_data(data, index, SPINE, 10)
pygame.draw.circle(screen, SKELETON_COLORS[index], (int(HeadPos[0]), int(HeadPos[1])), 20, 0)
# drawing the limbs
draw_skeleton_data(data, index, LEFT_ARM)
draw_skeleton_data(data, index, RIGHT_ARM)
draw_skeleton_data(data, index, LEFT_LEG)
draw_skeleton_data(data, index, RIGHT_LEG)
def depth_frame_ready(frame):
if video_display:
return
with screen_lock:
address = surface_to_array(screen)
frame.image.copy_bits(address)
del address
if skeletons is not None and draw_skeleton:
draw_skeletons(skeletons)
pygame.display.update()
def video_frame_ready(frame):
if not video_display:
return
with screen_lock:
address = surface_to_array(screen)
frame.image.copy_bits(address)
del address
if skeletons is not None and draw_skeleton:
draw_skeletons(skeletons)
pygame.display.update()
def post_frame(frame):
try:
pygame.event.post(pygame.event.Event(KINECTEVENT, skeletons = frame.SkeletonData))
except:
pass
class Paddle(object):
def __init__(self, screen, color, x, y, length, width, outline=0):
self.screen = screen
self.color = color
self.rectlist = [x, y, length, width]
self.outline = outline;
self.newx = x
self.diff = 0
self.center = x + length / 2
def draw(self):
self.rect = rect(self.screen, self.color, self.rectlist, self.outline)
def change(self):
if (abs(self.newx-self.rectlist[0])>4):
self.rectlist = [self.rectlist[0] + self.diff, self.rectlist[1], self.rectlist[2], self.rectlist[3]]
self.center = self.rectlist[0] + self.rectlist[2] / 2
self.draw()
def move(self, newx):
self.newx = newx
current = self.rectlist[0]
diff = self.newx - current
self.diff = diff/4
class Block(object):
def __init__(self, screen, color, x, y, length, width, exists, outline=0):
self.screen = screen
self.color = color
self.rectlist = [x, y, length, width]
self.outline = outline
self.newx = x
self.diff = 0
self.exists = exists
def draw(self):
if (self.exists):
self.rect = rect(self.screen, self.color, self.rectlist, self.outline)
def change(self):
if (abs(self.newx-self.rectlist[0])>4):
self.rectlist = [self.rectlist[0] + self.diff, self.rectlist[1], self.rectlist[2], self.rectlist[3]]
self.draw()
class Circle(object):
def __init__(self, screen, color, pos, radius, outline=0):
self.screen = screen
self.color = color
self.pos = pos
self.radius = radius
self.outline = outline
self.balldx = 2
self.balldy = -1
self.speed = math.sqrt(self.balldx**2 + self.balldy**2)
def draw(self):
self.setPos(int(self.pos[0]), int(self.pos[1]))
self.rect = circle(self.screen, self.color, self.pos, self.radius, self.outline)
def setPos(self, xpos, ypos):
self.pos = (xpos, ypos)
class Ball(Circle):
def change(self):
newx = int(self.pos[0])+self.balldx
newy = int(self.pos[1])+self.balldy
self.pos = (newx, newy)
self.draw()
clock = pygame.time.Clock()
class Game(object):
def __init__(self):
kinect.camera.elevation_angle = 4
kinect.skeleton_engine.enabled = True
kinect.skeleton_frame_ready += post_frame
kinect.video_frame_ready += video_frame_ready
kinect.video_stream.open(nui.ImageStreamType.Video, 2,
nui.ImageResolution.Resolution640x480,
nui.ImageType.Color)
self.screensize = get_screen_size()
self.screen = pygame.display.set_mode(self.screensize, pygame.FULLSCREEN)
pygame.mouse.set_visible(False)
self.width = 1200
self.height = 600
self.numBalls = 3
self.screen = pygame.display.set_mode((self.width, self.height), 0, 32)
self.screen.convert()
self.screen.fill(THECOLORS["black"])
self.background = pygame.Surface((self.width, self.height), 0, 32)
self.background.fill(THECOLORS["black"])
self.background.convert()
block19 = Block(self.screen, THECOLORS["red"], 120, 60, 120, 60, True)
block20 = Block(self.screen, THECOLORS["green"], 120, 120, 120, 60, True)
block21 = Block(self.screen, THECOLORS["blue"], 120, 180, 120, 60, True)
block13 = Block(self.screen, THECOLORS["green"], 240, 60, 120, 60, True)
block14 = Block(self.screen, THECOLORS["blue"], 240, 120, 120, 60, True)
block15 = Block(self.screen, THECOLORS["red"], 240, 180, 120, 60, True)
block2 = Block(self.screen, THECOLORS["blue"], 360, 60, 120, 60, True)
block7 = Block(self.screen, THECOLORS["red"], 360, 120, 120, 60, True)
block3 = Block(self.screen, THECOLORS["green"], 360, 180, 120, 60, True)
block1 = Block(self.screen, THECOLORS["red"], 480, 60, 120, 60, True)
block11 = Block(self.screen, THECOLORS["green"], 480, 120, 120, 60, True)
block9 = Block(self.screen, THECOLORS["blue"], 480, 180, 120, 60, True)
block4 = Block(self.screen, THECOLORS["green"], 600, 60, 120, 60, True)
block12 = Block(self.screen, THECOLORS["blue"], 600, 120, 120, 60, True)
block8 = Block(self.screen, THECOLORS["red"], 600, 180, 120, 60, True)
block5 = Block(self.screen, THECOLORS["blue"], 720, 60, 120, 60, True)
block6 = Block(self.screen, THECOLORS["red"], 720, 120, 120, 60, True)
block10 = Block(self.screen, THECOLORS["green"], 720, 180, 120, 60, True)
block16 = Block(self.screen, THECOLORS["red"], 840, 60, 120, 60, True)
block17 = Block(self.screen, THECOLORS["green"], 840, 120, 120, 60, True)
block18 = Block(self.screen, THECOLORS["blue"], 840, 180, 120, 60, True)
block22 = Block(self.screen, THECOLORS["green"], 960, 60, 120, 60, True)
block23 = Block(self.screen, THECOLORS["blue"], 960, 120, 120, 60, True)
block24 = Block(self.screen, THECOLORS["red"], 960, 180, 120, 60, True)
self.pieces_group = (block1, block2, block3, block4, block5, block6, block7, block8, block9, block10, block11, block12, block13, block14, block15, block16, block17, block18, block19, block20, block21, block22, block23, block24)
self.image1 = pygame.SurfaceType((15, 40))
pygame.draw.rect(self.image1, THECOLORS["red"], pygame.Rect(0, 0, 90, 6))
self.ball = Ball(self.screen, THECOLORS["white"], (650, 560), 12)
self.paddle = Paddle(self.screen, THECOLORS["red"], 550, 580, 200, 10)
self.isCollided = False
def quit(self):
pygame.quit()
sys.exit()
def go(self):
# move paddles to kinect locations
events = pygame.event.get()
for e in events:
if e.type == KINECTEVENT:
for skeleton in e.skeletons:
head = skeleton.SkeletonPositions[JointId.Head]
if (not head.x==0):
xval = interp(head.x, [-1, 1], [0,1])
xpos = (xval) * self.width
self.paddle.move(xpos)
elif e.type == KEYDOWN:
if e.key == K_ESCAPE:
self.quit()
def doUpdate(self):
pygame.display.set_caption('Python Kinect Game %d fps' % clock.get_fps())
self.screen.fill(THECOLORS["black"])
self.ball.change()
self.paddle.change()
for m in self.pieces_group:
m.change()
pygame.display.update()
def play(self):
while (self.numBalls > 0):
if (self.ball.pos[0] - self.ball.radius <= 0):
if (self.isCollided == False):
self.ball.balldx = abs(self.ball.balldx)
self.isCollided = True
elif (self.ball.pos[0] + self.ball.radius >= self.width):
if (self.isCollided == False):
self.ball.balldx = -abs(self.ball.balldx)
self.isCollided = True
else:
self.isCollided = False
if (self.ball.pos[1] - self.ball.radius <= 0):
if (self.isCollided == False):
self.ball.balldy = abs(self.ball.balldy)
self.isCollided = True
else:
self.isCollided = False
if (self.ball.pos[1] >= 610):
self.numBalls -= 1
self.ball.setPos(self.paddle.center, 550)
self.ball.balldy = random.choice([-1, -2])
if (self.ball.pos[1] + self.ball.radius >= 580 and self.ball.pos[0] >= self.paddle.rectlist[0] and self.ball.pos[0] <= self.paddle.rectlist[0] + self.paddle.rectlist[2]):
if (self.isCollided == False):
self.isCollided = True
if (self.ball.pos[0] == self.paddle.center):
self.angle = 90 + 5 * (self.paddle.center - self.ball.pos[0]) + 15
self.ball.balldy = -abs(math.sin(math.radians(self.angle)) * self.ball.speed)
self.ball.balldx = -math.cos(math.radians(self.angle)) * self.ball.speed
elif (self.ball.pos[0] < self.paddle.center):
self.angle = 90 + 5 * (self.paddle.center - self.ball.pos[0])
self.ball.balldy = -abs(math.sin(math.radians(self.angle)) * self.ball.speed)
self.ball.balldx = -math.cos(math.radians(self.angle)) * self.ball.speed
elif (self.ball.pos[0] > self.paddle.center):
self.angle = 90 - 5 * (self.ball.pos[0] - self.paddle.center)
self.ball.balldy = -abs(math.sin(math.radians(self.angle)) * self.ball.speed)
self.ball.balldx = -math.cos(math.radians(self.angle)) * self.ball.speed
else:
self.isCollided = False
check = False
if (self.isCollided == False):
for m in self.pieces_group:
if (self.ball.pos[0] + self.ball.radius >= m.rectlist[0] and self.ball.pos[0] - self.ball.radius <= m.rectlist[0] + m.rectlist[2]):
if (m.rectlist[1] <= self.ball.pos[1] <= m.rectlist[1] + m.rectlist[3] and (m.rectlist[0] < self.ball.pos[0] <= m.rectlist[0] + 5 or m.rectlist[0] + m.rectlist[2] - 5 <= self.ball.pos[0] < m.rectlist[0] + m.rectlist[2]) and m.exists): # block 1 left/right side
self.ball.balldx = -self.ball.balldx
check = True
self.isCollided = True
if (m.rectlist[0] <= self.ball.pos[0] <= m.rectlist[0] + m.rectlist[2] and (m.rectlist[1] < self.ball.pos[1] <= m.rectlist[1] + 5 or m.rectlist[1] + m.rectlist[3] - 5 <= self.ball.pos[1] < m.rectlist[1] + m.rectlist[3]) and m.exists): # block 1 top/bottom side
self.ball.balldy = -self.ball.balldy
self.isCollided = True
check = True
else:
self.isCollided = False
if (check):
m.exists = False
check = False
if (abs(self.ball.balldy) < 1):
if (self.ball.balldy < 0):
self.ball.balldy = -1
else:
self.ball.balldy = 1
if (abs(self.ball.balldx) < 1):
if (self.ball.balldx < 0):
self.ball.balldx = -1
else:
self.ball.balldx = 1
self.totalx = self.ball.pos[0] + self.ball.balldx
self.totaly = self.ball.pos[1] + self.ball.balldy
self.ball.setPos(int(self.totalx), int(self.totaly))
self.go()
self.doUpdate()
pygame.display.flip()
clock.tick(80)
if __name__ == '__main__':
# Initialize PyGame
pygame.init()
pygame.font.init()
game = Game()
game.play() | [
"pygame.event.Event",
"pygame.mouse.set_visible",
"pygame.event.get",
"pygame.Rect",
"pygame.font.init",
"pygame.display.update",
"numpy.interp",
"pykinect.nui.Runtime",
"ctypes.byref",
"math.radians",
"pygame.display.set_mode",
"pygame.quit",
"pygame.Surface",
"thread.allocate",
"math.s... | [((367, 380), 'pykinect.nui.Runtime', 'nui.Runtime', ([], {}), '()\n', (378, 380), False, 'from pykinect import nui\n'), ((434, 451), 'thread.allocate', 'thread.allocate', ([], {}), '()\n', (449, 451), False, 'import thread\n'), ((4251, 4270), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (4268, 4270), False, 'import pygame\n'), ((658, 675), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (673, 675), False, 'import ctypes\n'), ((11688, 11701), 'pygame.init', 'pygame.init', ([], {}), '()\n', (11699, 11701), False, 'import pygame\n'), ((11703, 11721), 'pygame.font.init', 'pygame.font.init', ([], {}), '()\n', (11719, 11721), False, 'import pygame\n'), ((770, 791), 'ctypes.byref', 'ctypes.byref', (['address'], {}), '(address)\n', (782, 791), False, 'import ctypes\n'), ((793, 811), 'ctypes.byref', 'ctypes.byref', (['size'], {}), '(size)\n', (805, 811), False, 'import ctypes\n'), ((1827, 1850), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (1848, 1850), False, 'import pygame\n'), ((2149, 2172), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (2170, 2172), False, 'import pygame\n'), ((3834, 3880), 'math.sqrt', 'math.sqrt', (['(self.balldx ** 2 + self.balldy ** 2)'], {}), '(self.balldx ** 2 + self.balldy ** 2)\n', (3843, 3880), False, 'import math\n'), ((4735, 4794), 'pygame.display.set_mode', 'pygame.display.set_mode', (['self.screensize', 'pygame.FULLSCREEN'], {}), '(self.screensize, pygame.FULLSCREEN)\n', (4758, 4794), False, 'import pygame\n'), ((4797, 4828), 'pygame.mouse.set_visible', 'pygame.mouse.set_visible', (['(False)'], {}), '(False)\n', (4821, 4828), False, 'import pygame\n'), ((4910, 4967), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(self.width, self.height)', '(0)', '(32)'], {}), '((self.width, self.height), 0, 32)\n', (4933, 4967), False, 'import pygame\n'), ((5052, 5100), 'pygame.Surface', 'pygame.Surface', (['(self.width, self.height)', '(0)', '(32)'], {}), '((self.width, self.height), 0, 32)\n', (5066, 5100), False, 'import pygame\n'), ((7204, 7232), 'pygame.SurfaceType', 'pygame.SurfaceType', (['(15, 40)'], {}), '((15, 40))\n', (7222, 7232), False, 'import pygame\n'), ((7498, 7511), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (7509, 7511), False, 'import pygame\n'), ((7589, 7607), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (7605, 7607), False, 'import pygame\n'), ((8171, 8194), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (8192, 8194), False, 'import pygame\n'), ((2232, 2293), 'pygame.event.Event', 'pygame.event.Event', (['KINECTEVENT'], {'skeletons': 'frame.SkeletonData'}), '(KINECTEVENT, skeletons=frame.SkeletonData)\n', (2250, 2293), False, 'import pygame\n'), ((7283, 7307), 'pygame.Rect', 'pygame.Rect', (['(0)', '(0)', '(90)', '(6)'], {}), '(0, 0, 90, 6)\n', (7294, 7307), False, 'import pygame\n'), ((11598, 11619), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (11617, 11619), False, 'import pygame\n'), ((8933, 8956), 'random.choice', 'random.choice', (['[-1, -2]'], {}), '([-1, -2])\n', (8946, 8956), False, 'import random\n'), ((7780, 7811), 'numpy.interp', 'interp', (['head.x', '[-1, 1]', '[0, 1]'], {}), '(head.x, [-1, 1], [0, 1])\n', (7786, 7811), False, 'from numpy import interp\n'), ((9437, 9461), 'math.radians', 'math.radians', (['self.angle'], {}), '(self.angle)\n', (9449, 9461), False, 'import math\n'), ((9357, 9381), 'math.radians', 'math.radians', (['self.angle'], {}), '(self.angle)\n', (9369, 9381), False, 'import math\n'), ((9720, 9744), 'math.radians', 'math.radians', (['self.angle'], {}), '(self.angle)\n', (9732, 9744), False, 'import math\n'), ((9640, 9664), 'math.radians', 'math.radians', (['self.angle'], {}), '(self.angle)\n', (9652, 9664), False, 'import math\n'), ((10003, 10027), 'math.radians', 'math.radians', (['self.angle'], {}), '(self.angle)\n', (10015, 10027), False, 'import math\n'), ((9923, 9947), 'math.radians', 'math.radians', (['self.angle'], {}), '(self.angle)\n', (9935, 9947), False, 'import math\n')] |
import pandas as pd
import json
import numpy as np
import os
import time
import asyncio
# def sendCred(self, command):
##### write config settings for Wizard to 'tinytuya.json' ####
CONFIGFILE = 'tinytuya.json'
print('')
config = {}
config['apiKey'] = "<KEY>"
config['apiSecret'] = "<KEY>"
config['apiDeviceID'] = "ebfc16d57ed374932cjqfk"
config['apiRegion'] = "us"
# Write Config
json_object = json.dumps(config, indent=4)
with open(CONFIGFILE, "w") as data_file:
pass
data_file.write(json_object)
print(">> Configuration Data Saved to " + CONFIGFILE)
print(json_object)
# os.system("tuya_device_import.py")
exec(open("tuya_device_import.py").read())
print("Gathering Devices Please be Patient")
time.sleep(20)
f = open('snapshot.json',)
if f is not None:
# jsonData = open('snapshot.json',) #json.loads(jsonData)
jsonData = json.load(f)
df = pd.json_normalize(jsonData['devices'])
df = df.fillna(-1)
df['type'] = None
df['type'] = np.where(df['devId.dps.20'] != -1, 'light', df['type'])
df['type'] = np.where(df['devId.dps.1'] != -1, 'switch', df['type'])
lights = df[df['type'] == 'light'].reset_index(drop=True)
switches = df[df['type'] == 'switch'].reset_index(drop=True)
device_list = [lights]
for device in device_list:
for idx, row in device.iterrows():
name = row['name']
id = row['id']
id_new = id
ip = row['ip']
key = row['key']
ver = row['ver']
address = row['type'] + '_%s' % (idx+1)
print('{name}\n{id_new}\n{ip}\n{key}\n{ver}\n{address}\n'.format(
name=name, id_new=id_new, ip=ip, key=key, ver=ver, address=address,))
device_list = [switches]
for device in device_list:
for idx, row in device.iterrows():
name = row['name']
id = row['id']
id_new = id
ip = row['ip']
key = row['key']
ver = row['ver']
address = row['type'] + '_%s' % (idx+1)
print('{name}\n{id_new}\n{ip}\n{key}\n{ver}\n{address}\n'.format(
name=name, id_new=id_new, ip=ip, key=key, ver=ver, address=address,))
f.close()
| [
"json.load",
"pandas.json_normalize",
"json.dumps",
"time.sleep",
"numpy.where"
] | [((398, 426), 'json.dumps', 'json.dumps', (['config'], {'indent': '(4)'}), '(config, indent=4)\n', (408, 426), False, 'import json\n'), ((708, 722), 'time.sleep', 'time.sleep', (['(20)'], {}), '(20)\n', (718, 722), False, 'import time\n'), ((866, 904), 'pandas.json_normalize', 'pd.json_normalize', (["jsonData['devices']"], {}), "(jsonData['devices'])\n", (883, 904), True, 'import pandas as pd\n'), ((956, 1011), 'numpy.where', 'np.where', (["(df['devId.dps.20'] != -1)", '"""light"""', "df['type']"], {}), "(df['devId.dps.20'] != -1, 'light', df['type'])\n", (964, 1011), True, 'import numpy as np\n'), ((1025, 1080), 'numpy.where', 'np.where', (["(df['devId.dps.1'] != -1)", '"""switch"""', "df['type']"], {}), "(df['devId.dps.1'] != -1, 'switch', df['type'])\n", (1033, 1080), True, 'import numpy as np\n'), ((847, 859), 'json.load', 'json.load', (['f'], {}), '(f)\n', (856, 859), False, 'import json\n')] |
import random
from typing import Union, Optional
import numpy as np
from eagle_bot.reinforcement_learning.exploration import OrnsteinUhlenbeckAndEpsilonGreedy
from eagle_bot.reinforcement_learning.model.base_model import BaseModel
from eagle_bot.reinforcement_learning.model.base_critic_model import BaseCriticModel
from eagle_bot.reinforcement_learning.replay.experience import InsufficientExperiencesError
from eagle_bot.reinforcement_learning.replay.replay_handler import ExperienceReplayHandler
class DDPGAgent:
def __init__(self,
actor_model: BaseModel,
critic_model: BaseCriticModel,
exploration: OrnsteinUhlenbeckAndEpsilonGreedy,
actor_learning_rate: float
):
self.actor_model = actor_model
self.critic_model = critic_model
self.target_actor_model = actor_model.create_copy()
self.target_critic_model = critic_model.create_copy()
self.exploration = exploration
self.replay_handler = ExperienceReplayHandler(size=1500000, batch_size=512, warmup=100000)
self.last_state: np.ndarray = np.zeros(actor_model.inputs)
self.last_action: np.ndarray = np.zeros(actor_model.outputs)
self.discount_rate = 0.999 # https://www.wolframalpha.com/input/?i=ln(2)+%2F+(1+-+0.999)+%2F+60
from tensorflow.python.keras.optimizers import Adam
self.actor_train_fn = self.critic_model.get_actor_train_fn(self.actor_model, Adam(actor_learning_rate))
self.i = 0
def reset_last_state_and_action(self):
self.last_state = np.zeros(self.actor_model.inputs)
self.last_action = np.zeros(self.actor_model.outputs)
def train_with_get_output(self, state: np.ndarray, reward: float, done: bool,
enforced_action: Optional[np.ndarray] = None,
evaluation: bool = False) -> Union[np.ndarray, None]:
if random.random() < 0.3 or done:
self.replay_handler.record_experience(self.last_state, self.last_action, reward, state, done)
self.i += 1
# if done:
if self.i == 50 or done:
self.update_target_models(True, 0.005)
try:
critic_loss = self.experience_replay()
# from quicktracer import trace
# trace(float(critic_loss))
except InsufficientExperiencesError:
pass
self.i = 0
if not done:
if evaluation:
action = self.get_action(state, True)
elif enforced_action is None:
action = self.get_action(state, False)
else:
# action = self.exploration.get_action(enforced_action)
action = enforced_action
self.last_state = state
self.last_action = action
return action
else:
# self.discount_rate = min(self.discount_rate + 0.00000001, 0.9993)
self.reset_last_state_and_action()
self.exploration.reset_states()
def get_action(self, state: np.ndarray, evaluation: bool):
action = self.actor_model.predict(state.reshape((1, -1))).flatten()
if evaluation:
return action
return self.exploration.get_action(action)
def experience_replay(self):
states = []
actions = []
rewards = []
next_states = []
dones = []
for experience in self.replay_handler.generator():
states.append(experience.state)
actions.append(experience.action)
rewards.append(experience.reward)
next_states.append(experience.next_state)
dones.append(experience.done)
# Converting to np.arrays
states = np.array(states)
actions = np.array(actions)
rewards = np.array(rewards)
next_states = np.array(next_states)
dones = np.array(dones)
targets = self.get_critic_targets(rewards, next_states, dones)
states_with_actions = self.critic_model.create_input(states, actions)
critic_loss = self.critic_model.train_on_batch(states_with_actions, targets)
# Train actor
actor_inputs = [states, True] # True tells model that it's in training mode.
action_values = self.actor_train_fn(actor_inputs)[0] # actions not needed for anything.
return critic_loss
def get_critic_targets(self, rewards: np.ndarray, next_states: np.ndarray, dones: np.ndarray) -> np.ndarray:
"""
Calculates targets based on done.
If done,
target = reward
If not done,
target = r + gamma * max(q_values(next_state))
:param rewards:
:param next_states:
:param dones:
:return: Targets - 1D np.array
"""
# Targets initialised w/ done == True steps
targets = rewards.copy()
# Targets for done == False steps calculated with target network
done_false_indices = dones == 0
gamma = self.discount_rate
# Below calculations only concern those where done is false
_next_states = next_states[done_false_indices]
target_next_actions = self.target_actor_model.predict_on_batch(_next_states)
next_states_with_next_actions = self.target_critic_model.create_input(_next_states, target_next_actions)
target_q_values = self.target_critic_model.predict_on_batch(next_states_with_next_actions).flatten()
targets[done_false_indices] += gamma * target_q_values
return targets
def update_target_models(self, soft: bool, tau: float):
"""
Update target model's weights with policy model's.
If soft,
theta_target <- tau * theta_policy + (1 - tau) * theta_target
tau << 1.
:param soft:
:param tau: tau << 1 (recommended: 0.001)
:return:
"""
if soft:
self.target_actor_model.model.set_weights(
tau * np.array(self.actor_model.model.get_weights())
+ (1 - tau) * np.array(self.target_actor_model.model.get_weights())
)
self.target_critic_model.model.set_weights(
tau * np.array(self.critic_model.model.get_weights())
+ (1 - tau) * np.array(self.target_critic_model.model.get_weights())
)
else:
self.target_actor_model.model.set_weights(self.actor_model.model.get_weights())
self.target_critic_model.model.set_weights(self.critic_model.model.get_weights())
| [
"tensorflow.python.keras.optimizers.Adam",
"numpy.zeros",
"eagle_bot.reinforcement_learning.replay.replay_handler.ExperienceReplayHandler",
"random.random",
"numpy.array"
] | [((1034, 1102), 'eagle_bot.reinforcement_learning.replay.replay_handler.ExperienceReplayHandler', 'ExperienceReplayHandler', ([], {'size': '(1500000)', 'batch_size': '(512)', 'warmup': '(100000)'}), '(size=1500000, batch_size=512, warmup=100000)\n', (1057, 1102), False, 'from eagle_bot.reinforcement_learning.replay.replay_handler import ExperienceReplayHandler\n'), ((1142, 1170), 'numpy.zeros', 'np.zeros', (['actor_model.inputs'], {}), '(actor_model.inputs)\n', (1150, 1170), True, 'import numpy as np\n'), ((1210, 1239), 'numpy.zeros', 'np.zeros', (['actor_model.outputs'], {}), '(actor_model.outputs)\n', (1218, 1239), True, 'import numpy as np\n'), ((1608, 1641), 'numpy.zeros', 'np.zeros', (['self.actor_model.inputs'], {}), '(self.actor_model.inputs)\n', (1616, 1641), True, 'import numpy as np\n'), ((1669, 1703), 'numpy.zeros', 'np.zeros', (['self.actor_model.outputs'], {}), '(self.actor_model.outputs)\n', (1677, 1703), True, 'import numpy as np\n'), ((3818, 3834), 'numpy.array', 'np.array', (['states'], {}), '(states)\n', (3826, 3834), True, 'import numpy as np\n'), ((3853, 3870), 'numpy.array', 'np.array', (['actions'], {}), '(actions)\n', (3861, 3870), True, 'import numpy as np\n'), ((3889, 3906), 'numpy.array', 'np.array', (['rewards'], {}), '(rewards)\n', (3897, 3906), True, 'import numpy as np\n'), ((3929, 3950), 'numpy.array', 'np.array', (['next_states'], {}), '(next_states)\n', (3937, 3950), True, 'import numpy as np\n'), ((3967, 3982), 'numpy.array', 'np.array', (['dones'], {}), '(dones)\n', (3975, 3982), True, 'import numpy as np\n'), ((1491, 1516), 'tensorflow.python.keras.optimizers.Adam', 'Adam', (['actor_learning_rate'], {}), '(actor_learning_rate)\n', (1495, 1516), False, 'from tensorflow.python.keras.optimizers import Adam\n'), ((1958, 1973), 'random.random', 'random.random', ([], {}), '()\n', (1971, 1973), False, 'import random\n')] |
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.distributions import Normal, Independent, Categorical
from rlkit.torch.core import eval_np
from rlkit.torch.networks import Mlp
from rlkit.torch.sac.gcs.networks import BNMlp
from rlkit.torch.sac.gcs.networks import BNMlp, MixtureSameFamily
import numpy as np
LOG_SIG_MAX = 2
LOG_SIG_MIN = -20
def identity(x):
return x
class SkillDiscriminator(BNMlp):
def __init__(
self,
hidden_sizes,
input_size,
skill_dim,
num_components=1,
batch_norm=False,
std=None,
init_w=1e-3,
output_activation=torch.tanh,
**kwargs
):
output_size = skill_dim * num_components
super().__init__(
hidden_sizes=hidden_sizes,
input_size=input_size,
output_size=output_size,
init_w=init_w,
output_activation=output_activation,
batch_norm=batch_norm,
**kwargs
)
self.skill_dim = skill_dim
self.log_std = None
self.std = std
# self.batchnorm_output = torch.nn.BatchNorm1d(skill_dim)
self.num_components = num_components
if std is None:
last_hidden_size = input_size
if len(hidden_sizes) > 0:
last_hidden_size = hidden_sizes[-1]
self.last_fc_log_std = nn.Linear(last_hidden_size, output_size)
self.last_fc_log_std.weight.data.uniform_(-init_w, init_w)
self.last_fc_log_std.bias.data.uniform_(-init_w, init_w)
else:
self.std = torch.Tensor(np.array(std))
self.log_std = torch.log(self.std)
assert np.all(LOG_SIG_MIN <= self.log_std) and np.all(self.log_std <= LOG_SIG_MAX)
if num_components > 1:
self.last_fc_categorical = nn.Linear(hidden_sizes[-1], num_components)
self.last_fc_categorical.weight.data.uniform_(-init_w, init_w)
self.last_fc_categorical.bias.data.uniform_(-init_w, init_w)
def forward(
self, input, return_preactivations=False,
):
h = input
if self.batch_norm:
h = self.batchnorm_input(h)
for i, fc in enumerate(self.fcs):
h = self.hidden_activation(fc(h))
if self.batch_norm:
h = self.batchnorm_hidden[i](h)
mean = self.last_fc(h)
if self.std is None:
log_std = self.last_fc_log_std(h)
log_std = torch.clamp(log_std, LOG_SIG_MIN, LOG_SIG_MAX)
std = torch.exp(log_std)
else:
std = self.std
if self.num_components > 1:
mean = mean.view(-1, self.num_components, self.skill_dim)
std = std.view(-1, self.num_components, self.skill_dim)
categorical_logits = self.last_fc_categorical(h)
distribution = MixtureSameFamily(
Categorical(logits=categorical_logits),
Independent(Normal(mean, std), 1)
)
else:
distribution = Independent(Normal(mean, std), 1)
return distribution
class DiscreteSkillDiscriminator(Mlp):
def __init__(
self,
hidden_sizes,
input_size,
skill_dim,
std=None,
init_w=1e-3,
**kwargs
):
super().__init__(
hidden_sizes=hidden_sizes,
input_size=input_size,
output_size=skill_dim,
init_w=init_w,
**kwargs
)
self.skill_dim = skill_dim
self.batchnorm_input = torch.nn.BatchNorm1d(input_size)
self.batchnorm_hidden = [torch.nn.BatchNorm1d(h) for h in hidden_sizes]
# self.batchnorm_output = torch.nn.BatchNorm1d(skill_dim)
def forward(
self, input, return_preactivations=False,
):
h = input
for i, fc in enumerate(self.fcs):
h = self.batchnorm_hidden[i](self.hidden_activation(fc(h)))
out = self.last_fc(h)
return out
def predict(self, input):
out = eval_np(self, input)
prob = F.softmax(out)
val = np.argmax(out)
| [
"torch.distributions.Categorical",
"numpy.argmax",
"torch.nn.BatchNorm1d",
"torch.nn.functional.softmax",
"torch.exp",
"rlkit.torch.core.eval_np",
"torch.clamp",
"numpy.array",
"torch.nn.Linear",
"torch.distributions.Normal",
"torch.log",
"numpy.all"
] | [((3681, 3713), 'torch.nn.BatchNorm1d', 'torch.nn.BatchNorm1d', (['input_size'], {}), '(input_size)\n', (3701, 3713), False, 'import torch\n'), ((4166, 4186), 'rlkit.torch.core.eval_np', 'eval_np', (['self', 'input'], {}), '(self, input)\n', (4173, 4186), False, 'from rlkit.torch.core import eval_np\n'), ((4202, 4216), 'torch.nn.functional.softmax', 'F.softmax', (['out'], {}), '(out)\n', (4211, 4216), True, 'from torch.nn import functional as F\n'), ((4231, 4245), 'numpy.argmax', 'np.argmax', (['out'], {}), '(out)\n', (4240, 4245), True, 'import numpy as np\n'), ((1454, 1494), 'torch.nn.Linear', 'nn.Linear', (['last_hidden_size', 'output_size'], {}), '(last_hidden_size, output_size)\n', (1463, 1494), True, 'from torch import nn as nn\n'), ((1727, 1746), 'torch.log', 'torch.log', (['self.std'], {}), '(self.std)\n', (1736, 1746), False, 'import torch\n'), ((1913, 1956), 'torch.nn.Linear', 'nn.Linear', (['hidden_sizes[-1]', 'num_components'], {}), '(hidden_sizes[-1], num_components)\n', (1922, 1956), True, 'from torch import nn as nn\n'), ((2566, 2612), 'torch.clamp', 'torch.clamp', (['log_std', 'LOG_SIG_MIN', 'LOG_SIG_MAX'], {}), '(log_std, LOG_SIG_MIN, LOG_SIG_MAX)\n', (2577, 2612), False, 'import torch\n'), ((2631, 2649), 'torch.exp', 'torch.exp', (['log_std'], {}), '(log_std)\n', (2640, 2649), False, 'import torch\n'), ((3747, 3770), 'torch.nn.BatchNorm1d', 'torch.nn.BatchNorm1d', (['h'], {}), '(h)\n', (3767, 3770), False, 'import torch\n'), ((1685, 1698), 'numpy.array', 'np.array', (['std'], {}), '(std)\n', (1693, 1698), True, 'import numpy as np\n'), ((1766, 1801), 'numpy.all', 'np.all', (['(LOG_SIG_MIN <= self.log_std)'], {}), '(LOG_SIG_MIN <= self.log_std)\n', (1772, 1801), True, 'import numpy as np\n'), ((1806, 1841), 'numpy.all', 'np.all', (['(self.log_std <= LOG_SIG_MAX)'], {}), '(self.log_std <= LOG_SIG_MAX)\n', (1812, 1841), True, 'import numpy as np\n'), ((2989, 3027), 'torch.distributions.Categorical', 'Categorical', ([], {'logits': 'categorical_logits'}), '(logits=categorical_logits)\n', (3000, 3027), False, 'from torch.distributions import Normal, Independent, Categorical\n'), ((3146, 3163), 'torch.distributions.Normal', 'Normal', (['mean', 'std'], {}), '(mean, std)\n', (3152, 3163), False, 'from torch.distributions import Normal, Independent, Categorical\n'), ((3057, 3074), 'torch.distributions.Normal', 'Normal', (['mean', 'std'], {}), '(mean, std)\n', (3063, 3074), False, 'from torch.distributions import Normal, Independent, Categorical\n')] |
import json
import logging
from typing import Callable, Dict, List, Optional, Union
import bokeh
import hail as hl
import numpy as np
import pandas as pd
from bokeh.layouts import gridplot
from bokeh.models import (
BooleanFilter,
CDSView,
Column,
ColumnDataSource,
DataRange1d,
Div,
Grid,
HoverTool,
Legend,
Title,
)
from bokeh.models.widgets import Panel, Tabs
from bokeh.palettes import Spectral8, d3, viridis # pylint: disable=no-name-in-module
from bokeh.plotting import figure
from bokeh.transform import factor_cmap
from gnomad.utils.vep import (
CSQ_CODING_HIGH_IMPACT,
CSQ_CODING_LOW_IMPACT,
CSQ_CODING_MEDIUM_IMPACT,
CSQ_NON_CODING,
CSQ_ORDER,
)
logging.basicConfig(
format="%(asctime)s (%(name)s %(lineno)s): %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Setting some defaults for Table.show
if "old_show" not in dir():
old_show = hl.Table.show
def new_show(t, n=10, width=140, truncate=40, types=True):
old_show(t, n, width, truncate, types)
hl.Table.show = new_show
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
COLOR_CPG = "#2E9FFE"
COLOR_TI = "#458B00"
COLOR_TV = "#EA4444"
ACG = "#422efe"
CCG = "#2e73fe"
GCG = "#2ec3fe"
TCG = "#2efef7"
COLOR_METHYLATED_CPG = "#2E37FE"
variant_type_colors = {
"CpG": COLOR_CPG,
"non-CpG": COLOR_TI,
"non-CpG transition": COLOR_TI,
"transversion": COLOR_TV,
"ACG": ACG,
"CCG": CCG,
"GCG": GCG,
"TCG": TCG,
"methylated CpG": COLOR_METHYLATED_CPG,
}
COLOR_SYN = "#AAAAAA"
COLOR_MIS = "#FF6103"
COLOR_LOF = "#9D1309"
variant_annotation_colors = {x: COLOR_LOF for x in CSQ_CODING_HIGH_IMPACT}
variant_annotation_colors.update({x: COLOR_MIS for x in CSQ_CODING_MEDIUM_IMPACT})
variant_annotation_colors.update(
{x: COLOR_SYN for x in CSQ_CODING_LOW_IMPACT + CSQ_NON_CODING}
)
variant_annotation_colors.update(
{
"stop_lost": COLOR_MIS,
"splice_region_variant": COLOR_SYN,
"start_lost": COLOR_SYN,
"Synonymous": COLOR_SYN,
"Missense": COLOR_MIS,
"LoF": COLOR_LOF,
"PTV": COLOR_LOF,
}
)
variant_annotation_names = dict(
zip(CSQ_ORDER, [x.replace("_variant", "").replace("_", " ") for x in CSQ_ORDER])
)
variant_annotation_names["stop_gained"] = "nonsense"
variant_annotation_names["5_prime_UTR_variant"] = "5' UTR"
variant_annotation_names["3_prime_UTR_variant"] = "3' UTR"
dataset_colors = {"ExAC": "#4682B4", "gnomAD": "#73AB3D"}
def plot_hail_hist(
hist_data: hl.Struct,
title: str = "Plot",
log: bool = False,
fill_color: str = "#033649",
outlier_fill_color: str = "#036564",
line_color: str = "#033649",
hover_mode: str = "mouse",
hide_zeros: bool = False,
) -> bokeh.plotting.Figure:
"""
hist_data can (and should) come straight from ht.aggregate(hl.agg.hist(ht.data, start, end, bins))
:param hist_data: Data to plot
:param title: Plot title
:param log: Whether the y-axis should be log
:param fill_color: Color to fill the histogram bars that fall within the hist boundaries
:param outlier_fill_color: Color to fill the histogram bars that fall outside the hist boundaries
:param line_color: Color of the lines around the histogram bars
:param hover_mode: Hover mode; one of 'mouse' (default), 'vline' or 'hline'
:param hide_zeros: Remove hist bars with 0 count
:return: Histogram plot
"""
return plot_multi_hail_hist(
{"hist": hist_data},
title=title,
log=log,
fill_color={"hist": fill_color},
outlier_fill_color={"hist": outlier_fill_color},
line_color=line_color,
hover_mode=hover_mode,
hide_zeros=hide_zeros,
alpha=1.0,
)
def plot_multi_hail_hist(
hist_data: Dict[str, hl.Struct],
title: str = "Plot",
log: bool = False,
fill_color: Dict[str, str] = None,
outlier_fill_color: Dict[str, str] = None,
line_color: str = "#033649",
hover_mode: str = "mouse",
hide_zeros: bool = False,
alpha: float = None,
) -> bokeh.plotting.Figure:
"""
Plots multiple histograms on the same plot.
Each histogram can (and should) come straight from ht.aggregate(hl.agg.hist(ht.data, start, end, bins))
Example usage:
.. code-block:: python
plot_multi_hail_hist(ht.aggregate(hl.agg.group_by(ht.pop, hl.agg.hist(ht.data, start, end, bins))))
:param hist_data: Data to plot
:param title: Plot title
:param log: Whether the y-axis should be log
:param fill_color: Color to fill the histogram bars that fall within the hist boundaries
:param outlier_fill_color: Color to fill the histogram bars that fall outside the hist boundaries
:param line_color: Color of the lines around the histogram bars
:param hover_mode: Hover mode; one of 'mouse' (default), 'vline' or 'hline'
:param hide_zeros: Remove hist bars with 0 count
:param alpha: Alpha value (if None, then 1.0/len(hist_data) is used)
:return: Histogram plot
"""
low = int(log)
if alpha is None:
alpha = 1.0 / len(hist_data)
if fill_color is None:
color_palette = d3["Category10"][max(3, len(hist_data))]
fill_color = {
hist_name: color_palette[i] for i, hist_name in enumerate(hist_data.keys())
}
if outlier_fill_color is None:
outlier_fill_color = fill_color
p = (
figure(title=title, y_axis_type="log", tools=TOOLS)
if log
else figure(title=title, tools=TOOLS)
)
hists = []
for label, hist in hist_data.items():
data = {}
distance = abs(hist.bin_edges[0] - hist.bin_edges[1])
data["top"] = [x + low for x in hist.bin_freq]
data["left"] = hist.bin_edges[:-1]
data["right"] = hist.bin_edges[1:]
data["color"] = [fill_color[label]] * len(hist.bin_freq)
if hist.n_smaller > 0:
data["top"].insert(0, hist.n_smaller + low)
data["left"].insert(0, hist.bin_edges[0] - distance)
data["right"].insert(0, hist.bin_edges[0])
data["color"].insert(0, outlier_fill_color[label])
if hist.n_larger > 0:
data["top"].append(hist.n_larger + low)
data["left"].append(hist.bin_edges[-1])
data["right"].append(hist.bin_edges[-1] + distance)
data["color"].append(outlier_fill_color[label])
data["bottom"] = [low] * len(data["top"])
data["label"] = [label] * len(data["top"])
hist_source = ColumnDataSource(data)
view = (
CDSView(
source=hist_source,
filters=[BooleanFilter([top > 0 for top in hist_source.data["top"]])],
)
if hide_zeros
else CDSView(source=hist_source)
)
hists.append(
(
label,
[
p.quad(
top="top",
bottom="bottom",
left="left",
right="right",
source=hist_source,
view=view,
fill_color="color",
alpha=alpha,
line_color=line_color,
)
],
)
)
tooltips = [("bin", "$index"), ("bin_edges", "(@left, @right)"), ("freq", "@top")]
if len(hist_data) > 1:
tooltips.insert(0, ("label", "@label"))
p.add_layout(
Legend(
items=hists,
location=(0, 0),
orientation="horizontal",
click_policy="hide",
),
"above",
)
p.select_one(HoverTool).tooltips = tooltips
p.select_one(HoverTool).mode = hover_mode
num_data_points = sum([sum(x.bin_freq) for x in hist_data.values()])
p.add_layout(Title(text=f"({num_data_points:,} data points)"), "above")
return p
def plot_hail_hist_cumulative(
hist_data: hl.Struct,
title: str = "Plot",
normalize: bool = True,
line_color: str = "#036564",
line_width: int = 3,
log: bool = False,
hover_mode: str = "mouse",
) -> bokeh.plotting.Figure:
"""
hist_data can (and should) come straight from ht.aggregate(hl.agg.hist(ht.data, start, end, bins))
:param hist_data: Data to plot
:param title: Plot title
:param normalize: Whether to normalize the data (0,1)
:param line_color: Color of the line
:param line_width: Width of the line
:param log: Whether the y-axis should be log
:param hover_mode: Hover mode; one of 'mouse' (default), 'vline' or 'hline'
:return: Histogram plot
"""
cumulative_data = np.cumsum(hist_data.bin_freq) + hist_data.n_smaller
np.append(cumulative_data, [cumulative_data[-1] + hist_data.n_larger])
num_data_points = max(cumulative_data)
if normalize:
cumulative_data = cumulative_data / num_data_points
p = (
figure(title=title, y_axis_type="log", tools=TOOLS)
if log
else figure(title=title, tools=TOOLS)
)
p.add_layout(Title(text=f"({num_data_points:,} data points)"), "above")
p.select_one(HoverTool).tooltips = [("index", "$index"), ("(x,y)", "(@x, @y)")]
p.select_one(HoverTool).mode = hover_mode
data_source = ColumnDataSource(
{"x": hist_data.bin_edges[:-1], "y": cumulative_data}
)
p.line(
x="x", y="y", line_color=line_color, line_width=line_width, source=data_source
)
return p
def plot_hail_hist_both(
hist_data: hl.Struct, title: str, normalize: bool = True, log: bool = False
):
p1 = plot_hail_hist(hist_data, title, log)
p2 = plot_hail_hist_cumulative(
hist_data, f"{title} (Cumulative)", normalize, log=log
)
return Tabs(
tabs=[Panel(child=p1, title="Raw"), Panel(child=p2, title="Cumulative")]
)
def set_font_size(p, font_size: str = "12pt"):
p.title.text_font_size = font_size
p.legend.label_text_font_size = font_size
p.xaxis.axis_label_text_font_size = font_size
p.yaxis.axis_label_text_font_size = font_size
p.xaxis.major_label_text_font_size = font_size
p.yaxis.major_label_text_font_size = font_size
if hasattr(p.xaxis, "group_text_font_size"):
p.xaxis.group_text_font_size = font_size
return p
def linear_and_log_tabs(plot_func: Callable, **kwargs) -> Tabs:
panels = []
for axis_type in ["linear", "log"]:
fig = plot_func(**kwargs, axis_type=axis_type)
panel = Panel(child=fig, title=axis_type)
panels.append(panel)
return Tabs(tabs=panels)
def plot_hail_file_metadata(
t_path: str,
) -> Optional[Union[Grid, Tabs, bokeh.plotting.Figure]]:
"""
Takes path to hail Table or MatrixTable (gs://bucket/path/hail.mt), outputs Grid or Tabs, respectively.
Or if an unordered Table is provided, a Figure with file sizes is output.
If metadata file or rows directory is missing, returns None.
"""
panel_size = 600
subpanel_size = 150
files = hl.hadoop_ls(t_path)
rows_file = [x["path"] for x in files if x["path"].endswith("rows")]
entries_file = [x["path"] for x in files if x["path"].endswith("entries")]
# cols_file = [x['path'] for x in files if x['path'].endswith('cols')]
success_file = [
x["modification_time"] for x in files if x["path"].endswith("SUCCESS")
]
data_type = "Table"
metadata_file = [x["path"] for x in files if x["path"].endswith("metadata.json.gz")]
if not metadata_file:
logger.warning("No metadata file found. Exiting...")
return None
with hl.hadoop_open(metadata_file[0], "rb") as f:
overall_meta = json.loads(f.read())
rows_per_partition = overall_meta["components"]["partition_counts"]["counts"]
if not rows_file:
logger.warning("No rows directory found. Exiting...")
return None
rows_files = hl.hadoop_ls(rows_file[0])
if entries_file:
data_type = "MatrixTable"
rows_file = [x["path"] for x in rows_files if x["path"].endswith("rows")]
rows_files = hl.hadoop_ls(rows_file[0])
row_partition_bounds, row_file_sizes = get_rows_data(rows_files)
total_file_size, row_file_sizes, row_scale = scale_file_sizes(row_file_sizes)
if not row_partition_bounds:
logger.warning("Table is not partitioned. Only plotting file sizes")
row_file_sizes_hist, row_file_sizes_edges = np.histogram(
row_file_sizes, bins=50
)
p_file_size = figure(plot_width=panel_size, plot_height=panel_size)
p_file_size.quad(
right=row_file_sizes_hist,
left=0,
bottom=row_file_sizes_edges[:-1],
top=row_file_sizes_edges[1:],
fill_color="#036564",
line_color="#033649",
)
p_file_size.yaxis.axis_label = f"File size ({row_scale}B)"
return p_file_size
all_data = {
"partition_widths": [
-1 if x[0] != x[2] else x[3] - x[1] for x in row_partition_bounds
],
"partition_bounds": [
f"{x[0]}:{x[1]}-{x[2]}:{x[3]}" for x in row_partition_bounds
],
"spans_chromosome": [
"Spans chromosomes" if x[0] != x[2] else "Within chromosome"
for x in row_partition_bounds
],
"row_file_sizes": row_file_sizes,
"row_file_sizes_human": [f"{x:.1f} {row_scale}B" for x in row_file_sizes],
"rows_per_partition": rows_per_partition,
"index": list(range(len(rows_per_partition))),
}
if entries_file:
entries_rows_files = hl.hadoop_ls(entries_file[0])
entries_rows_file = [
x["path"] for x in entries_rows_files if x["path"].endswith("rows")
]
if entries_rows_file:
entries_files = hl.hadoop_ls(entries_rows_file[0])
entry_partition_bounds, entry_file_sizes = get_rows_data(entries_files)
total_entry_file_size, entry_file_sizes, entry_scale = scale_file_sizes(
entry_file_sizes
)
all_data["entry_file_sizes"] = entry_file_sizes
all_data["entry_file_sizes_human"] = [
f"{x:.1f} {entry_scale}B" for x in row_file_sizes
]
title = f"{data_type}: {t_path}"
msg = f"Rows: {sum(all_data['rows_per_partition']):,}<br/>Partitions: {len(all_data['rows_per_partition']):,}<br/>Size: {total_file_size}<br/>"
if success_file[0]:
msg += success_file[0]
source = ColumnDataSource(pd.DataFrame(all_data))
p = figure(tools=TOOLS, plot_width=panel_size, plot_height=panel_size)
p.title.text = title
p.xaxis.axis_label = "Number of rows"
p.yaxis.axis_label = f"File size ({row_scale}B)"
color_map = factor_cmap(
"spans_chromosome",
palette=Spectral8,
factors=list(set(all_data["spans_chromosome"])),
)
p.scatter(
"rows_per_partition",
"row_file_sizes",
color=color_map,
legend="spans_chromosome",
source=source,
)
p.legend.location = "bottom_right"
p.select_one(HoverTool).tooltips = [
(x, f"@{x}")
for x in (
"rows_per_partition",
"row_file_sizes_human",
"partition_bounds",
"index",
)
]
p_stats = Div(text=msg)
p_rows_per_partition = figure(
x_range=p.x_range, plot_width=panel_size, plot_height=subpanel_size
)
p_file_size = figure(
y_range=p.y_range, plot_width=subpanel_size, plot_height=panel_size
)
rows_per_partition_hist, rows_per_partition_edges = np.histogram(
all_data["rows_per_partition"], bins=50
)
p_rows_per_partition.quad(
top=rows_per_partition_hist,
bottom=0,
left=rows_per_partition_edges[:-1],
right=rows_per_partition_edges[1:],
fill_color="#036564",
line_color="#033649",
)
row_file_sizes_hist, row_file_sizes_edges = np.histogram(
all_data["row_file_sizes"], bins=50
)
p_file_size.quad(
right=row_file_sizes_hist,
left=0,
bottom=row_file_sizes_edges[:-1],
top=row_file_sizes_edges[1:],
fill_color="#036564",
line_color="#033649",
)
rows_grid = gridplot([[p_rows_per_partition, p_stats], [p, p_file_size]])
if "entry_file_sizes" in all_data:
title = f"Statistics for {data_type}: {t_path}"
msg = f"Rows: {sum(all_data['rows_per_partition']):,}<br/>Partitions: {len(all_data['rows_per_partition']):,}<br/>Size: {total_entry_file_size}<br/>"
if success_file[0]:
msg += success_file[0]
source = ColumnDataSource(pd.DataFrame(all_data))
panel_size = 600
subpanel_size = 150
p = figure(tools=TOOLS, plot_width=panel_size, plot_height=panel_size)
p.title.text = title
p.xaxis.axis_label = "Number of rows"
p.yaxis.axis_label = f"File size ({entry_scale}B)"
color_map = factor_cmap(
"spans_chromosome",
palette=Spectral8,
factors=list(set(all_data["spans_chromosome"])),
)
p.scatter(
"rows_per_partition",
"entry_file_sizes",
color=color_map,
legend="spans_chromosome",
source=source,
)
p.legend.location = "bottom_right"
p.select_one(HoverTool).tooltips = [
(x, f"@{x}")
for x in (
"rows_per_partition",
"entry_file_sizes_human",
"partition_bounds",
"index",
)
]
p_stats = Div(text=msg)
p_rows_per_partition = figure(
x_range=p.x_range, plot_width=panel_size, plot_height=subpanel_size
)
p_rows_per_partition.quad(
top=rows_per_partition_hist,
bottom=0,
left=rows_per_partition_edges[:-1],
right=rows_per_partition_edges[1:],
fill_color="#036564",
line_color="#033649",
)
p_file_size = figure(
y_range=p.y_range, plot_width=subpanel_size, plot_height=panel_size
)
row_file_sizes_hist, row_file_sizes_edges = np.histogram(
all_data["entry_file_sizes"], bins=50
)
p_file_size.quad(
right=row_file_sizes_hist,
left=0,
bottom=row_file_sizes_edges[:-1],
top=row_file_sizes_edges[1:],
fill_color="#036564",
line_color="#033649",
)
entries_grid = gridplot([[p_rows_per_partition, p_stats], [p, p_file_size]])
return Tabs(
tabs=[
Panel(child=entries_grid, title="Entries"),
Panel(child=rows_grid, title="Rows"),
]
)
else:
return rows_grid
def scale_file_sizes(file_sizes):
min_file_size = min(file_sizes) * 1.1
total_file_size = sum(file_sizes)
all_scales = [("T", 1e12), ("G", 1e9), ("M", 1e6), ("K", 1e3), ("", 1e0)]
for overall_scale, overall_factor in all_scales:
if total_file_size > overall_factor:
total_file_size /= overall_factor
break
for scale, factor in all_scales:
if min_file_size > factor:
file_sizes = [x / factor for x in file_sizes]
break
total_file_size = f"{total_file_size:.1f} {overall_scale}B"
return total_file_size, file_sizes, scale
def get_rows_data(rows_files):
file_sizes = []
partition_bounds = []
parts_file = [x["path"] for x in rows_files if x["path"].endswith("parts")]
if parts_file:
parts = hl.hadoop_ls(parts_file[0])
for i, x in enumerate(parts):
index = x["path"].split(f"{parts_file[0]}/part-")[1].split("-")[0]
if i < len(parts) - 1:
test_index = (
parts[i + 1]["path"]
.split(f"{parts_file[0]}/part-")[1]
.split("-")[0]
)
if test_index == index:
continue
file_sizes.append(x["size_bytes"])
metadata_file = [
x["path"] for x in rows_files if x["path"].endswith("metadata.json.gz")
]
if metadata_file:
with hl.hadoop_open(metadata_file[0], "rb") as f:
rows_meta = json.loads(f.read())
try:
partition_bounds = [
(
x["start"]["locus"]["contig"],
x["start"]["locus"]["position"],
x["end"]["locus"]["contig"],
x["end"]["locus"]["position"],
)
for x in rows_meta["jRangeBounds"]
]
except KeyError:
pass
return partition_bounds, file_sizes
def pair_plot(
data: pd.DataFrame,
label_col: str = None,
colors: Union[List[str], Dict[str, str]] = None,
tools: str = "save,pan,box_zoom,reset,wheel_zoom,box_select,lasso_select,help",
tooltip_cols: List[str] = None,
) -> Column:
"""
Plots each column of `data` against each other and returns a grid of plots.
The diagonal contains a histogram of each column, or a density plot if labels are provided.
The lower diagonal contains scatter plots of each column against each other.
The upper diagonal is empty.
All columns should be numerical with the exception of the `label_col` if provided.
If a color dict containing provided mapping labels to specific colors can be specified using `color_dict`
:param data: Dataframe to plot
:param label_col: Column of the DataFrame containing the labels
:param colors: RGB hex colors. If a dict is provided, it should contain the mapping of label to colors.
:param tools: Tools for the resulting plots
:param tooltip_cols: Additional columns that should be displayed in tooltip
:return: Grid of plots (column of rows)
"""
if tooltip_cols is None:
tooltip_cols = [] if label_col is None else [label_col]
elif label_col not in tooltip_cols:
tooltip_cols.append(label_col)
if label_col is None and colors is not None:
logger.warning("`colors_dict` ignored since no `label_col` specified")
colors_col = "__pair_plot_color"
colors_dict = {}
if label_col is None:
data[colors_col] = viridis(1) * len(data)
else:
if not isinstance(colors, dict):
labels = set(data[label_col])
color_palette = viridis(len(labels)) if colors is None else colors
colors_dict = {l: color_palette[i] for i, l in enumerate(labels)}
else:
colors_dict = colors
data[colors_col] = [colors_dict.get(l, "gray") for l in data[label_col]]
tools = "hover," + tools
data_cols = [
c for c in data.columns if c not in [colors_col, label_col] + tooltip_cols
]
data_ranges = [
DataRange1d(
start=rmin - (abs(rmin - rmax) * 0.05), end=rmax + (abs(rmin - rmax) * 0.05)
)
for rmin, rmax in zip(data[data_cols].min(axis=0), data[data_cols].max(axis=0))
]
data_source = ColumnDataSource(data={c: data[c] for c in data.columns})
n_cols = len(data_cols)
plot_grid = []
for i in range(n_cols):
row = [None] * n_cols
for j in range(i + 1):
p = figure(
x_axis_label=data_cols[j] if i == n_cols - 1 else "",
y_axis_label=data_cols[i] if j == 0 else "",
tools=tools,
)
p.x_range = data_ranges[j]
if i == j:
if label_col is None:
hist, edges = np.histogram(
data[data_cols[i]], density=False, bins=50
)
p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:])
else:
density_data = (
data[[label_col, data_cols[i]]]
.groupby(label_col)
.apply(
lambda df: np.histogram(
df[data_cols[i]], density=True, bins=20
)
)
)
for label, (hist, edges) in density_data.iteritems():
line_source = ColumnDataSource(
{
"edges": edges[:-1],
"hist": hist,
label_col: [label] * len(hist),
}
)
p.line(
"edges",
"hist",
color=colors_dict[label],
legend=label_col,
source=line_source,
)
p.select_one(HoverTool).tooltips = [
(label_col, f"@{label_col}")
]
else:
p.y_range = data_ranges[i]
if label_col is not None:
p.circle(
data_cols[j],
data_cols[i],
source=data_source,
color=colors_col,
legend=label_col,
)
else:
p.circle(
data_cols[j], data_cols[i], source=data_source, color=colors_col
)
if tooltip_cols:
p.select_one(HoverTool).tooltips = [
(x, f"@{x}") for x in tooltip_cols
]
row[j] = p
plot_grid.append(row)
return gridplot(plot_grid, toolbar_location="left")
| [
"bokeh.models.ColumnDataSource",
"numpy.histogram",
"pandas.DataFrame",
"hail.hadoop_ls",
"numpy.append",
"numpy.cumsum",
"bokeh.models.widgets.Panel",
"bokeh.models.Legend",
"bokeh.layouts.gridplot",
"bokeh.models.Div",
"bokeh.models.Title",
"bokeh.plotting.figure",
"hail.hadoop_open",
"l... | [((719, 831), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s (%(name)s %(lineno)s): %(message)s"""', 'datefmt': '"""%m/%d/%Y %I:%M:%S %p"""'}), "(format='%(asctime)s (%(name)s %(lineno)s): %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n", (738, 831), False, 'import logging\n'), ((848, 875), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (865, 875), False, 'import logging\n'), ((8885, 8955), 'numpy.append', 'np.append', (['cumulative_data', '[cumulative_data[-1] + hist_data.n_larger]'], {}), '(cumulative_data, [cumulative_data[-1] + hist_data.n_larger])\n', (8894, 8955), True, 'import numpy as np\n'), ((9439, 9510), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (["{'x': hist_data.bin_edges[:-1], 'y': cumulative_data}"], {}), "({'x': hist_data.bin_edges[:-1], 'y': cumulative_data})\n", (9455, 9510), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((10724, 10741), 'bokeh.models.widgets.Tabs', 'Tabs', ([], {'tabs': 'panels'}), '(tabs=panels)\n', (10728, 10741), False, 'from bokeh.models.widgets import Panel, Tabs\n'), ((11172, 11192), 'hail.hadoop_ls', 'hl.hadoop_ls', (['t_path'], {}), '(t_path)\n', (11184, 11192), True, 'import hail as hl\n'), ((12055, 12081), 'hail.hadoop_ls', 'hl.hadoop_ls', (['rows_file[0]'], {}), '(rows_file[0])\n', (12067, 12081), True, 'import hail as hl\n'), ((14713, 14779), 'bokeh.plotting.figure', 'figure', ([], {'tools': 'TOOLS', 'plot_width': 'panel_size', 'plot_height': 'panel_size'}), '(tools=TOOLS, plot_width=panel_size, plot_height=panel_size)\n', (14719, 14779), False, 'from bokeh.plotting import figure\n'), ((15481, 15494), 'bokeh.models.Div', 'Div', ([], {'text': 'msg'}), '(text=msg)\n', (15484, 15494), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((15522, 15597), 'bokeh.plotting.figure', 'figure', ([], {'x_range': 'p.x_range', 'plot_width': 'panel_size', 'plot_height': 'subpanel_size'}), '(x_range=p.x_range, plot_width=panel_size, plot_height=subpanel_size)\n', (15528, 15597), False, 'from bokeh.plotting import figure\n'), ((15630, 15705), 'bokeh.plotting.figure', 'figure', ([], {'y_range': 'p.y_range', 'plot_width': 'subpanel_size', 'plot_height': 'panel_size'}), '(y_range=p.y_range, plot_width=subpanel_size, plot_height=panel_size)\n', (15636, 15705), False, 'from bokeh.plotting import figure\n'), ((15777, 15830), 'numpy.histogram', 'np.histogram', (["all_data['rows_per_partition']"], {'bins': '(50)'}), "(all_data['rows_per_partition'], bins=50)\n", (15789, 15830), True, 'import numpy as np\n'), ((16133, 16182), 'numpy.histogram', 'np.histogram', (["all_data['row_file_sizes']"], {'bins': '(50)'}), "(all_data['row_file_sizes'], bins=50)\n", (16145, 16182), True, 'import numpy as np\n'), ((16433, 16494), 'bokeh.layouts.gridplot', 'gridplot', (['[[p_rows_per_partition, p_stats], [p, p_file_size]]'], {}), '([[p_rows_per_partition, p_stats], [p, p_file_size]])\n', (16441, 16494), False, 'from bokeh.layouts import gridplot\n'), ((23378, 23435), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', ([], {'data': '{c: data[c] for c in data.columns}'}), '(data={c: data[c] for c in data.columns})\n', (23394, 23435), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((26046, 26090), 'bokeh.layouts.gridplot', 'gridplot', (['plot_grid'], {'toolbar_location': '"""left"""'}), "(plot_grid, toolbar_location='left')\n", (26054, 26090), False, 'from bokeh.layouts import gridplot\n'), ((5500, 5551), 'bokeh.plotting.figure', 'figure', ([], {'title': 'title', 'y_axis_type': '"""log"""', 'tools': 'TOOLS'}), "(title=title, y_axis_type='log', tools=TOOLS)\n", (5506, 5551), False, 'from bokeh.plotting import figure\n'), ((5580, 5612), 'bokeh.plotting.figure', 'figure', ([], {'title': 'title', 'tools': 'TOOLS'}), '(title=title, tools=TOOLS)\n', (5586, 5612), False, 'from bokeh.plotting import figure\n'), ((6616, 6638), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['data'], {}), '(data)\n', (6632, 6638), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((8001, 8049), 'bokeh.models.Title', 'Title', ([], {'text': 'f"""({num_data_points:,} data points)"""'}), "(text=f'({num_data_points:,} data points)')\n", (8006, 8049), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((8829, 8858), 'numpy.cumsum', 'np.cumsum', (['hist_data.bin_freq'], {}), '(hist_data.bin_freq)\n', (8838, 8858), True, 'import numpy as np\n'), ((9096, 9147), 'bokeh.plotting.figure', 'figure', ([], {'title': 'title', 'y_axis_type': '"""log"""', 'tools': 'TOOLS'}), "(title=title, y_axis_type='log', tools=TOOLS)\n", (9102, 9147), False, 'from bokeh.plotting import figure\n'), ((9176, 9208), 'bokeh.plotting.figure', 'figure', ([], {'title': 'title', 'tools': 'TOOLS'}), '(title=title, tools=TOOLS)\n', (9182, 9208), False, 'from bokeh.plotting import figure\n'), ((9232, 9280), 'bokeh.models.Title', 'Title', ([], {'text': 'f"""({num_data_points:,} data points)"""'}), "(text=f'({num_data_points:,} data points)')\n", (9237, 9280), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((10649, 10682), 'bokeh.models.widgets.Panel', 'Panel', ([], {'child': 'fig', 'title': 'axis_type'}), '(child=fig, title=axis_type)\n', (10654, 10682), False, 'from bokeh.models.widgets import Panel, Tabs\n'), ((11758, 11796), 'hail.hadoop_open', 'hl.hadoop_open', (['metadata_file[0]', '"""rb"""'], {}), "(metadata_file[0], 'rb')\n", (11772, 11796), True, 'import hail as hl\n'), ((12241, 12267), 'hail.hadoop_ls', 'hl.hadoop_ls', (['rows_file[0]'], {}), '(rows_file[0])\n', (12253, 12267), True, 'import hail as hl\n'), ((12583, 12620), 'numpy.histogram', 'np.histogram', (['row_file_sizes'], {'bins': '(50)'}), '(row_file_sizes, bins=50)\n', (12595, 12620), True, 'import numpy as np\n'), ((12665, 12718), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': 'panel_size', 'plot_height': 'panel_size'}), '(plot_width=panel_size, plot_height=panel_size)\n', (12671, 12718), False, 'from bokeh.plotting import figure\n'), ((13758, 13787), 'hail.hadoop_ls', 'hl.hadoop_ls', (['entries_file[0]'], {}), '(entries_file[0])\n', (13770, 13787), True, 'import hail as hl\n'), ((14681, 14703), 'pandas.DataFrame', 'pd.DataFrame', (['all_data'], {}), '(all_data)\n', (14693, 14703), True, 'import pandas as pd\n'), ((16937, 17003), 'bokeh.plotting.figure', 'figure', ([], {'tools': 'TOOLS', 'plot_width': 'panel_size', 'plot_height': 'panel_size'}), '(tools=TOOLS, plot_width=panel_size, plot_height=panel_size)\n', (16943, 17003), False, 'from bokeh.plotting import figure\n'), ((17815, 17828), 'bokeh.models.Div', 'Div', ([], {'text': 'msg'}), '(text=msg)\n', (17818, 17828), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((17860, 17935), 'bokeh.plotting.figure', 'figure', ([], {'x_range': 'p.x_range', 'plot_width': 'panel_size', 'plot_height': 'subpanel_size'}), '(x_range=p.x_range, plot_width=panel_size, plot_height=subpanel_size)\n', (17866, 17935), False, 'from bokeh.plotting import figure\n'), ((18252, 18327), 'bokeh.plotting.figure', 'figure', ([], {'y_range': 'p.y_range', 'plot_width': 'subpanel_size', 'plot_height': 'panel_size'}), '(y_range=p.y_range, plot_width=subpanel_size, plot_height=panel_size)\n', (18258, 18327), False, 'from bokeh.plotting import figure\n'), ((18403, 18454), 'numpy.histogram', 'np.histogram', (["all_data['entry_file_sizes']"], {'bins': '(50)'}), "(all_data['entry_file_sizes'], bins=50)\n", (18415, 18454), True, 'import numpy as np\n'), ((18751, 18812), 'bokeh.layouts.gridplot', 'gridplot', (['[[p_rows_per_partition, p_stats], [p, p_file_size]]'], {}), '([[p_rows_per_partition, p_stats], [p, p_file_size]])\n', (18759, 18812), False, 'from bokeh.layouts import gridplot\n'), ((19835, 19862), 'hail.hadoop_ls', 'hl.hadoop_ls', (['parts_file[0]'], {}), '(parts_file[0])\n', (19847, 19862), True, 'import hail as hl\n'), ((6858, 6885), 'bokeh.models.CDSView', 'CDSView', ([], {'source': 'hist_source'}), '(source=hist_source)\n', (6865, 6885), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((7622, 7710), 'bokeh.models.Legend', 'Legend', ([], {'items': 'hists', 'location': '(0, 0)', 'orientation': '"""horizontal"""', 'click_policy': '"""hide"""'}), "(items=hists, location=(0, 0), orientation='horizontal', click_policy\n ='hide')\n", (7628, 7710), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((13966, 14000), 'hail.hadoop_ls', 'hl.hadoop_ls', (['entries_rows_file[0]'], {}), '(entries_rows_file[0])\n', (13978, 14000), True, 'import hail as hl\n'), ((16848, 16870), 'pandas.DataFrame', 'pd.DataFrame', (['all_data'], {}), '(all_data)\n', (16860, 16870), True, 'import pandas as pd\n'), ((20455, 20493), 'hail.hadoop_open', 'hl.hadoop_open', (['metadata_file[0]', '"""rb"""'], {}), "(metadata_file[0], 'rb')\n", (20469, 20493), True, 'import hail as hl\n'), ((22584, 22594), 'bokeh.palettes.viridis', 'viridis', (['(1)'], {}), '(1)\n', (22591, 22594), False, 'from bokeh.palettes import Spectral8, d3, viridis\n'), ((23590, 23713), 'bokeh.plotting.figure', 'figure', ([], {'x_axis_label': "(data_cols[j] if i == n_cols - 1 else '')", 'y_axis_label': "(data_cols[i] if j == 0 else '')", 'tools': 'tools'}), "(x_axis_label=data_cols[j] if i == n_cols - 1 else '', y_axis_label=\n data_cols[i] if j == 0 else '', tools=tools)\n", (23596, 23713), False, 'from bokeh.plotting import figure\n'), ((9936, 9964), 'bokeh.models.widgets.Panel', 'Panel', ([], {'child': 'p1', 'title': '"""Raw"""'}), "(child=p1, title='Raw')\n", (9941, 9964), False, 'from bokeh.models.widgets import Panel, Tabs\n'), ((9966, 10001), 'bokeh.models.widgets.Panel', 'Panel', ([], {'child': 'p2', 'title': '"""Cumulative"""'}), "(child=p2, title='Cumulative')\n", (9971, 10001), False, 'from bokeh.models.widgets import Panel, Tabs\n'), ((18870, 18912), 'bokeh.models.widgets.Panel', 'Panel', ([], {'child': 'entries_grid', 'title': '"""Entries"""'}), "(child=entries_grid, title='Entries')\n", (18875, 18912), False, 'from bokeh.models.widgets import Panel, Tabs\n'), ((18930, 18966), 'bokeh.models.widgets.Panel', 'Panel', ([], {'child': 'rows_grid', 'title': '"""Rows"""'}), "(child=rows_grid, title='Rows')\n", (18935, 18966), False, 'from bokeh.models.widgets import Panel, Tabs\n'), ((23907, 23963), 'numpy.histogram', 'np.histogram', (['data[data_cols[i]]'], {'density': '(False)', 'bins': '(50)'}), '(data[data_cols[i]], density=False, bins=50)\n', (23919, 23963), True, 'import numpy as np\n'), ((6739, 6800), 'bokeh.models.BooleanFilter', 'BooleanFilter', (["[(top > 0) for top in hist_source.data['top']]"], {}), "([(top > 0) for top in hist_source.data['top']])\n", (6752, 6800), False, 'from bokeh.models import BooleanFilter, CDSView, Column, ColumnDataSource, DataRange1d, Div, Grid, HoverTool, Legend, Title\n'), ((24321, 24374), 'numpy.histogram', 'np.histogram', (['df[data_cols[i]]'], {'density': '(True)', 'bins': '(20)'}), '(df[data_cols[i]], density=True, bins=20)\n', (24333, 24374), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from keras.utils import to_categorical
from DL_models import get_multiscaleDNN_model
## using synthetic data
input1_len = int(90*(90-1)*0.5)
input2_len = int(200*(200-1)*0.5)
input3_len = int(400*(400-1)*0.5)
input4_len = 5
train_data1 = np.random.randn(80, input1_len)
train_data2 = np.random.randn(80, input2_len)
train_data3 = np.random.randn(80, input3_len)
train_data4 = np.random.randn(80, input4_len)
train_label = to_categorical(np.random.randn(80,)>0)
test_data1 = np.random.randn(80, input1_len)
test_data2 = np.random.randn(80, input2_len)
test_data3 = np.random.randn(80, input3_len)
test_data4 = np.random.randn(80, input4_len)
test_label = to_categorical(np.random.randn(80,)>0)
## construct model
model = get_multiscaleDNN_model(input1_len, input2_len, input3_len, input4_len)
# Fit the model
model_training = model.fit([train_data1, train_data2, train_data3, train_data4], train_label,
epochs=10,
shuffle=True,
verbose=1,
batch_size=8)
##============ predict ============##
score = model.evaluate([test_data1, test_data2, test_data3, test_data4],train_label)
print('Validation accuracy is {}'.format(score[1]))
| [
"DL_models.get_multiscaleDNN_model",
"numpy.random.randn"
] | [((415, 446), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input1_len'], {}), '(80, input1_len)\n', (430, 446), True, 'import numpy as np\n'), ((462, 493), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input2_len'], {}), '(80, input2_len)\n', (477, 493), True, 'import numpy as np\n'), ((509, 540), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input3_len'], {}), '(80, input3_len)\n', (524, 540), True, 'import numpy as np\n'), ((556, 587), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input4_len'], {}), '(80, input4_len)\n', (571, 587), True, 'import numpy as np\n'), ((662, 693), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input1_len'], {}), '(80, input1_len)\n', (677, 693), True, 'import numpy as np\n'), ((708, 739), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input2_len'], {}), '(80, input2_len)\n', (723, 739), True, 'import numpy as np\n'), ((754, 785), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input3_len'], {}), '(80, input3_len)\n', (769, 785), True, 'import numpy as np\n'), ((800, 831), 'numpy.random.randn', 'np.random.randn', (['(80)', 'input4_len'], {}), '(80, input4_len)\n', (815, 831), True, 'import numpy as np\n'), ((920, 991), 'DL_models.get_multiscaleDNN_model', 'get_multiscaleDNN_model', (['input1_len', 'input2_len', 'input3_len', 'input4_len'], {}), '(input1_len, input2_len, input3_len, input4_len)\n', (943, 991), False, 'from DL_models import get_multiscaleDNN_model\n'), ((618, 637), 'numpy.random.randn', 'np.random.randn', (['(80)'], {}), '(80)\n', (633, 637), True, 'import numpy as np\n'), ((861, 880), 'numpy.random.randn', 'np.random.randn', (['(80)'], {}), '(80)\n', (876, 880), True, 'import numpy as np\n')] |
from torch.optim.lr_scheduler import _LRScheduler
import numpy
class WarmUpLR(_LRScheduler):
"""warmup_training learning rate scheduler
Args:
optimizer: optimzier(e.g. SGD)
total_iters: totoal_iters of warmup phase
"""
def __init__(self, optimizer, total_iters, last_epoch=-1):
self.total_iters = total_iters
super().__init__(optimizer, last_epoch)
def get_lr(self):
"""we will use the first m batches, and set the learning
rate to base_lr * m / total_iters
"""
return [base_lr * self.last_epoch / (self.total_iters + 1e-8) for base_lr in self.base_lrs]
def compute_mean_std(cifar100_dataset):
"""compute the mean and std of cifar100 dataset
Args:
cifar100_training_dataset or cifar100_test_dataset
witch derived from class torch.utils.data
Returns:
a tuple contains mean, std value of entire dataset
"""
data_r = numpy.dstack([cifar100_dataset[i][1][:, :, 0] for i in range(len(cifar100_dataset))])
data_g = numpy.dstack([cifar100_dataset[i][1][:, :, 1] for i in range(len(cifar100_dataset))])
data_b = numpy.dstack([cifar100_dataset[i][1][:, :, 2] for i in range(len(cifar100_dataset))])
mean = numpy.mean(data_r), numpy.mean(data_g), numpy.mean(data_b)
std = numpy.std(data_r), numpy.std(data_g), numpy.std(data_b)
return mean, std
| [
"numpy.std",
"numpy.mean"
] | [((1243, 1261), 'numpy.mean', 'numpy.mean', (['data_r'], {}), '(data_r)\n', (1253, 1261), False, 'import numpy\n'), ((1263, 1281), 'numpy.mean', 'numpy.mean', (['data_g'], {}), '(data_g)\n', (1273, 1281), False, 'import numpy\n'), ((1283, 1301), 'numpy.mean', 'numpy.mean', (['data_b'], {}), '(data_b)\n', (1293, 1301), False, 'import numpy\n'), ((1312, 1329), 'numpy.std', 'numpy.std', (['data_r'], {}), '(data_r)\n', (1321, 1329), False, 'import numpy\n'), ((1331, 1348), 'numpy.std', 'numpy.std', (['data_g'], {}), '(data_g)\n', (1340, 1348), False, 'import numpy\n'), ((1350, 1367), 'numpy.std', 'numpy.std', (['data_b'], {}), '(data_b)\n', (1359, 1367), False, 'import numpy\n')] |
# $Id$
#
# This file is part of the BCPy2000 framework, a Python framework for
# implementing modules that run on top of the BCI2000 <http://bci2000.org/>
# platform, for the purpose of realtime biosignal processing.
#
# Copyright (C) 2007-10 <NAME>, <NAME>,
# <NAME>, <NAME>
#
# <EMAIL>
#
# The BCPy2000 framework is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
__all__ = [
'Param', 'escape',
]
import numpy
def escape(s):
if isinstance(s, bool): s = int(s)
if s == None: s = ''
elif not isinstance(s, basestring): s = str(s)
if len(s) == 0: return '%'
out = ''
for c in s:
v = ord(c)
if c == '%' or not 32 < v < 127: out += '%%%02x' % v
else: out += str(c)
return out
class Param(object):
def __init__(self, x, tab='Tab', section='Section', name='ParamName', type='auto', comment='', fmt=None, range=(None,None), default=None, rlabels=None, clabels=None):
self.tab = tab
self.section = section
self.type = type
self.name = name
self.rlabels = rlabels
self.clabels = clabels
self.x = x
self.range = range
self.default = default
self.comment = comment
self.verbosity = 1
def determine_type(self):
x = self.x
if isinstance(x, numpy.ndarray):
if len(x.shape) == 0: x = x.flat[0]
elif len(x.shape) in (1,2): x = x.tolist()
else: raise ValueError("don't know how to deal with >2-D arrays")
if isinstance(x, bool): return 'bool'
if isinstance(x, int): return 'int'
if isinstance(x, float): return 'float'
if isinstance(x, basestring): return 'string'
if isinstance(x, (tuple,list)):
if False not in [isinstance(xi, int) for xi in x]: return 'intlist'
if False not in [isinstance(xi, (int,float)) for xi in x]: return 'floatlist'
if False not in [isinstance(xi, (int,float,basestring)) for xi in x]: return 'list'
if False not in [isinstance(xi, (tuple,list)) for xi in x]: return 'matrix'
raise ValueError("don't know how to deal with this data type")
def make_string(self, verbosity=1):
type = self.type
comment = self.comment
if verbosity < 1: comment = ''
comment = ' // ' + comment
if type in (None, 'auto'): type = self.determine_type()
if type == 'bool': type = 'int'; comment = comment + ' (boolean)'
s = '%s:%s %s %s= ' % (self.tab, self.section, type, self.name)
if type.endswith('list'):
x = numpy.asarray(self.x).flat
s += str(len(x))
xstr = ' ' + ' '.join([escape(xi) for xi in x])
elif type.endswith('matrix'):
x = numpy.asarray(self.x)
if self.rlabels == None: s += ' %d' % len(x)
elif len(self.rlabels) != len(x): raise ValueError("wrong number of row labels (got %d, expected %d)" % (len(self.rlabels), len(x)))
else: s += ' { ' + ' '.join([escape(xi) for xi in self.rlabels]) + ' }'
if self.clabels == None: s += ' %d' % len(x[0])
elif len(self.clabels) != len(x[0]): raise ValueError("wrong number of column labels (got %d, expected %d)" % (len(self.clabels), len(x[0])))
else: s += ' { ' + ' '.join([escape(xi) for xi in self.clabels]) + ' }'
xstr = ' ' + ' '.join([' '.join([escape(xi) for xi in row]) for row in x])
else:
xstr = escape(self.x)
if verbosity == 0 and len(xstr) > 10: xstr = '...'
s += ' ' + xstr
if verbosity >= 2:
range = self.range
if range == None: range = (None,None)
elif not isinstance(range, (tuple,list)): range = (0, range)
s += ' ' + escape(self.default) + ' ' + escape(range[0]) + ' ' + escape(range[1])
s += comment
return s
def writeto(self, file, append=False):
if isinstance(file, basestring):
mode = {True:'a', False:'w'}[append]
file = open(file, mode + 't')
if not append: file.seek(0)
file.write(str(self)+'\n')
def appendto(self, file):
return self.writeto(file, append=True)
def __getslice__(self, s, e):
return self.__getitem__(slice(s,e,None))
def __getitem__(self, sub):
def conv(self, i, x):
if isinstance(x, (tuple,list)):
if i == None: return [conv(self,i,xi) for i,xi in enumerate(x)]
else: return [conv(self, i, xi) for xi in x]
if i == None: i = 0
if isinstance(x, slice): return slice(conv(self,i,x.start), conv(self,i,x.stop), conv(self,i,x.step))
if isinstance(x, int):
if x < 0: x += numpy.asarray(self.x).shape[i]
return x
if not isinstance(x, basestring): return x
if i == 0: lab = self.rlabels; labname = 'row'
elif i == 1: lab = self.clabels; labname = 'column'
else: raise TypeError("too many subscripts")
if lab == None or x not in lab: raise ValueError("%s label '%s' not found" % (labname, x))
return lab.index(x)
sub = conv(self, None, sub)
if not hasattr(sub, '__len__') or len(sub) == 1: return numpy.asarray(self.x).__getitem__(sub)
elif len(sub) == 2: return numpy.asarray(numpy.asmatrix(self.x).__getitem__(sub))
return numpy.asarray(self.x).__getitem__(sub)
def __repr__(self):
return '<%s object at 0x%08X>: %s' % (self.__class__.__name__, id(self), self.make_string(verbosity=0))
def __str__(self):
return self.make_string(verbosity=max(1, self.verbosity))
| [
"numpy.asarray",
"numpy.asmatrix"
] | [((3008, 3029), 'numpy.asarray', 'numpy.asarray', (['self.x'], {}), '(self.x)\n', (3021, 3029), False, 'import numpy\n'), ((3152, 3173), 'numpy.asarray', 'numpy.asarray', (['self.x'], {}), '(self.x)\n', (3165, 3173), False, 'import numpy\n'), ((5527, 5548), 'numpy.asarray', 'numpy.asarray', (['self.x'], {}), '(self.x)\n', (5540, 5548), False, 'import numpy\n'), ((5393, 5414), 'numpy.asarray', 'numpy.asarray', (['self.x'], {}), '(self.x)\n', (5406, 5414), False, 'import numpy\n'), ((4936, 4957), 'numpy.asarray', 'numpy.asarray', (['self.x'], {}), '(self.x)\n', (4949, 4957), False, 'import numpy\n'), ((5476, 5498), 'numpy.asmatrix', 'numpy.asmatrix', (['self.x'], {}), '(self.x)\n', (5490, 5498), False, 'import numpy\n')] |
import numpy as np
import keras
import matplotlib.pyplot as plt
import tensorflow as tf
import keras.models
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.models import Model, load_model
from keras.layers import Dense, Dropout, Flatten, merge, UpSampling2D, Reshape, BatchNormalization
from keras.layers import Input, TimeDistributed
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import plot_model
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
from keras import backend as K
from keras.engine.topology import Layer
from tensorflow.python.ops import array_ops
from scipy.linalg._expm_frechet import vec
from tensorflow.python.framework import ops
from tensorflow.python.framework.op_def_library import _Flatten, _IsListValue
from keras.callbacks import TensorBoard, ModelCheckpoint
# from modelUnet import *
# from data import *
import cv2
import os
import tensorflow as tf
from skimage import transform
from scipy import ndimage
import numpy as np
from scipy.ndimage import zoom
from keras.callbacks import TensorBoard
from scipy import misc
from scipy.misc.pilutil import imread
# from createNEt import *
filePath1 = '/nfs/data/main/M32/Samik/180830/180830_JH_WG_Fezf2LSLflp_CFA_female_processed/TrainingDataProofread/small_train/train/pred'
filePath2 = '/nfs/data/main/M32/Samik/180830/180830_JH_WG_Fezf2LSLflp_CFA_female_processed/TrainingDataProofread/small_train/mask'
filePath3 = '/nfs/data/main/M32/Samik/180830/180830_JH_WG_Fezf2LSLflp_CFA_female_processed/TrainingDataProofread/small_train/dm'
fileList1 = os.listdir(filePath1)
fileList2 = os.listdir(filePath2)
fileList3 = os.listdir(filePath3)
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# config = tf.ConfigProto()
# config.gpu_options.allow_growth=True
# sess = tf.Session(config=config)
# K.set_session(sess)
eps = 0.001
def readImagesTwice(files1, name1, name2, name3):
L = len(files1)
X = []
Y = []
Z = []
# P = []
#filePath = 'membrane//morseUpdate/'
for f1 in files1:
img = imread(name1 + "/" + f1)
# print max(max(row) for row in img)
img = img.astype('float32')
# print(img.max())
# print filePath + name2 + "/" + f1[:-8] + '_mask.tif', filePath + name1 + "/" + f1
mask = imread(name2 + "/" + f1).astype('float32')
dm = imread(name3 + "/" + f1).astype('float32')
print(img.max(),dm.max(),mask.max())
img = img / 255.
dm = dm / 255.
mask = mask / 255.
X.append(img)
Y.append(dm)
Z.append(mask)
# P.append(org)
X_arr = np.asarray(X)
X_arr = X_arr[..., np.newaxis]
Y_arr = np.asarray(Y)
Y_arr = Y_arr[..., np.newaxis]
Z_arr = np.asarray(Z)
Z_arr = Z_arr[..., np.newaxis]
# P_arr = np.asarray(P)
# P_arr = P_arr[..., np.newaxis]
return X_arr, Y_arr, Z_arr
[X, Y, Z] = readImagesTwice(fileList1, filePath1, filePath2, filePath3)
np.save('dmSTP_RT.npy', Y)
np.save('albuSTP_RT.npy', X)
np.save('segSTP_RT.npy', Z)
# np.save('imgTrnR.npy', P)
| [
"scipy.misc.pilutil.imread",
"numpy.asarray",
"numpy.save",
"os.listdir"
] | [((1658, 1679), 'os.listdir', 'os.listdir', (['filePath1'], {}), '(filePath1)\n', (1668, 1679), False, 'import os\n'), ((1692, 1713), 'os.listdir', 'os.listdir', (['filePath2'], {}), '(filePath2)\n', (1702, 1713), False, 'import os\n'), ((1726, 1747), 'os.listdir', 'os.listdir', (['filePath3'], {}), '(filePath3)\n', (1736, 1747), False, 'import os\n'), ((3020, 3046), 'numpy.save', 'np.save', (['"""dmSTP_RT.npy"""', 'Y'], {}), "('dmSTP_RT.npy', Y)\n", (3027, 3046), True, 'import numpy as np\n'), ((3047, 3075), 'numpy.save', 'np.save', (['"""albuSTP_RT.npy"""', 'X'], {}), "('albuSTP_RT.npy', X)\n", (3054, 3075), True, 'import numpy as np\n'), ((3076, 3103), 'numpy.save', 'np.save', (['"""segSTP_RT.npy"""', 'Z'], {}), "('segSTP_RT.npy', Z)\n", (3083, 3103), True, 'import numpy as np\n'), ((2677, 2690), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (2687, 2690), True, 'import numpy as np\n'), ((2738, 2751), 'numpy.asarray', 'np.asarray', (['Y'], {}), '(Y)\n', (2748, 2751), True, 'import numpy as np\n'), ((2799, 2812), 'numpy.asarray', 'np.asarray', (['Z'], {}), '(Z)\n', (2809, 2812), True, 'import numpy as np\n'), ((2123, 2147), 'scipy.misc.pilutil.imread', 'imread', (["(name1 + '/' + f1)"], {}), "(name1 + '/' + f1)\n", (2129, 2147), False, 'from scipy.misc.pilutil import imread\n'), ((2363, 2387), 'scipy.misc.pilutil.imread', 'imread', (["(name2 + '/' + f1)"], {}), "(name2 + '/' + f1)\n", (2369, 2387), False, 'from scipy.misc.pilutil import imread\n'), ((2419, 2443), 'scipy.misc.pilutil.imread', 'imread', (["(name3 + '/' + f1)"], {}), "(name3 + '/' + f1)\n", (2425, 2443), False, 'from scipy.misc.pilutil import imread\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed May 16 12:46:00 2018
@author: <NAME>
"""
# =============================================================================
# Chapter 0: Import Modules
# =============================================================================
import logging
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()
# =============================================================================
# Chapter 1: Setting Logging Parameters
# =============================================================================
#logging.basicConfig(filename='reports/plot.log',
# format='%(asctime)s-%(levelname)s:%(message)s',
# datefmt='%d/%m/%Y %H:%M:%S',
# level=logging.DEBUG)
# =============================================================================
# Chapter 2: Plot Losses of the Network
# =============================================================================
def plot_loss(losses):
'''
Plot the losses of the network
'''
logging.info('Plotting the Losses of the' +
'Discriminative and Generative Models')
plt.figure(figsize=(10, 8))
plt.plot(losses["D"], label='Discriminitive loss')
plt.plot(losses["G"], label='Generative loss')
plt.legend()
plt.savefig('reports/figures/losses.png')
plt.close()
# =============================================================================
# Chapter 3: Plot generated Images
# =============================================================================
def plot_gen(generator, n_ex=16, dim=(4, 4), figsize=(10, 10)):
'''
Plot the generated images
'''
logging.info('Generaring noise to seed the image')
noise = np.random.uniform(0, 1, size=[n_ex, 100])
logging.info('Passing through image generator')
generated_images = generator.predict(noise)
logging.info('Plotting the image generated')
plt.figure(figsize=figsize)
for i in range(generated_images.shape[0]):
plt.subplot(dim[0], dim[1], i+1)
img = generated_images[i, :, :, 0].reshape([28, 28])
plt.imshow(img)
plt.axis('off')
plt.savefig('reports/figures/generated.png')
plt.close()
| [
"numpy.random.uniform",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.axis",
"logging.info",
"matplotlib.pyplot.figure",
"seaborn.set",
"matplotlib.pyplot.savefig"
] | [((362, 371), 'seaborn.set', 'sns.set', ([], {}), '()\n', (369, 371), True, 'import seaborn as sns\n'), ((1064, 1151), 'logging.info', 'logging.info', (["('Plotting the Losses of the' + 'Discriminative and Generative Models')"], {}), "('Plotting the Losses of the' +\n 'Discriminative and Generative Models')\n", (1076, 1151), False, 'import logging\n'), ((1169, 1196), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (1179, 1196), True, 'import matplotlib.pyplot as plt\n'), ((1201, 1251), 'matplotlib.pyplot.plot', 'plt.plot', (["losses['D']"], {'label': '"""Discriminitive loss"""'}), "(losses['D'], label='Discriminitive loss')\n", (1209, 1251), True, 'import matplotlib.pyplot as plt\n'), ((1256, 1302), 'matplotlib.pyplot.plot', 'plt.plot', (["losses['G']"], {'label': '"""Generative loss"""'}), "(losses['G'], label='Generative loss')\n", (1264, 1302), True, 'import matplotlib.pyplot as plt\n'), ((1307, 1319), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1317, 1319), True, 'import matplotlib.pyplot as plt\n'), ((1324, 1365), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""reports/figures/losses.png"""'], {}), "('reports/figures/losses.png')\n", (1335, 1365), True, 'import matplotlib.pyplot as plt\n'), ((1370, 1381), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1379, 1381), True, 'import matplotlib.pyplot as plt\n'), ((1693, 1743), 'logging.info', 'logging.info', (['"""Generaring noise to seed the image"""'], {}), "('Generaring noise to seed the image')\n", (1705, 1743), False, 'import logging\n'), ((1756, 1797), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': '[n_ex, 100]'}), '(0, 1, size=[n_ex, 100])\n', (1773, 1797), True, 'import numpy as np\n'), ((1802, 1849), 'logging.info', 'logging.info', (['"""Passing through image generator"""'], {}), "('Passing through image generator')\n", (1814, 1849), False, 'import logging\n'), ((1903, 1947), 'logging.info', 'logging.info', (['"""Plotting the image generated"""'], {}), "('Plotting the image generated')\n", (1915, 1947), False, 'import logging\n'), ((1952, 1979), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (1962, 1979), True, 'import matplotlib.pyplot as plt\n'), ((2181, 2225), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""reports/figures/generated.png"""'], {}), "('reports/figures/generated.png')\n", (2192, 2225), True, 'import matplotlib.pyplot as plt\n'), ((2230, 2241), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2239, 2241), True, 'import matplotlib.pyplot as plt\n'), ((2035, 2069), 'matplotlib.pyplot.subplot', 'plt.subplot', (['dim[0]', 'dim[1]', '(i + 1)'], {}), '(dim[0], dim[1], i + 1)\n', (2046, 2069), True, 'import matplotlib.pyplot as plt\n'), ((2137, 2152), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (2147, 2152), True, 'import matplotlib.pyplot as plt\n'), ((2161, 2176), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2169, 2176), True, 'import matplotlib.pyplot as plt\n')] |
import numpy as np
import pytest
from pandas._libs.tslibs import iNaT
from pandas._libs.tslibs.period import IncompatibleFrequency
from pandas.core.dtypes.base import registry
from pandas.core.dtypes.dtypes import PeriodDtype
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import (
PeriodArray,
period_array,
)
# ----------------------------------------------------------------------------
# Dtype
def test_registered():
assert PeriodDtype in registry.dtypes
result = registry.find("Period[D]")
expected = PeriodDtype("D")
assert result == expected
# ----------------------------------------------------------------------------
# period_array
def test_asi8():
result = period_array(["2000", "2001", None], freq="D").asi8
expected = np.array([10957, 11323, iNaT])
tm.assert_numpy_array_equal(result, expected)
def test_take_raises():
arr = period_array(["2000", "2001"], freq="D")
with pytest.raises(IncompatibleFrequency, match="freq"):
arr.take([0, -1], allow_fill=True, fill_value=pd.Period("2000", freq="W"))
msg = "value should be a 'Period' or 'NaT'. Got 'str' instead"
with pytest.raises(TypeError, match=msg):
arr.take([0, -1], allow_fill=True, fill_value="foo")
def test_fillna_raises():
arr = period_array(["2000", "2001", "2002"], freq="D")
with pytest.raises(ValueError, match="Length"):
arr.fillna(arr[:2])
def test_fillna_copies():
arr = period_array(["2000", "2001", "2002"], freq="D")
result = arr.fillna(pd.Period("2000", "D"))
assert result is not arr
# ----------------------------------------------------------------------------
# setitem
@pytest.mark.parametrize(
"key, value, expected",
[
([0], pd.Period("2000", "D"), [10957, 1, 2]),
([0], None, [iNaT, 1, 2]),
([0], np.nan, [iNaT, 1, 2]),
([0, 1, 2], pd.Period("2000", "D"), [10957] * 3),
(
[0, 1, 2],
[pd.Period("2000", "D"), pd.Period("2001", "D"), pd.Period("2002", "D")],
[10957, 11323, 11688],
),
],
)
def test_setitem(key, value, expected):
arr = PeriodArray(np.arange(3), freq="D")
expected = PeriodArray(expected, freq="D")
arr[key] = value
tm.assert_period_array_equal(arr, expected)
def test_setitem_raises_incompatible_freq():
arr = PeriodArray(np.arange(3), freq="D")
with pytest.raises(IncompatibleFrequency, match="freq"):
arr[0] = pd.Period("2000", freq="A")
other = period_array(["2000", "2001"], freq="A")
with pytest.raises(IncompatibleFrequency, match="freq"):
arr[[0, 1]] = other
def test_setitem_raises_length():
arr = PeriodArray(np.arange(3), freq="D")
with pytest.raises(ValueError, match="length"):
arr[[0, 1]] = [pd.Period("2000", freq="D")]
def test_setitem_raises_type():
arr = PeriodArray(np.arange(3), freq="D")
with pytest.raises(TypeError, match="int"):
arr[0] = 1
# ----------------------------------------------------------------------------
# Ops
def test_sub_period():
arr = period_array(["2000", "2001"], freq="D")
other = pd.Period("2000", freq="M")
with pytest.raises(IncompatibleFrequency, match="freq"):
arr - other
# ----------------------------------------------------------------------------
# Methods
@pytest.mark.parametrize(
"other",
[pd.Period("2000", freq="H"), period_array(["2000", "2001", "2000"], freq="H")],
)
def test_where_different_freq_raises(other):
ser = pd.Series(period_array(["2000", "2001", "2002"], freq="D"))
cond = np.array([True, False, True])
with pytest.raises(IncompatibleFrequency, match="freq"):
ser.where(cond, other)
# ----------------------------------------------------------------------------
# Printing
def test_repr_small():
arr = period_array(["2000", "2001"], freq="D")
result = str(arr)
expected = (
"<PeriodArray>\n['2000-01-01', '2001-01-01']\nLength: 2, dtype: period[D]"
)
assert result == expected
def test_repr_large():
arr = period_array(["2000", "2001"] * 500, freq="D")
result = str(arr)
expected = (
"<PeriodArray>\n"
"['2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', "
"'2000-01-01',\n"
" '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', "
"'2001-01-01',\n"
" ...\n"
" '2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', "
"'2000-01-01',\n"
" '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', "
"'2001-01-01']\n"
"Length: 1000, dtype: period[D]"
)
assert result == expected
| [
"pandas.core.arrays.period_array",
"pandas.core.arrays.PeriodArray",
"pandas.core.dtypes.base.registry.find",
"pandas._testing.assert_period_array_equal",
"pytest.raises",
"numpy.array",
"pandas.Period",
"numpy.arange",
"pandas.core.dtypes.dtypes.PeriodDtype",
"pandas._testing.assert_numpy_array_e... | [((516, 542), 'pandas.core.dtypes.base.registry.find', 'registry.find', (['"""Period[D]"""'], {}), "('Period[D]')\n", (529, 542), False, 'from pandas.core.dtypes.base import registry\n'), ((558, 574), 'pandas.core.dtypes.dtypes.PeriodDtype', 'PeriodDtype', (['"""D"""'], {}), "('D')\n", (569, 574), False, 'from pandas.core.dtypes.dtypes import PeriodDtype\n'), ((800, 830), 'numpy.array', 'np.array', (['[10957, 11323, iNaT]'], {}), '([10957, 11323, iNaT])\n', (808, 830), True, 'import numpy as np\n'), ((835, 880), 'pandas._testing.assert_numpy_array_equal', 'tm.assert_numpy_array_equal', (['result', 'expected'], {}), '(result, expected)\n', (862, 880), True, 'import pandas._testing as tm\n'), ((917, 957), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001']"], {'freq': '"""D"""'}), "(['2000', '2001'], freq='D')\n", (929, 957), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((1315, 1363), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001', '2002']"], {'freq': '"""D"""'}), "(['2000', '2001', '2002'], freq='D')\n", (1327, 1363), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((1482, 1530), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001', '2002']"], {'freq': '"""D"""'}), "(['2000', '2001', '2002'], freq='D')\n", (1494, 1530), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((2220, 2251), 'pandas.core.arrays.PeriodArray', 'PeriodArray', (['expected'], {'freq': '"""D"""'}), "(expected, freq='D')\n", (2231, 2251), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((2277, 2320), 'pandas._testing.assert_period_array_equal', 'tm.assert_period_array_equal', (['arr', 'expected'], {}), '(arr, expected)\n', (2305, 2320), True, 'import pandas._testing as tm\n'), ((2533, 2573), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001']"], {'freq': '"""A"""'}), "(['2000', '2001'], freq='A')\n", (2545, 2573), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((3118, 3158), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001']"], {'freq': '"""D"""'}), "(['2000', '2001'], freq='D')\n", (3130, 3158), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((3171, 3198), 'pandas.Period', 'pd.Period', (['"""2000"""'], {'freq': '"""M"""'}), "('2000', freq='M')\n", (3180, 3198), True, 'import pandas as pd\n'), ((3625, 3654), 'numpy.array', 'np.array', (['[True, False, True]'], {}), '([True, False, True])\n', (3633, 3654), True, 'import numpy as np\n'), ((3874, 3914), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001']"], {'freq': '"""D"""'}), "(['2000', '2001'], freq='D')\n", (3886, 3914), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((4108, 4154), 'pandas.core.arrays.period_array', 'period_array', (["(['2000', '2001'] * 500)"], {'freq': '"""D"""'}), "(['2000', '2001'] * 500, freq='D')\n", (4120, 4154), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((733, 779), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001', None]"], {'freq': '"""D"""'}), "(['2000', '2001', None], freq='D')\n", (745, 779), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((967, 1017), 'pytest.raises', 'pytest.raises', (['IncompatibleFrequency'], {'match': '"""freq"""'}), "(IncompatibleFrequency, match='freq')\n", (980, 1017), False, 'import pytest\n'), ((1179, 1214), 'pytest.raises', 'pytest.raises', (['TypeError'], {'match': 'msg'}), '(TypeError, match=msg)\n', (1192, 1214), False, 'import pytest\n'), ((1373, 1414), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Length"""'}), "(ValueError, match='Length')\n", (1386, 1414), False, 'import pytest\n'), ((1555, 1577), 'pandas.Period', 'pd.Period', (['"""2000"""', '"""D"""'], {}), "('2000', 'D')\n", (1564, 1577), True, 'import pandas as pd\n'), ((2181, 2193), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (2190, 2193), True, 'import numpy as np\n'), ((2390, 2402), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (2399, 2402), True, 'import numpy as np\n'), ((2423, 2473), 'pytest.raises', 'pytest.raises', (['IncompatibleFrequency'], {'match': '"""freq"""'}), "(IncompatibleFrequency, match='freq')\n", (2436, 2473), False, 'import pytest\n'), ((2492, 2519), 'pandas.Period', 'pd.Period', (['"""2000"""'], {'freq': '"""A"""'}), "('2000', freq='A')\n", (2501, 2519), True, 'import pandas as pd\n'), ((2583, 2633), 'pytest.raises', 'pytest.raises', (['IncompatibleFrequency'], {'match': '"""freq"""'}), "(IncompatibleFrequency, match='freq')\n", (2596, 2633), False, 'import pytest\n'), ((2721, 2733), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (2730, 2733), True, 'import numpy as np\n'), ((2754, 2795), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""length"""'}), "(ValueError, match='length')\n", (2767, 2795), False, 'import pytest\n'), ((2905, 2917), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (2914, 2917), True, 'import numpy as np\n'), ((2938, 2975), 'pytest.raises', 'pytest.raises', (['TypeError'], {'match': '"""int"""'}), "(TypeError, match='int')\n", (2951, 2975), False, 'import pytest\n'), ((3208, 3258), 'pytest.raises', 'pytest.raises', (['IncompatibleFrequency'], {'match': '"""freq"""'}), "(IncompatibleFrequency, match='freq')\n", (3221, 3258), False, 'import pytest\n'), ((3564, 3612), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001', '2002']"], {'freq': '"""D"""'}), "(['2000', '2001', '2002'], freq='D')\n", (3576, 3612), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((3664, 3714), 'pytest.raises', 'pytest.raises', (['IncompatibleFrequency'], {'match': '"""freq"""'}), "(IncompatibleFrequency, match='freq')\n", (3677, 3714), False, 'import pytest\n'), ((3417, 3444), 'pandas.Period', 'pd.Period', (['"""2000"""'], {'freq': '"""H"""'}), "('2000', freq='H')\n", (3426, 3444), True, 'import pandas as pd\n'), ((3446, 3494), 'pandas.core.arrays.period_array', 'period_array', (["['2000', '2001', '2000']"], {'freq': '"""H"""'}), "(['2000', '2001', '2000'], freq='H')\n", (3458, 3494), False, 'from pandas.core.arrays import PeriodArray, period_array\n'), ((1775, 1797), 'pandas.Period', 'pd.Period', (['"""2000"""', '"""D"""'], {}), "('2000', 'D')\n", (1784, 1797), True, 'import pandas as pd\n'), ((1907, 1929), 'pandas.Period', 'pd.Period', (['"""2000"""', '"""D"""'], {}), "('2000', 'D')\n", (1916, 1929), True, 'import pandas as pd\n'), ((2820, 2847), 'pandas.Period', 'pd.Period', (['"""2000"""'], {'freq': '"""D"""'}), "('2000', freq='D')\n", (2829, 2847), True, 'import pandas as pd\n'), ((1073, 1100), 'pandas.Period', 'pd.Period', (['"""2000"""'], {'freq': '"""W"""'}), "('2000', freq='W')\n", (1082, 1100), True, 'import pandas as pd\n'), ((1991, 2013), 'pandas.Period', 'pd.Period', (['"""2000"""', '"""D"""'], {}), "('2000', 'D')\n", (2000, 2013), True, 'import pandas as pd\n'), ((2015, 2037), 'pandas.Period', 'pd.Period', (['"""2001"""', '"""D"""'], {}), "('2001', 'D')\n", (2024, 2037), True, 'import pandas as pd\n'), ((2039, 2061), 'pandas.Period', 'pd.Period', (['"""2002"""', '"""D"""'], {}), "('2002', 'D')\n", (2048, 2061), True, 'import pandas as pd\n')] |
import pandas as pd
import numpy as np
import scipy.stats
from prettytable import PrettyTable
from prettytable import MSWORD_FRIENDLY
class bibd():
def __init__(self, file_name, alpha=0.05):
dataset = pd.read_csv(file_name)
missing=dataset.isna().sum(axis = 1)[0]
data = dataset.iloc[:,1:].values
data = data.astype(np.float)
self.no_of_treatments = np.size(data, 1)
self.blocks = np.size(data, 0)
k=self.no_of_treatments-missing
sum = np.nansum(data)
N=self.blocks*k
r=N/self.no_of_treatments
lambd = r*(k-1)/(self.no_of_treatments-1)
bias = sum*sum/(N)
self.ss_total = np.nansum(np.square(data))-bias
self.ss_blocks = np.nansum(np.square(np.nansum(data, axis=1)))/k-bias
self.ss_treatments=0
for i in range(self.no_of_treatments):
temp=np.nansum(data, axis=0)[i]
for j in range(self.blocks):
if not (np.isnan(data[j][i])):
temp-=(np.nansum(data, axis=1)[j])/k
self.ss_treatments+=temp*temp
self.ss_treatments=self.ss_treatments*k/(lambd*self.no_of_treatments)
self.ss_error = self.ss_total - self.ss_blocks - self.ss_treatments
self.df_total = N-1
self.df_treatments = self.no_of_treatments - 1
self.df_blocks=self.blocks-1
self.df_error = self.df_total - self.df_treatments - self.df_blocks
self.ms_treatments = self.ss_treatments/self.df_treatments
self.ms_blocks = self.ss_blocks/self.df_blocks
self.ms_error = self.ss_error/self.df_error
self.F_treatments = self.ms_treatments/self.ms_error
self.F_blocks = self.ms_blocks/self.ms_error
self.p_value_treatments = 1-scipy.stats.f.cdf(self.F_treatments, dfn=self.df_treatments, dfd=self.df_error)
self.p_value_blocks = 1-scipy.stats.f.cdf(self.F_blocks, dfn=self.df_blocks, dfd=self.df_error)
self.x = PrettyTable()
self.x.set_style(MSWORD_FRIENDLY)
self.x.field_names = ["Source of Variation", "Sum of squares", "Degrees of Freedom", "Mean Square", "F", "p value"]
self.x.float_format["Sum of squares"] = ' 10.2'
self.x.float_format["Mean Square"] = ' 10.2'
self.x.float_format["F"] = ' 10.2'
self.x.float_format["p value"] = ' 10.4'
self.x.add_row(["Treatments", self.ss_treatments, self.df_treatments, self.ms_treatments, self.F_treatments, self.p_value_treatments])
self.x.add_row(["Blocks", self.ss_blocks, self.df_blocks, self.ms_blocks, self.F_blocks, self.p_value_blocks])
self.x.add_row(["Error", self.ss_error, self.df_error, self.ms_error, " ", " "])
self.x.add_row(["Total", self.ss_total, self.df_total, " ", " ", " "])
def print(self):
print(self.x)
def export(self):
with open('result.csv', 'w') as csvFile:
csvFile.write(self.x.get_string())
| [
"numpy.nansum",
"numpy.size",
"pandas.read_csv",
"numpy.square",
"numpy.isnan",
"prettytable.PrettyTable"
] | [((204, 226), 'pandas.read_csv', 'pd.read_csv', (['file_name'], {}), '(file_name)\n', (215, 226), True, 'import pandas as pd\n'), ((361, 377), 'numpy.size', 'np.size', (['data', '(1)'], {}), '(data, 1)\n', (368, 377), True, 'import numpy as np\n'), ((394, 410), 'numpy.size', 'np.size', (['data', '(0)'], {}), '(data, 0)\n', (401, 410), True, 'import numpy as np\n'), ((453, 468), 'numpy.nansum', 'np.nansum', (['data'], {}), '(data)\n', (462, 468), True, 'import numpy as np\n'), ((1734, 1747), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (1745, 1747), False, 'from prettytable import PrettyTable\n'), ((608, 623), 'numpy.square', 'np.square', (['data'], {}), '(data)\n', (617, 623), True, 'import numpy as np\n'), ((774, 797), 'numpy.nansum', 'np.nansum', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (783, 797), True, 'import numpy as np\n'), ((845, 865), 'numpy.isnan', 'np.isnan', (['data[j][i]'], {}), '(data[j][i])\n', (853, 865), True, 'import numpy as np\n'), ((669, 692), 'numpy.nansum', 'np.nansum', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (678, 692), True, 'import numpy as np\n'), ((880, 903), 'numpy.nansum', 'np.nansum', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (889, 903), True, 'import numpy as np\n')] |
"""
Environment module
"""
from typing import Dict, Optional
import gym
import math
import numpy as np
from typing import Dict, List
from atcenv.definitions import *
from gym.envs.classic_control import rendering
from shapely.geometry import LineString, MultiPoint
from shapely.ops import nearest_points
WHITE = [255, 255, 255]
GREEN = [0, 255, 0]
BLUE = [0, 0, 255]
BLACK = [0, 0, 0]
RED = [255, 0, 0]
YELLOW = [255, 255, 0]
class Environment(gym.Env):
metadata = {'render.modes': ['rgb_array']}
def __init__(self,
num_flights: int = 10,
dt: float = 5.,
max_area: Optional[float] = 200. * 200.,
min_area: Optional[float] = 125. * 125.,
max_speed: Optional[float] = 500.,
min_speed: Optional[float] = 400,
max_episode_len: Optional[int] = 300,
min_distance: Optional[float] = 5.,
distance_init_buffer: Optional[float] = 5.,
max_agent_seen: Optional[int] = 3,
**kwargs):
"""
Initialises the environment
:param num_flights: numer of flights in the environment
:param dt: time step (in seconds)
:param max_area: maximum area of the sector (in nm^2)
:param min_area: minimum area of the sector (in nm^2)
:param max_speed: maximum speed of the flights (in kt)
:param min_speed: minimum speed of the flights (in kt)
:param max_episode_len: maximum episode length (in number of steps)
:param min_distance: pairs of flights which distance is < min_distance are considered in conflict (in nm)
:param distance_init_buffer: distance factor used when initialising the enviroment to avoid flights close to conflict and close to the target
:param kwargs: other arguments of your custom environment
:param max_agent_seen: maximum number of closest agents to consider in the partial observation
"""
self.num_flights = num_flights
self.max_area = max_area * (u.nm ** 2)
self.min_area = min_area * (u.nm ** 2)
self.max_speed = max_speed * u.kt
self.min_speed = min_speed * u.kt
self.min_distance = min_distance * u.nm
self.max_episode_len = max_episode_len
self.distance_init_buffer = distance_init_buffer
self.max_agent_seen = max_agent_seen
self.dt = dt
# tolerance to consider that the target has been reached (in meters)
self.tol = self.max_speed * 1.05 * self.dt
self.viewer = None
self.airspace = None
self.flights = [] # list of flights
self.conflicts = set() # set of flights that are in conflict
self.done = set() # set of flights that reached the target
self.i = None
def resolution(self, action: List) -> None:
"""
Applies the resolution actions
If your policy can modify the speed, then remember to clip the speed of each flight
In the range [min_speed, max_speed]
:param action: list of resolution actions assigned to each flight
:return:
"""
# RDC: here you should implement your resolution actions
##########################################################
return None
##########################################################
def reward(self) -> List:
"""
Returns the reward assigned to each agent
:return: reward assigned to each agent
"""
# RDC: here you should implement your reward function
##########################################################
return []
##########################################################
def observation(self) -> List:
"""
Returns the observation of each agent. A single agent observation is a
np.array of dimension 2*self.max_agent_seen. It represents the distances
(dx, dy) with the self.max_agent_seen closest flights
:return: observation of each agent
"""
observations = []
for i, flight in enumerate(self.flights):
obs = np.zeros(self.max_agent_seen * 2, dtype=np.float32)
origin = flight.position
seen_agents_indices = self.flights_in_fov(i)
if len(seen_agents_indices) != 0:
# if we saw less agents than the maximum number, we pick all of them
if len(seen_agents_indices) <= self.max_agent_seen:
for j, seen_agent_idx in enumerate(seen_agents_indices):
obs[j * 2:j * 2 + 2] = self.flights[seen_agent_idx].position.x - origin.x, \
self.flights[seen_agent_idx].position.y - origin.y
else:
# set of points of all the agents in the fov
seen_agents = MultiPoint(
[self.flights[seen_agent_idx].position for seen_agent_idx in seen_agents_indices])
# take the 3 closest agent
for j in range(self.max_agent_seen):
nearest_agent = nearest_points(origin, seen_agents)
obs[j * 2:j * 2 + 2] = nearest_agent.x - \
origin.x, nearest_agent.y - origin.y
seen_agents.difference(nearest_agent)
observations.append(obs)
# RDC: here you should implement your observation function
##########################################################
return observations
##########################################################
def flights_in_fov(self, flight_id: int) -> List:
"""
returns all the agents id in the FoV of the given agent
:return seen_agents: list of agent ids inside the FoV of the current agent
"""
seen_agents = []
flight_fov = self.flights[flight_id].fov
for i, flight in enumerate(self.flights):
if i == flight_id:
continue
else:
if flight_fov.contains(flight.position):
seen_agents.append(i)
##########################################################
return seen_agents
##########################################################
def update_conflicts(self) -> None:
"""
Updates the set of flights that are in conflict
Note: flights that reached the target are not considered
:return:
"""
# reset set
self.conflicts = set()
for i in range(self.num_flights - 1):
if i not in self.done:
for j in range(i + 1, self.num_flights):
if j not in self.done:
distance = self.flights[i].position.distance(
self.flights[j].position)
if distance < self.min_distance:
self.conflicts.update((i, j))
def update_done(self) -> None:
"""
Updates the set of flights that reached the target
:return:
"""
for i, f in enumerate(self.flights):
if i not in self.done:
distance = f.position.distance(f.target)
if distance < self.tol:
self.done.add(i)
def update_positions(self) -> None:
"""
Updates the position of the agents
Note: the position of agents that reached the target is not modified
:return:
"""
for i, f in enumerate(self.flights):
if i not in self.done:
# get current speed components
dx, dy = f.components
# get current position
position = f.position
# get new position and advance one time step
f.position._set_coords(
position.x + dx * self.dt, position.y + dy * self.dt)
def step(self, action: List) -> Tuple[List, List, bool, Dict]:
"""
Performs a simulation step
:param action: list of resolution actions assigned to each flight
:return: observation, reward, done status and other information
"""
# apply resolution actions
self.resolution(action)
# update positions
self.update_positions()
# update done set
self.update_done()
# update conflict set
self.update_conflicts()
# compute reward
rew = self.reward()
# compute observation
obs = self.observation()
# increase steps counter
self.i += 1
# check termination status
# termination happens when
# (1) all flights reached the target
# (2) the maximum episode length is reached
done = (self.i == self.max_episode_len) or (
len(self.done) == self.num_flights)
return rew, obs, done, {}
def reset(self) -> List:
"""
Resets the environment and returns initial observation
:return: initial observation
"""
# create random airspace
self.airspace = Airspace.random(self.min_area, self.max_area)
# create random flights
self.flights = []
tol = self.distance_init_buffer * self.tol
min_distance = self.distance_init_buffer * self.min_distance
idx = 0
while len(self.flights) < self.num_flights:
valid = True
candidate = Flight.random(
self.airspace, self.min_speed, self.max_speed, idx, tol)
# ensure that candidate is not in conflict
for f in self.flights:
if candidate.position.distance(f.position) < min_distance:
valid = False
break
if valid:
self.flights.append(candidate)
idx += 1
# initialise steps counter
self.i = 0
# clean conflicts and done sets
self.conflicts = set()
self.done = set()
# return initial observation
return self.observation()
def render(self, mode=None) -> None:
"""
Renders the environment
:param mode: rendering mode
:return:
"""
if self.viewer is None:
# initialise viewer
screen_width, screen_height = 600, 600
minx, miny, maxx, maxy = self.airspace.polygon.buffer(
10 * u.nm).bounds
self.viewer = rendering.Viewer(screen_width, screen_height)
self.viewer.set_bounds(minx, maxx, miny, maxy)
# fill background
background = rendering.make_polygon([(minx, miny),
(minx, maxy),
(maxx, maxy),
(maxx, miny)],
filled=True)
background.set_color(*BLACK)
self.viewer.add_geom(background)
# display airspace
sector = rendering.make_polygon(
self.airspace.polygon.boundary.coords, filled=False)
sector.set_linewidth(1)
sector.set_color(*WHITE)
self.viewer.add_geom(sector)
# add current positions
for i, f in enumerate(self.flights):
if i in self.done:
continue
if i in self.conflicts:
color = RED
else:
color = BLUE
circle = rendering.make_circle(radius=self.min_distance / 2.0,
res=10,
filled=False)
circle.add_attr(rendering.Transform(translation=(f.position.x,
f.position.y)))
circle.set_color(*BLUE)
plan = LineString([f.position, f.target])
self.viewer.draw_polyline(plan.coords, linewidth=1, color=color)
prediction = LineString([f.position, f.prediction])
self.viewer.draw_polyline(
prediction.coords, linewidth=4, color=color)
self.viewer.add_onetime(circle)
# add fovs
fov_points = list(zip(*f.fov.exterior.coords.xy))[:-1]
fov = rendering.make_polygon(fov_points, filled=True)
# fov = rendering.make_polygon([(fov_points[0].x, fov_points[0].y),
# (fov_points[1].x, fov_points[1].y),
# (fov_points[2].x, fov_points[2].y),
# ],
# filled=True)
fov.set_color(*YELLOW)
self.viewer.add_onetime(fov)
self.viewer.render()
def close(self) -> None:
"""
Closes the viewer
:return:
"""
if self.viewer is not None:
self.viewer.close()
self.viewer = None
| [
"gym.envs.classic_control.rendering.make_circle",
"gym.envs.classic_control.rendering.Transform",
"shapely.geometry.MultiPoint",
"shapely.ops.nearest_points",
"gym.envs.classic_control.rendering.make_polygon",
"numpy.zeros",
"shapely.geometry.LineString",
"gym.envs.classic_control.rendering.Viewer"
] | [((4166, 4217), 'numpy.zeros', 'np.zeros', (['(self.max_agent_seen * 2)'], {'dtype': 'np.float32'}), '(self.max_agent_seen * 2, dtype=np.float32)\n', (4174, 4217), True, 'import numpy as np\n'), ((10598, 10643), 'gym.envs.classic_control.rendering.Viewer', 'rendering.Viewer', (['screen_width', 'screen_height'], {}), '(screen_width, screen_height)\n', (10614, 10643), False, 'from gym.envs.classic_control import rendering\n'), ((10759, 10856), 'gym.envs.classic_control.rendering.make_polygon', 'rendering.make_polygon', (['[(minx, miny), (minx, maxy), (maxx, maxy), (maxx, miny)]'], {'filled': '(True)'}), '([(minx, miny), (minx, maxy), (maxx, maxy), (maxx,\n miny)], filled=True)\n', (10781, 10856), False, 'from gym.envs.classic_control import rendering\n'), ((11187, 11262), 'gym.envs.classic_control.rendering.make_polygon', 'rendering.make_polygon', (['self.airspace.polygon.boundary.coords'], {'filled': '(False)'}), '(self.airspace.polygon.boundary.coords, filled=False)\n', (11209, 11262), False, 'from gym.envs.classic_control import rendering\n'), ((11662, 11737), 'gym.envs.classic_control.rendering.make_circle', 'rendering.make_circle', ([], {'radius': '(self.min_distance / 2.0)', 'res': '(10)', 'filled': '(False)'}), '(radius=self.min_distance / 2.0, res=10, filled=False)\n', (11683, 11737), False, 'from gym.envs.classic_control import rendering\n'), ((12032, 12066), 'shapely.geometry.LineString', 'LineString', (['[f.position, f.target]'], {}), '([f.position, f.target])\n', (12042, 12066), False, 'from shapely.geometry import LineString, MultiPoint\n'), ((12169, 12207), 'shapely.geometry.LineString', 'LineString', (['[f.position, f.prediction]'], {}), '([f.position, f.prediction])\n', (12179, 12207), False, 'from shapely.geometry import LineString, MultiPoint\n'), ((12462, 12509), 'gym.envs.classic_control.rendering.make_polygon', 'rendering.make_polygon', (['fov_points'], {'filled': '(True)'}), '(fov_points, filled=True)\n', (12484, 12509), False, 'from gym.envs.classic_control import rendering\n'), ((11852, 11913), 'gym.envs.classic_control.rendering.Transform', 'rendering.Transform', ([], {'translation': '(f.position.x, f.position.y)'}), '(translation=(f.position.x, f.position.y))\n', (11871, 11913), False, 'from gym.envs.classic_control import rendering\n'), ((4908, 5005), 'shapely.geometry.MultiPoint', 'MultiPoint', (['[self.flights[seen_agent_idx].position for seen_agent_idx in\n seen_agents_indices]'], {}), '([self.flights[seen_agent_idx].position for seen_agent_idx in\n seen_agents_indices])\n', (4918, 5005), False, 'from shapely.geometry import LineString, MultiPoint\n'), ((5171, 5206), 'shapely.ops.nearest_points', 'nearest_points', (['origin', 'seen_agents'], {}), '(origin, seen_agents)\n', (5185, 5206), False, 'from shapely.ops import nearest_points\n')] |
"""Chi distribution."""
import numpy
from scipy import special
from ..baseclass import SimpleDistribution, ShiftScaleDistribution
class chi(SimpleDistribution):
"""Chi distribution."""
def __init__(self, df=1):
super(chi, self).__init__(dict(df=df))
def _pdf(self, x, df):
return x**(df-1)*numpy.exp(-x*x*.5)/2**(df*.5-1)/special.gamma(df*.5)
def _cdf(self, x, df):
return special.gammainc(df*0.5,0.5*x*x)
def _ppf(self, q, df):
return numpy.sqrt(2*special.gammaincinv(df*0.5, q))
def _lower(self, df):
return numpy.sqrt(2*special.gammaincinv(df*0.5, 1e-12))
def _upper(self, df):
return numpy.sqrt(2*special.gammaincinv(df*0.5, 1-1e-12))
def _mom(self, k, df):
return 2**(.5*k)*special.gamma(.5*(df+k))/special.gamma(.5*df)
class Chi(ShiftScaleDistribution):
"""
Chi distribution.
Args:
df (float, Distribution):
Degrees of freedom
scale (float, Distribution):
Scaling parameter
shift (float, Distribution):
Location parameter
Examples:
>>> distribution = chaospy.Chi(1.5)
>>> distribution
Chi(1.5)
>>> uloc = numpy.linspace(0, 1, 6)
>>> uloc
array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
>>> xloc = distribution.inv(uloc)
>>> xloc.round(3)
array([0. , 0.472, 0.791, 1.127, 1.568, 7.294])
>>> numpy.allclose(distribution.fwd(xloc), uloc)
True
>>> distribution.pdf(xloc).round(3)
array([0. , 0.596, 0.631, 0.546, 0.355, 0. ])
>>> distribution.sample(4).round(3)
array([1.229, 0.321, 2.234, 0.924])
>>> distribution.mom(1).round(3)
1.046
"""
def __init__(self, df=1, scale=1, shift=0):
super(Chi, self).__init__(
dist=chi(df),
scale=scale,
shift=shift,
repr_args=[df],
)
class Maxwell(ShiftScaleDistribution):
"""
Maxwell-Boltzmann distribution
Chi distribution with 3 degrees of freedom
Args:
scale (float, Distribution):
Scaling parameter
shift (float, Distribution):
Location parameter
Examples:
>>> distribution = chaospy.Maxwell()
>>> distribution
Maxwell()
>>> uloc = numpy.linspace(0, 1, 6)
>>> uloc
array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
>>> xloc = distribution.inv(uloc)
>>> xloc.round(3)
array([0. , 1.003, 1.367, 1.716, 2.154, 7.676])
>>> numpy.allclose(distribution.fwd(xloc), uloc)
True
>>> distribution.pdf(xloc).round(3)
array([0. , 0.485, 0.586, 0.539, 0.364, 0. ])
>>> distribution.sample(4).round(3)
array([1.819, 0.806, 2.798, 1.507])
>>> distribution.mom(1).round(3)
1.596
"""
def __init__(self, scale=1, shift=0):
super(Maxwell, self).__init__(
dist=chi(3),
scale=scale,
shift=shift,
repr_args=[],
)
class Rayleigh(ShiftScaleDistribution):
"""
Rayleigh distribution
Args:
scale (float, Distribution):
Scaling parameter
shift (float, Distribution):
Location parameter
Examples:
>>> distribution = chaospy.Rayleigh()
>>> distribution
Rayleigh()
>>> uloc = numpy.linspace(0, 1, 6)
>>> uloc
array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
>>> xloc = distribution.inv(uloc)
>>> xloc.round(3)
array([0. , 0.668, 1.011, 1.354, 1.794, 7.434])
>>> numpy.allclose(distribution.fwd(xloc), uloc)
True
>>> distribution.pdf(xloc).round(3)
array([0. , 0.534, 0.606, 0.541, 0.359, 0. ])
>>> distribution.sample(4).round(3)
array([1.456, 0.494, 2.45 , 1.147])
>>> distribution.mom(1).round(3)
1.253
"""
def __init__(self, scale=1, shift=0):
super(Rayleigh, self).__init__(
dist=chi(2),
scale=scale,
shift=shift,
repr_args=[],
)
| [
"scipy.special.gamma",
"numpy.exp",
"scipy.special.gammainc",
"scipy.special.gammaincinv"
] | [((419, 458), 'scipy.special.gammainc', 'special.gammainc', (['(df * 0.5)', '(0.5 * x * x)'], {}), '(df * 0.5, 0.5 * x * x)\n', (435, 458), False, 'from scipy import special\n'), ((355, 378), 'scipy.special.gamma', 'special.gamma', (['(df * 0.5)'], {}), '(df * 0.5)\n', (368, 378), False, 'from scipy import special\n'), ((802, 825), 'scipy.special.gamma', 'special.gamma', (['(0.5 * df)'], {}), '(0.5 * df)\n', (815, 825), False, 'from scipy import special\n'), ((508, 540), 'scipy.special.gammaincinv', 'special.gammaincinv', (['(df * 0.5)', 'q'], {}), '(df * 0.5, q)\n', (527, 540), False, 'from scipy import special\n'), ((595, 631), 'scipy.special.gammaincinv', 'special.gammaincinv', (['(df * 0.5)', '(1e-12)'], {}), '(df * 0.5, 1e-12)\n', (614, 631), False, 'from scipy import special\n'), ((686, 726), 'scipy.special.gammaincinv', 'special.gammaincinv', (['(df * 0.5)', '(1 - 1e-12)'], {}), '(df * 0.5, 1 - 1e-12)\n', (705, 726), False, 'from scipy import special\n'), ((777, 806), 'scipy.special.gamma', 'special.gamma', (['(0.5 * (df + k))'], {}), '(0.5 * (df + k))\n', (790, 806), False, 'from scipy import special\n'), ((323, 346), 'numpy.exp', 'numpy.exp', (['(-x * x * 0.5)'], {}), '(-x * x * 0.5)\n', (332, 346), False, 'import numpy\n')] |
# This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS).
# Last modified by <NAME> (<EMAIL>) 16/08/2021, 16:20. Copyright (c) <NAME>
import inspect
from datetime import date
from typing import List
from warnings import warn
import numpy as np
import scipy.odr as odr
from astropy.units import Quantity, Unit, UnitConversionError
from cycler import cycler
from getdist import plots, MCSamples
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
from ..models import MODEL_PUBLICATION_NAMES
# This is the default colour cycle for the AggregateScalingRelation view method
PRETTY_COLOUR_CYCLE = ['tab:gray', 'tab:blue', 'darkgreen', 'firebrick', 'slateblue', 'goldenrod']
# Given the existing structure of this part of XGA, I would have written a BaseRelation class in xga.products.base,
# but I can't think of a reason why individual scaling relations should have their own classes. One general class
# should be enough. Also I don't want relations to be able to be stored in source objects - these are for samples
# only
class ScalingRelation:
"""
This class is designed to store all information pertaining to a scaling relation fit, either performed by XGA
or from literature. It also aims to make creating publication quality plots simple and easy.
"""
def __init__(self, fit_pars: np.ndarray, fit_par_errs: np.ndarray, model_func, x_norm: Quantity, y_norm: Quantity,
x_name: str, y_name: str, fit_method: str = 'unknown', x_data: Quantity = None,
y_data: Quantity = None, x_err: Quantity = None, y_err: Quantity = None, x_lims: Quantity = None,
odr_output: odr.Output = None, chains: np.ndarray = None, relation_name: str = None,
relation_author: str = 'XGA', relation_year: str = str(date.today().year), relation_doi: str = '',
scatter_par: np.ndarray = None, scatter_chain: np.ndarray = None):
"""
The init for the ScalingRelation class, all information necessary to enable the different functions of
this class will be supplied by the user here.
:param np.ndarray fit_pars: The results of the fit to a model that describes this scaling relation.
:param np.ndarray fit_par_errs: The uncertainties on the fit results for this scalin relation.
:param model_func: A Python function of the model which this scaling relation is described by.
PLEASE NOTE, the function must be defined in the style used in xga.models.misc;
i.e. powerlaw(x: np.ndarray, k: float, a: float), where the first argument is for x values, and the
following arguments are all fit parameters.
:param Quantity x_norm: Quantity to normalise the x data by.
:param Quantity y_norm: Quantity to normalise the y data by.
:param str x_name: The name to be used for the x-axis of the plot (DON'T include the unit, that will be
inferred from an astropy Quantity.
:param str y_name: The name to be used for the y-axis of the plot (DON'T include the unit, that will be
inferred from an astropy Quantity.
:param str fit_method: The method used to fit this data, if known.
:param Quantity x_data: The x-data used to fit this scaling relation, if available. This should be
the raw, un-normalised data.
:param Quantity y_data: The y-data used to fit this scaling relation, if available. This should be
the raw, un-normalised data.
:param Quantity x_err: The x-errors used to fit this scaling relation, if available. This should be
the raw, un-normalised data.
:param Quantity y_err: The y-errors used to fit this scaling relation, if available. This should be
the raw, un-normalised data.
:param Quantity x_lims: The range of x values in which this relation is valid, default is None. If this
information is supplied, please pass it as a Quantity array, with the first element being the lower
bound and the second element being the upper bound.
:param odr.Output odr_output: The orthogonal distance regression output object associated with this
relation's fit, if available and applicable.
:param np.ndarray chains: The parameter chains associated with this relation's fit, if available and
applicable. They should be of shape N_stepxN_par, where N_steps is the number of steps (after burn-in
is removed), and N_par is the number of parameters in the fit.
:param str relation_name: A suitable name for this relation.
:param str relation_author: The author who deserves credit for this relation.
:param str relation_year: The year this relation was produced, default is the current year.
:param str relation_doi: The DOI of the original paper this relation appeared in.
:param np.ndarray scatter_par: A parameter describing the intrinsic scatter of y|x. Optional as many fits don't
include this.
:param np.ndarray scatter_chain: A corresponding MCMC chain for the scatter parameter. Optional.
"""
# These will always be passed in, and are assumed to be in the order required by the model_func that is also
# passed in by the user.
self._fit_pars = fit_pars
self._fit_par_errs = fit_par_errs
# This should be a Python function of the model which was fit to create this relation, and which will take the
# passed fit parameters as arguments
self._model_func = model_func
# These are very important, as many people apply normalisation before fitting, and they give us information
# about the units of the x and y axis in absence of any data (data doesn't have to be passed)
self._x_norm = x_norm
self._y_norm = y_norm
# These are also required, otherwise any plots we make are going to look a bit dumb with no x or y axis labels
self._x_name = x_name
self._y_name = y_name
# The default fit method is 'unknown', as we may not know the method of any relation from literature, but
# if the fit was performed by XGA then something more useful can be passed
self._fit_method = fit_method
# Again if this relation was generated by XGA then these things will be pased, but we might not have (or want)
# the data used to generate scaling relations from literature. If there is data we will check if it has the
# correct units
if x_data is not None and x_data.unit == self.x_unit:
self._x_data = x_data
elif x_data is not None and x_data.unit != self.x_unit:
raise UnitConversionError('Any x data ({d}) passed must have the same units as the x_norm ({n}) '
'argument'.format(d=x_data.unit.to_string(), n=self.x_unit.to_string()))
else:
# An empty quantity is defined if there is no data, rather than leaving it as None
self._x_data = Quantity([], self.x_unit)
if x_err is not None and x_err.unit == self.x_unit:
self._x_err = x_err
elif x_err is not None and x_err.unit != self.x_unit:
raise UnitConversionError('Any x error ({d}) passed must have the same units as the x_norm ({n}) '
'argument'.format(d=x_err.unit.to_string(), n=self.x_unit.to_string()))
else:
# An empty quantity is defined if there is no data, rather than leaving it as None
self._x_err = Quantity([], self.x_unit)
if y_data is not None and y_data.unit == self.y_unit:
self._y_data = y_data
elif y_data is not None and y_data.unit != self.y_unit:
raise UnitConversionError('Any y data ({d}) passed must have the same units as the y_norm ({n}) '
'argument'.format(d=y_data.unit.to_string(), n=self.y_unit.to_string()))
else:
# An empty quantity is defined if there is no data, rather than leaving it as None
self._y_data = Quantity([], self.y_unit)
if y_err is not None and y_err.unit == self.y_unit:
self._y_err = y_err
elif y_err is not None and y_err.unit != self.y_unit:
raise UnitConversionError('Any y error ({d}) passed must have the same units as the y_norm ({n}) '
'argument'.format(d=y_err.unit.to_string(), n=self.y_unit.to_string()))
else:
# An empty quantity is defined if there is no data, rather than leaving it as None
self._y_err = Quantity([], self.y_unit)
# Need to do a unit check (and I'll allow conversions in this case) on the x limits that may or may not
# have been passed by the user.
if x_lims is not None and not x_lims.unit.is_equivalent(self.x_unit):
raise UnitConversionError("Limits on the valid x range must be in units ({lu}) that are compatible with "
"this relation's x units ({ru})".format(lu=x_lims.unit.to_string(),
ru=self.x_unit.to_string()))
elif x_lims is not None and x_lims.unit.is_equivalent(self.x_unit):
self._x_lims = x_lims.to(self.x_unit)
else:
# If nothing is passed then its just None
self._x_lims = x_lims
# If the profile was created by XGA and fitted with ODR, then the user can pass the output object
# from that fitting method - I likely won't do much with it but it will be accessible
self._odr_output = odr_output
# If the profile was created by XGA and fitted by LIRA or emcee, the user can pass chains. I'll include the
# ability to make chain plots and corner plots as well.
if chains is not None and chains.shape[1] != len(self._fit_pars):
raise ValueError("The passed chains don't have an 2nd dimension length ({nd}) equal to the number of fit"
" parameters ({np}).".format(nd=chains.shape[1], np=len(self._fit_pars)))
else:
self._chains = chains
# If the user hasn't passed the name of the relation then I'll generate one from what I know so far
if relation_name is None:
self._name = self._y_name + '-' + self._x_name + ' ' + self.fit_method
else:
self._name = relation_name
# For relations from literature especially I need to give credit the author, and the original paper
self._author = relation_author
self._year = str(relation_year)
self._doi = relation_doi
# Just grabbing the parameter names from the model function to plot on the y-axis
self._par_names = list(inspect.signature(self._model_func).parameters)[1:]
self._scatter = scatter_par
if chains is not None and scatter_chain is not None and len(scatter_chain) != chains.shape[0]:
raise ValueError("There must be the same number of steps in any scatter and parameter chains passed "
"to this relation.")
self._scatter_chain = scatter_chain
@property
def pars(self) -> np.ndarray:
"""
The parameters that describe this scaling relation, along with their uncertainties. They are in the order in
which they are expected to be passed into the model function.
:return: A numpy array of the fit parameters and their uncertainties, first column are parameters,
second column are uncertainties.
:rtype: np.ndarray
"""
return np.concatenate([self._fit_pars.reshape((len(self._fit_pars), 1)),
self._fit_par_errs.reshape((len(self._fit_pars), 1))], axis=1)
@property
def model_func(self):
"""
Provides the model function used to fit this relation.
:return: The Python function of this relation's model.
"""
return self._model_func
@property
def x_name(self) -> str:
"""
A string containing the name of the x-axis of this relation.
:return: A Python string containing the name.
:rtype: str
"""
return self._x_name
@property
def y_name(self) -> str:
"""
A string containing the name of the x-axis of this relation.
:return: A Python string containing the name.
:rtype: str
"""
return self._y_name
@property
def x_norm(self) -> Quantity:
"""
The astropy quantity containing the x-axis normalisation used during fitting.
:return: An astropy quantity object.
:rtype: Quantity
"""
return self._x_norm
@property
def y_norm(self) -> Quantity:
"""
The astropy quantity containing the y-axis normalisation used during fitting.
:return: An astropy quantity object.
:rtype: Quantity
"""
return self._y_norm
@property
def x_unit(self) -> Unit:
"""
The astropy unit object relevant to the x-axis of this relation.
:return: An Astropy Unit object.
:rtype: Unit
"""
return self._x_norm.unit
@property
def y_unit(self) -> Unit:
"""
The astropy unit object relevant to the y-axis of this relation.
:return: An Astropy Unit object.
:rtype: Unit
"""
return self._y_norm.unit
@property
def x_data(self) -> Quantity:
"""
An astropy Quantity of the x-data used to fit this relation, or an empty quantity if that data
is not available. The first column is the data, the second is the uncertainties.
:return: An Astropy Quantity object, containing the data and uncertainties.
:rtype: Quantity
"""
num_points = len(self._x_data)
return np.concatenate([self._x_data.reshape((num_points, 1)), self._x_err.reshape((num_points, 1))], axis=1)
@property
def y_data(self) -> Quantity:
"""
An astropy Quantity of the y-data used to fit this relation, or an empty quantity if that data
is not available. The first column is the data, the second is the uncertainties.
:return: An Astropy Quantity object, containing the data and uncertainties.
:rtype: Quantity
"""
num_points = len(self._y_data)
return np.concatenate([self._y_data.reshape((num_points, 1)), self._y_err.reshape((num_points, 1))], axis=1)
@property
def x_lims(self) -> Quantity:
"""
If the user passed an x range in which the relation is valid on initialisation, then this will
return those limits in the same units as the x-axis.
:return: A quantity containing upper and lower x limits, or None.
:rtype: Quantity
"""
return self._x_lims
@property
def fit_method(self) -> str:
"""
A descriptor for the fit method used to generate this scaling relation.
:return: A string containing the name of the fit method.
:rtype: str
"""
return self._fit_method
@property
def name(self) -> str:
"""
A property getter for the name of the relation, this may not be unique in cases where no name was
passed on declaration.
:return: String containing the name of the relation.
:rtype: str
"""
return self._name
@name.setter
def name(self, new_val: str):
"""
A property setter for the name of the relation, it isn't a crucial quantity and the user may want to change
it after declaration has already happened.
:param str new_val:
"""
self._name = new_val
@property
def author(self) -> str:
"""
A property getter for the author of the relation, if not from literature it will be XGA.
:return: String containing the name of the author.
:rtype: str
"""
return self._author
@property
def year(self) -> str:
"""
A property getter for the year that the relation was created/published, if not from literature it will be the
current year.
:return: String containing the year of publication/creation.
:rtype: str
"""
return self._year
@property
def doi(self) -> str:
"""
A property getter for the doi of the original paper of the relation, if not from literature it will an
empty string.
:return: String containing the doi.
:rtype: str
"""
return self._doi
@property
def scatter_par(self) -> np.ndarray:
"""
A getter for the scatter information.
:return: The scatter parameter and its uncertainty. If no scatter information was passed on definition
then this will return None.
:rtype: np.ndarray
"""
return self._scatter
@property
def scatter_chain(self) -> np.ndarray:
"""
A getter for the scatter information chain.
:return: The scatter chain. If no scatter information was passed on definition then this will return None.
:rtype: np.ndarray
"""
return self._scatter_chain
@property
def chains(self) -> np.ndarray:
"""
Property getter for the parameter chains.
:return: The MCMC chains of the fit for this scaling relation, if they were passed. Otherwise None.
:rtype: np.ndarray
"""
return self._chains
@property
def par_names(self) -> List:
"""
Getter for the parameter names.
:return: The names of the model parameters.
:rtype: List
"""
return self._par_names
def view_chains(self, figsize: tuple = None):
"""
Simple view method to quickly look at the MCMC chains for a scaling relation fit.
:param tuple figsize: Desired size of the figure, if None will be set automatically.
"""
if self._chains is None:
raise ValueError('No chains are available for this scaling relation')
num_ch = len(self._fit_pars)
if self._scatter_chain is not None:
num_ch += 1
if figsize is None:
fig, axes = plt.subplots(nrows=num_ch, figsize=(12, 2 * num_ch), sharex='col')
else:
fig, axes = plt.subplots(num_ch, figsize=figsize, sharex='col')
# Now we iterate through the parameters and plot their chains
for i in range(len(self._fit_pars)):
ax = axes[i]
ax.plot(self._chains[:, i], "k", alpha=0.5)
ax.set_xlim(0, self._chains.shape[0])
ax.set_ylabel(self._par_names[i])
ax.yaxis.set_label_coords(-0.1, 0.5)
if num_ch > len(self._fit_pars):
ax = axes[-1]
ax.plot(self._scatter_chain, "k", alpha=0.5)
ax.set_xlim(0, len(self._scatter_chain))
ax.set_ylabel(r'$\sigma$')
ax.yaxis.set_label_coords(-0.1, 0.5)
axes[-1].set_xlabel("Step Number")
plt.show()
def view_corner(self, figsize: tuple = (10, 10), cust_par_names: List[str] = None,
colour: str = 'tab:gray', save_path: str = None):
"""
A convenient view method to examine the corner plot of the parameter posterior distributions.
:param tuple figsize: The size of the figure.
:param List[str] cust_par_names: A list of custom parameter names. If the names include LaTeX code do not
include $$ math environment symbols - you may also need to pass a string literal (e.g. r"\sigma"). Do
not include an entry for a scatter parameter.
:param List[str] colour: Colour for the contours, the default is tab:gray.
:param str save_path: The path where the figure produced by this method should be saved. Default is None, in
which case the figure will not be saved.
"""
# Checks whether custom parameter names were passed, and if they were it checks whether there are the right
# number
if cust_par_names is not None and len(cust_par_names) == len(self._par_names):
par_names = cust_par_names
elif cust_par_names is not None and len(cust_par_names) != len(self._par_names):
raise ValueError("cust_par_names must have one entry per parameter of the scaling relation model.")
else:
par_names = self._par_names
if self._chains is None:
raise ValueError('No chains are available for this scaling relation')
if self._scatter_chain is None:
samp_obj = MCSamples(samples=self._chains, label=self.name, names=par_names, labels=par_names)
else:
par_names += [r'\sigma']
all_ch = np.hstack([self._chains, self._scatter_chain[..., None]])
samp_obj = MCSamples(samples=all_ch, label=self.name, names=par_names, labels=par_names)
g = plots.get_subplot_plotter(width_inch=figsize[0])
if colour is not None:
g.triangle_plot(samp_obj, filled=True, contour_colors=[colour])
else:
g.triangle_plot(samp_obj, filled=True)
# If the user passed a save_path value, then we assume they want to save the figure
if save_path is not None:
plt.savefig(save_path)
plt.show()
def predict(self, x_values: Quantity) -> Quantity:
"""
This method allows for the prediction of y values from this scaling relation, you just need to pass in an
appropriate set of x values.
:param Quantity x_values: The x values to predict y values for.
:return: The predicted y values
:rtype: Quantity
"""
# Got to check that people aren't passing any nonsense x quantities in
if not x_values.unit.is_equivalent(self.x_unit):
raise UnitConversionError('Values of x passed to the predict method ({xp}) must be convertible '
'to the x-axis units of this scaling relation '
'({xr}).'.format(xp=x_values.unit.to_string(), xr=self.x_unit.to_string()))
# This is a check that all passed x values are within the validity limits of this relation (if the
# user passed those on init) - if they aren't a warning will be issued
if self.x_lims is not None and len(x_values[(x_values < self.x_lims[0]) | (x_values > self.x_lims[1])]) != 0:
warn("Some of the x values you have passed are outside the validity range of this relation "
"({l}-{h}{u}).".format(l=self.x_lims[0].value, h=self.x_lims[1].value, u=self.x_unit.to_string()))
# Units that are convertible to the x-units of this relation are allowed, so we make sure we convert
# to the exact units the fit was done in. This includes dividing by the x_norm value
x_values = x_values.to(self.x_unit) / self.x_norm
# Then we just pass the x_values into the model, along with fit parameters. Then multiply by
# the y normalisation
predicted_y = self._model_func(x_values.value, *self.pars[:, 0]) * self.y_norm
return predicted_y
def view(self, x_lims: Quantity = None, log_scale: bool = True, plot_title: str = None, figsize: tuple = (10, 8),
data_colour: str = 'black', model_colour: str = 'grey', grid_on: bool = False, conf_level: int = 90,
custom_x_label: str = None, custom_y_label: str = None, fontsize: float = 15, legend_fontsize: float = 13,
x_ticks: list = None, x_minor_ticks: list = None, y_ticks: list = None, y_minor_ticks: list = None,
save_path: str = None):
"""
A method that produces a high quality plot of this scaling relation (including the data it is based upon,
if available).
:param Quantity x_lims: If not set, this method will attempt to take appropriate limits from the x-data
this relation is based upon, if that data is not available an error will be thrown.
:param bool log_scale: If true then the x and y axes of the plot will be log-scaled.
:param str plot_title: A custom title to be used for the plot, otherwise one will be generated automatically.
:param tuple figsize: A custom figure size for the plot, default is (8, 8).
:param str data_colour: The colour to use for the data points in the plot, default is black.
:param str model_colour: The colour to use for the model in the plot, default is grey.
:param bool grid_on: If True then a grid will be included on the plot. Default is True.
:param int conf_level: The confidence level to use when plotting the model.
:param str custom_x_label: Passing a string to this variable will override the x axis label
of this plot, including the unit string.
:param str custom_y_label: Passing a string to this variable will override the y axis label
of this plot, including the unit string.
:param float fontsize: The fontsize for axis labels.
:param float legend_fontsize: The fontsize for text in the legend.
:param list x_ticks: Customise which major x-axis ticks and labels are on the figure, default is None in which
case they are determined automatically.
:param list x_minor_ticks: Customise which minor x-axis ticks and labels are on the figure, default is
None in which case they are determined automatically.
:param list y_ticks: Customise which major y-axis ticks and labels are on the figure, default is None in which
case they are determined automatically.
:param list y_minor_ticks: Customise which minor y-axis ticks and labels are on the figure, default is
None in which case they are determined automatically.
:param str save_path: The path where the figure produced by this method should be saved. Default is None, in
which case the figure will not be saved.
"""
# First we check that the passed axis limits are in appropriate units, if they weren't supplied then we check
# if any were supplied at initialisation, if that isn't the case then we make our own from the data, and
# if there's no data then we get stroppy
if x_lims is not None and x_lims.unit.is_equivalent(self.x_unit):
x_lims = x_lims.to(self.x_unit).value
elif self.x_lims is not None:
x_lims = self.x_lims.value
elif x_lims is not None and not x_lims.unit.is_equivalent(self.x_unit):
raise UnitConversionError('Limits on the x-axis ({xl}) must be convertible to the x-axis units of this '
'scaling relation ({xr}).'.format(xl=x_lims.unit.to_string(),
xr=self.x_unit.to_string()))
elif x_lims is None and len(self._x_data) != 0:
max_x_ind = np.argmax(self._x_data)
min_x_ind = np.argmin(self._x_data)
x_lims = [0.9*(self._x_data[min_x_ind].value - self._x_err[min_x_ind].value),
1.1*(self._x_data[max_x_ind].value + self._x_err[max_x_ind].value)]
elif x_lims is None and len(self._x_data) == 0:
raise ValueError('There is no data available to infer suitable axis limits from, please pass x limits.')
# Setting up the matplotlib figure
fig = plt.figure(figsize=figsize)
fig.tight_layout()
ax = plt.gca()
# Setting the axis limits
ax.set_xlim(x_lims)
# Making the scale log if requested
if log_scale:
ax.set_xscale("log")
ax.set_yscale("log")
# Setup the aesthetics of the axis
ax.minorticks_on()
ax.tick_params(axis='both', direction='in', which='both', top=True, right=True)
# Plot the data with uncertainties, if any data is present in this scaling relation.
if len(self.x_data) != 0:
ax.errorbar(self._x_data.value, self._y_data.value, xerr=self._x_err.value, yerr=self._y_err.value,
fmt="x", color=data_colour, capsize=2)
# Need to randomly sample from the fitted model
num_rand = 10000
model_pars = np.repeat(self._fit_pars[..., None], num_rand, axis=1).T
model_par_errs = np.repeat(self._fit_par_errs[..., None], num_rand, axis=1).T
model_par_dists = np.random.normal(model_pars, model_par_errs)
model_x = np.linspace(*(x_lims / self.x_norm.value), 100)
model_xs = np.repeat(model_x[..., None], num_rand, axis=1)
upper = 50 + (conf_level / 2)
lower = 50 - (conf_level / 2)
model_realisations = self._model_func(model_xs, *model_par_dists.T) * self._y_norm
model_mean = np.mean(model_realisations, axis=1)
model_lower = np.percentile(model_realisations, lower, axis=1)
model_upper = np.percentile(model_realisations, upper, axis=1)
# I want the name of the function to include in labels and titles, but if its one defined in XGA then
# I can grab the publication version of the name - it'll be prettier
mod_name = self._model_func.__name__
for m_name in MODEL_PUBLICATION_NAMES:
mod_name = mod_name.replace(m_name, MODEL_PUBLICATION_NAMES[m_name])
relation_label = " ".join([self._author, self._year, '-', mod_name,
"- {cf}% Confidence".format(cf=conf_level)])
plt.plot(model_x * self._x_norm.value, self._model_func(model_x, *model_pars[0, :]) * self._y_norm.value,
color=model_colour, label=relation_label)
plt.plot(model_x * self._x_norm.value, model_upper, color=model_colour, linestyle="--")
plt.plot(model_x * self._x_norm.value, model_lower, color=model_colour, linestyle="--")
ax.fill_between(model_x * self._x_norm.value, model_lower, model_upper, where=model_upper >= model_lower,
facecolor=model_colour, alpha=0.6, interpolate=True)
# I can dynamically grab the units in LaTeX formatting from the Quantity objects (thank you astropy)
# However I've noticed specific instances where the units can be made prettier
# Parsing the astropy units so that if they are double height then the square brackets will adjust size
x_unit = r"$\left[" + self.x_unit.to_string("latex").strip("$") + r"\right]$"
y_unit = r"$\left[" + self.y_unit.to_string("latex").strip("$") + r"\right]$"
# Dimensionless quantities can be fitted too, and this make the axis label look nicer by not having empty
# square brackets
if x_unit == r"$\left[\\mathrm{}\right]$":
x_unit = ''
if y_unit == r"$\left[\\mathrm{}\right]$":
y_unit = ''
# The scaling relation object knows what its x and y axes are called, though the user may pass
# their own if they wish
if custom_x_label is None:
plt.xlabel("{xn} {un}".format(xn=self._x_name, un=x_unit), fontsize=fontsize)
else:
plt.xlabel(custom_x_label, fontsize=fontsize)
if custom_y_label is None:
plt.ylabel("{yn} {un}".format(yn=self._y_name, un=y_unit), fontsize=fontsize)
else:
plt.ylabel(custom_y_label, fontsize=fontsize)
# The user can also pass a plot title, but if they don't then I construct one automatically
if plot_title is None and self._fit_method != 'unknown':
plot_title = 'Scaling Relation - {mod} fitted with {fm}'.format(mod=mod_name, fm=self._fit_method)
elif plot_title is None and self._fit_method == 'unknown':
plot_title = '{n} Scaling Relation'.format(n=self._name)
plt.title(plot_title, fontsize=13)
# Use the axis limits quite a lot in this next bit, so read them out into variables
x_axis_lims = ax.get_xlim()
y_axis_lims = ax.get_ylim()
# This dynamically changes how tick labels are formatted depending on the values displayed
if max(x_axis_lims) < 1000:
ax.xaxis.set_minor_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
ax.xaxis.set_major_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
if max(y_axis_lims) < 1000:
ax.yaxis.set_minor_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
ax.yaxis.set_major_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
# And this dynamically changes the grid depending on whether a whole order of magnitude is covered or not
# Though as I don't much like the look of the grid it is off by default, and users can enable it if they
# want to.
if grid_on and (max(x_axis_lims) / min(x_axis_lims)) < 10:
ax.grid(which='minor', axis='x', linestyle='dotted', color='grey')
elif grid_on:
ax.grid(which='major', axis='x', linestyle='dotted', color='grey')
else:
ax.grid(which='both', axis='both', b=False)
if grid_on and (max(y_axis_lims) / min(y_axis_lims)) < 10:
ax.grid(which='minor', axis='y', linestyle='dotted', color='grey')
elif grid_on:
ax.grid(which='major', axis='y', linestyle='dotted', color='grey')
else:
ax.grid(which='both', axis='both', b=False)
# I change the lengths of the tick lines, to make it look nicer (imo)
ax.tick_params(length=7)
ax.tick_params(which='minor', length=3)
# Here we check whether the user has manually set any of the ticks to be displayed (major or minor, either axis)
if x_ticks is not None:
ax.set_xticks(x_ticks)
ax.set_xticklabels(x_ticks)
if x_minor_ticks is not None:
ax.set_xticks(x_minor_ticks, minor=True)
ax.set_xticklabels(x_minor_ticks, minor=True)
if y_ticks is not None:
ax.set_yticks(y_ticks)
ax.set_yticklabels(y_ticks)
if y_minor_ticks is not None:
ax.set_xticks(y_minor_ticks, minor=True)
ax.set_xticklabels(y_minor_ticks, minor=True)
plt.legend(loc="best", fontsize=legend_fontsize)
plt.tight_layout()
# If the user passed a save_path value, then we assume they want to save the figure
if save_path is not None:
plt.savefig(save_path)
plt.show()
def __add__(self, other):
to_combine = [self]
if type(other) == list:
to_combine += other
elif isinstance(other, ScalingRelation):
to_combine.append(other)
elif isinstance(other, AggregateScalingRelation):
to_combine += other.relations
else:
raise TypeError("You may only add ScalingRelations, or a list of ScalingRelations, to this object.")
return AggregateScalingRelation(to_combine)
class AggregateScalingRelation:
"""
This class is akin to the BaseAggregateProfile class, in that it is the result of a sum of ScalingRelation
objects. References to the component objects will be stored within the structure of this class, and it primarily
exists to allow plots with multiple relations to be generated.
"""
def __init__(self, relations: List[ScalingRelation]):
# There aren't specific classes for different types of relations, but I do need to check that whatever
# relations are being added together have the same x and y units
x_units = [sr.x_unit for sr in relations]
if len(set(x_units)) != 1:
raise UnitConversionError("All component scaling relations must have the same x-axis units.")
y_units = [sr.y_unit for sr in relations]
if len(set(y_units)) != 1:
raise UnitConversionError("All component scaling relations must have the same y-axis units.")
# Set some unit attributes for this class just so it takes one call to retrieve them
self._x_unit = relations[0].x_unit
self._y_unit = relations[0].y_unit
# Making sure that the axis units match is the key check before allowing this class to be instantiated, but
# I'm also going to go through and see if the names of the x and y axes are the same and issue warnings if
# not
x_names = [sr.x_name for sr in relations]
if len(set(x_names)) != 1:
self._x_name = " or ".join(list(set(x_names)))
warn('Not all of these ScalingRelations have the same x-axis names.')
else:
self._x_name = relations[0].x_name
y_names = [sr.y_name for sr in relations]
if len(set(y_names)) != 1:
self._y_name = " or ".join(list(set(y_names)))
warn('Not all of these ScalingRelations have the same y-axis names.')
else:
self._y_name = relations[0].y_name
# This stores the relations as an attribute
self._relations = relations
# The relations are the key attribute of this class, and the mechanism I've set up is that these objects
# are created by adding ScalingRelations together, as such there will be no setter to alter this after
# declaration
@property
def relations(self) -> List[ScalingRelation]:
"""
This returns the list of ScalingRelation instances that make up this aggregate scaling relation.
:return: A list of ScalingRelation instances.
:rtype: List[ScalingRelation]
"""
return self._relations
@property
def x_unit(self) -> Unit:
"""
The astropy unit object relevant to the x-axis of this relation.
:return: An Astropy Unit object.
:rtype: Unit
"""
return self._x_unit
@property
def y_unit(self) -> Unit:
"""
The astropy unit object relevant to the y-axis of this relation.
:return: An Astropy Unit object.
:rtype: Unit
"""
return self._y_unit
def view_corner(self, figsize: tuple = (10, 10), cust_par_names: List[str] = None,
contour_colours: List[str] = None, save_path: str = None):
"""
A corner plot viewing method that will combine chains from all the relations that make up this
aggregate scaling relation and display them using getdist.
:param tuple figsize: The size of the figure.
:param List[str] cust_par_names: A list of custom parameter names. If the names include LaTeX code do not
include $$ math environment symbols - you may also need to pass a string literal (e.g. r"\sigma"). Do
not include an entry for a scatter parameter.
:param List[str] contour_colours: Custom colours for the contours, there should be one colour
per scaling relation.
:param str save_path: The path where the figure produced by this method should be saved. Default is None, in
which case the figure will not be saved.
"""
# First off checking that every relation has chains, otherwise we can't do this
not_chains = [r.chains is None for r in self._relations]
# Which parameter names are the same, they should all be the same
par_names = list(set([",".join(r.par_names) for r in self._relations]))
# Checking which relations also have a scatter chain
not_scatter_chains = [r.scatter_chain is None for r in self._relations]
# Stopping this method if anything is amiss
if any(not_chains):
raise ValueError('Not all scaling relations have parameter chains, cannot view aggregate corner plot.')
elif len(par_names) != 1:
raise ValueError('Not all scaling relations have the same model parameter names, cannot view aggregate'
' corner plot.')
elif len(contour_colours) != len(self._relations):
raise ValueError("If you pass a list of contour colours, there must be one entry per scaling relation.")
# The number of non-scatter parameters in the scaling relation models
num_pars = len(self._relations[0].par_names)
samples = []
# Need to remove $ from the labels because getdist adds them itself
par_names = [n.replace('$', '') for n in self._relations[0].par_names]
# Setup the getdist sample objects
if not any(not_scatter_chains):
# For if there ARE scatter chains
if cust_par_names is not None and len(cust_par_names) == num_pars:
par_names = cust_par_names
par_names += [r'\sigma']
for rel in self._relations:
all_ch = np.hstack([rel.chains, rel.scatter_chain[..., None]])
samp_obj = MCSamples(samples=all_ch, label=rel.name, names=par_names, labels=par_names)
samples.append(samp_obj)
else:
if cust_par_names is not None and len(cust_par_names) == num_pars:
par_names = cust_par_names
for rel in self._relations:
# For if there aren't scatter chains
samp_obj = MCSamples(samples=rel.chains, label=rel.name, names=par_names, labels=par_names)
samples.append(samp_obj)
# And generate the triangle plot
g = plots.get_subplot_plotter(width_inch=figsize[0])
if contour_colours is not None:
g.triangle_plot(samples, filled=True, contour_colors=contour_colours)
else:
g.triangle_plot(samples, filled=True)
# If the user passed a save_path value, then we assume they want to save the figure
if save_path is not None:
plt.savefig(save_path)
plt.show()
def view(self, x_lims: Quantity = None, log_scale: bool = True, plot_title: str = None, figsize: tuple = (10, 8),
colour_list: list = None, grid_on: bool = False, conf_level: int = 90, show_data: bool = True,
fontsize: float = 15, legend_fontsize: float = 13, x_ticks: list = None, x_minor_ticks: list = None,
y_ticks: list = None, y_minor_ticks: list = None, save_path: str = None):
"""
A method that produces a high quality plot of the component scaling relations in this
AggregateScalingRelation.
:param Quantity x_lims: If not set, this method will attempt to take appropriate limits from the x-data
this relation is based upon, if that data is not available an error will be thrown.
:param bool log_scale: If true then the x and y axes of the plot will be log-scaled.
:param str plot_title: A custom title to be used for the plot, otherwise one will be generated automatically.
:param tuple figsize: A custom figure size for the plot, default is (8, 8).
:param list colour_list: A list of matplotlib colours to use as a custom colour cycle.
:param bool grid_on: If True then a grid will be included on the plot. Default is True.
:param int conf_level: The confidence level to use when plotting the model.
:param bool show_data: Controls whether data points are shown on the view, as it can quickly become
confusing with multiple relations on one axis.
:param float fontsize: The fontsize for axis labels.
:param float legend_fontsize: The fontsize for text in the legend.
:param list x_ticks: Customise which major x-axis ticks and labels are on the figure, default is None in which
case they are determined automatically.
:param list x_minor_ticks: Customise which minor x-axis ticks and labels are on the figure, default is
None in which case they are determined automatically.
:param list y_ticks: Customise which major y-axis ticks and labels are on the figure, default is None in which
case they are determined automatically.
:param list y_minor_ticks: Customise which minor y-axis ticks and labels are on the figure, default is
None in which case they are determined automatically.
:param str save_path: The path where the figure produced by this method should be saved. Default is None, in
which case the figure will not be saved.
"""
# Very large chunks of this are almost direct copies of the view method of ScalingRelation, but this
# was the easiest way of setting this up so I think the duplication is justified.
# Set up the colour cycle
if colour_list is None:
colour_list = PRETTY_COLOUR_CYCLE
new_col_cycle = cycler(color=colour_list)
# This part decides the x_lims of the plot, much the same as in the ScalingRelation view but it works
# on a combined sets of x-data or combined built in validity ranges, though user limits passed to view
# will still override everything else
comb_x_data = np.concatenate([sr.x_data for sr in self._relations])
# Combining any x_lims defined at init for these relations is slightly more complicated, as if they weren't
# defined then they will be None, so I have different behaviours dependent on how many sets of built in
# x_lims there are
existing_x_lims = [sr.x_lims for sr in self._relations if sr.x_lims is not None]
if len(existing_x_lims) == 0:
comb_x_lims = None
elif len(existing_x_lims) == 1:
comb_x_lims = existing_x_lims[0]
else:
comb_x_lims = np.concatenate(existing_x_lims)
if x_lims is not None and not x_lims.unit.is_equivalent(self.x_unit):
raise UnitConversionError('Limits on the x-axis ({xl}) must be convertible to the x-axis units of this '
'scaling relation ({xr}).'.format(xl=x_lims.unit.to_string(),
xr=self.x_unit.to_string()))
elif x_lims is not None and x_lims.unit.is_equivalent(self.x_unit):
x_lims = x_lims.to(self.x_unit).value
elif comb_x_lims is not None:
x_lims = np.array([comb_x_lims.value.min(), comb_x_lims.value.max()])
elif x_lims is None and len(comb_x_data) != 0:
max_x_ind = np.argmax(comb_x_data[:, 0])
min_x_ind = np.argmin(comb_x_data[:, 0])
x_lims = [0.9 * (comb_x_data[min_x_ind, 0].value - comb_x_data[min_x_ind, 1].value),
1.1 * (comb_x_data[max_x_ind, 0].value + comb_x_data[max_x_ind, 1].value)]
elif x_lims is None and len(comb_x_data) == 0:
raise ValueError('There is no data available to infer suitable axis limits from, please pass x limits.')
# Setting up the matplotlib figure
fig = plt.figure(figsize=figsize)
fig.tight_layout()
ax = plt.gca()
ax.set_prop_cycle(new_col_cycle)
# Setting the axis limits
ax.set_xlim(x_lims)
# Making the scale log if requested
if log_scale:
ax.set_xscale("log")
ax.set_yscale("log")
# Setup the aesthetics of the axis
ax.minorticks_on()
ax.tick_params(axis='both', direction='in', which='both', top=True, right=True)
for rel in self._relations:
# This is a horrifying bodge, but I do just want the colour out and I can't be bothered to figure out
# how to use the colour cycle object properly
if len(rel.x_data.value[:, 0]) == 0 or not show_data:
# Sets up a null error bar instance for the colour basically
d_out = ax.errorbar(None, None, xerr=None, yerr=None, fmt="x", capsize=2, label='')
else:
d_out = ax.errorbar(rel.x_data.value[:, 0], rel.y_data.value[:, 0], xerr=rel.x_data.value[:, 1],
yerr=rel.y_data.value[:, 1], fmt="x", capsize=2)
d_colour = d_out[0].get_color()
# Need to randomly sample from the fitted model
num_rand = 10000
model_pars = np.repeat(rel.pars[:, 0, None], num_rand, axis=1).T
model_par_errs = np.repeat(rel.pars[:, 1, None], num_rand, axis=1).T
model_par_dists = np.random.normal(model_pars, model_par_errs)
model_x = np.linspace(*(x_lims / rel.x_norm.value), 100)
model_xs = np.repeat(model_x[..., None], num_rand, axis=1)
upper = 50 + (conf_level / 2)
lower = 50 - (conf_level / 2)
model_realisations = rel.model_func(model_xs, *model_par_dists.T) * rel._y_norm
model_mean = np.mean(model_realisations, axis=1)
model_lower = np.percentile(model_realisations, lower, axis=1)
model_upper = np.percentile(model_realisations, upper, axis=1)
# I want the name of the function to include in labels and titles, but if its one defined in XGA then
# I can grab the publication version of the name - it'll be prettier
mod_name = rel.model_func.__name__
for m_name in MODEL_PUBLICATION_NAMES:
mod_name = mod_name.replace(m_name, MODEL_PUBLICATION_NAMES[m_name])
if rel.author != 'XGA':
relation_label = " ".join([rel.author, rel.year])
else:
relation_label = rel.name + ' Scaling Relation'
plt.plot(model_x * rel.x_norm.value, rel.model_func(model_x, *model_pars[0, :]) * rel.y_norm.value,
color=d_colour, label=relation_label)
plt.plot(model_x * rel.x_norm.value, model_upper, color=d_colour, linestyle="--")
plt.plot(model_x * rel.x_norm.value, model_lower, color=d_colour, linestyle="--")
ax.fill_between(model_x * rel.x_norm.value, model_lower, model_upper, where=model_upper >= model_lower,
facecolor=d_colour, alpha=0.6, interpolate=True)
# I can dynamically grab the units in LaTeX formatting from the Quantity objects (thank you astropy)
# However I've noticed specific instances where the units can be made prettier
# Parsing the astropy units so that if they are double height then the square brackets will adjust size
x_unit = r"$\left[" + self.x_unit.to_string("latex").strip("$") + r"\right]$"
y_unit = r"$\left[" + self.y_unit.to_string("latex").strip("$") + r"\right]$"
# Dimensionless quantities can be fitted too, and this make the axis label look nicer by not having empty
# square brackets
if x_unit == r"$\left[\\mathrm{}\right]$":
x_unit = ''
if y_unit == r"$\left[\\mathrm{}\right]$":
y_unit = ''
# The scaling relation object knows what its x and y axes are called
plt.xlabel("{xn} {un}".format(xn=self._x_name, un=x_unit), fontsize=fontsize)
plt.ylabel("{yn} {un}".format(yn=self._y_name, un=y_unit), fontsize=fontsize)
# The user can also pass a plot title, but if they don't then I construct one automatically
if plot_title is None:
plot_title = 'Scaling Relation Comparison - {c}% Confidence Limits'.format(c=conf_level)
plt.title(plot_title, fontsize=13)
# Use the axis limits quite a lot in this next bit, so read them out into variables
x_axis_lims = ax.get_xlim()
y_axis_lims = ax.get_ylim()
# This dynamically changes how tick labels are formatted depending on the values displayed
if max(x_axis_lims) < 1000:
ax.xaxis.set_minor_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
ax.xaxis.set_major_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
if max(y_axis_lims) < 1000:
ax.yaxis.set_minor_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
ax.yaxis.set_major_formatter(FuncFormatter(lambda inp, _: '{:g}'.format(inp)))
# And this dynamically changes the grid depending on whether a whole order of magnitude is covered or not
# Though as I don't much like the look of the grid it is off by default, and users can enable it if they
# want to.
if grid_on and (max(x_axis_lims) / min(x_axis_lims)) < 10:
ax.grid(which='minor', axis='x', linestyle='dotted', color='grey')
elif grid_on:
ax.grid(which='major', axis='x', linestyle='dotted', color='grey')
else:
ax.grid(which='both', axis='both', b=False)
if grid_on and (max(y_axis_lims) / min(y_axis_lims)) < 10:
ax.grid(which='minor', axis='y', linestyle='dotted', color='grey')
elif grid_on:
ax.grid(which='major', axis='y', linestyle='dotted', color='grey')
else:
ax.grid(which='both', axis='both', b=False)
# I change the lengths of the tick lines, to make it look nicer (imo)
ax.tick_params(length=7)
ax.tick_params(which='minor', length=3)
# Here we check whether the user has manually set any of the ticks to be displayed (major or minor, either axis)
if x_ticks is not None:
ax.set_xticks(x_ticks)
ax.set_xticklabels(x_ticks)
if x_minor_ticks is not None:
ax.set_xticks(x_minor_ticks, minor=True)
ax.set_xticklabels(x_minor_ticks, minor=True)
if y_ticks is not None:
ax.set_yticks(y_ticks)
ax.set_yticklabels(y_ticks)
if y_minor_ticks is not None:
ax.set_xticks(y_minor_ticks, minor=True)
ax.set_xticklabels(y_minor_ticks, minor=True)
plt.legend(loc="best", fontsize=legend_fontsize)
plt.tight_layout()
# If the user passed a save_path value, then we assume they want to save the figure
if save_path is not None:
plt.savefig(save_path)
plt.show()
def __len__(self) -> int:
return len(self._relations)
def __add__(self, other):
to_combine = self.relations
if type(other) == list:
to_combine += other
elif isinstance(other, ScalingRelation):
to_combine.append(other)
elif isinstance(other, AggregateScalingRelation):
to_combine += other.relations
else:
raise TypeError("You may only add ScalingRelations, AggregateScalingRelations, or a "
"list of ScalingRelations.")
return AggregateScalingRelation(to_combine)
| [
"matplotlib.pyplot.title",
"cycler.cycler",
"numpy.argmax",
"numpy.argmin",
"matplotlib.pyplot.figure",
"numpy.mean",
"getdist.MCSamples",
"numpy.random.normal",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tight_layout",
"inspect.signature",
"numpy.linspace",
"matplotlib.pyplot.subplots",
... | [((19367, 19377), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19375, 19377), True, 'from matplotlib import pyplot as plt\n'), ((21280, 21328), 'getdist.plots.get_subplot_plotter', 'plots.get_subplot_plotter', ([], {'width_inch': 'figsize[0]'}), '(width_inch=figsize[0])\n', (21305, 21328), False, 'from getdist import plots, MCSamples\n'), ((21672, 21682), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (21680, 21682), True, 'from matplotlib import pyplot as plt\n'), ((27829, 27856), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (27839, 27856), True, 'from matplotlib import pyplot as plt\n'), ((27897, 27906), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (27904, 27906), True, 'from matplotlib import pyplot as plt\n'), ((28838, 28882), 'numpy.random.normal', 'np.random.normal', (['model_pars', 'model_par_errs'], {}), '(model_pars, model_par_errs)\n', (28854, 28882), True, 'import numpy as np\n'), ((28902, 28949), 'numpy.linspace', 'np.linspace', (['*(x_lims / self.x_norm.value)', '(100)'], {}), '(*(x_lims / self.x_norm.value), 100)\n', (28913, 28949), True, 'import numpy as np\n'), ((28969, 29016), 'numpy.repeat', 'np.repeat', (['model_x[..., None]', 'num_rand'], {'axis': '(1)'}), '(model_x[..., None], num_rand, axis=1)\n', (28978, 29016), True, 'import numpy as np\n'), ((29207, 29242), 'numpy.mean', 'np.mean', (['model_realisations'], {'axis': '(1)'}), '(model_realisations, axis=1)\n', (29214, 29242), True, 'import numpy as np\n'), ((29265, 29313), 'numpy.percentile', 'np.percentile', (['model_realisations', 'lower'], {'axis': '(1)'}), '(model_realisations, lower, axis=1)\n', (29278, 29313), True, 'import numpy as np\n'), ((29336, 29384), 'numpy.percentile', 'np.percentile', (['model_realisations', 'upper'], {'axis': '(1)'}), '(model_realisations, upper, axis=1)\n', (29349, 29384), True, 'import numpy as np\n'), ((30086, 30177), 'matplotlib.pyplot.plot', 'plt.plot', (['(model_x * self._x_norm.value)', 'model_upper'], {'color': 'model_colour', 'linestyle': '"""--"""'}), "(model_x * self._x_norm.value, model_upper, color=model_colour,\n linestyle='--')\n", (30094, 30177), True, 'from matplotlib import pyplot as plt\n'), ((30182, 30273), 'matplotlib.pyplot.plot', 'plt.plot', (['(model_x * self._x_norm.value)', 'model_lower'], {'color': 'model_colour', 'linestyle': '"""--"""'}), "(model_x * self._x_norm.value, model_lower, color=model_colour,\n linestyle='--')\n", (30190, 30273), True, 'from matplotlib import pyplot as plt\n'), ((32190, 32224), 'matplotlib.pyplot.title', 'plt.title', (['plot_title'], {'fontsize': '(13)'}), '(plot_title, fontsize=13)\n', (32199, 32224), True, 'from matplotlib import pyplot as plt\n'), ((34613, 34661), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'fontsize': 'legend_fontsize'}), "(loc='best', fontsize=legend_fontsize)\n", (34623, 34661), True, 'from matplotlib import pyplot as plt\n'), ((34670, 34688), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (34686, 34688), True, 'from matplotlib import pyplot as plt\n'), ((34860, 34870), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (34868, 34870), True, 'from matplotlib import pyplot as plt\n'), ((41761, 41809), 'getdist.plots.get_subplot_plotter', 'plots.get_subplot_plotter', ([], {'width_inch': 'figsize[0]'}), '(width_inch=figsize[0])\n', (41786, 41809), False, 'from getdist import plots, MCSamples\n'), ((42168, 42178), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (42176, 42178), True, 'from matplotlib import pyplot as plt\n'), ((45044, 45069), 'cycler.cycler', 'cycler', ([], {'color': 'colour_list'}), '(color=colour_list)\n', (45050, 45069), False, 'from cycler import cycler\n'), ((45362, 45415), 'numpy.concatenate', 'np.concatenate', (['[sr.x_data for sr in self._relations]'], {}), '([sr.x_data for sr in self._relations])\n', (45376, 45415), True, 'import numpy as np\n'), ((47217, 47244), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (47227, 47244), True, 'from matplotlib import pyplot as plt\n'), ((47285, 47294), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (47292, 47294), True, 'from matplotlib import pyplot as plt\n'), ((51643, 51677), 'matplotlib.pyplot.title', 'plt.title', (['plot_title'], {'fontsize': '(13)'}), '(plot_title, fontsize=13)\n', (51652, 51677), True, 'from matplotlib import pyplot as plt\n'), ((54066, 54114), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'fontsize': 'legend_fontsize'}), "(loc='best', fontsize=legend_fontsize)\n", (54076, 54114), True, 'from matplotlib import pyplot as plt\n'), ((54123, 54141), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (54139, 54141), True, 'from matplotlib import pyplot as plt\n'), ((54313, 54323), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (54321, 54323), True, 'from matplotlib import pyplot as plt\n'), ((18550, 18616), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': 'num_ch', 'figsize': '(12, 2 * num_ch)', 'sharex': '"""col"""'}), "(nrows=num_ch, figsize=(12, 2 * num_ch), sharex='col')\n", (18562, 18616), True, 'from matplotlib import pyplot as plt\n'), ((18655, 18706), 'matplotlib.pyplot.subplots', 'plt.subplots', (['num_ch'], {'figsize': 'figsize', 'sharex': '"""col"""'}), "(num_ch, figsize=figsize, sharex='col')\n", (18667, 18706), True, 'from matplotlib import pyplot as plt\n'), ((20952, 21040), 'getdist.MCSamples', 'MCSamples', ([], {'samples': 'self._chains', 'label': 'self.name', 'names': 'par_names', 'labels': 'par_names'}), '(samples=self._chains, label=self.name, names=par_names, labels=\n par_names)\n', (20961, 21040), False, 'from getdist import plots, MCSamples\n'), ((21108, 21165), 'numpy.hstack', 'np.hstack', (['[self._chains, self._scatter_chain[..., None]]'], {}), '([self._chains, self._scatter_chain[..., None]])\n', (21117, 21165), True, 'import numpy as np\n'), ((21189, 21266), 'getdist.MCSamples', 'MCSamples', ([], {'samples': 'all_ch', 'label': 'self.name', 'names': 'par_names', 'labels': 'par_names'}), '(samples=all_ch, label=self.name, names=par_names, labels=par_names)\n', (21198, 21266), False, 'from getdist import plots, MCSamples\n'), ((21640, 21662), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (21651, 21662), True, 'from matplotlib import pyplot as plt\n'), ((28668, 28722), 'numpy.repeat', 'np.repeat', (['self._fit_pars[..., None]', 'num_rand'], {'axis': '(1)'}), '(self._fit_pars[..., None], num_rand, axis=1)\n', (28677, 28722), True, 'import numpy as np\n'), ((28750, 28808), 'numpy.repeat', 'np.repeat', (['self._fit_par_errs[..., None]', 'num_rand'], {'axis': '(1)'}), '(self._fit_par_errs[..., None], num_rand, axis=1)\n', (28759, 28808), True, 'import numpy as np\n'), ((31524, 31569), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['custom_x_label'], {'fontsize': 'fontsize'}), '(custom_x_label, fontsize=fontsize)\n', (31534, 31569), True, 'from matplotlib import pyplot as plt\n'), ((31722, 31767), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['custom_y_label'], {'fontsize': 'fontsize'}), '(custom_y_label, fontsize=fontsize)\n', (31732, 31767), True, 'from matplotlib import pyplot as plt\n'), ((34828, 34850), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (34839, 34850), True, 'from matplotlib import pyplot as plt\n'), ((36050, 36142), 'astropy.units.UnitConversionError', 'UnitConversionError', (['"""All component scaling relations must have the same x-axis units."""'], {}), "(\n 'All component scaling relations must have the same x-axis units.')\n", (36069, 36142), False, 'from astropy.units import Quantity, Unit, UnitConversionError\n'), ((36241, 36333), 'astropy.units.UnitConversionError', 'UnitConversionError', (['"""All component scaling relations must have the same y-axis units."""'], {}), "(\n 'All component scaling relations must have the same y-axis units.')\n", (36260, 36333), False, 'from astropy.units import Quantity, Unit, UnitConversionError\n'), ((36913, 36982), 'warnings.warn', 'warn', (['"""Not all of these ScalingRelations have the same x-axis names."""'], {}), "('Not all of these ScalingRelations have the same x-axis names.')\n", (36917, 36982), False, 'from warnings import warn\n'), ((37201, 37270), 'warnings.warn', 'warn', (['"""Not all of these ScalingRelations have the same y-axis names."""'], {}), "('Not all of these ScalingRelations have the same y-axis names.')\n", (37205, 37270), False, 'from warnings import warn\n'), ((42136, 42158), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (42147, 42158), True, 'from matplotlib import pyplot as plt\n'), ((48684, 48728), 'numpy.random.normal', 'np.random.normal', (['model_pars', 'model_par_errs'], {}), '(model_pars, model_par_errs)\n', (48700, 48728), True, 'import numpy as np\n'), ((48752, 48798), 'numpy.linspace', 'np.linspace', (['*(x_lims / rel.x_norm.value)', '(100)'], {}), '(*(x_lims / rel.x_norm.value), 100)\n', (48763, 48798), True, 'import numpy as np\n'), ((48822, 48869), 'numpy.repeat', 'np.repeat', (['model_x[..., None]', 'num_rand'], {'axis': '(1)'}), '(model_x[..., None], num_rand, axis=1)\n', (48831, 48869), True, 'import numpy as np\n'), ((49073, 49108), 'numpy.mean', 'np.mean', (['model_realisations'], {'axis': '(1)'}), '(model_realisations, axis=1)\n', (49080, 49108), True, 'import numpy as np\n'), ((49135, 49183), 'numpy.percentile', 'np.percentile', (['model_realisations', 'lower'], {'axis': '(1)'}), '(model_realisations, lower, axis=1)\n', (49148, 49183), True, 'import numpy as np\n'), ((49210, 49258), 'numpy.percentile', 'np.percentile', (['model_realisations', 'upper'], {'axis': '(1)'}), '(model_realisations, upper, axis=1)\n', (49223, 49258), True, 'import numpy as np\n'), ((50008, 50094), 'matplotlib.pyplot.plot', 'plt.plot', (['(model_x * rel.x_norm.value)', 'model_upper'], {'color': 'd_colour', 'linestyle': '"""--"""'}), "(model_x * rel.x_norm.value, model_upper, color=d_colour, linestyle\n ='--')\n", (50016, 50094), True, 'from matplotlib import pyplot as plt\n'), ((50102, 50188), 'matplotlib.pyplot.plot', 'plt.plot', (['(model_x * rel.x_norm.value)', 'model_lower'], {'color': 'd_colour', 'linestyle': '"""--"""'}), "(model_x * rel.x_norm.value, model_lower, color=d_colour, linestyle\n ='--')\n", (50110, 50188), True, 'from matplotlib import pyplot as plt\n'), ((54281, 54303), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (54292, 54303), True, 'from matplotlib import pyplot as plt\n'), ((1868, 1880), 'datetime.date.today', 'date.today', ([], {}), '()\n', (1878, 1880), False, 'from datetime import date\n'), ((7139, 7164), 'astropy.units.Quantity', 'Quantity', (['[]', 'self.x_unit'], {}), '([], self.x_unit)\n', (7147, 7164), False, 'from astropy.units import Quantity, Unit, UnitConversionError\n'), ((7676, 7701), 'astropy.units.Quantity', 'Quantity', (['[]', 'self.x_unit'], {}), '([], self.x_unit)\n', (7684, 7701), False, 'from astropy.units import Quantity, Unit, UnitConversionError\n'), ((8220, 8245), 'astropy.units.Quantity', 'Quantity', (['[]', 'self.y_unit'], {}), '([], self.y_unit)\n', (8228, 8245), False, 'from astropy.units import Quantity, Unit, UnitConversionError\n'), ((8757, 8782), 'astropy.units.Quantity', 'Quantity', (['[]', 'self.y_unit'], {}), '([], self.y_unit)\n', (8765, 8782), False, 'from astropy.units import Quantity, Unit, UnitConversionError\n'), ((41129, 41182), 'numpy.hstack', 'np.hstack', (['[rel.chains, rel.scatter_chain[..., None]]'], {}), '([rel.chains, rel.scatter_chain[..., None]])\n', (41138, 41182), True, 'import numpy as np\n'), ((41210, 41286), 'getdist.MCSamples', 'MCSamples', ([], {'samples': 'all_ch', 'label': 'rel.name', 'names': 'par_names', 'labels': 'par_names'}), '(samples=all_ch, label=rel.name, names=par_names, labels=par_names)\n', (41219, 41286), False, 'from getdist import plots, MCSamples\n'), ((41585, 41670), 'getdist.MCSamples', 'MCSamples', ([], {'samples': 'rel.chains', 'label': 'rel.name', 'names': 'par_names', 'labels': 'par_names'}), '(samples=rel.chains, label=rel.name, names=par_names, labels=par_names\n )\n', (41594, 41670), False, 'from getdist import plots, MCSamples\n'), ((45957, 45988), 'numpy.concatenate', 'np.concatenate', (['existing_x_lims'], {}), '(existing_x_lims)\n', (45971, 45988), True, 'import numpy as np\n'), ((48520, 48569), 'numpy.repeat', 'np.repeat', (['rel.pars[:, 0, None]', 'num_rand'], {'axis': '(1)'}), '(rel.pars[:, 0, None], num_rand, axis=1)\n', (48529, 48569), True, 'import numpy as np\n'), ((48601, 48650), 'numpy.repeat', 'np.repeat', (['rel.pars[:, 1, None]', 'num_rand'], {'axis': '(1)'}), '(rel.pars[:, 1, None], num_rand, axis=1)\n', (48610, 48650), True, 'import numpy as np\n'), ((10961, 10996), 'inspect.signature', 'inspect.signature', (['self._model_func'], {}), '(self._model_func)\n', (10978, 10996), False, 'import inspect\n'), ((27346, 27369), 'numpy.argmax', 'np.argmax', (['self._x_data'], {}), '(self._x_data)\n', (27355, 27369), True, 'import numpy as np\n'), ((27394, 27417), 'numpy.argmin', 'np.argmin', (['self._x_data'], {}), '(self._x_data)\n', (27403, 27417), True, 'import numpy as np\n'), ((46711, 46739), 'numpy.argmax', 'np.argmax', (['comb_x_data[:, 0]'], {}), '(comb_x_data[:, 0])\n', (46720, 46739), True, 'import numpy as np\n'), ((46764, 46792), 'numpy.argmin', 'np.argmin', (['comb_x_data[:, 0]'], {}), '(comb_x_data[:, 0])\n', (46773, 46792), True, 'import numpy as np\n')] |
import numpy as np
from matplotlib import pyplot as plt
def plot_spectrum(x: np.ndarray, eps: float = 1e-7):
assert len(x.shape) == 1
x_fft = np.fft.fft(x)
x_fft_abs = np.abs(x_fft)
x_fft_angle = np.angle(x_fft)
f_dig = np.linspace(-np.pi, np.pi, x.shape[0])
plt.subplot(2, 1, 1)
plt.plot(f_dig, 10 * np.log10(x_fft_abs + eps))
plt.ylabel("dB")
plt.grid()
plt.subplot(2, 1, 2)
plt.plot(f_dig, x_fft_angle)
plt.grid()
plt.show()
| [
"matplotlib.pyplot.subplot",
"numpy.abs",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.fft.fft",
"numpy.angle",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"numpy.log10",
"matplotlib.pyplot.grid"
] | [((152, 165), 'numpy.fft.fft', 'np.fft.fft', (['x'], {}), '(x)\n', (162, 165), True, 'import numpy as np\n'), ((182, 195), 'numpy.abs', 'np.abs', (['x_fft'], {}), '(x_fft)\n', (188, 195), True, 'import numpy as np\n'), ((214, 229), 'numpy.angle', 'np.angle', (['x_fft'], {}), '(x_fft)\n', (222, 229), True, 'import numpy as np\n'), ((242, 280), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', 'x.shape[0]'], {}), '(-np.pi, np.pi, x.shape[0])\n', (253, 280), True, 'import numpy as np\n'), ((285, 305), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (296, 305), True, 'from matplotlib import pyplot as plt\n'), ((362, 378), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""dB"""'], {}), "('dB')\n", (372, 378), True, 'from matplotlib import pyplot as plt\n'), ((383, 393), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (391, 393), True, 'from matplotlib import pyplot as plt\n'), ((398, 418), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (409, 418), True, 'from matplotlib import pyplot as plt\n'), ((423, 451), 'matplotlib.pyplot.plot', 'plt.plot', (['f_dig', 'x_fft_angle'], {}), '(f_dig, x_fft_angle)\n', (431, 451), True, 'from matplotlib import pyplot as plt\n'), ((456, 466), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (464, 466), True, 'from matplotlib import pyplot as plt\n'), ((471, 481), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (479, 481), True, 'from matplotlib import pyplot as plt\n'), ((331, 356), 'numpy.log10', 'np.log10', (['(x_fft_abs + eps)'], {}), '(x_fft_abs + eps)\n', (339, 356), True, 'import numpy as np\n')] |
import os
from collections import OrderedDict
import pymatgen as pmg
from pymatgen.core import Specie, Element, Structure
from pymatgen.core.periodic_table import _pt_data as periodic_table
import numpy as np
from .core import LammpsBox, LammpsPotentials
class LammpsInput:
def __init__(self, lammps_script, lammps_data, additional_files=None):
self.lammps_data = lammps_data
self.lammps_script = lammps_script
self.additional_files = additional_files or []
def write_input(self, output_dir, input_filename="lammps.in", make_dir=True):
if make_dir and not os.path.exists(output_dir):
os.makedirs(output_dir)
self.lammps_data.write_file(os.path.join(output_dir, self.lammps_script['read_data']))
self.lammps_script.write_file(os.path.join(output_dir, input_filename))
for file_buffer, filename in self.additional_files:
with open(os.path.join(output_dir, filename)) as f:
f.write(file_buffer)
class LammpsScript(OrderedDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __str__(self):
lines = ""
for k1, v1 in self.items():
if isinstance(v1, dict):
v1 = v1.values()
if isinstance(v1, list):
for x in v1:
lines = "".join([lines, "{} ".format(k1)])
lines = "".join([lines, str(x), os.linesep])
else:
lines = "".join([lines, "{} ".format(k1)])
lines = "".join([lines, " {}{}".format(str(v1), os.linesep)])
return lines
@property
def log_filename(self):
log = self.get('log', 'log.lammps')
if log is None:
log = "log.lammps"
elif isinstance(log, (list, tuple)):
log = log[-1]
return str(log).split(' ')[0]
@property
def data_filenames(self):
data = self.get('read_data', None)
if data is None:
return []
elif isinstance(data, (list, tuple)):
return [str(d).split()[0] for d in data]
else:
return [str(data).split()[0]]
@property
def dump_filename(self):
dump = self.get('dump', None)
if dump is None:
return None
elif isinstance(dump, (list, tuple)):
dump = log[-1]
dump = str(dump).split()
if len(dump) < 4:
raise ValueError('Invalid dump command: %s' % dump)
return dump[4]
def write_file(self, filename):
with open(filename, 'w') as f:
f.write(str(self))
class LammpsData:
HEADER_TAGS = {
'atoms', 'bonds', 'angles', 'dihedrals', 'impropers',
'atom types', 'bond types', 'angle types', 'dihedral types', 'improper types',
'extra bond per atom', 'extra angle per atom', 'extra dihedral per atom', 'extra improper per atom', 'extra special per atom',
'ellipsoids', 'lines', 'triangles', 'bodies', 'xlo xhi', 'ylo yhi', 'zlo zhi', 'xy xz yz'
}
# Otherwise implied integer
FLOAT_HEADER_TAGS = {'xlo xhi', 'ylo yhi', 'zlo zhi', 'xy xz yz'}
REQUIRED_HEADER_TAGS = {'xlo xhi', 'ylo yhi', 'zlo zhi', 'atoms', 'atom types'}
REQUIRED_SECTION_TAGS = {'Atoms', 'Masses'}
CHECKED_SECTION_TAGS = {'Atoms', 'Pair Coeffs', 'PairIJ Coeffs', 'Bond Coeffs', 'Angle Coeffs', 'Dihedral Coeffs', 'Improper Coeffs'}
SECTIONS_TAGS = {
'Atoms', 'Velocities', 'Masses', 'Ellipsoids', 'Lines', 'Triangles', 'Bodies',
'Bonds', 'Angles', 'Dihedrals', 'Impropers',
'Pair Coeffs', 'PairIJ Coeffs', 'Bond Coeffs', 'Angle Coeffs', 'Dihedral Coeffs', 'Improper Coeffs',
'BondBond Coeffs', 'BondAngle Coeffs', 'MiddleBondTorsion Coeffs', 'EndBondTorsion Coeffs',
'AngleTorsion Coeffs', 'AngleAngleTorsion Coeffs', 'BondBond13 Coeffs', 'AngleAngle Coeffs'
}
def __init__(self, name, symbol_indicies, masses, atoms, lammps_box, potentials=None, velocities=None):
self.name = name
self.symbol_indicies = symbol_indicies
self.masses = masses
self.atoms = atoms
self.lammps_box = lammps_box
self.potentials = potentials
self.velocities = velocities
if self.potentials:
self.potentials.symbol_indicies = self.symbol_indicies
@classmethod
def from_structure(cls, structure, potentials=None, include_charge=False, include_velocities=False):
lammps_box, symmop = LammpsBox.from_lattice(structure.lattice)
name = 'pymatgen autogenerated data file'
symbol_indicies = {}
masses = {}
atoms = []
velocities = None
if include_velocities:
velocities = []
counter = 1
for atom in structure:
if atom.specie not in symbol_indicies:
symbol_indicies[atom.specie] = counter
counter += 1
if isinstance(atom.specie, Specie):
element = atom.specie.element
charge = atom.specie.oxi_state
elif isinstance(atom.specie, Element):
element = atom.specie
charge = 0.0
if atom.specie not in masses:
masses[atom.specie] = element.atomic_mass
if include_velocities:
velocity = atom.properties.get('velocity', [0, 0, 0])
rotation = pmg.SymmOp.from_rotation_and_translation(symmop.rotation_matrix)
velocities.append(rotation.operate_multi(velocity))
coords = symmop.operate_multi(atom.coords)
atoms.append([atom.specie, charge, coords])
return cls(name, symbol_indicies, masses, atoms, lammps_box,
potentials=potentials, velocities=velocities)
@classmethod
def _parse_data_file(cls, filename):
def is_header(line):
for header in cls.HEADER_TAGS:
if header in line:
data = line.replace(header, '').strip().split()
if header in cls.FLOAT_HEADER_TAGS:
value = list(map(float, data))
else:
value = int(data[0])
return header, value
return None
def is_section(line):
for section in cls.SECTIONS_TAGS:
if section in line:
return section
return None
def parseline(line):
line = line.strip()
comment = ''
if '#' in line:
comment_index = line.find('#')
comment = line[comment_index+1:].strip()
line = line[:comment_index]
return line, comment
def data_to_array(data):
if len(data) == 0:
return np.array([])
# either int or floats
is_integer = np.vectorize(lambda f:f.is_integer())
row_types = is_integer(data[0])
for row in data:
row_types = row_types * is_integer(row)
names = ['f%d' % i for i in range(len(row_types))]
formats = [np.int64 if _ else np.float64 for _ in row_types]
return np.rec.array(data, dtype={'names': names, 'formats': formats})
headers = {}
sections = {}
with open(filename) as f:
description = f.readline()
f.readline() # second line blank
in_header = True
current_section = [None, None, []]
for line in f:
line, comment = parseline(line)
if not line:
continue # Blank line or comment
if in_header:
header_found = is_header(line)
if header_found:
header, value = header_found
headers[header] = value
elif is_section(line):
in_header = False
current_section[0] = is_section(line)
current_section[1] = comment or None
current_section[2] = []
else:
raise ValueError('line: %s not recognized' % line)
elif is_section(line):
if current_section[0]:
section, check, data = current_section
sections[section] = {'data': data_to_array(data), 'check': check}
current_section[0] = is_section(line)
current_section[1] = comment or None
current_section[2] = []
else: # Reading data from section
current_section[2].append(tuple(map(float, line.split())))
if current_section[0]:
section, check, data = current_section
sections[section] = {'data': data_to_array(data), 'check': check}
return description, headers, sections
@classmethod
def _validate_data_file(cls, headers, sections):
for required_header_tag in cls.REQUIRED_HEADER_TAGS:
if required_header_tag not in headers:
return 'Required header tag %s not included' % required_header_tag
for required_section_tag in cls.REQUIRED_SECTION_TAGS:
if required_section_tag not in sections:
return 'Required section tag %s not included' % required_section_tag
# Obviously can do more checks
@classmethod
def from_file(cls, filename, atom_style=None):
description, headers, sections = cls._parse_data_file(filename)
errors = cls._validate_data_file(headers, sections)
if errors:
raise ValueError('data file is invalid: {}'.format(errors))
xlo, xhi = headers['xlo xhi']
ylo, yhi = headers['ylo yhi']
zlo, zhi = headers['zlo zhi']
xy, xz, yz = headers.get('xy xz yz', [0, 0, 0])
lammps_box = LammpsBox(xhi, yhi, zhi, xlo, ylo, zlo, xy, xz, yz)
# Guess symbol from closest atomic mass (yes not great for isotopes)
elements = np.array(
[tuple([Element(element).atomic_mass, Element(element)]) for element in periodic_table],
dtype={'names': ['mass', 'symbol'], 'formats': [np.float64, np.chararray]}
)
symbol_indicies = {}
index_symbols = {} # Makes element lookup quicker
masses = {}
for index, atomic_mass, in sections['Masses']['data']:
symbol = elements['symbol'][np.abs(elements['mass'] - atomic_mass).argmin()]
symbol_indicies[Element(symbol)] = index
index_symbols[index] = Element(symbol)
masses[Element(symbol)] = atomic_mass
# Default full format or use check format
atoms = []
sections['Atoms']['data'].sort(order='f0') # f0 is default name of first field
for atom in sections['Atoms']['data']:
if sections['Atoms'].get('check') == 'full':
atom_type, charge, *position = atom['f2'], atom['f3'], atom['f4'], atom['f5'], atom['f6']
else:
index, mol, atom_type, charge, *position = atom
element = index_symbols[atom_type]
atoms.append([element, charge, position])
velocities = None
if 'Velocities' in sections:
sections['Velocities']['data'].sort(order='f0') # f0 is default name of first field
velocities = [[vx, vy, vz] for vx, vy, vz in sections['Velocities']['data'][['f1', 'f2', 'f3']]]
# Get Potentials
# TODO only gets pair potentials for now and no reason to keep str
pair_potentials = {}
if 'PairIJ Coeffs' in sections:
for s1, s2, *parameters in sections['PairIJ Coeffs']['data']:
pair_potentials[(index_symbols[s1], index_symbols[s2])] = ' '.join(list(map(str, parameters)))
potentials = LammpsPotentials(pair_potentials, symbol_indicies)
return cls(description, symbol_indicies, masses, atoms, lammps_box,
potentials=potentials, velocities=velocities)
@property
def structure(self):
lattice = self.lammps_box.lattice
species = []
positions = []
for specie, charge, coords in self.atoms:
positions.append(coords)
if isinstance(specie, Specie):
symbol = specie.element.symbol
else:
symbol = specie.symbol
if charge:
species.append(Specie(symbol, charge))
else:
species.append(Element(symbol))
site_properties = {}
if self.velocities:
site_properties['velocities'] = self.velocities
return Structure(lattice, species, positions, coords_are_cartesian=True, site_properties=site_properties)
def __str__(self):
lammps_data_str = [
'{}\n'.format(self.name),
'{} atoms\n'.format(len(self.atoms)),
'{} atom types\n'.format(len(self.symbol_indicies)),
'{}\n'.format(str(self.lammps_box)),
'Masses\n',
'\n'.join(['{} {}'.format(self.symbol_indicies[specie], float(mass)) for specie, mass in self.masses.items()]) + '\n',
'Atoms\n',
'\n'.join(['{} {} {} {} {} {} {}'.format(i+1, 1, self.symbol_indicies[specie], charge, *coords) for i, (specie, charge, coords) in enumerate(self.atoms)]) + '\n',
]
if self.velocities:
lammps_data_str.extend([
'Velocities\n',
'\n'.join(['{} {} {} {}'.format(i+1, *velocity) for i, velocity in enumerate(self.velocities)]) + '\n'
])
if self.potentials:
lammps_data_str.append('{}\n'.format(str(self.potentials)))
return '\n'.join(lammps_data_str)
def write_file(self, filename):
with open(filename, 'w') as f:
f.write(str(self))
| [
"numpy.abs",
"os.makedirs",
"pymatgen.core.Element",
"pymatgen.core.Structure",
"os.path.exists",
"numpy.rec.array",
"numpy.array",
"os.path.join",
"pymatgen.core.Specie",
"pymatgen.SymmOp.from_rotation_and_translation"
] | [((12820, 12922), 'pymatgen.core.Structure', 'Structure', (['lattice', 'species', 'positions'], {'coords_are_cartesian': '(True)', 'site_properties': 'site_properties'}), '(lattice, species, positions, coords_are_cartesian=True,\n site_properties=site_properties)\n', (12829, 12922), False, 'from pymatgen.core import Specie, Element, Structure\n'), ((641, 664), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (652, 664), False, 'import os\n'), ((702, 759), 'os.path.join', 'os.path.join', (['output_dir', "self.lammps_script['read_data']"], {}), "(output_dir, self.lammps_script['read_data'])\n", (714, 759), False, 'import os\n'), ((799, 839), 'os.path.join', 'os.path.join', (['output_dir', 'input_filename'], {}), '(output_dir, input_filename)\n', (811, 839), False, 'import os\n'), ((7251, 7313), 'numpy.rec.array', 'np.rec.array', (['data'], {'dtype': "{'names': names, 'formats': formats}"}), "(data, dtype={'names': names, 'formats': formats})\n", (7263, 7313), True, 'import numpy as np\n'), ((10725, 10740), 'pymatgen.core.Element', 'Element', (['symbol'], {}), '(symbol)\n', (10732, 10740), False, 'from pymatgen.core import Specie, Element, Structure\n'), ((601, 627), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (615, 627), False, 'import os\n'), ((5438, 5502), 'pymatgen.SymmOp.from_rotation_and_translation', 'pmg.SymmOp.from_rotation_and_translation', (['symmop.rotation_matrix'], {}), '(symmop.rotation_matrix)\n', (5478, 5502), True, 'import pymatgen as pmg\n'), ((6854, 6866), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6862, 6866), True, 'import numpy as np\n'), ((10665, 10680), 'pymatgen.core.Element', 'Element', (['symbol'], {}), '(symbol)\n', (10672, 10680), False, 'from pymatgen.core import Specie, Element, Structure\n'), ((10760, 10775), 'pymatgen.core.Element', 'Element', (['symbol'], {}), '(symbol)\n', (10767, 10775), False, 'from pymatgen.core import Specie, Element, Structure\n'), ((924, 958), 'os.path.join', 'os.path.join', (['output_dir', 'filename'], {}), '(output_dir, filename)\n', (936, 958), False, 'import os\n'), ((12596, 12618), 'pymatgen.core.Specie', 'Specie', (['symbol', 'charge'], {}), '(symbol, charge)\n', (12602, 12618), False, 'from pymatgen.core import Specie, Element, Structure\n'), ((12669, 12684), 'pymatgen.core.Element', 'Element', (['symbol'], {}), '(symbol)\n', (12676, 12684), False, 'from pymatgen.core import Specie, Element, Structure\n'), ((10230, 10246), 'pymatgen.core.Element', 'Element', (['element'], {}), '(element)\n', (10237, 10246), False, 'from pymatgen.core import Specie, Element, Structure\n'), ((10588, 10626), 'numpy.abs', 'np.abs', (["(elements['mass'] - atomic_mass)"], {}), "(elements['mass'] - atomic_mass)\n", (10594, 10626), True, 'import numpy as np\n'), ((10200, 10216), 'pymatgen.core.Element', 'Element', (['element'], {}), '(element)\n', (10207, 10216), False, 'from pymatgen.core import Specie, Element, Structure\n')] |
import math
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
from cvcore.modeling.backbone.fpn import get_act, get_norm
from .build import SEM_SEG_HEAD_REGISTRY
__all__ = ["FPNHead"]
@SEM_SEG_HEAD_REGISTRY.register()
class FPNHead(nn.Module):
"""
A semantic segmentation head described in detail in the Panoptic Feature Pyramid Networks paper
(https://arxiv.org/abs/1901.02446). It takes FPN features as input and merges information from
all levels of the FPN into single output.
"""
def __init__(self, cfg, in_feature_strides, in_feature_channels):
super(FPNHead, self).__init__()
self.in_features = cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
feature_strides = {f: in_feature_strides[f] for f in self.in_features}
feature_channels = {f: in_feature_channels[f] for f in self.in_features}
num_classes = cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES
conv_dims = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM
self.common_stride = cfg.MODEL.SEM_SEG_HEAD.COMMON_STRIDE
norm = cfg.MODEL.SEM_SEG_HEAD.NORM
act = cfg.MODEL.SEM_SEG_HEAD.ACT
fuse_type = cfg.MODEL.SEM_SEG_HEAD.FUSE_TYPE
use_bias = norm == ""
self.scale_heads = []
for in_feature in self.in_features:
head_ops = []
head_length = max(
1, int(np.log2(feature_strides[in_feature]) - np.log2(self.common_stride))
)
for k in range(head_length):
conv = nn.Conv2d(
feature_channels[in_feature] if k == 0 else conv_dims, conv_dims,
kernel_size=3, stride=1, padding=1, bias=use_bias)
norm_layer = get_norm(norm, conv_dims)
act_layer = get_act(act)
head_ops.extend([conv, norm_layer, act_layer])
if feature_strides[in_feature] != self.common_stride:
head_ops.append(
nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False))
self.scale_heads.append(nn.Sequential(*head_ops))
self.add_module(in_feature, self.scale_heads[-1])
if fuse_type == "cat":
predictor_in_chans = conv_dims * len(self.in_features)
else:
predictor_in_chans = conv_dims
self.predictor = nn.Conv2d(predictor_in_chans, num_classes,
kernel_size=1, stride=1, padding=0)
self._fuse_type = fuse_type
def forward(self, features):
x = []
for i, f in enumerate(self.in_features):
x.append(self.scale_heads[i](features[f]))
if self._fuse_type == "cat":
x = torch.cat(x, 1)
elif self._fuse_type == "sum":
x = torch.stack(x, 0).sum(0)
x = self.predictor(x)
x = F.interpolate(x, scale_factor=self.common_stride, mode="bilinear", align_corners=False)
return x | [
"torch.stack",
"torch.nn.Sequential",
"numpy.log2",
"torch.nn.Conv2d",
"cvcore.modeling.backbone.fpn.get_act",
"torch.cat",
"torch.nn.Upsample",
"torch.nn.functional.interpolate",
"cvcore.modeling.backbone.fpn.get_norm"
] | [((2924, 3015), 'torch.nn.functional.interpolate', 'F.interpolate', (['x'], {'scale_factor': 'self.common_stride', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(x, scale_factor=self.common_stride, mode='bilinear',\n align_corners=False)\n", (2937, 3015), True, 'import torch.nn.functional as F\n'), ((2430, 2508), 'torch.nn.Conv2d', 'nn.Conv2d', (['predictor_in_chans', 'num_classes'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(predictor_in_chans, num_classes, kernel_size=1, stride=1, padding=0)\n', (2439, 2508), True, 'import torch.nn as nn\n'), ((2782, 2797), 'torch.cat', 'torch.cat', (['x', '(1)'], {}), '(x, 1)\n', (2791, 2797), False, 'import torch\n'), ((1564, 1694), 'torch.nn.Conv2d', 'nn.Conv2d', (['(feature_channels[in_feature] if k == 0 else conv_dims)', 'conv_dims'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': 'use_bias'}), '(feature_channels[in_feature] if k == 0 else conv_dims, conv_dims,\n kernel_size=3, stride=1, padding=1, bias=use_bias)\n', (1573, 1694), True, 'import torch.nn as nn\n'), ((1764, 1789), 'cvcore.modeling.backbone.fpn.get_norm', 'get_norm', (['norm', 'conv_dims'], {}), '(norm, conv_dims)\n', (1772, 1789), False, 'from cvcore.modeling.backbone.fpn import get_act, get_norm\n'), ((1819, 1831), 'cvcore.modeling.backbone.fpn.get_act', 'get_act', (['act'], {}), '(act)\n', (1826, 1831), False, 'from cvcore.modeling.backbone.fpn import get_act, get_norm\n'), ((2134, 2158), 'torch.nn.Sequential', 'nn.Sequential', (['*head_ops'], {}), '(*head_ops)\n', (2147, 2158), True, 'import torch.nn as nn\n'), ((1415, 1451), 'numpy.log2', 'np.log2', (['feature_strides[in_feature]'], {}), '(feature_strides[in_feature])\n', (1422, 1451), True, 'import numpy as np\n'), ((1454, 1481), 'numpy.log2', 'np.log2', (['self.common_stride'], {}), '(self.common_stride)\n', (1461, 1481), True, 'import numpy as np\n'), ((2030, 2095), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2)', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(scale_factor=2, mode='bilinear', align_corners=False)\n", (2041, 2095), True, 'import torch.nn as nn\n'), ((2855, 2872), 'torch.stack', 'torch.stack', (['x', '(0)'], {}), '(x, 0)\n', (2866, 2872), False, 'import torch\n')] |
import os
import json
import math
import random
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from .dataset_utils import listdir_nohidden, normalize_trajectory, random_rotation_augment
class ReplicaDataset(Dataset):
def __init__(
self,
data_dir,
split='train',
seq_len=10,
step=1,
img_res=64,
depth=True,
center='first',
normalize_rotation=True,
rot_aug=False,
single_sample_per_trajectory=False,
samples_per_epoch=10000,
**kwargs
):
self.episode_len = 100
self.data_dir = data_dir
self.split = split
self.datapath = os.path.join(self.data_dir, self.split)
self.seq_len = seq_len
self.img_res = img_res
self.depth = depth
self.center = center
self.normalize_rotation = normalize_rotation
self.seq_idxs = listdir_nohidden(self.datapath)
self.rot_aug = rot_aug
self.single_sample_per_trajectory = single_sample_per_trajectory
self.samples_per_epoch = samples_per_epoch
# step*seq_len < total_seq_len
step = min(step, self.episode_len / seq_len)
self.step = step
self.resize_transform_rgb = transforms.Compose([transforms.Resize(self.img_res), transforms.ToTensor()])
self.resize_transform_depth = transforms.Compose([transforms.Resize(self.img_res)])
def get_trajectory_Rt(self):
Rt = []
for idxstr in self.seq_idxs:
episode_Rt = []
episode_path = os.path.join(self.datapath, idxstr)
with open(os.path.join(episode_path, 'cameras.json'), 'r') as f:
cameras = json.load(f)
for i in range(0, self.episode_len):
episode_Rt.append(torch.Tensor(cameras[i]['Rt']))
episode_Rt = torch.stack(episode_Rt, dim=0)
trim = episode_Rt.shape[0] % (self.seq_len * self.step)
episode_Rt = episode_Rt[: episode_Rt.shape[0] - trim]
Rt.append(episode_Rt)
Rt = torch.stack(Rt, dim=0)
# this basically samples points at the stride length
Rt = Rt.view(-1, self.seq_len, self.step, 4, 4).permute(0, 2, 1, 3, 4).reshape(-1, self.seq_len, 4, 4)
if self.center is not None:
Rt = normalize_trajectory(Rt, center=self.center, normalize_rotation=self.normalize_rotation)
if self.single_sample_per_trajectory:
# randomly select a single point along each trajectory
selected_indices = torch.multinomial(torch.ones(Rt.shape[:2]), num_samples=1).squeeze()
bool_mask = torch.eye(self.seq_len)[selected_indices].bool()
Rt = Rt[bool_mask].unsqueeze(1)
if self.rot_aug:
for i in range(Rt.shape[0]):
Rt[i] = random_rotation_augment(Rt[i])
return Rt
def __len__(self):
if self.samples_per_epoch:
return self.samples_per_epoch
else:
trajectory_len = self.seq_len * self.step
n_val_trajectories = int(len(self.seq_idxs) * math.floor(self.episode_len / trajectory_len))
return n_val_trajectories
def __getitem__(self, idx):
random.seed()
trajectory_len = self.seq_len * self.step
if self.samples_per_epoch:
idx = random.randint(0, len(self.seq_idxs) - 1)
idxstr = self.seq_idxs[idx]
seq_start = random.randint(0, self.episode_len - trajectory_len)
else:
trajectories_per_episode = math.floor(self.episode_len / trajectory_len)
seq_idx = int(idx / trajectories_per_episode)
seq_idx = int(self.seq_idxs[seq_idx])
idxstr = str(seq_idx).zfill(2)
seq_start = (idx % trajectories_per_episode) * trajectory_len
seq_start = int(seq_start)
# Load cameras
episode_path = os.path.join(self.datapath, idxstr)
with open(os.path.join(episode_path, 'cameras.json'), 'r') as f:
cameras = json.load(f)
Rt = []
K = []
rgb = []
depth = []
sample_indices = list(range(seq_start, seq_start + (self.seq_len * self.step), self.step))
for idx, i in enumerate(sample_indices):
Rt.append(torch.Tensor(cameras[i]['Rt']))
K.append(torch.Tensor(cameras[i]['K']))
_rgb = os.path.join(episode_path, str(i).zfill(3) + '_rgb.png')
_rgb = self.resize_transform_rgb(Image.open(_rgb))
rgb.append(_rgb[:3, :, :])
if self.depth:
_depth = os.path.join(episode_path, str(i).zfill(3) + '_depth.tiff')
# We dont want to normalize depth values
_depth = self.resize_transform_depth(Image.open(_depth))
depth.append(torch.from_numpy(np.array(_depth)).unsqueeze(0))
rgb = torch.stack(rgb)
depth = torch.stack(depth).float()
K = torch.stack(K)
Rt = torch.stack(Rt)
Rt = Rt.unsqueeze(0) # add batch dimension
Rt = normalize_trajectory(Rt, center=self.center, normalize_rotation=self.normalize_rotation)
Rt = Rt[0] # remove batch dimension
if self.single_sample_per_trajectory:
selected_indices = torch.multinomial(torch.ones(Rt.shape[0]), num_samples=1).squeeze()
rgb = rgb[selected_indices].unsqueeze(0)
depth = depth[selected_indices].unsqueeze(0)
K = K[selected_indices].unsqueeze(0)
Rt = Rt[selected_indices].unsqueeze(0)
if self.rot_aug:
Rt = random_rotation_augment(Rt)
# Normalize K to img_res
K = K[:, :3, :3]
# https://codeyarns.com/tech/2015-09-08-how-to-compute-intrinsic-camera-matrix-for-a-camera.html
# images were rendered at 512x512 res
fx = 256.0 / np.tan(np.deg2rad(90.0) / 2)
fy = 256.0 / np.tan(np.deg2rad(90.0) / 2)
K[:, 0, 0] = K[:, 0, 0] * fx
K[:, 1, 1] = K[:, 1, 1] * fy
downsampling_ratio = self.img_res / 512
K[:, 0, 0] = K[:, 0, 0] * downsampling_ratio
K[:, 1, 1] = K[:, 1, 1] * downsampling_ratio
depth = depth * 1000 # recommended scaling from game engine units to real world units
# print('hi')
# print(depth.size())
if self.depth:
sample = {'rgb': rgb, 'depth': depth, 'K': K, 'Rt': Rt, 'scene_idx': idx}
else:
sample = {'rgb': rgb, 'K': K, 'Rt': Rt, 'scene_idx': idx}
return sample
| [
"torch.ones",
"json.load",
"torch.eye",
"random.randint",
"torch.stack",
"numpy.deg2rad",
"math.floor",
"torchvision.transforms.ToTensor",
"PIL.Image.open",
"torch.Tensor",
"random.seed",
"numpy.array",
"os.path.join",
"torchvision.transforms.Resize"
] | [((755, 794), 'os.path.join', 'os.path.join', (['self.data_dir', 'self.split'], {}), '(self.data_dir, self.split)\n', (767, 794), False, 'import os\n'), ((2157, 2179), 'torch.stack', 'torch.stack', (['Rt'], {'dim': '(0)'}), '(Rt, dim=0)\n', (2168, 2179), False, 'import torch\n'), ((3320, 3333), 'random.seed', 'random.seed', ([], {}), '()\n', (3331, 3333), False, 'import random\n'), ((4009, 4044), 'os.path.join', 'os.path.join', (['self.datapath', 'idxstr'], {}), '(self.datapath, idxstr)\n', (4021, 4044), False, 'import os\n'), ((4991, 5007), 'torch.stack', 'torch.stack', (['rgb'], {}), '(rgb)\n', (5002, 5007), False, 'import torch\n'), ((5063, 5077), 'torch.stack', 'torch.stack', (['K'], {}), '(K)\n', (5074, 5077), False, 'import torch\n'), ((5091, 5106), 'torch.stack', 'torch.stack', (['Rt'], {}), '(Rt)\n', (5102, 5106), False, 'import torch\n'), ((1642, 1677), 'os.path.join', 'os.path.join', (['self.datapath', 'idxstr'], {}), '(self.datapath, idxstr)\n', (1654, 1677), False, 'import os\n'), ((1943, 1973), 'torch.stack', 'torch.stack', (['episode_Rt'], {'dim': '(0)'}), '(episode_Rt, dim=0)\n', (1954, 1973), False, 'import torch\n'), ((3545, 3597), 'random.randint', 'random.randint', (['(0)', '(self.episode_len - trajectory_len)'], {}), '(0, self.episode_len - trajectory_len)\n', (3559, 3597), False, 'import random\n'), ((3651, 3696), 'math.floor', 'math.floor', (['(self.episode_len / trajectory_len)'], {}), '(self.episode_len / trajectory_len)\n', (3661, 3696), False, 'import math\n'), ((4140, 4152), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4149, 4152), False, 'import json\n'), ((1351, 1382), 'torchvision.transforms.Resize', 'transforms.Resize', (['self.img_res'], {}), '(self.img_res)\n', (1368, 1382), True, 'import torchvision.transforms as transforms\n'), ((1384, 1405), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1403, 1405), True, 'import torchvision.transforms as transforms\n'), ((1466, 1497), 'torchvision.transforms.Resize', 'transforms.Resize', (['self.img_res'], {}), '(self.img_res)\n', (1483, 1497), True, 'import torchvision.transforms as transforms\n'), ((1781, 1793), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1790, 1793), False, 'import json\n'), ((4063, 4105), 'os.path.join', 'os.path.join', (['episode_path', '"""cameras.json"""'], {}), "(episode_path, 'cameras.json')\n", (4075, 4105), False, 'import os\n'), ((4392, 4422), 'torch.Tensor', 'torch.Tensor', (["cameras[i]['Rt']"], {}), "(cameras[i]['Rt'])\n", (4404, 4422), False, 'import torch\n'), ((4445, 4474), 'torch.Tensor', 'torch.Tensor', (["cameras[i]['K']"], {}), "(cameras[i]['K'])\n", (4457, 4474), False, 'import torch\n'), ((4598, 4614), 'PIL.Image.open', 'Image.open', (['_rgb'], {}), '(_rgb)\n', (4608, 4614), False, 'from PIL import Image\n'), ((5024, 5042), 'torch.stack', 'torch.stack', (['depth'], {}), '(depth)\n', (5035, 5042), False, 'import torch\n'), ((1700, 1742), 'os.path.join', 'os.path.join', (['episode_path', '"""cameras.json"""'], {}), "(episode_path, 'cameras.json')\n", (1712, 1742), False, 'import os\n'), ((3194, 3239), 'math.floor', 'math.floor', (['(self.episode_len / trajectory_len)'], {}), '(self.episode_len / trajectory_len)\n', (3204, 3239), False, 'import math\n'), ((4878, 4896), 'PIL.Image.open', 'Image.open', (['_depth'], {}), '(_depth)\n', (4888, 4896), False, 'from PIL import Image\n'), ((5973, 5989), 'numpy.deg2rad', 'np.deg2rad', (['(90.0)'], {}), '(90.0)\n', (5983, 5989), True, 'import numpy as np\n'), ((6023, 6039), 'numpy.deg2rad', 'np.deg2rad', (['(90.0)'], {}), '(90.0)\n', (6033, 6039), True, 'import numpy as np\n'), ((1886, 1916), 'torch.Tensor', 'torch.Tensor', (["cameras[i]['Rt']"], {}), "(cameras[i]['Rt'])\n", (1898, 1916), False, 'import torch\n'), ((2659, 2683), 'torch.ones', 'torch.ones', (['Rt.shape[:2]'], {}), '(Rt.shape[:2])\n', (2669, 2683), False, 'import torch\n'), ((2734, 2757), 'torch.eye', 'torch.eye', (['self.seq_len'], {}), '(self.seq_len)\n', (2743, 2757), False, 'import torch\n'), ((5403, 5426), 'torch.ones', 'torch.ones', (['Rt.shape[0]'], {}), '(Rt.shape[0])\n', (5413, 5426), False, 'import torch\n'), ((4944, 4960), 'numpy.array', 'np.array', (['_depth'], {}), '(_depth)\n', (4952, 4960), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 16 16:40:55 2014
@author: michaelwalton
"""
import csv
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
# general simulator settings
expType = 1 #which input dataset to use
inhibFreq = 20.0 #frequency of LFP oscillation in the inhibitory pop (Hz)
fs = 1000.0 #sample rate in hz
oscInhib_weight = -0.25
addNoise = False
###############################################################################
# Pick a dataset
# As the project grows, this should be replaced by a line arg.
# to set a containing folder then run on the data in that dir
if (expType == 0):
train_conc_file = "data/Otrain_4Otest/train_c.csv"
train_actv_file = "data/Otrain_4Otest/train_a.csv"
test_conc_file = "data/Otrain_4Otest/test_c.csv"
test_actv_file = "data/Otrain_4Otest/test_a.csv"
elif (expType == 1):
train_conc_file = "data/Otrain_4OBGtest/train_c.csv"
train_actv_file = "data/Otrain_4OBGtest/train_a.csv"
test_conc_file = "data/Otrain_4OBGtest/test_c.csv"
test_actv_file = "data/Otrain_4OBGtest/test_a.csv"
else:
train_conc_file = "data/OBGtrain_4OBGtest/train_c.csv"
train_actv_file = "data/OBGtrain_4OBGtest/train_a.csv"
test_conc_file = "data/OBGtrain_4OBGtest/test_c.csv"
test_actv_file = "data/OBGtrain_4OBGtest/test_a.csv"
###############################################################################
#load data
reader = csv.reader(open(test_actv_file,"rb"), delimiter=",")
x = list(reader)
glomeruli = np.array(x).astype('float')
###############################################################################
#precompute a 20Hz sine wave over a 1 second period with ms resolution
#20Hz -> 50ms duty cycle
t = np.arange(0, glomeruli.shape[0], 1 / fs)
inhibLFP = np.sin(2 * np.pi * inhibFreq * t)
inhibLFP /= 2
inhibLFP += 0.5
if (addNoise):
randomRange = np.random.random_sample(fs * glomeruli.shape[0])
inhibLFP *= randomRange
glomeruliMS = np.transpose(np.repeat(glomeruli, 1000, axis=0))
###############################################################################
#Apply glomerular excitation and oscillating inhibition to mitrals
mitralArray = (glomeruliMS + (inhibLFP * oscInhib_weight)) / (1 + oscInhib_weight)
#mitral LIF model settings
T = mitralArray.shape[1] - 1 # total time to simulate (msec)
dt = 0.5 # simulation time step (msec)
time = np.arange(0, T+dt, dt) # time array
t_rest = 0 # initial refractory time
## LIF properties
Vm = np.zeros(len(time)) # potential (V) trace over time
Rm = 1 # resistance (kOhm)
Cm = 10 # capacitance (uF)
tau_m = Rm*Cm # time constant (msec)
tau_ref = 4 # refractory period (msec)
Vth = 1 # spike threshold (V)
V_spike = 1.0 # spike delta (V)
#compute mitral spike emissions for cell[0]
## iterate over each time step
for i, t in enumerate(time):
if t > t_rest:
I = mitralArray[0][t]
Vm[i] = Vm[i-1] + (-Vm[i-1] + I*Rm) / tau_m * dt
if Vm[i] >= Vth:
Vm[i] += V_spike
t_rest = t + tau_ref
###############################################################################
#PLOT DATA
#plot imported data and target
pl.figure(num=1, figsize=(10, 30))
plt.imshow(np.transpose(glomeruli))
#plt.colorbar()
plt.title('Glomeruli')
plt.ylabel('Activation')
plt.xlabel('Time')
plt.show()
#plot the inhibition signal
pl.figure(2)
plt.plot(inhibLFP[0:1000])
plt.title('Inhibitory Population LFP')
plt.ylabel('Activation')
plt.xlabel('Time')
plt.show()
pl.figure(2, figsize=(10, 30))
plt.imshow(mitralArray[:, 1000:1300])
#plt.colorbar()
plt.title('Mitral Cells')
plt.ylabel('Activation')
plt.xlabel('Time')
plt.show()
## plot membrane potential trace
pl.figure(3)
plt.plot(time, Vm)
plt.title('Mitral Cell [0] (LIF)')
plt.ylabel('Membrane Potential (V)')
plt.xlabel('Time (msec)')
plt.ylim([0,2])
plt.show() | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.random.random_sample",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.imshow",
"numpy.transpose",
"numpy.sin",
"numpy.arange",
"pylab.figure",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xla... | [((1761, 1801), 'numpy.arange', 'np.arange', (['(0)', 'glomeruli.shape[0]', '(1 / fs)'], {}), '(0, glomeruli.shape[0], 1 / fs)\n', (1770, 1801), True, 'import numpy as np\n'), ((1813, 1846), 'numpy.sin', 'np.sin', (['(2 * np.pi * inhibFreq * t)'], {}), '(2 * np.pi * inhibFreq * t)\n', (1819, 1846), True, 'import numpy as np\n'), ((2467, 2491), 'numpy.arange', 'np.arange', (['(0)', '(T + dt)', 'dt'], {}), '(0, T + dt, dt)\n', (2476, 2491), True, 'import numpy as np\n'), ((3388, 3422), 'pylab.figure', 'pl.figure', ([], {'num': '(1)', 'figsize': '(10, 30)'}), '(num=1, figsize=(10, 30))\n', (3397, 3422), True, 'import pylab as pl\n'), ((3475, 3497), 'matplotlib.pyplot.title', 'plt.title', (['"""Glomeruli"""'], {}), "('Glomeruli')\n", (3484, 3497), True, 'import matplotlib.pyplot as plt\n'), ((3498, 3522), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Activation"""'], {}), "('Activation')\n", (3508, 3522), True, 'import matplotlib.pyplot as plt\n'), ((3523, 3541), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (3533, 3541), True, 'import matplotlib.pyplot as plt\n'), ((3542, 3552), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3550, 3552), True, 'import matplotlib.pyplot as plt\n'), ((3582, 3594), 'pylab.figure', 'pl.figure', (['(2)'], {}), '(2)\n', (3591, 3594), True, 'import pylab as pl\n'), ((3595, 3621), 'matplotlib.pyplot.plot', 'plt.plot', (['inhibLFP[0:1000]'], {}), '(inhibLFP[0:1000])\n', (3603, 3621), True, 'import matplotlib.pyplot as plt\n'), ((3622, 3660), 'matplotlib.pyplot.title', 'plt.title', (['"""Inhibitory Population LFP"""'], {}), "('Inhibitory Population LFP')\n", (3631, 3660), True, 'import matplotlib.pyplot as plt\n'), ((3661, 3685), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Activation"""'], {}), "('Activation')\n", (3671, 3685), True, 'import matplotlib.pyplot as plt\n'), ((3686, 3704), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (3696, 3704), True, 'import matplotlib.pyplot as plt\n'), ((3705, 3715), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3713, 3715), True, 'import matplotlib.pyplot as plt\n'), ((3717, 3747), 'pylab.figure', 'pl.figure', (['(2)'], {'figsize': '(10, 30)'}), '(2, figsize=(10, 30))\n', (3726, 3747), True, 'import pylab as pl\n'), ((3748, 3785), 'matplotlib.pyplot.imshow', 'plt.imshow', (['mitralArray[:, 1000:1300]'], {}), '(mitralArray[:, 1000:1300])\n', (3758, 3785), True, 'import matplotlib.pyplot as plt\n'), ((3802, 3827), 'matplotlib.pyplot.title', 'plt.title', (['"""Mitral Cells"""'], {}), "('Mitral Cells')\n", (3811, 3827), True, 'import matplotlib.pyplot as plt\n'), ((3828, 3852), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Activation"""'], {}), "('Activation')\n", (3838, 3852), True, 'import matplotlib.pyplot as plt\n'), ((3853, 3871), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (3863, 3871), True, 'import matplotlib.pyplot as plt\n'), ((3872, 3882), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3880, 3882), True, 'import matplotlib.pyplot as plt\n'), ((3919, 3931), 'pylab.figure', 'pl.figure', (['(3)'], {}), '(3)\n', (3928, 3931), True, 'import pylab as pl\n'), ((3932, 3950), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'Vm'], {}), '(time, Vm)\n', (3940, 3950), True, 'import matplotlib.pyplot as plt\n'), ((3951, 3985), 'matplotlib.pyplot.title', 'plt.title', (['"""Mitral Cell [0] (LIF)"""'], {}), "('Mitral Cell [0] (LIF)')\n", (3960, 3985), True, 'import matplotlib.pyplot as plt\n'), ((3986, 4022), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Membrane Potential (V)"""'], {}), "('Membrane Potential (V)')\n", (3996, 4022), True, 'import matplotlib.pyplot as plt\n'), ((4023, 4048), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (msec)"""'], {}), "('Time (msec)')\n", (4033, 4048), True, 'import matplotlib.pyplot as plt\n'), ((4049, 4065), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 2]'], {}), '([0, 2])\n', (4057, 4065), True, 'import matplotlib.pyplot as plt\n'), ((4065, 4075), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4073, 4075), True, 'import matplotlib.pyplot as plt\n'), ((1911, 1959), 'numpy.random.random_sample', 'np.random.random_sample', (['(fs * glomeruli.shape[0])'], {}), '(fs * glomeruli.shape[0])\n', (1934, 1959), True, 'import numpy as np\n'), ((2020, 2054), 'numpy.repeat', 'np.repeat', (['glomeruli', '(1000)'], {'axis': '(0)'}), '(glomeruli, 1000, axis=0)\n', (2029, 2054), True, 'import numpy as np\n'), ((3434, 3457), 'numpy.transpose', 'np.transpose', (['glomeruli'], {}), '(glomeruli)\n', (3446, 3457), True, 'import numpy as np\n'), ((1552, 1563), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1560, 1563), True, 'import numpy as np\n')] |
"""
This module implements some of the spatial analysis techniques and processes used to
understand the patterns and relationships of geographic features.
This is mainly inspired by turf.js.
link: http://turfjs.org/
"""
import copy
import itertools
import math
from math import floor, sqrt
from typing import List, Optional, Union
import numpy as np
from geojson import Feature, FeatureCollection, LineString, MultiLineString
from geojson import Point as GeoPoint
from geojson import Polygon
from scipy.spatial import Delaunay, Voronoi
from shapely import geometry as geometry
from shapely.geometry import LineString as ShapelyLineString
from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape
from shapely.ops import cascaded_union, clip_by_rect, polygonize, unary_union
from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees
from turfpy.measurement import (
bbox,
bbox_polygon,
center,
centroid,
destination,
rhumb_bearing,
rhumb_destination,
rhumb_distance,
)
from turfpy.meta import coord_each, feature_each, flatten_each
from .dev_lib.earcut import earcut
from .dev_lib.spline import Spline
def circle(
center: Feature, radius: int, steps: int = 64, units: str = "km", **kwargs
) -> Polygon:
"""
Takes a Point and calculates the circle polygon given a radius in degrees,
radians, miles, or kilometers; and steps for precision.
:param center: A `Point` object representing center point of circle.
:param radius: An int representing radius of the circle.
:param steps: An int representing number of steps.
:param units: A string representing units of distance e.g. 'mi', 'km',
'deg' and 'rad'.
:param kwargs: A dict representing additional properties.
:return: A polygon feature object.
Example:
>>> from turfpy.transformation import circle
>>> from geojson import Feature, Point
>>> circle(center=Feature(geometry=Point((-75.343, 39.984))), radius=5, steps=10)
"""
coordinates = []
options = dict(steps=steps, units=units)
options.update(kwargs)
for i in range(steps):
bearing = i * -360 / steps
pt = destination(center, radius, bearing, options=options)
cords = pt.geometry.coordinates
coordinates.append(cords)
coordinates.append(coordinates[0])
return Feature(geometry=Polygon([coordinates], **kwargs))
def bbox_clip(geojson: Feature, bbox: list) -> Feature:
"""
Takes a Feature or geometry and a bbox and clips the feature to the bbox
:param geojson: Geojson data
:param bbox: Bounding Box which is used to clip the geojson
:return: Clipped geojson
Example:
>>> from turfpy.transformation import bbox_clip
>>> from geojson import Feature
>>> f = Feature(geometry={"coordinates": [[[2, 2], [8, 4],
>>> [12, 8], [3, 7], [2, 2]]], "type": "Polygon"})
>>> bbox = [0, 0, 10, 10]
>>> clip = bbox_clip(f, bbox)
"""
bb_polygon = bbox_polygon(bbox)
bb_clip = intersect([geojson, bb_polygon])
if not bb_clip:
return bb_clip
if "properties" in geojson:
bb_clip.properties = geojson["properties"]
return bb_clip
def intersect(features: Union[List[Feature], FeatureCollection]) -> Feature:
"""
Takes polygons and finds their intersection
:param features: List of features of Feature Collection
:return: Intersection Geojson Feature
Example:
>>> from turfpy.transformation import intersect
>>> from geojson import Feature
>>> f = Feature(geometry={"coordinates": [
>>> [[-122.801742, 45.48565], [-122.801742, 45.60491],
>>> [-122.584762, 45.60491], [-122.584762, 45.48565],
>>> [-122.801742, 45.48565]]], "type": "Polygon"})
>>> b = Feature(geometry={"coordinates": [
>>> [[-122.520217, 45.535693], [-122.64038, 45.553967],
>>> [-122.720031, 45.526554], [-122.669906, 45.507309],
>>> [-122.723464, 45.446643], [-122.532577, 45.408574],
>>> [-122.487258, 45.477466], [-122.520217, 45.535693]
>>> ]], "type": "Polygon"})
>>> inter = intersect([f, b])
"""
properties_list = []
if isinstance(features, list):
shapes = []
for f in features:
poly = get_geom(f)
s = shape(poly)
shapes.append(s)
if "properties" in f.keys():
properties_list.append(f["properties"])
else:
if "features" not in features.keys():
raise Exception("Invalid FeatureCollection")
if "properties" in features.keys():
properties_list.append(features["properties"])
shapes = []
for f in features["features"]:
poly = get_geom(f)
s = shape(poly)
shapes.append(s)
if "properties" in f.keys():
properties_list.append(f["properties"])
intersection = shapes[0]
for shape_value in shapes:
intersection = shape_value.intersection(intersection)
intersection = mapping(intersection)
if len(intersection["coordinates"]) == 0:
return None
properties = merge_dict(properties_list)
intersection_feature = Feature(geometry=intersection, properties=properties)
return intersection_feature
def bezier_spline(line: Feature, resolution=10000, sharpness=0.85) -> Feature:
"""
Takes a line and returns a curved version by applying a Bezier spline algorithm
:param line: LineString Feature which is used to draw the curve
:param resolution: time in milliseconds between points
:param sharpness: a measure of how curvy the path should be between splines
:return: Curve as LineString Feature
Example:
>>> from geojson import LineString, Feature
>>> from turfpy.transformation import bezier_spline
>>> ls = LineString([(-76.091308, 18.427501),
>>> (-76.695556, 18.729501),
>>> (-76.552734, 19.40443),
>>> (-74.61914, 19.134789),
>>> (-73.652343, 20.07657),
>>> (-73.157958, 20.210656)])
>>> f = Feature(geometry=ls)
>>> bezier_spline(f)
"""
coords = []
points = []
geom = get_geom(line)
for c in geom["coordinates"]:
points.append({"x": c[0], "y": c[1]})
spline = Spline(points_data=points, resolution=resolution, sharpness=sharpness)
i = 0
while i < spline.duration:
pos = spline.pos(i)
if floor(i / 100) % 2 == 0:
coords.append((pos["x"], pos["y"]))
i = i + 10
return Feature(geometry=LineString(coords))
def merge_dict(dicts: list):
super_dict: dict = {}
for d in dicts:
for k, v in d.items():
if k not in super_dict.keys():
super_dict[k] = v
else:
if isinstance(super_dict[k], list):
if v not in super_dict[k]:
super_dict[k].append(v)
else:
if super_dict[k] != v:
super_dict[k] = [super_dict[k], v]
return super_dict
def union(
features: Union[List[Feature], FeatureCollection]
) -> Union[Feature, FeatureCollection]:
"""
Given list of features or ``FeatureCollection`` return union of those.
:param features: A list of GeoJSON features or FeatureCollection.
:return: A GeoJSON Feature or FeatureCollection.
Example:
>>> from turfpy.transformation import union
>>> from geojson import Feature, Polygon, FeatureCollection
>>> f1 = Feature(geometry=Polygon([[
... [-82.574787, 35.594087],
... [-82.574787, 35.615581],
... [-82.545261, 35.615581],
... [-82.545261, 35.594087],
... [-82.574787, 35.594087]
... ]]), properties={"fill": "#00f"})
>>> f2 = Feature(geometry=Polygon([[
... [-82.560024, 35.585153],
... [-82.560024, 35.602602],
... [-82.52964, 35.602602],
... [-82.52964, 35.585153],
... [-82.560024, 35.585153]]]), properties={"fill": "#00f"})
>>> union(FeatureCollection([f1, f2], properties={"combine": "yes"}))
"""
shapes = []
properties_list = []
if isinstance(features, list):
for f in features:
if f.type != "Feature":
raise Exception("Not a valid feature")
geom = get_geom(f)
s = shape(geom)
shapes.append(s)
if "properties" in f.keys():
properties_list.append(f["properties"])
else:
if "features" not in features.keys():
raise Exception("Invalid FeatureCollection")
if "properties" in features.keys():
properties_list.append(features["properties"])
for f in features["features"]:
geom = get_geom(f)
s = shape(geom)
shapes.append(s)
if "properties" in f.keys():
properties_list.append(f["properties"])
result = cascaded_union(shapes)
result = mapping(result)
properties = merge_dict(properties_list)
if result["type"] == "GeometryCollection":
features = []
for geom in result["geometries"]:
features.append(Feature(geometry=geom))
return FeatureCollection(features, properties=properties)
return Feature(geometry=result, properties=properties)
def _alpha_shape(points, alpha):
"""
Compute the alpha shape (concave hull) of a set of points.
:param points: Iterable container of points.
:param alpha: alpha value to influence the gooeyness of the border. Smaller
numbers don't fall inward as much as larger numbers. Too large,
and you lose everything!
"""
if len(points) < 4:
# When you have a triangle, there is no sense in computing an alpha
# shape.
return geometry.MultiPoint(list(points)).convex_hull
def add_edge(edges, edge_points, coords, i, j):
"""Add a line between the i-th and j-th points, if not in the list already"""
if (i, j) in edges or (j, i) in edges:
# already added
return
edges.add((i, j))
edge_points.append(coords[[i, j]])
coords = np.array([point.coords[0] for point in points])
tri = Delaunay(coords)
edges = set()
edge_points = []
# loop over triangles:
# ia, ib, ic = indices of corner points of the triangle
for ia, ib, ic in tri.vertices:
pa = coords[ia]
pb = coords[ib]
pc = coords[ic]
# Lengths of sides of triangle
a = math.sqrt((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2)
b = math.sqrt((pb[0] - pc[0]) ** 2 + (pb[1] - pc[1]) ** 2)
c = math.sqrt((pc[0] - pa[0]) ** 2 + (pc[1] - pa[1]) ** 2)
# Semiperimeter of triangle
s = (a + b + c) / 2.0
# Area of triangle by Heron's formula
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
circum_r = a * b * c / (4.0 * area)
# Here's the radius filter.
# print circum_r
if circum_r < 1.0 / alpha:
add_edge(edges, edge_points, coords, ia, ib)
add_edge(edges, edge_points, coords, ib, ic)
add_edge(edges, edge_points, coords, ic, ia)
m = geometry.MultiLineString(edge_points)
triangles = list(polygonize(m))
return cascaded_union(triangles), edge_points
def get_points(features):
points = []
if "type" not in features.keys():
raise Exception("Invalid Feature")
if features["type"] == "Feature":
get_ext_points(geometry.shape(features["geometry"]), points)
else:
if "features" not in features.keys():
raise Exception("Invalid FeatureCollection")
for feature in features["features"]:
get_ext_points(geometry.shape(feature["geometry"]), points)
return points
def get_ext_points(geom, points):
if geom.type == "Point":
for p in geom.coords:
points.append(Point(p))
elif geom.type == "MultiPoint":
for p in geom.geoms:
points.append(p)
elif geom.type == "LineString":
for p in geom.coords:
points.append(Point(p))
elif geom.type == "MultiLineString":
for g in geom.geoms:
for p in g.coords:
points.append(Point(p))
elif geom.type == "Polygon":
for p in geom.exterior.coords:
points.append(Point(p))
elif geom.type == "MultiPolygon":
for g in geom.geoms:
for p in g.exterior.coords:
points.append(Point(p))
else:
raise Exception("Invalid Geometry")
def concave(features: Union[Feature, FeatureCollection], alpha=2):
"""Generate concave hull for the given feature or Feature Collection.
:param features: It can be a feature or Feature Collection
:param alpha: Alpha determines the shape of concave hull,
greater values will make shape more tighten
:return: Feature of concave hull polygon
Example:
>>> from turfpy.transformation import concave
>>> from geojson import FeatureCollection, Feature, Point
>>> f1 = Feature(geometry=Point((-63.601226, 44.642643)))
>>> f2 = Feature(geometry=Point((-63.591442, 44.651436)))
>>> f3 = Feature(geometry=Point((-63.580799, 44.648749)))
>>> f4 = Feature(geometry=Point((-63.573589, 44.641788)))
>>> f5 = Feature(geometry=Point((-63.587665, 44.64533)))
>>> f6 = Feature(geometry=Point((-63.595218, 44.64765)))
>>> fc = [f1, f2, f3, f4, f5, f6]
>>> concave(FeatureCollection(fc), alpha=100)
"""
points = get_points(features)
concave_hull, edges = _alpha_shape(points, alpha)
return Feature(geometry=mapping(concave_hull))
def convex(features: Union[Feature, FeatureCollection]):
"""Generate convex hull for the given feature or Feature Collection
:param features: It can be a feature or Feature Collection
:return: Feature of convex hull polygon
Example:
>>> from turfpy.transformation import convex
>>> from geojson import FeatureCollection, Feature, Point
>>> f1 = Feature(geometry=Point((10.195312, 43.755225)))
>>> f2 = Feature(geometry=Point((10.404052, 43.8424511)))
>>> f3 = Feature(geometry=Point((10.579833, 43.659924)))
>>> f4 = Feature(geometry=Point((10.360107, 43.516688)))
>>> f5 = Feature(geometry=Point((10.14038, 43.588348)))
>>> f6 = Feature(geometry=Point((10.195312, 43.755225)))
>>> fc = [f1, f2, f3, f4, f5, f6]
>>> convex(FeatureCollection(fc))
"""
points = get_points(features)
point_collection = geometry.MultiPoint(list(points))
return Feature(geometry=mapping(point_collection.convex_hull))
def dissolve(
features: Union[List[Feature], FeatureCollection], property_name: str = None
) -> FeatureCollection:
"""
Take FeatureCollection or list of features to dissolve based on
property_name provided.
:param features: A list of GeoJSON features or FeatureCollection.
:param property_name: Name of property based on which to dissolve.
:return: A GeoJSON Feature or FeatureCollection.
Example:
>>> from geojson import Polygon, Feature, FeatureCollection
>>> from turfpy.transformation import dissolve
>>> f1 = Feature(geometry=Polygon([[
>>> [0, 0],
>>> [0, 1],
>>> [1, 1],
>>> [1, 0],
>>> [0, 0]]]), properties={"combine": "yes", "fill": "#00f"})
>>> f2 = Feature(geometry=Polygon([[
>>> [0, -1],
>>> [0, 0],
>>> [1, 0],
>>> [1, -1],
>>> [0,-1]]]), properties={"combine": "yes"})
>>> f3 = Feature(geometry=Polygon([[
>>> [1,-1],
>>> [1, 0],
>>> [2, 0],
>>> [2, -1],
>>> [1, -1]]]), properties={"combine": "no"})
>>> dissolve(FeatureCollection([f1, f2, f3]), property_name='combine')
"""
if isinstance(features, list):
features = FeatureCollection(features)
if "features" not in features.keys():
raise Exception("Invalid FeatureCollection")
dissolve_feature_list = []
if property_name:
for k, g in itertools.groupby(
features["features"], key=lambda x: x["properties"].get(property_name)
):
fc = FeatureCollection(list(g))
# if "properties" in features.keys():
# fc['properties'] = features['properties']
result = union(fc)
if result["type"] == "FeatureCollection":
for f in result["features"]:
dissolve_feature_list.append(f)
else:
dissolve_feature_list.append(result)
else:
return union(features)
if "properties" in features.keys():
return FeatureCollection(dissolve_feature_list, properties=features["properties"])
else:
return FeatureCollection(dissolve_feature_list)
def difference(feature_1: Feature, feature_2: Feature) -> Feature:
"""
Find the difference between given two features.
:param feature_1: A GeoJSON feature
:param feature_2: A GeoJSON feature
:return: A GeoJSON feature
Example:
>>> from geojson import Polygon, Feature
>>> from turfpy.transformation import difference
>>> f1 = Feature(geometry=Polygon([[
>>> [128, -26],
>>> [141, -26],
>>> [141, -21],
>>> [128, -21],
>>> [128, -26]]]), properties={"combine": "yes", "fill": "#00f"})
>>> f2 = Feature(geometry=Polygon([[
>>> [126, -28],
>>> [140, -28],
>>> [140, -20],
>>> [126, -20],
>>> [126, -28]]]), properties={"combine": "yes"})
>>> difference(f1, f2)
"""
properties_list = []
if "properties" in feature_1.keys():
properties_list.append(feature_1["properties"])
if "properties" in feature_2.keys():
properties_list.append(feature_2["properties"])
shape_1 = shape(get_geom(feature_1))
shape_2 = shape(get_geom(feature_2))
difference_result = shape_1.difference(shape_2)
difference_result = mapping(difference_result)
if len(difference_result["coordinates"]) == 0:
return None
properties = merge_dict(properties_list)
difference_feature = Feature(geometry=difference_result, properties=properties)
return difference_feature
def transform_rotate(
feature: Union[List[Feature], FeatureCollection],
angle: float,
pivot: list = None,
mutate: bool = False,
):
"""
Rotates any geojson Feature or Geometry of a specified angle,
around its centroid or a given pivot
point; all rotations follow the right-hand rule.
:param feature: Geojson to be rotated.
:param angle: angle of rotation (along the vertical axis),
from North in decimal degrees, negative clockwise
:param pivot: point around which the rotation will be performed
:param mutate: allows GeoJSON input to be mutated
(significant performance increase if True)
:return: the rotated GeoJSON
Example :-
>>> from turfpy.transformation import transform_rotate
>>> from geojson import Polygon, Feature
>>> f = Feature(geometry=Polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]))
>>> pivot = [0, 25]
>>> transform_rotate(f, 10, pivot)
"""
if not feature:
raise Exception("geojson is required")
if angle == 0:
return feature
if not pivot:
pivot = centroid(feature)["geometry"]["coordinates"]
if not mutate:
feature = copy.deepcopy(feature)
def _callback_coord_each(
coord, coord_index, feature_index, multi_feature_index, geometry_index
):
nonlocal pivot, angle
initial_angle = rhumb_bearing(GeoPoint(pivot), GeoPoint(coord))
final_angle = initial_angle + angle
distance = rhumb_distance(GeoPoint(pivot), GeoPoint(coord))
new_coords = get_coord(rhumb_destination(GeoPoint(pivot), distance, final_angle))
coord[0] = new_coords[0]
coord[1] = new_coords[1]
coord_each(feature, _callback_coord_each)
return feature
def transform_translate(
feature: Union[List[Feature], FeatureCollection],
distance: float,
direction: float,
units: str = "km",
z_translation: float = 0,
mutate: bool = False,
):
"""
Moves any geojson Feature or Geometry
of a specified distance along a
Rhumb Line on the provided direction angle.
:param feature: Geojson data that is to be translated
:param distance: length of the motion;
negative values determine motion in opposite direction
:param direction: of the motion; angle
from North in decimal degrees, positive clockwise
:param units: units for the distance and z_translation
:param z_translation: length of the vertical motion, same unit of distance
:param mutate: allows GeoJSON input to be mutated
(significant performance increase if true)
:return: the translated GeoJSON
Example :-
>>> from turfpy.transformation import transform_translate
>>> from geojson import Polygon, Feature
>>> f = Feature(geometry=Polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]))
>>> transform_translate(f, 100, 35, mutate=True)
"""
if not feature:
raise Exception("geojson is required")
if not distance:
raise Exception("distance is required")
if distance == 0 and z_translation == 0:
return feature
if not direction:
raise Exception("direction is required")
if distance < 0:
distance = -distance
direction = direction + 180
if not mutate:
feature = copy.deepcopy(feature)
def _callback_coord_each(
coord, coord_index, feature_index, multi_feature_index, geometry_index
):
nonlocal distance, direction, units, z_translation
new_coords = get_coord(
rhumb_destination(GeoPoint(coord), distance, direction, {"units": units})
)
coord[0] = new_coords[0]
coord[1] = new_coords[1]
if z_translation and len(coord) == 3:
coord[2] += z_translation
coord_each(feature, _callback_coord_each)
return feature
def transform_scale(
features,
factor: float,
origin: Union[str, list] = "centroid",
mutate: bool = False,
):
"""
Scale a GeoJSON from a given
point by a factor of scaling
(ex: factor=2 would make the GeoJSON 200% larger).
If a FeatureCollection is provided, the origin
point will be calculated based on each individual Feature.
:param features: GeoJSON to be scaled
:param factor: of scaling, positive or negative values greater than 0
:param origin: Point from which the scaling will occur
(string options: sw/se/nw/ne/center/centroid)
:param mutate: allows GeoJSON input to be mutated
(significant performance increase if true)
:return: Scaled Geojson
Example :-
>>> from turfpy.transformation import transform_scale
>>> from geojson import Polygon, Feature
>>> f = Feature(geometry=Polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]))
>>> transform_scale(f, 3, origin=[0, 29])
"""
if not features:
raise Exception("geojson is required")
if not factor:
raise Exception("invalid factor")
if not mutate:
features = copy.deepcopy(features)
if features["type"] == "FeatureCollection":
def _callback_feature_each(feature, feature_index):
nonlocal factor, origin, features
features["features"][feature_index] = scale(feature, factor, origin)
feature_each(features, _callback_feature_each)
return features
return scale(features, factor, origin)
def scale(feature, factor, origin):
is_point = get_type(feature) == "Point"
origin = define_origin(feature, origin)
if factor == 1 or is_point:
return feature
def _callback_coord_each(
coord, coord_index, feature_index, multi_feature_index, geometry_index
):
nonlocal factor, origin
original_distance = rhumb_distance(GeoPoint(origin), GeoPoint(coord))
bearing = rhumb_bearing(GeoPoint(origin), GeoPoint(coord))
new_distance = original_distance * factor
new_coord = get_coord(rhumb_destination(GeoPoint(origin), new_distance, bearing))
coord[0] = new_coord[0]
coord[1] = new_coord[1]
if len(coord) == 3:
coord[2] = coord[2] * factor
coord_each(feature, _callback_coord_each)
return feature
def define_origin(geojson, origin):
if not origin:
origin = "centroid"
if isinstance(origin, list):
return get_coord(origin)
bb = bbox(geojson)
west = bb[0]
south = bb[1]
east = bb[2]
north = bb[3]
if (
origin == "sw"
or origin == "southwest"
or origin == "westsouth"
or origin == "bottomleft"
):
return [west, south]
elif (
origin == "se"
or origin == "southeast"
or origin == "eastsouth"
or origin == "bottomright"
):
return [east, south]
elif (
origin == "nw"
or origin == "northwest"
or origin == "westnorth"
or origin == "topleft"
):
return [west, north]
elif (
origin == "ne"
or origin == "northeast"
or origin == "eastnorth"
or origin == "topright"
):
return [east, north]
elif origin == "center":
return center(geojson)["geometry"]["coordinates"]
elif origin is None or origin == "centroid":
return centroid(geojson)["geometry"]["coordinates"]
else:
raise Exception("invalid origin")
def tesselate(poly: Feature) -> FeatureCollection:
"""Tesselates a Feature into a FeatureCollection of triangles using earcut.
:param poly: A GeoJSON feature ``class:geojson.Polygon``.
:return: A GeoJSON FeatureCollection of triangular polygons.
Example:
>>> from geojson import Feature
>>> from turfpy.transformation import tesselate
>>> polygon = Feature(geometry={"coordinates": [[[11, 0], [22, 4], [31, 0], [31, 11],
... [21, 15], [11, 11], [11, 0]]], "type": "Polygon"})
>>> tesselate(polygon)
"""
if (
poly["geometry"]["type"] != "Polygon"
and poly["geometry"]["type"] != "MultiPolygon"
):
raise ValueError("Geometry must be Polygon or MultiPolygon")
fc = FeatureCollection([])
if poly.geometry.type == "Polygon":
fc["features"] = __process_polygon(poly.geometry.coordinates)
else:
for co in poly.geometry.coordinates:
fc["features"].extend(__process_polygon(co))
return fc
def __process_polygon(coordinates):
data = __flatten_coords(coordinates)
dim = 2
result = earcut(data["vertices"], data["holes"], dim)
features = []
vertices = []
for i, val in enumerate(result):
index = val
vertices.append(
[data["vertices"][index * dim], data["vertices"][index * dim + 1]]
)
i = 0
while i < len(vertices):
coords = vertices[i : i + 3]
coords.append(vertices[i])
features.append(Feature(geometry={"coordinates": [coords], "type": "Polygon"}))
i += 3
return features
def __flatten_coords(data):
dim = len(data[0][0])
result = {"vertices": [], "holes": [], "dimensions": dim}
hole_index = 0
for i, val in enumerate(data):
for j, _ in enumerate(val):
for d in range(dim):
result["vertices"].append(data[i][j][d])
if i > 0:
hole_index += len(data[i - 1])
result["holes"].append(hole_index)
return result
def line_offset(geojson: Feature, distance: float, unit: str = "km") -> Feature:
"""
Takes a linestring or multilinestring and returns
a line at offset by the specified distance.
:param geojson: input GeoJSON
:param distance: distance to offset the line (can be of negative value)
:param unit: Units in which distance to be calculated, values can be 'deg', 'rad',
'mi', 'km', default is 'km'
:return: Line feature offset from the input line
Example:
>>> from geojson import MultiLineString, Feature
>>> from turfpy.transformation import line_offset
>>> ls = Feature(geometry=MultiLineString([
... [(3.75, 9.25), (-130.95, 1.52)],
... [(23.15, -34.25), (-1.35, -4.65), (3.45, 77.95)]
... ]))
>>> line_offset(ls, 2, unit='mi')
"""
if not geojson:
raise Exception("geojson is required")
if not distance:
raise Exception("distance is required")
type = get_type(geojson)
properties = geojson.get("properties", {})
if type == "LineString":
return line_offset_feature(geojson, distance, unit)
elif type == "MultiLineString":
coords = []
def callback_flatten_each(feature, feature_index, multi_feature_index):
nonlocal coords
coords.append(
line_offset_feature(feature, distance, unit).geometry.coordinates
)
return True
flatten_each(geojson, callback_flatten_each)
return Feature(geometry=MultiLineString(coords), properties=properties)
def line_offset_feature(line, distance, units):
segments = []
offset_degrees = length_to_degrees(distance, units)
coords = get_coords(line)
final_coords = []
for index, current_coords in enumerate(coords):
if index != len(coords) - 1:
segment = _process_segment(current_coords, coords[index + 1], offset_degrees)
segments.append(segment)
if index > 0:
seg2_coords = segments[index - 1]
intersects = _intersection(segment, seg2_coords)
if intersects:
seg2_coords[1] = intersects
segment[0] = intersects
final_coords.append(seg2_coords[0])
if index == len(coords) - 2:
final_coords.append(segment[0])
final_coords.append(segment[1])
if len(coords) == 2:
final_coords.append(segment[0])
final_coords.append(segment[1])
return Feature(
geometry=LineString(final_coords), properties=line.get("properties", {})
)
def _process_segment(point1, point2, offset):
L = sqrt(
(point1[0] - point2[0]) * (point1[0] - point2[0])
+ (point1[1] - point2[1]) * (point1[1] - point2[1])
)
out1x = point1[0] + offset * (point2[1] - point1[1]) / L
out2x = point2[0] + offset * (point2[1] - point1[1]) / L
out1y = point1[1] + offset * (point1[0] - point2[0]) / L
out2y = point2[1] + offset * (point1[0] - point2[0]) / L
return [[out1x, out1y], [out2x, out2y]]
def _intersection(a, b):
if _is_parallel(a, b):
return False
return _intersect_segments(a, b)
def _is_parallel(a, b):
r = _ab(a)
s = _ab(b)
return _cross_product(r, s) == 0
def _ab(segment):
start = segment[0]
end = segment[1]
return [end[0] - start[0], end[1] - start[1]]
def _cross_product(v1, v2):
return (v1[0] * v2[1]) - (v2[0] * v1[1])
def _intersect_segments(a, b):
p = a[0]
r = _ab(a)
q = b[0]
s = _ab(b)
cross = _cross_product(r, s)
qmp = _sub(q, p)
numerator = _cross_product(qmp, s)
t = numerator / cross
intersection = _add(p, _scalar_mult(t, r))
return intersection
def _add(v1, v2):
return [v1[0] + v2[0], v1[1] + v2[1]]
def _sub(v1, v2):
return [v1[0] - v2[0], v1[1] - v2[1]]
def _scalar_mult(s, v):
return [s * v[0], s * v[1]]
def voronoi(
points: Union[FeatureCollection, List], bbox: Optional[list] = None
) -> Feature:
"""Takes a FeatureCollection of points, and a bounding box,
and returns a FeatureCollection of Voronoi polygons.
:param points: To find the Voronoi polygons around. Points should be either
FeatureCollection of points or list of points.
:param bbox: A bounding box to clip.
:return: A GeoJSON Feature.
Example:
>>> from turfpy.transformation import voronoi
>>> points = [
... [-66.9703, 40.3183],
... [-63.7763, 40.4500],
... [-65.4196, 42.13985310302137],
... [-69.5813, 43.95405461286195],
... [-65.66337553550034, 55.97088945355232],
... [-60.280418548905, 56.240669185466146],
... [-68.5129561347689, 50.12984589640148],
... [-64.2393519226657, 59.66235385923687],
... ]
>>> bbox = [-70, 40, -60, 60]
>>> voronoi(points, bbox)
"""
if isinstance(points, FeatureCollection):
coords = []
for feature in points["features"]:
coords.append(feature["features"][0]["geometry"]["coordinates"])
points = np.array(coords)
elif isinstance(points, list):
points = np.array(points)
else:
raise ValueError(
"points should be either FeatureCollection of points of List of Points"
)
vor = Voronoi(points)
lines = [
ShapelyLineString(vor.vertices[line])
for line in vor.ridge_vertices
if -1 not in line
]
convex_hull = MultiPoint([Point(i) for i in points]).convex_hull.buffer(2)
result = MultiPolygon([poly.intersection(convex_hull) for poly in polygonize(lines)])
result = MultiPolygon(
[p for p in result] + [p for p in convex_hull.difference(unary_union(result))]
)
if bbox is not None:
w, s, e, n = bbox
cliped_result = clip_by_rect(result, w, s, e, n)
return Feature(geometry=cliped_result)
return Feature(geometry=result)
| [
"shapely.ops.unary_union",
"shapely.geometry.MultiLineString",
"turfpy.measurement.bbox_polygon",
"turfpy.helper.get_geom",
"scipy.spatial.Voronoi",
"turfpy.meta.flatten_each",
"turfpy.helper.get_coords",
"turfpy.helper.get_type",
"shapely.geometry.shape",
"scipy.spatial.Delaunay",
"geojson.Line... | [((3007, 3025), 'turfpy.measurement.bbox_polygon', 'bbox_polygon', (['bbox'], {}), '(bbox)\n', (3019, 3025), False, 'from turfpy.measurement import bbox, bbox_polygon, center, centroid, destination, rhumb_bearing, rhumb_destination, rhumb_distance\n'), ((5043, 5064), 'shapely.geometry.mapping', 'mapping', (['intersection'], {}), '(intersection)\n', (5050, 5064), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((5206, 5259), 'geojson.Feature', 'Feature', ([], {'geometry': 'intersection', 'properties': 'properties'}), '(geometry=intersection, properties=properties)\n', (5213, 5259), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((6255, 6269), 'turfpy.helper.get_geom', 'get_geom', (['line'], {}), '(line)\n', (6263, 6269), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((9155, 9177), 'shapely.ops.cascaded_union', 'cascaded_union', (['shapes'], {}), '(shapes)\n', (9169, 9177), False, 'from shapely.ops import cascaded_union, clip_by_rect, polygonize, unary_union\n'), ((9191, 9206), 'shapely.geometry.mapping', 'mapping', (['result'], {}), '(result)\n', (9198, 9206), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((9494, 9541), 'geojson.Feature', 'Feature', ([], {'geometry': 'result', 'properties': 'properties'}), '(geometry=result, properties=properties)\n', (9501, 9541), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((10385, 10432), 'numpy.array', 'np.array', (['[point.coords[0] for point in points]'], {}), '([point.coords[0] for point in points])\n', (10393, 10432), True, 'import numpy as np\n'), ((10444, 10460), 'scipy.spatial.Delaunay', 'Delaunay', (['coords'], {}), '(coords)\n', (10452, 10460), False, 'from scipy.spatial import Delaunay, Voronoi\n'), ((11429, 11466), 'shapely.geometry.MultiLineString', 'geometry.MultiLineString', (['edge_points'], {}), '(edge_points)\n', (11453, 11466), True, 'from shapely import geometry as geometry\n'), ((18249, 18275), 'shapely.geometry.mapping', 'mapping', (['difference_result'], {}), '(difference_result)\n', (18256, 18275), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((18420, 18478), 'geojson.Feature', 'Feature', ([], {'geometry': 'difference_result', 'properties': 'properties'}), '(geometry=difference_result, properties=properties)\n', (18427, 18478), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((20208, 20249), 'turfpy.meta.coord_each', 'coord_each', (['feature', '_callback_coord_each'], {}), '(feature, _callback_coord_each)\n', (20218, 20249), False, 'from turfpy.meta import coord_each, feature_each, flatten_each\n'), ((22300, 22341), 'turfpy.meta.coord_each', 'coord_each', (['feature', '_callback_coord_each'], {}), '(feature, _callback_coord_each)\n', (22310, 22341), False, 'from turfpy.meta import coord_each, feature_each, flatten_each\n'), ((24653, 24694), 'turfpy.meta.coord_each', 'coord_each', (['feature', '_callback_coord_each'], {}), '(feature, _callback_coord_each)\n', (24663, 24694), False, 'from turfpy.meta import coord_each, feature_each, flatten_each\n'), ((24877, 24890), 'turfpy.measurement.bbox', 'bbox', (['geojson'], {}), '(geojson)\n', (24881, 24890), False, 'from turfpy.measurement import bbox, bbox_polygon, center, centroid, destination, rhumb_bearing, rhumb_destination, rhumb_distance\n'), ((26628, 26649), 'geojson.FeatureCollection', 'FeatureCollection', (['[]'], {}), '([])\n', (26645, 26649), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((28857, 28874), 'turfpy.helper.get_type', 'get_type', (['geojson'], {}), '(geojson)\n', (28865, 28874), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((29547, 29581), 'turfpy.helper.length_to_degrees', 'length_to_degrees', (['distance', 'units'], {}), '(distance, units)\n', (29564, 29581), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((29595, 29611), 'turfpy.helper.get_coords', 'get_coords', (['line'], {}), '(line)\n', (29605, 29611), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((30612, 30723), 'math.sqrt', 'sqrt', (['((point1[0] - point2[0]) * (point1[0] - point2[0]) + (point1[1] - point2[1]\n ) * (point1[1] - point2[1]))'], {}), '((point1[0] - point2[0]) * (point1[0] - point2[0]) + (point1[1] -\n point2[1]) * (point1[1] - point2[1]))\n', (30616, 30723), False, 'from math import floor, sqrt\n'), ((33242, 33257), 'scipy.spatial.Voronoi', 'Voronoi', (['points'], {}), '(points)\n', (33249, 33257), False, 'from scipy.spatial import Delaunay, Voronoi\n'), ((33845, 33869), 'geojson.Feature', 'Feature', ([], {'geometry': 'result'}), '(geometry=result)\n', (33852, 33869), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((2199, 2252), 'turfpy.measurement.destination', 'destination', (['center', 'radius', 'bearing'], {'options': 'options'}), '(center, radius, bearing, options=options)\n', (2210, 2252), False, 'from turfpy.measurement import bbox, bbox_polygon, center, centroid, destination, rhumb_bearing, rhumb_destination, rhumb_distance\n'), ((9431, 9481), 'geojson.FeatureCollection', 'FeatureCollection', (['features'], {'properties': 'properties'}), '(features, properties=properties)\n', (9448, 9481), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((10747, 10801), 'math.sqrt', 'math.sqrt', (['((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2)'], {}), '((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2)\n', (10756, 10801), False, 'import math\n'), ((10814, 10868), 'math.sqrt', 'math.sqrt', (['((pb[0] - pc[0]) ** 2 + (pb[1] - pc[1]) ** 2)'], {}), '((pb[0] - pc[0]) ** 2 + (pb[1] - pc[1]) ** 2)\n', (10823, 10868), False, 'import math\n'), ((10881, 10935), 'math.sqrt', 'math.sqrt', (['((pc[0] - pa[0]) ** 2 + (pc[1] - pa[1]) ** 2)'], {}), '((pc[0] - pa[0]) ** 2 + (pc[1] - pa[1]) ** 2)\n', (10890, 10935), False, 'import math\n'), ((11065, 11107), 'math.sqrt', 'math.sqrt', (['(s * (s - a) * (s - b) * (s - c))'], {}), '(s * (s - a) * (s - b) * (s - c))\n', (11074, 11107), False, 'import math\n'), ((11488, 11501), 'shapely.ops.polygonize', 'polygonize', (['m'], {}), '(m)\n', (11498, 11501), False, 'from shapely.ops import cascaded_union, clip_by_rect, polygonize, unary_union\n'), ((11514, 11539), 'shapely.ops.cascaded_union', 'cascaded_union', (['triangles'], {}), '(triangles)\n', (11528, 11539), False, 'from shapely.ops import cascaded_union, clip_by_rect, polygonize, unary_union\n'), ((16117, 16144), 'geojson.FeatureCollection', 'FeatureCollection', (['features'], {}), '(features)\n', (16134, 16144), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((16930, 17005), 'geojson.FeatureCollection', 'FeatureCollection', (['dissolve_feature_list'], {'properties': "features['properties']"}), "(dissolve_feature_list, properties=features['properties'])\n", (16947, 17005), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((17031, 17071), 'geojson.FeatureCollection', 'FeatureCollection', (['dissolve_feature_list'], {}), '(dissolve_feature_list)\n', (17048, 17071), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((18108, 18127), 'turfpy.helper.get_geom', 'get_geom', (['feature_1'], {}), '(feature_1)\n', (18116, 18127), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((18150, 18169), 'turfpy.helper.get_geom', 'get_geom', (['feature_2'], {}), '(feature_2)\n', (18158, 18169), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((19693, 19715), 'copy.deepcopy', 'copy.deepcopy', (['feature'], {}), '(feature)\n', (19706, 19715), False, 'import copy\n'), ((21818, 21840), 'copy.deepcopy', 'copy.deepcopy', (['feature'], {}), '(feature)\n', (21831, 21840), False, 'import copy\n'), ((23514, 23537), 'copy.deepcopy', 'copy.deepcopy', (['features'], {}), '(features)\n', (23527, 23537), False, 'import copy\n'), ((23784, 23830), 'turfpy.meta.feature_each', 'feature_each', (['features', '_callback_feature_each'], {}), '(features, _callback_feature_each)\n', (23796, 23830), False, 'from turfpy.meta import coord_each, feature_each, flatten_each\n'), ((23952, 23969), 'turfpy.helper.get_type', 'get_type', (['feature'], {}), '(feature)\n', (23960, 23969), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((24849, 24866), 'turfpy.helper.get_coord', 'get_coord', (['origin'], {}), '(origin)\n', (24858, 24866), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((33016, 33032), 'numpy.array', 'np.array', (['coords'], {}), '(coords)\n', (33024, 33032), True, 'import numpy as np\n'), ((33280, 33317), 'shapely.geometry.LineString', 'ShapelyLineString', (['vor.vertices[line]'], {}), '(vor.vertices[line])\n', (33297, 33317), True, 'from shapely.geometry import LineString as ShapelyLineString\n'), ((33754, 33786), 'shapely.ops.clip_by_rect', 'clip_by_rect', (['result', 'w', 's', 'e', 'n'], {}), '(result, w, s, e, n)\n', (33766, 33786), False, 'from shapely.ops import cascaded_union, clip_by_rect, polygonize, unary_union\n'), ((33802, 33833), 'geojson.Feature', 'Feature', ([], {'geometry': 'cliped_result'}), '(geometry=cliped_result)\n', (33809, 33833), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((2394, 2426), 'geojson.Polygon', 'Polygon', (['[coordinates]'], {}), '([coordinates], **kwargs)\n', (2401, 2426), False, 'from geojson import Polygon\n'), ((4268, 4279), 'turfpy.helper.get_geom', 'get_geom', (['f'], {}), '(f)\n', (4276, 4279), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((4296, 4307), 'shapely.geometry.shape', 'shape', (['poly'], {}), '(poly)\n', (4301, 4307), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((4732, 4743), 'turfpy.helper.get_geom', 'get_geom', (['f'], {}), '(f)\n', (4740, 4743), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((4760, 4771), 'shapely.geometry.shape', 'shape', (['poly'], {}), '(poly)\n', (4765, 4771), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((6638, 6656), 'geojson.LineString', 'LineString', (['coords'], {}), '(coords)\n', (6648, 6656), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((8532, 8543), 'turfpy.helper.get_geom', 'get_geom', (['f'], {}), '(f)\n', (8540, 8543), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((8560, 8571), 'shapely.geometry.shape', 'shape', (['geom'], {}), '(geom)\n', (8565, 8571), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((8974, 8985), 'turfpy.helper.get_geom', 'get_geom', (['f'], {}), '(f)\n', (8982, 8985), False, 'from turfpy.helper import get_coord, get_coords, get_geom, get_type, length_to_degrees\n'), ((9002, 9013), 'shapely.geometry.shape', 'shape', (['geom'], {}), '(geom)\n', (9007, 9013), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((11740, 11776), 'shapely.geometry.shape', 'geometry.shape', (["features['geometry']"], {}), "(features['geometry'])\n", (11754, 11776), True, 'from shapely import geometry as geometry\n'), ((13889, 13910), 'shapely.geometry.mapping', 'mapping', (['concave_hull'], {}), '(concave_hull)\n', (13896, 13910), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((14848, 14885), 'shapely.geometry.mapping', 'mapping', (['point_collection.convex_hull'], {}), '(point_collection.convex_hull)\n', (14855, 14885), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((19901, 19916), 'geojson.Point', 'GeoPoint', (['pivot'], {}), '(pivot)\n', (19909, 19916), True, 'from geojson import Point as GeoPoint\n'), ((19918, 19933), 'geojson.Point', 'GeoPoint', (['coord'], {}), '(coord)\n', (19926, 19933), True, 'from geojson import Point as GeoPoint\n'), ((20013, 20028), 'geojson.Point', 'GeoPoint', (['pivot'], {}), '(pivot)\n', (20021, 20028), True, 'from geojson import Point as GeoPoint\n'), ((20030, 20045), 'geojson.Point', 'GeoPoint', (['coord'], {}), '(coord)\n', (20038, 20045), True, 'from geojson import Point as GeoPoint\n'), ((24273, 24289), 'geojson.Point', 'GeoPoint', (['origin'], {}), '(origin)\n', (24281, 24289), True, 'from geojson import Point as GeoPoint\n'), ((24291, 24306), 'geojson.Point', 'GeoPoint', (['coord'], {}), '(coord)\n', (24299, 24306), True, 'from geojson import Point as GeoPoint\n'), ((24340, 24356), 'geojson.Point', 'GeoPoint', (['origin'], {}), '(origin)\n', (24348, 24356), True, 'from geojson import Point as GeoPoint\n'), ((24358, 24373), 'geojson.Point', 'GeoPoint', (['coord'], {}), '(coord)\n', (24366, 24373), True, 'from geojson import Point as GeoPoint\n'), ((27379, 27441), 'geojson.Feature', 'Feature', ([], {'geometry': "{'coordinates': [coords], 'type': 'Polygon'}"}), "(geometry={'coordinates': [coords], 'type': 'Polygon'})\n", (27386, 27441), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((29333, 29377), 'turfpy.meta.flatten_each', 'flatten_each', (['geojson', 'callback_flatten_each'], {}), '(geojson, callback_flatten_each)\n', (29345, 29377), False, 'from turfpy.meta import coord_each, feature_each, flatten_each\n'), ((30486, 30510), 'geojson.LineString', 'LineString', (['final_coords'], {}), '(final_coords)\n', (30496, 30510), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((33085, 33101), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (33093, 33101), True, 'import numpy as np\n'), ((6517, 6531), 'math.floor', 'floor', (['(i / 100)'], {}), '(i / 100)\n', (6522, 6531), False, 'from math import floor, sqrt\n'), ((9392, 9414), 'geojson.Feature', 'Feature', ([], {'geometry': 'geom'}), '(geometry=geom)\n', (9399, 9414), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((11972, 12007), 'shapely.geometry.shape', 'geometry.shape', (["feature['geometry']"], {}), "(feature['geometry'])\n", (11986, 12007), True, 'from shapely import geometry as geometry\n'), ((12156, 12164), 'shapely.geometry.Point', 'Point', (['p'], {}), '(p)\n', (12161, 12164), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((19610, 19627), 'turfpy.measurement.centroid', 'centroid', (['feature'], {}), '(feature)\n', (19618, 19627), False, 'from turfpy.measurement import bbox, bbox_polygon, center, centroid, destination, rhumb_bearing, rhumb_destination, rhumb_distance\n'), ((20096, 20111), 'geojson.Point', 'GeoPoint', (['pivot'], {}), '(pivot)\n', (20104, 20111), True, 'from geojson import Point as GeoPoint\n'), ((22079, 22094), 'geojson.Point', 'GeoPoint', (['coord'], {}), '(coord)\n', (22087, 22094), True, 'from geojson import Point as GeoPoint\n'), ((24473, 24489), 'geojson.Point', 'GeoPoint', (['origin'], {}), '(origin)\n', (24481, 24489), True, 'from geojson import Point as GeoPoint\n'), ((33539, 33556), 'shapely.ops.polygonize', 'polygonize', (['lines'], {}), '(lines)\n', (33549, 33556), False, 'from shapely.ops import cascaded_union, clip_by_rect, polygonize, unary_union\n'), ((29410, 29433), 'geojson.MultiLineString', 'MultiLineString', (['coords'], {}), '(coords)\n', (29425, 29433), False, 'from geojson import Feature, FeatureCollection, LineString, MultiLineString\n'), ((12352, 12360), 'shapely.geometry.Point', 'Point', (['p'], {}), '(p)\n', (12357, 12360), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((33420, 33428), 'shapely.geometry.Point', 'Point', (['i'], {}), '(i)\n', (33425, 33428), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((33651, 33670), 'shapely.ops.unary_union', 'unary_union', (['result'], {}), '(result)\n', (33662, 33670), False, 'from shapely.ops import cascaded_union, clip_by_rect, polygonize, unary_union\n'), ((12493, 12501), 'shapely.geometry.Point', 'Point', (['p'], {}), '(p)\n', (12498, 12501), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((12601, 12609), 'shapely.geometry.Point', 'Point', (['p'], {}), '(p)\n', (12606, 12609), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n'), ((25680, 25695), 'turfpy.measurement.center', 'center', (['geojson'], {}), '(geojson)\n', (25686, 25695), False, 'from turfpy.measurement import bbox, bbox_polygon, center, centroid, destination, rhumb_bearing, rhumb_destination, rhumb_distance\n'), ((25787, 25804), 'turfpy.measurement.centroid', 'centroid', (['geojson'], {}), '(geojson)\n', (25795, 25804), False, 'from turfpy.measurement import bbox, bbox_polygon, center, centroid, destination, rhumb_bearing, rhumb_destination, rhumb_distance\n'), ((12748, 12756), 'shapely.geometry.Point', 'Point', (['p'], {}), '(p)\n', (12753, 12756), False, 'from shapely.geometry import MultiPoint, MultiPolygon, Point, mapping, shape\n')] |
#########################################################################################################################
## Distribution code Version 1.0 -- 14/10/2021 by <NAME> Copyright 2021, University of Siegen
##
## The Code is created based on the method described in the following paper
## [1] "Deep Optimization Prior for THz Model Parameter Estimation", <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
## Winter Conference on Applications of Computer Vision (WACV) 2022.
##
## If you use this code in your scientific publication, please cite the mentioned paper.
## The code and the algorithm are for non-comercial use only.
##
## For other details, please visit website https://github.com/tak-wong/Deep-Optimization-Prior
#########################################################################################################################
import h5py
import numpy as np
import torch
from .dataset import *
class dataset_thz(dataset):
# -----------------------------------------------------------------------
def __init__(self, path_data, device, verbose = True):
super(dataset_thz, self).__init__(path_data, device, verbose)
# start of initialization
self.load_data()
if self.verbose:
print('dataset_thz.init')
# -----------------------------------------------------------------------
def load_data(self):
# load the data from file
with h5py.File(self.path_data, 'r') as hf:
self.data_np_complex = hf['data'][:]
self.z_np = np.array(hf['vector_z'][0]).astype(np.float)
self.NC = np.array(hf['NC'][0]).astype(np.int)[0]
self.NZ = np.array(hf['NZ'][0]).astype(np.int)[0]
self.NX = np.array(hf['NX'][0]).astype(np.int)[0]
self.NY = np.array(hf['NY'][0]).astype(np.int)[0]
self.INDEX_REAL = np.array(hf['INDEX_REAL'][0]).astype(np.int)[0]
self.INDEX_IMAG = np.array(hf['INDEX_IMAG'][0]).astype(np.int)[0]
self.OMEGA = np.array(hf['OMEGA'][0]).astype(np.float)[0]
self.ZERO_PADDING = np.array(hf['ZERO_PADDING'][0]).astype(np.float)[0]
self.MAX_VALUE = np.array(hf['MAX_VALUE'][0]).astype(np.float)[0]
hf.close()
self.data_np = np.ndarray(shape=(self.NC, self.NY, self.NX, self.NZ), dtype=float)
self.data_np[self.INDEX_REAL, :, :, :] = self.data_np_complex['real']
self.data_np[self.INDEX_IMAG, :, :, :] = self.data_np_complex['imag']
# load the data from numpy to pytorch tensor
self.data_tensor = torch.from_numpy(self.data_np).permute(0, 3, 2, 1).float().to(self.device).unsqueeze(0)
if self.verbose:
print("data_tensor shape: {}".format(self.data_tensor.shape))
# -----------------------------------------------------------------------
def __len__(self):
return 1
# -----------------------------------------------------------------------
def __getitem__(self, index):
return self.data_tensor
# -----------------------------------------------------------------------
def get_method(self):
return "complex_matrix"
# -----------------------------------------------------------------------
def get_shape(self):
return (self.NC, self.NZ, self.NX, self.NY)
| [
"numpy.array",
"h5py.File",
"numpy.ndarray",
"torch.from_numpy"
] | [((2323, 2390), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(self.NC, self.NY, self.NX, self.NZ)', 'dtype': 'float'}), '(shape=(self.NC, self.NY, self.NX, self.NZ), dtype=float)\n', (2333, 2390), True, 'import numpy as np\n'), ((1472, 1502), 'h5py.File', 'h5py.File', (['self.path_data', '"""r"""'], {}), "(self.path_data, 'r')\n", (1481, 1502), False, 'import h5py\n'), ((1583, 1610), 'numpy.array', 'np.array', (["hf['vector_z'][0]"], {}), "(hf['vector_z'][0])\n", (1591, 1610), True, 'import numpy as np\n'), ((1650, 1671), 'numpy.array', 'np.array', (["hf['NC'][0]"], {}), "(hf['NC'][0])\n", (1658, 1671), True, 'import numpy as np\n'), ((1712, 1733), 'numpy.array', 'np.array', (["hf['NZ'][0]"], {}), "(hf['NZ'][0])\n", (1720, 1733), True, 'import numpy as np\n'), ((1774, 1795), 'numpy.array', 'np.array', (["hf['NX'][0]"], {}), "(hf['NX'][0])\n", (1782, 1795), True, 'import numpy as np\n'), ((1836, 1857), 'numpy.array', 'np.array', (["hf['NY'][0]"], {}), "(hf['NY'][0])\n", (1844, 1857), True, 'import numpy as np\n'), ((1906, 1935), 'numpy.array', 'np.array', (["hf['INDEX_REAL'][0]"], {}), "(hf['INDEX_REAL'][0])\n", (1914, 1935), True, 'import numpy as np\n'), ((1984, 2013), 'numpy.array', 'np.array', (["hf['INDEX_IMAG'][0]"], {}), "(hf['INDEX_IMAG'][0])\n", (1992, 2013), True, 'import numpy as np\n'), ((2057, 2081), 'numpy.array', 'np.array', (["hf['OMEGA'][0]"], {}), "(hf['OMEGA'][0])\n", (2065, 2081), True, 'import numpy as np\n'), ((2134, 2165), 'numpy.array', 'np.array', (["hf['ZERO_PADDING'][0]"], {}), "(hf['ZERO_PADDING'][0])\n", (2142, 2165), True, 'import numpy as np\n'), ((2215, 2243), 'numpy.array', 'np.array', (["hf['MAX_VALUE'][0]"], {}), "(hf['MAX_VALUE'][0])\n", (2223, 2243), True, 'import numpy as np\n'), ((2640, 2670), 'torch.from_numpy', 'torch.from_numpy', (['self.data_np'], {}), '(self.data_np)\n', (2656, 2670), False, 'import torch\n')] |
#!/usr/bin/env python3
import numpy as np
RNNCell = __import__('0-rnn_cell').RNNCell
np.random.seed(0)
rnn_cell = RNNCell(10, 15, 5)
print("Wh:", rnn_cell.Wh)
print("Wy:", rnn_cell.Wy)
print("bh:", rnn_cell.bh)
print("by:", rnn_cell.by)
rnn_cell.bh = np.random.randn(1, 15)
rnn_cell.by = np.random.randn(1, 5)
h_prev = np.random.randn(8, 15)
x_t = np.random.randn(8, 10)
h, y = rnn_cell.forward(h_prev, x_t)
print(h.shape)
print(h)
print(y.shape)
print(y)
| [
"numpy.random.seed",
"numpy.random.randn"
] | [((87, 104), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (101, 104), True, 'import numpy as np\n'), ((253, 275), 'numpy.random.randn', 'np.random.randn', (['(1)', '(15)'], {}), '(1, 15)\n', (268, 275), True, 'import numpy as np\n'), ((290, 311), 'numpy.random.randn', 'np.random.randn', (['(1)', '(5)'], {}), '(1, 5)\n', (305, 311), True, 'import numpy as np\n'), ((321, 343), 'numpy.random.randn', 'np.random.randn', (['(8)', '(15)'], {}), '(8, 15)\n', (336, 343), True, 'import numpy as np\n'), ((350, 372), 'numpy.random.randn', 'np.random.randn', (['(8)', '(10)'], {}), '(8, 10)\n', (365, 372), True, 'import numpy as np\n')] |
"""
Файнтюнинг ruT5 на датасете, подготовленном в prepare_training_dataset.py
"""
import io
import re
import os
import tqdm
import torch
from transformers import T5ForConditionalGeneration, T5Tokenizer, T5Config
from transformers import TrainingArguments
from transformers import Trainer
from transformers import AdamW
from torch.utils.data import Dataset, DataLoader
import numpy as np
def ngrams(s, n):
return set(u''.join(z) for z in zip(*[s[i:] for i in range(n)]))
def jaccard(s1, s2, shingle_len):
shingles1 = ngrams(s1.lower(), shingle_len)
shingles2 = ngrams(s2.lower(), shingle_len)
return float(len(shingles1 & shingles2))/float(len(shingles1 | shingles2) + 1e-6)
class NP_Dataset(torch.utils.data.Dataset):
def __init__(self, device, tokenizer):
self.device = device
self.samples = []
self.max_len = 0
self.tokenizer = tokenizer
self.pad_token_id = tokenizer.pad_token_id
def append(self, input_text, output_text):
input_tokens = self.tokenizer(input_text, add_special_tokens=True).input_ids
output_tokens = self.tokenizer(output_text, add_special_tokens=True).input_ids
self.max_len = max(self.max_len, len(input_tokens), len(output_tokens))
self.samples.append((input_tokens, output_tokens))
def __len__(self):
return len(self.samples)
def pad_tokens(self, tokens):
return tokens + [self.pad_token_id] * (self.max_len - len(tokens))
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
tokens1, tokens2 = self.samples[idx]
z1 = torch.tensor(self.pad_tokens(tokens1))
z2 = torch.tensor(self.pad_tokens(tokens2))
return {'input_ids': z1, 'labels': z2}
def load_samples(dataset_path, device, tokenizer, computed_params):
train_samples = NP_Dataset(device, tokenizer)
eval_samples = NP_Dataset(device, tokenizer)
with io.open(dataset_path, 'r', encoding='utf-8') as rdr:
for iline, line in enumerate(rdr, start=1):
fields = line.strip().split('\t')
input_context = fields[0]
output_context = fields[1]
if 0 == (iline % 20):
eval_samples.append(input_context, output_context)
else:
train_samples.append(input_context, output_context)
computed_params['max_len'] = train_samples.max_len
return train_samples, eval_samples
def decode_token_ids(tok_ids, tokenizer):
s = tokenizer.decode(tok_ids).replace('<pad>', ' ')
if '</s>' in s:
s = s[:s.index('</s')]
return s.strip()
def test(model, tokenizer, device, batch_generator):
model.eval()
accs = []
with torch.no_grad():
for batch in tqdm.tqdm(batch_generator, total=len(batch_generator), desc='Evaluating'):
input_ids = batch['input_ids'].to(device)
true_y = batch['labels'].to(device)
#pred_y = model(input_ids)
pred_y = model.generate(input_ids=input_ids,
max_length=input_ids.shape[1]+1,
eos_token_id=tokenizer.eos_token_id,
early_stopping=True)
#pred_y = pred_y[:, 1:]
for isample in range(input_ids.shape[0]):
true_str = decode_token_ids(true_y[isample, :], tokenizer)
pred_str = decode_token_ids(pred_y[isample, 1:], tokenizer)
acc = jaccard(true_str, pred_str, 3)
accs.append(acc)
#a = (true_y == pred_y).sum().item() / float(true_y.shape[0] * true_y.shape[1])
#accs.append(a)
acc = np.mean(accs)
#print('\nTest set: Accuracy: {:.0f}\n'.format(acc))
return acc
sentinel0 = '<extra_id_0>'
eos_token = '</s>'
if __name__ == '__main__':
EPOCHS = 10
tmp_dir = './tmp'
model_name = 'sberbank-ai/ruT5-base'
weights_path = os.path.join(tmp_dir, 'rut5.pt')
tokenizer = T5Tokenizer.from_pretrained(model_name,)
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
print('Device={}'.format(device))
# ==== ТРЕНИРОВКА ====
print('Loading T5 weights...')
model = T5ForConditionalGeneration.from_pretrained(model_name)
print('Loading dataset...')
computed_params = dict()
train_dataset, eval_dataset = load_samples('./data/t5_dataset.txt', device, tokenizer, computed_params)
batch_size = 10
train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)
eval_dataloader = DataLoader(eval_dataset, batch_size=batch_size, shuffle=False, num_workers=0)
print('Start training...')
model.to(device)
model.train()
optim = AdamW(model.parameters(), lr=5e-5)
if True: # fp16
print('fp16 initialization...')
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model, optim, opt_level="O1")
# multi-gpu training (should be after apex fp16 initialization)
if False:
print('multi-gpu training initialization...')
model = torch.nn.DataParallel(model)
best_acc = 0.0
nb_bad_epochs = 0
for epoch in range(EPOCHS):
try:
print('Epoch #{}...'.format(epoch+1))
for batch in tqdm.tqdm(train_dataloader, total=len(train_dataloader), desc='Training'):
optim.zero_grad()
input_ids = batch['input_ids'].to(device)
labels = batch['labels'].to(device)
loss = model(input_ids, labels=labels).loss
loss.backward()
optim.step()
acc = test(model, tokenizer, device, eval_dataloader)
print('')
if acc > best_acc:
print('NEW BEST ACC={}'.format(acc))
best_acc = acc
nb_bad_epochs = 0
print('Saving model to "{}"...'.format(weights_path))
torch.save(model.state_dict(), weights_path)
else:
nb_bad_epochs += 1
print('Score={}, no improvement over current best_acc={}'.format(acc, best_acc))
if nb_bad_epochs >= 10:
print('Early stopping on epoch={} best_acc={}'.format(epoch, best_acc))
break
except KeyboardInterrupt:
print('Training interrupted on epoch {}.'.format(epoch+1))
break
| [
"apex.amp.initialize",
"torch.no_grad",
"torch.utils.data.DataLoader",
"transformers.T5ForConditionalGeneration.from_pretrained",
"numpy.mean",
"torch.cuda.is_available",
"io.open",
"torch.device",
"transformers.T5Tokenizer.from_pretrained",
"torch.nn.DataParallel",
"torch.is_tensor",
"os.path... | [((3702, 3715), 'numpy.mean', 'np.mean', (['accs'], {}), '(accs)\n', (3709, 3715), True, 'import numpy as np\n'), ((3964, 3996), 'os.path.join', 'os.path.join', (['tmp_dir', '"""rut5.pt"""'], {}), "(tmp_dir, 'rut5.pt')\n", (3976, 3996), False, 'import os\n'), ((4014, 4053), 'transformers.T5Tokenizer.from_pretrained', 'T5Tokenizer.from_pretrained', (['model_name'], {}), '(model_name)\n', (4041, 4053), False, 'from transformers import T5ForConditionalGeneration, T5Tokenizer, T5Config\n'), ((4070, 4095), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4093, 4095), False, 'import torch\n'), ((4109, 4152), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (4121, 4152), False, 'import torch\n'), ((4266, 4320), 'transformers.T5ForConditionalGeneration.from_pretrained', 'T5ForConditionalGeneration.from_pretrained', (['model_name'], {}), '(model_name)\n', (4308, 4320), False, 'from transformers import T5ForConditionalGeneration, T5Tokenizer, T5Config\n'), ((4535, 4612), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)\n', (4545, 4612), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4635, 4712), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(eval_dataset, batch_size=batch_size, shuffle=False, num_workers=0)\n', (4645, 4712), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((1523, 1543), 'torch.is_tensor', 'torch.is_tensor', (['idx'], {}), '(idx)\n', (1538, 1543), False, 'import torch\n'), ((1953, 1997), 'io.open', 'io.open', (['dataset_path', '"""r"""'], {'encoding': '"""utf-8"""'}), "(dataset_path, 'r', encoding='utf-8')\n", (1960, 1997), False, 'import io\n'), ((2732, 2747), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2745, 2747), False, 'import torch\n'), ((5109, 5153), 'apex.amp.initialize', 'amp.initialize', (['model', 'optim'], {'opt_level': '"""O1"""'}), "(model, optim, opt_level='O1')\n", (5123, 5153), False, 'from apex import amp\n'), ((5307, 5335), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (5328, 5335), False, 'import torch\n')] |
from typing import Dict, Tuple, Any
import numpy as np
import cv2
import matplotlib.pyplot as plt
from . import image
class Warp(object):
def __init__(self, mapping:Dict[Tuple[Any, Any], Tuple[Any, Any]]):
'''
initializes the warp perspective transformation from a mapping of
four source points to target points
'''
if len(mapping) != 4:
raise ValueError('source-to-target mapping must contain exactly four points')
image_points, object_points = zip(*mapping.items())
self.transform_matrix = cv2.getPerspectiveTransform(
np.array(image_points, dtype=np.float32), np.array(object_points, dtype=np.float32))
self.inverse_transform_matrix = cv2.getPerspectiveTransform(
np.array(object_points, dtype=np.float32), np.array(image_points, dtype=np.float32))
def transform(self, img:np.array) -> np.array:
return cv2.warpPerspective(img, self.transform_matrix,
(img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR)
def inverse_transform(self, img:np.array) -> np.array:
return cv2.warpPerspective(img, self.inverse_transform_matrix,
(img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR)
# _birds_eye_image_points = [(600.5522583218831, 446.8418731439211), (680.3359558530209, 446.8418731439211), (1040.9582686937638, 675.5551393998494), (265.46072869110424, 676.618922033598)]
_birds_eye_image_points = [(603.2432092820274, 458.2994161111194), (683.4225895772826, 460.46642638936953), (1062.649388271057, 719.4241546402611), (248.93702878812962, 719.4241546402611)]
# x_left = 265
# x_right = 1063
x_left = 450
x_right = 850
_x_left = x_left
_x_right = x_right
_y_top = 0
_y_bottom = 719
_birds_eye_object_points = [(_x_left, _y_top), (_x_right, _y_top), (_x_right, _y_bottom), (_x_left, _y_bottom)]
birds_eye = Warp(dict(zip(_birds_eye_image_points, _birds_eye_object_points)))
if __name__ == '__main__':
# when run as a module, warp starts a helper point picker for choosing image points
import sys
from . import camera
image_file = sys.argv[1]
c = camera.Camera()
c.calibrate()
img = image.read(image_file, rgb=True)
img = c.undistort(img)
plt.imshow(img)
print(plt.ginput(4)) | [
"matplotlib.pyplot.imshow",
"cv2.warpPerspective",
"numpy.array",
"matplotlib.pyplot.ginput"
] | [((2248, 2263), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (2258, 2263), True, 'import matplotlib.pyplot as plt\n'), ((931, 1037), 'cv2.warpPerspective', 'cv2.warpPerspective', (['img', 'self.transform_matrix', '(img.shape[1], img.shape[0])'], {'flags': 'cv2.INTER_LINEAR'}), '(img, self.transform_matrix, (img.shape[1], img.shape[0]\n ), flags=cv2.INTER_LINEAR)\n', (950, 1037), False, 'import cv2\n'), ((1124, 1238), 'cv2.warpPerspective', 'cv2.warpPerspective', (['img', 'self.inverse_transform_matrix', '(img.shape[1], img.shape[0])'], {'flags': 'cv2.INTER_LINEAR'}), '(img, self.inverse_transform_matrix, (img.shape[1], img.\n shape[0]), flags=cv2.INTER_LINEAR)\n', (1143, 1238), False, 'import cv2\n'), ((2274, 2287), 'matplotlib.pyplot.ginput', 'plt.ginput', (['(4)'], {}), '(4)\n', (2284, 2287), True, 'import matplotlib.pyplot as plt\n'), ((609, 649), 'numpy.array', 'np.array', (['image_points'], {'dtype': 'np.float32'}), '(image_points, dtype=np.float32)\n', (617, 649), True, 'import numpy as np\n'), ((651, 692), 'numpy.array', 'np.array', (['object_points'], {'dtype': 'np.float32'}), '(object_points, dtype=np.float32)\n', (659, 692), True, 'import numpy as np\n'), ((775, 816), 'numpy.array', 'np.array', (['object_points'], {'dtype': 'np.float32'}), '(object_points, dtype=np.float32)\n', (783, 816), True, 'import numpy as np\n'), ((818, 858), 'numpy.array', 'np.array', (['image_points'], {'dtype': 'np.float32'}), '(image_points, dtype=np.float32)\n', (826, 858), True, 'import numpy as np\n')] |
import os
import sys
import random
import math
import re
import time
import numpy as np
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from pathlib import PureWindowsPath as Path
import utils
import visualize
from visualize import display_images
import model as modellib
from model import log
import skimage.io
import skimage.transform
from config import Config
import pickle
from tqdm import tqdm
import torch
from adriving_util import *
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import json
with open('../../settings.json') as f:
setting = json.load(f)
image_size_crop = (2048, 3384)
image_size = (2048, 3584)
SCALE = 1
FLIP = False
if SCALE == 2:
image_size = (int(image_size[0]/2), int(image_size[1]/2))
else:
image_size = (image_size[0], image_size[1])
class AdrivingConfig(Config):
"""Configuration for training on the toy dataset.
Derives from the base Config class and overrides some values.
"""
# Give the configuration a recognizable name
NAME = "Adriving"
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 7 # Background + baloon
# Number of training steps per epoch
STEPS_PER_EPOCH = 1000
RPN_NMS_THRESHOLD = 0.6
TRAIN_ROIS_PER_IMAGE = 1500
RPN_TRAIN_ANCHORS_PER_IMAGE = 1000
POST_NMS_ROIS_TRAINING = 4000
POST_NMS_ROIS_INFERENCE = 2000
IMAGE_MIN_DIM = image_size[0]
IMAGE_MAX_DIM = image_size[1]
IMAGE_RESIZE_MODE = "none"
MEAN_PIXEL = np.array([88.59672608, 95.91837699, 98.90089033])
DETECTION_MIN_CONFIDENCE = 0.1
DETECTION_NMS_THRESHOLD = 0.3
MASK_THRESHOLD = 0.35
config = AdrivingConfig()
config.display()
DEVICE = "/gpu:0" # /cpu:0 or /gpu:0
import utils
import skimage.io
import skimage.transform
from skimage import data, img_as_float
from skimage import exposure
def crop_and_resize_test(image, scale = SCALE, flip = FLIP):
img_crop = np.zeros([image_size[0], image_size[1], 3], dtype = np.float)
img_roi = image[-image_size_crop[0]:, :, :]
if scale == 2:
img_resize = skimage.transform.resize(img_roi, (image_size_crop[0]/2, image_size_crop[1]/2),
order=1, mode="constant",
preserve_range=True)
else:
img_resize = img_roi
start_y = int((img_crop.shape[1] - img_resize.shape[1])/2)
# print(start_y)
img_crop[:, start_y:(start_y+img_resize.shape[1]), :] = img_resize
if flip:
img_crop = np.fliplr(img_crop)
return img_crop
def load_test_image(image_filename, test_dir):
if os.path.islink(str(test_dir/image_filename)):
image_path = os.readlink(test_dir/image_filename)
else:
image_path = str(test_dir/image_filename)
image = skimage.io.imread(image_path)
image = crop_and_resize_test(image, scale = SCALE)
return image
from scipy import sparse
def prediction_to_sparse(prediction, flip = FLIP):
prediction_sparse = dict()
prediction_sparse['rois'] = prediction['rois']
prediction_sparse['class_ids'] = prediction['class_ids']
prediction_sparse['scores'] = prediction['scores']
prediction_sparse['masks'] = []
for i in range(len(prediction['scores'])):
if flip:
mask = np.fliplr(prediction['masks'][:, :, i])
else:
mask = prediction['masks'][:, :, i]
prediction_sparse['masks'].append(sparse.bsr_matrix(mask))
return prediction_sparse
def predict(model, test_image, test_dir, results_folder, write_rle = False):
file_name = results_folder + '.txt'
if write_rle:
with open(file_name, 'w+') as prediction_file:
prediction_file.write('ImageId,LabelId,Confidence,PixelCount,EncodedPixels\n')
for image_filename in tqdm(test_image, ncols = 50):
image = load_test_image(image_filename, test_dir)
image_id = image_filename[:-4]
prediction = model.detect([image])[0]
if prediction is None:
continue
if len(prediction['class_ids']) == 0:
continue
prediction_sparse = prediction_to_sparse(prediction)
with open(results_folder + '/' + image_id + '.p', 'wb') as f:
pickle.dump(prediction_sparse, f)
if write_rle:
with open(file_name, 'a+') as prediction_file:
mask_pred = np.zeros([2710, 3384, len(prediction['scores'])], dtype = bool)
mask_pred[-image_size[0]:, :, :] = prediction['masks'][:, 72:(72+3384), :]
mask, instance_score = instance_to_mask(mask_pred, prediction['class_ids'],
prediction['scores'])
rle_string_list = write_mask(image_id, mask, score = instance_score)
for rle_str in rle_string_list:
prediction_file.write(rle_str)
prediction_file.write('\n')
if __name__ == '__main__':
test_dir = Path(os.path.join('../../', setting['TEST_DATA_CLEAN_PATH'], 'test'))
test_image = os.listdir(str(test_dir))
test_image = [x for x in test_image if x[0] != '.']
test_image.sort()
MODEL_DIR = 'log'
# with tf.device(DEVICE):
model = modellib.MaskRCNN(model_dir=MODEL_DIR,
config=config)
weights_path = os.path.join('../../',
setting['MODEL_CHECKPOINT_DIR'],
'mask_rcnn_adriving_0521_1e-5_bz_32_0.82.pth')
print("Loading weights ", weights_path)
model.load_weights(weights_path, strict=True)
model = model.cuda()
results_folder = 'pytorch_resnet/test_20180521_01_mask_th_' \
+ str(config.MASK_THRESHOLD) \
+ '_nms_th_' + str(config.RPN_NMS_THRESHOLD) \
+ '_Scale_' + str(SCALE) + '_Flip_' + str(FLIP) \
+ '_DT_NMS_TH_' + str(config.DETECTION_NMS_THRESHOLD)
results_folder = os.path.join('../../',
setting['SUBMISSION_DIR'],
results_folder)
print(results_folder)
if not os.path.isdir(results_folder):
os.makedirs(results_folder)
predict(model, test_image, test_dir, results_folder, write_rle = False)
| [
"tqdm.tqdm",
"json.load",
"pickle.dump",
"os.makedirs",
"os.readlink",
"os.path.isdir",
"scipy.sparse.bsr_matrix",
"numpy.zeros",
"numpy.fliplr",
"numpy.array",
"model.MaskRCNN",
"os.path.join"
] | [((612, 624), 'json.load', 'json.load', (['f'], {}), '(f)\n', (621, 624), False, 'import json\n'), ((1551, 1600), 'numpy.array', 'np.array', (['[88.59672608, 95.91837699, 98.90089033]'], {}), '([88.59672608, 95.91837699, 98.90089033])\n', (1559, 1600), True, 'import numpy as np\n'), ((1990, 2049), 'numpy.zeros', 'np.zeros', (['[image_size[0], image_size[1], 3]'], {'dtype': 'np.float'}), '([image_size[0], image_size[1], 3], dtype=np.float)\n', (1998, 2049), True, 'import numpy as np\n'), ((3890, 3916), 'tqdm.tqdm', 'tqdm', (['test_image'], {'ncols': '(50)'}), '(test_image, ncols=50)\n', (3894, 3916), False, 'from tqdm import tqdm\n'), ((5379, 5432), 'model.MaskRCNN', 'modellib.MaskRCNN', ([], {'model_dir': 'MODEL_DIR', 'config': 'config'}), '(model_dir=MODEL_DIR, config=config)\n', (5396, 5432), True, 'import model as modellib\n'), ((5487, 5593), 'os.path.join', 'os.path.join', (['"""../../"""', "setting['MODEL_CHECKPOINT_DIR']", '"""mask_rcnn_adriving_0521_1e-5_bz_32_0.82.pth"""'], {}), "('../../', setting['MODEL_CHECKPOINT_DIR'],\n 'mask_rcnn_adriving_0521_1e-5_bz_32_0.82.pth')\n", (5499, 5593), False, 'import os\n'), ((6152, 6217), 'os.path.join', 'os.path.join', (['"""../../"""', "setting['SUBMISSION_DIR']", 'results_folder'], {}), "('../../', setting['SUBMISSION_DIR'], results_folder)\n", (6164, 6217), False, 'import os\n'), ((2594, 2613), 'numpy.fliplr', 'np.fliplr', (['img_crop'], {}), '(img_crop)\n', (2603, 2613), True, 'import numpy as np\n'), ((2757, 2795), 'os.readlink', 'os.readlink', (['(test_dir / image_filename)'], {}), '(test_dir / image_filename)\n', (2768, 2795), False, 'import os\n'), ((5127, 5190), 'os.path.join', 'os.path.join', (['"""../../"""', "setting['TEST_DATA_CLEAN_PATH']", '"""test"""'], {}), "('../../', setting['TEST_DATA_CLEAN_PATH'], 'test')\n", (5139, 5190), False, 'import os\n'), ((6330, 6359), 'os.path.isdir', 'os.path.isdir', (['results_folder'], {}), '(results_folder)\n', (6343, 6359), False, 'import os\n'), ((6369, 6396), 'os.makedirs', 'os.makedirs', (['results_folder'], {}), '(results_folder)\n', (6380, 6396), False, 'import os\n'), ((3365, 3404), 'numpy.fliplr', 'np.fliplr', (["prediction['masks'][:, :, i]"], {}), "(prediction['masks'][:, :, i])\n", (3374, 3404), True, 'import numpy as np\n'), ((3522, 3545), 'scipy.sparse.bsr_matrix', 'sparse.bsr_matrix', (['mask'], {}), '(mask)\n', (3539, 3545), False, 'from scipy import sparse\n'), ((4360, 4393), 'pickle.dump', 'pickle.dump', (['prediction_sparse', 'f'], {}), '(prediction_sparse, f)\n', (4371, 4393), False, 'import pickle\n')] |
from letop_examples import (
compliance_optimization,
heat_exchanger_optimization,
)
from numpy.testing import assert_allclose
def test_heat_exchanger():
results = heat_exchanger_optimization(n_iters=10)
cost_func = results["J"][-1]
assert_allclose(
cost_func,
-1.316,
rtol=1e-2,
)
def test_compliance():
results = compliance_optimization(n_iters=10)
cost_func = results["J"][-1]
assert_allclose(
cost_func,
11.86,
rtol=1e-2,
)
| [
"numpy.testing.assert_allclose",
"letop_examples.heat_exchanger_optimization",
"letop_examples.compliance_optimization"
] | [((178, 217), 'letop_examples.heat_exchanger_optimization', 'heat_exchanger_optimization', ([], {'n_iters': '(10)'}), '(n_iters=10)\n', (205, 217), False, 'from letop_examples import compliance_optimization, heat_exchanger_optimization\n'), ((255, 300), 'numpy.testing.assert_allclose', 'assert_allclose', (['cost_func', '(-1.316)'], {'rtol': '(0.01)'}), '(cost_func, -1.316, rtol=0.01)\n', (270, 300), False, 'from numpy.testing import assert_allclose\n'), ((371, 406), 'letop_examples.compliance_optimization', 'compliance_optimization', ([], {'n_iters': '(10)'}), '(n_iters=10)\n', (394, 406), False, 'from letop_examples import compliance_optimization, heat_exchanger_optimization\n'), ((444, 488), 'numpy.testing.assert_allclose', 'assert_allclose', (['cost_func', '(11.86)'], {'rtol': '(0.01)'}), '(cost_func, 11.86, rtol=0.01)\n', (459, 488), False, 'from numpy.testing import assert_allclose\n')] |
"""Functions used for registering stacks of images, e.g. spectroscopic data"""
import numpy as np
import dask.array as da
import dask
from dask.delayed import delayed
from scipy.optimize import least_squares
import scipy.ndimage as ndi
from scipy.interpolate import interp1d
import scipy.sparse as ssp
from skimage import filters
import numba
def filter_block(block, sigma, mode='nearest'):
"""Perform Gaussian and Sobel filtering on a block of images
TODO: replace with gaussian_gradient_magnitude as implemented in cupy, ndi and dask_image
"""
# return np.stack([GSfilter(block[i], sigma, mode) for i in range(block.shape[0])])
return np.stack([GSfilter(image, sigma, mode) for image in block])
def GSfilter(image, sigma, mode):
"""Combine a Sobel and a Gaussian filter"""
return filters.sobel(filters.gaussian(image, sigma=sigma, mode=mode))
def crop_and_filter(images, sigma=11, mode='nearest', finalsize=256):
"""Crop images to finalsize and apply the filters.
Cropping is initially with a margin of sigma,
to prevent edge effects of the filters.
"""
cent = [dim//2 for dim in images.shape[1:]]
halfsize = finalsize//2 + sigma
result = images[:, (cent[0]-halfsize):(cent[0]+halfsize),
(cent[1]-halfsize):(cent[1]+halfsize)]
result = result.map_blocks(filter_block, dtype=np.float64,
sigma=sigma, mode=mode)
if sigma > 0:
result = result[:, sigma:-sigma, sigma:-sigma]
return result
def crop_and_filter_extent(images, extent, sigma=11, mode='nearest'):
"""Crop images to extent chosen and apply the filters. Cropping is initially with a margin of sigma,
to prevent edge effects of the filters. extent = minx,maxx,miny,maxy of ROI"""
result = images[:, extent[0]-sigma:extent[1]+sigma,
extent[2]-sigma:extent[3]+sigma]
result = result.map_blocks(filter_block, dtype=np.float64,
sigma=sigma, mode=mode)
if sigma > 0:
result = result[:, sigma:-sigma, sigma:-sigma]
return result
def dask_cross_corr(data):
"""Return the dask array with the crosscorrelations of data
(uncomputed)
"""
# Define the Correlation `Corr` via FFT's:
F = da.fft.rfft2(data, axes=(1, 2))
Corr = da.fft.irfft2(F[:, np.newaxis, ...] * F.conj()[np.newaxis, ...],
axes=(2, 3)
).real
Corr = da.fft.fftshift(Corr, axes=(2, 3))
return Corr
def max_and_argmax(data):
"""Returns max and argmax along last two axes.
Last two axes should correspond to the x and y dimensions.
Parameters
----------
data : dask array
data with at least 3 dimensions
Returns
-------
weights : dask array
max of `data` along the last two axes
argmax : dask array
argmax of `data` along the last two axes
"""
# Slap out a dimension to nicely apply argmax and max
flatData = data.reshape(data.shape[:-2]+(-1,))
argmax = da.argmax(flatData, axis=-1)
# We can forego calculating both max and argmax as soon as
# we have da.take_along_axis() https://github.com/dask/dask/issues/3663
# Would a map_blocks of np.take_along_axis() work and be faster?
weights = da.max(flatData, axis=-1)
return weights, argmax
def calculate_halfmatrices(weights, argmax, fftsize=128):
"""Compute the half matrices of the weights and the argmax
and reconstruct the full arrays.
Parameters
----------
weights : dask array
argmax : dask array
fftsize : int, default: 128
Returns
-------
Wc : numpy array
Computed weights, symmetric
Mc : numpy array
Computed locations of maxima
"""
# Calculate half of the matrices only, because we know it is antisymmetric.
uargmax = da.triu(argmax, 1) # Diagonal shifts are zero anyway, so 1. Reconstruct after computation
uW = da.triu(weights, 1)
uW = uW + uW.T + da.diag(da.diag(weights))
# Do actual computations, get a cup of coffee
Mc, Wc = da.compute(uargmax, uW)
# Undo the flatten: Reconstruct 2D indices from global linear indices of argmax
Mc = np.stack(np.unravel_index(Mc, (fftsize*2, fftsize*2)))
Mc -= np.triu(np.full_like(Mc, fftsize), 1) # Compensate for the fft-shift
Mc = Mc - Mc.swapaxes(1, 2) # Reconstruct full antisymmetric matrices
# Mc = Mc / z_factor # Compensate for zoomfactor
return Wc, Mc
def threshold_and_mask(min_normed_weight, W, Mc, coords): # =np.arange(Wc.shape[0])*stride + start):
"""Normalize the weights W, threshold to min_normed_weight and remove diagonal,
reduce DX and DY to the columns and rows still containing weights.
Returns
-------
coords : array_like
the indices of these columns in terms of original image indices
W_n_m : array_like
the thresholded weights
D_X_m : array_like
The reduced DX
D_Y_m : array_like
The reduced DY
row_mask : array_like
The indices of these columns in terms of calculated arrays.
"""
#coords = np.arange(Wc.shape[0])*stride + start
wcdiag = np.atleast_2d(np.diag(W))
W_n = W / np.sqrt(wcdiag.T*wcdiag)
mask = W_n - np.diag(np.diag(W_n)) > min_normed_weight
row_mask = np.any(mask, axis=0)
W_n = np.where(mask, W_n, 0)
DX, DY = Mc[0], Mc[1]
W_n_m = W_n[:, row_mask][row_mask, :]
coords = coords[row_mask]
#mask_red = mask[row_mask, :][:, row_mask]
DX_m, DY_m = DX[row_mask, :][:, row_mask], DY[row_mask, :][:, row_mask]
return coords, W_n_m, DX_m, DY_m, row_mask
def construct_jac(W):
"""Construct a sparse Jacobian matrix of the least squares problem
from a weight matrix.
This Jacobian is independent of the position
vector dx as the problem is actually linear
Parameters
----------
W : array_like (N,N)
weight matrix
Returns
-------
sparse array (N, N*N)
Jacobian in compressed sparse row format
"""
N = W.shape[0]
i = np.arange(N)
j = i + N*i
data = np.ones(N)
A = ssp.coo_matrix((data, (i, j)), shape=(N, N*N)).tocsr()
wsp = ssp.csr_matrix(W)
J = wsp.dot(A)
J = J.reshape((N*N, N))
return J - wsp.T.dot(A).reshape((N*N, N), order='F')
def calc_shift_vectors(DX, DY, weightmatrix, wpower=4, lsqkwargs={}):
"""From relative displacement matrices, compute absolute displacement
vectors.
Parameters
----------
DX : array_like (N,N)
horizontal relative displacement matrix
DY : array_like (N,N)
vertical relative displacement matrix
weightmatrix : array_like (N,N)
weights for least sqaures minimization
wpower : int or float, default=4
weightmatrix is used to this power
(componentwise)
lsqkwargs : dict, default={}
keyword arguments to pass to calls of
`scipy.optimize.least_squares`
Returns
-------
dx : array (N,)
horizontal absolute shift vector
dy : array (N,)
vertical absolute shift vector
"""
wopt = weightmatrix**wpower
@numba.jit(nopython=True, nogil=True)
def err_func(x, result):
x = np.atleast_2d(x)
epsilon = x - x.T - result
epsilon = epsilon * wopt
return epsilon.ravel()
Jac = construct_jac(wopt)
res = least_squares(err_func, DX[DX.shape[0]//2, :],
jac=lambda x, Jargs: Jac,
args=(DX,), **lsqkwargs)
dx = res['x']
res = least_squares(err_func, DY[DY.shape[0]//2, :],
jac=lambda x, Jargs: Jac,
args=(DY,), **lsqkwargs)
dy = res['x']
dx -= dx.min()
dy -= dy.min()
return dx, dy
def interp_shifts(coords, shifts, n=None):
"""
Interpolate shifts for all frames not in coords and create dask array
Parameters
----------
coords : (N,)
coordinates for shifts
shifts : (d, N)
list of arrays to be interpolated
n : int or None, defaults=None
final length (original size)
Returns
-------
shifts_interp : (d, n)
array of interpolated shifts
"""
if n is None:
ns = np.arange(coords.min(), coords.max()+1)
else:
ns = np.arange(n)
shifts_interp = []
for dr in shifts:
f = interp1d(coords, dr, fill_value=(dr[0], dr[-1]),
kind='linear', assume_sorted=True, bounds_error=False)
shifts_interp.append(f(ns))
#shift = da.from_array(shift, chunks=(dE,1,1))
return np.array(shifts_interp)
# def shift_block(images, shifts, margins=(0,0)):
# """Shift a block of images per image in the x,y plane by shifts[index].
# Embed this in margins extra space"""
# result = np.zeros((images.shape[0],
# images.shape[1] + margins[0],
# images.shape[2] + margins[1]))
# for index in range(images.shape[0]):
# result[index,
# 0:images.shape[1],
# 0:images.shape[2]] = images[index]
# result[index,...] = shift(result[index,...],
# shift=shifts[index],
# order=1,
# )
# return result
# def syn_shift_blocks(shiftsX, shiftsY, image):
# result = np.stack([image] * dE)
# for index in range(dE):
# result[index,...] = shift(result[index,...],
# shift=(shiftsX[index,...],shiftsY[index,...]),
# order=1,
# )
# return result
def only_filter(images, sigma=11, mode='nearest'):
"""Apply the filters.
Cropped with a margin of sigma,
to prevent edge effects of the filters.
"""
result = images.map_blocks(filter_block, dtype=np.float64,
sigma=sigma, mode=mode)
if sigma > 0:
si = int(np.ceil(sigma))
result = result[:, si:-si, si:-si]
return result
def register_stack(data, sigma=5, fftsize=256, dE=10, min_norm=0.15):
"""Top level convenience function to register a stack of images.
`data` should be a stack of images stacked along axis 0 in the form
of anything convertible to a dask array by `da.asarray()`.
Quick and dirty function, should only be used for small stacks, as
not all parameters are exposed, in particular strides/interpolation
are unavailable.
Parameters
----------
data : array_like, (N x m x k)
stack of N images
sigma : int
width of the gaussian filter
fftsize : int
size of FFTs to use. powers of 2 are preferred
dE : int
blocksize of computation.
min_norm: float
minimum normalized weight to use
Returns
-------
corrected: dask array
dask array of the shifted/corrected images
shifts: (Nx2) dask array
array of the computed shifts
"""
data = da.asarray(data, chunks=(dE, -1, -1))
sobel = crop_and_filter(data.rechunk({0: dE}), sigma=sigma, finalsize=2*fftsize)
sobel = (sobel - sobel.mean(axis=(1, 2), keepdims=True)).persist()
corr = dask_cross_corr(sobel)
W, M = calculate_halfmatrices(*max_and_argmax(corr), fftsize=fftsize)
#w_diag = np.atleast_2d(np.diag(W))
#W_n = W / np.sqrt(w_diag.T * w_diag)
nr = np.arange(data.shape[0])
coords, weightmatrix, DX, DY, row_mask = threshold_and_mask(min_norm, W, M, nr)
dx, dy = calc_shift_vectors(DX, DY, weightmatrix)
shifts = np.stack(interp_shifts(coords, [dx, dy], n=data.shape[0]), axis=1)
neededMargins = np.ceil(shifts.max(axis=0)).astype(int)
shifts = da.from_array(shifts, chunks=(dE, -1))
@da.as_gufunc(signature="(i,j),(2)->(i,j)", output_dtypes=data.dtype, vectorize=True)
def shift_images(image, shifts):
"""Shift `image` by `shift` pixels."""
return ndi.shift(image, shift=shifts, order=1)
padded = da.pad(data.rechunk({0: dE}),
((0, 0),
(0, neededMargins[0]),
(0, neededMargins[1])
),
mode='constant'
)
corrected = shift_images(padded.rechunk({1: -1, 2: -1}), shifts)
return corrected, shifts
def strided_register(data, sigma=5, fftsize=256, stride=10, min_norm=0.15, start=0):
"""Top level convenience function for large stacks of images
Instead of calculating the full matrix of all combinations of images,
only computes a band of between stride and 2*stride nearest neighbors
to enable a linear in the number of images computation.
Parameters
----------
data : array_like, (N x m x k)
stack of N images
sigma : int
width of the gaussian filter
fftsize : int
size of FFTs to use. powers of 2 are preferred
stride : int
blocksize of computation. For each image 3*stride neighbors are considered:
at least stride before and after, at most 2*stride
min_norm: float
minimum normalized weight to use
start : int
First image in the stack to consider for registering.
All images before `start` will be shifted to the same position
as the first image considered.
Returns
-------
corrected: dask array
dask array of the shifted/corrected images
shifts: (Nx2) dask array
array of the computed shifts
W_full: (NxN) numpy array
computed weights
M_full: (2xNxN) numpy array
computed relative shifts
"""
dE = stride
data = da.asarray(data, chunks=(dE, -1, -1))
nr = np.arange(start, data.shape[0])
sobel = crop_and_filter(data.rechunk({0: dE}), sigma=sigma, finalsize=2*fftsize)
sobel = (sobel - sobel.mean(axis=(1, 2), keepdims=True))#.persist()
W_full = np.zeros((data.shape[0],
data.shape[0]))
M_full = np.zeros((2, data.shape[0],
data.shape[0]))
outer_stride = 2*stride
for i in np.arange(start, data.shape[0], stride):
print(i, end=' ')
i2 = i + outer_stride
corr = dask_cross_corr(sobel[i:i2]) #Todo: only compute every block once.
W, M = calculate_halfmatrices(*max_and_argmax(corr),
fftsize=fftsize)
W_full[i:i2, i:i2] = W
M_full[:, i:i2, i:i2] = M
#w_diag = np.atleast_2d(np.diag(W))
#W_n = W / np.sqrt(w_diag.T * w_diag)
coords, weightmatrix, DX, DY, row_mask = threshold_and_mask(min_norm,
W_full[start:,start:],
M_full[:,start:,start:],
nr)
dx, dy = calc_shift_vectors(DX, DY, weightmatrix)
shifts = np.stack(interp_shifts(coords, [dx, dy], n=data.shape[0]), axis=1)
neededMargins = np.ceil(shifts.max(axis=0)).astype(int)
shifts = da.from_array(shifts, chunks=(dE, -1))
@da.as_gufunc(signature="(i,j),(2)->(i,j)", output_dtypes=data.dtype, vectorize=True)
def shift_images(image, shifts):
"""Shift `image` by `shift` pixels."""
return ndi.shift(image, shift=shifts, order=1)
padded = da.pad(data.rechunk({0: dE}),
((0, 0),
(0, neededMargins[0]),
(0, neededMargins[1])
),
mode='constant'
)
corrected = shift_images(padded.rechunk({1: -1, 2: -1}), shifts)
return corrected, shifts, W_full, M_full
| [
"numpy.ones",
"dask.array.diag",
"dask.array.max",
"numpy.arange",
"numpy.diag",
"scipy.interpolate.interp1d",
"numpy.atleast_2d",
"numpy.full_like",
"dask.array.asarray",
"scipy.optimize.least_squares",
"scipy.sparse.coo_matrix",
"dask.array.argmax",
"dask.array.as_gufunc",
"dask.array.tr... | [((2269, 2300), 'dask.array.fft.rfft2', 'da.fft.rfft2', (['data'], {'axes': '(1, 2)'}), '(data, axes=(1, 2))\n', (2281, 2300), True, 'import dask.array as da\n'), ((2457, 2491), 'dask.array.fft.fftshift', 'da.fft.fftshift', (['Corr'], {'axes': '(2, 3)'}), '(Corr, axes=(2, 3))\n', (2472, 2491), True, 'import dask.array as da\n'), ((3043, 3071), 'dask.array.argmax', 'da.argmax', (['flatData'], {'axis': '(-1)'}), '(flatData, axis=-1)\n', (3052, 3071), True, 'import dask.array as da\n'), ((3294, 3319), 'dask.array.max', 'da.max', (['flatData'], {'axis': '(-1)'}), '(flatData, axis=-1)\n', (3300, 3319), True, 'import dask.array as da\n'), ((3861, 3879), 'dask.array.triu', 'da.triu', (['argmax', '(1)'], {}), '(argmax, 1)\n', (3868, 3879), True, 'import dask.array as da\n'), ((3962, 3981), 'dask.array.triu', 'da.triu', (['weights', '(1)'], {}), '(weights, 1)\n', (3969, 3981), True, 'import dask.array as da\n'), ((4093, 4116), 'dask.array.compute', 'da.compute', (['uargmax', 'uW'], {}), '(uargmax, uW)\n', (4103, 4116), True, 'import dask.array as da\n'), ((5326, 5346), 'numpy.any', 'np.any', (['mask'], {'axis': '(0)'}), '(mask, axis=0)\n', (5332, 5346), True, 'import numpy as np\n'), ((5357, 5379), 'numpy.where', 'np.where', (['mask', 'W_n', '(0)'], {}), '(mask, W_n, 0)\n', (5365, 5379), True, 'import numpy as np\n'), ((6080, 6092), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (6089, 6092), True, 'import numpy as np\n'), ((6120, 6130), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (6127, 6130), True, 'import numpy as np\n'), ((6204, 6221), 'scipy.sparse.csr_matrix', 'ssp.csr_matrix', (['W'], {}), '(W)\n', (6218, 6221), True, 'import scipy.sparse as ssp\n'), ((7158, 7194), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'nogil': '(True)'}), '(nopython=True, nogil=True)\n', (7167, 7194), False, 'import numba\n'), ((7393, 7496), 'scipy.optimize.least_squares', 'least_squares', (['err_func', 'DX[DX.shape[0] // 2, :]'], {'jac': '(lambda x, Jargs: Jac)', 'args': '(DX,)'}), '(err_func, DX[DX.shape[0] // 2, :], jac=lambda x, Jargs: Jac,\n args=(DX,), **lsqkwargs)\n', (7406, 7496), False, 'from scipy.optimize import least_squares\n'), ((7567, 7670), 'scipy.optimize.least_squares', 'least_squares', (['err_func', 'DY[DY.shape[0] // 2, :]'], {'jac': '(lambda x, Jargs: Jac)', 'args': '(DY,)'}), '(err_func, DY[DY.shape[0] // 2, :], jac=lambda x, Jargs: Jac,\n args=(DY,), **lsqkwargs)\n', (7580, 7670), False, 'from scipy.optimize import least_squares\n'), ((8612, 8635), 'numpy.array', 'np.array', (['shifts_interp'], {}), '(shifts_interp)\n', (8620, 8635), True, 'import numpy as np\n'), ((10982, 11019), 'dask.array.asarray', 'da.asarray', (['data'], {'chunks': '(dE, -1, -1)'}), '(data, chunks=(dE, -1, -1))\n', (10992, 11019), True, 'import dask.array as da\n'), ((11375, 11399), 'numpy.arange', 'np.arange', (['data.shape[0]'], {}), '(data.shape[0])\n', (11384, 11399), True, 'import numpy as np\n'), ((11691, 11729), 'dask.array.from_array', 'da.from_array', (['shifts'], {'chunks': '(dE, -1)'}), '(shifts, chunks=(dE, -1))\n', (11704, 11729), True, 'import dask.array as da\n'), ((11736, 11824), 'dask.array.as_gufunc', 'da.as_gufunc', ([], {'signature': '"""(i,j),(2)->(i,j)"""', 'output_dtypes': 'data.dtype', 'vectorize': '(True)'}), "(signature='(i,j),(2)->(i,j)', output_dtypes=data.dtype,\n vectorize=True)\n", (11748, 11824), True, 'import dask.array as da\n'), ((13611, 13648), 'dask.array.asarray', 'da.asarray', (['data'], {'chunks': '(dE, -1, -1)'}), '(data, chunks=(dE, -1, -1))\n', (13621, 13648), True, 'import dask.array as da\n'), ((13658, 13689), 'numpy.arange', 'np.arange', (['start', 'data.shape[0]'], {}), '(start, data.shape[0])\n', (13667, 13689), True, 'import numpy as np\n'), ((13860, 13900), 'numpy.zeros', 'np.zeros', (['(data.shape[0], data.shape[0])'], {}), '((data.shape[0], data.shape[0]))\n', (13868, 13900), True, 'import numpy as np\n'), ((13937, 13980), 'numpy.zeros', 'np.zeros', (['(2, data.shape[0], data.shape[0])'], {}), '((2, data.shape[0], data.shape[0]))\n', (13945, 13980), True, 'import numpy as np\n'), ((14048, 14087), 'numpy.arange', 'np.arange', (['start', 'data.shape[0]', 'stride'], {}), '(start, data.shape[0], stride)\n', (14057, 14087), True, 'import numpy as np\n'), ((15023, 15061), 'dask.array.from_array', 'da.from_array', (['shifts'], {'chunks': '(dE, -1)'}), '(shifts, chunks=(dE, -1))\n', (15036, 15061), True, 'import dask.array as da\n'), ((15068, 15156), 'dask.array.as_gufunc', 'da.as_gufunc', ([], {'signature': '"""(i,j),(2)->(i,j)"""', 'output_dtypes': 'data.dtype', 'vectorize': '(True)'}), "(signature='(i,j),(2)->(i,j)', output_dtypes=data.dtype,\n vectorize=True)\n", (15080, 15156), True, 'import dask.array as da\n'), ((828, 875), 'skimage.filters.gaussian', 'filters.gaussian', (['image'], {'sigma': 'sigma', 'mode': 'mode'}), '(image, sigma=sigma, mode=mode)\n', (844, 875), False, 'from skimage import filters\n'), ((4220, 4268), 'numpy.unravel_index', 'np.unravel_index', (['Mc', '(fftsize * 2, fftsize * 2)'], {}), '(Mc, (fftsize * 2, fftsize * 2))\n', (4236, 4268), True, 'import numpy as np\n'), ((4284, 4309), 'numpy.full_like', 'np.full_like', (['Mc', 'fftsize'], {}), '(Mc, fftsize)\n', (4296, 4309), True, 'import numpy as np\n'), ((5201, 5211), 'numpy.diag', 'np.diag', (['W'], {}), '(W)\n', (5208, 5211), True, 'import numpy as np\n'), ((5227, 5253), 'numpy.sqrt', 'np.sqrt', (['(wcdiag.T * wcdiag)'], {}), '(wcdiag.T * wcdiag)\n', (5234, 5253), True, 'import numpy as np\n'), ((7236, 7252), 'numpy.atleast_2d', 'np.atleast_2d', (['x'], {}), '(x)\n', (7249, 7252), True, 'import numpy as np\n'), ((8319, 8331), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (8328, 8331), True, 'import numpy as np\n'), ((8389, 8496), 'scipy.interpolate.interp1d', 'interp1d', (['coords', 'dr'], {'fill_value': '(dr[0], dr[-1])', 'kind': '"""linear"""', 'assume_sorted': '(True)', 'bounds_error': '(False)'}), "(coords, dr, fill_value=(dr[0], dr[-1]), kind='linear',\n assume_sorted=True, bounds_error=False)\n", (8397, 8496), False, 'from scipy.interpolate import interp1d\n'), ((11920, 11959), 'scipy.ndimage.shift', 'ndi.shift', (['image'], {'shift': 'shifts', 'order': '(1)'}), '(image, shift=shifts, order=1)\n', (11929, 11959), True, 'import scipy.ndimage as ndi\n'), ((15252, 15291), 'scipy.ndimage.shift', 'ndi.shift', (['image'], {'shift': 'shifts', 'order': '(1)'}), '(image, shift=shifts, order=1)\n', (15261, 15291), True, 'import scipy.ndimage as ndi\n'), ((4011, 4027), 'dask.array.diag', 'da.diag', (['weights'], {}), '(weights)\n', (4018, 4027), True, 'import dask.array as da\n'), ((6139, 6187), 'scipy.sparse.coo_matrix', 'ssp.coo_matrix', (['(data, (i, j))'], {'shape': '(N, N * N)'}), '((data, (i, j)), shape=(N, N * N))\n', (6153, 6187), True, 'import scipy.sparse as ssp\n'), ((9951, 9965), 'numpy.ceil', 'np.ceil', (['sigma'], {}), '(sigma)\n', (9958, 9965), True, 'import numpy as np\n'), ((5277, 5289), 'numpy.diag', 'np.diag', (['W_n'], {}), '(W_n)\n', (5284, 5289), True, 'import numpy as np\n')] |
import torch
from torch import nn
import numpy as np
import utils
import excitability_modules as em
class fc_layer(nn.Module):
'''Fully connected layer, with possibility of returning "pre-activations".
Input: [batch_size] x ... x [in_size] tensor
Output: [batch_size] x ... x [out_size] tensor'''
def __init__(self,
in_size,
out_size,
nl=nn.ReLU(),
drop=0.,
bias=True,
excitability=False,
excit_buffer=False,
batch_norm=False,
gated=False,
kfac=False):
super().__init__()
if drop > 0:
self.dropout = nn.Dropout(drop)
self.linear = em.LinearExcitability(in_size,
out_size,
bias=False if batch_norm else bias,
excitability=excitability,
excit_buffer=excit_buffer)
self.bias = bias
if batch_norm:
self.bn = nn.BatchNorm1d(out_size)
if gated:
self.gate = nn.Linear(in_size, out_size)
self.sigmoid = nn.Sigmoid()
if isinstance(nl, nn.Module):
self.nl = nl
elif not nl == "none":
self.nl = nn.ReLU() if nl == "relu" else (
nn.LeakyReLU() if nl == "leakyrelu" else utils.Identity())
self.kfac = kfac
if self.kfac:
print('initializing phantom')
self.phantom = nn.Parameter(torch.zeros(out_size),
requires_grad=True)
else:
self.phantom = None
def forward(self, x, return_pa=False):
input = self.dropout(x) if hasattr(self, 'dropout') else x
pre_activ = self.bn(self.linear(input)) if hasattr(
self, 'bn') else self.linear(input)
gate = self.sigmoid(self.gate(x)) if hasattr(self, 'gate') else None
gated_pre_activ = gate * pre_activ if hasattr(self,
'gate') else pre_activ
gpa = gated_pre_activ + self.phantom if self.kfac else gated_pre_activ
output = self.nl(gpa) if hasattr(self, 'nl') else gpa
return (output, gpa) if return_pa else output
def list_init_layers(self):
'''Return list of modules whose parameters could be initialized differently (i.e., conv- or fc-layers).'''
return [self.linear, self.gate] if hasattr(self,
'gate') else [self.linear]
class fc_layer_split(nn.Module):
'''Fully connected layer outputting [mean] and [logvar] for each unit.
Input: [batch_size] x ... x [in_size] tensor
Output: tuple with two [batch_size] x ... x [out_size] tensors'''
def __init__(self,
in_size,
out_size,
nl_mean=nn.Sigmoid(),
nl_logvar=nn.Hardtanh(min_val=-4.5, max_val=0.),
drop=0.,
bias=True,
excitability=False,
excit_buffer=False,
batch_norm=False,
gated=False):
super().__init__()
self.mean = fc_layer(in_size,
out_size,
drop=drop,
bias=bias,
excitability=excitability,
excit_buffer=excit_buffer,
batch_norm=batch_norm,
gated=gated,
nl=nl_mean)
self.logvar = fc_layer(in_size,
out_size,
drop=drop,
bias=False,
excitability=excitability,
excit_buffer=excit_buffer,
batch_norm=batch_norm,
gated=gated,
nl=nl_logvar)
def forward(self, x):
return (self.mean(x), self.logvar(x))
def list_init_layers(self):
'''Return list of modules whose parameters could be initialized differently (i.e., conv- or fc-layers).'''
list = []
list += self.mean.list_init_layers()
list += self.logvar.list_init_layers()
return list
#-----------------------------------------------------------------------------------------------------------#
class MLP(nn.Module):
'''Module for a multi-layer perceptron (MLP).
Input: [batch_size] x ... x [size_per_layer[0]] tensor
Output: (tuple of) [batch_size] x ... x [size_per_layer[-1]] tensor'''
def __init__(self,
input_size=1000,
output_size=10,
layers=2,
hid_size=1000,
hid_smooth=None,
size_per_layer=None,
drop=0,
batch_norm=True,
nl="relu",
bias=True,
excitability=False,
excit_buffer=False,
gated=False,
output='normal',
kfac=False):
'''sizes: 0th=[input], 1st=[hid_size], ..., 1st-to-last=[hid_smooth], last=[output].
[input_size] # of inputs
[output_size] # of units in final layer
[layers] # of layers
[hid_size] # of units in each hidden layer
[hid_smooth] if None, all hidden layers have [hid_size] units, else # of units linearly in-/decreases s.t.
final hidden layer has [hid_smooth] units (if only 1 hidden layer, it has [hid_size] units)
[size_per_layer] None or <list> with for each layer number of units (1st element = number of inputs)
--> overwrites [input_size], [output_size], [layers], [hid_size] and [hid_smooth]
[drop] % of each layer's inputs that is randomly set to zero during training
[batch_norm] <bool>; if True, batch-normalization is applied to each layer
[nl] <str>; type of non-linearity to be used (options: "relu", "leakyrelu", "none")
[gated] <bool>; if True, each linear layer has an additional learnable gate
[output] <str>; if - "normal", final layer is same as all others
- "BCE", final layer has sigmoid non-linearity
[kfac] <bool>; whether to add phantom parameters to pre_activation, usefor computing kfac fisher
only applies to fc_layers
'''
super().__init__()
self.output = output
# get sizes of all layers
if size_per_layer is None:
hidden_sizes = []
if layers > 1:
if (hid_smooth is not None):
hidden_sizes = [
int(x) for x in np.linspace(
hid_size, hid_smooth, num=layers - 1)
]
else:
hidden_sizes = [
int(x) for x in np.repeat(hid_size, layers - 1)
]
size_per_layer = [input_size] + hidden_sizes + [output_size]
self.layers = len(size_per_layer) - 1
self.kfac = kfac
# set label for this module
# -determine "non-default options"-label
nd_label = "{drop}{bias}{exc}{bn}{nl}{gate}{out}".format(
drop="" if drop == 0 else "-drop{}".format(drop),
bias="" if bias else "-noBias",
exc="-exc" if excitability else "",
bn="-bn" if batch_norm else "",
nl="-lr" if nl == "leakyrelu" else "",
gate="-gated" if gated else "",
out="" if output == "normal" else "-{}".format(output),
)
# -set label
self.label = "MLP({}{})".format(size_per_layer,
nd_label) if self.layers > 0 else ""
# set layers
for lay_id in range(1, self.layers + 1):
# number of units of this layer's input and output
in_size = size_per_layer[lay_id - 1]
out_size = size_per_layer[lay_id]
# define and set the fully connected layer
if lay_id == self.layers and output in ("logistic", "gaussian"):
layer = fc_layer_split(
in_size,
out_size,
bias=bias,
excitability=excitability,
excit_buffer=excit_buffer,
drop=drop,
batch_norm=False,
gated=gated,
nl_mean=nn.Sigmoid()
if output == "logistic" else utils.Identity(),
nl_logvar=nn.Hardtanh(min_val=-4.5, max_val=0.)
if output == "logistic" else utils.Identity(),
)
else:
layer = fc_layer(
in_size,
out_size,
bias=bias,
excitability=excitability,
excit_buffer=excit_buffer,
drop=drop,
batch_norm=False if
(lay_id == self.layers
and not output == "normal") else batch_norm,
gated=gated,
nl=nn.Sigmoid() if
(lay_id == self.layers and not output == "normal") else nl,
kfac=kfac,
)
setattr(self, 'fcLayer{}'.format(lay_id), layer)
# if no layers, add "identity"-module to indicate in this module's representation nothing happens
if self.layers < 1:
self.noLayers = utils.Identity()
def forward(self, x, return_intermediate=False):
if not return_intermediate:
for lay_id in range(1, self.layers + 1):
x = getattr(self, 'fcLayer{}'.format(lay_id))(x)
return x
else:
intermediate = {}
for lay_id in range(1, self.layers + 1):
intermediate[f'fcLayer{lay_id}'] = x
x = getattr(self, 'fcLayer{}'.format(lay_id))(x)
return x, intermediate
@property
def name(self):
return self.label
def list_init_layers(self):
'''Return list of modules whose parameters could be initialized differently (i.e., conv- or fc-layers).'''
list = []
for layer_id in range(1, self.layers + 1):
list += getattr(self,
'fcLayer{}'.format(layer_id)).list_init_layers()
return list | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.BatchNorm1d",
"utils.Identity",
"torch.nn.Sigmoid",
"excitability_modules.LinearExcitability",
"numpy.repeat",
"numpy.linspace",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LeakyReLU",
"torch.nn.Hardtanh"
] | [((409, 418), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (416, 418), False, 'from torch import nn\n'), ((757, 891), 'excitability_modules.LinearExcitability', 'em.LinearExcitability', (['in_size', 'out_size'], {'bias': '(False if batch_norm else bias)', 'excitability': 'excitability', 'excit_buffer': 'excit_buffer'}), '(in_size, out_size, bias=False if batch_norm else bias,\n excitability=excitability, excit_buffer=excit_buffer)\n', (778, 891), True, 'import excitability_modules as em\n'), ((2996, 3008), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (3006, 3008), False, 'from torch import nn\n'), ((3037, 3075), 'torch.nn.Hardtanh', 'nn.Hardtanh', ([], {'min_val': '(-4.5)', 'max_val': '(0.0)'}), '(min_val=-4.5, max_val=0.0)\n', (3048, 3075), False, 'from torch import nn\n'), ((718, 734), 'torch.nn.Dropout', 'nn.Dropout', (['drop'], {}), '(drop)\n', (728, 734), False, 'from torch import nn\n'), ((1134, 1158), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['out_size'], {}), '(out_size)\n', (1148, 1158), False, 'from torch import nn\n'), ((1201, 1229), 'torch.nn.Linear', 'nn.Linear', (['in_size', 'out_size'], {}), '(in_size, out_size)\n', (1210, 1229), False, 'from torch import nn\n'), ((1257, 1269), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (1267, 1269), False, 'from torch import nn\n'), ((9969, 9985), 'utils.Identity', 'utils.Identity', ([], {}), '()\n', (9983, 9985), False, 'import utils\n'), ((1624, 1645), 'torch.zeros', 'torch.zeros', (['out_size'], {}), '(out_size)\n', (1635, 1645), False, 'import torch\n'), ((1386, 1395), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1393, 1395), False, 'from torch import nn\n'), ((1435, 1449), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (1447, 1449), False, 'from torch import nn\n'), ((1476, 1492), 'utils.Identity', 'utils.Identity', ([], {}), '()\n', (1490, 1492), False, 'import utils\n'), ((7105, 7154), 'numpy.linspace', 'np.linspace', (['hid_size', 'hid_smooth'], {'num': '(layers - 1)'}), '(hid_size, hid_smooth, num=layers - 1)\n', (7116, 7154), True, 'import numpy as np\n'), ((7305, 7336), 'numpy.repeat', 'np.repeat', (['hid_size', '(layers - 1)'], {}), '(hid_size, layers - 1)\n', (7314, 7336), True, 'import numpy as np\n'), ((8895, 8907), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (8905, 8907), False, 'from torch import nn\n'), ((8957, 8973), 'utils.Identity', 'utils.Identity', ([], {}), '()\n', (8971, 8973), False, 'import utils\n'), ((9005, 9043), 'torch.nn.Hardtanh', 'nn.Hardtanh', ([], {'min_val': '(-4.5)', 'max_val': '(0.0)'}), '(min_val=-4.5, max_val=0.0)\n', (9016, 9043), False, 'from torch import nn\n'), ((9092, 9108), 'utils.Identity', 'utils.Identity', ([], {}), '()\n', (9106, 9108), False, 'import utils\n'), ((9600, 9612), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (9610, 9612), False, 'from torch import nn\n')] |
# coding=utf-8
# Copyright 2020 <NAME>.
#
# 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.
"""Deal with webapp graphics components."""
import html
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import RendererAgg
# Added fix from https://docs.streamlit.io/en/stable/deploy_streamlit_app.html
_lock = RendererAgg.lock
def html_highlight_text(weights, tokens, color=(135, 206, 250), intensity=1):
"""
Return HTML code of highlighted tokens with different intensity color.
Arguments:
weights: (`obj`:list):
List of attentions scores for each token.
tokens: (`obj`:list):
List of tokens used in input. Need to match in length with attentions.
color: (`obj`: str):
String of RGB values separated by comma.
intensity: (`obj`: int):
Multiply each weight by this value to show up color.
Returns:
(`obj`: str):
String containing html code for color highlight.
"""
# Store all text with html code for coloring.
highlighted_text = []
# Larges weight value used to normalize.
max_weight_value = 1 if None in weights else max(weights)
# Loop through each weight and token to highlight with color.
for weight, word in zip(weights, tokens):
# Append html code text if we have weight.
if weight is not None:
highlighted_text.append(
f'<span style="background-color:rgba({str(color)[1:-1]},\
{str((intensity * weight) / max_weight_value)});">{html.escape(word)}</span>')
else:
# Append plain text if no weight.
highlighted_text.append(word)
# Return single string with html code.
return ' '.join(highlighted_text)
def plot_labels_confidence(labels_percentages, labels_coloring):
# Figure Size
with _lock:
plt.rcParams.update({'font.size': 22})
fig, ax = plt.subplots(figsize=(16, 9))
# Make the plot
for index, (label, percent) in enumerate(labels_percentages.items()):
plt.barh(index, percent, color=np.array(labels_coloring[label]) / 255,
edgecolor='grey', label=label)
plt.yticks(list(range(len(labels_percentages) + 1)), labels_percentages.keys())
# Add padding between axes and labels
ax.xaxis.set_tick_params(pad=5)
ax.yaxis.set_tick_params(pad=10)
# Add x, y gridlines
ax.grid(b=True, color='grey',
linestyle='-.', linewidth=0.5,
alpha=0.2)
# Show top values
ax.invert_yaxis()
# Add annotation to bars
for i in ax.patches:
plt.text(i.get_width() + 0.2, i.get_y() + 0.5,
f'{round((i.get_width()), 2)}%',
fontsize=22, fontweight='bold',
color='grey')
plt.xticks(list(range(0, 110, 10)))
ax.get_xaxis().set_visible(False)
plt.box(False)
return fig
| [
"matplotlib.pyplot.box",
"matplotlib.pyplot.rcParams.update",
"numpy.array",
"matplotlib.pyplot.subplots",
"html.escape"
] | [((2396, 2434), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 22}"], {}), "({'font.size': 22})\n", (2415, 2434), True, 'import matplotlib.pyplot as plt\n'), ((2453, 2482), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(16, 9)'}), '(figsize=(16, 9))\n', (2465, 2482), True, 'import matplotlib.pyplot as plt\n'), ((3492, 3506), 'matplotlib.pyplot.box', 'plt.box', (['(False)'], {}), '(False)\n', (3499, 3506), True, 'import matplotlib.pyplot as plt\n'), ((2092, 2109), 'html.escape', 'html.escape', (['word'], {}), '(word)\n', (2103, 2109), False, 'import html\n'), ((2629, 2661), 'numpy.array', 'np.array', (['labels_coloring[label]'], {}), '(labels_coloring[label])\n', (2637, 2661), True, 'import numpy as np\n')] |
import math
import random
import numpy as np
from typing import Union, Optional, Dict, List
from python_ghost_cursor.shared._math import (
Vector,
magnitude,
direction,
bezierCurve,
)
def fitts(distance: float, width: float) -> float:
a = 0
b = 2
id_ = math.log2(distance / width + 1)
return a + b * id_
def path(
start: Vector, end: Union[Dict, Vector], spreadOverride: Optional[float] = None
) -> List[Vector]:
defaultWidth = 100
minSteps = 25
if isinstance(end, dict):
width = end["width"]
end = Vector(end["x"], end["y"])
else:
width = defaultWidth
curve = bezierCurve(start, end, spreadOverride)
length = curve.length * 0.8
baseTime = random.random() * minSteps
steps = math.ceil((math.log2(fitts(length, width) + 1) + baseTime) * 3)
s_vals = np.linspace(0.0, 1.0, steps)
points = curve.evaluate_multi(s_vals)
vectors = []
for i in range(steps):
vectors.append(Vector(points[0][i], points[1][i]))
return clampPositive(vectors)
def clampPositive(vectors: List[Vector]) -> List[Vector]:
clamp0 = lambda elem: max(0, elem)
return [Vector(clamp0(el.x), clamp0(el.y)) for el in vectors]
overshootThreshold = 500
def should_overshoot(a: Vector, b: Vector) -> bool:
return magnitude(direction(a, b)) > overshootThreshold
def get_path(start: Dict, end: Dict) -> List[Dict]:
vectors = path(Vector(**start), Vector(**end))
return [el.__dict__ for el in vectors]
def get_random_box_point(
box: Dict, padding_percentage: Optional[float] = None
) -> Vector:
"""Get a random point on a box"""
paddingWidth = paddingHeight = 0
if (
padding_percentage is not None
and padding_percentage > 0
and padding_percentage < 100
):
paddingWidth = box["width"] * padding_percentage / 100
paddingHeight = box["height"] * padding_percentage / 100
return Vector(
box["x"] + (paddingWidth / 2) + random.random() * (box["width"] - paddingWidth),
box["y"]
+ (paddingHeight / 2)
+ random.random() * (box["height"] - paddingHeight),
)
| [
"python_ghost_cursor.shared._math.Vector",
"python_ghost_cursor.shared._math.bezierCurve",
"python_ghost_cursor.shared._math.direction",
"random.random",
"numpy.linspace",
"math.log2"
] | [((283, 314), 'math.log2', 'math.log2', (['(distance / width + 1)'], {}), '(distance / width + 1)\n', (292, 314), False, 'import math\n'), ((645, 684), 'python_ghost_cursor.shared._math.bezierCurve', 'bezierCurve', (['start', 'end', 'spreadOverride'], {}), '(start, end, spreadOverride)\n', (656, 684), False, 'from python_ghost_cursor.shared._math import Vector, magnitude, direction, bezierCurve\n'), ((848, 876), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'steps'], {}), '(0.0, 1.0, steps)\n', (859, 876), True, 'import numpy as np\n'), ((567, 593), 'python_ghost_cursor.shared._math.Vector', 'Vector', (["end['x']", "end['y']"], {}), "(end['x'], end['y'])\n", (573, 593), False, 'from python_ghost_cursor.shared._math import Vector, magnitude, direction, bezierCurve\n'), ((732, 747), 'random.random', 'random.random', ([], {}), '()\n', (745, 747), False, 'import random\n'), ((1434, 1449), 'python_ghost_cursor.shared._math.Vector', 'Vector', ([], {}), '(**start)\n', (1440, 1449), False, 'from python_ghost_cursor.shared._math import Vector, magnitude, direction, bezierCurve\n'), ((1451, 1464), 'python_ghost_cursor.shared._math.Vector', 'Vector', ([], {}), '(**end)\n', (1457, 1464), False, 'from python_ghost_cursor.shared._math import Vector, magnitude, direction, bezierCurve\n'), ((986, 1020), 'python_ghost_cursor.shared._math.Vector', 'Vector', (['points[0][i]', 'points[1][i]'], {}), '(points[0][i], points[1][i])\n', (992, 1020), False, 'from python_ghost_cursor.shared._math import Vector, magnitude, direction, bezierCurve\n'), ((1323, 1338), 'python_ghost_cursor.shared._math.direction', 'direction', (['a', 'b'], {}), '(a, b)\n', (1332, 1338), False, 'from python_ghost_cursor.shared._math import Vector, magnitude, direction, bezierCurve\n'), ((1997, 2012), 'random.random', 'random.random', ([], {}), '()\n', (2010, 2012), False, 'import random\n'), ((2103, 2118), 'random.random', 'random.random', ([], {}), '()\n', (2116, 2118), False, 'import random\n')] |
# Data processing imports
import scipy.io as io
import numpy as np
from pyDOE import lhs
# Plotting imports
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.interpolate import griddata
import matplotlib.gridspec as gridspec
def load_dataset(file):
data = io.loadmat(file)
return data['x'], data['t'], data['usol'].T
# Inference
def preprocess_data_continuous_inference(file, Nu = 100, Nf = 10000):
x, t, u_exact = load_dataset(file)
X, T = np.meshgrid(x, t)
test_X = np.hstack([X.flatten()[:,None], T.flatten()[:,None]])
test_u = u_exact.flatten()[:,None]
# Sampling for initial and boundary conditions
x_i = np.hstack([X[:1,:].T,T[:1,:].T]) # Initial
u_i = u_exact[:1,:].T
x_b1 = np.hstack([X[:,:1], T[:,:1]]) # Boundary 1
u_b1 = u_exact[:,:1]
x_b2 = np.hstack([X[:,-1:], T[:,-1:]]) # Boundary 2
u_b2 = u_exact[:,-1:]
train_X_u = np.vstack([x_i, x_b1, x_b2])
train_u = np.vstack([u_i, u_b1, u_b2])
# Domain bounds for Lattice Hypercube Sampling
lb = test_X.min(0)
ub = test_X.max(0)
collocation_points = lb + (ub-lb)*lhs(2, Nf) # Samples (Nf x 2) points and scales them to be in the domain
train_X_f = np.vstack([collocation_points, train_X_u])
# Restrics the boundary conditions to only Nu random points
sample = np.random.choice(train_X_u.shape[0], size = Nu)
train_X_u = train_X_u[sample]
train_u = train_u[sample]
return x, t, u_exact, X, T, lb, ub, train_X_u, train_u, train_X_f, test_X, test_u
def plot_results_continuous_inference(x, t, X, T, u_exact, u_pred, train_X_u, train_X_f, train_u, test_X):
u_pred = griddata(test_X, u_pred.flatten(), (X, T), method='cubic')
fig = plt.figure(figsize = (10, 9.5))
ax = plt.gca()
ax.axis('off')
fig.patch.set_facecolor('white')
####### Row 0: u(t,x) ##################
gs0 = gridspec.GridSpec(1, 2)
gs0.update(top=1-0.06, bottom=1-1/3, left=0.15, right=0.85, wspace=0)
ax = plt.subplot(gs0[:, :])
h = ax.imshow(u_pred.T, interpolation='nearest', cmap='rainbow',
extent=[t.min(), t.max(), x.min(), x.max()],
origin='lower', aspect='auto')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(h, cax=cax)
ax.plot(train_X_u[:,1], train_X_u[:,0], 'kx', markersize = 4, clip_on = False)
ax.plot(train_X_f[:,1], train_X_f[:,0], 'k.', markersize = 1, clip_on = False)
line = np.linspace(x.min(), x.max(), 2)[:,None]
ax.plot(t[25]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.plot(t[50]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.plot(t[75]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.set_xlabel('$t$')
ax.set_ylabel('$x$')
# ax.legend(frameon=False, loc = 'best')
ax.set_title('$u(t,x)$', fontsize = 10)
####### Row 1: u(t,x) slices ##################
gs1 = gridspec.GridSpec(2, 3)
gs1.update(top=1-12/30, bottom=0, left=0.1, right=0.9, wspace=0.5)
ax = plt.subplot(gs1[0, 0])
ax.plot(x,u_exact[0,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[0,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.set_title('$t = 0$', fontsize = 10)
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax = plt.subplot(gs1[0, 1])
ax.plot(x,u_exact[24,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[24,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.set_title('$t = 0.25$', fontsize = 10)
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax = plt.subplot(gs1[0, 2])
ax.plot(x,u_exact[49,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[49,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 0.50$', fontsize = 10)
ax = plt.subplot(gs1[1, 0])
ax.plot(x,u_exact[74,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[74,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 0.75$', fontsize = 10)
ax = plt.subplot(gs1[1, 1])
ax.plot(x,u_exact[99,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[99,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 1.00$', fontsize = 10)
ax.legend(loc='center', bbox_to_anchor=(2.5, 0.6), ncol=5, frameon=False)
plt.show()
# Identification
def preprocess_data_continuous_identification(file, N = 2000, noise = 0.0):
x, t, u_exact = load_dataset(file)
X, T = np.meshgrid(x, t)
test_X = np.hstack([X.flatten()[:,None], T.flatten()[:,None]])
test_u = u_exact.flatten()[:,None]
# Domain bounds for Lattice Hypercube Sampling
lb = test_X.min(0)
ub = test_X.max(0)
# Sample N random points
sample = np.random.choice(test_X.shape[0], size = N)
train_X = test_X[sample]
train_u = test_u[sample]
train_u = train_u + noise*np.std(train_u)*np.random.randn(train_u.shape[0], train_u.shape[1])
return x, t, u_exact, X, T, lb, ub, train_X, train_u, test_X, test_u
def plot_results_continuous_identification(x, t, X, T, u_exact, u_pred, train_X, train_u, test_X, lambda_1, lambda_2):
u_pred = griddata(test_X, u_pred.flatten(), (X, T), method='cubic')
fig = plt.figure(figsize = (10, 9.5))
ax = plt.gca()
ax.axis('off')
fig.patch.set_facecolor('white')
####### Row 0: u(t,x) ##################
gs0 = gridspec.GridSpec(1, 2)
gs0.update(top=1-0.06, bottom=1-1/3, left=0.15, right=0.85, wspace=0)
ax = plt.subplot(gs0[:, :])
h = ax.imshow(u_pred.T, interpolation='nearest', cmap='rainbow',
extent=[t.min(), t.max(), x.min(), x.max()],
origin='lower', aspect='auto')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(h, cax=cax)
ax.plot(train_X[:,1], train_X[:,0], 'k.', markersize = 2, clip_on = False)
line = np.linspace(x.min(), x.max(), 2)[:,None]
ax.plot(t[25]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.plot(t[50]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.plot(t[75]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.set_xlabel('$t$')
ax.set_ylabel('$x$')
# ax.legend(frameon=False, loc = 'best')
ax.set_title('$u(t,x)$', fontsize = 10)
####### Row 1: u(t,x) slices ##################
gs1 = gridspec.GridSpec(2, 3)
gs1.update(top=1-12/30, bottom=0, left=0.1, right=0.9, wspace=0.5)
ax = plt.subplot(gs1[0, 0])
ax.plot(x,u_exact[0,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[0,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.set_title('$t = 0$', fontsize = 10)
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax = plt.subplot(gs1[0, 1])
ax.plot(x,u_exact[24,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[24,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.set_title('$t = 0.25$', fontsize = 10)
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax = plt.subplot(gs1[0, 2])
ax.plot(x,u_exact[49,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[49,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 0.50$', fontsize = 10)
ax = plt.subplot(gs1[1, 0])
ax.plot(x,u_exact[74,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[74,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 0.75$', fontsize = 10)
ax = plt.subplot(gs1[1, 1])
ax.plot(x,u_exact[99,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,u_pred[99,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 1.00$', fontsize = 10)
ax.legend(loc='center', bbox_to_anchor=(1.8, 0.3), ncol=5, frameon=False)
# Prediction
ax = plt.subplot(gs1[1, 2])
ax.axis('off')
s1 = '$\begin{tabular}{ |c|c| } \hline Correct PDE & $u_t + u u_x - 0.0031831 u_{xx} = 0$ \\ \hline Identified PDE (clean data) & '
s2 = '$u_t + %.5f u u_x - %.7f u_{xx} = 0$ \\ \hline ' % (lambda_1, lambda_2)
# s3 = r'Identified PDE (1\% noise) & '
# s4 = r'$u_t + %.5f u u_x - %.7f u_{xx} = 0$ \\ \hline ' % (lambda_1_value_noisy, lambda_2_value_noisy)
s3 = '\end{tabular}$'
s = s1+s2+s3
ax.text(-0.3,0.5,f'Correct PDE: $u_t + u u_x - 0.0031831 u_{{xx}} = 0$ \n\t\t\t$\lambda_1$: {lambda_1:.5f}, $\lambda_2$: {lambda_2:.5f}')
plt.show()
| [
"mpl_toolkits.axes_grid1.make_axes_locatable",
"matplotlib.pyplot.subplot",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"scipy.io.loadmat",
"matplotlib.pyplot.gca",
"pyDOE.lhs",
"numpy.random.randn",
"numpy.std",
"numpy.ones",
"numpy.hstack",
"matplotlib.pyplot.figure",
"numpy.random.choice"... | [((311, 327), 'scipy.io.loadmat', 'io.loadmat', (['file'], {}), '(file)\n', (321, 327), True, 'import scipy.io as io\n'), ((510, 527), 'numpy.meshgrid', 'np.meshgrid', (['x', 't'], {}), '(x, t)\n', (521, 527), True, 'import numpy as np\n'), ((700, 735), 'numpy.hstack', 'np.hstack', (['[X[:1, :].T, T[:1, :].T]'], {}), '([X[:1, :].T, T[:1, :].T])\n', (709, 735), True, 'import numpy as np\n'), ((780, 811), 'numpy.hstack', 'np.hstack', (['[X[:, :1], T[:, :1]]'], {}), '([X[:, :1], T[:, :1]])\n', (789, 811), True, 'import numpy as np\n'), ((859, 892), 'numpy.hstack', 'np.hstack', (['[X[:, -1:], T[:, -1:]]'], {}), '([X[:, -1:], T[:, -1:]])\n', (868, 892), True, 'import numpy as np\n'), ((951, 979), 'numpy.vstack', 'np.vstack', (['[x_i, x_b1, x_b2]'], {}), '([x_i, x_b1, x_b2])\n', (960, 979), True, 'import numpy as np\n'), ((994, 1022), 'numpy.vstack', 'np.vstack', (['[u_i, u_b1, u_b2]'], {}), '([u_i, u_b1, u_b2])\n', (1003, 1022), True, 'import numpy as np\n'), ((1257, 1299), 'numpy.vstack', 'np.vstack', (['[collocation_points, train_X_u]'], {}), '([collocation_points, train_X_u])\n', (1266, 1299), True, 'import numpy as np\n'), ((1383, 1428), 'numpy.random.choice', 'np.random.choice', (['train_X_u.shape[0]'], {'size': 'Nu'}), '(train_X_u.shape[0], size=Nu)\n', (1399, 1428), True, 'import numpy as np\n'), ((1782, 1811), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 9.5)'}), '(figsize=(10, 9.5))\n', (1792, 1811), True, 'import matplotlib.pyplot as plt\n'), ((1823, 1832), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1830, 1832), True, 'import matplotlib.pyplot as plt\n'), ((1945, 1968), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(2)'], {}), '(1, 2)\n', (1962, 1968), True, 'import matplotlib.gridspec as gridspec\n'), ((2052, 2074), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs0[:, :]'], {}), '(gs0[:, :])\n', (2063, 2074), True, 'import matplotlib.pyplot as plt\n'), ((2272, 2295), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (2291, 2295), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((2992, 3015), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(2)', '(3)'], {}), '(2, 3)\n', (3009, 3015), True, 'import matplotlib.gridspec as gridspec\n'), ((3097, 3119), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 0]'], {}), '(gs1[0, 0])\n', (3108, 3119), True, 'import matplotlib.pyplot as plt\n'), ((3443, 3465), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 1]'], {}), '(gs1[0, 1])\n', (3454, 3465), True, 'import matplotlib.pyplot as plt\n'), ((3794, 3816), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 2]'], {}), '(gs1[0, 2])\n', (3805, 3816), True, 'import matplotlib.pyplot as plt\n'), ((4145, 4167), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[1, 0]'], {}), '(gs1[1, 0])\n', (4156, 4167), True, 'import matplotlib.pyplot as plt\n'), ((4496, 4518), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[1, 1]'], {}), '(gs1[1, 1])\n', (4507, 4518), True, 'import matplotlib.pyplot as plt\n'), ((4920, 4930), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4928, 4930), True, 'import matplotlib.pyplot as plt\n'), ((5082, 5099), 'numpy.meshgrid', 'np.meshgrid', (['x', 't'], {}), '(x, t)\n', (5093, 5099), True, 'import numpy as np\n'), ((5360, 5401), 'numpy.random.choice', 'np.random.choice', (['test_X.shape[0]'], {'size': 'N'}), '(test_X.shape[0], size=N)\n', (5376, 5401), True, 'import numpy as np\n'), ((5847, 5876), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 9.5)'}), '(figsize=(10, 9.5))\n', (5857, 5876), True, 'import matplotlib.pyplot as plt\n'), ((5888, 5897), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5895, 5897), True, 'import matplotlib.pyplot as plt\n'), ((6010, 6033), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(2)'], {}), '(1, 2)\n', (6027, 6033), True, 'import matplotlib.gridspec as gridspec\n'), ((6117, 6139), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs0[:, :]'], {}), '(gs0[:, :])\n', (6128, 6139), True, 'import matplotlib.pyplot as plt\n'), ((6337, 6360), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (6356, 6360), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((6970, 6993), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(2)', '(3)'], {}), '(2, 3)\n', (6987, 6993), True, 'import matplotlib.gridspec as gridspec\n'), ((7075, 7097), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 0]'], {}), '(gs1[0, 0])\n', (7086, 7097), True, 'import matplotlib.pyplot as plt\n'), ((7421, 7443), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 1]'], {}), '(gs1[0, 1])\n', (7432, 7443), True, 'import matplotlib.pyplot as plt\n'), ((7772, 7794), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 2]'], {}), '(gs1[0, 2])\n', (7783, 7794), True, 'import matplotlib.pyplot as plt\n'), ((8123, 8145), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[1, 0]'], {}), '(gs1[1, 0])\n', (8134, 8145), True, 'import matplotlib.pyplot as plt\n'), ((8474, 8496), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[1, 1]'], {}), '(gs1[1, 1])\n', (8485, 8496), True, 'import matplotlib.pyplot as plt\n'), ((8927, 8949), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[1, 2]'], {}), '(gs1[1, 2])\n', (8938, 8949), True, 'import matplotlib.pyplot as plt\n'), ((9543, 9553), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9551, 9553), True, 'import matplotlib.pyplot as plt\n'), ((1168, 1178), 'pyDOE.lhs', 'lhs', (['(2)', 'Nf'], {}), '(2, Nf)\n', (1171, 1178), False, 'from pyDOE import lhs\n'), ((2623, 2638), 'numpy.ones', 'np.ones', (['(2, 1)'], {}), '((2, 1))\n', (2630, 2638), True, 'import numpy as np\n'), ((2684, 2699), 'numpy.ones', 'np.ones', (['(2, 1)'], {}), '((2, 1))\n', (2691, 2699), True, 'import numpy as np\n'), ((2745, 2760), 'numpy.ones', 'np.ones', (['(2, 1)'], {}), '((2, 1))\n', (2752, 2760), True, 'import numpy as np\n'), ((5508, 5559), 'numpy.random.randn', 'np.random.randn', (['train_u.shape[0]', 'train_u.shape[1]'], {}), '(train_u.shape[0], train_u.shape[1])\n', (5523, 5559), True, 'import numpy as np\n'), ((6601, 6616), 'numpy.ones', 'np.ones', (['(2, 1)'], {}), '((2, 1))\n', (6608, 6616), True, 'import numpy as np\n'), ((6662, 6677), 'numpy.ones', 'np.ones', (['(2, 1)'], {}), '((2, 1))\n', (6669, 6677), True, 'import numpy as np\n'), ((6723, 6738), 'numpy.ones', 'np.ones', (['(2, 1)'], {}), '((2, 1))\n', (6730, 6738), True, 'import numpy as np\n'), ((5492, 5507), 'numpy.std', 'np.std', (['train_u'], {}), '(train_u)\n', (5498, 5507), True, 'import numpy as np\n')] |
import copy
from datetime import datetime
from decimal import Decimal
from unittest import TestCase
import numpy as np
import pandas as pd
import pytz
from pandas import DataFrame
from src.constants import UTC, US_EASTERN, NAN
from src.dao.dao import DAO
from src.dao.intraday_dao import IntradayDAO
from src.entity.configuration_entity import ConfigurationEntity
from src.entity.evaluation_entity import EvaluationEntity
from src.entity.forward_entity import ForwardEntity
from src.entity.intraday_entity import IntradayEntity
from src.entity.stock_entity import StockEntity
class Utils:
@staticmethod
def create_table_frame() -> DataFrame:
dates = pd.date_range('1/1/2000', periods=150, tz=UTC)
prices_aaa = np.full((150, 1), Decimal(500))
prices_bbb = copy.copy(prices_aaa)
prices_ccc = copy.copy(prices_aaa)
prices_aaa[30:60] = prices_aaa[90:120] = prices_ccc[0:30] = prices_ccc[60:90] = prices_ccc[120:150] = Decimal(
100)
prices_bbb[0:30] = NAN
tickers = ['AAA', 'BBB', 'CCC']
prices = np.hstack((prices_aaa, prices_bbb, prices_ccc))
frame = DataFrame(prices, index=dates, columns=tickers)
frame.sort_index(inplace=True, ascending=True)
return frame
@staticmethod
def assert_attributes(assertable, **kwargs):
for key, value in kwargs.items():
TestCase().assertEqual(getattr(assertable, key), value)
@staticmethod
def assert_items(assertable, **kwargs):
for key, value in kwargs.items():
TestCase().assertEqual(value, assertable[key])
@staticmethod
def persist_intraday(ticker, date, o, high, low, close, volume):
Utils.__persist_get_intraday(date.replace(tzinfo=None), np.full((1, 5), [o, high, low, close, volume]), ticker)
@staticmethod
def persist_intraday_frame():
table_aaa = np.full((150, 5), Decimal(500))
table_ccc = copy.copy(table_aaa)
table_aaa[30:60] = table_aaa[90:120] = table_ccc[0:30] = table_ccc[60:90] = table_ccc[120:150] = Decimal(100)
data = {'AAA': {'start': '1/1/2000', 'data': table_aaa},
'BBB': {'start': '31/1/2000', 'data': np.full((120, 5), Decimal(500))},
'CCC': {'start': '1/1/2000', 'data': table_ccc}}
for key, value in data.items():
Utils.__persist_get_intraday(value['start'], value['data'], key)
@staticmethod
def __persist_get_intraday(start, data, ticker):
frame, meta_data = Utils.get_intraday(start, data)
frame = frame.reset_index()
for index, row in frame.iterrows():
intraday = IntradayDAO.init(row, ticker, meta_data['6. Time Zone'])
DAO.persist(intraday)
@staticmethod
def get_intraday(start='1/1/2000', data=np.full((10, 5), Decimal(500))):
dates = pd.date_range(start, periods=len(data))
columns = ['1. open', '2. high', '3. low', '4. close', '5. volume']
frame = DataFrame(data, columns=columns)
frame['date'] = dates
frame.sort_index(inplace=True, ascending=False)
meta_data = {'6. Time Zone': US_EASTERN}
return frame, meta_data
@staticmethod
def truncate_tables():
EvaluationEntity.query.delete()
IntradayEntity.query.delete()
ForwardEntity.query.delete()
StockEntity.query.delete()
ConfigurationEntity.query.delete()
@staticmethod
def create_datetime(date: str, timezone: str = US_EASTERN):
return pytz.timezone(timezone).localize(datetime.fromisoformat(date))
| [
"pandas.DataFrame",
"numpy.full",
"pandas.date_range",
"datetime.datetime.fromisoformat",
"decimal.Decimal",
"unittest.TestCase",
"src.entity.stock_entity.StockEntity.query.delete",
"copy.copy",
"src.entity.forward_entity.ForwardEntity.query.delete",
"src.entity.intraday_entity.IntradayEntity.quer... | [((670, 716), 'pandas.date_range', 'pd.date_range', (['"""1/1/2000"""'], {'periods': '(150)', 'tz': 'UTC'}), "('1/1/2000', periods=150, tz=UTC)\n", (683, 716), True, 'import pandas as pd\n'), ((791, 812), 'copy.copy', 'copy.copy', (['prices_aaa'], {}), '(prices_aaa)\n', (800, 812), False, 'import copy\n'), ((834, 855), 'copy.copy', 'copy.copy', (['prices_aaa'], {}), '(prices_aaa)\n', (843, 855), False, 'import copy\n'), ((966, 978), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (973, 978), False, 'from decimal import Decimal\n'), ((1080, 1127), 'numpy.hstack', 'np.hstack', (['(prices_aaa, prices_bbb, prices_ccc)'], {}), '((prices_aaa, prices_bbb, prices_ccc))\n', (1089, 1127), True, 'import numpy as np\n'), ((1144, 1191), 'pandas.DataFrame', 'DataFrame', (['prices'], {'index': 'dates', 'columns': 'tickers'}), '(prices, index=dates, columns=tickers)\n', (1153, 1191), False, 'from pandas import DataFrame\n'), ((1943, 1963), 'copy.copy', 'copy.copy', (['table_aaa'], {}), '(table_aaa)\n', (1952, 1963), False, 'import copy\n'), ((2069, 2081), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (2076, 2081), False, 'from decimal import Decimal\n'), ((2986, 3018), 'pandas.DataFrame', 'DataFrame', (['data'], {'columns': 'columns'}), '(data, columns=columns)\n', (2995, 3018), False, 'from pandas import DataFrame\n'), ((3240, 3271), 'src.entity.evaluation_entity.EvaluationEntity.query.delete', 'EvaluationEntity.query.delete', ([], {}), '()\n', (3269, 3271), False, 'from src.entity.evaluation_entity import EvaluationEntity\n'), ((3280, 3309), 'src.entity.intraday_entity.IntradayEntity.query.delete', 'IntradayEntity.query.delete', ([], {}), '()\n', (3307, 3309), False, 'from src.entity.intraday_entity import IntradayEntity\n'), ((3318, 3346), 'src.entity.forward_entity.ForwardEntity.query.delete', 'ForwardEntity.query.delete', ([], {}), '()\n', (3344, 3346), False, 'from src.entity.forward_entity import ForwardEntity\n'), ((3355, 3381), 'src.entity.stock_entity.StockEntity.query.delete', 'StockEntity.query.delete', ([], {}), '()\n', (3379, 3381), False, 'from src.entity.stock_entity import StockEntity\n'), ((3390, 3424), 'src.entity.configuration_entity.ConfigurationEntity.query.delete', 'ConfigurationEntity.query.delete', ([], {}), '()\n', (3422, 3424), False, 'from src.entity.configuration_entity import ConfigurationEntity\n'), ((756, 768), 'decimal.Decimal', 'Decimal', (['(500)'], {}), '(500)\n', (763, 768), False, 'from decimal import Decimal\n'), ((1762, 1808), 'numpy.full', 'np.full', (['(1, 5)', '[o, high, low, close, volume]'], {}), '((1, 5), [o, high, low, close, volume])\n', (1769, 1808), True, 'import numpy as np\n'), ((1909, 1921), 'decimal.Decimal', 'Decimal', (['(500)'], {}), '(500)\n', (1916, 1921), False, 'from decimal import Decimal\n'), ((2651, 2707), 'src.dao.intraday_dao.IntradayDAO.init', 'IntradayDAO.init', (['row', 'ticker', "meta_data['6. Time Zone']"], {}), "(row, ticker, meta_data['6. Time Zone'])\n", (2667, 2707), False, 'from src.dao.intraday_dao import IntradayDAO\n'), ((2720, 2741), 'src.dao.dao.DAO.persist', 'DAO.persist', (['intraday'], {}), '(intraday)\n', (2731, 2741), False, 'from src.dao.dao import DAO\n'), ((2822, 2834), 'decimal.Decimal', 'Decimal', (['(500)'], {}), '(500)\n', (2829, 2834), False, 'from decimal import Decimal\n'), ((3556, 3584), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['date'], {}), '(date)\n', (3578, 3584), False, 'from datetime import datetime\n'), ((3523, 3546), 'pytz.timezone', 'pytz.timezone', (['timezone'], {}), '(timezone)\n', (3536, 3546), False, 'import pytz\n'), ((1390, 1400), 'unittest.TestCase', 'TestCase', ([], {}), '()\n', (1398, 1400), False, 'from unittest import TestCase\n'), ((1563, 1573), 'unittest.TestCase', 'TestCase', ([], {}), '()\n', (1571, 1573), False, 'from unittest import TestCase\n'), ((2219, 2231), 'decimal.Decimal', 'Decimal', (['(500)'], {}), '(500)\n', (2226, 2231), False, 'from decimal import Decimal\n')] |
# Import packages
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from keras.models import Sequential, load_model
from keras.layers import Dense
from keras.optimizers import Adam
from keras.layers import Dropout, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
import numpy as np
import cv2
import os
# Parameters
path = 'Data'
testRatio = 0.2
valRatio = 0.2
imageDimensions = (32, 32, 3)
# Importing Data
count = 0
images = [] # List of Images
classNo = [] # Id of all the corresponding Images
myList = os.listdir(path)
noOfClasses = len(myList)
for x in range(0, noOfClasses):
myPicList = os.listdir(path+"/"+str(x))
for y in myPicList:
curImg = cv2.imread(path+"/"+str(x)+"/"+y)
curImg = cv2.resize(curImg, (32, 32))
images.append(curImg)
classNo.append(x)
# Converting Images to Numpy Array
images = np.array(images)
classNo = np.array(classNo)
# Spliting data into Train and Test
X_train, X_test, y_train, y_test = train_test_split(
images, classNo, test_size=testRatio)
X_train, X_validation, y_train, y_validation = train_test_split(
X_train, y_train, test_size=valRatio)
# Preprocessing
def preProcessing(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.equalizeHist(img)
img = img/255
return img
X_train = np.array(list(map(preProcessing, X_train)))
X_test = np.array(list(map(preProcessing, X_test)))
X_validation = np.array(list(map(preProcessing, X_validation)))
# Reshape and Transform Images
X_train = X_train.reshape(
X_train.shape[0], X_train.shape[1], X_train.shape[2], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2], 1)
X_validation = X_validation.reshape(
X_validation.shape[0], X_validation.shape[1], X_validation.shape[2], 1)
dataGen = ImageDataGenerator(width_shift_range=0.1,
height_shift_range=0.1,
zoom_range=0.2,
shear_range=0.1,
rotation_range=10)
dataGen.fit(X_train)
# One HOT ENCODING
y_train = to_categorical(y_train, noOfClasses)
y_test = to_categorical(y_test, noOfClasses)
y_validation = to_categorical(y_validation, noOfClasses)
def myModel(): # Creating model
noOfFilters = 60
sizeOfFilter1 = (5, 5)
sizeOfFilter2 = (3, 3)
sizeOfPool = (2, 2)
noOfNodes = 500
model = Sequential()
model.add((Conv2D(noOfFilters, sizeOfFilter1, input_shape=(imageDimensions[0],
imageDimensions[1], 1), activation='relu')))
model.add((Conv2D(noOfFilters, sizeOfFilter1, activation='relu')))
model.add(MaxPooling2D(pool_size=sizeOfPool))
model.add((Conv2D(noOfFilters//2, sizeOfFilter2, activation='relu')))
model.add((Conv2D(noOfFilters//2, sizeOfFilter2, activation='relu')))
model.add(MaxPooling2D(pool_size=sizeOfPool))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(noOfNodes, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(noOfClasses, activation='softmax'))
model.compile(Adam(lr=0.001), loss='categorical_crossentropy',
metrics=['accuracy'])
return model
model = myModel()
history = model.fit(X_train, y_train, validation_data=(
X_validation, y_validation), epochs=10, steps_per_epoch=2000)
# Score evaluation
score = model.evaluate(X_test, y_test, verbose=0)
# Saving model
model.save("model_trained.p")
| [
"keras.preprocessing.image.ImageDataGenerator",
"cv2.equalizeHist",
"cv2.cvtColor",
"sklearn.model_selection.train_test_split",
"keras.layers.Dropout",
"keras.layers.convolutional.MaxPooling2D",
"keras.layers.Flatten",
"keras.optimizers.Adam",
"keras.utils.np_utils.to_categorical",
"keras.layers.c... | [((676, 692), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (686, 692), False, 'import os\n'), ((1019, 1035), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (1027, 1035), True, 'import numpy as np\n'), ((1046, 1063), 'numpy.array', 'np.array', (['classNo'], {}), '(classNo)\n', (1054, 1063), True, 'import numpy as np\n'), ((1136, 1190), 'sklearn.model_selection.train_test_split', 'train_test_split', (['images', 'classNo'], {'test_size': 'testRatio'}), '(images, classNo, test_size=testRatio)\n', (1152, 1190), False, 'from sklearn.model_selection import train_test_split\n'), ((1243, 1297), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_train', 'y_train'], {'test_size': 'valRatio'}), '(X_train, y_train, test_size=valRatio)\n', (1259, 1297), False, 'from sklearn.model_selection import train_test_split\n'), ((1954, 2075), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'width_shift_range': '(0.1)', 'height_shift_range': '(0.1)', 'zoom_range': '(0.2)', 'shear_range': '(0.1)', 'rotation_range': '(10)'}), '(width_shift_range=0.1, height_shift_range=0.1,\n zoom_range=0.2, shear_range=0.1, rotation_range=10)\n', (1972, 2075), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((2239, 2275), 'keras.utils.np_utils.to_categorical', 'to_categorical', (['y_train', 'noOfClasses'], {}), '(y_train, noOfClasses)\n', (2253, 2275), False, 'from keras.utils.np_utils import to_categorical\n'), ((2285, 2320), 'keras.utils.np_utils.to_categorical', 'to_categorical', (['y_test', 'noOfClasses'], {}), '(y_test, noOfClasses)\n', (2299, 2320), False, 'from keras.utils.np_utils import to_categorical\n'), ((2336, 2377), 'keras.utils.np_utils.to_categorical', 'to_categorical', (['y_validation', 'noOfClasses'], {}), '(y_validation, noOfClasses)\n', (2350, 2377), False, 'from keras.utils.np_utils import to_categorical\n'), ((1355, 1392), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (1367, 1392), False, 'import cv2\n'), ((1403, 1424), 'cv2.equalizeHist', 'cv2.equalizeHist', (['img'], {}), '(img)\n', (1419, 1424), False, 'import cv2\n'), ((2545, 2557), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2555, 2557), False, 'from keras.models import Sequential, load_model\n'), ((889, 917), 'cv2.resize', 'cv2.resize', (['curImg', '(32, 32)'], {}), '(curImg, (32, 32))\n', (899, 917), False, 'import cv2\n'), ((2573, 2687), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['noOfFilters', 'sizeOfFilter1'], {'input_shape': '(imageDimensions[0], imageDimensions[1], 1)', 'activation': '"""relu"""'}), "(noOfFilters, sizeOfFilter1, input_shape=(imageDimensions[0],\n imageDimensions[1], 1), activation='relu')\n", (2579, 2687), False, 'from keras.layers.convolutional import Conv2D, MaxPooling2D\n'), ((2764, 2817), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['noOfFilters', 'sizeOfFilter1'], {'activation': '"""relu"""'}), "(noOfFilters, sizeOfFilter1, activation='relu')\n", (2770, 2817), False, 'from keras.layers.convolutional import Conv2D, MaxPooling2D\n'), ((2834, 2868), 'keras.layers.convolutional.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': 'sizeOfPool'}), '(pool_size=sizeOfPool)\n', (2846, 2868), False, 'from keras.layers.convolutional import Conv2D, MaxPooling2D\n'), ((2885, 2943), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(noOfFilters // 2)', 'sizeOfFilter2'], {'activation': '"""relu"""'}), "(noOfFilters // 2, sizeOfFilter2, activation='relu')\n", (2891, 2943), False, 'from keras.layers.convolutional import Conv2D, MaxPooling2D\n'), ((2959, 3017), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(noOfFilters // 2)', 'sizeOfFilter2'], {'activation': '"""relu"""'}), "(noOfFilters // 2, sizeOfFilter2, activation='relu')\n", (2965, 3017), False, 'from keras.layers.convolutional import Conv2D, MaxPooling2D\n'), ((3032, 3066), 'keras.layers.convolutional.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': 'sizeOfPool'}), '(pool_size=sizeOfPool)\n', (3044, 3066), False, 'from keras.layers.convolutional import Conv2D, MaxPooling2D\n'), ((3082, 3094), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (3089, 3094), False, 'from keras.layers import Dropout, Flatten\n'), ((3111, 3120), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3118, 3120), False, 'from keras.layers import Dropout, Flatten\n'), ((3136, 3171), 'keras.layers.Dense', 'Dense', (['noOfNodes'], {'activation': '"""relu"""'}), "(noOfNodes, activation='relu')\n", (3141, 3171), False, 'from keras.layers import Dense\n'), ((3187, 3199), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (3194, 3199), False, 'from keras.layers import Dropout, Flatten\n'), ((3215, 3255), 'keras.layers.Dense', 'Dense', (['noOfClasses'], {'activation': '"""softmax"""'}), "(noOfClasses, activation='softmax')\n", (3220, 3255), False, 'from keras.layers import Dense\n'), ((3276, 3290), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (3280, 3290), False, 'from keras.optimizers import Adam\n')] |
import os
import pytest
import numpy as np
import pyansys
from pyansys import examples
test_path = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture(scope='module')
def result():
return pyansys.read_binary(examples.rstfile)
@pytest.fixture(scope='module')
def archive():
return pyansys.Archive(examples.hexarchivefile)
def test_geometry_elements(result, archive):
r_elem = np.array(result.geometry.elem)[result._sidx_elem]
assert np.allclose(r_elem, archive.elem)
def test_geometry_nodes(result, archive):
assert np.allclose(result.geometry.nodes[:, :3], archive.nodes)
def test_geometry_nodenum(result, archive):
assert np.allclose(result.geometry.nnum, archive.nnum)
def test_results_displacement(result):
textfile = os.path.join(test_path, 'prnsol_u.txt')
nnum, r_values = result.nodal_solution(0)
a_values = np.loadtxt(textfile, skiprows=2)[:, 1:4]
assert np.allclose(r_values, a_values)
def test_results_stress(result):
_, r_values = result.nodal_stress(0)
textfile = os.path.join(test_path, 'prnsol_s.txt')
a_values = np.loadtxt(textfile, skiprows=2)[:, 1:]
# ignore nan
nanmask = ~np.isnan(r_values).any(1)
assert np.allclose(r_values[nanmask], a_values, atol=1E-1)
def test_results_pstress(result):
r_nnum, r_values = result.principal_nodal_stress(0)
textfile = os.path.join(test_path, 'prnsol_s_prin.txt')
a_values = np.loadtxt(textfile, skiprows=2)[:, 1:]
# ignore nan
nanmask = ~np.isnan(r_values).any(1)
assert np.allclose(r_values[nanmask], a_values, atol=100)
| [
"os.path.abspath",
"os.path.join",
"pyansys.read_binary",
"numpy.allclose",
"pytest.fixture",
"numpy.isnan",
"numpy.array",
"numpy.loadtxt",
"pyansys.Archive"
] | [((147, 177), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (161, 177), False, 'import pytest\n'), ((244, 274), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (258, 274), False, 'import pytest\n'), ((117, 142), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (132, 142), False, 'import os\n'), ((203, 240), 'pyansys.read_binary', 'pyansys.read_binary', (['examples.rstfile'], {}), '(examples.rstfile)\n', (222, 240), False, 'import pyansys\n'), ((301, 341), 'pyansys.Archive', 'pyansys.Archive', (['examples.hexarchivefile'], {}), '(examples.hexarchivefile)\n', (316, 341), False, 'import pyansys\n'), ((463, 496), 'numpy.allclose', 'np.allclose', (['r_elem', 'archive.elem'], {}), '(r_elem, archive.elem)\n', (474, 496), True, 'import numpy as np\n'), ((552, 608), 'numpy.allclose', 'np.allclose', (['result.geometry.nodes[:, :3]', 'archive.nodes'], {}), '(result.geometry.nodes[:, :3], archive.nodes)\n', (563, 608), True, 'import numpy as np\n'), ((666, 713), 'numpy.allclose', 'np.allclose', (['result.geometry.nnum', 'archive.nnum'], {}), '(result.geometry.nnum, archive.nnum)\n', (677, 713), True, 'import numpy as np\n'), ((770, 809), 'os.path.join', 'os.path.join', (['test_path', '"""prnsol_u.txt"""'], {}), "(test_path, 'prnsol_u.txt')\n", (782, 809), False, 'import os\n'), ((923, 954), 'numpy.allclose', 'np.allclose', (['r_values', 'a_values'], {}), '(r_values, a_values)\n', (934, 954), True, 'import numpy as np\n'), ((1046, 1085), 'os.path.join', 'os.path.join', (['test_path', '"""prnsol_s.txt"""'], {}), "(test_path, 'prnsol_s.txt')\n", (1058, 1085), False, 'import os\n'), ((1211, 1261), 'numpy.allclose', 'np.allclose', (['r_values[nanmask]', 'a_values'], {'atol': '(0.1)'}), '(r_values[nanmask], a_values, atol=0.1)\n', (1222, 1261), True, 'import numpy as np\n'), ((1370, 1414), 'os.path.join', 'os.path.join', (['test_path', '"""prnsol_s_prin.txt"""'], {}), "(test_path, 'prnsol_s_prin.txt')\n", (1382, 1414), False, 'import os\n'), ((1540, 1590), 'numpy.allclose', 'np.allclose', (['r_values[nanmask]', 'a_values'], {'atol': '(100)'}), '(r_values[nanmask], a_values, atol=100)\n', (1551, 1590), True, 'import numpy as np\n'), ((402, 432), 'numpy.array', 'np.array', (['result.geometry.elem'], {}), '(result.geometry.elem)\n', (410, 432), True, 'import numpy as np\n'), ((871, 903), 'numpy.loadtxt', 'np.loadtxt', (['textfile'], {'skiprows': '(2)'}), '(textfile, skiprows=2)\n', (881, 903), True, 'import numpy as np\n'), ((1101, 1133), 'numpy.loadtxt', 'np.loadtxt', (['textfile'], {'skiprows': '(2)'}), '(textfile, skiprows=2)\n', (1111, 1133), True, 'import numpy as np\n'), ((1430, 1462), 'numpy.loadtxt', 'np.loadtxt', (['textfile'], {'skiprows': '(2)'}), '(textfile, skiprows=2)\n', (1440, 1462), True, 'import numpy as np\n'), ((1174, 1192), 'numpy.isnan', 'np.isnan', (['r_values'], {}), '(r_values)\n', (1182, 1192), True, 'import numpy as np\n'), ((1503, 1521), 'numpy.isnan', 'np.isnan', (['r_values'], {}), '(r_values)\n', (1511, 1521), True, 'import numpy as np\n')] |
#from tensorlayer.prepro import *
import numpy as np
import skimage.measure
import scipy
from time import localtime, strftime
import logging
import tensorflow as tf
import os
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
def distort_img(x):
x = (x + 1.) / 2.
# x = flip_axis(x, axis=1, is_random=True)
# x = elastic_transform(x, alpha=255 * 3, sigma=255 * 0.10, is_random=True)
x = rotation(x, rg=10, is_random=True, fill_mode='constant')
x = shift(x, wrg=0.10, hrg=0.10, is_random=True, fill_mode='constant')
x = zoom(x, zoom_range=[0.90, 1.10], is_random=True, fill_mode='constant')
x = brightness(x, gamma=0.05, is_random=True)
x = x * 2 - 1
return x
def to_bad_img(x, mask):
x = (x + 1.) / 2.
fft = scipy.fftpack.fft2(x[:, :, 0])
fft = scipy.fftpack.fftshift(fft)
fft = fft * mask
fft = scipy.fftpack.ifftshift(fft)
x = scipy.fftpack.ifft2(fft)
x = np.abs(x)
x = x * 2 - 1
return x[:, :, np.newaxis]
def fft_abs_for_map_fn(x):
x = (x + 1.) / 2.
x_complex = tf.complex(x, tf.zeros_like(x))[:, :, 0]
fft = tf.spectral.fft2d(x_complex)
fft_abs = tf.abs(fft)
return fft_abs
def ssim(data):
x_good, x_bad = data
x_good = np.squeeze(x_good)
x_bad = np.squeeze(x_bad)
ssim_res = skimage.measure.compare_ssim(x_good, x_bad)
return ssim_res
def psnr(data):
x_good, x_bad = data
psnr_res = skimage.measure.compare_psnr(x_good, x_bad)
return psnr_res
def vgg_prepro(x):
x = imresize(x, [244, 244], interp='bilinear', mode=None)
x = np.tile(x, 3)
x = x / 127.5 - 1
return x
def logging_setup(log_dir):
current_time_str = strftime("%Y_%m_%d_%H_%M_%S", localtime())
log_all_filename = os.path.join(log_dir, 'log_all_{}.log'.format(current_time_str))
log_eval_filename = os.path.join(log_dir, 'log_eval_{}.log'.format(current_time_str))
log_all = logging.getLogger('log_all')
log_all.setLevel(logging.DEBUG)
log_all.addHandler(logging.FileHandler(log_all_filename))
log_eval = logging.getLogger('log_eval')
log_eval.setLevel(logging.INFO)
log_eval.addHandler(logging.FileHandler(log_eval_filename))
log_50_filename = os.path.join(log_dir, 'log_50_images_testing_{}.log'.format(current_time_str))
log_50 = logging.getLogger('log_50')
log_50.setLevel(logging.DEBUG)
log_50.addHandler(logging.FileHandler(log_50_filename))
return log_all, log_eval, log_50, log_all_filename, log_eval_filename, log_50_filename
def apply_random_deformation(images):
assert len(images.shape) == 4
[batch_length, x, y, z] = images.shape
for i in range(0, batch_length):
images[i, :, :, :] = random_elastic_deformation(images[i, :, :, :])
return images
def random_elastic_deformation(image, alpha=500, sigma=20, mode='nearest',
random_state=None):
"""Elastic deformation of images as described in [Simard2003]_.
.. [Simard2003] <NAME> Platt, "Best Practices for
Convolutional Neural Networks applied to Visual Document Analysis", in
Proc. of the International Conference on Document Analysis and
Recognition, 2003.
"""
assert len(image.shape) == 3
if random_state is None:
random_state = np.random.RandomState(None)
height, width, channels = image.shape
dx = gaussian_filter(2 * random_state.rand(height, width) - 1,
sigma, mode="constant", cval=0) * alpha
dy = gaussian_filter(2 * random_state.rand(height, width) - 1,
sigma, mode="constant", cval=0) * alpha
x, y = np.meshgrid(np.arange(height), np.arange(width), indexing='ij')
indices = (np.repeat(np.ravel(x + dx), channels),
np.repeat(np.ravel(y + dy), channels),
np.tile(np.arange(channels), height * width))
values = map_coordinates(image, indices, order=1, mode=mode)
return values.reshape((height, width, channels))
if __name__ == "__main__":
pass | [
"tensorflow.spectral.fft2d",
"tensorflow.abs",
"numpy.abs",
"logging.FileHandler",
"numpy.ravel",
"scipy.fftpack.fftshift",
"tensorflow.zeros_like",
"logging.getLogger",
"numpy.random.RandomState",
"scipy.ndimage.interpolation.map_coordinates",
"scipy.fftpack.ifft2",
"time.localtime",
"scipy... | [((810, 840), 'scipy.fftpack.fft2', 'scipy.fftpack.fft2', (['x[:, :, 0]'], {}), '(x[:, :, 0])\n', (828, 840), False, 'import scipy\n'), ((851, 878), 'scipy.fftpack.fftshift', 'scipy.fftpack.fftshift', (['fft'], {}), '(fft)\n', (873, 878), False, 'import scipy\n'), ((910, 938), 'scipy.fftpack.ifftshift', 'scipy.fftpack.ifftshift', (['fft'], {}), '(fft)\n', (933, 938), False, 'import scipy\n'), ((947, 971), 'scipy.fftpack.ifft2', 'scipy.fftpack.ifft2', (['fft'], {}), '(fft)\n', (966, 971), False, 'import scipy\n'), ((980, 989), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (986, 989), True, 'import numpy as np\n'), ((1157, 1185), 'tensorflow.spectral.fft2d', 'tf.spectral.fft2d', (['x_complex'], {}), '(x_complex)\n', (1174, 1185), True, 'import tensorflow as tf\n'), ((1200, 1211), 'tensorflow.abs', 'tf.abs', (['fft'], {}), '(fft)\n', (1206, 1211), True, 'import tensorflow as tf\n'), ((1287, 1305), 'numpy.squeeze', 'np.squeeze', (['x_good'], {}), '(x_good)\n', (1297, 1305), True, 'import numpy as np\n'), ((1318, 1335), 'numpy.squeeze', 'np.squeeze', (['x_bad'], {}), '(x_bad)\n', (1328, 1335), True, 'import numpy as np\n'), ((1628, 1641), 'numpy.tile', 'np.tile', (['x', '(3)'], {}), '(x, 3)\n', (1635, 1641), True, 'import numpy as np\n'), ((1966, 1994), 'logging.getLogger', 'logging.getLogger', (['"""log_all"""'], {}), "('log_all')\n", (1983, 1994), False, 'import logging\n'), ((2109, 2138), 'logging.getLogger', 'logging.getLogger', (['"""log_eval"""'], {}), "('log_eval')\n", (2126, 2138), False, 'import logging\n'), ((2355, 2382), 'logging.getLogger', 'logging.getLogger', (['"""log_50"""'], {}), "('log_50')\n", (2372, 2382), False, 'import logging\n'), ((3933, 3984), 'scipy.ndimage.interpolation.map_coordinates', 'map_coordinates', (['image', 'indices'], {'order': '(1)', 'mode': 'mode'}), '(image, indices, order=1, mode=mode)\n', (3948, 3984), False, 'from scipy.ndimage.interpolation import map_coordinates\n'), ((1760, 1771), 'time.localtime', 'localtime', ([], {}), '()\n', (1769, 1771), False, 'from time import localtime, strftime\n'), ((2054, 2091), 'logging.FileHandler', 'logging.FileHandler', (['log_all_filename'], {}), '(log_all_filename)\n', (2073, 2091), False, 'import logging\n'), ((2199, 2237), 'logging.FileHandler', 'logging.FileHandler', (['log_eval_filename'], {}), '(log_eval_filename)\n', (2218, 2237), False, 'import logging\n'), ((2440, 2476), 'logging.FileHandler', 'logging.FileHandler', (['log_50_filename'], {}), '(log_50_filename)\n', (2459, 2476), False, 'import logging\n'), ((3338, 3365), 'numpy.random.RandomState', 'np.random.RandomState', (['None'], {}), '(None)\n', (3359, 3365), True, 'import numpy as np\n'), ((3698, 3715), 'numpy.arange', 'np.arange', (['height'], {}), '(height)\n', (3707, 3715), True, 'import numpy as np\n'), ((3717, 3733), 'numpy.arange', 'np.arange', (['width'], {}), '(width)\n', (3726, 3733), True, 'import numpy as np\n'), ((1120, 1136), 'tensorflow.zeros_like', 'tf.zeros_like', (['x'], {}), '(x)\n', (1133, 1136), True, 'import tensorflow as tf\n'), ((3775, 3791), 'numpy.ravel', 'np.ravel', (['(x + dx)'], {}), '(x + dx)\n', (3783, 3791), True, 'import numpy as np\n'), ((3829, 3845), 'numpy.ravel', 'np.ravel', (['(y + dy)'], {}), '(y + dy)\n', (3837, 3845), True, 'import numpy as np\n'), ((3881, 3900), 'numpy.arange', 'np.arange', (['channels'], {}), '(channels)\n', (3890, 3900), True, 'import numpy as np\n')] |
# 你好, 欢迎使用 EF 饮食计算器
# 你只需要改两个数字就可以使用了:
heat_required = 2500 # 请把数字2500改成你所需要摄入的总能量
required_cp_ratio=2.5 # 如果你希望碳水提供的能量是蛋白质提供的能能量的三倍, 就把2改成3
# 按照这个格式添加你需要的食物数据
# '鸡胸肉': [7.72, 0, 29.55] 的意思是:
# 食物名称:鸡胸肉
# 每100g鸡胸肉含有7.72g脂肪
# 每100g鸡胸肉含有0g碳水化合物
# 每100g鸡胸肉含有29.55g脂肪
# 如果要添加数据, 需要在 '蒸南瓜': [0.07, 5.33, 0.8] 后面加入一条新数据
# 注意, 每个食物的数据之间要用逗号隔开
data_dict = {'鸡胸肉': [7.72, 0, 29.55], '米饭': [0.33, 25.86, 2.60], '红薯': [0.05, 20.45, 1.57], '牛排': [15.01, 0, 27.29], '蒸南瓜': [0.07, 5.33, 0.8],'面包':[3.29,50.61,7.64],'可口可乐':[0,10.6,0]}
# 下面的不需要看
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
#-----------
import numpy as np
import pandas as pd
import time
start=time.time()
def data_function(data_dict):
data = pd.DataFrame(data_dict)
data.shape[1]
for i in range(data.shape[0]):
data.loc[i] = pd.to_numeric(data.iloc[i, :], errors='coerce')
data_ndarray = np.array([data.iloc[0], data.iloc[1], data.iloc[2]])
df = pd.DataFrame(np.zeros((data.shape[1], 1)))
df.columns = ['food_type']
df['food_type'] = data.columns
df['fat'] = pd.Series(data_ndarray[0, :])
df['carbohydrate'] = pd.Series(data_ndarray[1, :])
df['protein'] = pd.Series(data_ndarray[2, :])
return df
nutrition_information=data_function(data_dict)
nutrition_information['heat_per_gram']= (nutrition_information['fat'] * 9 + nutrition_information['carbohydrate'] * 4 + nutrition_information['protein'] * 4) / 100
food_type_num=nutrition_information.shape[0]
def weight_generator(number):
w=np.random.random(number)
return w/sum(w)
fat=np.array(nutrition_information.iloc[:, 1])
carbohydrate=np.array(nutrition_information.iloc[:, 2])
protein=np.array(nutrition_information.iloc[:, 3])
nutrition_matrix= np.array([fat, carbohydrate, protein]) / 100
play_times=12000
fcp0=np.zeros((play_times, 3))
weight_container=np.zeros((play_times,food_type_num))
for i in range(play_times):
w=weight_generator(food_type_num)
fcp0[i, :]= np.dot(nutrition_matrix, w)
weight_container[i,:]=w
fcp1=pd.DataFrame()
fcp1['fat']=fcp0[:,0]
fcp1['carb']=fcp0[:,1]
fcp1['protein']=fcp0[:,2]
permitted_volatility_percentage=0.05
fcp2=pd.DataFrame()
fcp2['p_f']=fcp1['protein']/fcp1['fat']
fcp2['c_p']=fcp1['carb']/fcp1['protein']
fcp2['lower_b']=required_cp_ratio*(1-permitted_volatility_percentage)
fcp2['upper_b']=required_cp_ratio*(1+permitted_volatility_percentage)
proper_ratio_position=np.array(fcp2.query('lower_b<c_p<upper_b').index)
if proper_ratio_position.shape[0]<5:
print('请再运行一次')
else:
ratio_with_best_pf_positon = fcp2.loc[fcp2.query('lower_b<c_p<upper_b').index].iloc[:, 0].idxmax()
the_one = weight_container[ratio_with_best_pf_positon]
heat = np.array(nutrition_information['heat_per_gram'])
per_gram_heat = np.dot(the_one,heat)
eatfolio_mass = heat_required / per_gram_heat
components = eatfolio_mass * the_one
output='你好, 欢迎使用EF, 你的食谱如下:\n'
for i in range(nutrition_information.shape[0]):
output= output +'\n' + str(nutrition_information.iloc[i, 0]) + ' ' + str(round(components[i], 1)) + 'g'
fat_taken = str(round((np.dot(nutrition_matrix, the_one) * eatfolio_mass)[0], 1))
carbohydrate_taken = (str(round((np.dot(nutrition_matrix, the_one) * eatfolio_mass)[1], 1)))
protein_taken = str(round((np.dot(nutrition_matrix, the_one) * eatfolio_mass)[2], 1))
output += "\n\n你将摄入:"
output += '\n' + fat_taken + 'g 脂肪'
output += '\n' + carbohydrate_taken + 'g 碳水化合物'
output += '\n' + protein_taken + 'g 蛋白质'
end=time.time()
duration=round(end-start,4)
print(output)
print(f'\n运行用时:{duration}s')
print('计算使用食物营养成分来源如下:')
print('https://www.fatsecret.cn/%E7%83%AD%E9%87%8F%E8%90%A5%E5%85%BB/search?q=') | [
"pandas.DataFrame",
"numpy.zeros",
"time.time",
"numpy.random.random",
"numpy.array",
"pandas.Series",
"numpy.dot",
"pandas.to_numeric"
] | [((909, 920), 'time.time', 'time.time', ([], {}), '()\n', (918, 920), False, 'import time\n'), ((1808, 1850), 'numpy.array', 'np.array', (['nutrition_information.iloc[:, 1]'], {}), '(nutrition_information.iloc[:, 1])\n', (1816, 1850), True, 'import numpy as np\n'), ((1864, 1906), 'numpy.array', 'np.array', (['nutrition_information.iloc[:, 2]'], {}), '(nutrition_information.iloc[:, 2])\n', (1872, 1906), True, 'import numpy as np\n'), ((1915, 1957), 'numpy.array', 'np.array', (['nutrition_information.iloc[:, 3]'], {}), '(nutrition_information.iloc[:, 3])\n', (1923, 1957), True, 'import numpy as np\n'), ((2044, 2069), 'numpy.zeros', 'np.zeros', (['(play_times, 3)'], {}), '((play_times, 3))\n', (2052, 2069), True, 'import numpy as np\n'), ((2087, 2124), 'numpy.zeros', 'np.zeros', (['(play_times, food_type_num)'], {}), '((play_times, food_type_num))\n', (2095, 2124), True, 'import numpy as np\n'), ((2270, 2284), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2282, 2284), True, 'import pandas as pd\n'), ((2399, 2413), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2411, 2413), True, 'import pandas as pd\n'), ((962, 985), 'pandas.DataFrame', 'pd.DataFrame', (['data_dict'], {}), '(data_dict)\n', (974, 985), True, 'import pandas as pd\n'), ((1128, 1180), 'numpy.array', 'np.array', (['[data.iloc[0], data.iloc[1], data.iloc[2]]'], {}), '([data.iloc[0], data.iloc[1], data.iloc[2]])\n', (1136, 1180), True, 'import numpy as np\n'), ((1315, 1344), 'pandas.Series', 'pd.Series', (['data_ndarray[0, :]'], {}), '(data_ndarray[0, :])\n', (1324, 1344), True, 'import pandas as pd\n'), ((1370, 1399), 'pandas.Series', 'pd.Series', (['data_ndarray[1, :]'], {}), '(data_ndarray[1, :])\n', (1379, 1399), True, 'import pandas as pd\n'), ((1420, 1449), 'pandas.Series', 'pd.Series', (['data_ndarray[2, :]'], {}), '(data_ndarray[2, :])\n', (1429, 1449), True, 'import pandas as pd\n'), ((1758, 1782), 'numpy.random.random', 'np.random.random', (['number'], {}), '(number)\n', (1774, 1782), True, 'import numpy as np\n'), ((1976, 2014), 'numpy.array', 'np.array', (['[fat, carbohydrate, protein]'], {}), '([fat, carbohydrate, protein])\n', (1984, 2014), True, 'import numpy as np\n'), ((2208, 2235), 'numpy.dot', 'np.dot', (['nutrition_matrix', 'w'], {}), '(nutrition_matrix, w)\n', (2214, 2235), True, 'import numpy as np\n'), ((2946, 2994), 'numpy.array', 'np.array', (["nutrition_information['heat_per_gram']"], {}), "(nutrition_information['heat_per_gram'])\n", (2954, 2994), True, 'import numpy as np\n'), ((3016, 3037), 'numpy.dot', 'np.dot', (['the_one', 'heat'], {}), '(the_one, heat)\n', (3022, 3037), True, 'import numpy as np\n'), ((3772, 3783), 'time.time', 'time.time', ([], {}), '()\n', (3781, 3783), False, 'import time\n'), ((1061, 1108), 'pandas.to_numeric', 'pd.to_numeric', (['data.iloc[i, :]'], {'errors': '"""coerce"""'}), "(data.iloc[i, :], errors='coerce')\n", (1074, 1108), True, 'import pandas as pd\n'), ((1203, 1231), 'numpy.zeros', 'np.zeros', (['(data.shape[1], 1)'], {}), '((data.shape[1], 1))\n', (1211, 1231), True, 'import numpy as np\n'), ((3355, 3388), 'numpy.dot', 'np.dot', (['nutrition_matrix', 'the_one'], {}), '(nutrition_matrix, the_one)\n', (3361, 3388), True, 'import numpy as np\n'), ((3451, 3484), 'numpy.dot', 'np.dot', (['nutrition_matrix', 'the_one'], {}), '(nutrition_matrix, the_one)\n', (3457, 3484), True, 'import numpy as np\n'), ((3542, 3575), 'numpy.dot', 'np.dot', (['nutrition_matrix', 'the_one'], {}), '(nutrition_matrix, the_one)\n', (3548, 3575), True, 'import numpy as np\n')] |
import os
import numpy as np
from file_handling import recording
from file_handling.file_handling_exceptions import InconsistentNChanError
class RecordingGroup(object):
"""
class for managing recordings and applying operations to multiple recording instances together
typically, a single experiment would consist of several 2 minute long recordings separated by a few minutes
example usage:
>>> root = "./my/path/to/the/directory"
>>> exp = RecordingGroup(root, trigger_index=384)
>>> for rec in exp.recordings:
>>> data = rec.get_data('ap') # load some raw data
>>> trigger_trace = data[:, exp.trigger_index]
>>> plt.plot(trigger_trace)
>>> plt.show()
"""
# FIXME: recordings must have a channel number, so self.recordings is all messed up
# TODO: exp.recordings not as a property, so that _raw_data n_chan can be put in as an argument
def __init__(self, root, trigger_index=None):
self.root = root
self.probe_type = 'Neuropixels 3A'
self.trigger_index = trigger_index
self.root = root
def raw_file_names(self, extension='.ap.bin'):
"""get all file names of a given extension"""
file_names = []
for file_name in os.listdir(self.root):
if file_name[-len(extension):] == extension:
file_names.append(file_name.split('.')[0])
return file_names
@property
def recordings(self):
"""list of recording objects associated with experiment"""
recording_list = []
for name in self.raw_file_names():
rec = recording.Recording(self.root, self.root, name, self.trigger_index)
recording_list.append(rec)
return recording_list
def common_avg_ref_all(self, n_chan=None, processing_func=None, out_root=None, trigger_idx=(-1,),
save_shortened_trigger=None, end_sample=None, start_sample=0):
"""apply common average reference normalisation to all raw files in directory"""
all_nchans = set([rec.n_chan for rec in self.recordings])
if len(all_nchans) != 1:
raise InconsistentNChanError('expected equal channel numbers for all recordings, got {}'.format(all_nchans))
for rec in self.recordings:
rec.subtract_common_avg_reference(n_chan=n_chan, start_sample=start_sample, end_sample=end_sample,
save_shortened_trigger=save_shortened_trigger, out_root=out_root,
trigger_idx=trigger_idx, processing_func=processing_func)
def concatenate_files(self, fpath_out, extension):
"""
join together all files in directory into one file. NOTE: make sure common_avg_ref_all is done first
:param string fpath_out:
:param string extension: need to specify the extension as there may be denoised data and non-denoised data e.g.
:return:
"""
fout = open(fpath_out, 'wb')
for rec in np.sort(self.recordings):
fin = open(rec.get_path(extension), 'rb') # FIXME: this is stupid
while True:
data = fin.read(2 ** 16)
if not data:
break
fout.write(data)
fin.close()
fout.close() | [
"numpy.sort",
"os.listdir",
"file_handling.recording.Recording"
] | [((1295, 1316), 'os.listdir', 'os.listdir', (['self.root'], {}), '(self.root)\n', (1305, 1316), False, 'import os\n'), ((3117, 3141), 'numpy.sort', 'np.sort', (['self.recordings'], {}), '(self.recordings)\n', (3124, 3141), True, 'import numpy as np\n'), ((1667, 1734), 'file_handling.recording.Recording', 'recording.Recording', (['self.root', 'self.root', 'name', 'self.trigger_index'], {}), '(self.root, self.root, name, self.trigger_index)\n', (1686, 1734), False, 'from file_handling import recording\n')] |
# Copyright 2020 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 IPU Embedding layer."""
import numpy as np
from tensorflow.python import ipu
from tensorflow.python import keras
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import nn
from tensorflow.python.platform import test
dataType = np.float32
def kerasIPUEmbeddingLookup(params, ids, name=None):
input_dim = params.shape[0]
output_dim = params.shape[1]
layer = ipu.layers.Embedding(
input_dim=input_dim,
output_dim=output_dim,
embeddings_initializer=keras.initializers.constant(params),
name=name)
layer.build(input_shape=ids.shape)
@def_function.function
def impl(ids):
return layer(inputs=ids)
return impl(ids)
class IPUEmbeddingLookupTest(test.TestCase):
def testEmbeddingLookup(self):
ids = constant_op.constant([[1, 2, 3]])
paras = np.array([[10], [20], [80], [40]])
emb_lookup_tf = nn.embedding_lookup(paras, ids)
emb_lookup_ipu = kerasIPUEmbeddingLookup(paras, ids, name="emb_test_0")
self.assertAllClose(emb_lookup_tf, emb_lookup_ipu)
def testEmbeddingLookupBatchSize2(self):
ids = constant_op.constant([[1, 2, 3], [3, 4, 5]])
paras = np.array([[10], [20], [80], [40], [50], [60]])
emb_lookup_tf = nn.embedding_lookup(paras, ids)
emb_lookup_ipu = kerasIPUEmbeddingLookup(paras, ids, name="emb_test_1")
self.assertAllClose(emb_lookup_tf, emb_lookup_ipu)
# Based on ipu/tests/embedding_lookup_test.py
def testEmbeddingLookupBigGather(self):
ids = np.arange(0, 8, dtype=np.int32).reshape([1, 8])
paras = np.arange(2400000, dtype=dataType).reshape([12000, 200])
result_ipu = kerasIPUEmbeddingLookup(paras, ids, name="emb_test_2")
result_np = np.take(paras, ids, axis=0)
self.assertAllClose(result_ipu, result_np)
self.assertEqual(result_ipu.shape, (1, 8, 200))
def testEmbeddingBadInputShape(self):
ids = np.arange(0, 16, dtype=np.int32)
paras = np.arange(25600, dtype=dataType).reshape([32, 200, 4])
with self.assertRaisesRegexp(ValueError, r'The input shape should be a'):
kerasIPUEmbeddingLookup(paras, ids, name="emb_test_4")
if __name__ == '__main__':
test.main()
| [
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.nn.embedding_lookup",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.keras.initializers.constant",
"numpy.take",
"numpy.array",
"numpy.arange"
] | [((2888, 2899), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (2897, 2899), False, 'from tensorflow.python.platform import test\n'), ((1529, 1562), 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[1, 2, 3]]'], {}), '([[1, 2, 3]])\n', (1549, 1562), False, 'from tensorflow.python.framework import constant_op\n'), ((1575, 1609), 'numpy.array', 'np.array', (['[[10], [20], [80], [40]]'], {}), '([[10], [20], [80], [40]])\n', (1583, 1609), True, 'import numpy as np\n'), ((1630, 1661), 'tensorflow.python.ops.nn.embedding_lookup', 'nn.embedding_lookup', (['paras', 'ids'], {}), '(paras, ids)\n', (1649, 1661), False, 'from tensorflow.python.ops import nn\n'), ((1847, 1891), 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[1, 2, 3], [3, 4, 5]]'], {}), '([[1, 2, 3], [3, 4, 5]])\n', (1867, 1891), False, 'from tensorflow.python.framework import constant_op\n'), ((1904, 1950), 'numpy.array', 'np.array', (['[[10], [20], [80], [40], [50], [60]]'], {}), '([[10], [20], [80], [40], [50], [60]])\n', (1912, 1950), True, 'import numpy as np\n'), ((1971, 2002), 'tensorflow.python.ops.nn.embedding_lookup', 'nn.embedding_lookup', (['paras', 'ids'], {}), '(paras, ids)\n', (1990, 2002), False, 'from tensorflow.python.ops import nn\n'), ((2440, 2467), 'numpy.take', 'np.take', (['paras', 'ids'], {'axis': '(0)'}), '(paras, ids, axis=0)\n', (2447, 2467), True, 'import numpy as np\n'), ((2618, 2650), 'numpy.arange', 'np.arange', (['(0)', '(16)'], {'dtype': 'np.int32'}), '(0, 16, dtype=np.int32)\n', (2627, 2650), True, 'import numpy as np\n'), ((1256, 1291), 'tensorflow.python.keras.initializers.constant', 'keras.initializers.constant', (['params'], {}), '(params)\n', (1283, 1291), False, 'from tensorflow.python import keras\n'), ((2235, 2266), 'numpy.arange', 'np.arange', (['(0)', '(8)'], {'dtype': 'np.int32'}), '(0, 8, dtype=np.int32)\n', (2244, 2266), True, 'import numpy as np\n'), ((2295, 2329), 'numpy.arange', 'np.arange', (['(2400000)'], {'dtype': 'dataType'}), '(2400000, dtype=dataType)\n', (2304, 2329), True, 'import numpy as np\n'), ((2663, 2695), 'numpy.arange', 'np.arange', (['(25600)'], {'dtype': 'dataType'}), '(25600, dtype=dataType)\n', (2672, 2695), True, 'import numpy as np\n')] |
import os
from glob import glob
import pickle
import numpy as np
import cv2
import torch
import torch.nn.functional as F
from face_detection_dsfd.face_ssd_infer import SSD
from face_detection_dsfd.data import widerface_640, TestBaseTransform
def parse_images(input, postfix='.jpg', indices=None):
out_dir = None
if len(input) == 1:
assert os.path.isfile(input[0]) or os.path.isdir(input[0]), 'input must be a file or a directory: "%s"' % input
if os.path.isfile(input[0]):
img_paths = input
out_dir = os.path.split(input[0])[0]
elif os.path.isdir(input[0]):
img_paths = sorted(glob(os.path.join(input[0], '*' + postfix)))
out_dir = input[0]
elif len(input) == 2:
list_file_path = os.path.join(input[0], input[1]) if not os.path.isfile(input[1]) else input[1]
if os.path.isdir(input[0]) and os.path.isfile(list_file_path): # Directory and list file
rel_paths = np.loadtxt(list_file_path, str)
img_paths = [os.path.join(input[0], p) for p in rel_paths]
out_dir = input[0]
img_paths = eval('img_paths[%s]' % indices) if indices is not None else img_paths
return img_paths, out_dir
def main(input, out_dir=None, indices=None, detection_model_path='weights/WIDERFace_DSFD_RES152.pth', postfix='.jpg',
out_postfix='_dsfd.pkl', image_padding=None, max_res=2048, display=False):
# Parse images
img_paths, suggested_out_dir = parse_images(input, postfix, indices)
# out_dir = suggested_out_dir if out_dir is None else out_dir
# Initialize device
cuda = True
torch.set_grad_enabled(False)
device = torch.device('cuda:{}'.format(0))
if cuda and torch.cuda.is_available():
torch.set_default_tensor_type('torch.cuda.FloatTensor')
else:
torch.set_default_tensor_type('torch.FloatTensor')
# Initialize detection model
net = SSD("test")
net.load_state_dict(torch.load(detection_model_path))
net.eval()
transform = TestBaseTransform((104, 117, 123))
cfg = widerface_640
thresh = cfg['conf_thresh']
# For each image file
for n, img_path in enumerate(img_paths):
img_name = os.path.splitext(os.path.basename(img_path))[0]
if out_dir is None:
curr_cache_path = os.path.splitext(img_path)[0] + out_postfix
else:
curr_cache_path = os.path.join(out_dir, img_name + out_postfix)
if os.path.exists(curr_cache_path):
print('[%d/%d] Skipping "%s"' % (n + 1, len(img_paths), img_name))
continue
else:
print('[%d/%d] Processing "%s"...' % (n + 1, len(img_paths), img_name))
# Process image
img = cv2.imread(img_path)
image_size = img.shape[:2]
# Scale images above the maximum resolution
scale = np.array(image_size[::-1] * 2, dtype=float)
shrink = min(max_res / np.max(np.array(image_size)), 1.0)
if shrink < 1.0:
img_scaled = cv2.resize(img, None, None, fx=shrink, fy=shrink, interpolation=cv2.INTER_LINEAR)
image_size = img_scaled.shape[:2]
frame_tensor = torch.from_numpy(transform(img_scaled)[0]).permute(2, 0, 1).unsqueeze(0).to(device)
else:
frame_tensor = torch.from_numpy(transform(img)[0]).permute(2, 0, 1).unsqueeze(0).to(device)
# Pad image
if image_padding is not None:
image_pad_size = np.round(np.array(image_size[::-1]) * image_padding).astype(int)
frame_tensor = F.pad(frame_tensor, [image_pad_size[0], image_pad_size[0],
image_pad_size[1], image_pad_size[1]], 'reflect')
image_pad_size = np.round(np.array(img.shape[1::-1]) * image_padding).astype(int)
image_size = np.round(np.array(img.shape[1::-1]) * (1 + image_padding * 2)).astype(int)
scale = np.array(tuple(image_size) * 2, dtype=float)
# Detect faces
detections = net(frame_tensor)
det = []
# shrink = 1.0
# scale = torch.Tensor([image_size[1] / shrink, image_size[0] / shrink,
# image_size[1] / shrink, image_size[0] / shrink])
for i in range(detections.size(1)):
j = 0
while detections[0, i, j, 0] >= thresh:
curr_det = detections[0, i, j, [1, 2, 3, 4, 0]].cpu().numpy()
# curr_det[:4] *= scale.cpu().numpy()
curr_det[:4] *= scale
det.append(curr_det)
j += 1
if len(det) == 0:
det = np.array([], dtype='float32')
else:
det = np.row_stack((det))
det = det[det[:, 4] > 0.5, :4]
# Restore detection relative to original image
if image_padding is not None:
det[:, :2] -= image_pad_size
det[:, 2:] -= image_pad_size
# Render
if display:
det_display = np.round(det).astype(int)
render_img = img
if shrink < 1.0:
render_img = cv2.resize(render_img, None, None, fx=shrink, fy=shrink, interpolation=cv2.INTER_LINEAR)
det_display = (det_display * shrink).astype('float32')
for rect in det_display:
cv2.rectangle(render_img, tuple(rect[:2]), tuple(rect[2:]), (0, 0, 255), 1)
cv2.imshow('render_img', render_img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Write detection to file
with open(curr_cache_path, 'wb') as f:
pickle.dump([det], f)
if __name__ == "__main__":
# Parse program arguments
import argparse
parser = argparse.ArgumentParser(os.path.splitext(os.path.basename(__file__))[0])
parser.add_argument('input', metavar='PATH', nargs='+',
help='input paths')
parser.add_argument('-o', '--output', metavar='DIR',
help='output directory')
parser.add_argument('-i', '--indices', default=None,
help='python style indices (e.g 0:10')
parser.add_argument('-dm', '--detection_model', metavar='PATH', default='weights/WIDERFace_DSFD_RES152.pth',
help='path to face detection model')
parser.add_argument('-p', '--postfix', default='.jpg', metavar='POSTFIX',
help='input image postfix')
parser.add_argument('-op', '--out_postfix', default='_dsfd.pkl', metavar='POSTFIX',
help='output file postfix')
parser.add_argument('-ip', '--image_padding', type=float, metavar='F',
help='image padding relative to image size')
parser.add_argument('-mr', '--max_res', default=2048, type=int, metavar='N',
help='maximum detection resolution (higher resolution images will be scaled down)')
parser.add_argument('-d', '--display', action='store_true',
help='display the rendering')
args = parser.parse_args()
main(args.input, args.output, args.indices, args.detection_model, args.postfix, args.out_postfix,
args.image_padding, args.max_res, args.display)
| [
"pickle.dump",
"torch.set_default_tensor_type",
"os.path.isfile",
"cv2.imshow",
"os.path.join",
"numpy.round",
"torch.nn.functional.pad",
"torch.load",
"os.path.exists",
"numpy.loadtxt",
"cv2.resize",
"face_detection_dsfd.face_ssd_infer.SSD",
"os.path.basename",
"cv2.waitKey",
"torch.cud... | [((1636, 1665), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (1658, 1665), False, 'import torch\n'), ((1933, 1944), 'face_detection_dsfd.face_ssd_infer.SSD', 'SSD', (['"""test"""'], {}), "('test')\n", (1936, 1944), False, 'from face_detection_dsfd.face_ssd_infer import SSD\n'), ((2035, 2069), 'face_detection_dsfd.data.TestBaseTransform', 'TestBaseTransform', (['(104, 117, 123)'], {}), '((104, 117, 123))\n', (2052, 2069), False, 'from face_detection_dsfd.data import widerface_640, TestBaseTransform\n'), ((473, 497), 'os.path.isfile', 'os.path.isfile', (['input[0]'], {}), '(input[0])\n', (487, 497), False, 'import os\n'), ((1729, 1754), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1752, 1754), False, 'import torch\n'), ((1764, 1819), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.cuda.FloatTensor"""'], {}), "('torch.cuda.FloatTensor')\n", (1793, 1819), False, 'import torch\n'), ((1838, 1888), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.FloatTensor"""'], {}), "('torch.FloatTensor')\n", (1867, 1888), False, 'import torch\n'), ((1969, 2001), 'torch.load', 'torch.load', (['detection_model_path'], {}), '(detection_model_path)\n', (1979, 2001), False, 'import torch\n'), ((2469, 2500), 'os.path.exists', 'os.path.exists', (['curr_cache_path'], {}), '(curr_cache_path)\n', (2483, 2500), False, 'import os\n'), ((2739, 2759), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (2749, 2759), False, 'import cv2\n'), ((2864, 2907), 'numpy.array', 'np.array', (['(image_size[::-1] * 2)'], {'dtype': 'float'}), '(image_size[::-1] * 2, dtype=float)\n', (2872, 2907), True, 'import numpy as np\n'), ((357, 381), 'os.path.isfile', 'os.path.isfile', (['input[0]'], {}), '(input[0])\n', (371, 381), False, 'import os\n'), ((385, 408), 'os.path.isdir', 'os.path.isdir', (['input[0]'], {}), '(input[0])\n', (398, 408), False, 'import os\n'), ((591, 614), 'os.path.isdir', 'os.path.isdir', (['input[0]'], {}), '(input[0])\n', (604, 614), False, 'import os\n'), ((2411, 2456), 'os.path.join', 'os.path.join', (['out_dir', '(img_name + out_postfix)'], {}), '(out_dir, img_name + out_postfix)\n', (2423, 2456), False, 'import os\n'), ((3024, 3110), 'cv2.resize', 'cv2.resize', (['img', 'None', 'None'], {'fx': 'shrink', 'fy': 'shrink', 'interpolation': 'cv2.INTER_LINEAR'}), '(img, None, None, fx=shrink, fy=shrink, interpolation=cv2.\n INTER_LINEAR)\n', (3034, 3110), False, 'import cv2\n'), ((3561, 3674), 'torch.nn.functional.pad', 'F.pad', (['frame_tensor', '[image_pad_size[0], image_pad_size[0], image_pad_size[1], image_pad_size[1]]', '"""reflect"""'], {}), "(frame_tensor, [image_pad_size[0], image_pad_size[0], image_pad_size[1\n ], image_pad_size[1]], 'reflect')\n", (3566, 3674), True, 'import torch.nn.functional as F\n'), ((4631, 4660), 'numpy.array', 'np.array', (['[]'], {'dtype': '"""float32"""'}), "([], dtype='float32')\n", (4639, 4660), True, 'import numpy as np\n'), ((4693, 4710), 'numpy.row_stack', 'np.row_stack', (['det'], {}), '(det)\n', (4705, 4710), True, 'import numpy as np\n'), ((5411, 5447), 'cv2.imshow', 'cv2.imshow', (['"""render_img"""', 'render_img'], {}), "('render_img', render_img)\n", (5421, 5447), False, 'import cv2\n'), ((5614, 5635), 'pickle.dump', 'pickle.dump', (['[det]', 'f'], {}), '([det], f)\n', (5625, 5635), False, 'import pickle\n'), ((551, 574), 'os.path.split', 'os.path.split', (['input[0]'], {}), '(input[0])\n', (564, 574), False, 'import os\n'), ((774, 806), 'os.path.join', 'os.path.join', (['input[0]', 'input[1]'], {}), '(input[0], input[1])\n', (786, 806), False, 'import os\n'), ((864, 887), 'os.path.isdir', 'os.path.isdir', (['input[0]'], {}), '(input[0])\n', (877, 887), False, 'import os\n'), ((892, 922), 'os.path.isfile', 'os.path.isfile', (['list_file_path'], {}), '(list_file_path)\n', (906, 922), False, 'import os\n'), ((977, 1008), 'numpy.loadtxt', 'np.loadtxt', (['list_file_path', 'str'], {}), '(list_file_path, str)\n', (987, 1008), True, 'import numpy as np\n'), ((2234, 2260), 'os.path.basename', 'os.path.basename', (['img_path'], {}), '(img_path)\n', (2250, 2260), False, 'import os\n'), ((5109, 5202), 'cv2.resize', 'cv2.resize', (['render_img', 'None', 'None'], {'fx': 'shrink', 'fy': 'shrink', 'interpolation': 'cv2.INTER_LINEAR'}), '(render_img, None, None, fx=shrink, fy=shrink, interpolation=cv2.\n INTER_LINEAR)\n', (5119, 5202), False, 'import cv2\n'), ((5769, 5795), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (5785, 5795), False, 'import os\n'), ((814, 838), 'os.path.isfile', 'os.path.isfile', (['input[1]'], {}), '(input[1])\n', (828, 838), False, 'import os\n'), ((1034, 1059), 'os.path.join', 'os.path.join', (['input[0]', 'p'], {}), '(input[0], p)\n', (1046, 1059), False, 'import os\n'), ((2323, 2349), 'os.path.splitext', 'os.path.splitext', (['img_path'], {}), '(img_path)\n', (2339, 2349), False, 'import os\n'), ((2946, 2966), 'numpy.array', 'np.array', (['image_size'], {}), '(image_size)\n', (2954, 2966), True, 'import numpy as np\n'), ((4996, 5009), 'numpy.round', 'np.round', (['det'], {}), '(det)\n', (5004, 5009), True, 'import numpy as np\n'), ((5463, 5477), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5474, 5477), False, 'import cv2\n'), ((652, 689), 'os.path.join', 'os.path.join', (['input[0]', "('*' + postfix)"], {}), "(input[0], '*' + postfix)\n", (664, 689), False, 'import os\n'), ((3478, 3504), 'numpy.array', 'np.array', (['image_size[::-1]'], {}), '(image_size[::-1])\n', (3486, 3504), True, 'import numpy as np\n'), ((3756, 3782), 'numpy.array', 'np.array', (['img.shape[1::-1]'], {}), '(img.shape[1::-1])\n', (3764, 3782), True, 'import numpy as np\n'), ((3846, 3872), 'numpy.array', 'np.array', (['img.shape[1::-1]'], {}), '(img.shape[1::-1])\n', (3854, 3872), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 09:11:12 2020
@author: emc1977
"""
import numpy as np
from scipy import optimize
def f(x): # The rosenbrock function
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
def jacobian(x):
return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2)))
solution = optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian)
print(solution)
| [
"scipy.optimize.minimize",
"numpy.array"
] | [((354, 417), 'scipy.optimize.minimize', 'optimize.minimize', (['f', '[2, -1]'], {'method': '"""Newton-CG"""', 'jac': 'jacobian'}), "(f, [2, -1], method='Newton-CG', jac=jacobian)\n", (371, 417), False, 'from scipy import optimize\n'), ((265, 358), 'numpy.array', 'np.array', (['(-2 * 0.5 * (1 - x[0]) - 4 * x[0] * (x[1] - x[0] ** 2), 2 * (x[1] - x[0] ** 2))'], {}), '((-2 * 0.5 * (1 - x[0]) - 4 * x[0] * (x[1] - x[0] ** 2), 2 * (x[1] -\n x[0] ** 2)))\n', (273, 358), True, 'import numpy as np\n')] |
import numpy as np
import kornia
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
class ReplayBuffer(object):
"""Buffer to store environment transitions."""
def __init__(self, view, obs_shape, action_shape, capacity, image_pad, device, num_frames_per_stack):
self.view = view
self.capacity = capacity
self.device = device
self.aug_trans = nn.Sequential(
nn.ReplicationPad2d(image_pad),
kornia.augmentation.RandomCrop((obs_shape[-1], obs_shape[-1])))
if str(view) == 'both':
self.img_obses1 = np.empty((capacity, *obs_shape), dtype=np.uint8)
self.img_obses3 = np.empty((capacity, *obs_shape), dtype=np.uint8)
self.next_img_obses1 = np.empty((capacity, *obs_shape), dtype=np.uint8)
self.next_img_obses3 = np.empty((capacity, *obs_shape), dtype=np.uint8)
else:
self.img_obses = np.empty((capacity, *obs_shape), dtype=np.uint8)
self.next_img_obses = np.empty((capacity, *obs_shape), dtype=np.uint8)
self.proprio_obses = np.empty((capacity, 39*num_frames_per_stack), dtype=np.float32)
self.next_proprio_obses = np.empty((capacity, 39*num_frames_per_stack), dtype=np.float32)
self.actions = np.empty((capacity, *action_shape), dtype=np.float32)
self.rewards = np.empty((capacity, 1), dtype=np.float32)
self.not_dones = np.empty((capacity, 1), dtype=np.float32)
self.not_dones_no_max = np.empty((capacity, 1), dtype=np.float32)
self.idx = 0
self.full = False
def __len__(self):
return self.capacity if self.full else self.idx
def add(self, obs, action, reward, next_obs, done, done_no_max):
if str(self.view) == 'both':
img_obs1, img_obs3, proprio_obs = obs
np.copyto(self.img_obses1[self.idx], img_obs1)
np.copyto(self.img_obses3[self.idx], img_obs3)
next_img_obs1, next_img_obs3, next_proprio_obs = next_obs
np.copyto(self.next_img_obses1[self.idx], next_img_obs1)
np.copyto(self.next_img_obses3[self.idx], next_img_obs3)
else:
img_obs, proprio_obs = obs
np.copyto(self.img_obses[self.idx], img_obs)
next_img_obs, next_proprio_obs = next_obs
np.copyto(self.next_img_obses[self.idx], next_img_obs)
np.copyto(self.proprio_obses[self.idx], proprio_obs)
np.copyto(self.next_proprio_obses[self.idx], next_proprio_obs)
np.copyto(self.actions[self.idx], action)
np.copyto(self.rewards[self.idx], reward)
np.copyto(self.not_dones[self.idx], not done)
np.copyto(self.not_dones_no_max[self.idx], not done_no_max)
self.idx = (self.idx + 1) % self.capacity
self.full = self.full or self.idx == 0
def sample(self, batch_size):
idxs = np.random.randint(0,
self.capacity if self.full else self.idx,
size=batch_size)
actions = torch.as_tensor(self.actions[idxs], device=self.device)
rewards = torch.as_tensor(self.rewards[idxs], device=self.device)
not_dones_no_max = torch.as_tensor(self.not_dones_no_max[idxs],
device=self.device)
proprio_obses = torch.as_tensor(self.proprio_obses[idxs], device=self.device).float()
next_proprio_obses = torch.as_tensor(self.next_proprio_obses[idxs], device=self.device).float()
if str(self.view) == 'both':
img_obses1 = self.img_obses1[idxs]
next_img_obses1 = self.next_img_obses1[idxs]
img_obses_aug1 = img_obses1.copy()
next_img_obses_aug1 = next_img_obses1.copy()
img_obses3 = self.img_obses3[idxs]
next_img_obses3 = self.next_img_obses3[idxs]
img_obses_aug3 = img_obses3.copy()
next_img_obses_aug3 = next_img_obses3.copy()
img_obses1 = torch.as_tensor(img_obses1, device=self.device).float()
next_img_obses1 = torch.as_tensor(next_img_obses1, device=self.device).float()
img_obses_aug1 = torch.as_tensor(img_obses_aug1, device=self.device).float()
next_img_obses_aug1 = torch.as_tensor(next_img_obses_aug1,
device=self.device).float()
img_obses3 = torch.as_tensor(img_obses3, device=self.device).float()
next_img_obses3 = torch.as_tensor(next_img_obses3, device=self.device).float()
img_obses_aug3 = torch.as_tensor(img_obses_aug3, device=self.device).float()
next_img_obses_aug3 = torch.as_tensor(next_img_obses_aug3,
device=self.device).float()
img_obses1 = self.aug_trans(img_obses1)
next_img_obses1 = self.aug_trans(next_img_obses1)
img_obses_aug1 = self.aug_trans(img_obses_aug1)
next_img_obses_aug1 = self.aug_trans(next_img_obses_aug1)
img_obses3 = self.aug_trans(img_obses3)
next_img_obses3 = self.aug_trans(next_img_obses3)
img_obses_aug3 = self.aug_trans(img_obses_aug3)
next_img_obses_aug3 = self.aug_trans(next_img_obses_aug3)
obses = (img_obses1, img_obses3, proprio_obses)
next_obses = (next_img_obses1, next_img_obses3, next_proprio_obses)
obses_aug = (img_obses_aug1, img_obses_aug3, proprio_obses)
next_obses_aug = (next_img_obses_aug1, next_img_obses3, next_proprio_obses)
else:
img_obses = self.img_obses[idxs]
next_img_obses = self.next_img_obses[idxs]
img_obses_aug = img_obses.copy()
next_img_obses_aug = next_img_obses.copy()
img_obses = torch.as_tensor(img_obses, device=self.device).float()
next_img_obses = torch.as_tensor(next_img_obses, device=self.device).float()
img_obses_aug = torch.as_tensor(img_obses_aug, device=self.device).float()
next_img_obses_aug = torch.as_tensor(next_img_obses_aug,
device=self.device).float()
img_obses = self.aug_trans(img_obses)
next_img_obses = self.aug_trans(next_img_obses)
img_obses_aug = self.aug_trans(img_obses_aug)
next_img_obses_aug = self.aug_trans(next_img_obses_aug)
obses = (img_obses, proprio_obses)
next_obses = (next_img_obses, next_proprio_obses)
obses_aug = (img_obses_aug, proprio_obses)
next_obses_aug = (next_img_obses_aug, next_proprio_obses)
return obses, actions, rewards, next_obses, not_dones_no_max, obses_aug, next_obses_aug
| [
"torch.nn.ReplicationPad2d",
"numpy.empty",
"kornia.augmentation.RandomCrop",
"numpy.random.randint",
"torch.as_tensor",
"numpy.copyto"
] | [((1112, 1177), 'numpy.empty', 'np.empty', (['(capacity, 39 * num_frames_per_stack)'], {'dtype': 'np.float32'}), '((capacity, 39 * num_frames_per_stack), dtype=np.float32)\n', (1120, 1177), True, 'import numpy as np\n'), ((1210, 1275), 'numpy.empty', 'np.empty', (['(capacity, 39 * num_frames_per_stack)'], {'dtype': 'np.float32'}), '((capacity, 39 * num_frames_per_stack), dtype=np.float32)\n', (1218, 1275), True, 'import numpy as np\n'), ((1298, 1351), 'numpy.empty', 'np.empty', (['(capacity, *action_shape)'], {'dtype': 'np.float32'}), '((capacity, *action_shape), dtype=np.float32)\n', (1306, 1351), True, 'import numpy as np\n'), ((1375, 1416), 'numpy.empty', 'np.empty', (['(capacity, 1)'], {'dtype': 'np.float32'}), '((capacity, 1), dtype=np.float32)\n', (1383, 1416), True, 'import numpy as np\n'), ((1442, 1483), 'numpy.empty', 'np.empty', (['(capacity, 1)'], {'dtype': 'np.float32'}), '((capacity, 1), dtype=np.float32)\n', (1450, 1483), True, 'import numpy as np\n'), ((1516, 1557), 'numpy.empty', 'np.empty', (['(capacity, 1)'], {'dtype': 'np.float32'}), '((capacity, 1), dtype=np.float32)\n', (1524, 1557), True, 'import numpy as np\n'), ((2408, 2460), 'numpy.copyto', 'np.copyto', (['self.proprio_obses[self.idx]', 'proprio_obs'], {}), '(self.proprio_obses[self.idx], proprio_obs)\n', (2417, 2460), True, 'import numpy as np\n'), ((2469, 2531), 'numpy.copyto', 'np.copyto', (['self.next_proprio_obses[self.idx]', 'next_proprio_obs'], {}), '(self.next_proprio_obses[self.idx], next_proprio_obs)\n', (2478, 2531), True, 'import numpy as np\n'), ((2541, 2582), 'numpy.copyto', 'np.copyto', (['self.actions[self.idx]', 'action'], {}), '(self.actions[self.idx], action)\n', (2550, 2582), True, 'import numpy as np\n'), ((2591, 2632), 'numpy.copyto', 'np.copyto', (['self.rewards[self.idx]', 'reward'], {}), '(self.rewards[self.idx], reward)\n', (2600, 2632), True, 'import numpy as np\n'), ((2641, 2686), 'numpy.copyto', 'np.copyto', (['self.not_dones[self.idx]', '(not done)'], {}), '(self.not_dones[self.idx], not done)\n', (2650, 2686), True, 'import numpy as np\n'), ((2695, 2754), 'numpy.copyto', 'np.copyto', (['self.not_dones_no_max[self.idx]', '(not done_no_max)'], {}), '(self.not_dones_no_max[self.idx], not done_no_max)\n', (2704, 2754), True, 'import numpy as np\n'), ((2903, 2982), 'numpy.random.randint', 'np.random.randint', (['(0)', '(self.capacity if self.full else self.idx)'], {'size': 'batch_size'}), '(0, self.capacity if self.full else self.idx, size=batch_size)\n', (2920, 2982), True, 'import numpy as np\n'), ((3068, 3123), 'torch.as_tensor', 'torch.as_tensor', (['self.actions[idxs]'], {'device': 'self.device'}), '(self.actions[idxs], device=self.device)\n', (3083, 3123), False, 'import torch\n'), ((3142, 3197), 'torch.as_tensor', 'torch.as_tensor', (['self.rewards[idxs]'], {'device': 'self.device'}), '(self.rewards[idxs], device=self.device)\n', (3157, 3197), False, 'import torch\n'), ((3225, 3289), 'torch.as_tensor', 'torch.as_tensor', (['self.not_dones_no_max[idxs]'], {'device': 'self.device'}), '(self.not_dones_no_max[idxs], device=self.device)\n', (3240, 3289), False, 'import torch\n'), ((441, 471), 'torch.nn.ReplicationPad2d', 'nn.ReplicationPad2d', (['image_pad'], {}), '(image_pad)\n', (460, 471), True, 'import torch.nn as nn\n'), ((485, 547), 'kornia.augmentation.RandomCrop', 'kornia.augmentation.RandomCrop', (['(obs_shape[-1], obs_shape[-1])'], {}), '((obs_shape[-1], obs_shape[-1]))\n', (515, 547), False, 'import kornia\n'), ((612, 660), 'numpy.empty', 'np.empty', (['(capacity, *obs_shape)'], {'dtype': 'np.uint8'}), '((capacity, *obs_shape), dtype=np.uint8)\n', (620, 660), True, 'import numpy as np\n'), ((691, 739), 'numpy.empty', 'np.empty', (['(capacity, *obs_shape)'], {'dtype': 'np.uint8'}), '((capacity, *obs_shape), dtype=np.uint8)\n', (699, 739), True, 'import numpy as np\n'), ((775, 823), 'numpy.empty', 'np.empty', (['(capacity, *obs_shape)'], {'dtype': 'np.uint8'}), '((capacity, *obs_shape), dtype=np.uint8)\n', (783, 823), True, 'import numpy as np\n'), ((859, 907), 'numpy.empty', 'np.empty', (['(capacity, *obs_shape)'], {'dtype': 'np.uint8'}), '((capacity, *obs_shape), dtype=np.uint8)\n', (867, 907), True, 'import numpy as np\n'), ((951, 999), 'numpy.empty', 'np.empty', (['(capacity, *obs_shape)'], {'dtype': 'np.uint8'}), '((capacity, *obs_shape), dtype=np.uint8)\n', (959, 999), True, 'import numpy as np\n'), ((1034, 1082), 'numpy.empty', 'np.empty', (['(capacity, *obs_shape)'], {'dtype': 'np.uint8'}), '((capacity, *obs_shape), dtype=np.uint8)\n', (1042, 1082), True, 'import numpy as np\n'), ((1855, 1901), 'numpy.copyto', 'np.copyto', (['self.img_obses1[self.idx]', 'img_obs1'], {}), '(self.img_obses1[self.idx], img_obs1)\n', (1864, 1901), True, 'import numpy as np\n'), ((1914, 1960), 'numpy.copyto', 'np.copyto', (['self.img_obses3[self.idx]', 'img_obs3'], {}), '(self.img_obses3[self.idx], img_obs3)\n', (1923, 1960), True, 'import numpy as np\n'), ((2043, 2099), 'numpy.copyto', 'np.copyto', (['self.next_img_obses1[self.idx]', 'next_img_obs1'], {}), '(self.next_img_obses1[self.idx], next_img_obs1)\n', (2052, 2099), True, 'import numpy as np\n'), ((2112, 2168), 'numpy.copyto', 'np.copyto', (['self.next_img_obses3[self.idx]', 'next_img_obs3'], {}), '(self.next_img_obses3[self.idx], next_img_obs3)\n', (2121, 2168), True, 'import numpy as np\n'), ((2234, 2278), 'numpy.copyto', 'np.copyto', (['self.img_obses[self.idx]', 'img_obs'], {}), '(self.img_obses[self.idx], img_obs)\n', (2243, 2278), True, 'import numpy as np\n'), ((2345, 2399), 'numpy.copyto', 'np.copyto', (['self.next_img_obses[self.idx]', 'next_img_obs'], {}), '(self.next_img_obses[self.idx], next_img_obs)\n', (2354, 2399), True, 'import numpy as np\n'), ((3358, 3419), 'torch.as_tensor', 'torch.as_tensor', (['self.proprio_obses[idxs]'], {'device': 'self.device'}), '(self.proprio_obses[idxs], device=self.device)\n', (3373, 3419), False, 'import torch\n'), ((3457, 3523), 'torch.as_tensor', 'torch.as_tensor', (['self.next_proprio_obses[idxs]'], {'device': 'self.device'}), '(self.next_proprio_obses[idxs], device=self.device)\n', (3472, 3523), False, 'import torch\n'), ((4011, 4058), 'torch.as_tensor', 'torch.as_tensor', (['img_obses1'], {'device': 'self.device'}), '(img_obses1, device=self.device)\n', (4026, 4058), False, 'import torch\n'), ((4097, 4149), 'torch.as_tensor', 'torch.as_tensor', (['next_img_obses1'], {'device': 'self.device'}), '(next_img_obses1, device=self.device)\n', (4112, 4149), False, 'import torch\n'), ((4187, 4238), 'torch.as_tensor', 'torch.as_tensor', (['img_obses_aug1'], {'device': 'self.device'}), '(img_obses_aug1, device=self.device)\n', (4202, 4238), False, 'import torch\n'), ((4281, 4337), 'torch.as_tensor', 'torch.as_tensor', (['next_img_obses_aug1'], {'device': 'self.device'}), '(next_img_obses_aug1, device=self.device)\n', (4296, 4337), False, 'import torch\n'), ((4415, 4462), 'torch.as_tensor', 'torch.as_tensor', (['img_obses3'], {'device': 'self.device'}), '(img_obses3, device=self.device)\n', (4430, 4462), False, 'import torch\n'), ((4501, 4553), 'torch.as_tensor', 'torch.as_tensor', (['next_img_obses3'], {'device': 'self.device'}), '(next_img_obses3, device=self.device)\n', (4516, 4553), False, 'import torch\n'), ((4591, 4642), 'torch.as_tensor', 'torch.as_tensor', (['img_obses_aug3'], {'device': 'self.device'}), '(img_obses_aug3, device=self.device)\n', (4606, 4642), False, 'import torch\n'), ((4685, 4741), 'torch.as_tensor', 'torch.as_tensor', (['next_img_obses_aug3'], {'device': 'self.device'}), '(next_img_obses_aug3, device=self.device)\n', (4700, 4741), False, 'import torch\n'), ((5820, 5866), 'torch.as_tensor', 'torch.as_tensor', (['img_obses'], {'device': 'self.device'}), '(img_obses, device=self.device)\n', (5835, 5866), False, 'import torch\n'), ((5904, 5955), 'torch.as_tensor', 'torch.as_tensor', (['next_img_obses'], {'device': 'self.device'}), '(next_img_obses, device=self.device)\n', (5919, 5955), False, 'import torch\n'), ((5992, 6042), 'torch.as_tensor', 'torch.as_tensor', (['img_obses_aug'], {'device': 'self.device'}), '(img_obses_aug, device=self.device)\n', (6007, 6042), False, 'import torch\n'), ((6084, 6139), 'torch.as_tensor', 'torch.as_tensor', (['next_img_obses_aug'], {'device': 'self.device'}), '(next_img_obses_aug, device=self.device)\n', (6099, 6139), False, 'import torch\n')] |
import numpy as np
class Config:
#########################################################################
# GENERAL PARAMETERS
COLLISION_AVOIDANCE = True
continuous, discrete = range(2) # Initialize game types as enum
ACTION_SPACE_TYPE = continuous
ANIMATE_EPISODES = True
SHOW_EPISODE_PLOTS = False
SAVE_EPISODE_PLOTS = True
TRAIN_MODE = False # Enable to see the trained agent in action (for testing)
PLAY_MODE = False # Enable to see the trained agent in action (for testing)
EVALUATE_MODE = False # Enable to see the trained agent in action (for testing)
TRAIN_SINGLE_AGENT = True
LSTM_HIDDEN_SIZE = 16
NUM_LAYERS = 2
NUM_HIDDEN_UNITS = 64
NETWORK = "mfe_network"
GAMMA = 0.99
LEARNING_RATE = 1e-3
#########################################################################
# COLLISION AVOIDANCE PARAMETER
NUM_TEST_CASES = 50
PLOT_EVERY_N_EPISODES = 10 # for tensorboard visualization
DT = 0.1 # seconds between simulation time steps
REWARD_AT_GOAL = 3.0 # reward given when agent reaches goal position
REWARD_COLLISION_WITH_AGENT = -10.0 # reward given when agent collides with another agent
REWARD_TIMEOUT = -10.0 # reward given for not reaching the goal
REWARD_INFEASIBLE = 0.0
REWARD_COLLISION_WITH_WALL = -0.25 # reward given when agent collides with wall
REWARD_GETTING_CLOSE = 0.0 # reward when agent gets close to another agent (unused?)
REWARD_ENTERED_NORM_ZONE = 0.0 # reward when agent enters another agent's social zone
REWARD_TIME_STEP = -0.01 # default reward given if none of the others apply (encourage speed)
REWARD_DISTANCE_TO_GOAL = 0.0 # default reward given if none of the others apply (encourage speed)
REWARD_WIGGLY_BEHAVIOR = 0.0
WIGGLY_BEHAVIOR_THRESHOLD = 0.0
ENABLE_COLLISION_AVOIDANCE = True
COLLISION_DIST = 0.5 # meters between agents' boundaries for collision
GETTING_CLOSE_RANGE = 0.2 # meters between agents' boundaries for collision
JOINT_MPC_RL_TRAINING = False # select the action that has highets reward (mpc/rl)
CURRICULUM_LEARNING = False
HOMOGENEOUS_TESTING = False
PERFORMANCE_TEST = False
PLOT_PREDICTIONS = True
COLLISION_AV_W_STATIC_AGENT = False
#MPC
FORCES_N = 15
FORCES_DT = 0.3
REPEAT_STEPS = 2
LASERSCAN_LENGTH = 16 # num range readings in one scan
NUM_STEPS_IN_OBS_HISTORY = 1 # number of time steps to store in observation vector
NUM_PAST_ACTIONS_IN_STATE = 0
NEAR_GOAL_THRESHOLD = 0.75
MAX_TIME_RATIO = 3.0 # agent has this number times the straight-line-time to reach its goal before "timing out"
SENSING_HORIZON = np.inf
#SENSING_HORIZON = 3.0
RVO_TIME_HORIZON = 5.0
RVO_COLLAB_COEFF = 0.5
RVO_ANTI_COLLAB_T = 1.0
MAX_NUM_AGENTS_IN_ENVIRONMENT = 10
MAX_NUM_OTHER_AGENTS_IN_ENVIRONMENT = MAX_NUM_AGENTS_IN_ENVIRONMENT - 1
MAX_NUM_OTHER_AGENTS_OBSERVED = MAX_NUM_AGENTS_IN_ENVIRONMENT - 1
PLOT_CIRCLES_ALONG_TRAJ = False
ANIMATION_PERIOD_STEPS = 1 # plot every n-th DT step (if animate mode on)
PLT_LIMITS = ((-15, 15), (-15, 15))
PLT_FIG_SIZE = (12, 8)
PLT_SHOW_LEGEND = False
PLT_SUBPLT_TRAJ = False
PLT_SUBPLT_TARGMAP = True
# Gridmap parameters
SUBMAP_WIDTH = 60 # Pixels
SUBMAP_HEIGHT = 60 # Pixels
SUBMAP_RESOLUTION = 0.1 # Pixel / meter
# STATIC MAP
MAP_WIDTH = 30 # Meters
MAP_HEIGHT = 30 # Meters
SCENARIOS_FOR_TRAINING = ["IG_agent_crossing"]#["train_agents_swap_circle","train_agents_random_positions","train_agents_pairwise_swap"]
# Angular Map
NUM_OF_SLICES = 16
MAX_RANGE = 6
#STATES_IN_OBS = ['dist_to_goal', 'rel_goal', 'radius', 'heading_ego_frame', 'pref_speed', 'other_agents_states']
STATES_IN_OBS = ['radius', 'heading_global_frame', 'pos_global_frame', 'pref_speed', 'other_agents_states','local_grid'] #occupancy grid
#STATES_IN_OBS = ['dist_to_goal', 'rel_goal', 'radius', 'heading_ego_frame', 'pref_speed', 'other_agents_states', 'angular_map'] #angular map
# STATES_IN_OBS = ['dist_to_goal', 'radius', 'heading_ego_frame', 'pref_speed', 'other_agent_states', 'use_ppo', 'laserscan']
# STATES_IN_OBS = ['dist_to_goal', 'radius', 'heading_ego_frame', 'pref_speed', 'other_agent_states', 'use_ppo'] # 2-agent net
# STATES_IN_OBS = ['dist_to_goal', 'radius', 'heading_ego_frame', 'pref_speed', 'other_agents_states', 'use_ppo', 'num_other_agents', 'laserscan'] # LSTM
STATES_NOT_USED_IN_POLICY = ['use_ppo', 'num_other_agents']
STATE_INFO_DICT = {
'dist_to_goal': {
'dtype': np.float32,
'size': 1,
'bounds': [-np.inf, np.inf],
'attr': 'get_agent_data("dist_to_goal")',
'std': np.array([5.], dtype=np.float32),
'mean': np.array([0.], dtype=np.float32)
},
'radius': {
'dtype': np.float32,
'size': 1,
'bounds': [0, np.inf],
'attr': 'get_agent_data("radius")',
'std': np.array([1.0], dtype=np.float32),
'mean': np.array([0.5], dtype=np.float32)
},
'rel_goal': {
'dtype': np.float32,
'size': 2,
'bounds': [-np.inf, np.inf],
'attr': 'get_agent_data("rel_goal")',
'std': np.array([10.0], dtype=np.float32),
'mean': np.array([0.], dtype=np.float32)
},
'heading_ego_frame': {
'dtype': np.float32,
'size': 1,
'bounds': [-np.pi, np.pi],
'attr': 'get_agent_data("heading_ego_frame")',
'std': np.array([3.14], dtype=np.float32),
'mean': np.array([0.], dtype=np.float32)
},
'heading_global_frame': {
'dtype': np.float32,
'size': 1,
'bounds': [-np.pi, np.pi],
'attr': 'get_agent_data("heading_global_frame")',
'std': np.array([3.14], dtype=np.float32),
'mean': np.array([0.], dtype=np.float32)
},
'pos_global_frame': {
'dtype': np.float32,
'size': 2,
'bounds': [-np.inf, np.inf],
'attr': 'get_agent_data("pos_global_frame")',
'std': np.array([1.0], dtype=np.float32),
'mean': np.array([0.], dtype=np.float32)
},
'pref_speed': {
'dtype': np.float32,
'size': 1,
'bounds': [0, np.inf],
'attr': 'get_agent_data("pref_speed")',
'std': np.array([1.0], dtype=np.float32),
'mean': np.array([1.0], dtype=np.float32)
},
'num_other_agents': {
'dtype': np.float32,
'size': 1,
'bounds': [0, np.inf],
'attr': 'get_agent_data("num_other_agents_observed")',
'std': np.array([1.0], dtype=np.float32),
'mean': np.array([1.0], dtype=np.float32)
},
'other_agent_states': {
'dtype': np.float32,
'size': 9,
'bounds': [-np.inf, np.inf],
'attr': 'get_agent_data("other_agent_states")',
'std': np.array([5.0, 5.0,5.0, 5.0, 1.0, 1.0, 1.0, 5.0, 1.0], dtype=np.float32),
'mean': np.array([0.0, 0.0,0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 1.0], dtype=np.float32)
},
'other_agents_states': {
'dtype': np.float32,
'size': (MAX_NUM_OTHER_AGENTS_IN_ENVIRONMENT,10),
'bounds': [-np.inf, np.inf],
'attr': 'get_sensor_data("other_agents_states")',
'std': np.tile(np.array([5.0, 5.0, 1.0, 1.0, 1.0, 5.0, 1.0, 5.0, 1.0], dtype=np.float32), (MAX_NUM_OTHER_AGENTS_IN_ENVIRONMENT, 1)),
'mean': np.tile(np.array([0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 1.0, 0.0, 1.0], dtype=np.float32), (MAX_NUM_OTHER_AGENTS_IN_ENVIRONMENT, 1)),
},
'local_grid': {
'dtype': np.float32,
'size': (SUBMAP_WIDTH, SUBMAP_HEIGHT),
'bounds': [-np.inf, np.inf],
'attr': 'get_sensor_data("local_grid")',
'std': np.ones((SUBMAP_WIDTH,SUBMAP_HEIGHT), dtype=np.float32),
'mean': np.ones((SUBMAP_WIDTH,SUBMAP_HEIGHT), dtype=np.float32),
},
'angular_map': {
'dtype': np.float32,
'size': NUM_OF_SLICES,
'bounds': [0., 6.],
'attr': 'get_sensor_data("angular_map")',
'std': np.ones(NUM_OF_SLICES, dtype=np.float32),
'mean': np.ones(NUM_OF_SLICES, dtype=np.float32),
},
'laserscan': {
'dtype': np.float32,
'size': LASERSCAN_LENGTH,
'bounds': [0., 6.],
'attr': 'get_sensor_data("laserscan")',
'std': 5.*np.ones((LASERSCAN_LENGTH), dtype=np.float32),
'mean': 5.*np.ones((LASERSCAN_LENGTH), dtype=np.float32)
},
'use_ppo': {
'dtype': np.float32,
'size': 1,
'bounds': [0., 1.],
'attr': 'get_agent_data_equiv("policy.str", "learning")'
}
}
MEAN_OBS = {}; STD_OBS = {}
for state in STATES_IN_OBS:
if 'mean' in STATE_INFO_DICT[state]:
MEAN_OBS[state] = STATE_INFO_DICT[state]['mean']
if 'std' in STATE_INFO_DICT[state]:
STD_OBS[state] = STATE_INFO_DICT[state]['std']
| [
"numpy.array",
"numpy.ones"
] | [((4833, 4866), 'numpy.array', 'np.array', (['[5.0]'], {'dtype': 'np.float32'}), '([5.0], dtype=np.float32)\n', (4841, 4866), True, 'import numpy as np\n'), ((4887, 4920), 'numpy.array', 'np.array', (['[0.0]'], {'dtype': 'np.float32'}), '([0.0], dtype=np.float32)\n', (4895, 4920), True, 'import numpy as np\n'), ((5113, 5146), 'numpy.array', 'np.array', (['[1.0]'], {'dtype': 'np.float32'}), '([1.0], dtype=np.float32)\n', (5121, 5146), True, 'import numpy as np\n'), ((5168, 5201), 'numpy.array', 'np.array', (['[0.5]'], {'dtype': 'np.float32'}), '([0.5], dtype=np.float32)\n', (5176, 5201), True, 'import numpy as np\n'), ((5405, 5439), 'numpy.array', 'np.array', (['[10.0]'], {'dtype': 'np.float32'}), '([10.0], dtype=np.float32)\n', (5413, 5439), True, 'import numpy as np\n'), ((5461, 5494), 'numpy.array', 'np.array', (['[0.0]'], {'dtype': 'np.float32'}), '([0.0], dtype=np.float32)\n', (5469, 5494), True, 'import numpy as np\n'), ((5713, 5747), 'numpy.array', 'np.array', (['[3.14]'], {'dtype': 'np.float32'}), '([3.14], dtype=np.float32)\n', (5721, 5747), True, 'import numpy as np\n'), ((5769, 5802), 'numpy.array', 'np.array', (['[0.0]'], {'dtype': 'np.float32'}), '([0.0], dtype=np.float32)\n', (5777, 5802), True, 'import numpy as np\n'), ((6023, 6057), 'numpy.array', 'np.array', (['[3.14]'], {'dtype': 'np.float32'}), '([3.14], dtype=np.float32)\n', (6031, 6057), True, 'import numpy as np\n'), ((6079, 6112), 'numpy.array', 'np.array', (['[0.0]'], {'dtype': 'np.float32'}), '([0.0], dtype=np.float32)\n', (6087, 6112), True, 'import numpy as np\n'), ((6327, 6360), 'numpy.array', 'np.array', (['[1.0]'], {'dtype': 'np.float32'}), '([1.0], dtype=np.float32)\n', (6335, 6360), True, 'import numpy as np\n'), ((6382, 6415), 'numpy.array', 'np.array', (['[0.0]'], {'dtype': 'np.float32'}), '([0.0], dtype=np.float32)\n', (6390, 6415), True, 'import numpy as np\n'), ((6612, 6645), 'numpy.array', 'np.array', (['[1.0]'], {'dtype': 'np.float32'}), '([1.0], dtype=np.float32)\n', (6620, 6645), True, 'import numpy as np\n'), ((6667, 6700), 'numpy.array', 'np.array', (['[1.0]'], {'dtype': 'np.float32'}), '([1.0], dtype=np.float32)\n', (6675, 6700), True, 'import numpy as np\n'), ((6923, 6956), 'numpy.array', 'np.array', (['[1.0]'], {'dtype': 'np.float32'}), '([1.0], dtype=np.float32)\n', (6931, 6956), True, 'import numpy as np\n'), ((6978, 7011), 'numpy.array', 'np.array', (['[1.0]'], {'dtype': 'np.float32'}), '([1.0], dtype=np.float32)\n', (6986, 7011), True, 'import numpy as np\n'), ((7235, 7308), 'numpy.array', 'np.array', (['[5.0, 5.0, 5.0, 5.0, 1.0, 1.0, 1.0, 5.0, 1.0]'], {'dtype': 'np.float32'}), '([5.0, 5.0, 5.0, 5.0, 1.0, 1.0, 1.0, 5.0, 1.0], dtype=np.float32)\n', (7243, 7308), True, 'import numpy as np\n'), ((7329, 7402), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 1.0]'], {'dtype': 'np.float32'}), '([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 1.0], dtype=np.float32)\n', (7337, 7402), True, 'import numpy as np\n'), ((8175, 8231), 'numpy.ones', 'np.ones', (['(SUBMAP_WIDTH, SUBMAP_HEIGHT)'], {'dtype': 'np.float32'}), '((SUBMAP_WIDTH, SUBMAP_HEIGHT), dtype=np.float32)\n', (8182, 8231), True, 'import numpy as np\n'), ((8252, 8308), 'numpy.ones', 'np.ones', (['(SUBMAP_WIDTH, SUBMAP_HEIGHT)'], {'dtype': 'np.float32'}), '((SUBMAP_WIDTH, SUBMAP_HEIGHT), dtype=np.float32)\n', (8259, 8308), True, 'import numpy as np\n'), ((8518, 8558), 'numpy.ones', 'np.ones', (['NUM_OF_SLICES'], {'dtype': 'np.float32'}), '(NUM_OF_SLICES, dtype=np.float32)\n', (8525, 8558), True, 'import numpy as np\n'), ((8580, 8620), 'numpy.ones', 'np.ones', (['NUM_OF_SLICES'], {'dtype': 'np.float32'}), '(NUM_OF_SLICES, dtype=np.float32)\n', (8587, 8620), True, 'import numpy as np\n'), ((7675, 7748), 'numpy.array', 'np.array', (['[5.0, 5.0, 1.0, 1.0, 1.0, 5.0, 1.0, 5.0, 1.0]'], {'dtype': 'np.float32'}), '([5.0, 5.0, 1.0, 1.0, 1.0, 5.0, 1.0, 5.0, 1.0], dtype=np.float32)\n', (7683, 7748), True, 'import numpy as np\n'), ((7821, 7894), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 1.0, 0.0, 1.0]'], {'dtype': 'np.float32'}), '([0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 1.0, 0.0, 1.0], dtype=np.float32)\n', (7829, 7894), True, 'import numpy as np\n'), ((8833, 8876), 'numpy.ones', 'np.ones', (['LASERSCAN_LENGTH'], {'dtype': 'np.float32'}), '(LASERSCAN_LENGTH, dtype=np.float32)\n', (8840, 8876), True, 'import numpy as np\n'), ((8903, 8946), 'numpy.ones', 'np.ones', (['LASERSCAN_LENGTH'], {'dtype': 'np.float32'}), '(LASERSCAN_LENGTH, dtype=np.float32)\n', (8910, 8946), True, 'import numpy as np\n')] |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms
import os
def image_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation=inter)
# return the resized image
return resized
def line_segment(base_path, test_path, pre_processed_path, image_name):
print("Line Segmenting Started...")
image_pre_processed = cv2.imread(base_path + pre_processed_path + image_name, 0)
image_original = cv2.imread(base_path + test_path + image_name)
height, width, channels = image_original.shape
# if image size is larger, down sample
if height > 1100 or width > 1100:
image_original = cv2.pyrDown(image_original)
image_pre_processed = 255 - image_pre_processed
img_row_sum = np.sum(image_pre_processed, axis=1).tolist()
# ignore counts less than 100
for i in range(len(img_row_sum)):
if img_row_sum[i] < 10000:
img_row_sum[i] = 0
cords = []
# identify rising points and falling points
for i in range(len(img_row_sum) - 1):
current_value = img_row_sum[i]
next_value = img_row_sum[i + 1]
if current_value == 0 and next_value == 0:
continue
elif current_value > 0 and next_value > 0:
continue
elif current_value == 0 and next_value > 0:
cords.append(i + 1)
elif current_value > 0 and next_value == 0:
cords.append(i)
# transform graph
base = plt.gca().transData
rot = matplotlib.transforms.Affine2D().rotate_deg(270)
#plt.plot(img_row_sum, transform=rot + base)
#plt.show()
H, W = image_pre_processed.shape[:2]
differences = []
# get line differences
for i in range(len(cords) - 1):
current_value = cords[i]
next_value = cords[i + 1]
difference = next_value - current_value
# filter values
if 10 < difference < 120:
differences.append(difference)
else:
differences.append(0)
# detect pairs
pairs = []
for i in range(len(differences)):
pair = []
if 15 < differences[i] < 80:
pair.append(cords[i])
pair.append(cords[i+1])
pairs.append(pair)
image_pre_processed = 255 - image_pre_processed
line_segment_base_path = 'step_9_vertical_projection_filtered/'
image_name_array = image_name.split('.')
line_segmented_path = line_segment_base_path + 'segmented/' + image_name_array[0]
if not os.path.exists(base_path + line_segmented_path):
os.makedirs(base_path + line_segmented_path)
for i in range(len(pairs)):
pair = pairs[i]
roi = image_pre_processed[pair[0]:pair[1], 0:W]
# count black pixels
black_pixel_count = np.sum(roi == 0)
# filter segments by black pixel count
if black_pixel_count > 100:
cv2.line(image_original, (0, pair[0]), (W, pair[0]), (0, 0, 255), 1)
cv2.line(image_original, (0, pair[1]), (W, pair[1]), (0, 255, 0), 1)
roi = image_resize(roi, height=40)
cv2.imwrite(os.path.join(base_path + line_segmented_path, str(i) + '.' + image_name_array[1]), roi)
cv2.imshow('Segmented Image', image_original)
cv2.imwrite(os.path.join(base_path + line_segment_base_path + image_name), image_original)
#cv2.waitKey(0)
print("Line Segmenting Done.")
| [
"cv2.line",
"numpy.sum",
"os.makedirs",
"os.path.join",
"os.path.exists",
"cv2.imread",
"matplotlib.pyplot.gca",
"cv2.imshow",
"cv2.pyrDown",
"cv2.resize"
] | [((927, 970), 'cv2.resize', 'cv2.resize', (['image', 'dim'], {'interpolation': 'inter'}), '(image, dim, interpolation=inter)\n', (937, 970), False, 'import cv2\n'), ((1172, 1230), 'cv2.imread', 'cv2.imread', (['(base_path + pre_processed_path + image_name)', '(0)'], {}), '(base_path + pre_processed_path + image_name, 0)\n', (1182, 1230), False, 'import cv2\n'), ((1253, 1299), 'cv2.imread', 'cv2.imread', (['(base_path + test_path + image_name)'], {}), '(base_path + test_path + image_name)\n', (1263, 1299), False, 'import cv2\n'), ((4094, 4139), 'cv2.imshow', 'cv2.imshow', (['"""Segmented Image"""', 'image_original'], {}), "('Segmented Image', image_original)\n", (4104, 4139), False, 'import cv2\n'), ((1463, 1490), 'cv2.pyrDown', 'cv2.pyrDown', (['image_original'], {}), '(image_original)\n', (1474, 1490), False, 'import cv2\n'), ((2304, 2313), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2311, 2313), True, 'import matplotlib.pyplot as plt\n'), ((3375, 3422), 'os.path.exists', 'os.path.exists', (['(base_path + line_segmented_path)'], {}), '(base_path + line_segmented_path)\n', (3389, 3422), False, 'import os\n'), ((3433, 3477), 'os.makedirs', 'os.makedirs', (['(base_path + line_segmented_path)'], {}), '(base_path + line_segmented_path)\n', (3444, 3477), False, 'import os\n'), ((3656, 3672), 'numpy.sum', 'np.sum', (['(roi == 0)'], {}), '(roi == 0)\n', (3662, 3672), True, 'import numpy as np\n'), ((4157, 4218), 'os.path.join', 'os.path.join', (['(base_path + line_segment_base_path + image_name)'], {}), '(base_path + line_segment_base_path + image_name)\n', (4169, 4218), False, 'import os\n'), ((1567, 1602), 'numpy.sum', 'np.sum', (['image_pre_processed'], {'axis': '(1)'}), '(image_pre_processed, axis=1)\n', (1573, 1602), True, 'import numpy as np\n'), ((3773, 3841), 'cv2.line', 'cv2.line', (['image_original', '(0, pair[0])', '(W, pair[0])', '(0, 0, 255)', '(1)'], {}), '(image_original, (0, pair[0]), (W, pair[0]), (0, 0, 255), 1)\n', (3781, 3841), False, 'import cv2\n'), ((3855, 3923), 'cv2.line', 'cv2.line', (['image_original', '(0, pair[1])', '(W, pair[1])', '(0, 255, 0)', '(1)'], {}), '(image_original, (0, pair[1]), (W, pair[1]), (0, 255, 0), 1)\n', (3863, 3923), False, 'import cv2\n')] |
import argparse
import os
import torch
from torchvision import utils
from tqdm import tqdm
from torch.utils import data
import numpy as np
import random
from PIL import Image
import torchvision.transforms as transforms
from dataset import DeepFashionDataset
from model import Generator
from util.dp2coor import getSymXYcoordinates
from util.coordinate_completion_model import define_G as define_CCM
def tensors2square(im, pose, sil):
width = im.shape[2]
diff = args.size - width
left = int((args.size-width)/2)
right = diff - left
im = torch.nn.functional.pad(input=im, pad=(right, left, 0, 0), mode='constant', value=0)
pose = torch.nn.functional.pad(input=pose, pad=(right, left, 0, 0), mode='constant', value=0)
sil = torch.nn.functional.pad(input=sil, pad=(right, left, 0, 0), mode='constant', value=0)
return im, pose, sil
def tensor2square(x):
width = x.shape[2]
diff = args.size - width
left = int((args.size-width)/2)
right = diff - left
x = torch.nn.functional.pad(input=x, pad=(right, left, 0, 0), mode='constant', value=0)
return x
def generate(args, g_ema, device, mean_latent):
with torch.no_grad():
g_ema.eval()
path = args.input_path
input_name = args.input_name
pose_name = args.target_name
# input
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
input_image = Image.open(os.path.join(path, input_name+'.png')).convert('RGB')
w, h = input_image.size
input_image = transform(input_image).float().to(device)
input_pose = np.array(Image.open(os.path.join(path, input_name+'_iuv.png')))
input_sil = np.array(Image.open(os.path.join(path, input_name+'_sil.png')))/255
# get partial coordinates from dense pose
dp_uv_lookup_256_np = np.load('util/dp_uv_lookup_256.npy')
uv_coor, uv_mask, uv_symm_mask = getSymXYcoordinates(input_pose, resolution = 512)
# union sil with densepose masks
input_sil = 1-((1-input_sil) * (input_pose[:, :, 0] == 0).astype('float'))
input_sil = torch.from_numpy(input_sil).float().unsqueeze(0)
input_pose = torch.from_numpy(input_pose).permute(2, 0, 1)
# target
target_pose = np.array(Image.open(os.path.join(path, pose_name+'_iuv.png')))
target_pose = torch.from_numpy(target_pose).permute(2, 0, 1)
# convert to square by centering
input_image, input_pose, input_sil = tensors2square(input_image, input_pose, input_sil)
target_pose = tensor2square(target_pose)
# add batch dimension
input_image = input_image.unsqueeze(0).float().to(device)
input_pose = input_pose.unsqueeze(0).float().to(device)
input_sil = input_sil.unsqueeze(0).float().to(device)
target_pose = target_pose.unsqueeze(0).float().to(device)
# complete partial coordinates
coor_completion_generator = define_CCM().cuda()
CCM_checkpoint = torch.load(args.CCM_pretrained_model)
coor_completion_generator.load_state_dict(CCM_checkpoint["g"])
coor_completion_generator.eval()
for param in coor_completion_generator.parameters():
coor_completion_generator.requires_grad = False
# uv coor preprocessing (put image in center)
shift = int((h-w)/2) # center shift
uv_coor[:,:,0] = uv_coor[:,:,0] + shift # put in center
uv_coor = ((2*uv_coor/(h-1))-1)
uv_coor = uv_coor*np.expand_dims(uv_mask,2) + (-10*(1-np.expand_dims(uv_mask,2)))
# coordinate completion
uv_coor_pytorch = torch.from_numpy(uv_coor).float().permute(2, 0, 1).unsqueeze(0) # from h,w,c to 1,c,h,w
uv_mask_pytorch = torch.from_numpy(uv_mask).unsqueeze(0).unsqueeze(0).float() #1xchw
with torch.no_grad():
coor_completion_generator.eval()
complete_coor = coor_completion_generator(uv_coor_pytorch.cuda(), uv_mask_pytorch.cuda())
# reposing
appearance = torch.cat([input_image, input_sil, complete_coor], 1)
output, _ = g_ema(appearance=appearance, pose=target_pose)
utils.save_image(
output[:, :, :, int(shift):args.size-int(shift)],
os.path.join(args.save_path, input_name+'_2_'+pose_name+'_vis.png'),
nrow=1,
normalize=True,
range=(-1, 1),
)
if __name__ == "__main__":
device = "cuda"
parser = argparse.ArgumentParser(description="inference")
parser.add_argument("--input_path", type=str, help="path to the input dataset")
parser.add_argument("--input_name", type=str, default="fashionWOMENDressesid0000262902_3back", help="input file name")
parser.add_argument("--target_name", type=str, default="fashionWOMENDressesid0000262902_1front", help="target file name")
parser.add_argument("--size", type=int, default=512, help="output image size of the generator")
parser.add_argument("--truncation", type=float, default=1, help="truncation ratio")
parser.add_argument("--truncation_mean", type=int, default=4096, help="number of vectors to calculate mean for the truncation")
parser.add_argument("--channel_multiplier", type=int, default=2, help="channel multiplier of the generator. config-f = 2, else = 1")
parser.add_argument("--pretrained_model", type=str, default="posewithstyle.pt", help="pose with style pretrained model")
parser.add_argument("--CCM_pretrained_model", type=str, default="CCM_epoch50.pt", help="pretrained coordinate completion model")
parser.add_argument("--save_path", type=str, default="./data/output", help="path to save output .data/output")
args = parser.parse_args()
args.latent = 2048
args.n_mlp = 8
if not os.path.exists(args.save_path):
os.makedirs(args.save_path)
g_ema = Generator(args.size, args.latent, args.n_mlp, channel_multiplier=args.channel_multiplier).to(device)
checkpoint = torch.load(args.pretrained_model)
g_ema.load_state_dict(checkpoint["g_ema"])
if args.truncation < 1:
with torch.no_grad():
mean_latent = g_ema.mean_latent(args.truncation_mean)
else:
mean_latent = None
generate(args, g_ema, device, mean_latent)
| [
"numpy.load",
"torch.from_numpy",
"argparse.ArgumentParser",
"os.makedirs",
"util.coordinate_completion_model.define_G",
"torch.load",
"os.path.exists",
"torch.cat",
"numpy.expand_dims",
"torchvision.transforms.ToTensor",
"model.Generator",
"util.dp2coor.getSymXYcoordinates",
"torchvision.tr... | [((557, 645), 'torch.nn.functional.pad', 'torch.nn.functional.pad', ([], {'input': 'im', 'pad': '(right, left, 0, 0)', 'mode': '"""constant"""', 'value': '(0)'}), "(input=im, pad=(right, left, 0, 0), mode='constant',\n value=0)\n", (580, 645), False, 'import torch\n'), ((653, 744), 'torch.nn.functional.pad', 'torch.nn.functional.pad', ([], {'input': 'pose', 'pad': '(right, left, 0, 0)', 'mode': '"""constant"""', 'value': '(0)'}), "(input=pose, pad=(right, left, 0, 0), mode=\n 'constant', value=0)\n", (676, 744), False, 'import torch\n'), ((750, 839), 'torch.nn.functional.pad', 'torch.nn.functional.pad', ([], {'input': 'sil', 'pad': '(right, left, 0, 0)', 'mode': '"""constant"""', 'value': '(0)'}), "(input=sil, pad=(right, left, 0, 0), mode='constant',\n value=0)\n", (773, 839), False, 'import torch\n'), ((1004, 1091), 'torch.nn.functional.pad', 'torch.nn.functional.pad', ([], {'input': 'x', 'pad': '(right, left, 0, 0)', 'mode': '"""constant"""', 'value': '(0)'}), "(input=x, pad=(right, left, 0, 0), mode='constant',\n value=0)\n", (1027, 1091), False, 'import torch\n'), ((4500, 4548), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""inference"""'}), "(description='inference')\n", (4523, 4548), False, 'import argparse\n'), ((5999, 6032), 'torch.load', 'torch.load', (['args.pretrained_model'], {}), '(args.pretrained_model)\n', (6009, 6032), False, 'import torch\n'), ((1159, 1174), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1172, 1174), False, 'import torch\n'), ((1878, 1914), 'numpy.load', 'np.load', (['"""util/dp_uv_lookup_256.npy"""'], {}), "('util/dp_uv_lookup_256.npy')\n", (1885, 1914), True, 'import numpy as np\n'), ((1957, 2004), 'util.dp2coor.getSymXYcoordinates', 'getSymXYcoordinates', (['input_pose'], {'resolution': '(512)'}), '(input_pose, resolution=512)\n', (1976, 2004), False, 'from util.dp2coor import getSymXYcoordinates\n'), ((3038, 3075), 'torch.load', 'torch.load', (['args.CCM_pretrained_model'], {}), '(args.CCM_pretrained_model)\n', (3048, 3075), False, 'import torch\n'), ((4060, 4113), 'torch.cat', 'torch.cat', (['[input_image, input_sil, complete_coor]', '(1)'], {}), '([input_image, input_sil, complete_coor], 1)\n', (4069, 4113), False, 'import torch\n'), ((5800, 5830), 'os.path.exists', 'os.path.exists', (['args.save_path'], {}), '(args.save_path)\n', (5814, 5830), False, 'import os\n'), ((5840, 5867), 'os.makedirs', 'os.makedirs', (['args.save_path'], {}), '(args.save_path)\n', (5851, 5867), False, 'import os\n'), ((3855, 3870), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3868, 3870), False, 'import torch\n'), ((4282, 4355), 'os.path.join', 'os.path.join', (['args.save_path', "(input_name + '_2_' + pose_name + '_vis.png')"], {}), "(args.save_path, input_name + '_2_' + pose_name + '_vis.png')\n", (4294, 4355), False, 'import os\n'), ((5881, 5975), 'model.Generator', 'Generator', (['args.size', 'args.latent', 'args.n_mlp'], {'channel_multiplier': 'args.channel_multiplier'}), '(args.size, args.latent, args.n_mlp, channel_multiplier=args.\n channel_multiplier)\n', (5890, 5975), False, 'from model import Generator\n'), ((6122, 6137), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6135, 6137), False, 'import torch\n'), ((1360, 1381), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1379, 1381), True, 'import torchvision.transforms as transforms\n'), ((1383, 1437), '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', (1403, 1437), True, 'import torchvision.transforms as transforms\n'), ((1665, 1708), 'os.path.join', 'os.path.join', (['path', "(input_name + '_iuv.png')"], {}), "(path, input_name + '_iuv.png')\n", (1677, 1708), False, 'import os\n'), ((2223, 2251), 'torch.from_numpy', 'torch.from_numpy', (['input_pose'], {}), '(input_pose)\n', (2239, 2251), False, 'import torch\n'), ((2329, 2371), 'os.path.join', 'os.path.join', (['path', "(pose_name + '_iuv.png')"], {}), "(path, pose_name + '_iuv.png')\n", (2341, 2371), False, 'import os\n'), ((2394, 2423), 'torch.from_numpy', 'torch.from_numpy', (['target_pose'], {}), '(target_pose)\n', (2410, 2423), False, 'import torch\n'), ((2993, 3005), 'util.coordinate_completion_model.define_G', 'define_CCM', ([], {}), '()\n', (3003, 3005), True, 'from util.coordinate_completion_model import define_G as define_CCM\n'), ((3538, 3564), 'numpy.expand_dims', 'np.expand_dims', (['uv_mask', '(2)'], {}), '(uv_mask, 2)\n', (3552, 3564), True, 'import numpy as np\n'), ((1473, 1512), 'os.path.join', 'os.path.join', (['path', "(input_name + '.png')"], {}), "(path, input_name + '.png')\n", (1485, 1512), False, 'import os\n'), ((1749, 1792), 'os.path.join', 'os.path.join', (['path', "(input_name + '_sil.png')"], {}), "(path, input_name + '_sil.png')\n", (1761, 1792), False, 'import os\n'), ((3574, 3600), 'numpy.expand_dims', 'np.expand_dims', (['uv_mask', '(2)'], {}), '(uv_mask, 2)\n', (3588, 3600), True, 'import numpy as np\n'), ((2153, 2180), 'torch.from_numpy', 'torch.from_numpy', (['input_sil'], {}), '(input_sil)\n', (2169, 2180), False, 'import torch\n'), ((3661, 3686), 'torch.from_numpy', 'torch.from_numpy', (['uv_coor'], {}), '(uv_coor)\n', (3677, 3686), False, 'import torch\n'), ((3775, 3800), 'torch.from_numpy', 'torch.from_numpy', (['uv_mask'], {}), '(uv_mask)\n', (3791, 3800), False, 'import torch\n')] |
# Advent of Code 2021 Day 20
# Author: <NAME>
# URL: https://adventofcode.com/2021/day/20
import numpy as np
from scipy.ndimage import convolve
def part_a(data: list[str]):
n = 2
key, _, *img = data
key = np.array([int(v == "#") for v in key])
img = np.array([[int(v == "#") for v in line] for line in img])
img = np.pad(np.array(img, dtype=int), n)
kernel = np.array([[1, 2, 4], [8, 16, 32], [64, 128, 256]])
for _ in range(n):
img = key[convolve(img, kernel)]
return img.sum()
def part_b(data: list[str]):
n = 50
key, _, *img = data
key = np.array([int(v == "#") for v in key])
img = np.array([[int(v == "#") for v in line] for line in img])
img = np.pad(np.array(img, dtype=int), n)
kernel = np.array([[1, 2, 4], [8, 16, 32], [64, 128, 256]])
for _ in range(n):
img = key[convolve(img, kernel)]
return img.sum()
| [
"numpy.array",
"scipy.ndimage.convolve"
] | [((386, 436), 'numpy.array', 'np.array', (['[[1, 2, 4], [8, 16, 32], [64, 128, 256]]'], {}), '([[1, 2, 4], [8, 16, 32], [64, 128, 256]])\n', (394, 436), True, 'import numpy as np\n'), ((766, 816), 'numpy.array', 'np.array', (['[[1, 2, 4], [8, 16, 32], [64, 128, 256]]'], {}), '([[1, 2, 4], [8, 16, 32], [64, 128, 256]])\n', (774, 816), True, 'import numpy as np\n'), ((344, 368), 'numpy.array', 'np.array', (['img'], {'dtype': 'int'}), '(img, dtype=int)\n', (352, 368), True, 'import numpy as np\n'), ((724, 748), 'numpy.array', 'np.array', (['img'], {'dtype': 'int'}), '(img, dtype=int)\n', (732, 748), True, 'import numpy as np\n'), ((479, 500), 'scipy.ndimage.convolve', 'convolve', (['img', 'kernel'], {}), '(img, kernel)\n', (487, 500), False, 'from scipy.ndimage import convolve\n'), ((859, 880), 'scipy.ndimage.convolve', 'convolve', (['img', 'kernel'], {}), '(img, kernel)\n', (867, 880), False, 'from scipy.ndimage import convolve\n')] |
import numpy as np
def isrowvector(m):
"""Check if the array has only one dimension
f = isrowvector(m)
function f = isrowvector(m)
<m> is a matrix
return whether <m> is 1 x n where n >= 0.
specifically:
f = isvector(m) & size(m,1)==1;
example:
isrowvector([[1,2]])
isrowvector([[1]])
isrowvector(np.zeros(1))
not isrowvector([])
"""
if not isinstance(m, np.ndarray):
m = np.asarray(m)
f = m.shape[0] == 1
return f
| [
"numpy.asarray"
] | [((443, 456), 'numpy.asarray', 'np.asarray', (['m'], {}), '(m)\n', (453, 456), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import numpy as np
x12 = np.array([95.25, 94.00, 95.50, 94.50])
x34 = np.array([230.00, 230.00, 230.26, 228.75, 229.75])
def sab(arr, mw):
return np.sqrt((np.sum((arr - mw)**2))/(arr.size - 1))
x12mw = np.mean(x12)
x12ab = sab(x12, x12mw)
x34mw = np.mean(x34)
x34ab = sab(x34, x34mw)
print("x12 = ", x12mw, " +- ", x12ab)
print("x34 = ", x34mw, " +- ", x34ab) | [
"numpy.mean",
"numpy.array",
"numpy.sum"
] | [((50, 85), 'numpy.array', 'np.array', (['[95.25, 94.0, 95.5, 94.5]'], {}), '([95.25, 94.0, 95.5, 94.5])\n', (58, 85), True, 'import numpy as np\n'), ((95, 143), 'numpy.array', 'np.array', (['[230.0, 230.0, 230.26, 228.75, 229.75]'], {}), '([230.0, 230.0, 230.26, 228.75, 229.75])\n', (103, 143), True, 'import numpy as np\n'), ((230, 242), 'numpy.mean', 'np.mean', (['x12'], {}), '(x12)\n', (237, 242), True, 'import numpy as np\n'), ((275, 287), 'numpy.mean', 'np.mean', (['x34'], {}), '(x34)\n', (282, 287), True, 'import numpy as np\n'), ((182, 205), 'numpy.sum', 'np.sum', (['((arr - mw) ** 2)'], {}), '((arr - mw) ** 2)\n', (188, 205), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
# Import libraries
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
# In[4]:
# Load input image in grayscale
img = cv.imread('hitchcock.png', 0)
kernel = np.ones((3,3), np.uint8)
# Functions
imgEroded = cv.erode(img, kernel)
imgDilate = cv.dilate(img, kernel)
imgOpened = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
imgClosed = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
# Image contour definition
Contour1 = img - imgEroded
Contour2 = imgDilate - img
# Output image resizing
plt.figure(figsize=(15,15))
# Alignment, ordering and display of the output images
plt.subplot(5,5,1)
plt.title("Original image:")
plt.imshow(img, cmap = 'gray')
plt.subplot(5,5,2)
plt.title("Eroded image:")
plt.imshow(imgEroded, cmap = 'gray')
plt.subplot(5,5,3)
plt.title("Dilated image:")
plt.imshow(imgDilate, cmap = 'gray')
plt.subplot(5,5,4)
plt.title("Image outline1:")
plt.imshow(Contour1, cmap = 'gray')
plt.subplot(5,5,5)
plt.title("Image outline2:")
plt.imshow(Contour2, cmap = 'gray')
plt.show ()
# In[ ]:
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"cv2.dilate",
"cv2.morphologyEx",
"matplotlib.pyplot.imshow",
"numpy.ones",
"cv2.imread",
"matplotlib.pyplot.figure",
"cv2.erode"
] | [((188, 217), 'cv2.imread', 'cv.imread', (['"""hitchcock.png"""', '(0)'], {}), "('hitchcock.png', 0)\n", (197, 217), True, 'import cv2 as cv\n'), ((227, 252), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.uint8'], {}), '((3, 3), np.uint8)\n', (234, 252), True, 'import numpy as np\n'), ((279, 300), 'cv2.erode', 'cv.erode', (['img', 'kernel'], {}), '(img, kernel)\n', (287, 300), True, 'import cv2 as cv\n'), ((313, 335), 'cv2.dilate', 'cv.dilate', (['img', 'kernel'], {}), '(img, kernel)\n', (322, 335), True, 'import cv2 as cv\n'), ((348, 391), 'cv2.morphologyEx', 'cv.morphologyEx', (['img', 'cv.MORPH_OPEN', 'kernel'], {}), '(img, cv.MORPH_OPEN, kernel)\n', (363, 391), True, 'import cv2 as cv\n'), ((404, 448), 'cv2.morphologyEx', 'cv.morphologyEx', (['img', 'cv.MORPH_CLOSE', 'kernel'], {}), '(img, cv.MORPH_CLOSE, kernel)\n', (419, 448), True, 'import cv2 as cv\n'), ((556, 584), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 15)'}), '(figsize=(15, 15))\n', (566, 584), True, 'import matplotlib.pyplot as plt\n'), ((640, 660), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(5)', '(5)', '(1)'], {}), '(5, 5, 1)\n', (651, 660), True, 'import matplotlib.pyplot as plt\n'), ((659, 687), 'matplotlib.pyplot.title', 'plt.title', (['"""Original image:"""'], {}), "('Original image:')\n", (668, 687), True, 'import matplotlib.pyplot as plt\n'), ((688, 716), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (698, 716), True, 'import matplotlib.pyplot as plt\n'), ((720, 740), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(5)', '(5)', '(2)'], {}), '(5, 5, 2)\n', (731, 740), True, 'import matplotlib.pyplot as plt\n'), ((739, 765), 'matplotlib.pyplot.title', 'plt.title', (['"""Eroded image:"""'], {}), "('Eroded image:')\n", (748, 765), True, 'import matplotlib.pyplot as plt\n'), ((766, 800), 'matplotlib.pyplot.imshow', 'plt.imshow', (['imgEroded'], {'cmap': '"""gray"""'}), "(imgEroded, cmap='gray')\n", (776, 800), True, 'import matplotlib.pyplot as plt\n'), ((804, 824), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(5)', '(5)', '(3)'], {}), '(5, 5, 3)\n', (815, 824), True, 'import matplotlib.pyplot as plt\n'), ((823, 850), 'matplotlib.pyplot.title', 'plt.title', (['"""Dilated image:"""'], {}), "('Dilated image:')\n", (832, 850), True, 'import matplotlib.pyplot as plt\n'), ((851, 885), 'matplotlib.pyplot.imshow', 'plt.imshow', (['imgDilate'], {'cmap': '"""gray"""'}), "(imgDilate, cmap='gray')\n", (861, 885), True, 'import matplotlib.pyplot as plt\n'), ((889, 909), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(5)', '(5)', '(4)'], {}), '(5, 5, 4)\n', (900, 909), True, 'import matplotlib.pyplot as plt\n'), ((908, 936), 'matplotlib.pyplot.title', 'plt.title', (['"""Image outline1:"""'], {}), "('Image outline1:')\n", (917, 936), True, 'import matplotlib.pyplot as plt\n'), ((937, 970), 'matplotlib.pyplot.imshow', 'plt.imshow', (['Contour1'], {'cmap': '"""gray"""'}), "(Contour1, cmap='gray')\n", (947, 970), True, 'import matplotlib.pyplot as plt\n'), ((974, 994), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(5)', '(5)', '(5)'], {}), '(5, 5, 5)\n', (985, 994), True, 'import matplotlib.pyplot as plt\n'), ((993, 1021), 'matplotlib.pyplot.title', 'plt.title', (['"""Image outline2:"""'], {}), "('Image outline2:')\n", (1002, 1021), True, 'import matplotlib.pyplot as plt\n'), ((1022, 1055), 'matplotlib.pyplot.imshow', 'plt.imshow', (['Contour2'], {'cmap': '"""gray"""'}), "(Contour2, cmap='gray')\n", (1032, 1055), True, 'import matplotlib.pyplot as plt\n'), ((1058, 1068), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1066, 1068), True, 'import matplotlib.pyplot as plt\n')] |
"""SequenceDataset class."""
from typing import Callable, Tuple
import warnings
import numpy as np
import tensorflow as tf
from ..util import relative_shuffle
class SequenceDataset(tf.keras.utils.Sequence):
"""Custom Sequence class used to feed data into model.fit.
Args:
x_list: List of inputs.
y_list: List of targets.
batch_size: Size of one mini-batch.
augment_fn: Function to augment one mini-batch of x and y.
format_fn: Function to format raw data to model input.
overfit: If only one batch should be used thereby causing overfitting.
"""
def __init__(
self,
x: np.ndarray,
y: np.ndarray,
batch_size: int = 16,
augment_fn: Callable = None,
format_fn: Callable = None,
overfit: bool = False,
):
self.x = x
self.y = y
self.batch_size = batch_size
self.augment_fn = augment_fn
self.format_fn = format_fn
self.overfit = overfit
def __len__(self) -> int:
"""Return length of the dataset in unit of batch size."""
if len(self.x) <= self.batch_size:
warnings.warn(
"Batch size larger than dataset, setting batch size to match length of dataset",
RuntimeWarning,
)
self.batch_size = len(self.x)
return int(np.floor(len(self.x) / self.batch_size))
def __getitem__(self, idx) -> Tuple[np.ndarray, np.ndarray]:
"""Return a single batch."""
if self.overfit:
idx = 0
begin = idx * self.batch_size
end = (idx + 1) * self.batch_size
batch_x = self.x[begin:end]
batch_y = self.y[begin:end]
if self.format_fn:
batch_x, batch_y = self.format_fn(batch_x, batch_y)
if self.augment_fn:
batch_x, batch_y = self.augment_fn(batch_x, batch_y)
if batch_x.ndim < 4:
batch_x = np.expand_dims(batch_x, -1)
if batch_y.ndim < 4:
batch_y = np.expand_dims(batch_y, -1)
return batch_x, batch_y
def on_epoch_end(self) -> None:
"""Shuffle data after every epoch."""
if not self.overfit:
self.x, self.y = relative_shuffle(self.x, self.y)
| [
"warnings.warn",
"numpy.expand_dims"
] | [((1162, 1282), 'warnings.warn', 'warnings.warn', (['"""Batch size larger than dataset, setting batch size to match length of dataset"""', 'RuntimeWarning'], {}), "(\n 'Batch size larger than dataset, setting batch size to match length of dataset'\n , RuntimeWarning)\n", (1175, 1282), False, 'import warnings\n'), ((1962, 1989), 'numpy.expand_dims', 'np.expand_dims', (['batch_x', '(-1)'], {}), '(batch_x, -1)\n', (1976, 1989), True, 'import numpy as np\n'), ((2041, 2068), 'numpy.expand_dims', 'np.expand_dims', (['batch_y', '(-1)'], {}), '(batch_y, -1)\n', (2055, 2068), True, 'import numpy as np\n')] |
import os
import torch
from torch import nn
import numpy as np
import torch.nn.functional as F
class InterpretTransformer(object):
def __init__(self, model):
self.model = model
self.model.eval()
def transition_attention_maps(self, input, index=None, start_layer=4, steps=20, with_integral=True, first_state=False):
b = input.shape[0]
output = self.model(input, register_hook=True)
if index == None:
index = np.argmax(output.cpu().data.numpy(), axis=-1)
one_hot = np.zeros((b, output.size()[-1]), dtype=np.float32)
one_hot[np.arange(b), index] = 1
one_hot_vector = one_hot
one_hot = torch.from_numpy(one_hot).requires_grad_(True)
one_hot = torch.sum(one_hot.cuda() * output)
self.model.zero_grad()
one_hot.backward(retain_graph=True)
b, h, s, _ = self.model.blocks[-1].attn.get_attention_map().shape
num_blocks = len(self.model.blocks)
states = self.model.blocks[-1].attn.get_attention_map().mean(1)[:, 0, :].reshape(b, 1, s)
for i in range(start_layer, num_blocks-1)[::-1]:
attn = self.model.blocks[i].attn.get_attention_map().mean(1)
states_ = states
states = states.bmm(attn)
states += states_
total_gradients = torch.zeros(b, h, s, s).cuda()
for alpha in np.linspace(0, 1, steps):
# forward propagation
data_scaled = input * alpha
# backward propagation
output = self.model(data_scaled, register_hook=True)
one_hot = np.zeros((b, output.size()[-1]), dtype=np.float32)
one_hot[np.arange(b), index] = 1
one_hot_vector = one_hot
one_hot = torch.from_numpy(one_hot).requires_grad_(True)
one_hot = torch.sum(one_hot.cuda() * output)
self.model.zero_grad()
one_hot.backward(retain_graph=True)
# cal grad
gradients = self.model.blocks[-1].attn.get_attn_gradients()
total_gradients += gradients
if with_integral:
W_state = (total_gradients / steps).clamp(min=0).mean(1)[:, 0, :].reshape(b, 1, s)
else:
W_state = self.model.blocks[-1].attn.get_attn_gradients().clamp(min=0).mean(1)[:, 0, :].reshape(b, 1, s)
if first_state:
states = self.model.blocks[-1].attn.get_attention_map().mean(1)[:, 0, :].reshape(b, 1, s)
states = states * W_state
return states[:, 0, 1:]
def attribution(self, input, index=None, start_layer=0):
b = input.shape[0]
output = self.model(input)
kwargs = {"alpha": 1}
if index == None:
index = np.argmax(output.cpu().data.numpy(), axis=-1)
one_hot = np.zeros((b, output.size()[-1]), dtype=np.float32)
one_hot[np.arange(b), index] = 1
one_hot_vector = one_hot
one_hot = torch.from_numpy(one_hot).requires_grad_(True)
one_hot = torch.sum(one_hot.cuda() * output)
self.model.zero_grad()
one_hot.backward(retain_graph=True)
self.model.relprop(torch.tensor(one_hot_vector).cuda(), **kwargs)
b, h, s, _ = self.model.blocks[-1].attn.get_attn_gradients().shape
num_blocks = len(self.model.blocks)
# first_block
attn = self.model.blocks[start_layer].attn.get_attn_cam()
grad = self.model.blocks[start_layer].attn.get_attn_gradients()
attr = (grad * attn).clamp(min=0).mean(1)
# add residual
eye = torch.eye(s).expand(b, s, s).cuda()
attr = attr + eye
attr = attr / attr.sum(dim=-1, keepdim=True)
attrs = attr
for i in range(start_layer+1, num_blocks):
attn = self.model.blocks[i].attn.get_attn_cam()
grad = self.model.blocks[i].attn.get_attn_gradients()
attr = (grad * attn).clamp(min=0).mean(1)
# add residual
eye = torch.eye(s).expand(b, s, s).cuda()
attr = attr + eye
attr = attr / attr.sum(dim=-1, keepdim=True)
attrs = attr.bmm(attrs)
return attrs[:, 0, 1:]
def raw_attn(self, input, index=None):
b = input.shape[0]
output = self.model(input, register_hook=True)
attr = self.model.blocks[-1].attn.get_attention_map().mean(dim=1)
return attr[:, 0, 1:]
def rollout(self, input, index=None, start_layer=0):
b = input.shape[0]
output = self.model(input, register_hook=True)
if index == None:
index = np.argmax(output.cpu().data.numpy(), axis=-1)
one_hot = np.zeros((b, output.size()[-1]), dtype=np.float32)
one_hot[np.arange(b), index] = 1
one_hot_vector = one_hot
one_hot = torch.from_numpy(one_hot).requires_grad_(True)
one_hot = torch.sum(one_hot.cuda() * output)
self.model.zero_grad()
one_hot.backward(retain_graph=True)
b, h, s, _ = self.model.blocks[-1].attn.get_attn_gradients().shape
num_blocks = len(self.model.blocks)
attrs = torch.eye(s).expand(b, h, s, s).cuda()
for i in range(start_layer, num_blocks):
attr = self.model.blocks[i].attn.get_attention_map()
eye = torch.eye(s).expand(b, h, s, s).cuda()
attr = attr + eye
attr = attr / attr.sum(dim=-1, keepdim=True)
attrs = (attr @ attrs)
attrs = attrs.mean(1)
return attrs[:, 0, 1:] | [
"torch.eye",
"numpy.arange",
"numpy.linspace",
"torch.zeros",
"torch.tensor",
"torch.from_numpy"
] | [((1384, 1408), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'steps'], {}), '(0, 1, steps)\n', (1395, 1408), True, 'import numpy as np\n'), ((606, 618), 'numpy.arange', 'np.arange', (['b'], {}), '(b)\n', (615, 618), True, 'import numpy as np\n'), ((682, 707), 'torch.from_numpy', 'torch.from_numpy', (['one_hot'], {}), '(one_hot)\n', (698, 707), False, 'import torch\n'), ((1332, 1355), 'torch.zeros', 'torch.zeros', (['b', 'h', 's', 's'], {}), '(b, h, s, s)\n', (1343, 1355), False, 'import torch\n'), ((2908, 2920), 'numpy.arange', 'np.arange', (['b'], {}), '(b)\n', (2917, 2920), True, 'import numpy as np\n'), ((2984, 3009), 'torch.from_numpy', 'torch.from_numpy', (['one_hot'], {}), '(one_hot)\n', (3000, 3009), False, 'import torch\n'), ((4798, 4810), 'numpy.arange', 'np.arange', (['b'], {}), '(b)\n', (4807, 4810), True, 'import numpy as np\n'), ((4874, 4899), 'torch.from_numpy', 'torch.from_numpy', (['one_hot'], {}), '(one_hot)\n', (4890, 4899), False, 'import torch\n'), ((1686, 1698), 'numpy.arange', 'np.arange', (['b'], {}), '(b)\n', (1695, 1698), True, 'import numpy as np\n'), ((1770, 1795), 'torch.from_numpy', 'torch.from_numpy', (['one_hot'], {}), '(one_hot)\n', (1786, 1795), False, 'import torch\n'), ((3188, 3216), 'torch.tensor', 'torch.tensor', (['one_hot_vector'], {}), '(one_hot_vector)\n', (3200, 3216), False, 'import torch\n'), ((3603, 3615), 'torch.eye', 'torch.eye', (['s'], {}), '(s)\n', (3612, 3615), False, 'import torch\n'), ((5187, 5199), 'torch.eye', 'torch.eye', (['s'], {}), '(s)\n', (5196, 5199), False, 'import torch\n'), ((4024, 4036), 'torch.eye', 'torch.eye', (['s'], {}), '(s)\n', (4033, 4036), False, 'import torch\n'), ((5359, 5371), 'torch.eye', 'torch.eye', (['s'], {}), '(s)\n', (5368, 5371), False, 'import torch\n')] |
from sklearn.datasets import load_digits
import numpy as np
from numpy import linalg as linalg
import math
import matplotlib.pyplot as plt
def hw1p3c(train_data, train_target, test_data, test_target, plot_gate):
# digits = load_digits()
# d_data = digits.data
# d_target = digits.target
#
# divider = 1797-100
#
# x_train = d_data[:divider,:] # N*D
# x_test = d_data[divider:,:]
#
# t_train = d_target[0:divider]
# t_test = d_target[divider:]
x_train = train_data # N*D
x_test = test_data
t_train = train_target
t_test = test_target
classes = t_train==0
for idx in range(1,10,1):
class_i = t_train==idx
classes = np.vstack((classes,class_i))
n_elem = np.sum(classes,1)
# cla = classes[0]
# x_train[cla].shape
# classes.shape
means = np.zeros((10,64))
for idx,cla in enumerate(classes):
# print(x_train[cla].shape)
means[idx] = np.mean(x_train[cla], 0)
mu = np.mean(x_train,0)
Sw = np.zeros((64,64))
for idx in range(0,10,1):
Sw_i = np.dot((x_train[classes[idx]] - means[idx]).transpose(), (x_train[classes[idx]] - means[idx]))
Sw = Sw + Sw_i
Sb = np.zeros((64,64))
for idx in range(0,10,1):
Sb = Sb + n_elem[idx]*np.dot( (x_train[classes[idx]] - mu).transpose(),x_train[classes[idx]]-mu )
A = np.dot(linalg.pinv(Sw),Sb)
lam,vec = linalg.eig( A )
w = vec[:,lam>0.0000001]
w = w[:,0:2] # D*K=2
w = w/linalg.norm(w)
# Now project it onto 2D and histogram the projected points:
proj_data = dict()
if plot_gate:
plt.subplot(1,2,1)
for labName,cl in enumerate(classes):
proj_data_i= np.dot(x_train[cl],w) # N,D * D,K = N,K
x,y = np.transpose(proj_data_i) # k1,k2 = K*N
if plot_gate:
plt.scatter(x,y,label = ("class"+str(labName)))
proj_data[labName] = proj_data_i # proj_data: C * N*K
if plot_gate:
plt.legend()
plt.title("Training set's projected points in the last run of validation")
if plot_gate:
plt.subplot(1,2,2)
for labName,cl in enumerate(classes):
projdata = np.dot(x_test[np.where(t_test == int(labName))],w) # N,D * D,K = N,K
x,y = np.transpose(projdata ) # k1,k2 = K*N
if plot_gate:
plt.scatter(x,y,label = ("class"+str(labName)))
# proj_data[labName] = projdata # proj_data: C * N*K
if plot_gate:
plt.legend()
plt.title("Testing set's projected points in the last run of validation")
# Gaussian generative modeling:
def gaus_param(X):
# X is of N*K
N = len(X)
mu = np.mean(X,0) # 1*K
Sigma = np.dot( np.transpose(X-mu), X-mu) / (N-1) # K*K
return mu,Sigma
mu = dict() # N=1 * K=2
Sigma = dict()
prior = dict() # prior probability estimator
for idx in proj_data:
mu[idx],Sigma[idx] = gaus_param(proj_data[idx])
prior[idx] = n_elem[idx]/sum(n_elem)
def disc(mu,Sigma,prior,test):
# This is a gasussian discriminant on 2D
# test: N*K
# mu: 1*K
# Sigma: K*K
# return: int class 0-9 N*1
if test.ndim <2:
test = test[None,:]
n_class = len(mu)
result = np.zeros(len(test))
for ord,x in enumerate(test): # x: 1*K
logp = np.zeros(n_class)
for idx in range(0,n_class,1):
# distance = 0.5 * np.dot( (x-mu[idx]) )
logp[idx] = math.log(prior[idx]) - 0.5*math.log( linalg.det(Sigma[idx]) ) - 0.5* np.dot( ( x-mu[idx]),np.dot( linalg.inv(Sigma[idx]), (x-mu[idx]).transpose() ))
result[ord] = np.argmax(logp)
return result
proj_test = np.dot(x_test[:],w) # N*D. D*K = N*K
result_test = disc(mu,Sigma,prior,proj_test)
err = 1-np.mean(result_test==t_test[:])
y_test = t_test
proj_test = np.dot(x_train[:],w) # N*D. D*K = N*K
result_train = disc(mu,Sigma,prior,proj_test)
err_train = 1-np.mean(result_train==t_train[:])
y_train = t_train
return err, err_train, y_test, result_test, y_train, result_train | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"numpy.sum",
"numpy.argmax",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.transpose",
"numpy.linalg.eig",
"numpy.mean",
"numpy.linalg.norm",
"numpy.linalg.det",
"numpy.linalg.inv",
"numpy.dot",
"math.log",
"numpy.linalg.pinv",
... | [((746, 764), 'numpy.sum', 'np.sum', (['classes', '(1)'], {}), '(classes, 1)\n', (752, 764), True, 'import numpy as np\n'), ((846, 864), 'numpy.zeros', 'np.zeros', (['(10, 64)'], {}), '((10, 64))\n', (854, 864), True, 'import numpy as np\n'), ((995, 1014), 'numpy.mean', 'np.mean', (['x_train', '(0)'], {}), '(x_train, 0)\n', (1002, 1014), True, 'import numpy as np\n'), ((1024, 1042), 'numpy.zeros', 'np.zeros', (['(64, 64)'], {}), '((64, 64))\n', (1032, 1042), True, 'import numpy as np\n'), ((1215, 1233), 'numpy.zeros', 'np.zeros', (['(64, 64)'], {}), '((64, 64))\n', (1223, 1233), True, 'import numpy as np\n'), ((1419, 1432), 'numpy.linalg.eig', 'linalg.eig', (['A'], {}), '(A)\n', (1429, 1432), True, 'from numpy import linalg as linalg\n'), ((3779, 3799), 'numpy.dot', 'np.dot', (['x_test[:]', 'w'], {}), '(x_test[:], w)\n', (3785, 3799), True, 'import numpy as np\n'), ((3949, 3970), 'numpy.dot', 'np.dot', (['x_train[:]', 'w'], {}), '(x_train[:], w)\n', (3955, 3970), True, 'import numpy as np\n'), ((703, 732), 'numpy.vstack', 'np.vstack', (['(classes, class_i)'], {}), '((classes, class_i))\n', (712, 732), True, 'import numpy as np\n'), ((960, 984), 'numpy.mean', 'np.mean', (['x_train[cla]', '(0)'], {}), '(x_train[cla], 0)\n', (967, 984), True, 'import numpy as np\n'), ((1385, 1400), 'numpy.linalg.pinv', 'linalg.pinv', (['Sw'], {}), '(Sw)\n', (1396, 1400), True, 'from numpy import linalg as linalg\n'), ((1499, 1513), 'numpy.linalg.norm', 'linalg.norm', (['w'], {}), '(w)\n', (1510, 1513), True, 'from numpy import linalg as linalg\n'), ((1634, 1654), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (1645, 1654), True, 'import matplotlib.pyplot as plt\n'), ((1716, 1738), 'numpy.dot', 'np.dot', (['x_train[cl]', 'w'], {}), '(x_train[cl], w)\n', (1722, 1738), True, 'import numpy as np\n'), ((1770, 1795), 'numpy.transpose', 'np.transpose', (['proj_data_i'], {}), '(proj_data_i)\n', (1782, 1795), True, 'import numpy as np\n'), ((1982, 1994), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1992, 1994), True, 'import matplotlib.pyplot as plt\n'), ((2003, 2077), 'matplotlib.pyplot.title', 'plt.title', (['"""Training set\'s projected points in the last run of validation"""'], {}), '("Training set\'s projected points in the last run of validation")\n', (2012, 2077), True, 'import matplotlib.pyplot as plt\n'), ((2106, 2126), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (2117, 2126), True, 'import matplotlib.pyplot as plt\n'), ((2269, 2291), 'numpy.transpose', 'np.transpose', (['projdata'], {}), '(projdata)\n', (2281, 2291), True, 'import numpy as np\n'), ((2479, 2491), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2489, 2491), True, 'import matplotlib.pyplot as plt\n'), ((2500, 2573), 'matplotlib.pyplot.title', 'plt.title', (['"""Testing set\'s projected points in the last run of validation"""'], {}), '("Testing set\'s projected points in the last run of validation")\n', (2509, 2573), True, 'import matplotlib.pyplot as plt\n'), ((2692, 2705), 'numpy.mean', 'np.mean', (['X', '(0)'], {}), '(X, 0)\n', (2699, 2705), True, 'import numpy as np\n'), ((3878, 3911), 'numpy.mean', 'np.mean', (['(result_test == t_test[:])'], {}), '(result_test == t_test[:])\n', (3885, 3911), True, 'import numpy as np\n'), ((4056, 4091), 'numpy.mean', 'np.mean', (['(result_train == t_train[:])'], {}), '(result_train == t_train[:])\n', (4063, 4091), True, 'import numpy as np\n'), ((3393, 3410), 'numpy.zeros', 'np.zeros', (['n_class'], {}), '(n_class)\n', (3401, 3410), True, 'import numpy as np\n'), ((3723, 3738), 'numpy.argmax', 'np.argmax', (['logp'], {}), '(logp)\n', (3732, 3738), True, 'import numpy as np\n'), ((2735, 2755), 'numpy.transpose', 'np.transpose', (['(X - mu)'], {}), '(X - mu)\n', (2747, 2755), True, 'import numpy as np\n'), ((3546, 3566), 'math.log', 'math.log', (['prior[idx]'], {}), '(prior[idx])\n', (3554, 3566), False, 'import math\n'), ((3583, 3605), 'numpy.linalg.det', 'linalg.det', (['Sigma[idx]'], {}), '(Sigma[idx])\n', (3593, 3605), True, 'from numpy import linalg as linalg\n'), ((3646, 3668), 'numpy.linalg.inv', 'linalg.inv', (['Sigma[idx]'], {}), '(Sigma[idx])\n', (3656, 3668), True, 'from numpy import linalg as linalg\n')] |
'''
Copyright (c) 2018 by <NAME>
This file is part of Statistical Parameter Optimization Tool for Python(SPOTPY).
:author: <NAME>
'''
from . import _algorithm
import numpy as np
class mle(_algorithm):
"""
This class holds the Maximum Likelihood (MLE) algorithm,
based on a simple uphill method as presented by Houska et al (2015):
<NAME>., <NAME>., <NAME>. and <NAME>. (2015)
SPOTting Model Parameters Using a Ready-Made Python Package, PLoS ONE.
"""
def __init__(self, *args, **kwargs):
'''
Implements the Maximum Likelihood Estimation algorithm.
Input
----------
spot_setup: class
model: function
Should be callable with a parameter combination of the parameter-function
and return an list of simulation results (as long as evaluation list)
parameter: function
When called, it should return a random parameter combination. Which can
be e.g. uniform or Gaussian
objectivefunction: function
Should return the objectivefunction for a given list of a model simulation and
observation.
evaluation: function
Should return the true values as return by the model.
dbname: str
* Name of the database where parameter, objectivefunction value and simulation results will be saved.
dbformat: str
* ram: fast suited for short sampling time. no file will be created and results are saved in an array.
* csv: A csv file will be created, which you can import afterwards.
save_sim: boolean
* True: Simulation results will be saved
* False: Simulation results will not be saved
'''
kwargs['optimization_direction'] = 'maximize'
kwargs['algorithm_name'] = 'Maximum Likelihood Estimation (MLE) algorithm'
super(mle, self).__init__(*args, **kwargs)
def check_par_validity(self, par):
if len(par) == len(self.min_bound) and len(par) == len(self.max_bound):
for i in range(len(par)):
if par[i] < self.min_bound[i]:
par[i] = self.min_bound[i]
if par[i] > self.max_bound[i]:
par[i] = self.max_bound[i]
else:
print('ERROR Bounds have not the same lenghts as Parameterarray')
return par
def sample(self, repetitions):
self.set_repetiton(repetitions)
print(
'Starting the MLE algotrithm with ' +
str(repetitions) +
' repetitions...')
# Define stepsize of MLE
stepsizes = self.parameter()['step'] # array of stepsizes
accepted = 0.0
self.min_bound, self.max_bound = self.parameter(
)['minbound'], self.parameter()['maxbound']
# Metropolis-Hastings iterations.
burnIn = int(repetitions / 10)
likes = []
pars = []
sims = []
print('burnIn...')
for i in range(burnIn):
randompar = self.parameter()['random']
pars.append(randompar)
_, _, simulations = self.simulate((i, randompar))
sims.append(simulations)
like = self.postprocessing(i, randompar, simulations)
likes.append(like)
old_like = max(likes)
old_par = pars[likes.index(old_like)]
print('Beginn Random Walk')
for rep in range(repetitions - burnIn):
# Suggest new candidate from Gaussian proposal distribution.
# Use stepsize provided for every dimension.
new_par = np.random.normal(loc=old_par, scale=stepsizes)
new_par = self.check_par_validity(new_par)
_, _, new_simulations = self.simulate((i, new_par))
new_like = self.postprocessing(
rep + burnIn, new_par, new_simulations)
# Accept new candidate in Monte-Carlo fashing.
if (new_like > old_like):
accepted = accepted + 1.0 # monitor acceptance
old_par = new_par
old_like = new_like
#self.status(rep, new_like, new_par)
self.final_call()
| [
"numpy.random.normal"
] | [((3666, 3712), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'old_par', 'scale': 'stepsizes'}), '(loc=old_par, scale=stepsizes)\n', (3682, 3712), True, 'import numpy as np\n')] |
################################################################################
#
# test_wham.py - testing the pyfeat wham class
#
# author: <NAME> <ch<EMAIL>h.wehmeyer@fu-berlin.de>
# author: <NAME> <<EMAIL>>
#
################################################################################
from nose.tools import assert_raises, assert_true
from pyfeat.estimator import WHAM
from pytram import ExpressionError, NotConvergedWarning
import numpy as np
#WHAM testing
def test_expression_error_None():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), None )
def test_expression_error_int():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), 5 )
def test_expression_error_list():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), [1,2] )
def test_expression_error_dim():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), np.ones( shape=(2,2,2), dtype=np.float64 ) )
def test_expression_error_markov():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), np.ones( shape=(2,2), dtype=np.float64 ) )
def test_expression_error_therm():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), np.ones( shape=(1,3), dtype=np.float64 ) )
def test_expression_error_int16():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), np.ones( shape=(2,3), dtype=np.int16 ) )
def test_expression_error_float32():
assert_raises( ExpressionError, WHAM, np.ones( shape=(2,3,3), dtype=np.intc ), np.ones( shape=(2,3), dtype=np.float32 ) )
| [
"numpy.ones"
] | [((551, 590), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (558, 590), True, 'import numpy as np\n'), ((674, 713), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (681, 713), True, 'import numpy as np\n'), ((795, 834), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (802, 834), True, 'import numpy as np\n'), ((919, 958), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (926, 958), True, 'import numpy as np\n'), ((960, 1002), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 2, 2)', 'dtype': 'np.float64'}), '(shape=(2, 2, 2), dtype=np.float64)\n', (967, 1002), True, 'import numpy as np\n'), ((1083, 1122), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (1090, 1122), True, 'import numpy as np\n'), ((1124, 1163), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 2)', 'dtype': 'np.float64'}), '(shape=(2, 2), dtype=np.float64)\n', (1131, 1163), True, 'import numpy as np\n'), ((1244, 1283), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (1251, 1283), True, 'import numpy as np\n'), ((1285, 1324), 'numpy.ones', 'np.ones', ([], {'shape': '(1, 3)', 'dtype': 'np.float64'}), '(shape=(1, 3), dtype=np.float64)\n', (1292, 1324), True, 'import numpy as np\n'), ((1405, 1444), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (1412, 1444), True, 'import numpy as np\n'), ((1446, 1483), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3)', 'dtype': 'np.int16'}), '(shape=(2, 3), dtype=np.int16)\n', (1453, 1483), True, 'import numpy as np\n'), ((1566, 1605), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3, 3)', 'dtype': 'np.intc'}), '(shape=(2, 3, 3), dtype=np.intc)\n', (1573, 1605), True, 'import numpy as np\n'), ((1607, 1646), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 3)', 'dtype': 'np.float32'}), '(shape=(2, 3), dtype=np.float32)\n', (1614, 1646), True, 'import numpy as np\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import edward as ed
import numpy as np
import tensorflow as tf
from edward.models import Bernoulli, Categorical, Mixture, Normal
class test_copy_class(tf.test.TestCase):
def test_scope(self):
with self.test_session():
x = tf.constant(2.0)
x_new = ed.copy(x, scope='new_scope')
self.assertTrue(x_new.name.startswith('new_scope'))
def test_replace_itself(self):
with self.test_session():
x = tf.constant(2.0)
y = tf.constant(3.0)
x_new = ed.copy(x, {x: y}, replace_itself=False)
self.assertEqual(x_new.eval(), 2.0)
x_new = ed.copy(x, {x: y}, replace_itself=True)
self.assertEqual(x_new.eval(), 3.0)
def test_copy_q(self):
with self.test_session() as sess:
x = tf.constant(2.0)
y = tf.random_normal([])
x_new = ed.copy(x, {x: y}, replace_itself=True, copy_q=False)
x_new_val, y_val = sess.run([x_new, y])
self.assertEqual(x_new_val, y_val)
x_new = ed.copy(x, {x: y}, replace_itself=True, copy_q=True)
x_new_val, x_val, y_val = sess.run([x_new, x, y])
self.assertNotEqual(x_new_val, x_val)
self.assertNotEqual(x_new_val, y_val)
def test_copy_parent_rvs(self):
with self.test_session() as sess:
x = Normal(0.0, 1.0)
y = tf.constant(3.0)
z = x * y
z_new = ed.copy(z, scope='no_copy_parent_rvs', copy_parent_rvs=False)
self.assertEqual(len(ed.random_variables()), 1)
z_new = ed.copy(z, scope='copy_parent_rvs', copy_parent_rvs=True)
self.assertEqual(len(ed.random_variables()), 2)
def test_placeholder(self):
with self.test_session() as sess:
x = tf.placeholder(tf.float32, name="CustomName")
y = tf.constant(3.0)
z = x * y
z_new = ed.copy(z)
self.assertEqual(sess.run(z_new, feed_dict={x: 4.0}), 12.0)
def test_variable(self):
with self.test_session() as sess:
x = tf.Variable(2.0, name="CustomName")
y = tf.constant(3.0)
z = x * y
z_new = ed.copy(z)
tf.variables_initializer([x]).run()
self.assertEqual(z_new.eval(), 6.0)
def test_queue(self):
with self.test_session() as sess:
tensor = tf.constant([0.0, 1.0, 2.0, 3.0])
x = tf.train.batch([tensor], batch_size=2, enqueue_many=True,
name='CustomName')
y = tf.constant(3.0)
z = x * y
z_new = ed.copy(z)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
self.assertAllEqual(sess.run(z_new), np.array([0.0, 3.0]))
self.assertAllEqual(sess.run(z_new), np.array([6.0, 9.0]))
coord.request_stop()
coord.join(threads)
def test_list(self):
with self.test_session() as sess:
x = Normal(tf.constant(0.0), tf.constant(0.1))
y = Normal(tf.constant(10.0), tf.constant(0.1))
cat = Categorical(logits=tf.zeros(5))
components = [Normal(x, tf.constant(0.1))
for _ in range(5)]
z = Mixture(cat=cat, components=components)
z_new = ed.copy(z, {x: y.value()})
self.assertGreater(z_new.value().eval(), 5.0)
def test_random(self):
with self.test_session() as sess:
ed.set_seed(3742)
x = tf.random_normal([])
x_copy = ed.copy(x)
result_copy, result = sess.run([x_copy, x])
self.assertNotAlmostEquals(result_copy, result)
def test_scan(self):
with self.test_session() as sess:
ed.set_seed(42)
op = tf.scan(lambda a, x: a + x, tf.constant([2.0, 3.0, 1.0]))
copy_op = ed.copy(op)
result_copy, result = sess.run([copy_op, op])
self.assertAllClose(result_copy, [2.0, 5.0, 6.0])
self.assertAllClose(result, [2.0, 5.0, 6.0])
def test_swap_tensor_tensor(self):
with self.test_session():
x = tf.constant(2.0)
y = tf.constant(3.0)
z = x * y
qx = tf.constant(4.0)
z_new = ed.copy(z, {x: qx})
self.assertEqual(z_new.eval(), 12.0)
def test_swap_placeholder_tensor(self):
with self.test_session():
x = tf.placeholder(tf.float32, name="CustomName")
y = tf.constant(3.0)
z = x * y
qx = tf.constant(4.0)
z_new = ed.copy(z, {x: qx})
self.assertEqual(z_new.eval(), 12.0)
def test_swap_tensor_placeholder(self):
with self.test_session() as sess:
x = tf.constant(2.0)
y = tf.constant(3.0)
z = x * y
qx = tf.placeholder(tf.float32, name="CustomName")
z_new = ed.copy(z, {x: qx})
self.assertEqual(sess.run(z_new, feed_dict={qx: 4.0}), 12.0)
def test_swap_variable_tensor(self):
with self.test_session():
x = tf.Variable(2.0, name="CustomName")
y = tf.constant(3.0)
z = x * y
qx = tf.constant(4.0)
z_new = ed.copy(z, {x: qx})
tf.variables_initializer([x]).run()
self.assertEqual(z_new.eval(), 12.0)
def test_swap_tensor_variable(self):
with self.test_session() as sess:
x = tf.constant(2.0)
y = tf.constant(3.0)
z = x * y
qx = tf.Variable(4.0, name="CustomName")
z_new = ed.copy(z, {x: qx})
tf.variables_initializer([qx]).run()
self.assertEqual(z_new.eval(), 12.0)
def test_swap_rv_rv(self):
with self.test_session():
ed.set_seed(325135)
x = Normal(0.0, 0.1)
y = tf.constant(1.0)
z = x * y
qx = Normal(10.0, 0.1)
z_new = ed.copy(z, {x: qx})
self.assertGreater(z_new.eval(), 5.0)
def test_swap_rv_tensor(self):
with self.test_session():
ed.set_seed(289362)
x = Normal(0.0, 0.1)
y = tf.constant(1.0)
z = x * y
qx = Normal(10.0, 0.1)
z_new = ed.copy(z, {x: qx.value()})
self.assertGreater(z_new.eval(), 5.0)
def test_swap_tensor_rv(self):
with self.test_session():
ed.set_seed(95258)
x = Normal(0.0, 0.1)
y = tf.constant(1.0)
z = x * y
qx = Normal(10.0, 0.1)
z_new = ed.copy(z, {x.value(): qx})
self.assertGreater(z_new.eval(), 5.0)
def test_ordering_rv_tensor(self):
# Check that random variables are copied correctly in dependency
# structure.
with self.test_session() as sess:
ed.set_seed(12432)
x = Bernoulli(logits=0.0)
y = tf.cast(x, tf.float32)
y_new = ed.copy(y)
x_new = ed.copy(x)
x_new_val, y_new_val = sess.run([x_new, y_new])
self.assertEqual(x_new_val, y_new_val)
def test_ordering_rv_rv(self):
# Check that random variables are copied correctly in dependency
# structure.
with self.test_session() as sess:
ed.set_seed(21782)
x = Normal(loc=0.0, scale=10.0)
x_abs = tf.abs(x)
y = Normal(loc=x_abs, scale=1e-8)
y_new = ed.copy(y)
x_new = ed.copy(x)
x_new_val, y_new_val = sess.run([x_new, y_new])
self.assertAllClose(abs(x_new_val), y_new_val)
if __name__ == '__main__':
tf.test.main()
| [
"tensorflow.train.Coordinator",
"tensorflow.variables_initializer",
"tensorflow.Variable",
"edward.set_seed",
"tensorflow.train.batch",
"edward.random_variables",
"tensorflow.test.main",
"edward.copy",
"tensorflow.abs",
"tensorflow.train.start_queue_runners",
"tensorflow.placeholder",
"tensorf... | [((6928, 6942), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (6940, 6942), True, 'import tensorflow as tf\n'), ((348, 364), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (359, 364), True, 'import tensorflow as tf\n'), ((379, 408), 'edward.copy', 'ed.copy', (['x'], {'scope': '"""new_scope"""'}), "(x, scope='new_scope')\n", (386, 408), True, 'import edward as ed\n'), ((541, 557), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (552, 557), True, 'import tensorflow as tf\n'), ((568, 584), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (579, 584), True, 'import tensorflow as tf\n'), ((599, 639), 'edward.copy', 'ed.copy', (['x', '{x: y}'], {'replace_itself': '(False)'}), '(x, {x: y}, replace_itself=False)\n', (606, 639), True, 'import edward as ed\n'), ((696, 735), 'edward.copy', 'ed.copy', (['x', '{x: y}'], {'replace_itself': '(True)'}), '(x, {x: y}, replace_itself=True)\n', (703, 735), True, 'import edward as ed\n'), ((852, 868), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (863, 868), True, 'import tensorflow as tf\n'), ((879, 899), 'tensorflow.random_normal', 'tf.random_normal', (['[]'], {}), '([])\n', (895, 899), True, 'import tensorflow as tf\n'), ((914, 967), 'edward.copy', 'ed.copy', (['x', '{x: y}'], {'replace_itself': '(True)', 'copy_q': '(False)'}), '(x, {x: y}, replace_itself=True, copy_q=False)\n', (921, 967), True, 'import edward as ed\n'), ((1069, 1121), 'edward.copy', 'ed.copy', (['x', '{x: y}'], {'replace_itself': '(True)', 'copy_q': '(True)'}), '(x, {x: y}, replace_itself=True, copy_q=True)\n', (1076, 1121), True, 'import edward as ed\n'), ((1349, 1365), 'edward.models.Normal', 'Normal', (['(0.0)', '(1.0)'], {}), '(0.0, 1.0)\n', (1355, 1365), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((1376, 1392), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (1387, 1392), True, 'import tensorflow as tf\n'), ((1423, 1484), 'edward.copy', 'ed.copy', (['z'], {'scope': '"""no_copy_parent_rvs"""', 'copy_parent_rvs': '(False)'}), "(z, scope='no_copy_parent_rvs', copy_parent_rvs=False)\n", (1430, 1484), True, 'import edward as ed\n'), ((1553, 1610), 'edward.copy', 'ed.copy', (['z'], {'scope': '"""copy_parent_rvs"""', 'copy_parent_rvs': '(True)'}), "(z, scope='copy_parent_rvs', copy_parent_rvs=True)\n", (1560, 1610), True, 'import edward as ed\n'), ((1744, 1789), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""CustomName"""'}), "(tf.float32, name='CustomName')\n", (1758, 1789), True, 'import tensorflow as tf\n'), ((1800, 1816), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (1811, 1816), True, 'import tensorflow as tf\n'), ((1847, 1857), 'edward.copy', 'ed.copy', (['z'], {}), '(z)\n', (1854, 1857), True, 'import edward as ed\n'), ((2000, 2035), 'tensorflow.Variable', 'tf.Variable', (['(2.0)'], {'name': '"""CustomName"""'}), "(2.0, name='CustomName')\n", (2011, 2035), True, 'import tensorflow as tf\n'), ((2046, 2062), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (2057, 2062), True, 'import tensorflow as tf\n'), ((2093, 2103), 'edward.copy', 'ed.copy', (['z'], {}), '(z)\n', (2100, 2103), True, 'import edward as ed\n'), ((2266, 2299), 'tensorflow.constant', 'tf.constant', (['[0.0, 1.0, 2.0, 3.0]'], {}), '([0.0, 1.0, 2.0, 3.0])\n', (2277, 2299), True, 'import tensorflow as tf\n'), ((2310, 2386), 'tensorflow.train.batch', 'tf.train.batch', (['[tensor]'], {'batch_size': '(2)', 'enqueue_many': '(True)', 'name': '"""CustomName"""'}), "([tensor], batch_size=2, enqueue_many=True, name='CustomName')\n", (2324, 2386), True, 'import tensorflow as tf\n'), ((2422, 2438), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (2433, 2438), True, 'import tensorflow as tf\n'), ((2469, 2479), 'edward.copy', 'ed.copy', (['z'], {}), '(z)\n', (2476, 2479), True, 'import edward as ed\n'), ((2494, 2516), 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), '()\n', (2514, 2516), True, 'import tensorflow as tf\n'), ((2533, 2574), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), '(coord=coord)\n', (2561, 2574), True, 'import tensorflow as tf\n'), ((3068, 3107), 'edward.models.Mixture', 'Mixture', ([], {'cat': 'cat', 'components': 'components'}), '(cat=cat, components=components)\n', (3075, 3107), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((3271, 3288), 'edward.set_seed', 'ed.set_seed', (['(3742)'], {}), '(3742)\n', (3282, 3288), True, 'import edward as ed\n'), ((3299, 3319), 'tensorflow.random_normal', 'tf.random_normal', (['[]'], {}), '([])\n', (3315, 3319), True, 'import tensorflow as tf\n'), ((3335, 3345), 'edward.copy', 'ed.copy', (['x'], {}), '(x)\n', (3342, 3345), True, 'import edward as ed\n'), ((3519, 3534), 'edward.set_seed', 'ed.set_seed', (['(42)'], {}), '(42)\n', (3530, 3534), True, 'import edward as ed\n'), ((3620, 3631), 'edward.copy', 'ed.copy', (['op'], {}), '(op)\n', (3627, 3631), True, 'import edward as ed\n'), ((3870, 3886), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (3881, 3886), True, 'import tensorflow as tf\n'), ((3897, 3913), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (3908, 3913), True, 'import tensorflow as tf\n'), ((3941, 3957), 'tensorflow.constant', 'tf.constant', (['(4.0)'], {}), '(4.0)\n', (3952, 3957), True, 'import tensorflow as tf\n'), ((3972, 3991), 'edward.copy', 'ed.copy', (['z', '{x: qx}'], {}), '(z, {x: qx})\n', (3979, 3991), True, 'import edward as ed\n'), ((4118, 4163), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""CustomName"""'}), "(tf.float32, name='CustomName')\n", (4132, 4163), True, 'import tensorflow as tf\n'), ((4174, 4190), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (4185, 4190), True, 'import tensorflow as tf\n'), ((4218, 4234), 'tensorflow.constant', 'tf.constant', (['(4.0)'], {}), '(4.0)\n', (4229, 4234), True, 'import tensorflow as tf\n'), ((4249, 4268), 'edward.copy', 'ed.copy', (['z', '{x: qx}'], {}), '(z, {x: qx})\n', (4256, 4268), True, 'import edward as ed\n'), ((4403, 4419), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (4414, 4419), True, 'import tensorflow as tf\n'), ((4430, 4446), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (4441, 4446), True, 'import tensorflow as tf\n'), ((4474, 4519), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""CustomName"""'}), "(tf.float32, name='CustomName')\n", (4488, 4519), True, 'import tensorflow as tf\n'), ((4534, 4553), 'edward.copy', 'ed.copy', (['z', '{x: qx}'], {}), '(z, {x: qx})\n', (4541, 4553), True, 'import edward as ed\n'), ((4701, 4736), 'tensorflow.Variable', 'tf.Variable', (['(2.0)'], {'name': '"""CustomName"""'}), "(2.0, name='CustomName')\n", (4712, 4736), True, 'import tensorflow as tf\n'), ((4747, 4763), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (4758, 4763), True, 'import tensorflow as tf\n'), ((4791, 4807), 'tensorflow.constant', 'tf.constant', (['(4.0)'], {}), '(4.0)\n', (4802, 4807), True, 'import tensorflow as tf\n'), ((4822, 4841), 'edward.copy', 'ed.copy', (['z', '{x: qx}'], {}), '(z, {x: qx})\n', (4829, 4841), True, 'import edward as ed\n'), ((5015, 5031), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (5026, 5031), True, 'import tensorflow as tf\n'), ((5042, 5058), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (5053, 5058), True, 'import tensorflow as tf\n'), ((5086, 5121), 'tensorflow.Variable', 'tf.Variable', (['(4.0)'], {'name': '"""CustomName"""'}), "(4.0, name='CustomName')\n", (5097, 5121), True, 'import tensorflow as tf\n'), ((5136, 5155), 'edward.copy', 'ed.copy', (['z', '{x: qx}'], {}), '(z, {x: qx})\n', (5143, 5155), True, 'import edward as ed\n'), ((5308, 5327), 'edward.set_seed', 'ed.set_seed', (['(325135)'], {}), '(325135)\n', (5319, 5327), True, 'import edward as ed\n'), ((5338, 5354), 'edward.models.Normal', 'Normal', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (5344, 5354), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((5365, 5381), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), '(1.0)\n', (5376, 5381), True, 'import tensorflow as tf\n'), ((5409, 5426), 'edward.models.Normal', 'Normal', (['(10.0)', '(0.1)'], {}), '(10.0, 0.1)\n', (5415, 5426), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((5441, 5460), 'edward.copy', 'ed.copy', (['z', '{x: qx}'], {}), '(z, {x: qx})\n', (5448, 5460), True, 'import edward as ed\n'), ((5575, 5594), 'edward.set_seed', 'ed.set_seed', (['(289362)'], {}), '(289362)\n', (5586, 5594), True, 'import edward as ed\n'), ((5605, 5621), 'edward.models.Normal', 'Normal', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (5611, 5621), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((5632, 5648), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), '(1.0)\n', (5643, 5648), True, 'import tensorflow as tf\n'), ((5676, 5693), 'edward.models.Normal', 'Normal', (['(10.0)', '(0.1)'], {}), '(10.0, 0.1)\n', (5682, 5693), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((5850, 5868), 'edward.set_seed', 'ed.set_seed', (['(95258)'], {}), '(95258)\n', (5861, 5868), True, 'import edward as ed\n'), ((5879, 5895), 'edward.models.Normal', 'Normal', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (5885, 5895), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((5906, 5922), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), '(1.0)\n', (5917, 5922), True, 'import tensorflow as tf\n'), ((5950, 5967), 'edward.models.Normal', 'Normal', (['(10.0)', '(0.1)'], {}), '(10.0, 0.1)\n', (5956, 5967), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((6222, 6240), 'edward.set_seed', 'ed.set_seed', (['(12432)'], {}), '(12432)\n', (6233, 6240), True, 'import edward as ed\n'), ((6251, 6272), 'edward.models.Bernoulli', 'Bernoulli', ([], {'logits': '(0.0)'}), '(logits=0.0)\n', (6260, 6272), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((6283, 6305), 'tensorflow.cast', 'tf.cast', (['x', 'tf.float32'], {}), '(x, tf.float32)\n', (6290, 6305), True, 'import tensorflow as tf\n'), ((6320, 6330), 'edward.copy', 'ed.copy', (['y'], {}), '(y)\n', (6327, 6330), True, 'import edward as ed\n'), ((6345, 6355), 'edward.copy', 'ed.copy', (['x'], {}), '(x)\n', (6352, 6355), True, 'import edward as ed\n'), ((6619, 6637), 'edward.set_seed', 'ed.set_seed', (['(21782)'], {}), '(21782)\n', (6630, 6637), True, 'import edward as ed\n'), ((6648, 6675), 'edward.models.Normal', 'Normal', ([], {'loc': '(0.0)', 'scale': '(10.0)'}), '(loc=0.0, scale=10.0)\n', (6654, 6675), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((6690, 6699), 'tensorflow.abs', 'tf.abs', (['x'], {}), '(x)\n', (6696, 6699), True, 'import tensorflow as tf\n'), ((6710, 6740), 'edward.models.Normal', 'Normal', ([], {'loc': 'x_abs', 'scale': '(1e-08)'}), '(loc=x_abs, scale=1e-08)\n', (6716, 6740), False, 'from edward.models import Bernoulli, Categorical, Mixture, Normal\n'), ((6754, 6764), 'edward.copy', 'ed.copy', (['y'], {}), '(y)\n', (6761, 6764), True, 'import edward as ed\n'), ((6779, 6789), 'edward.copy', 'ed.copy', (['x'], {}), '(x)\n', (6786, 6789), True, 'import edward as ed\n'), ((2618, 2638), 'numpy.array', 'np.array', (['[0.0, 3.0]'], {}), '([0.0, 3.0])\n', (2626, 2638), True, 'import numpy as np\n'), ((2683, 2703), 'numpy.array', 'np.array', (['[6.0, 9.0]'], {}), '([6.0, 9.0])\n', (2691, 2703), True, 'import numpy as np\n'), ((2837, 2853), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), '(0.0)\n', (2848, 2853), True, 'import tensorflow as tf\n'), ((2855, 2871), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {}), '(0.1)\n', (2866, 2871), True, 'import tensorflow as tf\n'), ((2890, 2907), 'tensorflow.constant', 'tf.constant', (['(10.0)'], {}), '(10.0)\n', (2901, 2907), True, 'import tensorflow as tf\n'), ((2909, 2925), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {}), '(0.1)\n', (2920, 2925), True, 'import tensorflow as tf\n'), ((3574, 3602), 'tensorflow.constant', 'tf.constant', (['[2.0, 3.0, 1.0]'], {}), '([2.0, 3.0, 1.0])\n', (3585, 3602), True, 'import tensorflow as tf\n'), ((1512, 1533), 'edward.random_variables', 'ed.random_variables', ([], {}), '()\n', (1531, 1533), True, 'import edward as ed\n'), ((1638, 1659), 'edward.random_variables', 'ed.random_variables', ([], {}), '()\n', (1657, 1659), True, 'import edward as ed\n'), ((2110, 2139), 'tensorflow.variables_initializer', 'tf.variables_initializer', (['[x]'], {}), '([x])\n', (2134, 2139), True, 'import tensorflow as tf\n'), ((2958, 2969), 'tensorflow.zeros', 'tf.zeros', (['(5)'], {}), '(5)\n', (2966, 2969), True, 'import tensorflow as tf\n'), ((3001, 3017), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {}), '(0.1)\n', (3012, 3017), True, 'import tensorflow as tf\n'), ((4848, 4877), 'tensorflow.variables_initializer', 'tf.variables_initializer', (['[x]'], {}), '([x])\n', (4872, 4877), True, 'import tensorflow as tf\n'), ((5162, 5192), 'tensorflow.variables_initializer', 'tf.variables_initializer', (['[qx]'], {}), '([qx])\n', (5186, 5192), True, 'import tensorflow as tf\n')] |
from __future__ import print_function, division
# Standard
#from itertools import izip
#from ctypes.util import find_library
from os.path import realpath, dirname
import ctypes_interface
import ctypes as C
import collections
# Scientific
import numpy as np
# Hotspotter
from hscom import __common__
print, print_, print_on, print_off, rrr, profile, printDBG =\
__common__.init(__name__, module_prefix='[hes]', DEBUG=False, initmpl=False)
#============================
# hesaff ctypes interface
#============================
# numpy dtypes
kpts_dtype = np.float32
desc_dtype = np.uint8
# ctypes
FLAGS_RW = 'aligned, c_contiguous, writeable'
obj_t = C.c_void_p
kpts_t = np.ctypeslib.ndpointer(dtype=kpts_dtype, ndim=2, flags=FLAGS_RW)
desc_t = np.ctypeslib.ndpointer(dtype=desc_dtype, ndim=2, flags=FLAGS_RW)
str_t = C.c_char_p
int_t = C.c_int
float_t = C.c_float
# THE ORDER OF THIS LIST IS IMPORTANT!
hesaff_typed_params = [
# Pyramid Params
(int_t, 'numberOfScales', 3), # number of scale per octave
(float_t, 'threshold', 16.0 / 3.0), # noise dependent threshold on the response (sensitivity)
(float_t, 'edgeEigenValueRatio', 10.0), # ratio of the eigenvalues
(int_t, 'border', 5), # number of pixels ignored at the border of image
# Affine Shape Params
(int_t, 'maxIterations', 16), # number of affine shape interations
(float_t, 'convergenceThreshold', 0.05), # maximum deviation from isotropic shape at convergence
(int_t, 'smmWindowSize', 19), # width and height of the SMM mask
(float_t, 'mrSize', 3.0 * np.sqrt(3.0)), # size of the measurement region (as multiple of the feature scale)
# SIFT params
(int_t, 'spatialBins', 4),
(int_t, 'orientationBins', 8),
(float_t, 'maxBinValue', 0.2),
# Shared params
(float_t, 'initialSigma', 1.6), # amount of smoothing applied to the initial level of first octave
(int_t, 'patchSize', 41), # width and height of the patch
# My params
(float_t, 'scale_min', -1.0),
(float_t, 'scale_max', -1.0),
]
OrderedDict = collections.OrderedDict
hesaff_param_dict = OrderedDict([(key, val) for (type_, key, val) in hesaff_typed_params])
hesaff_param_types = [type_ for (type_, key, val) in hesaff_typed_params]
def load_hesaff_clib():
'''
Specificially loads the hesaff lib and defines its functions
'''
# Get the root directory which should have the dynamic library in it
#root_dir = realpath(dirname(__file__)) if '__file__' in vars() else realpath(os.getcwd())
root_dir = realpath(dirname(__file__))
libname = 'hesaff'
hesaff_lib, def_cfunc = ctypes_interface.load_clib(libname, root_dir)
# Expose extern C Functions
def_cfunc(int_t, 'detect', [obj_t])
def_cfunc(None, 'exportArrays', [obj_t, int_t, kpts_t, desc_t])
def_cfunc(None, 'extractDesc', [obj_t, int_t, kpts_t, desc_t])
def_cfunc(obj_t, 'new_hesaff', [str_t])
def_cfunc(obj_t, 'new_hesaff_from_params', [str_t] + hesaff_param_types)
return hesaff_lib
# Create a global interface to the hesaff lib
hesaff_lib = load_hesaff_clib()
#============================
# hesaff python interface
#============================
def _make_hesaff_cpp_params(**kwargs):
hesaff_params = hesaff_param_dict.copy()
for key, val in kwargs.iteritems():
if key in hesaff_params:
hesaff_params[key] = val
else:
print('[pyhesaff] WARNING: key=%r is not known' % key)
def new_hesaff(img_fpath, **kwargs):
# Make detector and read image
hesaff_params = hesaff_param_dict.copy()
hesaff_params.update(kwargs)
hesaff_args = hesaff_params.values()
hesaff_ptr = hesaff_lib.new_hesaff_from_params(realpath(img_fpath), *hesaff_args)
return hesaff_ptr
def detect_kpts(img_fpath, use_adaptive_scale=False, **kwargs):
#print('Detecting Keypoints')
hesaff_ptr = new_hesaff(img_fpath, **kwargs)
# Return the number of keypoints detected
nKpts = hesaff_lib.detect(hesaff_ptr)
# Allocate arrays
kpts = np.empty((nKpts, 5), kpts_dtype)
desc = np.empty((nKpts, 128), desc_dtype)
# Populate arrays
hesaff_lib.exportArrays(hesaff_ptr, nKpts, kpts, desc)
# Adapt scale if requested
if use_adaptive_scale:
#print('Adapting Scale')
kpts, desc = adapt_scale(img_fpath, kpts)
return kpts, desc
def adapt_scale(img_fpath, kpts):
import ellipse
nScales = 16
nSamples = 16
low, high = -1, 2
adapted_kpts = ellipse.adaptive_scale(img_fpath, kpts, nScales, low, high, nSamples)
adapted_desc = extract_desc(img_fpath, adapted_kpts)
return adapted_kpts, adapted_desc
def extract_desc(img_fpath, kpts, **kwargs):
hesaff_ptr = new_hesaff(img_fpath, **kwargs)
nKpts = len(kpts)
# allocate memory for new descriptors
desc = np.empty((nKpts, 128), desc_dtype)
kpts = np.ascontiguousarray(kpts) # kpts might not be contiguous
# extract descriptors at given locations
hesaff_lib.extractDesc(hesaff_ptr, nKpts, kpts, desc)
return desc
| [
"numpy.ctypeslib.ndpointer",
"ctypes_interface.load_clib",
"numpy.empty",
"os.path.dirname",
"os.path.realpath",
"ellipse.adaptive_scale",
"numpy.ascontiguousarray",
"hscom.__common__.init",
"numpy.sqrt"
] | [((365, 441), 'hscom.__common__.init', '__common__.init', (['__name__'], {'module_prefix': '"""[hes]"""', 'DEBUG': '(False)', 'initmpl': '(False)'}), "(__name__, module_prefix='[hes]', DEBUG=False, initmpl=False)\n", (380, 441), False, 'from hscom import __common__\n'), ((682, 746), 'numpy.ctypeslib.ndpointer', 'np.ctypeslib.ndpointer', ([], {'dtype': 'kpts_dtype', 'ndim': '(2)', 'flags': 'FLAGS_RW'}), '(dtype=kpts_dtype, ndim=2, flags=FLAGS_RW)\n', (704, 746), True, 'import numpy as np\n'), ((759, 823), 'numpy.ctypeslib.ndpointer', 'np.ctypeslib.ndpointer', ([], {'dtype': 'desc_dtype', 'ndim': '(2)', 'flags': 'FLAGS_RW'}), '(dtype=desc_dtype, ndim=2, flags=FLAGS_RW)\n', (781, 823), True, 'import numpy as np\n'), ((2721, 2766), 'ctypes_interface.load_clib', 'ctypes_interface.load_clib', (['libname', 'root_dir'], {}), '(libname, root_dir)\n', (2747, 2766), False, 'import ctypes_interface\n'), ((4182, 4214), 'numpy.empty', 'np.empty', (['(nKpts, 5)', 'kpts_dtype'], {}), '((nKpts, 5), kpts_dtype)\n', (4190, 4214), True, 'import numpy as np\n'), ((4226, 4260), 'numpy.empty', 'np.empty', (['(nKpts, 128)', 'desc_dtype'], {}), '((nKpts, 128), desc_dtype)\n', (4234, 4260), True, 'import numpy as np\n'), ((4636, 4705), 'ellipse.adaptive_scale', 'ellipse.adaptive_scale', (['img_fpath', 'kpts', 'nScales', 'low', 'high', 'nSamples'], {}), '(img_fpath, kpts, nScales, low, high, nSamples)\n', (4658, 4705), False, 'import ellipse\n'), ((4972, 5006), 'numpy.empty', 'np.empty', (['(nKpts, 128)', 'desc_dtype'], {}), '((nKpts, 128), desc_dtype)\n', (4980, 5006), True, 'import numpy as np\n'), ((5018, 5044), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['kpts'], {}), '(kpts)\n', (5038, 5044), True, 'import numpy as np\n'), ((2651, 2668), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (2658, 2668), False, 'from os.path import realpath, dirname\n'), ((3855, 3874), 'os.path.realpath', 'realpath', (['img_fpath'], {}), '(img_fpath)\n', (3863, 3874), False, 'from os.path import realpath, dirname\n'), ((1644, 1656), 'numpy.sqrt', 'np.sqrt', (['(3.0)'], {}), '(3.0)\n', (1651, 1656), True, 'import numpy as np\n')] |
import numpy as np
from .pointcloud_utils import *
def downsample_kitti(points, ring, verticle_switch=True, horizontal_switch=True):
if verticle_switch:
ring_remained = [33, 32, 29, 27, 25, 23, 21, 19, 16, 14, 12, 10, 8, 6, 4, 2]
points = points[np.in1d(ring,ring_remained)] # faster
if horizontal_switch:
distances = np.array(get_distances_2d(points)).T
distances = np.fabs(distances[1:] - distances[:-1])
np.append(distances,0)
half_mask = np.arange(0,points.shape[0]-1,2)
mask = np.ones(points.shape[0], dtype=bool)
mask[half_mask[np.any((distances[half_mask] < 0.1,distances[half_mask-1] < 0.1),axis=0)]] = False
points = points[mask]
return points
def downsample_nusc_v2(points, ring):
# if points.shape[1]!=5:
# print("points attribution do not contains ring num..")
# return points
points_mask = np.all([ring>16 ,ring<26],axis=0)
points = points[points_mask]
return points
def upsample_nusc_v1(points, ring):
if points.shape[0]>0:
distances = np.array(get_distances_2d(points)).T
points_upsample = (points[:-1] + points[1:])/2
mask = np.all((ring[:-1]!=25, abs(distances[1:] - distances[:-1])<0.1, distances[1:]>0.1 , distances[:-1]>0.1),axis=0)
points_upsample = points_upsample[mask]
if points_upsample.shape[0]>0:
# points_upsample[:,4] = 0
points = np.vstack((points, points_upsample))
return points
| [
"numpy.ones",
"numpy.any",
"numpy.append",
"numpy.fabs",
"numpy.arange",
"numpy.vstack",
"numpy.all",
"numpy.in1d"
] | [((913, 951), 'numpy.all', 'np.all', (['[ring > 16, ring < 26]'], {'axis': '(0)'}), '([ring > 16, ring < 26], axis=0)\n', (919, 951), True, 'import numpy as np\n'), ((408, 447), 'numpy.fabs', 'np.fabs', (['(distances[1:] - distances[:-1])'], {}), '(distances[1:] - distances[:-1])\n', (415, 447), True, 'import numpy as np\n'), ((456, 479), 'numpy.append', 'np.append', (['distances', '(0)'], {}), '(distances, 0)\n', (465, 479), True, 'import numpy as np\n'), ((499, 535), 'numpy.arange', 'np.arange', (['(0)', '(points.shape[0] - 1)', '(2)'], {}), '(0, points.shape[0] - 1, 2)\n', (508, 535), True, 'import numpy as np\n'), ((547, 583), 'numpy.ones', 'np.ones', (['points.shape[0]'], {'dtype': 'bool'}), '(points.shape[0], dtype=bool)\n', (554, 583), True, 'import numpy as np\n'), ((267, 295), 'numpy.in1d', 'np.in1d', (['ring', 'ring_remained'], {}), '(ring, ring_remained)\n', (274, 295), True, 'import numpy as np\n'), ((1447, 1483), 'numpy.vstack', 'np.vstack', (['(points, points_upsample)'], {}), '((points, points_upsample))\n', (1456, 1483), True, 'import numpy as np\n'), ((607, 683), 'numpy.any', 'np.any', (['(distances[half_mask] < 0.1, distances[half_mask - 1] < 0.1)'], {'axis': '(0)'}), '((distances[half_mask] < 0.1, distances[half_mask - 1] < 0.1), axis=0)\n', (613, 683), True, 'import numpy as np\n')] |
from __future__ import print_function
import numpy as np
from openmdao.api import ExplicitComponent
class ConvertVelocity(ExplicitComponent):
"""
Convert the freestream velocity magnitude into a velocity vector at each
evaluation point. In this case, each of the panels sees the same velocity.
This really just helps us set up the velocities for use in the VLM analysis.
Parameters
----------
alpha : float
The angle of attack for the aircraft (all lifting surfaces) in degrees.
v : float
The freestream velocity magnitude.
Returns
-------
freestream_velocities[system_size, 3] : numpy array
The rotated freestream velocities at each evaluation point for all
lifting surfaces. system_size is the sum of the count of all panels
for all lifting surfaces.
"""
def initialize(self):
self.options.declare('surfaces', types=list)
def setup(self):
surfaces = self.options['surfaces']
system_size = 0
# Loop through each surface and cumulatively add the number of panels
# to obtain system_size.
for surface in surfaces:
mesh=surface['mesh']
nx = mesh.shape[0]
ny = mesh.shape[1]
name = surface['name']
system_size += (nx - 1) * (ny - 1)
self.system_size = system_size
self.add_input('alpha', val=0., units='deg')
self.add_input('v', val=1., units='m/s')
self.add_output('freestream_velocities', shape=(system_size, 3), units='m/s')
self.declare_partials('freestream_velocities', 'alpha')
self.declare_partials('freestream_velocities', 'v')
def compute(self, inputs, outputs):
# Rotate the freestream velocities based on the angle of attack.
# Here we assume there is no beta, or sideslip angle.
alpha = inputs['alpha'][0] * np.pi / 180.
cosa = np.cos(alpha)
sina = np.sin(alpha)
v_inf = inputs['v'][0] * np.array([cosa, 0., sina])
outputs['freestream_velocities'][:, :] = v_inf
def compute_partials(self, inputs, J):
alpha = inputs['alpha'][0] * np.pi / 180.
cosa = np.cos(alpha)
sina = np.sin(alpha)
J['freestream_velocities','v'] = np.tile(np.array([cosa, 0., sina]), self.system_size)
J['freestream_velocities','alpha'] = np.tile(inputs['v'][0] * np.array([-sina, 0., cosa]) * np.pi/180., self.system_size)
| [
"numpy.sin",
"numpy.array",
"numpy.cos"
] | [((1940, 1953), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (1946, 1953), True, 'import numpy as np\n'), ((1969, 1982), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (1975, 1982), True, 'import numpy as np\n'), ((2207, 2220), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (2213, 2220), True, 'import numpy as np\n'), ((2236, 2249), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (2242, 2249), True, 'import numpy as np\n'), ((2016, 2043), 'numpy.array', 'np.array', (['[cosa, 0.0, sina]'], {}), '([cosa, 0.0, sina])\n', (2024, 2043), True, 'import numpy as np\n'), ((2300, 2327), 'numpy.array', 'np.array', (['[cosa, 0.0, sina]'], {}), '([cosa, 0.0, sina])\n', (2308, 2327), True, 'import numpy as np\n'), ((2416, 2444), 'numpy.array', 'np.array', (['[-sina, 0.0, cosa]'], {}), '([-sina, 0.0, cosa])\n', (2424, 2444), True, 'import numpy as np\n')] |
from sklearn.preprocessing import LabelBinarizer
import numpy as np
class CustomLabelBinarizer(LabelBinarizer):
def transform(self, y):
Y = super(CustomLabelBinarizer, self).transform(y)
if self.y_type_ == 'binary':
return np.hstack((1-Y,Y))
else:
return Y
def inverse_transform(self, Y, threshold=None):
if self.y_type_ == 'binary':
return super(CustomLabelBinarizer, self).inverser_transform(Y[:, 1], threshold)
else:
return super(CustomLabelBinarizer, self).inverser_transform(Y, threshold)
| [
"numpy.hstack"
] | [((256, 277), 'numpy.hstack', 'np.hstack', (['(1 - Y, Y)'], {}), '((1 - Y, Y))\n', (265, 277), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Functions used to generate manufacturable ply drop layouts with guide-based
blending
- format_ply_drops and format_ply_drops2
format the ply drop layouts
- ply_drops_rules
deletes the ply drop layouts that does not satisfy the ply drop guidelines
- randomly_pdl_guide
randomly generates manufacturable ply drop layouts
Guidelines:
1: The first two outer plies should not be stopped
2: The number of ply drops should be minimal (not butt joints)
3: The ply drops should be distributed as evenly as possible along the
thickness of the laminates
4: If this is not exactly possible the ply drops should rather be
concentrated in the larger groups (because smaller groups have a
smaller design space)
5: Then ply drops away from the middle plane are prefered to limit fibre
waviness
"""
import sys
import time
import random
import numpy as np
import scipy.special
sys.path.append(r'C:\BELLA')
from src.BELLA.parameters import Parameters
from src.BELLA.constraints import Constraints
from src.BELLA.obj_function import ObjFunction
from src.guidelines.ply_drop_spacing import calc_penalty_spacing
from src.BELLA.pdl_tools import format_ply_drops
from src.BELLA.pdl_tools import ply_drops_at_each_boundaries
from src.BELLA.pdl_tools import format_ply_drops2
from src.divers.pretty_print import print_lampam, print_ss, print_list_ss
def randomly_pdl_guide(
boundaries,
n_ply_drops,
n_max,
parameters,
obj_func_param,
constraints,
multipanel,
n_pdl_max=1,
pdl_before=None,
pdl_after=None,
last_group=False,
covering_top=False,
covering_bottom=False,
has_middle_ply=False,
middle_ply_indices=np.array((), dtype='int16')):
"""
randomly generates ply drop layouts that best satisfy the spacing and
stacking rules within a limited time.
INPUTS
- n_ply_drops: list of the number of ply drops for each group compared to
the groups thickest of the thickest laminate
- n_max: maximum number of plies for the group
- n_pdl_max: number of ply drop layouts asked
- pdl_before: matrix of ply drop layouts for the group placed above
- pdl_after: matrix of ply drop layouts for the group placed below
- last_group: true for the last groups
- constraints: design guidelines
- parameters: optimiser parameters
- multpanel: multi-panel structure
- obj_func_param: objective function parameters
- if covering_top = True, the top ply cannot be dropped
- if covering_bottom = True, the bottom ply cannot be dropped
- has_middle_ply: True if a panel has a middle ply
"""
# print('boundaries', boundaries)
# print('n_ply_drops', n_ply_drops)
# print('n_max', n_max)
# print('n_pdl_max', n_pdl_max)
# print('last_group', last_group)
# print('pdl_before', pdl_before)
# print('has_middle_ply', has_middle_ply)
# print('middle_ply_indices', middle_ply_indices)
# # boundaries one panel to another by increasing order of thickness
# boundaries = np.zeros((0, 2), dtype='int16')
# for ind_panel in range(n_ply_drops.size - 1):
# boundaries = np.vstack((
# boundaries, np.array([ind_panel, ind_panel + 1], dtype='int16')))
n_ply_drops_unique = np.unique(n_ply_drops)
n_unique = n_ply_drops_unique.size
# dictionary to retrieve indices related to the number of ply drops
indices_unique = dict()
for index, unique_index in enumerate(n_ply_drops_unique):
indices_unique[unique_index] = index
combi = []
for drops in n_ply_drops_unique:
# combi = list of the position that can take the ply drops per panel
combi.append(scipy.special.comb(n_max, drops))
n_pdl = int(min(np.product(combi), n_pdl_max))
#print('n_pdl', n_pdl)
# length of the group ply drop layout
if last_group and has_middle_ply:
n_maxx = n_max + 1
else:
n_maxx = n_max
pdl_perfect = np.zeros((n_pdl, n_ply_drops.size, n_maxx), dtype=int)
pdl_imperfect = np.zeros((n_pdl, n_ply_drops.size, n_maxx), dtype=int)
p_spacing_imperfect = np.zeros((n_pdl,), dtype=float)
ind_imperfect = 0
ind_perfect = 0
t_ini = time.time()
elapsed_time = 0
#print('n_pdl', n_pdl)
while ind_perfect < n_pdl \
and elapsed_time < parameters.time_limit_group_pdl:
#print('ind_perfect', ind_perfect)
#print('ind_imperfect', ind_imperfect)
# randomly chose a pdl
new_pdl = [[]]*n_unique
if covering_top and covering_bottom:
new_pdl[n_unique - 1] = random.sample(
range(1, n_max - 1), n_ply_drops_unique[n_unique - 1])
elif covering_top:
new_pdl[n_unique - 1] = random.sample(
range(1, n_max), n_ply_drops_unique[n_unique - 1])
elif covering_bottom:
new_pdl[n_unique - 1] = random.sample(
range(n_max - 1), n_ply_drops_unique[n_unique - 1])
else:
new_pdl[n_unique - 1] = random.sample(
range(n_max), n_ply_drops_unique[n_unique - 1])
# for guide-based blending, not generalised blending
for ind_panel in range(n_unique - 1)[::-1]:
new_pdl[ind_panel] = new_pdl[ind_panel + 1][:]
n_to_del = n_ply_drops_unique[ind_panel + 1] \
- n_ply_drops_unique[ind_panel]
to_del = random.sample(
list(range(len(new_pdl[ind_panel]))), n_to_del)
new_pdl[ind_panel] = [
elem for ind_elem, elem in enumerate(new_pdl[ind_panel]) \
if ind_elem not in to_del]
# Formatting the ply drop layout in the form as in the example:
# [[0 1 2 3]
# [-1 -1 2 3]
# [-1 -1 -1 3]]
# for a pdl with three panels
# the first panel having the four plies of index 0, 1, 2, 3
# the second panel having 2 plies of index 2 and 3
# the last panel having only the ply of index 3
#print('new_pdl', new_pdl)
new_pdl = format_ply_drops(new_pdl, n_max)
# <class 'numpy.ndarray'>
# print('new_pdl')
# print(new_pdl)
if last_group and has_middle_ply:
middle = -(middle_ply_indices[:-1] != 0).astype(int)
# print('middle', middle)
middle = middle.reshape((new_pdl.shape[0], 1))
# print('middle', middle)
new_pdl = np.hstack((new_pdl, middle))
# Formatting the ply drop layout so that a ply drop scheme is
# associated to each panel boundary
new_pdl = ply_drops_at_each_boundaries(
new_pdl, n_ply_drops_unique, indices_unique, n_ply_drops)
# <class 'numpy.ndarray'>
# print('new_pdl')
# print(new_pdl)
# Application ply drop spacing and stacking rules:
# - Ply drops should be separated by at least min_drop plies
# for the last groups of symmetric laminates
if last_group and constraints.sym:
if has_middle_ply:
pdl_after = np.flip(np.copy(new_pdl[:, :-1]), axis=1)
# print(new_pdl)
else:
pdl_after = np.flip(np.copy(new_pdl), axis=1)
p_spacing = calc_penalty_spacing(
pdl=new_pdl,
pdl_before=pdl_before,
pdl_after=pdl_after,
multipanel=multipanel,
obj_func_param=obj_func_param,
constraints=constraints,
on_blending_strip=True)
# print('p_spacing', p_spacing)
# <class 'numpy.ndarray'>
# print('new_pdl1')
# print(new_pdl)
# Formatting the ply drop layout in the form as in the example:
# [[0 1 2 3]
# [-1 -1 1 2]
# [-1 -1 -1 1]]
# for a pdl: with three panels
# the first panel having the four plies of index 0, 1, 2, 3
# the second panel having 2 plies of index 2 and 3
# the last panel having only the ply of index 3
new_pdl = format_ply_drops2(new_pdl).astype(int)
# <class 'numpy.ndarray'>
# print('new_pdl', new_pdl)
elapsed_time = time.time() - t_ini
# Store the new pdl if it is perfect (no violation of manufacturing
# constraint) or if it is among the n_pdl best unmanufacturable
# solutions found so far
if p_spacing == 0:
# To remove duplicates
is_double = False
for ind in range(ind_perfect):
if np.allclose(new_pdl, pdl_perfect[ind]):
is_double = True
break
if is_double:
continue
#print('is_double', is_double)
pdl_perfect[ind_perfect] = new_pdl
ind_perfect += 1
else:
# To only keep the imperfect pdl with the smallest penalties
if ind_imperfect >= n_pdl:
if p_spacing < max(p_spacing_imperfect):
# To remove duplicates
is_double = False
for ind in range(ind_imperfect):
if np.allclose(new_pdl, pdl_imperfect[ind]):
is_double = True
break
if is_double:
continue
#print('is_double', is_double)
indexx = np.argmin(p_spacing_imperfect)
pdl_imperfect[indexx] = new_pdl
p_spacing_imperfect[indexx] = p_spacing
else:
# To remove duplicates
is_double = False
for ind in range(ind_imperfect):
if np.allclose(new_pdl, pdl_imperfect[ind]):
is_double = True
break
if is_double:
continue
#print('is_double', is_double)
# print(new_pdl)
# print(ind_imperfect)
# print(pdl_imperfect.shape)
pdl_imperfect[ind_imperfect] = new_pdl
p_spacing_imperfect[ind_imperfect] = p_spacing
ind_imperfect += 1
# if the time limit is reached
if elapsed_time >= parameters.time_limit_group_pdl:
pdl_imperfect = pdl_imperfect[:ind_imperfect]
p_spacing_imperfect = p_spacing_imperfect[:ind_imperfect]
#print('pdl_perfect', pdl_perfect)
#print('pdl_imperfect', pdl_imperfect)
if not ind_imperfect + ind_perfect:
print('n_ply_drops', n_ply_drops)
print('n_max', n_max)
print('min_drop', constraints.min_drop)
print('pdl_before', pdl_before)
print('pdl_after', pdl_after)
raise Exception("""
No conform ply drop layout can be generated.
Too many ply drops between two adjacent panels.""")
# add the non-manufacturable ply drop layouts
for ind in range(ind_perfect, n_pdl_max):
indexx = np.argmin(p_spacing_imperfect)
pdl_perfect[ind] = pdl_imperfect[indexx]
p_spacing_imperfect[indexx] = 10e6
return pdl_perfect
# if enough manufacturable ply drop layouts have been found
return pdl_perfect
| [
"sys.path.append",
"src.BELLA.pdl_tools.format_ply_drops2",
"numpy.copy",
"src.BELLA.pdl_tools.ply_drops_at_each_boundaries",
"numpy.allclose",
"numpy.zeros",
"numpy.argmin",
"time.time",
"src.BELLA.pdl_tools.format_ply_drops",
"src.guidelines.ply_drop_spacing.calc_penalty_spacing",
"numpy.produ... | [((956, 984), 'sys.path.append', 'sys.path.append', (['"""C:\\\\BELLA"""'], {}), "('C:\\\\BELLA')\n", (971, 984), False, 'import sys\n'), ((1826, 1853), 'numpy.array', 'np.array', (['()'], {'dtype': '"""int16"""'}), "((), dtype='int16')\n", (1834, 1853), True, 'import numpy as np\n'), ((3421, 3443), 'numpy.unique', 'np.unique', (['n_ply_drops'], {}), '(n_ply_drops)\n', (3430, 3443), True, 'import numpy as np\n'), ((4133, 4187), 'numpy.zeros', 'np.zeros', (['(n_pdl, n_ply_drops.size, n_maxx)'], {'dtype': 'int'}), '((n_pdl, n_ply_drops.size, n_maxx), dtype=int)\n', (4141, 4187), True, 'import numpy as np\n'), ((4209, 4263), 'numpy.zeros', 'np.zeros', (['(n_pdl, n_ply_drops.size, n_maxx)'], {'dtype': 'int'}), '((n_pdl, n_ply_drops.size, n_maxx), dtype=int)\n', (4217, 4263), True, 'import numpy as np\n'), ((4291, 4322), 'numpy.zeros', 'np.zeros', (['(n_pdl,)'], {'dtype': 'float'}), '((n_pdl,), dtype=float)\n', (4299, 4322), True, 'import numpy as np\n'), ((4382, 4393), 'time.time', 'time.time', ([], {}), '()\n', (4391, 4393), False, 'import time\n'), ((6296, 6328), 'src.BELLA.pdl_tools.format_ply_drops', 'format_ply_drops', (['new_pdl', 'n_max'], {}), '(new_pdl, n_max)\n', (6312, 6328), False, 'from src.BELLA.pdl_tools import format_ply_drops\n'), ((6854, 6944), 'src.BELLA.pdl_tools.ply_drops_at_each_boundaries', 'ply_drops_at_each_boundaries', (['new_pdl', 'n_ply_drops_unique', 'indices_unique', 'n_ply_drops'], {}), '(new_pdl, n_ply_drops_unique, indices_unique,\n n_ply_drops)\n', (6882, 6944), False, 'from src.BELLA.pdl_tools import ply_drops_at_each_boundaries\n'), ((7518, 7707), 'src.guidelines.ply_drop_spacing.calc_penalty_spacing', 'calc_penalty_spacing', ([], {'pdl': 'new_pdl', 'pdl_before': 'pdl_before', 'pdl_after': 'pdl_after', 'multipanel': 'multipanel', 'obj_func_param': 'obj_func_param', 'constraints': 'constraints', 'on_blending_strip': '(True)'}), '(pdl=new_pdl, pdl_before=pdl_before, pdl_after=\n pdl_after, multipanel=multipanel, obj_func_param=obj_func_param,\n constraints=constraints, on_blending_strip=True)\n', (7538, 7707), False, 'from src.guidelines.ply_drop_spacing import calc_penalty_spacing\n'), ((3908, 3925), 'numpy.product', 'np.product', (['combi'], {}), '(combi)\n', (3918, 3925), True, 'import numpy as np\n'), ((6686, 6714), 'numpy.hstack', 'np.hstack', (['(new_pdl, middle)'], {}), '((new_pdl, middle))\n', (6695, 6714), True, 'import numpy as np\n'), ((8531, 8542), 'time.time', 'time.time', ([], {}), '()\n', (8540, 8542), False, 'import time\n'), ((11459, 11489), 'numpy.argmin', 'np.argmin', (['p_spacing_imperfect'], {}), '(p_spacing_imperfect)\n', (11468, 11489), True, 'import numpy as np\n'), ((8395, 8421), 'src.BELLA.pdl_tools.format_ply_drops2', 'format_ply_drops2', (['new_pdl'], {}), '(new_pdl)\n', (8412, 8421), False, 'from src.BELLA.pdl_tools import format_ply_drops2\n'), ((8896, 8934), 'numpy.allclose', 'np.allclose', (['new_pdl', 'pdl_perfect[ind]'], {}), '(new_pdl, pdl_perfect[ind])\n', (8907, 8934), True, 'import numpy as np\n'), ((7345, 7369), 'numpy.copy', 'np.copy', (['new_pdl[:, :-1]'], {}), '(new_pdl[:, :-1])\n', (7352, 7369), True, 'import numpy as np\n'), ((7469, 7485), 'numpy.copy', 'np.copy', (['new_pdl'], {}), '(new_pdl)\n', (7476, 7485), True, 'import numpy as np\n'), ((9802, 9832), 'numpy.argmin', 'np.argmin', (['p_spacing_imperfect'], {}), '(p_spacing_imperfect)\n', (9811, 9832), True, 'import numpy as np\n'), ((10115, 10155), 'numpy.allclose', 'np.allclose', (['new_pdl', 'pdl_imperfect[ind]'], {}), '(new_pdl, pdl_imperfect[ind])\n', (10126, 10155), True, 'import numpy as np\n'), ((9528, 9568), 'numpy.allclose', 'np.allclose', (['new_pdl', 'pdl_imperfect[ind]'], {}), '(new_pdl, pdl_imperfect[ind])\n', (9539, 9568), True, 'import numpy as np\n')] |
import numpy as np
import CoolProp.CoolProp as CP
#import grafici_termodinamici as gt
#import grafici_termodinamici_mixture as gt
from scipy.optimize import fsolve
from mixture_impianto_senza_eiettore_sep_function_T7fix import Funz as Funz7
from mixture_impianto_senza_eiettore_sep_function import Funz
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
#from joblib import Parallel, delayed
lib="REFPROP"
fluid1="CO2&"
fluid2=[] ; x0=[]
fluid2.append("R1234YF") ; x0.append(0.9112132132132)
# =============================================================================
# fluid2.append("R1233ZD") ; x0.append(0.98)
# #fluid2.append("R1233ZD") ; x0.append(0.985) #se T7=-20
#
#
# fluid2.append("R1234ZEE"); x0.append(0.98)
# fluid2.append("PENTANE" ); x0.append(0.9955)
# #fluid2.append("HEXANE" ) ; x0.append(0.99)
# fluid2.append("PROPANE" ) ; x0.append(0.9)
# fluid2.append("ISOBUTANE" ) ; x0.append(0.97)
# fluid2.append("CO2"); x0.append(0.99) #cop=2.25
# =============================================================================
fluids_list=[fluid1+e for e in fluid2]
fluids=fluids_list[0]
n=200
eps=0.8
T_gc=40
#10**np.linspace(0,np.log10(100),10) = np.logspace(0,np.log10(100),10)
# =============================================================================
# P_gc=95#np.linspace(70,110,n)#95
# #P_gc=np.linspace(110,70,n)#95
# cop=np.zeros(n)
# x=np.linspace(0.85,0.9,n)
# =============================================================================
T_eva=-5
T_sep=10
T_ref=273.15
eta_c=0.8
xx=[]
copcop=[]
n=30
m=30
x=np.linspace(0.8,1,n)
P_gc=np.linspace(70,110,m)
y=P_gc#np.linspace(34,59,m)
cop=np.zeros([m,n])
glide=10
def process(P_gcc):
funz=Funz(eps,P_gcc,T_gc,T_eva,T_sep,eta_c,mix,mix_l,mix_g)
T,P,H,S,m,cop=funz.imp()
T,P,H,S=funz.punti_rimanenti(T,P,H,S)
print(T[8]-T_ref)
return cop , T[8]-T[7]
def process7(P_gcc):
funz=Funz7(eps,P_gcc,T_gc,T_eva-glide,T_sep,eta_c,mix,mix_l,mix_g)
T,P,H,S,m,cop=funz.imp()
T,P,H,S=funz.punti_rimanenti(T,P,H,S)
print(T[8]-T_ref)
return cop , T[8]-T[7]
def f_glide(x,args):
P_gcc=args
mix.set_mass_fractions([x, 1-x])
cop,dT=process(P_gcc)
print(x,dT)
if dT<glide:
cop,dT=process7(P_gcc)
print(dT)
return cop#,dT-glide
mix = CP.AbstractState(lib, fluids)
mix_l = CP.AbstractState(lib, fluids)
mix_g = CP.AbstractState(lib, fluids)
# =============================================================================
# for i in range(n):
# print('i =',i)
# cop[i]=f_glide(x[i],P_gc)
#
#
# plt.figure(dpi=200)
# plt.plot(x,cop)
# plt.grid()
# =============================================================================
xx=[]
yy=[]
zz=[]
for i in range(n):
print('\n\ni=',i,'\n'+'*'*80)
for j in range(m):
print('j=',j)
try:
if x[i]==1:
mix = CP.AbstractState(lib, 'CO2&CO2')
mix_l = CP.AbstractState(lib, 'CO2&CO2')
mix_g = CP.AbstractState(lib, 'CO2&CO2')
copp=f_glide(0.99, y[j])
cop[j,i] =copp
xx.append(x[i])
yy.append(y[j])
zz.append(copp)
else:
copp=f_glide(x[i], y[j])
cop[j,i] =copp
xx.append(x[i])
yy.append(y[j])
zz.append(copp)
except Exception as e:
print(e)
z=cop
xi,yi = np.meshgrid(x,y)
metodo='linear'
zi = griddata((xx,yy),zz,(xi,yi),method=metodo)
# plot
plt.figure(dpi=200)
plt.contour(xi*100, yi, zi, levels=35, linewidths=0.5, colors='k')
cntr1 = plt.contourf(xi*100, yi, zi, levels=14, cmap="RdBu_r")
plt.colorbar(cntr1)
plt.xlabel(' x [%$kg_{CO_{2}}/kg_{tot}$]')#,fontsize=16)
plt.ylabel('$ P_{gc} $ [bar]')#,fontsize=16)
plt.title(' $ T_{gc} $=40°C, $ T_{eva} $='+str(T_eva-glide)+'°C, dT='+str(glide)+'°C, '+fluids)
plt.figure(dpi=200)
plt.contourf(xi*100,yi,zi, 60, cmap='jet')#,np.arange(0,1.01,0.01))
plt.colorbar();
#plt.plot(x,y,'k.')
plt.xlabel(' x [%$kg_{CO_{2}}/kg_{tot}$]')#,fontsize=16)
plt.ylabel('$ P_{gc} $ [bar]')#,fontsize=16)
plt.title(' $ T_{gc} $=40°C, $ T_{eva} $='+str(T_eva-glide)+'°C, dT='+str(glide)+'°C, '+fluids)
plt.figure(dpi=200)
plt.contourf(xi*100,yi,z, 30, cmap='jet')#,np.arange(0,1.01,0.01))
plt.colorbar();
#plt.plot(x,y,'k.')
plt.xlabel(' x [%$kg_{CO_{2}}/kg_{tot}$]')#,fontsize=16)
plt.ylabel('$ P_{gc} $ [bar]')#,fontsize=16)
plt.title('non interpolato')
# =============================================================================
# fig, ax = plt.subplots()
# CS = ax.contour(xi, yi, zi)
# ax.clabel(CS, inline=1, fontsize=10)
# ax.set_title('Simplest default with labels')
# =============================================================================
| [
"matplotlib.pyplot.title",
"numpy.meshgrid",
"CoolProp.CoolProp.AbstractState",
"scipy.interpolate.griddata",
"mixture_impianto_senza_eiettore_sep_function.Funz",
"numpy.zeros",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.contour",
"matplotlib.pyplot.contourf",
"... | [((1583, 1605), 'numpy.linspace', 'np.linspace', (['(0.8)', '(1)', 'n'], {}), '(0.8, 1, n)\n', (1594, 1605), True, 'import numpy as np\n'), ((1609, 1632), 'numpy.linspace', 'np.linspace', (['(70)', '(110)', 'm'], {}), '(70, 110, m)\n', (1620, 1632), True, 'import numpy as np\n'), ((1663, 1679), 'numpy.zeros', 'np.zeros', (['[m, n]'], {}), '([m, n])\n', (1671, 1679), True, 'import numpy as np\n'), ((2359, 2388), 'CoolProp.CoolProp.AbstractState', 'CP.AbstractState', (['lib', 'fluids'], {}), '(lib, fluids)\n', (2375, 2388), True, 'import CoolProp.CoolProp as CP\n'), ((2397, 2426), 'CoolProp.CoolProp.AbstractState', 'CP.AbstractState', (['lib', 'fluids'], {}), '(lib, fluids)\n', (2413, 2426), True, 'import CoolProp.CoolProp as CP\n'), ((2435, 2464), 'CoolProp.CoolProp.AbstractState', 'CP.AbstractState', (['lib', 'fluids'], {}), '(lib, fluids)\n', (2451, 2464), True, 'import CoolProp.CoolProp as CP\n'), ((3517, 3534), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (3528, 3534), True, 'import numpy as np\n'), ((3555, 3602), 'scipy.interpolate.griddata', 'griddata', (['(xx, yy)', 'zz', '(xi, yi)'], {'method': 'metodo'}), '((xx, yy), zz, (xi, yi), method=metodo)\n', (3563, 3602), False, 'from scipy.interpolate import griddata\n'), ((3606, 3625), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(200)'}), '(dpi=200)\n', (3616, 3625), True, 'import matplotlib.pyplot as plt\n'), ((3626, 3694), 'matplotlib.pyplot.contour', 'plt.contour', (['(xi * 100)', 'yi', 'zi'], {'levels': '(35)', 'linewidths': '(0.5)', 'colors': '"""k"""'}), "(xi * 100, yi, zi, levels=35, linewidths=0.5, colors='k')\n", (3637, 3694), True, 'import matplotlib.pyplot as plt\n'), ((3701, 3757), 'matplotlib.pyplot.contourf', 'plt.contourf', (['(xi * 100)', 'yi', 'zi'], {'levels': '(14)', 'cmap': '"""RdBu_r"""'}), "(xi * 100, yi, zi, levels=14, cmap='RdBu_r')\n", (3713, 3757), True, 'import matplotlib.pyplot as plt\n'), ((3756, 3775), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['cntr1'], {}), '(cntr1)\n', (3768, 3775), True, 'import matplotlib.pyplot as plt\n'), ((3776, 3818), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['""" x [%$kg_{CO_{2}}/kg_{tot}$]"""'], {}), "(' x [%$kg_{CO_{2}}/kg_{tot}$]')\n", (3786, 3818), True, 'import matplotlib.pyplot as plt\n'), ((3833, 3863), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$ P_{gc} $ [bar]"""'], {}), "('$ P_{gc} $ [bar]')\n", (3843, 3863), True, 'import matplotlib.pyplot as plt\n'), ((3982, 4001), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(200)'}), '(dpi=200)\n', (3992, 4001), True, 'import matplotlib.pyplot as plt\n'), ((4002, 4048), 'matplotlib.pyplot.contourf', 'plt.contourf', (['(xi * 100)', 'yi', 'zi', '(60)'], {'cmap': '"""jet"""'}), "(xi * 100, yi, zi, 60, cmap='jet')\n", (4014, 4048), True, 'import matplotlib.pyplot as plt\n'), ((4070, 4084), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (4082, 4084), True, 'import matplotlib.pyplot as plt\n'), ((4106, 4148), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['""" x [%$kg_{CO_{2}}/kg_{tot}$]"""'], {}), "(' x [%$kg_{CO_{2}}/kg_{tot}$]')\n", (4116, 4148), True, 'import matplotlib.pyplot as plt\n'), ((4163, 4193), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$ P_{gc} $ [bar]"""'], {}), "('$ P_{gc} $ [bar]')\n", (4173, 4193), True, 'import matplotlib.pyplot as plt\n'), ((4310, 4329), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(200)'}), '(dpi=200)\n', (4320, 4329), True, 'import matplotlib.pyplot as plt\n'), ((4330, 4375), 'matplotlib.pyplot.contourf', 'plt.contourf', (['(xi * 100)', 'yi', 'z', '(30)'], {'cmap': '"""jet"""'}), "(xi * 100, yi, z, 30, cmap='jet')\n", (4342, 4375), True, 'import matplotlib.pyplot as plt\n'), ((4397, 4411), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (4409, 4411), True, 'import matplotlib.pyplot as plt\n'), ((4433, 4475), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['""" x [%$kg_{CO_{2}}/kg_{tot}$]"""'], {}), "(' x [%$kg_{CO_{2}}/kg_{tot}$]')\n", (4443, 4475), True, 'import matplotlib.pyplot as plt\n'), ((4490, 4520), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$ P_{gc} $ [bar]"""'], {}), "('$ P_{gc} $ [bar]')\n", (4500, 4520), True, 'import matplotlib.pyplot as plt\n'), ((4536, 4564), 'matplotlib.pyplot.title', 'plt.title', (['"""non interpolato"""'], {}), "('non interpolato')\n", (4545, 4564), True, 'import matplotlib.pyplot as plt\n'), ((1720, 1782), 'mixture_impianto_senza_eiettore_sep_function.Funz', 'Funz', (['eps', 'P_gcc', 'T_gc', 'T_eva', 'T_sep', 'eta_c', 'mix', 'mix_l', 'mix_g'], {}), '(eps, P_gcc, T_gc, T_eva, T_sep, eta_c, mix, mix_l, mix_g)\n', (1724, 1782), False, 'from mixture_impianto_senza_eiettore_sep_function import Funz\n'), ((1936, 2007), 'mixture_impianto_senza_eiettore_sep_function_T7fix.Funz', 'Funz7', (['eps', 'P_gcc', 'T_gc', '(T_eva - glide)', 'T_sep', 'eta_c', 'mix', 'mix_l', 'mix_g'], {}), '(eps, P_gcc, T_gc, T_eva - glide, T_sep, eta_c, mix, mix_l, mix_g)\n', (1941, 2007), True, 'from mixture_impianto_senza_eiettore_sep_function_T7fix import Funz as Funz7\n'), ((2950, 2982), 'CoolProp.CoolProp.AbstractState', 'CP.AbstractState', (['lib', '"""CO2&CO2"""'], {}), "(lib, 'CO2&CO2')\n", (2966, 2982), True, 'import CoolProp.CoolProp as CP\n'), ((3007, 3039), 'CoolProp.CoolProp.AbstractState', 'CP.AbstractState', (['lib', '"""CO2&CO2"""'], {}), "(lib, 'CO2&CO2')\n", (3023, 3039), True, 'import CoolProp.CoolProp as CP\n'), ((3064, 3096), 'CoolProp.CoolProp.AbstractState', 'CP.AbstractState', (['lib', '"""CO2&CO2"""'], {}), "(lib, 'CO2&CO2')\n", (3080, 3096), True, 'import CoolProp.CoolProp as CP\n')] |
import os
import errno
import logging
from sklearn.metrics import accuracy_score
import numpy as np
from eval.utils.metrics import macroavg_prec, macroavg_f1, macroavg_rec, microavg_prec, microavg_rec, microavg_f1
def unit(x):
return x
def noop(*args, **kwargs):
pass
def one(*args, **kwargs):
return 1.
def multiple_scores(true_labels, predicted_labels):
"""
Chains several functions as specified in the configuration. When called
returns the return values of all of its callables as a tuple
Example usage:
# some sample functions
def t1(shared_param, conf):
print 'called t1(%s, %s)' % (str(shared_param), str(shared_param))
return 1
def t2(shared_param, conf):
print 'called t1(%s, %s)' % (str(shared_param), str(shared_param))
return 2
config = {'a': 1, 'b': 2}
ccall = chain_callable(config)
print ccall('X_Y')
print ccall('A_B')
"""
to_call = [macroavg_prec, macroavg_rec, macroavg_f1,
microavg_prec, microavg_rec, microavg_f1,
accuracy_score]
result = {}
for func in to_call:
func_name = func.__name__
result[func_name] = func(true_labels, predicted_labels)
return result
def calculate_log_odds(X, y, column_indices=None):
"""
:param X: term-document matrix, shape (m,n)
:type X: scipy.sparse
:param y: document labels, shape (m,)
:type y: np.array
:param column_indices: compute score only for these columns, other will be set to 0
:return: log odds scores of all features
:rtype: array-like, shape (n,)
"""
alpha = .000001
alpha_denom = alpha * len(set(y))
log_odds = np.empty(X.shape[1])
class0_indices = y == sorted(set(y))[0]
if column_indices is None:
column_indices = np.arange(X.shape[1])
for idx in column_indices:
all_counts = X[:, idx] # document counts of this feature
total_counts = np.count_nonzero(all_counts.data) # how many docs the feature occurs in
count_in_class0 = np.count_nonzero(all_counts[class0_indices].data) # how many of them are class 0
# p = float(count_in_class0) / total_counts
# smoothing to avoid taking log(0) below
p = (float(count_in_class0) + alpha) / (total_counts + alpha_denom)
log_odds_this_feature = np.log(p) - np.log(1 - p)
log_odds[idx] = log_odds_this_feature
return log_odds
def update_dict_according_to_mask(v, mask):
"""
Given a dictionary of {something:index} and a boolean mask, removes items as specified by the mask
and re-assigns consecutive indices to the remaining items. The values of `v` are assumed to be
consecutive integers starting at 0
:param mask: array-like, must be indexable by the values of `v`
:rtype: dict
"""
if len(v) != len(mask):
logging.error('Mask and dict do not match in size: %d vs %d', mask.shape[0], len(v))
return
# see which features are left
v = {feature: index for feature, index in v.items() if mask[index]}
# assign new indices for each remaining feature in order, map: old_index -> new_index
new_indices = {old_index: new_index for new_index, old_index in enumerate(sorted(v.values()))}
# update indices in vocabulary
return {feature: new_indices[index] for feature, index in v.items()}
| [
"numpy.count_nonzero",
"numpy.empty",
"numpy.arange",
"numpy.log"
] | [((1699, 1719), 'numpy.empty', 'np.empty', (['X.shape[1]'], {}), '(X.shape[1])\n', (1707, 1719), True, 'import numpy as np\n'), ((1820, 1841), 'numpy.arange', 'np.arange', (['X.shape[1]'], {}), '(X.shape[1])\n', (1829, 1841), True, 'import numpy as np\n'), ((1962, 1995), 'numpy.count_nonzero', 'np.count_nonzero', (['all_counts.data'], {}), '(all_counts.data)\n', (1978, 1995), True, 'import numpy as np\n'), ((2061, 2110), 'numpy.count_nonzero', 'np.count_nonzero', (['all_counts[class0_indices].data'], {}), '(all_counts[class0_indices].data)\n', (2077, 2110), True, 'import numpy as np\n'), ((2353, 2362), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (2359, 2362), True, 'import numpy as np\n'), ((2365, 2378), 'numpy.log', 'np.log', (['(1 - p)'], {}), '(1 - p)\n', (2371, 2378), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pyrealsense2 as rs
import json
import cv2
import os
import sys
from queue import Queue
from collections import deque
from copy import deepcopy
import threading
import struct
from dependencies.display_util.string_display_util import *
from dependencies.file_io_util.config_file import ConfigFile
from tqdm import tqdm
from PIL import Image
import labview_recorder.distribution as db
matplotlib.use('Qt5agg')
np.set_printoptions(threshold=np.inf)
is_stopping = False
cnf_file = "C:\\Users\\aaron.jencks\\Documents\\GitHub\\emerson_seed_object_detection\\realsense_cam_settings.json"
depth_dq = deque()
color_dq = deque()
if __name__ == "__main__":
in_dir = input("Input file path: ")
out_dir = input("Ourput file path: ")
codec = cv2.VideoWriter_fourcc(*'LAGS')
for file in os.listdir(in_dir):
file = os.path.join(in_dir, file)
prefix = os.path.splitext(file)[0].split('\\')[-1]
color_name = os.path.join(out_dir, '{}_color.avi'.format(prefix))
depth_name = os.path.join(out_dir, '{}_depth.avi'.format(prefix))
print_notification("Converting {}".format(file))
ctx = rs.context()
pipeline = rs.pipeline(ctx)
config = rs.config()
rs.config.enable_device_from_file(config, file, False)
config.enable_all_streams()
cap = pipeline.start(config)
scale = cap.get_device().first_depth_sensor().get_depth_scale()
# intr = cap.get_stream(rs.stream.depth).as_video_stream_profile().get_instrinsics()
#
# # cap = cv2.VideoCapture(0)
#
# # TODO
# print('Generating ini file')
# print('Saving to {}'.format(os.path.join(out_dir, '{}.ini'.format(prefix))))
# with ConfigFile(os.path.join(out_dir, '{}.ini'.format(prefix))) as ini:
# ini['Videos']['depth'] = depth_name
# ini['Videos']['color'] = color_name
# ini['intrinsics']['ppx'] = intr.ppx
# ini['intrinsics']['ppy'] = intr.ppy
# ini['intrinsics']['fx'] = intr.fx
# ini['intrinsics']['fy'] = intr.fy
#
# print("Depth Scale is {}".format(scale))
# print('Streaming intrinsics:')
# print('ppx: {}\nppy: {}\nfx: {}\nfy: {}'.format(intr.ppx, intr.ppy, intr.fx, intr.fy))
fig, ax = plt.subplots()
ax.axis('off')
plot = fig.add_axes([0.1, 0.5, 0.7, 0.4])
dist = fig.add_axes([0.1, 0.1, 0.7, 0.4])
print("Saving to {}".format(os.path.join(out_dir,
'{}_depth.mp4'.format(prefix))))
iteration = 0
try:
first = True
while not is_stopping:
iteration += 1
print('\rIterations {}'.format(iteration), end='')
frames = pipeline.wait_for_frames()
depth_frame = np.asanyarray(frames.get_depth_frame().get_data(), dtype=np.uint16)
color_frame = np.asanyarray(frames.get_color_frame().get_data(), dtype=np.uint8)
# depth_array = np.multiply(np.asanyarray(depth_frame.get_data()), 1) # scale)
# depth_frame = np.dstack((depth_frame, depth_frame, depth_frame))
# m = depth_frame.max()
# depth_frame = np.float32(np.multiply(depth_frame, 1 / m))
# depth_frame = np.dstack((depth_frame, depth_frame, depth_frame))
# print(depth_frame)
# ret, frame = cap.read()
depth_frame = db.compute_depth_bytes(depth_frame)
# depth_frame_t = np.zeros(shape=(depth_frame.shape[0], depth_frame.shape[1], 3), dtype=np.uint8)
#
# for i in range(depth_frame.shape[0]):
# for j in range(depth_frame.shape[1]):
# current = depth_frame[i, j]
# broken = struct.pack('H', current)
# depth_frame_t[i, j, 0] = broken[0]
# depth_frame_t[i, j, 1] = broken[1]
#
# depth_frame = depth_frame_t
# print("cv")
# print(frame.shape)
# print("rs")
# print(color_frame.shape)
# plot.clear()
# plot.imshow(depth_frame)
# plot.axis('off')
# norm = db.normal_distribution(frames)
# dist.clear()
# dist.imshow(color_frame)
# dist.axis('off')
# dist.hist(np.multiply(norm, scale), range=(-1, 1), histtype='step')
# dist.hist(norm[:, 1]) # , range=(-5, 5)) # [:, 1])
# plt.draw()
# plt.pause(0.001)
depth_dq.append(deepcopy(depth_frame))
color_dq.append(deepcopy(color_frame))
except RuntimeError as e:
print_info(str(e))
print_notification("Finished conversion")
plt.close(fig)
print_notification("Saving video files")
color_writer = cv2.VideoWriter(color_name, cv2.VideoWriter_fourcc(*'XVID'), 30, (1280, 720))
for f in tqdm(range(len(color_dq))):
color_writer.write(color_dq.popleft())
color_writer.release()
depth_writer = cv2.VideoWriter(depth_name, codec, 30, (848, 480))
for f in tqdm(range(len(depth_dq))):
depth_writer.write(depth_dq.popleft())
depth_writer.release()
finally:
plt.close(fig)
pipeline.stop()
| [
"copy.deepcopy",
"numpy.set_printoptions",
"pyrealsense2.config.enable_device_from_file",
"cv2.VideoWriter_fourcc",
"pyrealsense2.pipeline",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots",
"pyrealsense2.config",
"pyrealsense2.context",
"labview_recorder.distribution.compute_depth_bytes",
... | [((463, 487), 'matplotlib.use', 'matplotlib.use', (['"""Qt5agg"""'], {}), "('Qt5agg')\n", (477, 487), False, 'import matplotlib\n'), ((488, 525), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (507, 525), True, 'import numpy as np\n'), ((674, 681), 'collections.deque', 'deque', ([], {}), '()\n', (679, 681), False, 'from collections import deque\n'), ((693, 700), 'collections.deque', 'deque', ([], {}), '()\n', (698, 700), False, 'from collections import deque\n'), ((825, 856), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'LAGS'"], {}), "(*'LAGS')\n", (847, 856), False, 'import cv2\n'), ((874, 892), 'os.listdir', 'os.listdir', (['in_dir'], {}), '(in_dir)\n', (884, 892), False, 'import os\n'), ((909, 935), 'os.path.join', 'os.path.join', (['in_dir', 'file'], {}), '(in_dir, file)\n', (921, 935), False, 'import os\n'), ((1216, 1228), 'pyrealsense2.context', 'rs.context', ([], {}), '()\n', (1226, 1228), True, 'import pyrealsense2 as rs\n'), ((1248, 1264), 'pyrealsense2.pipeline', 'rs.pipeline', (['ctx'], {}), '(ctx)\n', (1259, 1264), True, 'import pyrealsense2 as rs\n'), ((1282, 1293), 'pyrealsense2.config', 'rs.config', ([], {}), '()\n', (1291, 1293), True, 'import pyrealsense2 as rs\n'), ((1302, 1356), 'pyrealsense2.config.enable_device_from_file', 'rs.config.enable_device_from_file', (['config', 'file', '(False)'], {}), '(config, file, False)\n', (1335, 1356), True, 'import pyrealsense2 as rs\n'), ((2393, 2407), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2405, 2407), True, 'import matplotlib.pyplot as plt\n'), ((5641, 5655), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (5650, 5655), True, 'import matplotlib.pyplot as plt\n'), ((3612, 3647), 'labview_recorder.distribution.compute_depth_bytes', 'db.compute_depth_bytes', (['depth_frame'], {}), '(depth_frame)\n', (3634, 3647), True, 'import labview_recorder.distribution as db\n'), ((5080, 5094), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (5089, 5094), True, 'import matplotlib.pyplot as plt\n'), ((5421, 5471), 'cv2.VideoWriter', 'cv2.VideoWriter', (['depth_name', 'codec', '(30)', '(848, 480)'], {}), '(depth_name, codec, 30, (848, 480))\n', (5436, 5471), False, 'import cv2\n'), ((4870, 4891), 'copy.deepcopy', 'deepcopy', (['depth_frame'], {}), '(depth_frame)\n', (4878, 4891), False, 'from copy import deepcopy\n'), ((4925, 4946), 'copy.deepcopy', 'deepcopy', (['color_frame'], {}), '(color_frame)\n', (4933, 4946), False, 'from copy import deepcopy\n'), ((5204, 5235), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (5226, 5235), False, 'import cv2\n'), ((953, 975), 'os.path.splitext', 'os.path.splitext', (['file'], {}), '(file)\n', (969, 975), False, 'import os\n')] |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import graphgallery as gg
from graphgallery import functional as gf
from graphgallery.utils import tqdm
from graphgallery.attack.untargeted import PyTorch
from graphgallery.attack.untargeted.untargeted_attacker import UntargetedAttacker
@PyTorch.register()
class PGD(UntargetedAttacker):
"""PGD cannot ensure that there is not singleton after attack.
https://github.com/KaidiXu/GCN_ADV_Train
"""
def process(self,
surrogate,
train_nodes,
unlabeled_nodes=None,
reset=True):
assert isinstance(surrogate, gg.gallery.nodeclas.GCN), surrogate
# poisoning attack in DeepRobust
if unlabeled_nodes is None:
victim_nodes = gf.asarray(train_nodes)
victim_labels = self.graph.node_label[victim_nodes]
else: # Evasion attack in original paper
self_training_labels = self.estimate_self_training_labels(surrogate, unlabeled_nodes)
victim_nodes = np.hstack([train_nodes, unlabeled_nodes])
victim_labels = np.hstack([self.graph.node_label[train_nodes], self_training_labels])
adj_tensor = gf.astensor(self.graph.adj_matrix.A, device=self.device)
self.victim_nodes = gf.astensor(victim_nodes, device=self.device)
self.victim_labels = gf.astensor(victim_labels, device=self.device)
self.adj_tensor = adj_tensor
self.x_tensor = gf.astensor(self.graph.node_attr, device=self.device)
self.complementary = (torch.ones_like(adj_tensor) - torch.eye(self.num_nodes).to(self.device) - 2. * adj_tensor)
self.loss_fn = nn.CrossEntropyLoss()
self.adj_changes = nn.Parameter(torch.zeros_like(self.adj_tensor))
self.surrogate = surrogate.model.to(self.device)
self.surrogate.eval()
# # used for `CW_loss=True`
self.label_matrix = torch.eye(self.num_classes)[self.victim_labels].to(self.device)
self.range_idx = torch.arange(victim_nodes.size).to(self.device)
self.indices_real = torch.stack([self.range_idx, self.victim_labels])
if reset:
self.reset()
return self
def reset(self):
super().reset()
self.adj_changes.data.zero_()
return self
def estimate_self_training_labels(self, surrogate, victim_nodes):
self_training_labels = surrogate.predict(victim_nodes).argmax(1)
return self_training_labels.astype(self.intx, copy=False)
def attack(self,
num_budgets=0.05,
sample_epochs=20,
C=None,
CW_loss=False,
epochs=200,
structure_attack=True,
feature_attack=False,
disable=False):
super().attack(num_budgets, structure_attack, feature_attack)
self.CW_loss = CW_loss
if not C:
if CW_loss:
C = 0.1
else:
C = 200
for epoch in tqdm(range(epochs),
desc='PGD Training',
disable=disable):
gradients = self.compute_gradients(self.victim_nodes)
lr = C / np.sqrt(epoch + 1)
self.adj_changes.data.add_(lr * gradients)
self.projection()
best_s = self.random_sample(sample_epochs, disable=disable)
self.adj_flips = np.transpose(np.where(best_s > 0.))
return self
def compute_gradients(self, victim_nodes):
loss = self.compute_loss(victim_nodes)
gradients = torch.autograd.grad(loss, self.adj_changes)
return gradients[0]
def compute_loss(self, victim_nodes):
adj = self.get_perturbed_adj()
adj_norm = gf.normalize_adj_tensor(adj)
logit = self.surrogate(self.x_tensor, adj_norm)[victim_nodes]
if self.CW_loss:
logit = F.log_softmax(logit, dim=1)
best_wrong_class = (logit - 1000 * self.label_matrix).argmax(1)
indices_attack = torch.stack([self.range_idx, best_wrong_class])
margin = logit[self.indices_real] - logit[indices_attack] + 0.2
loss = -torch.clamp(margin, min=0.)
return loss.mean()
else:
loss = self.loss_fn(logit, self.victim_labels)
return loss
def get_perturbed_adj(self):
adj_triu = torch.triu(self.adj_changes, diagonal=1)
adj_changes = adj_triu + adj_triu.t()
adj = self.complementary * adj_changes + self.adj_tensor
return adj
def projection(self):
clipped_matrix = self.clip(self.adj_changes)
num_modified = clipped_matrix.sum()
if num_modified > self.num_budgets:
left = (self.adj_changes - 1.).min()
right = self.adj_changes.max()
miu = self.bisection(left, right, epsilon=1e-5)
clipped_matrix = self.clip(self.adj_changes - miu)
else:
pass
self.adj_changes.data.copy_(clipped_matrix)
def bisection(self, a, b, epsilon):
def func(x):
clipped_matrix = self.clip(self.adj_changes - x)
return clipped_matrix.sum() - self.num_budgets
miu = a
while (b - a) > epsilon:
miu = (a + b) / 2
# Check if middle point is root
if func(miu) == 0:
break
# Decide the side to repeat the steps
if func(miu) * func(a) < 0:
b = miu
else:
a = miu
return miu
def clip(self, matrix):
clipped_matrix = torch.clamp(matrix, 0., 1.)
return clipped_matrix
def random_sample(self, sample_epochs=20, disable=False):
best_loss = -10000
best_s = None
s = torch.triu(self.adj_changes, diagonal=1)
_one = torch.tensor(1.).to(self.device)
_zero = torch.tensor(0.).to(self.device)
for it in tqdm(range(sample_epochs),
desc='Random Sampling',
disable=disable):
random_matrix = torch.zeros_like(s).uniform_(0, 1)
sampled = torch.where(s > random_matrix, _one, _zero)
if sampled.sum() > self.num_budgets:
continue
self.adj_changes.data.copy_(sampled)
loss = self.compute_loss(self.victim_nodes)
if best_loss < loss:
best_loss = loss
best_s = sampled
assert best_s is not None, "Something wrong"
return best_s.detach().cpu().numpy()
| [
"torch.eye",
"torch.autograd.grad",
"torch.arange",
"graphgallery.functional.astensor",
"graphgallery.functional.normalize_adj_tensor",
"torch.triu",
"torch.nn.functional.log_softmax",
"torch.zeros_like",
"torch.where",
"numpy.hstack",
"torch.clamp",
"torch.ones_like",
"torch.stack",
"torc... | [((327, 345), 'graphgallery.attack.untargeted.PyTorch.register', 'PyTorch.register', ([], {}), '()\n', (343, 345), False, 'from graphgallery.attack.untargeted import PyTorch\n'), ((1250, 1306), 'graphgallery.functional.astensor', 'gf.astensor', (['self.graph.adj_matrix.A'], {'device': 'self.device'}), '(self.graph.adj_matrix.A, device=self.device)\n', (1261, 1306), True, 'from graphgallery import functional as gf\n'), ((1335, 1380), 'graphgallery.functional.astensor', 'gf.astensor', (['victim_nodes'], {'device': 'self.device'}), '(victim_nodes, device=self.device)\n', (1346, 1380), True, 'from graphgallery import functional as gf\n'), ((1410, 1456), 'graphgallery.functional.astensor', 'gf.astensor', (['victim_labels'], {'device': 'self.device'}), '(victim_labels, device=self.device)\n', (1421, 1456), True, 'from graphgallery import functional as gf\n'), ((1518, 1571), 'graphgallery.functional.astensor', 'gf.astensor', (['self.graph.node_attr'], {'device': 'self.device'}), '(self.graph.node_attr, device=self.device)\n', (1529, 1571), True, 'from graphgallery import functional as gf\n'), ((1716, 1737), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1735, 1737), True, 'import torch.nn as nn\n'), ((2130, 2179), 'torch.stack', 'torch.stack', (['[self.range_idx, self.victim_labels]'], {}), '([self.range_idx, self.victim_labels])\n', (2141, 2179), False, 'import torch\n'), ((3632, 3675), 'torch.autograd.grad', 'torch.autograd.grad', (['loss', 'self.adj_changes'], {}), '(loss, self.adj_changes)\n', (3651, 3675), False, 'import torch\n'), ((3805, 3833), 'graphgallery.functional.normalize_adj_tensor', 'gf.normalize_adj_tensor', (['adj'], {}), '(adj)\n', (3828, 3833), True, 'from graphgallery import functional as gf\n'), ((4437, 4477), 'torch.triu', 'torch.triu', (['self.adj_changes'], {'diagonal': '(1)'}), '(self.adj_changes, diagonal=1)\n', (4447, 4477), False, 'import torch\n'), ((5664, 5693), 'torch.clamp', 'torch.clamp', (['matrix', '(0.0)', '(1.0)'], {}), '(matrix, 0.0, 1.0)\n', (5675, 5693), False, 'import torch\n'), ((5846, 5886), 'torch.triu', 'torch.triu', (['self.adj_changes'], {'diagonal': '(1)'}), '(self.adj_changes, diagonal=1)\n', (5856, 5886), False, 'import torch\n'), ((825, 848), 'graphgallery.functional.asarray', 'gf.asarray', (['train_nodes'], {}), '(train_nodes)\n', (835, 848), True, 'from graphgallery import functional as gf\n'), ((1088, 1129), 'numpy.hstack', 'np.hstack', (['[train_nodes, unlabeled_nodes]'], {}), '([train_nodes, unlabeled_nodes])\n', (1097, 1129), True, 'import numpy as np\n'), ((1158, 1227), 'numpy.hstack', 'np.hstack', (['[self.graph.node_label[train_nodes], self_training_labels]'], {}), '([self.graph.node_label[train_nodes], self_training_labels])\n', (1167, 1227), True, 'import numpy as np\n'), ((1778, 1811), 'torch.zeros_like', 'torch.zeros_like', (['self.adj_tensor'], {}), '(self.adj_tensor)\n', (1794, 1811), False, 'import torch\n'), ((3473, 3495), 'numpy.where', 'np.where', (['(best_s > 0.0)'], {}), '(best_s > 0.0)\n', (3481, 3495), True, 'import numpy as np\n'), ((3950, 3977), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['logit'], {'dim': '(1)'}), '(logit, dim=1)\n', (3963, 3977), True, 'import torch.nn.functional as F\n'), ((4083, 4130), 'torch.stack', 'torch.stack', (['[self.range_idx, best_wrong_class]'], {}), '([self.range_idx, best_wrong_class])\n', (4094, 4130), False, 'import torch\n'), ((6202, 6245), 'torch.where', 'torch.where', (['(s > random_matrix)', '_one', '_zero'], {}), '(s > random_matrix, _one, _zero)\n', (6213, 6245), False, 'import torch\n'), ((1602, 1629), 'torch.ones_like', 'torch.ones_like', (['adj_tensor'], {}), '(adj_tensor)\n', (1617, 1629), False, 'import torch\n'), ((2054, 2085), 'torch.arange', 'torch.arange', (['victim_nodes.size'], {}), '(victim_nodes.size)\n', (2066, 2085), False, 'import torch\n'), ((3262, 3280), 'numpy.sqrt', 'np.sqrt', (['(epoch + 1)'], {}), '(epoch + 1)\n', (3269, 3280), True, 'import numpy as np\n'), ((4227, 4255), 'torch.clamp', 'torch.clamp', (['margin'], {'min': '(0.0)'}), '(margin, min=0.0)\n', (4238, 4255), False, 'import torch\n'), ((5902, 5919), 'torch.tensor', 'torch.tensor', (['(1.0)'], {}), '(1.0)\n', (5914, 5919), False, 'import torch\n'), ((5951, 5968), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (5963, 5968), False, 'import torch\n'), ((1965, 1992), 'torch.eye', 'torch.eye', (['self.num_classes'], {}), '(self.num_classes)\n', (1974, 1992), False, 'import torch\n'), ((6145, 6164), 'torch.zeros_like', 'torch.zeros_like', (['s'], {}), '(s)\n', (6161, 6164), False, 'import torch\n'), ((1632, 1657), 'torch.eye', 'torch.eye', (['self.num_nodes'], {}), '(self.num_nodes)\n', (1641, 1657), False, 'import torch\n')] |
# flowProfile.py
"""
Notes
"""
# import modules
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import NonUniformImage
from math import ceil
def generate_flowProfile(testSetup, flowType='pdf', z_resolution=10, y_mod=1.1, z_mod=5,
Umax_pdf=0, slip_near=0, slip_far=0, E=0, ep_mobility=0):
"""
Notes: This program calculates the flow profile by using array indices as the channel resolution (except for z)
Params:
z_resolution: a resolution multiplier (e.g. z_resolution = 10 --> the number of z-coordinate points are 10X)
y_mod: decay function for y-domain boundaries
z_mod: decay function for z-domain boundaries
"""
# check flowTypes
valid_flowTypes = ['pdf', 'slip', 'ep']
for f in flowType:
if f not in valid_flowTypes:
raise ValueError("{} not a valid flowType: {}".format(f, valid_flowTypes))
# coordinate space bounds
zmax = testSetup.chip.channel.height
ymax = testSetup.chip.channel.width
# coordinate space
z = np.linspace(0, zmax, int(zmax * z_resolution * 1e6 + 1))
y = np.linspace(0, ymax, int(ymax * 1e6 + 1))
# decay function to help handle boundary conditions
z_decay = decay_fucntion(z, decay_rate=z_mod, invert=False)
y_decay = decay_fucntion(y, decay_rate=y_mod, invert=False)
# initialize flow types
ux_z_pdf = np.zeros_like(z)
ux_z_slip = np.zeros_like(z)
ux_y_pdf = np.zeros_like(y)
ux_y_ep = np.zeros_like(y)
ux_mag_pdf = 0
ux_mag_pdf_dir = 1
ux_mag_slip = 0
ux_mag_slip_dir = 1
ux_mag_ep = 0
ux_mag_ep_dir = 1
# type 1: pressure driven flow in rectangular channel
if 'pdf' in flowType and Umax_pdf != 0:
ux_z_pdf = 4 * Umax_pdf * (z / zmax) * (1 - z / zmax) # Ux ( z )
ux_y_pdf = 4 * Umax_pdf * (y / ymax) * (1 - y / ymax) / y_mod # Ux ( z )
ux_mag_pdf = np.max(np.abs(ux_z_pdf))
ux_mag_pdf_dir = np.mean(ux_z_pdf)/np.abs(np.mean(ux_z_pdf))
if 'slip' in flowType and (slip_near != 0 or slip_far != 0):
ux_z_slip = (slip_far - slip_near) * (z / zmax) + slip_near # Ux ( z )
ux_mag_slip = np.max(np.abs(ux_z_slip))
ux_mag_slip_dir = np.mean(ux_z_slip) / np.abs(np.mean(ux_z_slip))
if 'ep' in flowType and E != 0 and ep_mobility != 0:
ux_y_ep = ep_mobility * E * np.ones_like(y)
ux_mag_ep = np.max(np.abs(ux_y_ep))
ux_mag_ep_dir = np.mean(ux_y_pdf) / np.abs(np.mean(ux_y_ep))
# add z and y arrays
ux_z = (ux_z_pdf + ux_z_slip)*z_decay
ux_y = (ux_y_pdf + ux_y_ep)*y_decay
# stack the arrays
uxz = []
for i in range(int(ymax*1e6)+1):
uxz.append(ux_z)
uxz = np.array(uxz)
# stack uxy
uxy = []
for i in range(int(zmax * z_resolution * 1e6 + 1)):
uxy.append(ux_y)
uxy = np.array(uxy)
# 3d flow profile
uxx = uxy + np.transpose(uxz)
mag_scaling = ux_mag_pdf*ux_mag_pdf_dir + ux_mag_slip*ux_mag_slip_dir + ux_mag_ep*ux_mag_ep_dir
if mag_scaling == 0:
mag_scaling = 0.001
u_xyz = np.abs(uxx)/np.max(np.abs(uxx)) * mag_scaling
return u_xyz
def decay_fucntion(example_array, decay_rate, invert=False):
x = np.linspace(0, len(example_array)/2, num=len(example_array)//2)
if invert:
half_decay = np.exp(-x*decay_rate)
else:
half_decay = 1 - np.exp(-x*decay_rate)
decay = np.concatenate((half_decay, half_decay[::-1]), axis=0)
if len(decay) != len(example_array):
decay = np.insert(decay, len(decay)//2, 1)
return decay
def plot_flowProfile_2D(u_xyz, show_plot=True,
save_plot=False, savePath=None, saveName=None, saveType='.jpg',
cmap='viridis', interp='bilinear'):
x = np.arange(0, np.shape(u_xyz)[1], 1)
y = np.arange(0, np.shape(u_xyz)[0], 1)
fig, ax = plt.subplots(figsize=(10, 4), tight_layout=True)
im = NonUniformImage(ax, interpolation=interp, extent=(x[0], x[-1], y[0], y[-1]), cmap=cmap)
im.set_data(x, y, u_xyz)
cs = ax.add_image(im)
cbar = fig.colorbar(cs)
cbar.set_label(r'$\frac {U_{max, input}}{U_{max}}$')
plt.title('Normalized microchannel flow profile')
plt.xlabel('x (um)')
plt.ylabel('z (um)')
ax.set_xlim(x[0], x[-1])
ax.set_ylim(y[0], y[-1])
if save_plot:
plt.savefigure(fname=savePath+'/'+saveName+saveType)
if show_plot:
plt.show()
def plot_flowProfile_3D(u_xyz, plotType='surface', show_plot=True,
save_plot=False, savePath=None, saveName=None, saveType='.jpg',
cmap='viridis'):
x = np.arange(0, np.shape(u_xyz)[1], 1)
y = np.arange(0, np.shape(u_xyz)[0], 1)
X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(7, 5), tight_layout=True)
if plotType == 'surface':
cs = ax.plot_surface(X, Y, u_xyz, rstride=1, cstride=1, cmap=cmap, edgecolor=None)
if plotType == 'wireframe':
cs = ax.plot_wireframe(X, Y, u_xyz, cmap=cmap)
cbar = fig.colorbar(cs, shrink=0.5, orientation='vertical')
cbar.set_label(r'$\frac {U_{max, input}}{U_{max}}$', fontsize=14)
cbar.set_ticks([-np.min(u_xyz), np.max(u_xyz)])
ax.set_xlabel("x (um)", fontsize=12)
ax.set_ylabel("z (um)", fontsize=12)
ax.set_title('Normalized microchannel flow profile', fontsize=14)
ax.view_init(elev=40, azim=300)
plt.tight_layout()
if save_plot:
plt.savefigure(fname=savePath+'/'+saveName+saveType)
if show_plot:
plt.show()
| [
"matplotlib.pyplot.title",
"numpy.abs",
"numpy.shape",
"numpy.mean",
"numpy.exp",
"matplotlib.pyplot.tight_layout",
"numpy.zeros_like",
"numpy.meshgrid",
"numpy.transpose",
"numpy.max",
"matplotlib.pyplot.savefigure",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"numpy.ones_like... | [((1424, 1440), 'numpy.zeros_like', 'np.zeros_like', (['z'], {}), '(z)\n', (1437, 1440), True, 'import numpy as np\n'), ((1457, 1473), 'numpy.zeros_like', 'np.zeros_like', (['z'], {}), '(z)\n', (1470, 1473), True, 'import numpy as np\n'), ((1489, 1505), 'numpy.zeros_like', 'np.zeros_like', (['y'], {}), '(y)\n', (1502, 1505), True, 'import numpy as np\n'), ((1520, 1536), 'numpy.zeros_like', 'np.zeros_like', (['y'], {}), '(y)\n', (1533, 1536), True, 'import numpy as np\n'), ((2762, 2775), 'numpy.array', 'np.array', (['uxz'], {}), '(uxz)\n', (2770, 2775), True, 'import numpy as np\n'), ((2897, 2910), 'numpy.array', 'np.array', (['uxy'], {}), '(uxy)\n', (2905, 2910), True, 'import numpy as np\n'), ((3460, 3514), 'numpy.concatenate', 'np.concatenate', (['(half_decay, half_decay[::-1])'], {'axis': '(0)'}), '((half_decay, half_decay[::-1]), axis=0)\n', (3474, 3514), True, 'import numpy as np\n'), ((3926, 3974), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 4)', 'tight_layout': '(True)'}), '(figsize=(10, 4), tight_layout=True)\n', (3938, 3974), True, 'import matplotlib.pyplot as plt\n'), ((3985, 4076), 'matplotlib.image.NonUniformImage', 'NonUniformImage', (['ax'], {'interpolation': 'interp', 'extent': '(x[0], x[-1], y[0], y[-1])', 'cmap': 'cmap'}), '(ax, interpolation=interp, extent=(x[0], x[-1], y[0], y[-1]),\n cmap=cmap)\n', (4000, 4076), False, 'from matplotlib.image import NonUniformImage\n'), ((4219, 4268), 'matplotlib.pyplot.title', 'plt.title', (['"""Normalized microchannel flow profile"""'], {}), "('Normalized microchannel flow profile')\n", (4228, 4268), True, 'import matplotlib.pyplot as plt\n'), ((4273, 4293), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x (um)"""'], {}), "('x (um)')\n", (4283, 4293), True, 'import matplotlib.pyplot as plt\n'), ((4298, 4318), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""z (um)"""'], {}), "('z (um)')\n", (4308, 4318), True, 'import matplotlib.pyplot as plt\n'), ((4793, 4810), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (4804, 4810), True, 'import numpy as np\n'), ((4826, 4911), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'subplot_kw': "{'projection': '3d'}", 'figsize': '(7, 5)', 'tight_layout': '(True)'}), "(subplot_kw={'projection': '3d'}, figsize=(7, 5), tight_layout=True\n )\n", (4838, 4911), True, 'import matplotlib.pyplot as plt\n'), ((5497, 5515), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5513, 5515), True, 'import matplotlib.pyplot as plt\n'), ((2950, 2967), 'numpy.transpose', 'np.transpose', (['uxz'], {}), '(uxz)\n', (2962, 2967), True, 'import numpy as np\n'), ((3368, 3391), 'numpy.exp', 'np.exp', (['(-x * decay_rate)'], {}), '(-x * decay_rate)\n', (3374, 3391), True, 'import numpy as np\n'), ((4404, 4462), 'matplotlib.pyplot.savefigure', 'plt.savefigure', ([], {'fname': "(savePath + '/' + saveName + saveType)"}), "(fname=savePath + '/' + saveName + saveType)\n", (4418, 4462), True, 'import matplotlib.pyplot as plt\n'), ((4484, 4494), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4492, 4494), True, 'import matplotlib.pyplot as plt\n'), ((5543, 5601), 'matplotlib.pyplot.savefigure', 'plt.savefigure', ([], {'fname': "(savePath + '/' + saveName + saveType)"}), "(fname=savePath + '/' + saveName + saveType)\n", (5557, 5601), True, 'import matplotlib.pyplot as plt\n'), ((5623, 5633), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5631, 5633), True, 'import matplotlib.pyplot as plt\n'), ((1961, 1977), 'numpy.abs', 'np.abs', (['ux_z_pdf'], {}), '(ux_z_pdf)\n', (1967, 1977), True, 'import numpy as np\n'), ((2004, 2021), 'numpy.mean', 'np.mean', (['ux_z_pdf'], {}), '(ux_z_pdf)\n', (2011, 2021), True, 'import numpy as np\n'), ((2228, 2245), 'numpy.abs', 'np.abs', (['ux_z_slip'], {}), '(ux_z_slip)\n', (2234, 2245), True, 'import numpy as np\n'), ((2273, 2291), 'numpy.mean', 'np.mean', (['ux_z_slip'], {}), '(ux_z_slip)\n', (2280, 2291), True, 'import numpy as np\n'), ((2416, 2431), 'numpy.ones_like', 'np.ones_like', (['y'], {}), '(y)\n', (2428, 2431), True, 'import numpy as np\n'), ((2459, 2474), 'numpy.abs', 'np.abs', (['ux_y_ep'], {}), '(ux_y_ep)\n', (2465, 2474), True, 'import numpy as np\n'), ((2500, 2517), 'numpy.mean', 'np.mean', (['ux_y_pdf'], {}), '(ux_y_pdf)\n', (2507, 2517), True, 'import numpy as np\n'), ((3133, 3144), 'numpy.abs', 'np.abs', (['uxx'], {}), '(uxx)\n', (3139, 3144), True, 'import numpy as np\n'), ((3425, 3448), 'numpy.exp', 'np.exp', (['(-x * decay_rate)'], {}), '(-x * decay_rate)\n', (3431, 3448), True, 'import numpy as np\n'), ((3844, 3859), 'numpy.shape', 'np.shape', (['u_xyz'], {}), '(u_xyz)\n', (3852, 3859), True, 'import numpy as np\n'), ((3888, 3903), 'numpy.shape', 'np.shape', (['u_xyz'], {}), '(u_xyz)\n', (3896, 3903), True, 'import numpy as np\n'), ((4714, 4729), 'numpy.shape', 'np.shape', (['u_xyz'], {}), '(u_xyz)\n', (4722, 4729), True, 'import numpy as np\n'), ((4758, 4773), 'numpy.shape', 'np.shape', (['u_xyz'], {}), '(u_xyz)\n', (4766, 4773), True, 'import numpy as np\n'), ((5287, 5300), 'numpy.max', 'np.max', (['u_xyz'], {}), '(u_xyz)\n', (5293, 5300), True, 'import numpy as np\n'), ((2029, 2046), 'numpy.mean', 'np.mean', (['ux_z_pdf'], {}), '(ux_z_pdf)\n', (2036, 2046), True, 'import numpy as np\n'), ((2301, 2319), 'numpy.mean', 'np.mean', (['ux_z_slip'], {}), '(ux_z_slip)\n', (2308, 2319), True, 'import numpy as np\n'), ((2527, 2543), 'numpy.mean', 'np.mean', (['ux_y_ep'], {}), '(ux_y_ep)\n', (2534, 2543), True, 'import numpy as np\n'), ((3152, 3163), 'numpy.abs', 'np.abs', (['uxx'], {}), '(uxx)\n', (3158, 3163), True, 'import numpy as np\n'), ((5272, 5285), 'numpy.min', 'np.min', (['u_xyz'], {}), '(u_xyz)\n', (5278, 5285), True, 'import numpy as np\n')] |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = '<NAME>'
__date__ = '2018/11/5 15:25'
import copy
import math
import numpy as np
from scipy.stats import f
from scipy.stats import t
class MultipleLinearRegression(object):
def __init__(self):
self.__sample_num = 0
self.__predictor_num = 0
self.__x_mat = None
self.__design_mat = None
self.__y_mat = None
self.__beta_hat_mat = None
self.__hat_mat = None
self.__y_hat_mat = None
self.__error_mat = None
self.__sigma_square_hat = None
self.__variance_beta_hat = None
def load_data(self, *, file_name):
tmp_data = np.loadtxt(file_name)
self.__y_mat = np.mat(tmp_data[:, 0]).T
self.__x_mat = np.mat(tmp_data[:, 1:])
self.__sample_num = len(self.__y_mat)
self.__design_mat = np.hstack((np.ones((self.__sample_num, 1)), self.__x_mat))
self.__predictor_num = self.__design_mat.shape[1]
def init_model(self):
self.__beta_hat_mat = (self.__design_mat.T * self.__design_mat).I * self.__design_mat.T * self.__y_mat
self.__hat_mat = self.__design_mat * (self.__design_mat.T * self.__design_mat).I * self.__design_mat.T
self.__y_hat_mat = self.__hat_mat * self.__y_mat
self.__error_mat = self.__y_mat - self.__y_hat_mat
self.__sigma_square_hat = float((self.__error_mat.T * self.__error_mat) / (
self.__sample_num - self.__predictor_num))
self.__variance_beta_hat = self.__sigma_square_hat * (self.__design_mat.T * self.__design_mat).I
def variance_y_hat(self, *, x_list):
x_hat_mat = np.mat(x_list).T
return self.__sigma_square_hat * x_hat_mat.T * (self.__design_mat.T * self.__design_mat).I * x_hat_mat
def hypothesis_test_zero(self, *, index_list, alpha):
sse_full = float(self.__error_mat.T * self.__error_mat)
print("SSE_Full = ",sse_full)
tmp_design_mat = np.delete(self.__design_mat, index_list, axis=1)
tmp_beta_mat = (tmp_design_mat.T * tmp_design_mat).I * tmp_design_mat.T * self.__y_mat
tmp_yr_hat_mat = tmp_design_mat * tmp_beta_mat
tmp_error_mat = self.__y_mat - tmp_yr_hat_mat
sse_residual = tmp_error_mat.T * tmp_error_mat
print("SSE_Residual = ",sse_residual)
df_sse_f = self.__sample_num - self.__predictor_num
print("DF_full = ",df_sse_f)
df_sse_r = df_sse_f + len(index_list)
print("DF_residual = ",df_sse_r)
tmp_value = float(((sse_residual - sse_full) / (df_sse_r - df_sse_f)) / (sse_full / df_sse_f))
f_value = f.isf(alpha, df_sse_r - df_sse_f, df_sse_f)
ht = tmp_value < f_value
return [ht, tmp_value, f_value]
def confidence_interval_y_hat(self, *, x_list, alpha):
tmp_x_mat = np.mat(x_list).T
pre_num = tmp_x_mat.shape[1]
tmp_y_hat = tmp_x_mat.T * self.__beta_hat_mat
print('Y_Hat = ',tmp_y_hat)
t_value = t.isf(alpha / (2 * pre_num), self.__sample_num - self.__predictor_num)
tmp_sd = np.sqrt(self.variance_y_hat(x_list=x_list))
return [np.diag(tmp_y_hat - t_value * tmp_sd), np.diag(tmp_y_hat + t_value * tmp_sd)]
def prediction_interval_y_hat(self, *, x_list, alpha):
tmp_x_mat = np.mat(x_list).T
pre_num = tmp_x_mat.shape[1]
tmp_y_hat = tmp_x_mat.T * self.__beta_hat_mat
t_value = t.isf(alpha / (2 * pre_num), self.__sample_num - self.__predictor_num)
tmp_sd = np.sqrt(self.__sigma_square_hat * (
1 + tmp_x_mat.T * (self.__design_mat.T * self.__design_mat).I * tmp_x_mat))
return np.mat([np.diag(tmp_y_hat - t_value * tmp_sd),np.diag(tmp_y_hat + t_value * tmp_sd)]).T
@property
def sample_num(self):
return self.__sample_num
@property
def predictor_num(self):
return self.__predictor_num
@property
def x_mat(self):
return self.__x_mat
@property
def y_mat(self):
return self.__y_mat
@property
def design_mat(self):
return self.__design_mat
@property
def beta_hat_mat(self):
return self.__beta_hat_mat
@property
def hat_mat(self):
return self.__hat_mat
@property
def y_hat_mat(self):
return self.__y_hat_mat
@property
def error_mat(self):
return self.__error_mat
@property
def sigma_square_hat(self):
return self.__sigma_square_hat
@property
def variance_beta_hat(self):
return self.__variance_beta_hat
| [
"scipy.stats.t.isf",
"numpy.ones",
"numpy.loadtxt",
"numpy.diag",
"scipy.stats.f.isf",
"numpy.mat",
"numpy.delete",
"numpy.sqrt"
] | [((706, 727), 'numpy.loadtxt', 'np.loadtxt', (['file_name'], {}), '(file_name)\n', (716, 727), True, 'import numpy as np\n'), ((801, 824), 'numpy.mat', 'np.mat', (['tmp_data[:, 1:]'], {}), '(tmp_data[:, 1:])\n', (807, 824), True, 'import numpy as np\n'), ((2026, 2074), 'numpy.delete', 'np.delete', (['self.__design_mat', 'index_list'], {'axis': '(1)'}), '(self.__design_mat, index_list, axis=1)\n', (2035, 2074), True, 'import numpy as np\n'), ((2696, 2739), 'scipy.stats.f.isf', 'f.isf', (['alpha', '(df_sse_r - df_sse_f)', 'df_sse_f'], {}), '(alpha, df_sse_r - df_sse_f, df_sse_f)\n', (2701, 2739), False, 'from scipy.stats import f\n'), ((3064, 3134), 'scipy.stats.t.isf', 't.isf', (['(alpha / (2 * pre_num))', '(self.__sample_num - self.__predictor_num)'], {}), '(alpha / (2 * pre_num), self.__sample_num - self.__predictor_num)\n', (3069, 3134), False, 'from scipy.stats import t\n'), ((3504, 3574), 'scipy.stats.t.isf', 't.isf', (['(alpha / (2 * pre_num))', '(self.__sample_num - self.__predictor_num)'], {}), '(alpha / (2 * pre_num), self.__sample_num - self.__predictor_num)\n', (3509, 3574), False, 'from scipy.stats import t\n'), ((3593, 3707), 'numpy.sqrt', 'np.sqrt', (['(self.__sigma_square_hat * (1 + tmp_x_mat.T * (self.__design_mat.T * self.\n __design_mat).I * tmp_x_mat))'], {}), '(self.__sigma_square_hat * (1 + tmp_x_mat.T * (self.__design_mat.T *\n self.__design_mat).I * tmp_x_mat))\n', (3600, 3707), True, 'import numpy as np\n'), ((752, 774), 'numpy.mat', 'np.mat', (['tmp_data[:, 0]'], {}), '(tmp_data[:, 0])\n', (758, 774), True, 'import numpy as np\n'), ((1706, 1720), 'numpy.mat', 'np.mat', (['x_list'], {}), '(x_list)\n', (1712, 1720), True, 'import numpy as np\n'), ((2898, 2912), 'numpy.mat', 'np.mat', (['x_list'], {}), '(x_list)\n', (2904, 2912), True, 'import numpy as np\n'), ((3214, 3251), 'numpy.diag', 'np.diag', (['(tmp_y_hat - t_value * tmp_sd)'], {}), '(tmp_y_hat - t_value * tmp_sd)\n', (3221, 3251), True, 'import numpy as np\n'), ((3253, 3290), 'numpy.diag', 'np.diag', (['(tmp_y_hat + t_value * tmp_sd)'], {}), '(tmp_y_hat + t_value * tmp_sd)\n', (3260, 3290), True, 'import numpy as np\n'), ((3375, 3389), 'numpy.mat', 'np.mat', (['x_list'], {}), '(x_list)\n', (3381, 3389), True, 'import numpy as np\n'), ((912, 943), 'numpy.ones', 'np.ones', (['(self.__sample_num, 1)'], {}), '((self.__sample_num, 1))\n', (919, 943), True, 'import numpy as np\n'), ((3746, 3783), 'numpy.diag', 'np.diag', (['(tmp_y_hat - t_value * tmp_sd)'], {}), '(tmp_y_hat - t_value * tmp_sd)\n', (3753, 3783), True, 'import numpy as np\n'), ((3784, 3821), 'numpy.diag', 'np.diag', (['(tmp_y_hat + t_value * tmp_sd)'], {}), '(tmp_y_hat + t_value * tmp_sd)\n', (3791, 3821), True, 'import numpy as np\n')] |
import logging
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from mspypeline.core import MSPInitializer
from mspypeline.core.MSPPlots import BasePlotter
from mspypeline.plotting_backend import matplotlib_plots
class MQReader: # TODO currently circular dependency
pass
class MaxQuantPlotter(BasePlotter):
def __init__(
self,
start_dir: str,
reader_data: dict,
intensity_df_name: str = "proteinGroups",
interesting_proteins: dict = None,
go_analysis_gene_names: dict = None,
configs: dict = None,
required_reader="mqreader",
intensity_entries=(("raw", "Intensity ", "Intensity"), ("lfq", "LFQ intensity ", "LFQ intensity"), ("ibaq", "iBAQ ", "iBAQ intensity")),
loglevel=logging.DEBUG
):
super().__init__(
start_dir,
reader_data,
intensity_df_name,
interesting_proteins,
go_analysis_gene_names,
configs,
required_reader,
intensity_entries,
loglevel
)
@classmethod
def from_MSPInitializer(cls, mspinti_instance: MSPInitializer, **kwargs):
default_kwargs = dict(
intensity_entries=(("raw", "Intensity ", "Intensity"), ("lfq", "LFQ intensity ", "LFQ intensity"),
("ibaq", "iBAQ ", "iBAQ intensity")),
intensity_df_name="proteinGroups",
required_reader="mqreader"
)
default_kwargs.update(**kwargs)
return super().from_MSPInitializer(mspinti_instance, **default_kwargs)
@classmethod
def from_file_reader(cls, reader_instance: MQReader, **kwargs):
default_kwargs = dict(
intensity_df_name="proteinGroups",
intensity_entries=(("raw", "Intensity ", "Intensity"), ("lfq", "LFQ intensity ", "LFQ intensity"),
("ibaq", "iBAQ ", "iBAQ intensity")),
)
default_kwargs.update(**kwargs)
return super().from_file_reader(reader_instance, **default_kwargs)
def create_report(self):
def bar_from_counts(ax, counts, compare_counts=None, title=None, relative=False, yscale=None, bar_kwargs=None):
if relative:
ax.set_ylabel("Relative counts")
counts = counts / counts.sum()
else:
ax.set_ylabel("Counts")
if title is not None:
ax.set_title(title)
if bar_kwargs is None:
bar_kwargs = {}
bar_container = ax.bar([x for x in range(len(counts))], counts.values, **bar_kwargs)
if compare_counts is not None:
if relative:
compare_counts = compare_counts / compare_counts.sum()
for bar, height in zip(bar_container, compare_counts):
bar_x = bar.get_x()
bar_w = bar.get_width()
ax.plot((bar_x, bar_x, bar_x + bar_w, bar_x + bar_w),
(0, height, height, 0), color="black")
ax.set_xticks([i for i in range(len(counts))])
ax.set_xticklabels(counts.index)
if yscale is not None:
if isinstance(yscale, str):
ax.set_yscale(yscale)
elif isinstance(yscale, dict):
ax.set_yscale(**yscale)
return bar_container
def hist2d_with_hist(xdata, ydata, title=None, xlabel=None, ylabel=None):
fig = plt.figure(figsize=(14, 7))
if title is not None:
fig.suptitle(title)
spec = fig.add_gridspec(ncols=2, nrows=2, width_ratios=[2, 1], height_ratios=[1, 2])
ax2dhist = fig.add_subplot(spec[1, 0])
ax1dhistvert = fig.add_subplot(spec[0, 0])
ax1dhisthor = fig.add_subplot(spec[1, 1])
h, xedges, yedges, image = ax2dhist.hist2d(xdata, ydata,
bins=100, range=((0, 145), (0, 2))) # TODO find ranges/bins
ax2dhist.set_xlabel(xlabel)
ax2dhist.set_ylabel(ylabel)
ax1dhistvert.hist(xdata, bins=xedges)
ax1dhistvert.set_ylabel("Counts")
ax1dhisthor.hist(ydata, bins=yedges, orientation="horizontal")
ax1dhisthor.set_xlabel("Counts")
ax1dhistvert.set_xlim(*ax2dhist.get_xlim())
ax1dhisthor.set_ylim(*ax2dhist.get_ylim())
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
return fig, (ax2dhist, ax1dhistvert, ax1dhisthor)
def get_plot_data_from_hist(data, density=False, n_bins=16):
d_min, d_max = np.nanmin(data.values), np.nanmax(data.values)
bins = np.linspace(d_min, d_max, n_bins)
y, x = np.histogram(data.values.flatten(), bins=bins, density=density)
y = np.concatenate(([0], np.repeat(y, 2), [0]))
x = np.repeat(x, 2)
return x, y, bins
import matplotlib.cm as cm
cmap = cm.get_cmap("jet")
prefix = "Intensity "
group_iter = None
plot_colors = {}
self.logger.info("Reading files")
try:
self.logger.debug("Reading parameters")
parameters = self.required_reader_data['parameters']
except KeyError:
self.logger.warning("Did not find parameters")
parameters = None
try:
self.logger.debug("Reading summary")
summary = self.required_reader_data['summary']
except KeyError:
self.logger.warning("Did not find summary")
summary = None
try:
self.logger.debug("Reading peptides")
peptides = self.required_reader_data["peptides"]
peptides_prefix_columns = [x for x in peptides.columns if x.startswith(prefix)]
peptides_intensities = peptides[peptides_prefix_columns].replace({0: np.nan})
peptides_intensities.columns = pd.MultiIndex.from_arrays(
[["Grouped Intensity"] * len(peptides_intensities.columns), peptides_intensities.columns],
names=("agg", "sample")
)
last_aa = pd.concat([peptides["Last amino acid"].rename(col)[peptides[col].notna()]
for col in peptides.columns if col.startswith("Experiment")], axis=1)
last_aa_counts = last_aa.apply(pd.Series.value_counts)
last_aa_counts = last_aa_counts.fillna(0).rename(lambda x: x.replace("Experiment ", ""), axis=1)
before_aa = pd.concat([peptides["Amino acid before"].rename(col)[peptides[col].notna()]
for col in peptides.columns if col.startswith("Experiment")], axis=1)
before_aa_counts = before_aa.apply(pd.Series.value_counts)
before_aa_counts = before_aa_counts.fillna(0).rename(lambda x: x.replace("Experiment ", ""), axis=1)
except KeyError:
self.logger.warning("Did not find peptides")
peptides = None
try:
self.logger.debug("Reading proteinGroups")
prot_groups = self.required_reader_data["proteinGroups"]
prot_groups_prefix_columns = [x for x in prot_groups.columns if x.startswith(prefix)]
prot_groups_colors = [x.replace("Intensity ", "") for x in prot_groups_prefix_columns]
plot_colors.update({col: cmap(i/len(prot_groups_colors)) for i, col in enumerate(prot_groups_colors)})
prot_groups_intensities = prot_groups[prot_groups_prefix_columns].replace({0: np.nan})
prot_groups_intensities.columns = pd.MultiIndex.from_arrays(
[["Grouped Intensity"] * len(prot_groups_intensities.columns), prot_groups_intensities.columns],
names=("agg", "sample")
)
has_lfq = str(any([x.startswith("LFQ") for x in prot_groups.columns]))
has_ibaq = str(any([x.startswith("iBAQ") for x in prot_groups.columns]))
except KeyError:
self.logger.warning("Did not find proteinGroups")
prot_groups = None
has_lfq = "File is missing"
has_ibaq = "File is missing"
try:
self.logger.debug("Reading evidence")
evidence = self.required_reader_data["evidence"]
mz = evidence.pivot(index=None, columns="Experiment", values="m/z")
plot_colors.update({col: cmap(i/len(mz.columns)) for i, col in enumerate(mz.columns)})
charge = evidence.pivot(index=None, columns="Experiment", values="Charge")
charge = charge.apply(pd.Series.value_counts)
charge.index = charge.index.astype(int)
missed_cleavages = evidence.pivot(index=None, columns="Experiment", values="Missed cleavages")
missed_cleavages = missed_cleavages.apply(pd.Series.value_counts)
missed_cleavages.index = missed_cleavages.index.astype(int)
retention_length = evidence.pivot(index=None, columns="Experiment", values="Retention length")
retention_time = evidence.pivot(index=None, columns="Experiment", values="Retention time")
except KeyError:
self.logger.warning("Did not find evidence")
evidence = None
try:
self.logger.debug("Reading msScans")
ms_scans = self.required_reader_data["msScans"]
ms_scan_groups = ms_scans.groupby("Raw file")
group_iter = ms_scan_groups.groups
except KeyError:
self.logger.warning("Did not find msScans")
ms_scans = None
try:
self.logger.debug("Reading msmsScans")
msms_scans = self.required_reader_data["msmsScans"]
msms_scan_groups = msms_scans.groupby("Raw file")
group_iter = msms_scan_groups.groups
except KeyError:
self.logger.warning("Did not find msmsScans")
msms_scans = None
self.logger.info("Creating plots")
with PdfPages(os.path.join(self.start_dir, "MaxQuantReport.pdf")) as pdf:
self.logger.debug("Creating start page")
fig = plt.figure(figsize=(14, 7))
text_conf = dict(transform=fig.transFigure, size=24, ha="center")
fig.text(0.5, 0.92, "MaxQuant report", **text_conf)
text_conf.update({"size": 20})
fig.text(0.5, 0.85, "parameter.txt info", **text_conf)
text_conf.pop("size")
if parameters is not None:
fig.text(0.5, 0.8, f"Version: {parameters['Version']}, "
f"run at: {parameters['Date of writing']}", **text_conf)
fig.text(0.5, 0.75, f"Fasta File: {os.path.split(parameters['Fasta file'])[1]}, "
f"Match between runs: {parameters['Match between runs']}", **text_conf)
fig.text(0.5, 0.7, "Min. to Max. peptide length for unspecific search: "
f"{parameters['Min. peptide length for unspecific search']} to {parameters['Max. peptide length for unspecific search']}", **text_conf)
else:
fig.text(0.5, 0.8, "Missing", **text_conf)
text_conf.update({"size": 20})
fig.text(0.5, 0.65, "summary.txt info", **text_conf)
text_conf.pop("size")
if summary is not None:
fig.text(0.5, 0.6, f"Used Enzyme: {summary.loc[1, 'Enzyme']}", **text_conf)
fig.text(0.5, 0.55, f"Variable modifications: {summary.loc[1, 'Variable modifications']}", **text_conf)
fig.text(0.5, 0.5, f"Mass Standard Deviation: mean {summary.loc[:, 'Mass Standard Deviation [ppm]'].mean():.5f} ppm, max {summary.loc[:, 'Mass Standard Deviation [ppm]'].max():.5f} ppm", **text_conf)
else:
fig.text(0.5, 0.6, "Missing", **text_conf)
if prot_groups is not None:
fig.text(0.5, 0.45, f"Identified proteins (without contaminants): {prot_groups.shape[0]}", **text_conf)
if peptides is not None:
fig.text(0.5, 0.4, f"Identified peptides (without contaminants): {peptides.shape[0]}", **text_conf)
fig.text(0.5, 0.35, f"Has LFQ intensities: {has_lfq}", **text_conf)
fig.text(0.5, 0.3, f"Has iBAQ: {has_ibaq}", **text_conf)
pdf.savefig()
plt.close(fig)
# ######
# figure
if peptides is not None:
self.logger.debug("Creating peptide overview")
fig, axarr = plt.subplots(3, 1, figsize=(14, 7))
bar_from_counts(axarr[0], peptides["Missed cleavages"].value_counts(), title="Missed Cleavages", relative=True)
bar_from_counts(axarr[1], peptides["Amino acid before"].value_counts(), title="Amino acid before", yscale="log")
bar_from_counts(axarr[2], peptides["Last amino acid"].value_counts(), title="Last amino acid", yscale="log")
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
pdf.savefig()
plt.close(fig)
# ######
# figure stuff
self.logger.debug("Creating start ??") # TODO
fig, axarr = plt.subplots(3, 1, figsize=(14, 7))
if peptides is not None:
bar_from_counts(axarr[0], peptides["Charges"].str.split(";").explode().value_counts().sort_index(),
title="Peptide Charges")
if evidence is not None:
axarr[1].hist(evidence["m/z"])
axarr[1].set_xlabel("m/z")
axarr[1].set_ylabel("counts")
axarr[1].set_title("peptide m/z")
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
pdf.savefig()
plt.close(fig)
# ###########
# hist with peptide m/z from evidence["m.s"]
self.logger.debug("Creating identified proteins and peptides per sample")
fig, axarr = plt.subplots(2, 1, figsize=(14, 7), sharex=True)
# hist with identified proteins and hist with identified peptides, shared axis
if prot_groups is not None:
identified_proteins = (prot_groups_intensities["Grouped Intensity"] > 0).sum()
identified_proteins = identified_proteins.rename(lambda x: x.replace("Intensity ", ""), axis=0)
bar_from_counts(axarr[0], identified_proteins, title="Identified proteins")
# proteins from proteinGroups, peptides from peptides file per sample
if peptides is not None:
identified_peptides = (peptides_intensities["Grouped Intensity"] > 0).sum()
identified_peptides = identified_peptides.rename(lambda x: x.replace("Intensity ", ""), axis=0)
bar_from_counts(axarr[1], identified_peptides, title="Identified peptides")
axarr[1].xaxis.set_tick_params(rotation=90)
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
pdf.savefig()
plt.close(fig)
# #####################
# Page with stuff
if summary is not None:
self.logger.debug("Creating scan overview")
fig, axarr = plt.subplots(3, 1, sharex=True, figsize=(14, 7))
axarr[0].set_title("MS scans")
axarr[0].bar(range(summary.shape[0]), summary["MS"])
axarr[0].set_ylabel("count")
axarr[1].set_title("MS/MS scans")
axarr[1].bar(range(summary.shape[0]), summary["MS/MS"])
axarr[1].set_ylabel("count")
axarr[2].set_title("MS/MS identified [%]")
axarr[2].bar(range(summary.shape[0]), summary["MS/MS Identified [%]"])
axarr[2].set_ylabel("percent")
axarr[2].set_xticks(range(summary.shape[0]))
axarr[2].set_xticklabels(summary["Experiment"], rotation=90)
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
pdf.savefig()
plt.close(fig)
# ##################
# page with stuff
if prot_groups is not None:
self.logger.debug("Creating overall intensity histograms")
fig, axarr = plt.subplots(2, 1, sharex=True, figsize=(7, 7))
# stacked histogram of log2 intensities
colors = prot_groups_intensities["Grouped Intensity"].rename(lambda x: x.replace("Intensity ", ""), axis=1).columns
colors = [plot_colors[c] for c in colors]
matplotlib_plots.save_intensity_histogram_results(prot_groups_intensities, n_bins=11, histtype="barstacked",
plot=(fig, axarr[0]), color=colors)
# overlayed histogram of log2 intensities
matplotlib_plots.save_intensity_histogram_results(prot_groups_intensities, n_bins=11, histtype="step",
plot=(fig, axarr[1]), color=colors)
fig.legend(bbox_to_anchor=(1.02, 0.5), loc="center left")
fig.tight_layout()
pdf.savefig()
plt.close(fig)
# ############
# page with stuff
# two histograms with heatmap
# retention time vs retention length
# from evidence["Retention time"], evidence["Retention length"]
if evidence is not None:
self.logger.debug("Creating overall retention time vs retention length")
fig, ax = hist2d_with_hist(title="Overall Retention time vs Retention length",
xdata=evidence["Retention time"], ydata=evidence["Retention length"],
xlabel="Retention time [min]", ylabel="Retention length [min]")
pdf.savefig(figure=fig)
plt.close(fig)
# ##############
# individual comparison
if evidence is not None:
self.logger.debug("Creating individual experiment comparison")
charge_flat = charge.sum(axis=1)
missed_cleavages_flat = missed_cleavages.sum(axis=1)
before_aa_counts_flat = before_aa_counts.sum(axis=1)
last_aa_counts_flat = last_aa_counts.sum(axis=1)
mz_x, mz_y, mz_bins = get_plot_data_from_hist(mz, n_bins=15, density=True)
for experiment in mz.columns:
plot_color = plot_colors[experiment]
fig, axarr = plt.subplots(3, 2, figsize=(14, 7))
fig.suptitle(experiment)
axarr[0, 0].hist(mz[experiment], density=True, color=plot_color, bins=mz_bins)
axarr[0, 0].plot(mz_x, mz_y, color="black")
# axarr[0, 0].hist(mz.drop(experiment, axis=1).values.flatten(), histtype="step", density=True, color="black", bins=bins, linewidth=2)
# axarr[0, 0].hist(mz_flat, histtype="step", density=True, color="black", bins=bins, linewidth=2)
axarr[0, 0].set_xlabel("m/z")
axarr[0, 0].set_ylabel("density")
axarr[0, 0].set_title("peptide m/z")
bar_from_counts(axarr[0, 1], charge[experiment],
compare_counts=charge_flat,
relative=True,
title="peptide charges", bar_kwargs={"color": plot_color})
axarr[0, 1].set_xlabel("peptide charge")
bar_from_counts(axarr[1, 0], missed_cleavages[experiment],
compare_counts=missed_cleavages_flat,
relative=True,
title="Number of missed cleavages", bar_kwargs={"color": plot_color})
axarr[1, 0].set_xlabel("missed cleavages")
# TODO this might be missing
bar_from_counts(axarr[1, 1], before_aa_counts[experiment],
compare_counts=before_aa_counts_flat,
relative=True,
bar_kwargs={"color": plot_color})
axarr[1, 1].set_title("Amino acid before")
bar_from_counts(axarr[2, 0], last_aa_counts[experiment],
compare_counts=last_aa_counts_flat,
relative=True,
bar_kwargs={"color": plot_color})
axarr[2, 0].set_title("Last amino acid")
fig.tight_layout()
pdf.savefig()
plt.close(fig)
# ###############
# Intensity histograms of individual samples compared to remaining
if prot_groups is not None:
self.logger.debug("Creating individual intensity histograms")
log2_intensities = np.log2(prot_groups_intensities["Grouped Intensity"])
log2_intensities = log2_intensities.rename(lambda x: x.replace("Intensity ", ""), axis=1)
b, h, bins = get_plot_data_from_hist(log2_intensities, density=True, n_bins=16)
n_figures = int(np.ceil(len(log2_intensities.columns) / 9))
for n_figure in range(n_figures):
fig, axarr = plt.subplots(3, 3, figsize=(15, 15))
for i, (pos, ax) in enumerate(np.ndenumerate(axarr)):
idx = n_figure * 9 + i
try:
experiment = log2_intensities.columns[idx]
except IndexError:
break
ax.hist(log2_intensities.loc[:, experiment], bins=bins, density=True,
color=plot_colors[experiment])
ax.plot(b, h, color="black")
ax.set_title(experiment)
ax.set_xlabel("Intensity")
ax.set_ylabel("density")
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
pdf.savefig(fig)
plt.close(fig)
# ################
# Retention time of individuals samples vs remaining
if evidence is not None:
self.logger.debug("Creating individual retention time histograms")
b, h, bins = get_plot_data_from_hist(retention_time, density=True, n_bins=25)
n_figures = int(np.ceil(len(retention_time.columns) / 9))
for n_figure in range(n_figures):
fig, axarr = plt.subplots(3, 3, figsize=(15, 15))
for i, (pos, ax) in enumerate(np.ndenumerate(axarr)):
idx = n_figure * 9 + i
try:
experiment = retention_time.columns[idx]
except IndexError:
break
ax.hist(retention_time.loc[:, experiment], bins=bins, density=True,
color=plot_colors[experiment])
ax.plot(b, h, color="black")
ax.set_title(experiment)
ax.set_xlabel("Retention time")
ax.set_ylabel("density")
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
pdf.savefig(fig)
plt.close(fig)
# retention time vs retention length individual
if evidence is not None:
self.logger.debug("Creating individual retention time vs retention length")
for experiment in retention_length.columns:
fig, ax = hist2d_with_hist(title=experiment, xdata=retention_time[experiment],
ydata=retention_length[experiment], xlabel="Retention time [min]",
ylabel="Retention length [min]")
pdf.savefig(figure=fig)
plt.close(fig)
# ##########
# total ion current vs retention length
import matplotlib.ticker as ticker
@ticker.FuncFormatter
def scientific_formatter(x, pos):
if x != 0:
return f"{x:.1E}"
else:
return "0"
if group_iter is not None:
self.logger.debug("Creating MS scan and MSMS scan overview")
for n_plot in range(int(np.ceil(len(group_iter) / 4))):
fig = plt.figure(figsize=(14, 7))
outer = fig.add_gridspec(2, 2, wspace=0.2, hspace=0.4)
for i in range(4):
inner = outer[i].subgridspec(2, 1, wspace=0.1, hspace=0.0)
group_counter = 4 * n_plot + i
try:
if msms_scans is not None:
group_name = list(msms_scan_groups.groups.keys())[group_counter]
elif ms_scans is not None:
group_name = list(ms_scan_groups.groups.keys())[group_counter]
else:
raise ValueError("Logic error")
except IndexError:
break
# msms plot
ax_msms: plt.Axes = plt.subplot(inner[1])
ax_msms.text(0.1, 0.9, 'MSMS', horizontalalignment='center',
verticalalignment='center', transform=ax_msms.transAxes)
if msms_scans is not None:
df = msms_scan_groups.get_group(group_name)
ax_msms.plot(df["Retention time"], df["Total ion current"], color="black", linewidth=0.2)
ax_msms.yaxis.set_major_formatter(scientific_formatter)
ax_msms.set_xlabel("Retention time")
ax_msms.set_ylabel("Total ion current")
fig.add_subplot(ax_msms)
# ms plot
# get the axis with shared x axis
ax_ms: plt.Axes = plt.subplot(inner[0], sharex=ax_msms)
# add the text
ax_ms.text(0.1, 0.9, 'MS', horizontalalignment='center',
verticalalignment='center', transform=ax_ms.transAxes)
# disable the axis ticks
ax_ms.tick_params(axis="x", which="both", bottom=False, labelbottom=False)
ax_ms.set_title(group_name)
if ms_scans is not None:
df = ms_scan_groups.get_group(group_name)
ax_ms.plot(df["Retention time"], df["Total ion current"], color="black", linewidth=0.2)
ax_ms.yaxis.set_major_formatter(scientific_formatter)
fig.add_subplot(ax_ms)
pdf.savefig()
plt.close(fig)
self.logger.info("Done creating report") | [
"matplotlib.pyplot.subplot",
"os.path.join",
"matplotlib.cm.get_cmap",
"numpy.ndenumerate",
"matplotlib.pyplot.close",
"numpy.log2",
"numpy.nanmin",
"matplotlib.pyplot.figure",
"numpy.linspace",
"mspypeline.plotting_backend.matplotlib_plots.save_intensity_histogram_results",
"os.path.split",
"... | [((5178, 5196), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['"""jet"""'], {}), "('jet')\n", (5189, 5196), True, 'import matplotlib.cm as cm\n'), ((3654, 3681), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(14, 7)'}), '(figsize=(14, 7))\n', (3664, 3681), True, 'from matplotlib import pyplot as plt\n'), ((4887, 4920), 'numpy.linspace', 'np.linspace', (['d_min', 'd_max', 'n_bins'], {}), '(d_min, d_max, n_bins)\n', (4898, 4920), True, 'import numpy as np\n'), ((5081, 5096), 'numpy.repeat', 'np.repeat', (['x', '(2)'], {}), '(x, 2)\n', (5090, 5096), True, 'import numpy as np\n'), ((10326, 10353), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(14, 7)'}), '(figsize=(14, 7))\n', (10336, 10353), True, 'from matplotlib import pyplot as plt\n'), ((12542, 12556), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (12551, 12556), True, 'from matplotlib import pyplot as plt\n'), ((13401, 13436), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'figsize': '(14, 7)'}), '(3, 1, figsize=(14, 7))\n', (13413, 13436), True, 'from matplotlib import pyplot as plt\n'), ((13965, 13979), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (13974, 13979), True, 'from matplotlib import pyplot as plt\n'), ((14175, 14223), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(14, 7)', 'sharex': '(True)'}), '(2, 1, figsize=(14, 7), sharex=True)\n', (14187, 14223), True, 'from matplotlib import pyplot as plt\n'), ((15223, 15237), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (15232, 15237), True, 'from matplotlib import pyplot as plt\n'), ((4821, 4843), 'numpy.nanmin', 'np.nanmin', (['data.values'], {}), '(data.values)\n', (4830, 4843), True, 'import numpy as np\n'), ((4845, 4867), 'numpy.nanmax', 'np.nanmax', (['data.values'], {}), '(data.values)\n', (4854, 4867), True, 'import numpy as np\n'), ((10195, 10245), 'os.path.join', 'os.path.join', (['self.start_dir', '"""MaxQuantReport.pdf"""'], {}), "(self.start_dir, 'MaxQuantReport.pdf')\n", (10207, 10245), False, 'import os\n'), ((12729, 12764), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'figsize': '(14, 7)'}), '(3, 1, figsize=(14, 7))\n', (12741, 12764), True, 'from matplotlib import pyplot as plt\n'), ((13253, 13267), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (13262, 13267), True, 'from matplotlib import pyplot as plt\n'), ((15430, 15478), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'sharex': '(True)', 'figsize': '(14, 7)'}), '(3, 1, sharex=True, figsize=(14, 7))\n', (15442, 15478), True, 'from matplotlib import pyplot as plt\n'), ((16247, 16261), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (16256, 16261), True, 'from matplotlib import pyplot as plt\n'), ((16470, 16517), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'sharex': '(True)', 'figsize': '(7, 7)'}), '(2, 1, sharex=True, figsize=(7, 7))\n', (16482, 16517), True, 'from matplotlib import pyplot as plt\n'), ((16781, 16929), 'mspypeline.plotting_backend.matplotlib_plots.save_intensity_histogram_results', 'matplotlib_plots.save_intensity_histogram_results', (['prot_groups_intensities'], {'n_bins': '(11)', 'histtype': '"""barstacked"""', 'plot': '(fig, axarr[0])', 'color': 'colors'}), "(prot_groups_intensities,\n n_bins=11, histtype='barstacked', plot=(fig, axarr[0]), color=colors)\n", (16830, 16929), False, 'from mspypeline.plotting_backend import matplotlib_plots\n'), ((17066, 17208), 'mspypeline.plotting_backend.matplotlib_plots.save_intensity_histogram_results', 'matplotlib_plots.save_intensity_histogram_results', (['prot_groups_intensities'], {'n_bins': '(11)', 'histtype': '"""step"""', 'plot': '(fig, axarr[1])', 'color': 'colors'}), "(prot_groups_intensities,\n n_bins=11, histtype='step', plot=(fig, axarr[1]), color=colors)\n", (17115, 17208), False, 'from mspypeline.plotting_backend import matplotlib_plots\n'), ((17428, 17442), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (17437, 17442), True, 'from matplotlib import pyplot as plt\n'), ((18167, 18181), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (18176, 18181), True, 'from matplotlib import pyplot as plt\n'), ((21331, 21384), 'numpy.log2', 'np.log2', (["prot_groups_intensities['Grouped Intensity']"], {}), "(prot_groups_intensities['Grouped Intensity'])\n", (21338, 21384), True, 'import numpy as np\n'), ((5042, 5057), 'numpy.repeat', 'np.repeat', (['y', '(2)'], {}), '(y, 2)\n', (5051, 5057), True, 'import numpy as np\n'), ((18845, 18880), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(2)'], {'figsize': '(14, 7)'}), '(3, 2, figsize=(14, 7))\n', (18857, 18880), True, 'from matplotlib import pyplot as plt\n'), ((21053, 21067), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (21062, 21067), True, 'from matplotlib import pyplot as plt\n'), ((21749, 21785), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(3)'], {'figsize': '(15, 15)'}), '(3, 3, figsize=(15, 15))\n', (21761, 21785), True, 'from matplotlib import pyplot as plt\n'), ((22564, 22578), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (22573, 22578), True, 'from matplotlib import pyplot as plt\n'), ((23049, 23085), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(3)'], {'figsize': '(15, 15)'}), '(3, 3, figsize=(15, 15))\n', (23061, 23085), True, 'from matplotlib import pyplot as plt\n'), ((23865, 23879), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (23874, 23879), True, 'from matplotlib import pyplot as plt\n'), ((24488, 24502), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (24497, 24502), True, 'from matplotlib import pyplot as plt\n'), ((25042, 25069), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(14, 7)'}), '(figsize=(14, 7))\n', (25052, 25069), True, 'from matplotlib import pyplot as plt\n'), ((27605, 27619), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (27614, 27619), True, 'from matplotlib import pyplot as plt\n'), ((21836, 21857), 'numpy.ndenumerate', 'np.ndenumerate', (['axarr'], {}), '(axarr)\n', (21850, 21857), True, 'import numpy as np\n'), ((23136, 23157), 'numpy.ndenumerate', 'np.ndenumerate', (['axarr'], {}), '(axarr)\n', (23150, 23157), True, 'import numpy as np\n'), ((25911, 25932), 'matplotlib.pyplot.subplot', 'plt.subplot', (['inner[1]'], {}), '(inner[1])\n', (25922, 25932), True, 'from matplotlib import pyplot as plt\n'), ((26742, 26779), 'matplotlib.pyplot.subplot', 'plt.subplot', (['inner[0]'], {'sharex': 'ax_msms'}), '(inner[0], sharex=ax_msms)\n', (26753, 26779), True, 'from matplotlib import pyplot as plt\n'), ((10885, 10924), 'os.path.split', 'os.path.split', (["parameters['Fasta file']"], {}), "(parameters['Fasta file'])\n", (10898, 10924), False, 'import os\n')] |
#!/usr/bin/env python
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Object crash with prior vehicle action scenario:
The scenario realizes the user controlled ego vehicle
moving along the road and encounters a cyclist ahead after taking a right or left turn.
"""
import math
import py_trees
import carla
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.scenariomanager.scenarioatomics.atomic_behaviors import (ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity)
from srunner.scenariomanager.scenarioatomics.atomic_criteria import CollisionTest
from srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions import (InTriggerDistanceToLocationAlongRoute, InTriggerDistanceToVehicle, DriveDistance, InTriggerDistanceToLocation)
from srunner.scenariomanager.timer import TimeOut
from srunner.scenarios.basic_scenario import BasicScenario
from srunner.tools.scenario_helper import generate_target_waypoint, generate_target_waypoint_in_route
from leaderboard.utils.route_manipulation import interpolate_trajectory, downsample_route
import numpy as np
from collections import OrderedDict
import pickle
import os
from carla_specific_utils.carla_specific_tools import perturb_route, add_transform, create_transform, copy_transform
from customized_utils import make_hierarchical_dir
def get_generated_transform(added_dist, waypoint):
"""
Calculate the transform of the adversary
"""
if added_dist == 0:
return waypoint.transform
_wp = waypoint.next(added_dist)
if _wp:
_wp = _wp[-1]
else:
raise RuntimeError("Cannot get next waypoint !")
return _wp.transform
class Intersection(BasicScenario):
"""
This class holds everything required for a simple object crash
with prior vehicle action involving a vehicle and a cyclist.
The ego vehicle is passing through a road and encounters
a cyclist after taking a turn. This is the version used when the ego vehicle
is following a given route. (Traffic Scenario 4)
This is a single ego vehicle scenario
"""
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True, timeout=60, customized_data=None):
"""
Setup all relevant parameters and create scenario
"""
self.world = world
self.customized_data = customized_data
self._wmap = CarlaDataProvider.get_map()
self._trigger_location = config.trigger_points[0].location
self._num_lane_changes = 0
# Timeout of scenario in seconds
self.timeout = timeout
# Total Number of attempts to relocate a vehicle before spawning
if 'number_of_attempts_to_request_actor' in customized_data:
self._number_of_attempts = customized_data['number_of_attempts_to_request_actor']
else:
self._number_of_attempts = 10
self._ego_route = CarlaDataProvider.get_ego_vehicle_route()
self.static_list = []
self.pedestrian_list = []
self.vehicle_list = []
if 'tmp_travel_dist_file' in self.customized_data and os.path.exists(self.customized_data['tmp_travel_dist_file']):
os.remove(self.customized_data['tmp_travel_dist_file'])
print('remove tmp_travel_dist_file')
super(Intersection, self).__init__("Intersection",
ego_vehicles,
config,
world,
debug_mode,
criteria_enable=criteria_enable)
def _request_actor(self, actor_category, actor_model, waypoint_transform, simulation_enabled=False, color=None, bounds=None, is_waypoint_follower=None, center_transform=None):
def bound_xy(generated_transform, bounds):
if bounds:
x_min, x_max, y_min, y_max = bounds
g_x = generated_transform.location.x
g_y = generated_transform.location.y
if center_transform:
c_x = center_transform.location.x
c_y = center_transform.location.y
x_min += c_x
x_max += c_x
y_min += c_y
y_max += c_y
generated_transform.location.x = np.max([g_x, x_min])
generated_transform.location.x = np.min([g_x, x_max])
generated_transform.location.y = np.max([g_y, y_min])
generated_transform.location.y = np.min([g_y, y_max])
# print('bounds', x_min, x_max, y_min, y_max, g_x, g_y, center_transform)
# If we fail too many times, this will break and the session will be assigned the lowest default score. We do this to disencourage samples that result in invalid locations
# Number of attempts made so far
status = 'success'
is_success = False
generated_transform = copy_transform(waypoint_transform)
if actor_category != 'vehicle':
g_x = generated_transform.location.x
g_y = generated_transform.location.y
g_yaw = generated_transform.rotation.yaw
for i in range(self._number_of_attempts):
for j in range(2):
try:
added_dist = i*0.5
cur_x = g_x + np.random.uniform(0, added_dist)
cur_y = g_y + np.random.uniform(0, added_dist)
cur_t = create_transform(cur_x, cur_y, 0, 0, g_yaw, 0)
generated_transform.location.y += np.random.uniform(0, 1)
bound_xy(generated_transform, bounds)
actor_object = CarlaDataProvider.request_new_actor(
model=actor_model, spawn_point=cur_t, color=color, actor_category=actor_category)
is_success = True
break
except (RuntimeError, AttributeError) as r:
status = 'fail_1_'+str(i)
if is_success:
break
if actor_category == 'vehicle' or status == 'fail_1_'+str(self._number_of_attempts):
for i in range(self._number_of_attempts):
try:
added_dist = i*0.5
waypoint = self._wmap.get_waypoint(waypoint_transform.location, project_to_road=True, lane_type=carla.LaneType.Any)
generated_transform = get_generated_transform(added_dist, waypoint)
# if actor_category == 'vehicle' and is_waypoint_follower:
generated_transform.rotation.yaw = waypoint_transform.rotation.yaw
bound_xy(generated_transform, bounds)
actor_object = CarlaDataProvider.request_new_actor(
model=actor_model, spawn_point=generated_transform, color=color, actor_category=actor_category)
is_success = True
break
except (RuntimeError, AttributeError) as r:
status = 'fail_2_'+str(i)
if is_success:
actor_object.set_simulate_physics(enabled=simulation_enabled)
else:
actor_object = None
generated_transform = None
status = 'fail_all'
if status != 'success' and is_success:
print('{} {} {} ({:.2f},{:.2f},{:.2f})->({:.2f},{:.2f},{:.2f})'.format(status, actor_model, is_waypoint_follower, waypoint_transform.location.x, waypoint_transform.location.y, waypoint_transform.rotation.yaw, generated_transform.location.x, generated_transform.location.y, waypoint_transform.rotation.yaw))
else:
print(status, actor_category, actor_model, is_waypoint_follower)
return actor_object, generated_transform
def _initialize_actors(self, config):
"""
Custom initialization
static_center_transforms, static_center_transforms, vehicle_center_transforms:
{i:(x_i, y_i)}
"""
def spawning_actors_within_bounds(object_type):
final_generated_transforms = []
if object_type == 'static':
object_list = self.static_list
elif object_type == 'pedestrian':
object_list = self.pedestrian_list
elif object_type == 'vehicle':
object_list = self.vehicle_list
for i, object_i in enumerate(self.customized_data[object_type+'_list']):
if 'add_center' in self.customized_data and self.customized_data['add_center']:
key = object_type+'_center_transform'+'_'+str(i)
if key in self.customized_data:
center_transform = self.customized_data[key]
else:
center_transform = self.customized_data['center_transform']
# hack: only x, y should be added
center_transform.location.z = 0
center_transform.rotation.pitch = 0
center_transform.rotation.yaw = 0
center_transform.rotation.roll = 0
spawn_transform_i = add_transform(center_transform, object_i.spawn_transform)
# print(object_type, i, object_i.model, 'add center', object_i.spawn_transform, '->', spawn_transform_i)
else:
spawn_transform_i = object_i.spawn_transform
center_transform = None
if 'parameters_max_bounds' in self.customized_data.keys():
bounds = [self.customized_data[k1][object_type+'_'+k2+'_'+str(i)] for k1, k2 in [('parameters_min_bounds', 'x_min'), ('parameters_max_bounds', 'x_max'), ('parameters_min_bounds', 'y_min'), ('parameters_max_bounds', 'y_max')]]
# bounds = []
else:
bounds = []
if object_type == 'vehicle' and hasattr(object_i, 'color') and object_i.model != 'vehicle.tesla.cybertruck':
color = object_i.color
else:
color = None
if object_type == 'vehicle':
is_waypoint_follower = object_i.waypoint_follower
else:
is_waypoint_follower = None
if object_type == 'pedestrian':
simulation_enabled = False
else:
simulation_enabled = True
actor, generated_transform = self._request_actor(object_type, object_i.model, spawn_transform_i, simulation_enabled, color, bounds, is_waypoint_follower, center_transform)
if actor and generated_transform:
object_list.append((actor, generated_transform))
gx = generated_transform.location.x
gy = generated_transform.location.y
gyaw = generated_transform.rotation.yaw
if 'add_center' in self.customized_data and self.customized_data['add_center']:
cx = center_transform.location.x
cy = center_transform.location.y
else:
cx = 0
cy = 0
final_generated_transforms.append((gx - cx, gy - cy, gyaw))
else:
final_generated_transforms.append((None, None, None))
# print(object_type, 'saved final generated transform', final_generated_transforms)
return final_generated_transforms
all_final_generated_transforms = OrderedDict()
for object_type in ['static', 'pedestrian', 'vehicle']:
final_generated_transforms = spawning_actors_within_bounds(object_type)
all_final_generated_transforms[object_type] = final_generated_transforms
# hack:
tmp_folder = make_hierarchical_dir(['tmp_folder'])
filename = os.path.join(tmp_folder, str(config.cur_server_port)+'.pickle')
# print('filename', '\n'*10, filename, '\n'*10)
with open(filename, 'wb') as f_out:
pickle.dump(all_final_generated_transforms, f_out)
def _create_behavior(self):
"""
"""
def record_travel_dist(tmp_travel_dist_file, actor_id, actor_general_type, index):
with open(tmp_travel_dist_file, 'a') as f_out:
f_out.write(','.join([str(actor_id), actor_general_type, str(index)])+'\n')
# building the tree
scenario_sequence = py_trees.composites.Sequence()
waypoint_events = py_trees.composites.Parallel(
policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ALL)
destroy_actors = py_trees.composites.Sequence()
reach_destination = InTriggerDistanceToLocation(self.ego_vehicles[0], self.customized_data['destination'], 2)
scenario_sequence.add_child(waypoint_events)
scenario_sequence.add_child(reach_destination)
scenario_sequence.add_child(destroy_actors)
tmp_travel_dist_file = None
if 'tmp_travel_dist_file' in self.customized_data:
tmp_travel_dist_file = self.customized_data['tmp_travel_dist_file']
for i in range(len(self.pedestrian_list)):
pedestrian_actor, pedestrian_generated_transform = self.pedestrian_list[i]
pedestrian_info = self.customized_data['pedestrian_list'][i]
if tmp_travel_dist_file:
record_travel_dist(self.customized_data['tmp_travel_dist_file'], pedestrian_actor.id, 'pedestrian', i)
print('record_travel_dist tmp_travel_dist_file')
trigger_distance = InTriggerDistanceToVehicle(self.ego_vehicles[0],
pedestrian_actor, pedestrian_info.trigger_distance)
movement = py_trees.composites.Parallel(policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
actor_velocity = KeepVelocity(pedestrian_actor, pedestrian_info.speed)
actor_traverse = DriveDistance(pedestrian_actor, pedestrian_info.dist_to_travel, tmp_travel_dist_file=tmp_travel_dist_file)
movement.add_child(actor_velocity)
movement.add_child(actor_traverse)
if pedestrian_info.after_trigger_behavior == 'destroy':
after_trigger_behavior = ActorDestroy(pedestrian_actor)
elif pedestrian_info.after_trigger_behavior == 'stop':
after_trigger_behavior = StopVehicle(pedestrian_actor, brake_value=0.5)
destroy_actor = ActorDestroy(pedestrian_actor)
destroy_actors.add_child(destroy_actor)
else:
raise
pedestrian_behaviors = py_trees.composites.Sequence()
pedestrian_behaviors.add_child(trigger_distance)
pedestrian_behaviors.add_child(movement)
pedestrian_behaviors.add_child(after_trigger_behavior)
waypoint_events.add_child(pedestrian_behaviors)
for i in range(len(self.vehicle_list)):
vehicle_actor, generated_transform = self.vehicle_list[i]
vehicle_info = self.customized_data['vehicle_list'][i]
if tmp_travel_dist_file:
record_travel_dist(self.customized_data['tmp_travel_dist_file'], vehicle_actor.id, 'vehicle', i)
print('record_travel_dist tmp_travel_dist_file')
keep_velocity = py_trees.composites.Parallel("Trigger condition for changing behavior", policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
keep_velocity.add_child(InTriggerDistanceToVehicle(self.ego_vehicles[0], vehicle_actor, vehicle_info.trigger_distance))
keep_velocity.add_child(WaypointFollower(vehicle_actor, vehicle_info.initial_speed, avoid_collision=vehicle_info.avoid_collision))
if vehicle_info.waypoint_follower:
# interpolate current location and destination to find a path
start_location = generated_transform.location
end_location = vehicle_info.targeted_waypoint.location
_, route = interpolate_trajectory(self.world, [start_location, end_location])
ds_ids = downsample_route(route, self.customized_data['sample_factor'])
route = [(route[x][0], route[x][1]) for x in ds_ids]
# print('route', len(route))
perturb_route(route, vehicle_info.waypoints_perturbation)
# visualize_route(route)
plan = []
for transform, cmd in route:
wp = self._wmap.get_waypoint(transform.location, project_to_road=False, lane_type=carla.LaneType.Any)
if not wp:
wp = self._wmap.get_waypoint(transform.location, project_to_road=True, lane_type=carla.LaneType.Any)
print('(', transform.location.x, transform.location.y, ')', 'is replaced by', '(', wp.transform.location.x, wp.transform.location.y, ')')
plan.append((wp, cmd))
movement = WaypointFollower(actor=vehicle_actor, target_speed=vehicle_info.targeted_speed, plan=plan, avoid_collision=vehicle_info.avoid_collision)
else:
movement = py_trees.composites.Parallel(policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
actor_velocity = KeepVelocity(vehicle_actor, vehicle_info.targeted_speed, target_direction=vehicle_info.target_direction)
actor_traverse = DriveDistance(vehicle_actor, vehicle_info.dist_to_travel, tmp_travel_dist_file=tmp_travel_dist_file)
movement.add_child(actor_velocity)
movement.add_child(actor_traverse)
if vehicle_info.after_trigger_behavior == 'destroy':
after_trigger_behavior = ActorDestroy(vehicle_actor)
elif vehicle_info.after_trigger_behavior == 'stop':
after_trigger_behavior = StopVehicle(vehicle_actor, brake_value=0.5)
destroy_actor = ActorDestroy(vehicle_actor)
destroy_actors.add_child(destroy_actor)
else:
raise
vehicle_behaviors = py_trees.composites.Sequence()
vehicle_behaviors.add_child(keep_velocity)
vehicle_behaviors.add_child(movement)
vehicle_behaviors.add_child(after_trigger_behavior)
waypoint_events.add_child(vehicle_behaviors)
return scenario_sequence
def _create_test_criteria(self):
"""
A list of all test criteria will be created that is later used
in parallel behavior tree.
"""
criteria = []
collision_criterion = CollisionTest(self.ego_vehicles[0])
criteria.append(collision_criterion)
return criteria
def __del__(self):
"""
Remove all actors upon deletion
"""
self.remove_all_actors()
| [
"os.remove",
"pickle.dump",
"srunner.scenariomanager.carla_data_provider.CarlaDataProvider.request_new_actor",
"srunner.scenariomanager.scenarioatomics.atomic_criteria.CollisionTest",
"os.path.exists",
"customized_utils.make_hierarchical_dir",
"leaderboard.utils.route_manipulation.interpolate_trajectory... | [((2554, 2581), 'srunner.scenariomanager.carla_data_provider.CarlaDataProvider.get_map', 'CarlaDataProvider.get_map', ([], {}), '()\n', (2579, 2581), False, 'from srunner.scenariomanager.carla_data_provider import CarlaDataProvider\n'), ((3077, 3118), 'srunner.scenariomanager.carla_data_provider.CarlaDataProvider.get_ego_vehicle_route', 'CarlaDataProvider.get_ego_vehicle_route', ([], {}), '()\n', (3116, 3118), False, 'from srunner.scenariomanager.carla_data_provider import CarlaDataProvider\n'), ((5212, 5246), 'carla_specific_utils.carla_specific_tools.copy_transform', 'copy_transform', (['waypoint_transform'], {}), '(waypoint_transform)\n', (5226, 5246), False, 'from carla_specific_utils.carla_specific_tools import perturb_route, add_transform, create_transform, copy_transform\n'), ((11965, 11978), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (11976, 11978), False, 'from collections import OrderedDict\n'), ((12251, 12288), 'customized_utils.make_hierarchical_dir', 'make_hierarchical_dir', (["['tmp_folder']"], {}), "(['tmp_folder'])\n", (12272, 12288), False, 'from customized_utils import make_hierarchical_dir\n'), ((12897, 12927), 'py_trees.composites.Sequence', 'py_trees.composites.Sequence', ([], {}), '()\n', (12925, 12927), False, 'import py_trees\n'), ((12954, 13041), 'py_trees.composites.Parallel', 'py_trees.composites.Parallel', ([], {'policy': 'py_trees.common.ParallelPolicy.SUCCESS_ON_ALL'}), '(policy=py_trees.common.ParallelPolicy.\n SUCCESS_ON_ALL)\n', (12982, 13041), False, 'import py_trees\n'), ((13075, 13105), 'py_trees.composites.Sequence', 'py_trees.composites.Sequence', ([], {}), '()\n', (13103, 13105), False, 'import py_trees\n'), ((13136, 13230), 'srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions.InTriggerDistanceToLocation', 'InTriggerDistanceToLocation', (['self.ego_vehicles[0]', "self.customized_data['destination']", '(2)'], {}), "(self.ego_vehicles[0], self.customized_data[\n 'destination'], 2)\n", (13163, 13230), False, 'from srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions import InTriggerDistanceToLocationAlongRoute, InTriggerDistanceToVehicle, DriveDistance, InTriggerDistanceToLocation\n'), ((19061, 19096), 'srunner.scenariomanager.scenarioatomics.atomic_criteria.CollisionTest', 'CollisionTest', (['self.ego_vehicles[0]'], {}), '(self.ego_vehicles[0])\n', (19074, 19096), False, 'from srunner.scenariomanager.scenarioatomics.atomic_criteria import CollisionTest\n'), ((3278, 3338), 'os.path.exists', 'os.path.exists', (["self.customized_data['tmp_travel_dist_file']"], {}), "(self.customized_data['tmp_travel_dist_file'])\n", (3292, 3338), False, 'import os\n'), ((3352, 3407), 'os.remove', 'os.remove', (["self.customized_data['tmp_travel_dist_file']"], {}), "(self.customized_data['tmp_travel_dist_file'])\n", (3361, 3407), False, 'import os\n'), ((12485, 12535), 'pickle.dump', 'pickle.dump', (['all_final_generated_transforms', 'f_out'], {}), '(all_final_generated_transforms, f_out)\n', (12496, 12535), False, 'import pickle\n'), ((14031, 14135), 'srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions.InTriggerDistanceToVehicle', 'InTriggerDistanceToVehicle', (['self.ego_vehicles[0]', 'pedestrian_actor', 'pedestrian_info.trigger_distance'], {}), '(self.ego_vehicles[0], pedestrian_actor,\n pedestrian_info.trigger_distance)\n', (14057, 14135), False, 'from srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions import InTriggerDistanceToLocationAlongRoute, InTriggerDistanceToVehicle, DriveDistance, InTriggerDistanceToLocation\n'), ((14168, 14255), 'py_trees.composites.Parallel', 'py_trees.composites.Parallel', ([], {'policy': 'py_trees.common.ParallelPolicy.SUCCESS_ON_ONE'}), '(policy=py_trees.common.ParallelPolicy.\n SUCCESS_ON_ONE)\n', (14196, 14255), False, 'import py_trees\n'), ((14281, 14334), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.KeepVelocity', 'KeepVelocity', (['pedestrian_actor', 'pedestrian_info.speed'], {}), '(pedestrian_actor, pedestrian_info.speed)\n', (14293, 14334), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((14364, 14474), 'srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions.DriveDistance', 'DriveDistance', (['pedestrian_actor', 'pedestrian_info.dist_to_travel'], {'tmp_travel_dist_file': 'tmp_travel_dist_file'}), '(pedestrian_actor, pedestrian_info.dist_to_travel,\n tmp_travel_dist_file=tmp_travel_dist_file)\n', (14377, 14474), False, 'from srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions import InTriggerDistanceToLocationAlongRoute, InTriggerDistanceToVehicle, DriveDistance, InTriggerDistanceToLocation\n'), ((15058, 15088), 'py_trees.composites.Sequence', 'py_trees.composites.Sequence', ([], {}), '()\n', (15086, 15088), False, 'import py_trees\n'), ((15767, 15896), 'py_trees.composites.Parallel', 'py_trees.composites.Parallel', (['"""Trigger condition for changing behavior"""'], {'policy': 'py_trees.common.ParallelPolicy.SUCCESS_ON_ONE'}), "('Trigger condition for changing behavior',\n policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)\n", (15795, 15896), False, 'import py_trees\n'), ((18546, 18576), 'py_trees.composites.Sequence', 'py_trees.composites.Sequence', ([], {}), '()\n', (18574, 18576), False, 'import py_trees\n'), ((4583, 4603), 'numpy.max', 'np.max', (['[g_x, x_min]'], {}), '([g_x, x_min])\n', (4589, 4603), True, 'import numpy as np\n'), ((4653, 4673), 'numpy.min', 'np.min', (['[g_x, x_max]'], {}), '([g_x, x_max])\n', (4659, 4673), True, 'import numpy as np\n'), ((4723, 4743), 'numpy.max', 'np.max', (['[g_y, y_min]'], {}), '([g_y, y_min])\n', (4729, 4743), True, 'import numpy as np\n'), ((4793, 4813), 'numpy.min', 'np.min', (['[g_y, y_max]'], {}), '([g_y, y_max])\n', (4799, 4813), True, 'import numpy as np\n'), ((14677, 14707), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.ActorDestroy', 'ActorDestroy', (['pedestrian_actor'], {}), '(pedestrian_actor)\n', (14689, 14707), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((15929, 16027), 'srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions.InTriggerDistanceToVehicle', 'InTriggerDistanceToVehicle', (['self.ego_vehicles[0]', 'vehicle_actor', 'vehicle_info.trigger_distance'], {}), '(self.ego_vehicles[0], vehicle_actor,\n vehicle_info.trigger_distance)\n', (15955, 16027), False, 'from srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions import InTriggerDistanceToLocationAlongRoute, InTriggerDistanceToVehicle, DriveDistance, InTriggerDistanceToLocation\n'), ((16061, 16171), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.WaypointFollower', 'WaypointFollower', (['vehicle_actor', 'vehicle_info.initial_speed'], {'avoid_collision': 'vehicle_info.avoid_collision'}), '(vehicle_actor, vehicle_info.initial_speed, avoid_collision\n =vehicle_info.avoid_collision)\n', (16077, 16171), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((16458, 16524), 'leaderboard.utils.route_manipulation.interpolate_trajectory', 'interpolate_trajectory', (['self.world', '[start_location, end_location]'], {}), '(self.world, [start_location, end_location])\n', (16480, 16524), False, 'from leaderboard.utils.route_manipulation import interpolate_trajectory, downsample_route\n'), ((16550, 16612), 'leaderboard.utils.route_manipulation.downsample_route', 'downsample_route', (['route', "self.customized_data['sample_factor']"], {}), "(route, self.customized_data['sample_factor'])\n", (16566, 16612), False, 'from leaderboard.utils.route_manipulation import interpolate_trajectory, downsample_route\n'), ((16744, 16801), 'carla_specific_utils.carla_specific_tools.perturb_route', 'perturb_route', (['route', 'vehicle_info.waypoints_perturbation'], {}), '(route, vehicle_info.waypoints_perturbation)\n', (16757, 16801), False, 'from carla_specific_utils.carla_specific_tools import perturb_route, add_transform, create_transform, copy_transform\n'), ((17427, 17568), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.WaypointFollower', 'WaypointFollower', ([], {'actor': 'vehicle_actor', 'target_speed': 'vehicle_info.targeted_speed', 'plan': 'plan', 'avoid_collision': 'vehicle_info.avoid_collision'}), '(actor=vehicle_actor, target_speed=vehicle_info.\n targeted_speed, plan=plan, avoid_collision=vehicle_info.avoid_collision)\n', (17443, 17568), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((17609, 17696), 'py_trees.composites.Parallel', 'py_trees.composites.Parallel', ([], {'policy': 'py_trees.common.ParallelPolicy.SUCCESS_ON_ONE'}), '(policy=py_trees.common.ParallelPolicy.\n SUCCESS_ON_ONE)\n', (17637, 17696), False, 'import py_trees\n'), ((17725, 17834), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.KeepVelocity', 'KeepVelocity', (['vehicle_actor', 'vehicle_info.targeted_speed'], {'target_direction': 'vehicle_info.target_direction'}), '(vehicle_actor, vehicle_info.targeted_speed, target_direction=\n vehicle_info.target_direction)\n', (17737, 17834), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((17863, 17967), 'srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions.DriveDistance', 'DriveDistance', (['vehicle_actor', 'vehicle_info.dist_to_travel'], {'tmp_travel_dist_file': 'tmp_travel_dist_file'}), '(vehicle_actor, vehicle_info.dist_to_travel,\n tmp_travel_dist_file=tmp_travel_dist_file)\n', (17876, 17967), False, 'from srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions import InTriggerDistanceToLocationAlongRoute, InTriggerDistanceToVehicle, DriveDistance, InTriggerDistanceToLocation\n'), ((18179, 18206), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.ActorDestroy', 'ActorDestroy', (['vehicle_actor'], {}), '(vehicle_actor)\n', (18191, 18206), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((7085, 7221), 'srunner.scenariomanager.carla_data_provider.CarlaDataProvider.request_new_actor', 'CarlaDataProvider.request_new_actor', ([], {'model': 'actor_model', 'spawn_point': 'generated_transform', 'color': 'color', 'actor_category': 'actor_category'}), '(model=actor_model, spawn_point=\n generated_transform, color=color, actor_category=actor_category)\n', (7120, 7221), False, 'from srunner.scenariomanager.carla_data_provider import CarlaDataProvider\n'), ((9518, 9575), 'carla_specific_utils.carla_specific_tools.add_transform', 'add_transform', (['center_transform', 'object_i.spawn_transform'], {}), '(center_transform, object_i.spawn_transform)\n', (9531, 9575), False, 'from carla_specific_utils.carla_specific_tools import perturb_route, add_transform, create_transform, copy_transform\n'), ((14816, 14862), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.StopVehicle', 'StopVehicle', (['pedestrian_actor'], {'brake_value': '(0.5)'}), '(pedestrian_actor, brake_value=0.5)\n', (14827, 14862), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((14895, 14925), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.ActorDestroy', 'ActorDestroy', (['pedestrian_actor'], {}), '(pedestrian_actor)\n', (14907, 14925), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((18312, 18355), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.StopVehicle', 'StopVehicle', (['vehicle_actor'], {'brake_value': '(0.5)'}), '(vehicle_actor, brake_value=0.5)\n', (18323, 18355), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((18388, 18415), 'srunner.scenariomanager.scenarioatomics.atomic_behaviors.ActorDestroy', 'ActorDestroy', (['vehicle_actor'], {}), '(vehicle_actor)\n', (18400, 18415), False, 'from srunner.scenariomanager.scenarioatomics.atomic_behaviors import ActorTransformSetter, ActorDestroy, KeepVelocity, HandBrakeVehicle, StopVehicle, WaypointFollower, AccelerateToVelocity\n'), ((5771, 5817), 'carla_specific_utils.carla_specific_tools.create_transform', 'create_transform', (['cur_x', 'cur_y', '(0)', '(0)', 'g_yaw', '(0)'], {}), '(cur_x, cur_y, 0, 0, g_yaw, 0)\n', (5787, 5817), False, 'from carla_specific_utils.carla_specific_tools import perturb_route, add_transform, create_transform, copy_transform\n'), ((5876, 5899), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (5893, 5899), True, 'import numpy as np\n'), ((6001, 6122), 'srunner.scenariomanager.carla_data_provider.CarlaDataProvider.request_new_actor', 'CarlaDataProvider.request_new_actor', ([], {'model': 'actor_model', 'spawn_point': 'cur_t', 'color': 'color', 'actor_category': 'actor_category'}), '(model=actor_model, spawn_point=cur_t,\n color=color, actor_category=actor_category)\n', (6036, 6122), False, 'from srunner.scenariomanager.carla_data_provider import CarlaDataProvider\n'), ((5635, 5667), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'added_dist'], {}), '(0, added_dist)\n', (5652, 5667), True, 'import numpy as np\n'), ((5706, 5738), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'added_dist'], {}), '(0, added_dist)\n', (5723, 5738), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# In case of poor (Sh***y) commenting contact <EMAIL>
# Basic
from os import path
# Testing
import time
import numpy as np
import yaml
import h5py
# import pickle as pickle
from scipy import sparse
# from FP_initial_conditions import *
# from math import *
# Speed
# from numba import jit
# Other importing
# sys.path.append(os.path.join(os.path.dirname(__file__), '[PATH]'))
"""@package docstring
File:
Author: <NAME>
Email: <EMAIL>
Description:
"""
class Solver(object):
"""!Docstring for Solver. """
def __init__(self, pfile=None, name='Solver'):
"""!Set parameters for PDE to be solved including boundary conditions
@param pfile: parameter file for PDEs
"""
print("Init Solver")
self._name = name
self._pfile = pfile
self._params = None
self.data_frame_made = False
self.written = False
# Initialize parameters from file
self.ParseParams()
self.makeSolutionGrid()
self.setInitialCondition()
# Create data frame
self._h5_data = h5py.File(path.join("{}.h5".format(self._name)), 'w')
# self._h5_data.attrs = self._params
for k, v in self._params.items():
self._h5_data.attrs[k] = v
self.makeDataframe()
def ParseParams(self):
"""!TODO: Docstring for ParseParams.
@return: TODO
"""
if self._pfile is not None:
with open(self._pfile, 'r') as pf:
self._params = yaml.safe_load(pf)
else:
self._params = default_params
# Integration parameters
self.t = 0.
self.ds = self._params["ds"] # Segmentation size of microtubules
self.nwrite = self._params["nwrite"]
if "nt" not in self._params:
self.nsteps = self._params["nsteps"]
self.dt = self._params["dt"] # Time step
self.nt = self.nsteps * self.dt
self._params["nt"] = self.nt
elif "dt" not in self._params:
self.nt = self._params["nt"] # total time
self.nsteps = self._params["nsteps"]
self.dt = float(self.nt / self.nsteps)
self._params["dt"] = self.dt
elif "nsteps" not in self._params:
self.nt = self._params["nt"] # total time
self.dt = self._params["dt"] # Time step
self.nsteps = float(self.nt / self.dt)
self._params["nsteps"] = self.nsteps
# Make time array. Set extra space for initial condition
self.time = np.linspace(0, self.nt, self.nsteps + 1).tolist()
print("Time step: ", self.dt)
print("Total time: ", self.nt)
print("Number of steps: ", self.nsteps)
def setInitialCondition(self):
"""!TODO: Docstring for setInitialCondition.
@return: TODO
"""
if 'initial_condition' in self._params:
if self._params['initial_condition'] == 'equil':
self.sgrid += self.src_mat
else:
self.sgrid += eval(self._params['initial_condition'])
print(self.sgrid)
def makeSolutionGrid(self):
"""!Make an array of solutions to solve the PDE
@return: void
"""
L1 = self._params["L1"]
L2 = self._params["L2"]
ds = self.ds
self.ns1 = int(L1 / ds) + 2
self.ns2 = int(L2 / ds) + 2
# TODO This maintains proper spacing but I should check this with
# someone who understands methods better
self._params["L1"] = ds * (self.ns1 - 2)
self._params["L2"] = ds * (self.ns2 - 2)
# Discrete rod locations, extra spots left for boundary conditions
self.s1, step1 = np.linspace(
0, ds * (self.ns1 - 1), self.ns1, retstep=True)
self.s1 -= L1 * .5
self.s2, step2 = np.linspace(
0, ds * (self.ns2 - 1), self.ns2, retstep=True)
self.s2 -= (L2 * .5)
print("ds1: ", step1)
print("ds2: ", step2)
# self.sgrid = sparse.csc_matrix((self.ns1, self.ns2))
self.sgrid = np.zeros((self.ns1, self.ns2))
self.calcSourceMatrix()
self.calcForceMatrix()
self.calcTorqueMatrix()
def Run(self):
"""!Run PDE solver with parameters in pfile
@return: void
"""
# Write initial configuration
self.Write()
self.written = False
t0 = time.time()
while self.t < self.nt:
self.Step()
self.t += self.dt
if (int(self.t / self.dt) % self.nwrite) == 0:
t1 = time.time()
print(r" {} steps in {:.4f} seconds, {:.1f}% complete".format(
self.nwrite, t1 - t0, float(self.t / self.nt) * 100.))
self.Write()
# Reset write function
self.written = False
t0 = time.time()
return
def Step(self):
"""!Step solver method one unit in time
@return: Sum of changes of grid, Changes phi1 and phi0
"""
print("Step not made!")
def makeDataframe(self):
"""! Make data frame to read from later
@return: Dictionary pointing to data in dataframe
"""
# Enter params into hdf5 data file as attributes for later
if not self.data_frame_made:
for key, param in self._params.items():
self._h5_data.attrs[key] = param
time = self.time[::self.nwrite]
self._nframes = len(time)
self._time_dset = self._h5_data.create_dataset('time', data=time,
dtype=np.float32)
self._xl_grp = self._h5_data.create_group('XL_data')
self._mt_grp = self._h5_data.create_group('MT_data')
s1_dset = self._mt_grp.create_dataset('s1', data=self.s1)
s2_dset = self._mt_grp.create_dataset('s2', data=self.s2)
self._xl_distr_dset = self._xl_grp.create_dataset(
'XL_distr',
shape=(self.ns1, self.ns2, self._nframes + 1),
dtype=np.float32)
self._interaction_grp = self._h5_data.create_group(
'Interaction_data')
self._force_dset = self._interaction_grp.create_dataset(
'force_data',
shape=(self._nframes + 1, 3),
dtype=np.float32)
self._torque_dset = self._interaction_grp.create_dataset(
'torque_data',
shape=(self._nframes + 1, 3),
dtype=np.float32)
self.data_frame_made = True
def calcSourceMatrix(self):
"""Virtual functions for calculating source matrix
@return: TODO
"""
print("calcSourceMatrix not implemented. Source matrix initialized with zeros.")
self.src_mat = sparse.csc_matrix((self.ns1, self.ns2))
def calcForceMatrix(self):
"""Virtual functions for calculating force matrix for a given configuration
@return: TODO
"""
print("calcforceMatrix not implemented. Source matrix initialized with zeros.")
self.f_mat = sparse.csc_matrix((self.ns1, self.ns2, 3))
def calcTorqueMatrix(self):
"""Virtual functions for calculating force matrix for a given configuration
@return: TODO
"""
print("calcTorqueMatrix not implemented. Source matrix initialized with zeros.")
self.t_mat = sparse.csc_matrix((self.ns1, self.ns2, 3))
def Write(self):
"""!Write current step in algorithm into data frame
@return: void
"""
i_step = ((self.t / self.dt) / self.nwrite)
if not self.written:
# self._xl_distr_dset[:, :, i_step] = self.sgrid.todense()
self._xl_distr_dset[:, :, i_step] = self.sgrid
self._time_dset[i_step] = self.t
self._force_dset[i_step] = self.force
self._torque_dset[i_step] = self.torque
self.written = True
return i_step
def Save(self):
"""!Flush and close hdf5 data frame
@return: void
"""
self._h5_data.flush()
self._h5_data.close()
##########################################
if __name__ == "__main__":
print("Not implemented yet")
| [
"numpy.zeros",
"time.time",
"scipy.sparse.csc_matrix",
"yaml.safe_load",
"numpy.linspace"
] | [((3749, 3808), 'numpy.linspace', 'np.linspace', (['(0)', '(ds * (self.ns1 - 1))', 'self.ns1'], {'retstep': '(True)'}), '(0, ds * (self.ns1 - 1), self.ns1, retstep=True)\n', (3760, 3808), True, 'import numpy as np\n'), ((3874, 3933), 'numpy.linspace', 'np.linspace', (['(0)', '(ds * (self.ns2 - 1))', 'self.ns2'], {'retstep': '(True)'}), '(0, ds * (self.ns2 - 1), self.ns2, retstep=True)\n', (3885, 3933), True, 'import numpy as np\n'), ((4121, 4151), 'numpy.zeros', 'np.zeros', (['(self.ns1, self.ns2)'], {}), '((self.ns1, self.ns2))\n', (4129, 4151), True, 'import numpy as np\n'), ((4456, 4467), 'time.time', 'time.time', ([], {}), '()\n', (4465, 4467), False, 'import time\n'), ((6921, 6960), 'scipy.sparse.csc_matrix', 'sparse.csc_matrix', (['(self.ns1, self.ns2)'], {}), '((self.ns1, self.ns2))\n', (6938, 6960), False, 'from scipy import sparse\n'), ((7221, 7263), 'scipy.sparse.csc_matrix', 'sparse.csc_matrix', (['(self.ns1, self.ns2, 3)'], {}), '((self.ns1, self.ns2, 3))\n', (7238, 7263), False, 'from scipy import sparse\n'), ((7526, 7568), 'scipy.sparse.csc_matrix', 'sparse.csc_matrix', (['(self.ns1, self.ns2, 3)'], {}), '((self.ns1, self.ns2, 3))\n', (7543, 7568), False, 'from scipy import sparse\n'), ((1521, 1539), 'yaml.safe_load', 'yaml.safe_load', (['pf'], {}), '(pf)\n', (1535, 1539), False, 'import yaml\n'), ((2566, 2606), 'numpy.linspace', 'np.linspace', (['(0)', 'self.nt', '(self.nsteps + 1)'], {}), '(0, self.nt, self.nsteps + 1)\n', (2577, 2606), True, 'import numpy as np\n'), ((4634, 4645), 'time.time', 'time.time', ([], {}), '()\n', (4643, 4645), False, 'import time\n'), ((4926, 4937), 'time.time', 'time.time', ([], {}), '()\n', (4935, 4937), False, 'import time\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 19:46:14 2019
@author: Nate
"""
import numpy as np
import matplotlib.pyplot as plt
import pdb
'''
Determine the value of π to ≈ 14 digits by solving for the root of the equation
f(x) = cos(x) = 0
using the second order Newton’s method. The exact solution is
x∗ = π/2, so that π = 2x∗.
Use the initial guess of x = 1.5, corresponds to a guess of π ≈ 3. How many
iterations are needed to achieve 14 digits? Repeat the calculation with initial guesses
x = 1, x = 0.5 and x = 0.25.
'''
def f(guess):
return(np.cos(guess))
def df(guess):
return(-np.sin(guess))
guess = [1.5,1,.5,.25]
for i in range(len(guess)):
for val in range(4):
nextguess = guess[i] - f(guess[i])/df(guess[i])
guess[i] = nextguess
if i == 3:
answer = guess[i]
#print(guess[i])
#print(answer)
print(i, ": " , (3/2)*np.pi-answer)
if abs((3/2)*np.pi-answer) < 10**(-12):
print('True')
else:
answer = 2*guess[i]
print(i, ": " , np.pi-answer)
if abs(np.pi-answer) < 10**(-12):
print('True')
print(10**(-10)) | [
"numpy.sin",
"numpy.cos"
] | [((571, 584), 'numpy.cos', 'np.cos', (['guess'], {}), '(guess)\n', (577, 584), True, 'import numpy as np\n'), ((614, 627), 'numpy.sin', 'np.sin', (['guess'], {}), '(guess)\n', (620, 627), True, 'import numpy as np\n')] |
import time
import numpy as np
from column_01 import Column
from pump_01 import Pump
from sample_01 import Sample
from interaction_01 import Interaction
from calculation_current import Simu
import os
print(os.listdir())
if 'functions_with_D' in os.listdir():
from functions_with_D import Functions
else:
from Calculation.functions_with_D import Functions
class Simu_with_D(Simu):
def simulation(self):
const1 = -(self.Column.dz/(self.Column.dt*self.Column.velocity))
F = self.Column.F*const1
const1_1 = 1+const1
inter = list(self.Interaction.ads_max*self.Interaction.adsorption)
qq, cc = Functions.simulation_with_D(self.num_time_steps, self.num_length_steps,
self.Interaction.adsorption,
self.C,len(self.num_components),
self.q,inter,const1_1,const1,F)
self.q = np.array(qq)
self.C = np.array(cc)
return self.q,self.C
# def __init__(self,Sample,Column,Interaction, Pump, time_factor=1 ):
# super().__init__(Sample,Column,Interaction, Pump, time_factor=1 )
# print(self.Sample.a)
if __name__=='__main__':
n = 3
a = time.time()
sample = Sample(volume=0.1 , composition=np.ones(n)/n, concentration=1,
a=np.linspace(1,40,n), adsorption_max=np.linspace(0.025,0.04,n))
sample.disp_concentration = [0 for _ in range(n)]
sample.disp_concentration[-1] = 0.025
pump = Pump(1)
column = Column([1,20], 5*10**(-3), 0.635,pump, CFL=0.35)
interaction = Interaction(sample)
sim = Simu_with_D(sample,column,interaction,pump,time_factor=1)
#%%
sim.injection()
#%%
sim.simulation()
# q = np.array(q)
# C = np.array(C)
b = time.time()
Ausgabe = 'für {} Punkte braucht das Programm {} Sekunden'.format(np.product( sim.C.shape),(b-a))
print(Ausgabe) | [
"interaction_01.Interaction",
"pump_01.Pump",
"numpy.ones",
"time.time",
"numpy.product",
"numpy.array",
"numpy.linspace",
"column_01.Column",
"os.listdir"
] | [((208, 220), 'os.listdir', 'os.listdir', ([], {}), '()\n', (218, 220), False, 'import os\n'), ((247, 259), 'os.listdir', 'os.listdir', ([], {}), '()\n', (257, 259), False, 'import os\n'), ((1285, 1296), 'time.time', 'time.time', ([], {}), '()\n', (1294, 1296), False, 'import time\n'), ((1570, 1577), 'pump_01.Pump', 'Pump', (['(1)'], {}), '(1)\n', (1574, 1577), False, 'from pump_01 import Pump\n'), ((1591, 1643), 'column_01.Column', 'Column', (['[1, 20]', '(5 * 10 ** -3)', '(0.635)', 'pump'], {'CFL': '(0.35)'}), '([1, 20], 5 * 10 ** -3, 0.635, pump, CFL=0.35)\n', (1597, 1643), False, 'from column_01 import Column\n'), ((1658, 1677), 'interaction_01.Interaction', 'Interaction', (['sample'], {}), '(sample)\n', (1669, 1677), False, 'from interaction_01 import Interaction\n'), ((1869, 1880), 'time.time', 'time.time', ([], {}), '()\n', (1878, 1880), False, 'import time\n'), ((968, 980), 'numpy.array', 'np.array', (['qq'], {}), '(qq)\n', (976, 980), True, 'import numpy as np\n'), ((998, 1010), 'numpy.array', 'np.array', (['cc'], {}), '(cc)\n', (1006, 1010), True, 'import numpy as np\n'), ((1952, 1975), 'numpy.product', 'np.product', (['sim.C.shape'], {}), '(sim.C.shape)\n', (1962, 1975), True, 'import numpy as np\n'), ((1395, 1416), 'numpy.linspace', 'np.linspace', (['(1)', '(40)', 'n'], {}), '(1, 40, n)\n', (1406, 1416), True, 'import numpy as np\n'), ((1431, 1458), 'numpy.linspace', 'np.linspace', (['(0.025)', '(0.04)', 'n'], {}), '(0.025, 0.04, n)\n', (1442, 1458), True, 'import numpy as np\n'), ((1342, 1352), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (1349, 1352), True, 'import numpy as np\n')] |
try:
from ulab import numpy as np
except:
import numpy as np
dtypes = (np.uint8, np.int8, np.uint16, np.int16)
a = np.array(range(8)).reshape((2, 4))
np.savetxt('loadtxt.dat', a, header='test file data')
print(np.loadtxt('loadtxt.dat'))
print()
for dtype in dtypes:
print(np.loadtxt('loadtxt.dat', dtype=dtype))
print()
np.savetxt('loadtxt.dat', a, delimiter=',', header='test file data')
print(np.loadtxt('loadtxt.dat', delimiter=','))
print()
np.savetxt('loadtxt.dat', a, delimiter=',', comments='!', header='test file data')
print(np.loadtxt('loadtxt.dat', delimiter=',', comments='!'))
print()
print(np.loadtxt('loadtxt.dat', delimiter=',', comments='!', usecols=1))
print()
print(np.loadtxt('loadtxt.dat', delimiter=',', comments='!', usecols=(0, 1)))
print()
a = np.array(range(36)).reshape((9, 4))
np.savetxt('loadtxt.dat', a, header='9 data rows and a comment')
print(np.loadtxt('loadtxt.dat', max_rows=5))
print()
print(np.loadtxt('loadtxt.dat', skiprows=5, dtype=np.uint16))
| [
"numpy.savetxt",
"numpy.loadtxt"
] | [((160, 213), 'numpy.savetxt', 'np.savetxt', (['"""loadtxt.dat"""', 'a'], {'header': '"""test file data"""'}), "('loadtxt.dat', a, header='test file data')\n", (170, 213), True, 'import numpy as np\n'), ((341, 409), 'numpy.savetxt', 'np.savetxt', (['"""loadtxt.dat"""', 'a'], {'delimiter': '""","""', 'header': '"""test file data"""'}), "('loadtxt.dat', a, delimiter=',', header='test file data')\n", (351, 409), True, 'import numpy as np\n'), ((468, 555), 'numpy.savetxt', 'np.savetxt', (['"""loadtxt.dat"""', 'a'], {'delimiter': '""","""', 'comments': '"""!"""', 'header': '"""test file data"""'}), "('loadtxt.dat', a, delimiter=',', comments='!', header=\n 'test file data')\n", (478, 555), True, 'import numpy as np\n'), ((830, 894), 'numpy.savetxt', 'np.savetxt', (['"""loadtxt.dat"""', 'a'], {'header': '"""9 data rows and a comment"""'}), "('loadtxt.dat', a, header='9 data rows and a comment')\n", (840, 894), True, 'import numpy as np\n'), ((221, 246), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {}), "('loadtxt.dat')\n", (231, 246), True, 'import numpy as np\n'), ((417, 457), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {'delimiter': '""","""'}), "('loadtxt.dat', delimiter=',')\n", (427, 457), True, 'import numpy as np\n'), ((558, 612), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {'delimiter': '""","""', 'comments': '"""!"""'}), "('loadtxt.dat', delimiter=',', comments='!')\n", (568, 612), True, 'import numpy as np\n'), ((628, 693), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {'delimiter': '""","""', 'comments': '"""!"""', 'usecols': '(1)'}), "('loadtxt.dat', delimiter=',', comments='!', usecols=1)\n", (638, 693), True, 'import numpy as np\n'), ((709, 779), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {'delimiter': '""","""', 'comments': '"""!"""', 'usecols': '(0, 1)'}), "('loadtxt.dat', delimiter=',', comments='!', usecols=(0, 1))\n", (719, 779), True, 'import numpy as np\n'), ((901, 938), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {'max_rows': '(5)'}), "('loadtxt.dat', max_rows=5)\n", (911, 938), True, 'import numpy as np\n'), ((955, 1009), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {'skiprows': '(5)', 'dtype': 'np.uint16'}), "('loadtxt.dat', skiprows=5, dtype=np.uint16)\n", (965, 1009), True, 'import numpy as np\n'), ((288, 326), 'numpy.loadtxt', 'np.loadtxt', (['"""loadtxt.dat"""'], {'dtype': 'dtype'}), "('loadtxt.dat', dtype=dtype)\n", (298, 326), True, 'import numpy as np\n')] |
import json
import math
from collections import defaultdict, Counter
import linecache
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import jieba
from cfg import *
from index import Index, Document
import logging
jieba.setLogLevel(logging.INFO)
class Bm25:
def __init__(self, k1=2, k2=1, b=0.5):
self.k1=k1
self.k2=k2
self.b=b
def calcualte(self, N, df, dl, avg_dl, tf, qf):
w = math.log((N - df + 0.5) / (df + 0.5), 2)
K = self.k1 * (1 - self.b + self.b * dl / avg_dl)
return w*tf*(self.k1 + 1)/(tf + K)*qf*(self.k2 + 1)/(qf + self.k2)
def fit_transform(self, query_tokens_set, index_dict, qf) -> defaultdict:
scores = defaultdict(lambda: 0.0)
for token in query_tokens_set:
try:
index = index_dict[token]
df = index[0]
doc_list = index[1]
for doc_dict in doc_list:
doc = Index(**doc_dict)
s = self.calcualte(index_dict['_doc_cnt'], df, doc.dl, index_dict['_avg_dl'], doc.tf, qf[token])
scores[doc.doc_id] += s
except KeyError:
print(f'Query token {token} is not in dict!')
return scores
class TfIdf:
def calculate(self, N, df, tf, dl):
idf = math.log(N/(df + 1), 2)
return tf / dl * idf
def fit_transform(self, query_tokens, index_dict):
scores = defaultdict(lambda: 0.0)
for token in query_tokens:
try:
index = index_dict[token]
df = index[0]
doc_list = index[1]
for doc_dict in doc_list:
doc = Index(**doc_dict)
s = self.calculate(index_dict['_doc_cnt'], df, doc.tf, doc.dl)
scores[doc.doc_id] += s
except KeyError:
print(f'Query token {token} is not in dict!')
return scores
class F1Exp:
def __init__(self, s=0.25, k=0.35):
self.s = s
self.k = k
def calcualte(self, N, df, dl, avg_dl, tf, qf):
TF = 1 + math.log(1 + math.log(tf))
ln = (avg_dl + self.s) / (avg_dl + dl*self.s)
ex_idf = math.pow((N + 1) / df, self.k)
return qf*TF*ln*ex_idf
def fit_transform(self, query_tokens_set, index_dict, qf) -> defaultdict:
scores = defaultdict(lambda: 0.0)
for token in query_tokens_set:
try:
index = index_dict[token]
df = index[0]
doc_list = index[1]
for doc_dict in doc_list:
doc = Index(**doc_dict)
s = self.calcualte(index_dict['_doc_cnt'], df, doc.dl, index_dict['_avg_dl'], doc.tf, qf[token])
scores[doc.doc_id] += s
except KeyError:
print(f'Query token {token} is not in dict!')
return scores
class Sorter:
def __init__(self, top_n=10, stopwords_path=STOP_WORDS_PATH, index_path=INDEX_PATH, label_path=LABEL_PATH):
self.top_n = top_n
with open(stopwords_path, 'r', encoding='utf-8') as f:
self.stopwords = set(f.read().split('\n'))
with open(index_path, 'r', encoding='utf-8') as f:
self.index_dict = json.load(f)
with open(label_path, 'r', encoding='utf-8') as f:
self.label_dict = json.load(f)
self.bm25 = Bm25()
self.tfidf = TfIdf()
self.f1exp = F1Exp()
@staticmethod
def get_doc(doc_id) -> 'Document':
line = linecache.getline(TARGET_PATH, doc_id + 1)
doc_list = line.split('|||')
assert doc_id == int(doc_list[1])
return Document(label_id=int(doc_list[0]),
doc_id=int(doc_list[1]),
title=doc_list[2],
date=doc_list[3],
url=doc_list[4],
text=doc_list[5])
@staticmethod
def get_docs(doc_ids, top_n) -> (list, list):
docs = []
selected_ids = []
for i, doc_id in enumerate(doc_ids):
doc = Sorter.get_doc(doc_id)
if len(docs) > 0 and docs[-1].title == doc.title:
continue
docs.append(doc)
selected_ids.append(i)
if len(docs) == top_n:
break
return docs, selected_ids
def transform(self, scores_list: list):
mean_norm: np.array = None
for scores in scores_list:
vector = np.array(scores).reshape(-1, 1)
norm = MinMaxScaler().fit_transform(vector)
mean_norm = norm if mean_norm is None else mean_norm + norm
mean_norm /= 3
return np.argsort(-mean_norm.reshape(1, -1), axis=1)[0], mean_norm
def sort(self, query: str):
bm25_scores = self.sort_by_bm25(jieba.lcut(query))
tfidf_scores = self.sort_by_tfidf(jieba.lcut(query))
f1exp_scores = self.sort_by_f1exp(jieba.lcut(query))
assert len(bm25_scores) == len(tfidf_scores)
assert len(f1exp_scores) == len(tfidf_scores)
sort_id, mean_norm = self.transform([list(bm25_scores.values()), list(tfidf_scores.values()), list(f1exp_scores.values())])
doc_ids = np.array(list(bm25_scores.keys()))
# select twice for removing repeated docs
docs, selected_ids = self.get_docs(doc_ids[sort_id].tolist(), self.top_n)
assert len(selected_ids) == self.top_n
return docs, mean_norm[sort_id[selected_ids]].tolist()
def sort_by_bm25(self, query_tokens: list, key=0):
qf = Counter(query_tokens)
query_tokens_set = set(query_tokens)
bm25_scores: dict = self.bm25.fit_transform(query_tokens_set, self.index_dict, qf)
return dict(sorted(bm25_scores.items(), key=lambda x: x[key], reverse=True))
def sort_by_tfidf(self, query_tokens: list, key=0):
tfidf_scores: dict = self.tfidf.fit_transform(query_tokens, self.index_dict)
return dict(sorted(tfidf_scores.items(), key=lambda x: x[key], reverse=True))
def sort_by_f1exp(self, query_tokens: list, key=0):
qf = Counter(query_tokens)
query_tokens_set = set(query_tokens)
f1exp_scores: dict = self.f1exp.fit_transform(query_tokens_set, self.index_dict, qf)
return dict(sorted(f1exp_scores.items(), key=lambda x: x[key], reverse=True))
def sort_by_time(self, query_tokens: list):
pass
if __name__ == '__main__':
sorter = Sorter()
print(sorter.sort('计算机'))
| [
"index.Index",
"json.load",
"linecache.getline",
"math.pow",
"jieba.setLogLevel",
"sklearn.preprocessing.MinMaxScaler",
"collections.defaultdict",
"numpy.array",
"jieba.lcut",
"collections.Counter",
"math.log"
] | [((233, 264), 'jieba.setLogLevel', 'jieba.setLogLevel', (['logging.INFO'], {}), '(logging.INFO)\n', (250, 264), False, 'import jieba\n'), ((441, 481), 'math.log', 'math.log', (['((N - df + 0.5) / (df + 0.5))', '(2)'], {}), '((N - df + 0.5) / (df + 0.5), 2)\n', (449, 481), False, 'import math\n'), ((711, 736), 'collections.defaultdict', 'defaultdict', (['(lambda : 0.0)'], {}), '(lambda : 0.0)\n', (722, 736), False, 'from collections import defaultdict, Counter\n'), ((1328, 1353), 'math.log', 'math.log', (['(N / (df + 1))', '(2)'], {}), '(N / (df + 1), 2)\n', (1336, 1353), False, 'import math\n'), ((1454, 1479), 'collections.defaultdict', 'defaultdict', (['(lambda : 0.0)'], {}), '(lambda : 0.0)\n', (1465, 1479), False, 'from collections import defaultdict, Counter\n'), ((2225, 2255), 'math.pow', 'math.pow', (['((N + 1) / df)', 'self.k'], {}), '((N + 1) / df, self.k)\n', (2233, 2255), False, 'import math\n'), ((2383, 2408), 'collections.defaultdict', 'defaultdict', (['(lambda : 0.0)'], {}), '(lambda : 0.0)\n', (2394, 2408), False, 'from collections import defaultdict, Counter\n'), ((3567, 3609), 'linecache.getline', 'linecache.getline', (['TARGET_PATH', '(doc_id + 1)'], {}), '(TARGET_PATH, doc_id + 1)\n', (3584, 3609), False, 'import linecache\n'), ((5623, 5644), 'collections.Counter', 'Counter', (['query_tokens'], {}), '(query_tokens)\n', (5630, 5644), False, 'from collections import defaultdict, Counter\n'), ((6164, 6185), 'collections.Counter', 'Counter', (['query_tokens'], {}), '(query_tokens)\n', (6171, 6185), False, 'from collections import defaultdict, Counter\n'), ((3294, 3306), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3303, 3306), False, 'import json\n'), ((3396, 3408), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3405, 3408), False, 'import json\n'), ((4869, 4886), 'jieba.lcut', 'jieba.lcut', (['query'], {}), '(query)\n', (4879, 4886), False, 'import jieba\n'), ((4930, 4947), 'jieba.lcut', 'jieba.lcut', (['query'], {}), '(query)\n', (4940, 4947), False, 'import jieba\n'), ((4991, 5008), 'jieba.lcut', 'jieba.lcut', (['query'], {}), '(query)\n', (5001, 5008), False, 'import jieba\n'), ((968, 985), 'index.Index', 'Index', ([], {}), '(**doc_dict)\n', (973, 985), False, 'from index import Index, Document\n'), ((1707, 1724), 'index.Index', 'Index', ([], {}), '(**doc_dict)\n', (1712, 1724), False, 'from index import Index, Document\n'), ((2140, 2152), 'math.log', 'math.log', (['tf'], {}), '(tf)\n', (2148, 2152), False, 'import math\n'), ((2640, 2657), 'index.Index', 'Index', ([], {}), '(**doc_dict)\n', (2645, 2657), False, 'from index import Index, Document\n'), ((4534, 4550), 'numpy.array', 'np.array', (['scores'], {}), '(scores)\n', (4542, 4550), True, 'import numpy as np\n'), ((4585, 4599), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (4597, 4599), False, 'from sklearn.preprocessing import MinMaxScaler\n')] |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
from vis.colorline import colorline
import matplotlib.path as mpath
import os
from vis.plot_rl_figures import plot_from_file
def main():
filename="cooper/paper_figure/rl_data/recover_seed-0.csv"
plot_from_file(filename,reduce_plot_data=1, stepsize=1)
directory="cooper/paper_figure/rl_data/"
plot_agg_from_files(directory )
def plot_agg_from_files(directory, max_entries=None):
save_folder="cooper/paper_figure/plots/"
ignore_transients=100
perf_bias = 0.05
filenames = os.listdir(directory)
agg_dict={}
if max_entries != None:
filenames = filenames[:max_entries]
for filename in filenames:
print(filename)
label_to_data_map=plot_from_file(f"{directory}{filename}", show_subplots=False)
for key in label_to_data_map.keys():
if key not in agg_dict.keys():
agg_dict[key]=[]
else:
agg_dict[key].append(label_to_data_map[key])
#gotta deal with the weights and outputs across dimensions...
for i in range(len(agg_dict["time"])):
plt.plot(agg_dict["time"][i][ignore_transients:], agg_dict["performances"][i][ignore_transients:],\
label="instantaenous performance", color=[0,0,0.5,0.1] )
plt.xlabel("Time")
plt.ylabel("Performance")
plt.show()
for perf in ["performances","running_average_performances"]:
avg = (np.mean(agg_dict[perf], axis=0)+ perf_bias)*100
#err= np.std(agg_dict["performances"], ddof=1, axis=0) / np.sqrt(np.size(agg_dict[perf]))
err= np.std(agg_dict[perf], axis=0)*100
plt.plot(agg_dict["time"][0][ignore_transients:], avg[ignore_transients:], label=perf )
plt.fill_between(agg_dict["time"][0][ignore_transients:], (avg-err)[ignore_transients:], (avg+err)[ignore_transients:], alpha=0.2)
plt.xlabel("Time")
plt.ylabel(perf)
plt.savefig(f"{save_folder}{perf}.png")
plt.show()
size=2
if "w0_0" in agg_dict:
for i in range(size):
for j in range(size):
avg = np.mean(agg_dict[f"w{i}_{j}"], axis=0)
err= np.std(agg_dict[f"w{i}_{j}"], axis=0)
plt.plot(agg_dict["time"][0], avg, label=f"avg w{i}_{j}" )
plt.fill_between(agg_dict["time"][0], avg-err, avg+err, alpha=0.2)
plt.show()
if __name__ == "__main__":
main() | [
"vis.plot_rl_figures.plot_from_file",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.std",
"numpy.mean",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.xlabel",
"os.listdir",
"matplotlib.pyplot.savefig"
] | [((402, 458), 'vis.plot_rl_figures.plot_from_file', 'plot_from_file', (['filename'], {'reduce_plot_data': '(1)', 'stepsize': '(1)'}), '(filename, reduce_plot_data=1, stepsize=1)\n', (416, 458), False, 'from vis.plot_rl_figures import plot_from_file\n'), ((715, 736), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (725, 736), False, 'import os\n'), ((1466, 1484), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (1476, 1484), True, 'import matplotlib.pyplot as plt\n'), ((1489, 1514), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Performance"""'], {}), "('Performance')\n", (1499, 1514), True, 'import matplotlib.pyplot as plt\n'), ((1519, 1529), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1527, 1529), True, 'import matplotlib.pyplot as plt\n'), ((907, 968), 'vis.plot_rl_figures.plot_from_file', 'plot_from_file', (['f"""{directory}{filename}"""'], {'show_subplots': '(False)'}), "(f'{directory}{filename}', show_subplots=False)\n", (921, 968), False, 'from vis.plot_rl_figures import plot_from_file\n'), ((1286, 1452), 'matplotlib.pyplot.plot', 'plt.plot', (["agg_dict['time'][i][ignore_transients:]", "agg_dict['performances'][i][ignore_transients:]"], {'label': '"""instantaenous performance"""', 'color': '[0, 0, 0.5, 0.1]'}), "(agg_dict['time'][i][ignore_transients:], agg_dict['performances'][\n i][ignore_transients:], label='instantaenous performance', color=[0, 0,\n 0.5, 0.1])\n", (1294, 1452), True, 'import matplotlib.pyplot as plt\n'), ((1826, 1916), 'matplotlib.pyplot.plot', 'plt.plot', (["agg_dict['time'][0][ignore_transients:]", 'avg[ignore_transients:]'], {'label': 'perf'}), "(agg_dict['time'][0][ignore_transients:], avg[ignore_transients:],\n label=perf)\n", (1834, 1916), True, 'import matplotlib.pyplot as plt\n'), ((1923, 2062), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (["agg_dict['time'][0][ignore_transients:]", '(avg - err)[ignore_transients:]', '(avg + err)[ignore_transients:]'], {'alpha': '(0.2)'}), "(agg_dict['time'][0][ignore_transients:], (avg - err)[\n ignore_transients:], (avg + err)[ignore_transients:], alpha=0.2)\n", (1939, 2062), True, 'import matplotlib.pyplot as plt\n'), ((2062, 2080), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (2072, 2080), True, 'import matplotlib.pyplot as plt\n'), ((2089, 2105), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['perf'], {}), '(perf)\n', (2099, 2105), True, 'import matplotlib.pyplot as plt\n'), ((2114, 2153), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{save_folder}{perf}.png"""'], {}), "(f'{save_folder}{perf}.png')\n", (2125, 2153), True, 'import matplotlib.pyplot as plt\n'), ((2162, 2172), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2170, 2172), True, 'import matplotlib.pyplot as plt\n'), ((2565, 2575), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2573, 2575), True, 'import matplotlib.pyplot as plt\n'), ((1783, 1813), 'numpy.std', 'np.std', (['agg_dict[perf]'], {'axis': '(0)'}), '(agg_dict[perf], axis=0)\n', (1789, 1813), True, 'import numpy as np\n'), ((1622, 1653), 'numpy.mean', 'np.mean', (['agg_dict[perf]'], {'axis': '(0)'}), '(agg_dict[perf], axis=0)\n', (1629, 1653), True, 'import numpy as np\n'), ((2300, 2338), 'numpy.mean', 'np.mean', (["agg_dict[f'w{i}_{j}']"], {'axis': '(0)'}), "(agg_dict[f'w{i}_{j}'], axis=0)\n", (2307, 2338), True, 'import numpy as np\n'), ((2360, 2397), 'numpy.std', 'np.std', (["agg_dict[f'w{i}_{j}']"], {'axis': '(0)'}), "(agg_dict[f'w{i}_{j}'], axis=0)\n", (2366, 2397), True, 'import numpy as np\n'), ((2415, 2472), 'matplotlib.pyplot.plot', 'plt.plot', (["agg_dict['time'][0]", 'avg'], {'label': 'f"""avg w{i}_{j}"""'}), "(agg_dict['time'][0], avg, label=f'avg w{i}_{j}')\n", (2423, 2472), True, 'import matplotlib.pyplot as plt\n'), ((2490, 2560), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (["agg_dict['time'][0]", '(avg - err)', '(avg + err)'], {'alpha': '(0.2)'}), "(agg_dict['time'][0], avg - err, avg + err, alpha=0.2)\n", (2506, 2560), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 16 09:27:20 2021
@author: <NAME>
"""
import json
import multiprocessing
import pathlib
import numpy as np
import pandas as pd
import plottery
class Hero():
"""Baseclass for characters from the rpg `Das Shwarze Auge` (DSA).
This class is motivated by the need for automatic evaluation of test,
which is executed via the roll of three dices with twenty faces. This
independent random vector of three components must be lower than the
heros values in the corresponding attributes. See official rules at
https://ulisses-regelwiki.de/index.php/GR_Proben.html
Basic funtionality
------------------
>>> from held import Held
>>> mary = Held('<NAME>')
==-> Nun Eigenschaften eingeben <-==
...
==-> Nun Fertigkeiten eingeben <-==
...
>>> print(mary.absoviere('Zechen', modifikator=-1))
<NAME> absolviert eine Probe auf Zechen (Fertigkeistwert 5), um 1
erschwert.
Eigenschaften:
Klugheit - Konstitution - Körperkraft
Zielwerte:
[12 11 12]
Würfelergebnis:
[3 2 9]
Ergebnis: Erfolg mit 2 Qualitätsstufen
Parameters
----------
name : str
Name of the hero.
attribute_values : list, optional
List of integer with lenght 8, representing the values for the
attributes. Are asked in command line dialogue if not specified.
The default is [].
skill_values : list, optional
List of integer with length 59, representing the values for the
skills/talents. Are asked in command line dialogue if not
specified.
The default is [].
incompetences : list or set or None, optional
String representation of incompetent skills/talents.
The default is None.
gifted : list or set or None, optional
String representation of gifted skills or spell-likes.
The default is None.
Raises
------
TypeError
Raised when `incompetences` or `gifted` are not given as set, list
or None.
"""
SKILL_CHECKS = {
'Fliegen': ('Mut', 'Intuition', 'Gewandtheit'),
'Gaukeleien': ('Mut', 'Charisma', 'Fingerfertigkeit'),
'Klettern': ('Mut', 'Gewandtheit', 'Körperkraft'),
'Körperbeherrschung': ('Gewandtheit', 'Gewandtheit', 'Konstitution'),
'Kraftakt': ('Konstitution', 'Körperkraft', 'Körperkraft'),
'Reiten': ('Charisma', 'Gewandtheit', 'Körperkraft'),
'Schwimmen': ('Gewandtheit', 'Konstitution', 'Körperkraft'),
'Selbstbeherrschung': ('Mut', 'Mut', 'Konstitution'),
'Singen': ('Klugheit', 'Charisma', 'Konstitution'),
'Sinnesschärfe': ('Klugheit', 'Intuition', 'Intuition'),
'Tanzen': ('Klugheit', 'Charisma', 'Gewandtheit'),
'Taschendiebstahl': ('Mut', 'Fingerfertigkeit', 'Gewandtheit'),
'Verbergen': ('Mut', 'Intuition', 'Gewandtheit'),
'Zechen': ('Klugheit', 'Konstitution', 'Körperkraft'),
'Bekehren & Überzeugen': ('Mut', 'Klugheit', 'Charisma'),
'Betören': ('Mut', 'Charisma', 'Charisma'),
'Einschüchtern': ('Mut', 'Intuition', 'Charisma'),
'Etikette': ('Klugheit', 'Intuition', 'Charisma'),
'Gassenwissen': ('Klugheit', 'Intuition', 'Charisma'),
'Menschenkenntnis': ('Klugheit', 'Intuition', 'Charisma'),
'Überreden': ('Mut', 'Intuition', 'Charisma'),
'Verkleiden': ('Intuition', 'Charisma', 'Gewandtheit'),
'Willenskraft': ('Mut', 'Intuition', 'Charisma'),
'Fährtensuchen': ('Mut', 'Intuition', 'Gewandtheit'),
'Fesseln': ('Klugheit', 'Fingerfertigkeit', 'Körperkraft'),
'Fischen & Angeln': ('Fingerfertigkeit', 'Gewandtheit',
'Konstitution'),
'Orientierung': ('Klugheit', 'Intuition', 'Intuition'),
'Pflanzenkunde': ('Klugheit', 'Fingerfertigkeit', 'Konstitution'),
'Tierkunde': ('Mut', 'Mut', 'Charisma'),
'Wildnisleben': ('Mut', 'Gewandtheit', 'Konstitution'),
'Brett- & Glücksspiel': ('Klugheit', 'Klugheit', 'Intuition'),
'Geographie': ('Klugheit', 'Klugheit', 'Intuition'),
'Geschichtswissen': ('Klugheit', 'Klugheit', 'Intuition'),
'Götter & Kulte': ('Klugheit', 'Klugheit', 'Intuition'),
'Kriegskunst': ('Mut', 'Klugheit', 'Intuition'),
'Magiekunde': ('Klugheit', 'Klugheit', 'Intuition'),
'Mechanik': ('Klugheit', 'Klugheit', 'Fingerfertigkeit'),
'Rechnen': ('Klugheit', 'Klugheit', 'Intuition'),
'Rechtskunde': ('Klugheit', 'Klugheit', 'Intuition'),
'Sagen & Legenden': ('Klugheit', 'Klugheit', 'Intuition'),
'Sphärenkunde': ('Klugheit', 'Klugheit', 'Intuition'),
'Sternkunde': ('Klugheit', 'Klugheit', 'Intuition'),
'Alchimie': ('Mut', 'Klugheit', 'Fingerfertigkeit'),
'Boote & Schiffe': ('Fingerfertigkeit', 'Gewandtheit', 'Körperkraft'),
'Fahrzeuge': ('Charisma', 'Fingerfertigkeit', 'Konstitution'),
'Handel': ('Klugheit', 'Intuition', 'Charisma'),
'Heilkunde Gift': ('Mut', 'Klugheit', 'Intuition'),
'Heilkunde Krankheiten': ('Mut', 'Intuition', 'Konstitution'),
'Heilkunde Seele': ('Intuition', 'Charisma', 'Konstitution'),
'Heilkunde Wunden': ('Klugheit', 'Fingerfertigkeit',
'Fingerfertigkeit'),
'Holzbearbeitung': ('Fingerfertigkeit', 'Gewandtheit', 'Körperkraft'),
'Lebensmittelbearbeitung': ('Intuition', 'Fingerfertigkeit',
'Fingerfertigkeit'),
'Lederbearbeitung': ('Fingerfertigkeit', 'Gewandtheit',
'Konstitution'),
'Malen & Zeichen': ('Intuition', 'Fingerfertigkeit',
'Fingerfertigkeit'),
'Metallbearbeitung': ('Fingerfertigkeit', 'Konstitution',
'Körperkraft'),
'Musizieren': ('Charisma', 'Fingerfertigkeit', 'Konstitution'),
'Schlösserknacken': ('Intuition', 'Fingerfertigkeit',
'Fingerfertigkeit'),
'Steinbearbeitung': ('Fingerfertigkeit', 'Fingerfertigkeit',
'Körperkraft'),
'Stoffbearbeitung': ('Klugheit', 'Fingerfertigkeit',
'Fingerfertigkeit')
}
def __init__(self, name, attribute_values=[], skill_values=[],
incompetences=None, gifted=None):
self.name = name
self._attributes = dict.fromkeys(
['Mut', 'Klugheit', 'Intuition', 'Charisma', 'Fingerfertigkeit',
'Gewandtheit', 'Konstitution', 'Körperkraft'])
self._skills = dict.fromkeys(
list(self.SKILL_CHECKS.keys()))
if len(attribute_values) != len(self._attributes):
# User Interaction
print('==-> Nun Eigenschaften eingeben <-==')
attribute_values = self.__ask_for_values(self._attributes, (1, 25))
if all([1 <= val <= 25 for val in attribute_values]):
# check given list of values
self._attributes = {
list(self._attributes.keys())[i]: attribute_values[i]
for i in range(len(attribute_values))}
else:
raise ValueError('Werte für Eigenschaften müssen'
' im Bereich von 1 bis 25 liegen.')
if len(skill_values) != len(self._skills):
print('==-> Nun Fertigkeiten eingeben <-==')
skill_values = self.__ask_for_values(self._skills, (0, 25))
if all([0 <= val <= 25 for val in skill_values]):
self._skills = {
list(self._skills.keys())[i]: skill_values[i]
for i in range(len(skill_values))}
else:
raise ValueError('Werte für Talente müssen im '
'Bereich von 0 bis 25 liegen.')
if incompetences is None:
self._incompetences = set()
else:
if isinstance(incompetences, set):
self._incompetences = incompetences
elif isinstance(incompetences, list):
self._incompetences = set(incompetences)
else:
raise TypeError('`incompetences` is expected '
'as set or list.')
if gifted is None:
self._gifted = set()
else:
if isinstance(gifted, set):
self._gifted = gifted
elif isinstance(gifted, list):
self._gifted = set(gifted)
else:
raise TypeError('`gifted` is expected as list.')
@classmethod
def load(cls, character,
directory=pathlib.Path.cwd()):
"""Load character from harddrive and returns corresponding Hero object.
Parameters
----------
character : str
Name of the character to be loaded. Althogh underscore style is
used in file naming, the intended name may be used.
directory : str, optional
Specifies directory to load <name>.json from.
The default is pathlib.Path.cwd(), i.e. current work directory.
Raises
------
ValueError
Raised when specified hero is not found in given directory.
Returns
-------
Hero
Initiated hero.
"""
final_file = pathlib.Path(directory,
(character + '.json').replace(' ', '_'))
if final_file.exists() and final_file.is_file():
with open(final_file, 'r') as source:
data = json.load(source)
return cls._from_json(name=character.replace('_', ' '),
stats=data)
else:
raise ValueError('Keine gültigen Daten gefunden.')
@classmethod
def _from_json(cls, name, stats):
"""Initate an instance of Held from given `name` and specified `stats`.
Since incompetences and gifted skills are optional, `stats` is checked
for those values, if they are not represented in the dict, they point
to `None`.
Parameters
----------
name : str
Used as name for initiated object of type Held.
stats : dict
Contain statistics to instantiate hero with all informations.
Must provide stats:'Eigenschaften' -> a=[int], with len(a)=8
and stats:'Fertigkeiten' -> b=[int], with len(b)=59;
may contain Values for 'incompetences' and 'gifted'.
Returns
-------
hero : Hero
Initiated hero.
"""
try:
incompetences = stats['Unfähigkeiten']
except KeyError:
incompetences = None
try:
gifted_talents = stats['Begabungen']
except KeyError:
gifted_talents = None
hero = cls(name,
list(stats['Eigenschaften'].values()),
list(stats['Fertigkeiten'].values()),
incompetences,
gifted_talents)
return hero
def execute(self, talent, modifier=-0):
"""Perform a test on a certin talent, w.r.t. skikll value and modifier.
Core functionality.
This method allow the execution of the dsa signature content: the
3D20 test. For more details see Held._perform_test or the official
rules at https://ulisses-regelwiki.de/index.php/GR_Proben.html
Parameters
----------
talent : str
State the talent/skill to be tested.
modifier : int, optional
Modification set to the test; negative values for a more difficult,
positve values for an easier test
The default is 0.
Returns
-------
str
Formatted result of the skill test.
"""
# estimate objectives for rolling
objective, impossible = self._estimae_objective(
talent=talent, modifier=modifier,
attribute_source=self.SKILL_CHECKS)
if impossible:
msg = (f'Die Erschwernis von {abs(modifier)} '
'macht diese Probe unmöglich.')
return msg
_3w20 = np.random.randint(1, 21, 3)
# Zufallsereignis auswerten
suc, crit, quality_level, quality_level_app = self._perform_test(
aim=objective, random_event=_3w20,
skill_level=self._skills[talent],
gifted=(talent in self._gifted),
incompetent=(talent in self._incompetences))
# Ausgabe bestimmen
out = self._format_outcome(
skill=talent,
goals=objective,
random_event=_3w20,
talent_level=self._skills,
talent_composition=self.SKILL_CHECKS,
success=suc,
crit=crit,
quality_level=(quality_level, quality_level_app),
modification=modifier)
return out
def analyze_talent(self, talent, modifier=0):
"""Visualize the probability of the stated test with plot and string.
Wrapper for `_analyze_success`, specifies the source for the
combination of attributes.
Parameters
----------
talent : str
State the talent/skill to be tested.
modifier : int, optional
Modification set to the test; negative values for a more difficult,
positve values for an easier test
The default is 0.
Returns
-------
str
Formatted describtion of quality level distribution for
specified talent/skill.
"""
return self._analyze_success(talent=talent,
attribute_source=self.SKILL_CHECKS,
skill_value_source=self._skills,
modifier=modifier)
def _analyze_success(self, talent,
attribute_source,
skill_value_source,
modifier=0):
"""Visualize the probability of the statet test with plot and string.
Parameters
----------
talent : str
State the talent/skill to be tested.
attribute_source : dict
Look up dictionary to determine attributes for intended analyzing
objective. Must contain `talent` as key and 3-string-tuple,
representing attributes, as values.
skill_value_source : dict
Look up dictionary to determine skill level (value) for intended
analyzing objective. Must contain `talent` as key and integer as
values.
modifier : int, optional
Modification set to the test; negative values for a more difficult,
positve values for an easier test
The default is 0.
Note
----
As sideeffect a matplotlib panel is displayed within a further process.
Returns
-------
str
Formatted describtion of quality level distribution for
specified talent/skill.
"""
# estimate objectives for rolling
objective, impossible = self._estimae_objective(
talent=talent, modifier=modifier,
attribute_source=attribute_source)
if impossible:
msg = (f'Die Erschwernis von {abs(modifier)} '
'macht diese Probe unmöglich.')
return msg
# generate table with all possible random events
table = self._n_cartesian_three(20, talent, attribute_source)
header = list(table.columns)
qualities = []
# estimate all possible random events
for index, row in table.iterrows():
_, _, quality_level, _ = self._perform_test(
aim=objective,
random_event=row.to_numpy(),
skill_level=skill_value_source[talent],
gifted=(talent in self._gifted),
incompetent=(talent in self._incompetences))
qualities.append(quality_level)
table['#QS'] = qualities
# begin plotting process
title = f'Verteilung der Qualitätsstufen von {talent}'
proc = multiprocessing.Process(
target=plottery.plot_cube_of_success,
args=(table, title,))
proc.start()
# begin describing probabilities
distribution = (f'Erfolgsaussichten für ein Probe auf {talent} mit '
f'Modifikator {modifier}:\n\n')
results = table.groupby('#QS').count().index
prob = table.groupby('#QS').count()[header[0]].to_numpy(dtype='float')
prob /= sum(prob)
expected_value = sum(results * prob)
# following string formating
delimiter = ' | '
upper = ' q ' + delimiter
lower = ' P(#QS=q)' + delimiter
for i in range(len(results)):
if results[i] < 10:
upper += (' ' + str(results[i]) + ' ' + delimiter)
else:
upper += (' ' + str(results[i]) + ' ' + delimiter)
lower += (
'{:5.2f}'.format(np.round(prob[i]*100, 2))
+ delimiter)
# correct last char
upper = upper[:-1]
lower = lower[:-1]
line = '-' * len(upper)
distribution += upper + '\n' + line + '\n' + lower + '\n'
distribution += ' '*len(line[:-3]) + '[in Prozent]'
distribution += f'\nErwartungswert: {expected_value:.2f}'
# phrase non-determenistic warning if analyzed talent is a special one
if talent in self._gifted or talent in self._incompetences:
if talent in self._gifted:
speciality = 'Begabung'
else:
speciality = 'Unfähigkeit'
warning = f'\n Achtung! Das Talent {talent} ist eine {speciality}'
warning += (', daher unterliegt die Wahrscheinlichkeitsverteilung'
' gewissen (vernachlässigbaren) Schwankungen. Durch '
'diesen Nichtdeterminismus begründet sich auch das '
'besondere Erscheinungsbild der Visualisierung.')
distribution += warning
return distribution
def update_special_abilities(self, also_permitted=[]):
"""Initiate command line dialogue to update gifted and incompetences.
After confirmation the corresponding sets are updated.
Parameters
----------
also_permitted : list, optional
List of strings representing additional legal skills for gifted
and incompetences. Enable derived classes to allow spell-likes as
gifted skills.
The default is [].
Raises
------
ValueError
Raised when user try to...
...set more than 3 gifted skills.
...set more than 2 incompetences.
...set the same skill as gifted and incompetence.
...choose a non legal option (typo, attributes, etc.)
Returns
-------
None.
"""
# Whether gifts shall be updated
val = self._clean_read(text='Begabungen aktualisieren?\n(j/n) ',
legal_response=['j', 'n'])
if val == 'j':
temp = self._show_and_update_set(
f'{self.name}\'s Begabungen:',
self._gifted)
if len(temp) > 3:
raise ValueError('Nicht mehr als 3 Begabungen erlaubt.')
for t in temp:
in_skills = t in self.SKILL_CHECKS.keys()
in_further_skills = t in also_permitted
if not in_skills and not in_further_skills:
raise ValueError(f'{t} ist keine zulässige Fertigkeit.')
if temp.isdisjoint(self._incompetences):
self._gifted = temp
else:
raise ValueError('Begabungen und Unfähigkeiten'
' dürfen sich nicht überlappen.')
# whether inability shall be updated
val = self._clean_read(text='Unfähigkeiten aktualisieren?\n(j/n) ',
legal_response=['j', 'n'])
if val == 'j':
temp = self._show_and_update_set(
f'{self.name}\'s Unfähigkeiten:',
self._incompetences)
if len(temp) > 2:
raise ValueError('Nicht mehr als 2 Unfähigkeiten erlaubt.')
for t in temp:
if t not in self.SKILL_CHECKS.keys():
raise ValueError('{t} ist keine zulässige Fertigkeit.')
if temp.isdisjoint(self._gifted):
self._incompetences = temp
else:
raise ValueError('Begabungen und Unfähigkeiten'
' dürfen sich nicht überlappen.')
val = self._clean_read(
text='Weitere Aktualisierungen vornehmen?\n(j/n) ',
legal_response=['j', 'n'])
# whether more updates shall be happen
if val == 'j':
self.update_special_abilities(
also_permitted=also_permitted)
def save(self, directory=pathlib.Path.cwd()):
"""Store character describing dictionaries as json on harddrive.
File is written as <name>.json, whereby spaces are removed.
Parameters
----------
directory : str, optional
Directory to store the char.
The default is directory=pathlib.Path.cwd(), i.e. current work
directory.
Raises
------
OSError
Raised in cases of problems concerning writing permissions or
errors in specified path.
Returns
-------
None.
"""
directory = pathlib.Path(directory)
if directory.exists() and directory.is_dir():
file = '{}.json'.format(self.name.replace(' ', '_'))
data_to_dump = {'Eigenschaften': self._attributes,
'Fertigkeiten': self._skills,
'Begabungen': list(self._gifted),
'Unfähigkeiten': list(self._incompetences)}
with open(pathlib.Path(directory, file),
'w') as file:
json.dump(data_to_dump, file)
else:
raise OSError('Mit gültigem Pfad erneut versuchen.'
' Eventuell Schreibrechte überprüfen.')
def test(self, attribute, modifikator=0):
"""Perform an attribute check, meaning a 1D20 roll.
Parameters
----------
attribute : str
Attribute to be checked.
modifikator : int, optional
Modification set to the test; negative values for a more difficult,
positve values for an easier test
The default is 0.
Returns
-------
msg : str
Formatted result of the attribute check.
"""
assert attribute in self._attributes.keys(),\
'{} ist keine gültige Eigenschaft.'.format(attribute)
eigenschaftswert_mod = min(
self._attributes[attribute] + modifikator, 19)
_1w20 = np.random.randint(1, 21, 1)
suc, _, _, _ = self._perform_test(
aim=np.array(eigenschaftswert_mod),
random_event=_1w20)
msg = f'{self.name} testet {attribute} ({self._attributes[attribute]})'
if modifikator == 0:
msg += ':\n'
elif modifikator > 0:
msg += f', erleichtert um {abs(modifikator)}:\n'
elif modifikator < 0:
msg += f', erschwert um {abs(modifikator)}:\n'
if suc:
msg += '\nGeschafft mit einem Wurf von {}.'.format(*_1w20)
else:
msg += '\nNicht geschafft mit einem Wurf von {}.'.format(*_1w20)
return msg
def show_special_abilities(self):
"""Show talents which are marked as gifted or incompetent.
Returns
-------
out : str
Formatted representation.
"""
msg_1 = f'{self.name}\'s Begabungen:'
line = '='*len(msg_1)
msg_1 += f'\n{line}\n\t'
for t in self._gifted:
msg_1 += f'{t} '
msg_2 = f'{self.name}\'s Unfähigkeiten:'
line = '='*len(msg_2)
msg_2 += f'\n{line}\n\t'
for u in self._incompetences:
msg_2 += f'{u} '
out = msg_1 + '\n' + msg_2
return out
def show_attributes(self):
"""Show attributes and values.
Returns
-------
str
Formatted representation.
"""
return self._show_pretty_dicts(
f'{self.name}\'s Eigenschaften:', self._attributes)
def show_skills(self):
"""Show skills and values.
Returns
-------
str
Formatted representation.
"""
return self._show_pretty_dicts(
f'{self.name}\'s Fertigkeiten:', self._skills)
def update_attribute(self, attribute: str, by=1):
"""Update attribute value by given integer.
Parameters
----------
attribute : str
Attribute to update.
by : int, optional
Value for additive manipulation.
The default is 1.
Raises
------
ValueError
Iff updated attribute value would violent legal limits.
KeyError
Iff argument `attribute` is not among the attributes.
Returns
-------
None.
"""
assert isinstance(by, int),\
'Entwicklungsdiffernez muss als ganze Zahl gegeben sein.'
try:
old_val = self._attributes[attribute]
new_val = old_val + by
if 1 <= new_val <= 25:
msg = (f'Attribut {attribute} von {old_val} auf {new_val} '
'setzen?\n(j/n) ')
res = self._clean_read(msg, legal_response=['j', 'n'])
if res == 'j':
self._attributes[attribute] = new_val
print('Wert angepasst.')
else:
print('Keine Änderungen vorgenommen.')
else:
raise ValueError('Entwickelter Wert muss im '
'Bereich 1 bis 25 liegen.')
except KeyError:
raise KeyError(f'{attribute} ist kein gültiges Attribut.')
def update_talent(self, talent: str, by=1):
"""Update talent value by given integer.
Parameters
----------
talent : str
Talent/skill to update.
by : int, optional
Value for additive manipulation.
The default is 1.
Raises
------
ValueError
Iff updated skill value would violent legal limits.
KeyError
Iff argument `talent` is not among the talents/skills.
Returns
-------
None.
"""
assert isinstance(by, int),\
'Entwicklungsdiffernez muss als ganze Zahl gegeben sein.'
try:
old_val = self._skills[talent]
new_val = old_val + by
if 0 <= new_val <= 25:
msg = \
(f'Fertigkeitswert von {talent} von {old_val} auf '
f'{new_val} setzen?\n(j/n) ')
res = self._clean_read(msg, legal_response=['j', 'n'])
if res == 'j':
self._skills[talent] = new_val
print('Wert angepasst.')
else:
print('Keine Änderungen vorgenommen.')
else:
raise ValueError('Entwickelter Wert muss im '
'Bereich 0 bis 25 liegen.')
except KeyError:
raise KeyError(f'{talent} ist kein gültiges Talent.')
@classmethod
def get_all_skills_gui(cls):
"""Getter for skills; concerning GUI.
Returns
-------
skill_set : list
List of strings representing all skills.
"""
skill_set = []
for skill in cls.SKILL_CHECKS.keys():
skill_set.append(cls._tamper_designation(skill))
return skill_set
def get_gifted_skills_gui(self):
"""Getter for gifted skills(`Begabungen`); concerning GUI.
Returns
-------
gifted_skills : list
List of strings representing the heros' gifted skills.
"""
gifted_skills = []
for skill in self._gifted:
gifted_skills.append(self._tamper_designation(skill))
return gifted_skills
def get_incompetent_skills_gui(self):
"""Getter for incompetences(`Unfähigkeiten`); concerning GUI.
Returns
-------
incompetent_skills : list
List of strings representing the heros' incompetences.
"""
incompetent_skills = []
for skill in self._incompetences:
incompetent_skills.append(self._tamper_designation(skill))
return incompetent_skills
def _estimae_objective(self, talent, modifier, attribute_source):
"""Derives objective for random event for a test on talent.
Each talent correspond to three attributes, which values make up the
objective to roll against (random event). These values may be modified
on DM decision, marked by modfier. Each value is lower or equal to 19.
If any value is lower than one, the test is considered as impossible.
Parameters
----------
talent : str
skill or spell like to be tested.
modifier : int
Alleviation (positive Values) or difficulty on objective.
attribute_source : dict
Source to look up attributes for the test of talent. Therefore
`talent` must be among `attribute_source.keys()`.
Raises
------
ValueError
Raised when specified talent is not legal, i.e. is not a key in
specified `attribute_source`.
Returns
-------
objective : numpy.ndarry
Estimated objective for test.
impossible : bool
Iff any objective value is lower than one after considering the
modifier.
"""
try:
objective = np.array(
[self._attributes[eig]
for eig in attribute_source[talent]])
add_cap_19 = np.vectorize(
lambda x: min(19, x + modifier)
)
objective = add_cap_19(objective)
except KeyError:
raise ValueError('{} ist keine'
' gültige Fertigkeit.'.format(talent))
if any(objective < 1): # detect impossible tests
impossible = True
else:
impossible = False
return objective, impossible
def _format_outcome(self, skill: str, goals, random_event,
talent_level: dict,
talent_composition: dict,
success: bool, crit: bool, quality_level: (int, int),
kind_of_test='absolviert eine Probe auf',
modification=0):
"""Summarize the results of a (3D20) roll with all necessary values.
Parameters
----------
skill : str
Talent which was tested.
goals : numpy.ndarry
Values to achieve lower rolls.
random_event : numpy.ndarray
Representing the roll.
talent_level : dict
Must contain `skill` as key.
talent_composition : dict
Must contain `skill` as key.
success : bool
Iff test was passed.
crit : bool
Iff test was passed outstanding (success or fail).
quality_level : int
Measurement of success (if accomplished).
kind_of_test : str, optional
Allows to formate also spell-likes from derived classes.
The default is 'absolviert eine Probe auf'.
modification : int, optional
Modification set to the test; negative values for a more difficult,
positve values for an easier test
The default is 0.
Returns
-------
out : str
Summarized information.
"""
out = ''
if modification == 0:
test = '{} {} {} (Fertigkeitswert {}).'
else:
if modification < 0:
test = '{} {} {} (Fertigkeitswert {}), um ' +\
str(abs(modification)) + ' erschwert.'
else:
test = '{} {} {} (Fertigkeitswert {}), um ' +\
str(abs(modification)) + ' erleichtert.'
out += test.format(self.name, kind_of_test, skill,
talent_level[skill])
goal_to_aim = ('\nEigenschaften:\n\t{} - {} -'
' {}\nZielwerte:\n\t{}').format(
*talent_composition[skill], goals)
out += '\n' + goal_to_aim
outcome_rng = 'Würfelergebnis:\n\t{}\n'.format(random_event)
out += '\n' + outcome_rng
if skill in self._gifted:
kind_of_result = 'Ergebnis der Begabung'
elif skill in self._incompetences:
kind_of_result = 'Ergebnis der Unfähigkeit'
else:
kind_of_result = 'Ergebnis'
if success:
if crit:
final_result = ('{}:\nKritischer Erfolg mit {} ({})'
'Qualitätsstufen.\t:-D'.format(
kind_of_result,
quality_level[0],
quality_level[1]))
else:
final_result = ('{}:\nErfolg mit '
'{} ({}) Qualitätsstufen.'.format(
kind_of_result,
quality_level[0],
quality_level[1]))
else:
if crit:
final_result = '{}:\nPatzer\t>:-|'.format(kind_of_result)
else:
final_result = ('{}:\nFehlschlag ({} QS)').format(
kind_of_result, quality_level[1])
out += '\n' + final_result
return out
@staticmethod
def _n_cartesian_three(n: int, skill: str,
attribute_source: dict):
"""Generate DataFrame with n**3 rows, corresponding to attributes.
Parameters
----------
n : int
One to n describes the base set for cartesian product.
skill : str
Designate talent. Must be among keys from attribute_source.
attribute_source : dict
Look up dictionary to determine attributes for given skill.
Returns
-------
out : pandas.DataFrame
DESCRIPTION.
"""
base = list(range(1, n+1))
third = base * (n**2)
second = []
first = []
for e in base:
second += [e]*n
first += [e]*(n**2)
second = second * n
'[1] ' + attribute_source[skill][0]
out = pd.DataFrame({
'[1] ' + attribute_source[skill][0]: first,
'[2] ' + attribute_source[skill][1]: second,
'[3] ' + attribute_source[skill][2]: third})
return out
def _perform_test(self, aim, random_event, skill_level=0,
gifted=False, incompetent=False):
"""Evalutae the performance of random event and measure the success.
Core functionality of this class, evaluate the signature content from
DSA: the 3D20 test. All rolls that surpass the corresponding value in
`aim` must be compensated with `skill_level`. If this is possible, the
test is consierd as success.
See https://ulisses-regelwiki.de/index.php/GR_Proben.html for more
information.
Special cases: If `random_event` contain more than one ones or
twenties, the test is accomplished with a critical result and the test
is passed (ones) or failed (twenty) independet from the spare points
from `skill_level`.
May also be used for nDm-test against a target value `aim`, as long as
`skill_level` equals zero.
Parameters
----------
aim : numpy.ndarray
Target values (integer) to fall below. Must match the length of
`random_event`.
random_event : numpy.ndarray
Roll to be evaluated if (and how good) accomplished. Must match the
length of `aim`.
skill_level : int, optional
Number of points to compensate high rolls.
The default is 0.
gifted : bool, optional
Random event is preprocessed: The highest roll will be rerolled and
the better (lower) event will be taken for further process.
See https://ulisses-regelwiki.de/index.php/V_Begabung.html
The default is False.
incompetent : bool, optional
Random event is preprocessed: The lowest (best) roll will be
rerolled and then taken for further process. Therefore
`random_event` actual may be improved.
See http://ulisses-gamereference.com/index.php/N_Unf%C3%A4hig.html
The default is False.
Raises
------
ValueError
Raised if `random_event` shall be preprocessed in both ways.
Returns
-------
success : bool
True iff test was accomplished.
critical : bool
True iff result is outstanding (either success or failure).
quality_level : int
Measurement of success.
"""
if gifted and incompetent:
raise ValueError('A test can not be taken on a talent, which'
' is considered gifted an incompetent at the'
' same time.')
if incompetent: # estimate and execute reroll of imcompetence
idx = np.argmin(random_event)
random_event[idx] = np.random.randint(1, 21)
compensation = random_event - aim
compensation[compensation < 0] = 0
if gifted: # estimate reroll for gifted skills
idx = np.argmax(compensation)
reroll = np.random.randint(1, 21)
better_roll = min(random_event[idx], reroll)
random_event[idx] = better_roll
# recursive call with updated rand toggled gifted flag
return self._perform_test(aim=aim, random_event=random_event,
skill_level=skill_level,
gifted=False)
spare = skill_level - sum(compensation)
# concerning `field of application` rule:
spare_application = spare + 2
fail_copy = random_event.copy()
fail_copy[fail_copy != 20] = 0
crit_fail = sum(fail_copy) > 20
win_copy = random_event.copy()
win_copy[win_copy != 1] = 0
crit_win = sum(win_copy) > 1
success = ((spare >= 0) or crit_win) and not crit_fail
critical = crit_win or crit_fail
if crit_win:
spare = max(spare, 0)
quality_level = self.__determine_quality_level(spare)
quality_level *= 2
quality_level_application = self.__determine_quality_level(
spare_application)
quality_level_application *= 2
elif crit_fail:
quality_level = 0
quality_level_application = 0
else:
quality_level = self.__determine_quality_level(spare)
quality_level_application = self.__determine_quality_level(
spare_application)
return success, critical, quality_level, quality_level_application
def _show_and_update_set(self, title, group):
"""Initate command line dialogue (german) to update given set.
User get `group` displayed and asked for an element to update. If the
given input is already in `group`, it will be removed from that set,
else the given input is added to the set. In both cases a confirmation
is asked for.
Parameters
----------
title : str
Is displayed to user before `group` is shown.
group : set
Set to be updated.
Returns
-------
group : set
Updated copy of `group`.
"""
group = group.copy()
print('{}\n{}'.format(title, '='*len(title)))
print(group)
val = input('Aktualisiere um Element: ')
if val in group:
confirm = self._clean_read('{} entfernen?\n(j/n) '.format(val),
['j', 'n'])
if confirm == 'j':
group.discard(val)
else:
confirm = self._clean_read('{} hinzufügen?\n(j/n) '.format(val),
['j', 'n'])
if confirm == 'j':
group.add(val)
return group
def _show_pretty_dicts(self, title, dictionary, alphabetical_order=True,
depth=1):
"""Formate dictionary to pleasant readable string.
Parameters
----------
title : str
Prefix and first line of formulated string.
dictionary : dict
Dictionary to display.
alphabetical_order : bool, optional
True <=> key-value-pairs are shown in the keys alphabetical order.
The default is True.
depth : int, optional
Used for nested dictionaries. Regulate underlines and indentation.
The default is 1.
Returns
-------
msg : str
Pretty print version of dictionary.
"""
gifted = ' (+)'
incomp = ' (-)'
msg = ''
list_of_keys = list(dictionary.keys())
if alphabetical_order:
list_of_keys.sort()
if depth == 1:
underline = '\n' + '=' * len(title)
elif depth == 2:
underline = '\n' + '-' * len(title)
else:
underline = ''
msg += ('\n' + title + underline)
for key in list_of_keys:
if isinstance(dictionary[key], dict):
value = str(self._show_pretty_dicts(
title=key,
dictionary=dictionary[key],
depth=depth+1))
msg += ('\t'*depth + value)
else:
value = str(dictionary[key])
if key in self._incompetences:
msg += ('\n' + key + incomp + ':\n' + '\t'*depth + value)
elif key in self._gifted:
msg += ('\n' + key + gifted + ':\n' + '\t'*depth + value)
else:
msg += ('\n' + key + ':\n' + '\t'*depth + value)
return msg
@staticmethod
def _clean_read(text, legal_response):
"""Helperfunction for command line interaction.
Parameters
----------
text : str
Message to display user in console.
legal_response : list
List of legal responses. Input is rejected iff it does not occure
in this list.
Returns
-------
val : str
Legal user response on displayed message.
"""
clean_read = False
while not clean_read:
val = input(text)
if val in legal_response:
clean_read = True
return val
@staticmethod
def _tamper_designation(skill):
"""Transform a given string for GUI concerns.
In general the given string is changed to lower cases and umlauts are
replaced. If the given `skill` corresponds to one of the formulated
special cases, then the special transformation is applied.
Parameters
----------
skill : str
String to transform, expected to be a skill (`Fertikeit`) or
identifier of a spell-like (from derived Funzel).
Returns
-------
out : str
Transformed string.
"""
special_cases = {'Bekehren & Überzeugen': 'bekehren',
'Fischen & Angeln': 'angeln',
'Brett- & Glücksspiel': 'brettspiel',
'Götter & Kulte': 'kulte',
'Sagen & Legenden': 'sagen',
'Boote & Schiffe': 'boote',
'Heilkunde Gift': 'heilenGift',
'Heilkunde Krankheiten': 'heilenKrankheit',
'Heilkunde Seele': 'heilenSeele',
'Heilkunde Wunden': 'heilenWunden',
'Fährtensuchen': 'faehrtensuche',
'Alchimie': 'alchemie',
'Malen & Zeichen': 'malen'}
if skill in special_cases.keys():
out = special_cases[skill]
else:
umlaute = {'ä': 'ae', 'ö': 'oe', 'ü': 'ue'}
out = skill.lower()
for u in umlaute:
out = out.replace(u, umlaute[u])
return out
@staticmethod
def __ask_for_values(dictionary, limits=(-float('inf'), float('inf'))):
"""Initaialize command line dialogue to determine dict's values.
Parameters
----------
dictionary : dict
Dictionary which values shall be determined by user.
limits : 2-tuple, optional
Set upper and lower limit for recieved values. Values which violent
these limits are rejected and the user is informed about the limits
and asked again for that value.
The default is (-float('inf'), float('inf')).
Returns
-------
values : list
List of integer values, corresponding to the order of the keys.
"""
values = []
for key in dictionary.keys():
clean_read = False
while not clean_read:
try:
val = int(input('Wert für {} eingeben:\t'.format(key)))
if val < limits[0] or limits[1] < val:
print(
'Achtung:\tWert muss sich in Bereich '
'von {} bis {} bewegen'.format(*limits))
else:
clean_read = True
except ValueError:
print('Achtung:\tWert muss als Integer lesbar sein.')
values.append(val)
return values
@staticmethod
def __determine_quality_level(spare_points):
"""Discretize the success from spare points to quality level.
In DSA the success of a test is measured in terms of spare points,
whereby the inital points represent the skill value. For comparrability
and further evaluation these points are discretize into quality level.
See https://ulisses-regelwiki.de/index.php/GR_Proben.html for more
informations.
Parameters
----------
spare_points : int
Amount of skill points, which were not used for comensation.
Returns
-------
quality_level : int
Measurement of success. 0 <=> input messed up.
"""
if 0 <= spare_points <= 3:
quality_level = 1
elif 4 <= spare_points <= 6:
quality_level = 2
elif 7 <= spare_points <= 9:
quality_level = 3
elif 10 <= spare_points <= 12:
quality_level = 4
elif 13 <= spare_points <= 15:
quality_level = 5
elif 16 <= spare_points:
quality_level = 6
else:
quality_level = 0
return quality_level
| [
"pandas.DataFrame",
"json.dump",
"json.load",
"numpy.argmax",
"numpy.argmin",
"pathlib.Path",
"numpy.random.randint",
"numpy.array",
"pathlib.Path.cwd",
"numpy.round",
"multiprocessing.Process"
] | [((8704, 8722), 'pathlib.Path.cwd', 'pathlib.Path.cwd', ([], {}), '()\n', (8720, 8722), False, 'import pathlib\n'), ((12286, 12313), 'numpy.random.randint', 'np.random.randint', (['(1)', '(21)', '(3)'], {}), '(1, 21, 3)\n', (12303, 12313), True, 'import numpy as np\n'), ((16335, 16421), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'plottery.plot_cube_of_success', 'args': '(table, title)'}), '(target=plottery.plot_cube_of_success, args=(table,\n title))\n', (16358, 16421), False, 'import multiprocessing\n'), ((21350, 21368), 'pathlib.Path.cwd', 'pathlib.Path.cwd', ([], {}), '()\n', (21366, 21368), False, 'import pathlib\n'), ((21964, 21987), 'pathlib.Path', 'pathlib.Path', (['directory'], {}), '(directory)\n', (21976, 21987), False, 'import pathlib\n'), ((23388, 23415), 'numpy.random.randint', 'np.random.randint', (['(1)', '(21)', '(1)'], {}), '(1, 21, 1)\n', (23405, 23415), True, 'import numpy as np\n'), ((35519, 35681), 'pandas.DataFrame', 'pd.DataFrame', (["{('[1] ' + attribute_source[skill][0]): first, ('[2] ' + attribute_source[\n skill][1]): second, ('[3] ' + attribute_source[skill][2]): third}"], {}), "({('[1] ' + attribute_source[skill][0]): first, ('[2] ' +\n attribute_source[skill][1]): second, ('[3] ' + attribute_source[skill][\n 2]): third})\n", (35531, 35681), True, 'import pandas as pd\n'), ((30581, 30650), 'numpy.array', 'np.array', (['[self._attributes[eig] for eig in attribute_source[talent]]'], {}), '([self._attributes[eig] for eig in attribute_source[talent]])\n', (30589, 30650), True, 'import numpy as np\n'), ((38448, 38471), 'numpy.argmin', 'np.argmin', (['random_event'], {}), '(random_event)\n', (38457, 38471), True, 'import numpy as np\n'), ((38504, 38528), 'numpy.random.randint', 'np.random.randint', (['(1)', '(21)'], {}), '(1, 21)\n', (38521, 38528), True, 'import numpy as np\n'), ((38714, 38737), 'numpy.argmax', 'np.argmax', (['compensation'], {}), '(compensation)\n', (38723, 38737), True, 'import numpy as np\n'), ((38759, 38783), 'numpy.random.randint', 'np.random.randint', (['(1)', '(21)'], {}), '(1, 21)\n', (38776, 38783), True, 'import numpy as np\n'), ((9635, 9652), 'json.load', 'json.load', (['source'], {}), '(source)\n', (9644, 9652), False, 'import json\n'), ((22467, 22496), 'json.dump', 'json.dump', (['data_to_dump', 'file'], {}), '(data_to_dump, file)\n', (22476, 22496), False, 'import json\n'), ((23476, 23506), 'numpy.array', 'np.array', (['eigenschaftswert_mod'], {}), '(eigenschaftswert_mod)\n', (23484, 23506), True, 'import numpy as np\n'), ((17269, 17295), 'numpy.round', 'np.round', (['(prob[i] * 100)', '(2)'], {}), '(prob[i] * 100, 2)\n', (17277, 17295), True, 'import numpy as np\n'), ((22384, 22413), 'pathlib.Path', 'pathlib.Path', (['directory', 'file'], {}), '(directory, file)\n', (22396, 22413), False, 'import pathlib\n')] |
""""
This script contains a set metrics used for evaluating the performance
of the models trained for the task of Singing Language Identification.
"""
import os
from itertools import product, cycle
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, precision_recall_curve, \
roc_curve, average_precision_score
from sklearn.preprocessing import label_binarize
from .utils import idx2lang, copy_file_to_gcs
colorCycle = cycle([
'aqua', 'xkcd:azure', 'beige', 'black', 'blue',
'chartreuse', 'chocolate', 'coral', 'xkcd:crimson', 'grey', 'darkblue',
'xkcd:fuchsia', 'gold', 'indigo', 'khaki', 'lightgreen', 'lightblue', 'lavender',
'olive', 'red', 'pink', 'orchid', 'plum', 'purple',
'tomato', 'teal', 'violet', 'wheat', 'yellow'
])
fig_titles = {
'cm': 'cm.png',
'multipr': 'multipr.png',
'iso-f1': 'iso-f1.png'
}
def compute_confusion_matrix(y_true, y_pred, classes):
"""
Computes the confusion matrix to evaluate the performance of a classifier.
Parameters
----------
y_true : list
The list of true labels
y_pred : list
The list of predicted labels
classes: list
The list of categories to which the labels can belong to
"""
y_pred = np.around(
np.clip(
y_pred,
a_min=np.min(classes),
a_max=np.max(classes)
)
)
cm = confusion_matrix(y_true, y_pred, labels=classes)
num_labels_vectorized = cm.sum(axis=1)[:, np.newaxis]
cm = np.divide(cm.astype('float'),
num_labels_vectorized)
return cm
def plot_confusion_matrix(y_true, y_pred, dict_classes, n_classes):
"""
Plots the confusion matrix.
Parameters
----------
y_true : list
The list of true labels
y_pred : list
The list of predicted labels
dict_classes: dict
The dict of categories to which the labels can belong to
n_classes: int
The number of possible categories
"""
classes = list(range(n_classes))
fig, ax = plt.subplots()
cm = compute_confusion_matrix(y_true, y_pred, classes)
im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
ax.set_title('Confusion matrix')
fig.colorbar(im, ax=ax)
# label the x axis ticks
ax.set_xticks(classes)
ax.set_xticklabels([dict_classes[c] for c in classes])
xticklabels = ax.get_xticklabels()
# rotate x axis ticks
for xtlabel in xticklabels:
xtlabel.set_rotation(45)
# label the y axis ticks
ax.set_yticks(classes)
ax.set_yticklabels([dict_classes[c] for c in classes])
# set the format of the cell values
fmt = '.2f'
thresh = cm.max() / 2.
for i, j in product(range(cm.shape[0]), range(cm.shape[1])):
ax.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
return fig
def save_confusion_matrix(
log_dir,
y_true,
y_pred,
dict_classes,
n_classes=len(idx2lang),
tmp_dir='/tmp/figures',
save=True
):
"""
Saves the confusion matrix as an image.
Parameters
----------
log_dir : str
The logging directory in the cloud
y_true : list
The list of true labels
y_pred : list
The list of predicted labels
dict_classes: dict
The dict of categories to which the labels can belong to
n_classes: int
The number of possible categories
tmp_dir : str
The local temporary directory where to store the image
save : bool
The option to just plot or plot and save the figure
"""
# plot and return confusion matrix figure
fig = plot_confusion_matrix(y_true, y_pred, dict_classes, n_classes)
# save figure
if save:
if not os.path.isdir(tmp_dir):
os.makedirs(tmp_dir)
fig.savefig(
os.path.join(tmp_dir, fig_titles['cm']),
dpi=600,
bbox_inches='tight'
)
copy_file_to_gcs(
path_source=os.path.join(tmp_dir, fig_titles['cm']),
path_dest=os.path.join(log_dir, fig_titles['cm']))
return fig
def multipr(y_true, y_pred, n_classes):
"""
Computes precision-recall curves.
Parameters
----------
y_true : list
The list of true labels
y_pred : list
The list of predicted labels
n_classes: int
The number of possible categories
"""
# convert labels to one-hot vectors
y_true = label_binarize(y_true, classes=range(n_classes))
y_pred = np.array(y_pred)
precision = dict()
recall = dict()
average_precision = dict()
# compute precision-recall values
for i in range(n_classes):
precision[i], recall[i], _ = precision_recall_curve(y_true[:, i],
y_pred[:, i])
average_precision[i] = average_precision_score(
y_true[:, i],
y_pred[:, i]
)
# micro-average quantifies score on all classes jointly
precision["micro"], recall["micro"], _ = precision_recall_curve(
y_true.ravel(),
y_pred.ravel()
)
average_precision["micro"] = average_precision_score(
y_true,
y_pred,
average="micro"
)
print('Average precision score, micro-averaged over all classes: {0:0.2f}'
.format(average_precision["micro"]))
return precision, recall, average_precision
def save_multipr(
log_dir,
precision,
recall,
average_precision,
tmp_dir,
save=True
):
"""
Saves precision-recall curves as images.
Parameters
----------
log_dir : str
The logging directory in the cloud
precision : dict
The dict of precision values
recall : dict
The dict of recall values
average_precision: dict
The dict of averaged precision values
tmp_dir : str
The local temporary directory where to store the image
save : bool
The option to just plot or plot and save the figure
"""
# create figure
fig, ax = plt.subplots()
step_kwargs = {'step': 'post'}
ax.step(recall['micro'], precision['micro'], color='b', alpha=0.2,
where='post')
ax.fill_between(recall["micro"], precision["micro"], alpha=0.2, color='b',
**step_kwargs)
# set figure title, axes labels and limits
ax.set_xlabel('Recall')
ax.set_ylabel('Precision')
ax.set_ylim([0.0, 1.05])
ax.set_xlim([0.0, 1.0])
ax.set_title(
'Average precision score, micro-averaged over all classes: AP={0:0.2f}'
.format(average_precision["micro"]))
# save figure
if save:
if not os.path.isdir(tmp_dir):
os.makedirs(tmp_dir)
fig.savefig(
os.path.join(tmp_dir, fig_titles['multipr']),
dpi=600,
bbox_inches='tight'
)
copy_file_to_gcs(
path_source=os.path.join(tmp_dir, fig_titles['multipr']),
path_dest=os.path.join(log_dir, fig_titles['multipr']))
return fig
def save_isof1(
log_dir,
precision,
recall,
average_precision,
n_classes,
tmp_dir,
save=True
):
"""
Computes and saves ISO-F1 curves as images.
Parameters
----------
log_dir : str
The logging directory in the cloud
precision : dict
The dict of precision values
recall : dict
The dict of recall values
average_precision: dict
The dict of averaged precision values
n_classes : int
The number of possible categories
tmp_dir : str
The local temporary directory where to store the image
save : bool
The option to just plot or plot and save the figure
"""
# create figure
fig, ax = plt.subplots(figsize=(7, 8))
f_scores = np.linspace(0.2, 0.8, num=4)
lines = []
labels = []
for f_score in f_scores:
x = np.linspace(0.01, 1)
y = f_score * x / (2 * x - f_score)
l, = ax.plot(x[y >= 0], y[y >= 0], color='gray', alpha=0.2)
ax.annotate('f1={0:0.1f}'.format(f_score), xy=(0.9, y[45] + 0.02))
lines.append(l)
labels.append('iso-f1 curves')
l, = ax.plot(recall["micro"], precision["micro"], color='gold', lw=2)
lines.append(l)
labels.append('micro-average Precision-recall (area = {0:0.2f})'
''.format(average_precision["micro"]))
for i, color in zip(range(n_classes), colorCycle):
l, = ax.plot(recall[i], precision[i], color=color, lw=2)
lines.append(l)
labels.append('Precision-recall for class {0} (area = {1:0.2f})'
''.format(idx2lang[i], average_precision[i]))
fig.subplots_adjust(bottom=0.25)
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('Recall')
ax.set_ylabel('Precision')
ax.set_title('Extension of Precision-Recall curve to multi-class')
ax.legend(lines, labels, loc=(0, -.38), prop=dict(size=10))
# save figure
if save:
if not os.path.isdir(tmp_dir):
os.makedirs(tmp_dir)
fig.savefig(
os.path.join(tmp_dir, fig_titles['iso-f1']),
dpi=600,
bbox_inches='tight'
)
copy_file_to_gcs(
path_source=os.path.join(tmp_dir, fig_titles['iso-f1']),
path_dest=os.path.join(log_dir, fig_titles['iso-f1']))
return fig
| [
"sklearn.metrics.confusion_matrix",
"sklearn.metrics.average_precision_score",
"os.makedirs",
"os.path.join",
"os.path.isdir",
"sklearn.metrics.precision_recall_curve",
"numpy.min",
"matplotlib.use",
"numpy.array",
"numpy.max",
"numpy.linspace",
"itertools.cycle",
"matplotlib.pyplot.subplots... | [((238, 259), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (252, 259), False, 'import matplotlib\n'), ((544, 868), 'itertools.cycle', 'cycle', (["['aqua', 'xkcd:azure', 'beige', 'black', 'blue', 'chartreuse', 'chocolate',\n 'coral', 'xkcd:crimson', 'grey', 'darkblue', 'xkcd:fuchsia', 'gold',\n 'indigo', 'khaki', 'lightgreen', 'lightblue', 'lavender', 'olive',\n 'red', 'pink', 'orchid', 'plum', 'purple', 'tomato', 'teal', 'violet',\n 'wheat', 'yellow']"], {}), "(['aqua', 'xkcd:azure', 'beige', 'black', 'blue', 'chartreuse',\n 'chocolate', 'coral', 'xkcd:crimson', 'grey', 'darkblue',\n 'xkcd:fuchsia', 'gold', 'indigo', 'khaki', 'lightgreen', 'lightblue',\n 'lavender', 'olive', 'red', 'pink', 'orchid', 'plum', 'purple',\n 'tomato', 'teal', 'violet', 'wheat', 'yellow'])\n", (549, 868), False, 'from itertools import product, cycle\n'), ((1529, 1577), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {'labels': 'classes'}), '(y_true, y_pred, labels=classes)\n', (1545, 1577), False, 'from sklearn.metrics import confusion_matrix, precision_recall_curve, roc_curve, average_precision_score\n'), ((2224, 2238), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2236, 2238), True, 'import matplotlib.pyplot as plt\n'), ((4989, 5005), 'numpy.array', 'np.array', (['y_pred'], {}), '(y_pred)\n', (4997, 5005), True, 'import numpy as np\n'), ((5631, 5687), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['y_true', 'y_pred'], {'average': '"""micro"""'}), "(y_true, y_pred, average='micro')\n", (5654, 5687), False, 'from sklearn.metrics import confusion_matrix, precision_recall_curve, roc_curve, average_precision_score\n'), ((6615, 6629), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (6627, 6629), True, 'import matplotlib.pyplot as plt\n'), ((8422, 8450), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(7, 8)'}), '(figsize=(7, 8))\n', (8434, 8450), True, 'import matplotlib.pyplot as plt\n'), ((8466, 8494), 'numpy.linspace', 'np.linspace', (['(0.2)', '(0.8)'], {'num': '(4)'}), '(0.2, 0.8, num=4)\n', (8477, 8494), True, 'import numpy as np\n'), ((5187, 5237), 'sklearn.metrics.precision_recall_curve', 'precision_recall_curve', (['y_true[:, i]', 'y_pred[:, i]'], {}), '(y_true[:, i], y_pred[:, i])\n', (5209, 5237), False, 'from sklearn.metrics import confusion_matrix, precision_recall_curve, roc_curve, average_precision_score\n'), ((5329, 5380), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['y_true[:, i]', 'y_pred[:, i]'], {}), '(y_true[:, i], y_pred[:, i])\n', (5352, 5380), False, 'from sklearn.metrics import confusion_matrix, precision_recall_curve, roc_curve, average_precision_score\n'), ((8567, 8587), 'numpy.linspace', 'np.linspace', (['(0.01)', '(1)'], {}), '(0.01, 1)\n', (8578, 8587), True, 'import numpy as np\n'), ((4184, 4206), 'os.path.isdir', 'os.path.isdir', (['tmp_dir'], {}), '(tmp_dir)\n', (4197, 4206), False, 'import os\n'), ((4220, 4240), 'os.makedirs', 'os.makedirs', (['tmp_dir'], {}), '(tmp_dir)\n', (4231, 4240), False, 'import os\n'), ((4274, 4313), 'os.path.join', 'os.path.join', (['tmp_dir', "fig_titles['cm']"], {}), "(tmp_dir, fig_titles['cm'])\n", (4286, 4313), False, 'import os\n'), ((7231, 7253), 'os.path.isdir', 'os.path.isdir', (['tmp_dir'], {}), '(tmp_dir)\n', (7244, 7253), False, 'import os\n'), ((7267, 7287), 'os.makedirs', 'os.makedirs', (['tmp_dir'], {}), '(tmp_dir)\n', (7278, 7287), False, 'import os\n'), ((7321, 7365), 'os.path.join', 'os.path.join', (['tmp_dir', "fig_titles['multipr']"], {}), "(tmp_dir, fig_titles['multipr'])\n", (7333, 7365), False, 'import os\n'), ((9673, 9695), 'os.path.isdir', 'os.path.isdir', (['tmp_dir'], {}), '(tmp_dir)\n', (9686, 9695), False, 'import os\n'), ((9709, 9729), 'os.makedirs', 'os.makedirs', (['tmp_dir'], {}), '(tmp_dir)\n', (9720, 9729), False, 'import os\n'), ((9763, 9806), 'os.path.join', 'os.path.join', (['tmp_dir', "fig_titles['iso-f1']"], {}), "(tmp_dir, fig_titles['iso-f1'])\n", (9775, 9806), False, 'import os\n'), ((1453, 1468), 'numpy.min', 'np.min', (['classes'], {}), '(classes)\n', (1459, 1468), True, 'import numpy as np\n'), ((1488, 1503), 'numpy.max', 'np.max', (['classes'], {}), '(classes)\n', (1494, 1503), True, 'import numpy as np\n'), ((4428, 4467), 'os.path.join', 'os.path.join', (['tmp_dir', "fig_titles['cm']"], {}), "(tmp_dir, fig_titles['cm'])\n", (4440, 4467), False, 'import os\n'), ((4491, 4530), 'os.path.join', 'os.path.join', (['log_dir', "fig_titles['cm']"], {}), "(log_dir, fig_titles['cm'])\n", (4503, 4530), False, 'import os\n'), ((7480, 7524), 'os.path.join', 'os.path.join', (['tmp_dir', "fig_titles['multipr']"], {}), "(tmp_dir, fig_titles['multipr'])\n", (7492, 7524), False, 'import os\n'), ((7548, 7592), 'os.path.join', 'os.path.join', (['log_dir', "fig_titles['multipr']"], {}), "(log_dir, fig_titles['multipr'])\n", (7560, 7592), False, 'import os\n'), ((9921, 9964), 'os.path.join', 'os.path.join', (['tmp_dir', "fig_titles['iso-f1']"], {}), "(tmp_dir, fig_titles['iso-f1'])\n", (9933, 9964), False, 'import os\n'), ((9988, 10031), 'os.path.join', 'os.path.join', (['log_dir', "fig_titles['iso-f1']"], {}), "(log_dir, fig_titles['iso-f1'])\n", (10000, 10031), False, 'import os\n')] |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
y_label = np.random.randint(0, 2, (100,))
y_pred = np.random.randint(0, 2, (100,))
precision_vs_recall = metrics.precision_recall_curve(y_label, y_pred)
metrics.accuracy_score()
print(precision_vs_recall) | [
"sklearn.metrics.precision_recall_curve",
"sklearn.metrics.accuracy_score",
"numpy.random.randint"
] | [((91, 122), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', '(100,)'], {}), '(0, 2, (100,))\n', (108, 122), True, 'import numpy as np\n'), ((132, 163), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', '(100,)'], {}), '(0, 2, (100,))\n', (149, 163), True, 'import numpy as np\n'), ((187, 234), 'sklearn.metrics.precision_recall_curve', 'metrics.precision_recall_curve', (['y_label', 'y_pred'], {}), '(y_label, y_pred)\n', (217, 234), False, 'from sklearn import metrics\n'), ((235, 259), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', ([], {}), '()\n', (257, 259), False, 'from sklearn import metrics\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 5 15:52:15 2021
Objective: Memory optimisation and preprocessing handy features
Reference: https://www.kaggle.com/shravankoninti/python-data-pre-processing-handy-tips
@author: Ashish
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# load data
df = pd.read_csv("../../data/kaggle_pimadiabetes.csv")
print(df.head())
print(df.dtypes)
memory = df.memory_usage()
print(memory)
print("Total Memory Usage = ",sum(memory))
# memory optimisation.
df.iloc[:,0:9] = df.iloc[:,0:9].astype('float16')
memory = df.memory_usage()
print(memory)
print("Total Memory Usage = ",sum(memory))
# check for outliers
fig, axs = plt.subplots()
sns.boxplot(data=df,orient='h',palette="Set2")
plt.show()
# dealing with outliers
q75, q25 = np.percentile(df["Insulin"], [75 ,25])
iqr = q75-q25
print("IQR",iqr)
whisker = q75 + (1.5*iqr)
print("Upper whisker",whisker)
df["Insulin"] = df["Insulin"].clip(upper=whisker)
fig, axs = plt.subplots()
sns.boxplot(data=df,orient='h',palette="Set2")
plt.show()
| [
"matplotlib.pyplot.show",
"pandas.read_csv",
"numpy.percentile",
"seaborn.boxplot",
"matplotlib.pyplot.subplots"
] | [((347, 396), 'pandas.read_csv', 'pd.read_csv', (['"""../../data/kaggle_pimadiabetes.csv"""'], {}), "('../../data/kaggle_pimadiabetes.csv')\n", (358, 396), True, 'import pandas as pd\n'), ((707, 721), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (719, 721), True, 'import matplotlib.pyplot as plt\n'), ((722, 770), 'seaborn.boxplot', 'sns.boxplot', ([], {'data': 'df', 'orient': '"""h"""', 'palette': '"""Set2"""'}), "(data=df, orient='h', palette='Set2')\n", (733, 770), True, 'import seaborn as sns\n'), ((769, 779), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (777, 779), True, 'import matplotlib.pyplot as plt\n'), ((816, 854), 'numpy.percentile', 'np.percentile', (["df['Insulin']", '[75, 25]'], {}), "(df['Insulin'], [75, 25])\n", (829, 854), True, 'import numpy as np\n'), ((1005, 1019), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1017, 1019), True, 'import matplotlib.pyplot as plt\n'), ((1020, 1068), 'seaborn.boxplot', 'sns.boxplot', ([], {'data': 'df', 'orient': '"""h"""', 'palette': '"""Set2"""'}), "(data=df, orient='h', palette='Set2')\n", (1031, 1068), True, 'import seaborn as sns\n'), ((1067, 1077), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1075, 1077), True, 'import matplotlib.pyplot as plt\n')] |
import scipy.io as scio
import numpy as np
from utils import channel_position
CHANNELS = ['Fz', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'C5', 'C3', 'C1', 'Cz', 'C2', 'C4', 'C6', 'CP3', 'CP1', 'CPz',
'CP2', 'CP4', 'P1', 'Pz', 'P2', 'POz']
INTERSECTION = ['Fz', 'FC3', 'FC1', 'FC2', 'FC4', 'C5', 'C3', 'C1', 'Cz', 'C2', 'C4', 'C6', 'CP3', 'CP1', 'CPz',
'CP2', 'CP4', 'P1', 'Pz', 'P2', 'POz']
def competition_iv_2a():
root = './data/BCICompetition-IV2a/'
p_train, p_test = root + 'train/', root + 'test/'
train, test = None, None
for sub in range(1, 10):
data_train = scio.loadmat(p_train + '{}.mat'.format(sub))
data_test = scio.loadmat(p_test + '{}.mat'.format(sub))
x1 = np.transpose(data_train.get('trainX'), (2, 1, 0))
x2 = np.transpose(data_test.get('testX'), (2, 1, 0))
x = np.vstack((x1, x2))[np.newaxis, :]
y1 = np.transpose(data_train.get('trainY'), (1, 0))
y2 = np.transpose(data_test.get('testY'), (1, 0))
y = np.vstack((y1, y2))[np.newaxis, :]
for i in range(y.shape[1]-1, 0, -1):
if (y[0][i][0] != 0) and (y[0][i][0] != 1):
x, y = np.delete(x, i, 1), np.delete(y, i, 1)
if train is None:
train = [x, y]
else:
train[0], train[1] = np.vstack((train[0], x)), np.vstack((train[1], y))
# Intersection channel
pos = channel_position(CHANNELS, INTERSECTION)
for i in range(pos.shape[0]-1, -1, -1):
if pos[i] == 0:
train[0] = np.delete(train[0], i, 2)
# Length cut from 1001 to 1000
train[0] = np.delete(train[0], 0, 3)
# Type: List[data, label]
# Dimension: data: Sub x Trial x Channel x Length
return train
# competition_iv_2a()
| [
"utils.channel_position",
"numpy.delete",
"numpy.vstack"
] | [((1422, 1462), 'utils.channel_position', 'channel_position', (['CHANNELS', 'INTERSECTION'], {}), '(CHANNELS, INTERSECTION)\n', (1438, 1462), False, 'from utils import channel_position\n'), ((1631, 1656), 'numpy.delete', 'np.delete', (['train[0]', '(0)', '(3)'], {}), '(train[0], 0, 3)\n', (1640, 1656), True, 'import numpy as np\n'), ((866, 885), 'numpy.vstack', 'np.vstack', (['(x1, x2)'], {}), '((x1, x2))\n', (875, 885), True, 'import numpy as np\n'), ((1032, 1051), 'numpy.vstack', 'np.vstack', (['(y1, y2)'], {}), '((y1, y2))\n', (1041, 1051), True, 'import numpy as np\n'), ((1554, 1579), 'numpy.delete', 'np.delete', (['train[0]', 'i', '(2)'], {}), '(train[0], i, 2)\n', (1563, 1579), True, 'import numpy as np\n'), ((1333, 1357), 'numpy.vstack', 'np.vstack', (['(train[0], x)'], {}), '((train[0], x))\n', (1342, 1357), True, 'import numpy as np\n'), ((1359, 1383), 'numpy.vstack', 'np.vstack', (['(train[1], y)'], {}), '((train[1], y))\n', (1368, 1383), True, 'import numpy as np\n'), ((1192, 1210), 'numpy.delete', 'np.delete', (['x', 'i', '(1)'], {}), '(x, i, 1)\n', (1201, 1210), True, 'import numpy as np\n'), ((1212, 1230), 'numpy.delete', 'np.delete', (['y', 'i', '(1)'], {}), '(y, i, 1)\n', (1221, 1230), True, 'import numpy as np\n')] |
import sklearn
if sklearn.__version__.startswith('0.18'):
from sklearn.pipeline import _BasePipeline as bp
else:
from sklearn.utils.metaestimators import _BaseComposition as bp
import numpy as np
class XcessivStackedEnsemble(bp):
"""Contains the class for the Xcessiv stacked ensemble"""
def __init__(self, base_learners, meta_feature_generators,
secondary_learner, cv_function):
super(XcessivStackedEnsemble, self).__init__()
self.base_learners = base_learners
self.meta_feature_generators = meta_feature_generators
self.secondary_learner = secondary_learner
self.cv_function = cv_function
self._named_learners = [('bl{}'.format(idx), base_learner) for idx, base_learner
in enumerate(base_learners)]
self._named_learners.append(('secondary-learner', secondary_learner))
def get_params(self, deep=True):
"""Get parameters for this estimator.
Args:
deep (boolean, optional): If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
params: mapping of string to any Parameter names mapped to their values.
"""
return self._get_params('_named_learners', deep=deep)
def set_params(self, **params):
"""Set the parameters of this estimator."""
self._set_params('_named_learners', **params)
return self
def fit(self, X, y):
print('Fitting {} base learners'.format(len(self.base_learners)))
all_learner_meta_features = []
for idx, base_learner in enumerate(self.base_learners):
single_learner_meta_features = []
test_indices = []
for num, (train_idx, test_idx) in enumerate(self.cv_function(X, y)):
print('Fold {} of base learner {}'.format(num+1, idx+1))
base_learner.fit(X[train_idx], y[train_idx])
preds = getattr(base_learner, self.meta_feature_generators[idx])(X[test_idx])
if len(preds.shape) == 1:
preds = preds.reshape(-1, 1)
single_learner_meta_features.append(
preds
)
test_indices.append(test_idx)
single_learner_meta_features = np.concatenate(single_learner_meta_features)
all_learner_meta_features.append(single_learner_meta_features)
all_learner_meta_features = np.concatenate(all_learner_meta_features, axis=1)
test_indices = np.concatenate(test_indices) # reorganized order due to CV
print('Fitting meta-learner')
self.secondary_learner.fit(all_learner_meta_features, y[test_indices])
return self
def _process_using_meta_feature_generator(self, X, meta_feature_generator):
"""Process using secondary learner meta-feature generator
Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make sure secondary learner
has the method.
Args:
X (array-like): Features array
meta_feature_generator (str, unicode): Method for use by secondary learner
"""
all_learner_meta_features = []
for idx, base_learner in enumerate(self.base_learners):
single_learner_meta_features = getattr(base_learner,
self.meta_feature_generators[idx])(X)
if len(single_learner_meta_features.shape) == 1:
single_learner_meta_features = single_learner_meta_features.reshape(-1, 1)
all_learner_meta_features.append(single_learner_meta_features)
all_learner_meta_features = np.concatenate(all_learner_meta_features, axis=1)
out = getattr(self.secondary_learner, meta_feature_generator)(all_learner_meta_features)
return out
| [
"sklearn.__version__.startswith",
"numpy.concatenate"
] | [((18, 56), 'sklearn.__version__.startswith', 'sklearn.__version__.startswith', (['"""0.18"""'], {}), "('0.18')\n", (48, 56), False, 'import sklearn\n'), ((2506, 2555), 'numpy.concatenate', 'np.concatenate', (['all_learner_meta_features'], {'axis': '(1)'}), '(all_learner_meta_features, axis=1)\n', (2520, 2555), True, 'import numpy as np\n'), ((2579, 2607), 'numpy.concatenate', 'np.concatenate', (['test_indices'], {}), '(test_indices)\n', (2593, 2607), True, 'import numpy as np\n'), ((3831, 3880), 'numpy.concatenate', 'np.concatenate', (['all_learner_meta_features'], {'axis': '(1)'}), '(all_learner_meta_features, axis=1)\n', (3845, 3880), True, 'import numpy as np\n'), ((2349, 2393), 'numpy.concatenate', 'np.concatenate', (['single_learner_meta_features'], {}), '(single_learner_meta_features)\n', (2363, 2393), True, 'import numpy as np\n')] |
import os
import cv2
import mmcv
import numpy as np
import torch
from mmpose.apis import (inference, inference_top_down_pose_model, init_pose_model,
vis_pose_result)
import PIL
from PIL import Image
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = init_pose_model(config='train_head_resnet.py', checkpoint='epoch_210.pth', device = device)
image = Image.open('test_0.png')
data = np.asarray(image)
data = np.expand_dims(data, axis=0)
data = np.transpose(data, [0,3,1,2])
trdata = torch.from_numpy(data).float().to(device)
person_result = []
person_result.append({'bbox': [0, 0, 256, 256]})
# test a single image, with a list of bboxes.
pose_results, _ = inference_top_down_pose_model(
model, 'test_0.png', person_result, format='xywh', dataset='AnimalHorse10Dataset')
print(pose_results)
#vis_pose_result(model, 'test_0.png', pose_results)
#res = model(trdata)
#print(res)
| [
"numpy.asarray",
"numpy.transpose",
"numpy.expand_dims",
"PIL.Image.open",
"mmpose.apis.inference_top_down_pose_model",
"torch.cuda.is_available",
"mmpose.apis.init_pose_model",
"torch.from_numpy"
] | [((309, 402), 'mmpose.apis.init_pose_model', 'init_pose_model', ([], {'config': '"""train_head_resnet.py"""', 'checkpoint': '"""epoch_210.pth"""', 'device': 'device'}), "(config='train_head_resnet.py', checkpoint='epoch_210.pth',\n device=device)\n", (324, 402), False, 'from mmpose.apis import inference, inference_top_down_pose_model, init_pose_model, vis_pose_result\n'), ((409, 433), 'PIL.Image.open', 'Image.open', (['"""test_0.png"""'], {}), "('test_0.png')\n", (419, 433), False, 'from PIL import Image\n'), ((441, 458), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (451, 458), True, 'import numpy as np\n'), ((466, 494), 'numpy.expand_dims', 'np.expand_dims', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (480, 494), True, 'import numpy as np\n'), ((502, 534), 'numpy.transpose', 'np.transpose', (['data', '[0, 3, 1, 2]'], {}), '(data, [0, 3, 1, 2])\n', (514, 534), True, 'import numpy as np\n'), ((716, 833), 'mmpose.apis.inference_top_down_pose_model', 'inference_top_down_pose_model', (['model', '"""test_0.png"""', 'person_result'], {'format': '"""xywh"""', 'dataset': '"""AnimalHorse10Dataset"""'}), "(model, 'test_0.png', person_result, format=\n 'xywh', dataset='AnimalHorse10Dataset')\n", (745, 833), False, 'from mmpose.apis import inference, inference_top_down_pose_model, init_pose_model, vis_pose_result\n'), ((261, 286), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (284, 286), False, 'import torch\n'), ((541, 563), 'torch.from_numpy', 'torch.from_numpy', (['data'], {}), '(data)\n', (557, 563), False, 'import torch\n')] |
import numpy as np
from nengo import *
from nengo_spa import *
from utils import *
D = 16 # Number of dimensions for each ensemble.
N = 64 # Number of neurons per dimension.
CLOCK_PERIOD = 0.25 # How many seconds a full clock cycle takes.
SIM_TIME = 20 # How long to run the simulation.
LEARN_TIME = 15 # How long until learning should be switched off.
SEED = 42 # RNG seed for deterministic results.
RNG = np.random.RandomState(SEED)
goals = 'Start Retrieve Compare'.split()
actions = 'Yes No'.split()
numbers = 'Nil One Two Three Four'.split() # "Zero" is a built-in pointer, so that's why we use "Nil" instead.
letters = 'A B C D E F G H'.split()
concepts = letters + numbers
vocab_concepts = Vocabulary(dimensions=D, pointer_gen=RNG)
vocab_goals = Vocabulary(dimensions=D, pointer_gen=RNG)
vocab_motor = Vocabulary(dimensions=1, pointer_gen=RNG)
vocab_concepts.populate(';'.join(concepts))
vocab_goals.populate(';'.join(goals))
vocab_motor.populate(';'.join(actions))
ideal_mapping = {}
for number_idx in range(len(numbers)):
for letter_idx in range(len(letters) - number_idx):
probe = '%s + %s' % (letters[letter_idx], numbers[number_idx])
ideal_mapping[probe] = letters[letter_idx + number_idx]
with Network('Counting', seed=SEED) as model:
with Network('Comparison'):
compare_a = WTAAssocMem(threshold=0.3, input_vocab=vocab_concepts, mapping=vocab_concepts.keys(), function=lambda x: x > 0, n_neurons=N)
compare_b = WTAAssocMem(threshold=0.3, input_vocab=vocab_concepts, mapping=vocab_concepts.keys(), function=lambda x: x > 0, n_neurons=N)
Connection(compare_a.output, compare_a.input, synapse=0.05, transform=0.8)
Connection(compare_b.output, compare_b.input, synapse=0.05, transform=0.8)
compare = Compare(vocab=vocab_concepts, neurons_per_dimension=N)
Connection(compare_a.output, compare.input_a)
Connection(compare_b.output, compare.input_b)
# compare.output is a Node, and we can't make Connections with functions from a Node. So we need to pass it through a Scalar first.
compare_output = Scalar()
Connection(compare.output, compare_output.input, synapse=None)
comparison_status = Scalar()
Connection(comparison_status.output, comparison_status.input, synapse=0.05)
Connection(compare_output.output, comparison_status.input, function=lambda x: 1 if x > 0.5 else -1)
with Network('Goal'):
lhs = State(vocab=vocab_concepts)
rhs = State(vocab=vocab_concepts)
target = State(vocab=vocab_concepts)
with Network('Imaginal'):
goal = WTAAssocMem(threshold=0.3, input_vocab=vocab_goals, mapping=vocab_goals.keys(), function=lambda x: x > 0, n_neurons=N)
next_goal = WTAAssocMem(threshold=0.3, input_vocab=vocab_goals, mapping=vocab_goals.keys(), function=lambda x: x > 0, n_neurons=N)
motor = WTAAssocMem(threshold=0.3, input_vocab=vocab_motor, mapping=vocab_motor.keys(), function=lambda x: x > 0, n_neurons=N)
Connection(goal.output, goal.input, synapse=0.05, transform=0.5)
Connection(next_goal.output, next_goal.input, synapse=0.05, transform=0.5)
Connection(motor.output, motor.input, synapse=0.05, transform=0.5)
with Network('Declarative'):
ideal_memory = WTAAssocMem(threshold=0.5, input_vocab=vocab_concepts, mapping=ideal_mapping, function=lambda x: x > 0, n_neurons=N)
#
# probe ----> learn_in --PES--> learn_out --Cleanup--> retrieval
# ^
# |
# error = learn_out - ideal_memory
#
probe = State(vocab=vocab_concepts, neurons_per_dimension=N)
learn_in = Ensemble(dimensions=D, n_neurons=D*N, intercepts=[0.5]*(D*N)) # 0.4 might be better.
learn_out = Ensemble(dimensions=D, n_neurons=D*N)
retrieval = WTAAssocMem(threshold=0.5, input_vocab=vocab_concepts, mapping=vocab_concepts.keys(), function=lambda x: x > 0, n_neurons=N)
Connection(probe.output, learn_in, synapse=None)
pes = Connection(learn_in, learn_out, synapse=None, learning_rule_type=PES(learning_rate=1e-3))
Connection(learn_out, retrieval.input, synapse=None)
error = Ensemble(dimensions=D, n_neurons=D*N)
Connection(learn_out, error, synapse=None)
Connection(ideal_memory.output, error, transform=-1, synapse=None)
Connection(error, pes.learning_rule, synapse=None)
inhibition = Node(lambda t: 0 if t < LEARN_TIME else -10)
Connection(inhibition, error.neurons, transform=np.ones((error.n_neurons, 1)), synapse=None)
with Network('Clock'):
clock = Scalar(n_neurons=100)
clock_node = Node(lambda t: +1 if t % CLOCK_PERIOD < CLOCK_PERIOD/2 else -1)
Connection(clock_node, clock.input, synapse=None)
def get_problem(t):
cycle = int(t / CLOCK_PERIOD)
index = cycle // len(goals)
problems = [
('A', 'Two', 'C'),
('B', 'Two', 'D'),
('C', 'Three', 'F'),
('D', 'Three', 'F'),
('A', 'Four', 'D'),
('B', 'Four', 'G'),
]
return problems[index % len(problems)]
Transcode(lambda t: 'Start' if t < CLOCK_PERIOD/2 else '0', output_vocab=vocab_goals) >> goal
Transcode(lambda t: get_problem(t)[0], output_vocab=vocab_concepts) >> lhs
Transcode(lambda t: get_problem(t)[1], output_vocab=vocab_concepts) >> rhs
Transcode(lambda t: get_problem(t)[2], output_vocab=vocab_concepts) >> target
lhs + rhs >> ideal_memory
lhs + rhs >> probe
with ActionSelection() as action_selection:
goal_start = dot(goal, sym.Start)
goal_retrieve = dot(goal, sym.Retrieve)
goal_compare = dot(goal, sym.Compare)
# Technically we don't need this many steps (only the compare is needed).
# Hopefully this should make it easier to integrate with the counting model though.
ifmax('Start',
(1/2)*(goal_start + clock),
sym.Retrieve >> next_goal)
ifmax('Retrieve',
(1/2)*(goal_retrieve + clock),
retrieval >> compare_a,
target >> compare_b,
sym.Compare >> next_goal)
ifmax('Compare Yes',
(1/3)*(goal_compare + comparison_status + clock),
sym.Yes >> motor,
sym.Start >> next_goal)
ifmax('Compare No',
(1/3)*(goal_compare - comparison_status + clock),
sym.No >> motor,
sym.Start >> next_goal)
ifmax('Update goal',
-clock,
next_goal >> goal)
MyProbe(lhs.output, 'LHS', synapse=0.03, vocab=vocab_concepts)
MyProbe(rhs.output, 'RHS', synapse=0.03, vocab=vocab_concepts)
#MyProbe(target.output, 'target', synapse=0.03, vocab=vocab_concepts)
#MyProbe(learn_in, 'Learn in', synapse=0.03, vocab=vocab_concepts)
#MyProbe(learn_out, 'Learn out', synapse=0.03, vocab=vocab_concepts)
MyProbe(ideal_memory.output, 'Ideal Mem.', synapse=0.03, vocab=vocab_concepts)
MyProbe(retrieval.output, 'Retrieval', synapse=0.03, vocab=vocab_concepts)
#MyProbe(error, 'Error', synapse=0.03)
#MyProbe(goal.output, 'Goal', synapse=0.03, vocab=vocab_goals)
#MyProbe(next_goal.output, 'Next', synapse=0.03, vocab=vocab_goals)
#MyProbe(compare_a.input, 'Compare A', synapse=0.03, vocab=vocab_concepts)
#MyProbe(compare_b.input, 'Compare B', synapse=0.03, vocab=vocab_concepts)
#MyProbe(comparison_status.output, 'CMP status', synapse=0.03)
MyProbe(inhibition, 'Inhibition', synapse=0.03)
#MyProbe(motor.output, 'Motor', synapse=0.03, vocab=vocab_motor)
#MyProbe(clock.output, 'Clock')
print('%d neurons' % model.n_neurons)
with Simulator(model) as sim:
sim.run(SIM_TIME)
plot_simulation_output('Learning model', sim) | [
"numpy.ones",
"numpy.random.RandomState"
] | [((455, 482), 'numpy.random.RandomState', 'np.random.RandomState', (['SEED'], {}), '(SEED)\n', (476, 482), True, 'import numpy as np\n'), ((4463, 4492), 'numpy.ones', 'np.ones', (['(error.n_neurons, 1)'], {}), '((error.n_neurons, 1))\n', (4470, 4492), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# @Date : 2020/7/20
# @Author : mingming.xu
# @Email : <EMAIL>
# @File : preprocess.py
import numpy as np
import tensorflow as tf
from toolkit4nlp.backend import K
class TrainingDataset(object):
def __init__(self, tokenizer, seq_length):
"""
:param tokenizer: tokenizer
:param seq_length: sequence length
"""
self.tokenizer = tokenizer
self.seq_length = seq_length
self.token_pad_id = tokenizer._token_pad_id
self.token_cls_id = tokenizer._token_start_id
self.token_sep_id = tokenizer._token_end_id
self.token_mask_id = tokenizer._token_mask_id
self.vocab_size = tokenizer._vocab_size
def process(self, corpus, record_name):
"""将语料(corpus)处理为tfrecord格式,并写入 record_name"""
writer = tf.io.TFRecordWriter(record_name)
instances = self.paragraph_process(corpus)
instances_serialized = self.tfrecord_serialize(instances)
for instance_serialized in instances_serialized:
writer.write(instance_serialized)
def get_start_end_padding_tokens(self):
"""get start/end/padding tokens for instance"""
raise NotImplementedError
def paragraph_process(self, corpus):
"""
将句子不断的塞进一个instance里,直到长度即将超出seq_length
:param corpus: sentence list构成的paragraph
:param starts_tokens: 每个序列开始的token_id
:param ends_tokens: 每个序列结束的token_id
:param paddings_tokens: 每个序列padding_token
:return: instances
"""
starts_tokens, ends_tokens, paddings_tokens = self.get_start_end_padding_tokens()
instances, instance = [], [[i] for i in starts_tokens]
for sentence in corpus:
sentence_tokens = self.sentence_process(sentence)
sentence_tokens = [tokens[:self.seq_length - 2] for tokens in sentence_tokens] # 单个句子长度不能超过最大限度
length_after_added = len(instance[0]) + len(sentence_tokens[0])
# 判断加入这句长度会不会超限
if length_after_added > self.seq_length - 1: # end_token保留一个位置
# save instance
one_instance = []
for tokens, end_token, pad_token in zip(instance, ends_tokens, paddings_tokens):
tokens.append(end_token)
tokens = self.padding(tokens, pad_token)
one_instance.append(tokens)
instances.append(one_instance) # 加入instances
# update new instance
instance = [[i] for i in starts_tokens]
# append sentence tokens
for tokens, last_tokens in zip(instance, sentence_tokens):
tokens.extend(last_tokens)
# 处理最后一个
one_instance = []
for tokens, end_token, pad_token in zip(instance, ends_tokens, paddings_tokens):
tokens.append(end_token)
tokens = self.padding(tokens, pad_token)
one_instance.append(tokens)
instances.append(one_instance)
return instances
def padding(self, seq_tokens, padding_value=None):
"""对单个token序列进行padding"""
if padding_value is None:
padding_value = self.token_pad_id
seq_tokens = seq_tokens[: self.seq_length]
padding_length = self.seq_length - len(seq_tokens)
return seq_tokens + [padding_value] * padding_length
def sentence_process(self, sentence):
"""根据任务对句子进行处理"""
raise NotImplementedError
def _int64_feature(self, value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _bytes_feature(self, value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(self, value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def get_instance_keys(self):
"""Return key of instance's item"""
raise NotImplementedError
def tfrecord_serialize(self, instances):
"""
将instances进行序列化:create_feature -> create_kv_feature -> create_example -> serialize_to_string
:param instances:
:param instance_keys: key of instance's item
:return:
"""
instance_serialized = []
instance_keys = self.get_instance_keys()
for instance in instances:
features = {k: self._int64_feature(v) for k, v in zip(instance_keys, instance)}
tf_features = tf.train.Features(feature=features)
tf_example = tf.train.Example(features=tf_features)
serialized = tf_example.SerializeToString()
instance_serialized.append(serialized)
return instance_serialized
@staticmethod
def load_tfrecord(record_names, batch_size, parse_func):
"""
读取tfrecord:按parse_func进行parse_single_example -> repeat -> batch
:param record_names:
:param batch_size:
:param parse_func:
:return:
"""
if type(record_names) != list:
record_names = [record_names]
dataset = tf.data.TFRecordDataset(record_names) # load
dataset = dataset.map(parse_func) # pars
dataset = dataset.repeat() # repeat
dataset = dataset.shuffle(batch_size * 1000) # shuffle
dataset = dataset.batch(batch_size) # batch
return dataset
class TrainingDataSetRoBERTa(TrainingDataset):
"""
生成Robert模式预训练数据:以词为单位进行mask;15%的概率进行替换;替换时80%替换为 [MASK], 10% 不变,10% 随机替换
"""
def __init__(self, tokenizer, word_seg, mask_rate=0.15, seq_length=512):
"""
:param tokenizer:
:param word_seg: 分词函数
:param mask_rate:
:param seq_length:
"""
super(TrainingDataSetRoBERTa, self).__init__(tokenizer, seq_length)
self.word_seg = word_seg
self.mask_rate = mask_rate
def get_instance_keys(self):
return ['token_ids', 'mask_ids']
def get_start_end_padding_tokens(self):
starts = [self.token_cls_id, 0]
ends = [self.token_sep_id, 0]
paddings = [self.token_pad_id, 0]
return starts, ends, paddings
def sentence_process(self, sentence):
""""""
words = self.word_seg(sentence)
probs = np.random.random(len(words))
sentence_token_ids, sentence_mask_ids = [], []
for word, prob in zip(words, probs):
tokens = self.tokenizer.tokenize(word)[1:-1]
token_ids = self.tokenizer.tokens_to_ids(tokens)
sentence_token_ids.extend(token_ids)
if prob < self.mask_rate:
# token_id加1,让unmask-id为0
mask_ids = [self.mask_token_process(token_id) + 1 for token_id in token_ids]
else:
mask_ids = [0] * len(token_ids)
sentence_mask_ids.extend(mask_ids)
return [sentence_token_ids, sentence_mask_ids]
def mask_token_process(self, token_id):
"""处理mask token ids,其中80%概率替换为 [MASK], 10% 概率不变,10% 概率随机替换"""
prob = np.random.random()
if prob < 0.8:
return self.token_mask_id
elif prob < 0.9:
return token_id
return np.random.randint(0, self.vocab_size)
@staticmethod
def load_tfrecord(record_names, seq_length, batch_size):
def parse_func(serialized_record):
feature_description = {
'token_ids': tf.io.FixedLenFeature([seq_length], tf.int64),
'mask_ids': tf.io.FixedLenFeature([seq_length], tf.int64)
}
features = tf.io.parse_single_example(serialized_record, feature_description)
token_ids = features['token_ids']
mask_ids = features['mask_ids']
segment_ids = K.zeros_like(token_ids, dtype='int64')
is_masked = K.not_equal(mask_ids, 0)
masked_token_ids = K.switch(mask_ids, mask_ids - 1, token_ids) # 之前让位给unmask_id一位,现在减1回归
x = {
'Input-Token': masked_token_ids,
'Input-Segment': segment_ids,
'token_ids': token_ids,
'is_masked': K.cast(is_masked, K.floatx())
}
y = {
'mlm_loss': K.zeros_like([1], tf.float32),
'mlm_acc': K.zeros_like([1], tf.float32)
}
return x, y
return TrainingDataset.load_tfrecord(record_names, batch_size, parse_func)
if __name__ == "__main__":
from toolkit4nlp.tokenizers import Tokenizer
import re
import json
import glob
import jieba_fast as jieba
from tqdm import tqdm
jieba.initialize()
vocab = '/home/mingming.xu/pretrain/NLP/chinese_L-12_H-768_A-12/vocab.txt'
tokenizer = Tokenizer(vocab, do_lower_case=True)
seq_length = 512
def word_seg(text):
return jieba.lcut(text)
def generate_corp():
file_names = glob.glob('/home/mingming.xu/datasets/NLP/qa/dureader_robust-data/pretraining/*')
count, sentences = 0, []
for fname in file_names:
with open(fname) as fin:
for p in json.load(fin)['data'][0]['paragraphs']:
para = [qa['question'] for qa in p['qas']]
para_text = ' '.join(para)
para_text += ' ' + p['context']
sentence_list = re.findall('.*?[\n.。 ]+', para_text)
sentences.extend(sentence_list)
count += 1
if count > 10:
yield sentences
count, sentences = 0, []
if sentences:
yield sentences
dataset = TrainingDataSetRoBERTa(tokenizer=tokenizer, word_seg=word_seg, seq_length=seq_length)
for i in range(10): # repeate 10 times to make 10 different ways of mask token
for corp in tqdm(generate_corp()):
dataset.process(corp, record_name='../corpus_record/corppus.%i.tfrecord' % i)
| [
"tensorflow.train.Int64List",
"numpy.random.randint",
"toolkit4nlp.tokenizers.Tokenizer",
"tensorflow.train.FloatList",
"glob.glob",
"toolkit4nlp.backend.K.floatx",
"jieba_fast.initialize",
"tensorflow.train.Example",
"re.findall",
"toolkit4nlp.backend.K.zeros_like",
"tensorflow.train.BytesList"... | [((8910, 8928), 'jieba_fast.initialize', 'jieba.initialize', ([], {}), '()\n', (8926, 8928), True, 'import jieba_fast as jieba\n'), ((9024, 9060), 'toolkit4nlp.tokenizers.Tokenizer', 'Tokenizer', (['vocab'], {'do_lower_case': '(True)'}), '(vocab, do_lower_case=True)\n', (9033, 9060), False, 'from toolkit4nlp.tokenizers import Tokenizer\n'), ((831, 864), 'tensorflow.io.TFRecordWriter', 'tf.io.TFRecordWriter', (['record_name'], {}), '(record_name)\n', (851, 864), True, 'import tensorflow as tf\n'), ((5395, 5432), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['record_names'], {}), '(record_names)\n', (5418, 5432), True, 'import tensorflow as tf\n'), ((7336, 7354), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (7352, 7354), True, 'import numpy as np\n'), ((7484, 7521), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.vocab_size'], {}), '(0, self.vocab_size)\n', (7501, 7521), True, 'import numpy as np\n'), ((9124, 9140), 'jieba_fast.lcut', 'jieba.lcut', (['text'], {}), '(text)\n', (9134, 9140), True, 'import jieba_fast as jieba\n'), ((9189, 9275), 'glob.glob', 'glob.glob', (['"""/home/mingming.xu/datasets/NLP/qa/dureader_robust-data/pretraining/*"""'], {}), "(\n '/home/mingming.xu/datasets/NLP/qa/dureader_robust-data/pretraining/*')\n", (9198, 9275), False, 'import glob\n'), ((4777, 4812), 'tensorflow.train.Features', 'tf.train.Features', ([], {'feature': 'features'}), '(feature=features)\n', (4794, 4812), True, 'import tensorflow as tf\n'), ((4838, 4876), 'tensorflow.train.Example', 'tf.train.Example', ([], {'features': 'tf_features'}), '(features=tf_features)\n', (4854, 4876), True, 'import tensorflow as tf\n'), ((7868, 7934), 'tensorflow.io.parse_single_example', 'tf.io.parse_single_example', (['serialized_record', 'feature_description'], {}), '(serialized_record, feature_description)\n', (7894, 7934), True, 'import tensorflow as tf\n'), ((8051, 8089), 'toolkit4nlp.backend.K.zeros_like', 'K.zeros_like', (['token_ids'], {'dtype': '"""int64"""'}), "(token_ids, dtype='int64')\n", (8063, 8089), False, 'from toolkit4nlp.backend import K\n'), ((8114, 8138), 'toolkit4nlp.backend.K.not_equal', 'K.not_equal', (['mask_ids', '(0)'], {}), '(mask_ids, 0)\n', (8125, 8138), False, 'from toolkit4nlp.backend import K\n'), ((8170, 8213), 'toolkit4nlp.backend.K.switch', 'K.switch', (['mask_ids', '(mask_ids - 1)', 'token_ids'], {}), '(mask_ids, mask_ids - 1, token_ids)\n', (8178, 8213), False, 'from toolkit4nlp.backend import K\n'), ((3641, 3672), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': 'value'}), '(value=value)\n', (3659, 3672), True, 'import tensorflow as tf\n'), ((3803, 3817), 'tensorflow.constant', 'tf.constant', (['(0)'], {}), '(0)\n', (3814, 3817), True, 'import tensorflow as tf\n'), ((3954, 3987), 'tensorflow.train.BytesList', 'tf.train.BytesList', ([], {'value': '[value]'}), '(value=[value])\n', (3972, 3987), True, 'import tensorflow as tf\n'), ((4128, 4161), 'tensorflow.train.FloatList', 'tf.train.FloatList', ([], {'value': '[value]'}), '(value=[value])\n', (4146, 4161), True, 'import tensorflow as tf\n'), ((7710, 7755), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), '([seq_length], tf.int64)\n', (7731, 7755), True, 'import tensorflow as tf\n'), ((7785, 7830), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), '([seq_length], tf.int64)\n', (7806, 7830), True, 'import tensorflow as tf\n'), ((8514, 8543), 'toolkit4nlp.backend.K.zeros_like', 'K.zeros_like', (['[1]', 'tf.float32'], {}), '([1], tf.float32)\n', (8526, 8543), False, 'from toolkit4nlp.backend import K\n'), ((8572, 8601), 'toolkit4nlp.backend.K.zeros_like', 'K.zeros_like', (['[1]', 'tf.float32'], {}), '([1], tf.float32)\n', (8584, 8601), False, 'from toolkit4nlp.backend import K\n'), ((8442, 8452), 'toolkit4nlp.backend.K.floatx', 'K.floatx', ([], {}), '()\n', (8450, 8452), False, 'from toolkit4nlp.backend import K\n'), ((9638, 9674), 're.findall', 're.findall', (['""".*?[\n.。 ]+"""', 'para_text'], {}), "('.*?[\\n.。 ]+', para_text)\n", (9648, 9674), False, 'import re\n'), ((9399, 9413), 'json.load', 'json.load', (['fin'], {}), '(fin)\n', (9408, 9413), False, 'import json\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.