code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
# -*- coding: utf-8 -*-
import os
import tensorflow as tf
import os
import pathlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import glob, os
import random
import math
import sys
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import confusion_matrix
import itertools
from yellowbrick.features.pca import PCADecomposition
from yellowbrick.style.palettes import PALETTES, SEQUENCES, color_palette
# Define names of folders and categories
folders = ['coarse', 'fine', 'real']
categories = {
'ape': 1,
'benchvise': 2,
'cam': 3,
'cat': 4,
'duck': 5
}
# Load whole data
train_set = []
template_set = []
test_set = []
train_pose_set = []
template_pose_set = []
test_pose_set = []
# pose string into (name, pose) tupple
def extract_pose(pose_str):
name_val = pose_str.split('\n')
name = name_val[0].strip()
quartenion_vals = [float(val) for val in name_val[1].split(' ')]
return (name, quartenion_vals)
# Real data consists of 2 parts, one for the training and one for the test
# Get file names for training part
with open('dataset/real/training_split.txt', 'r') as real_split_file:
real_split = real_split_file.read()
real_split = real_split.split(', ')
real_split[-1] = real_split[-1].replace('\n', '')
for folder in folders:
# Go over categories
for cat_idx, category in enumerate(categories):
# Read all poses for all files inside 'folder/category/'
poses_path = os.path.join('dataset', folder, category, 'poses.txt')
with open(poses_path, 'r') as poses_file:
all_poses = poses_file.read().split('#')[1:]
all_poses = dict(map(extract_pose, all_poses))
path = os.path.join('dataset', folder, category, '*.png')
files = glob.glob(path)
# Real data has 2 parts
if folder == 'real':
images_train = []
images_test = []
poses_train = []
poses_test = []
else:
images = []
poses = []
# Read process all images in folder
for filename in files:
# Read-Normalize image from [0, 255] to [-1, 1]
image = mpimg.imread(filename)
image = 2 * (image / 255) - 1
filename = filename.replace( "\\", '/')
# Retrieve pose - ex: dataset/coarse/ape/coarse191.png
pose = all_poses[filename.split('/')[-1]]
if folder == 'real':
if any(index in filename for index in real_split):
images_train.append(image)
poses_train.append(pose)
else:
images_test.append(image)
poses_test.append(pose)
else:
images.append(image)
poses.append(pose)
# Append current image/pose to corresponding dataset
if folder == 'coarse':
template_set.append(images)
template_pose_set.append(poses)
elif folder == 'fine':
train_set.append(images)
train_pose_set.append(poses)
elif folder == 'real':
train_set[cat_idx] += images_train
train_pose_set[cat_idx] += poses_train
test_set.append(images_test)
test_pose_set.append(poses_test)
# Convert datasets to numpy arrays
train_set = np.array(train_set)
template_set = np.array(template_set)
test_set = np.array(test_set)
train_pose_set = np.array(train_pose_set)
template_pose_set = np.array(template_pose_set)
test_pose_set = np.array(test_pose_set)
template_set_flat = template_set.reshape(-1, 64, 64, 3)
template_pose_set_flat = template_pose_set.reshape(-1, 4)
test_set_flat = test_set.reshape(-1, 64, 64, 3)
test_pose_set_flat = test_pose_set.reshape(-1, 4)
print("Training Set Shape: ", train_set.shape)
print("Template Set Shape: ", template_set.shape)
print("Test Set Shape: ", test_set.shape)
print()
print("Training Pose Set Shape: ", train_pose_set.shape)
print("Template Pose Set Shape: ", template_pose_set.shape)
print("Test Pose Set Shape: ", test_pose_set.shape)
'''
Training Set Shape: (5, 2148, 64, 64, 3)
Template Set Shape: (5, 267, 64, 64, 3)
Test Set Shape: (5, 41, 64, 64, 3)
Training Pose Set Shape: (5, 2148, 4)
Template Pose Set Shape: (5, 267, 4)
Test Pose Set Shape: (5, 41, 4)
'''
# Calculates angular difference between 2 quarternions (in degrees)
def calculate_angle_between(pose1, pose2):
dot_product = abs(np.dot(np.array(pose1), np.array(pose2)))
# To ensure numerical stability
dot_product = round(dot_product, 4)
degree = 2 * math.acos(dot_product)
degree = math.degrees(degree)
return degree
# Batch generator for generating batches on runtime
def batch_generator(batch_size=32):
while True:
# Anchor categories and indices
batch_categories = np.random.randint(5, size=batch_size)
category_indices = np.random.randint(train_set.shape[1], size=batch_size)
batch = []
for idx in range(batch_size):
# Retrieve anchor and pose
category = batch_categories[idx]
index = category_indices[idx]
anchor = train_set[category][index]
anchor_pose = train_pose_set[category][index]
# Select puller which is very similar to anchor
min_similarity = sys.maxsize
for template_idx, template_pose in enumerate(template_pose_set[category]):
# Get rotation degree between poses
similarity = calculate_angle_between(anchor_pose, template_pose)
# 0.1 to ensure poses are not the same
if similarity < min_similarity and similarity > 0.1:
min_similarity = similarity
puller = template_set[category][template_idx]
# Pusher can be:
# either from the same category (but different pose) or different category
pusher_is_same_category = random.choice([True, False])
if pusher_is_same_category: # same category different pose
pusher_category = category
pusher_idx = np.random.randint(len(template_set[category]))
while pusher_idx == index: # ensure pusher_idx not same as anchor
pusher_idx = np.random.randint(len(template_set[category]))
else: # randomly chosen different category
pusher_category = np.random.randint(5)
while pusher_category == category: # ensure pusher_category not same as anchor
pusher_category = np.random.randint(5)
pusher_idx = np.random.randint(len(template_set[pusher_category]))
# Retrieve pusher
pusher = template_set[pusher_category][pusher_idx]
# Append triple to batch
batch.append(anchor)
batch.append(puller)
batch.append(pusher)
# Yield batch
yield np.array(batch)
def conv_net(x):
# First Convolutional layer + ReLU + MaxPool
conv1 = tf.layers.conv2d(
inputs=x,
filters=16,
kernel_size=[8, 8],
padding="VALID",
use_bias=True,
activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(
inputs=conv1,
pool_size=[2, 2],
strides=2,
padding='VALID'
)
# Second Convolutional layer + ReLU + MaxPool
conv2 = tf.layers.conv2d(
inputs=pool1,
filters=7,
kernel_size=[5, 5],
padding="VALID",
use_bias=True,
activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(
inputs=conv2,
pool_size=[2, 2],
strides=2,
padding='VALID'
)
# Flatten
fc1 = tf.reshape(pool2, [-1, 12 * 12 * 7])
# First Fully Connected layer + ReLU
fc1 = tf.layers.dense(
inputs=fc1,
units=256,
activation=tf.nn.relu,
use_bias=True
)
# Second Fully Connected layer
fc2 = tf.layers.dense(
inputs=fc1,
units=16,
use_bias=True
)
return fc2
# Measure model accuracy based on Template and Test Sets
def measure_model_acc(template_predictions, test_predictions):
# Build NearestNeighbors model
nearest_neighbor = NearestNeighbors(n_neighbors=1, algorithm='auto').fit(template_predictions)
# Get nearest neighbor of each test sample
distances, nearest_indices = nearest_neighbor.kneighbors(test_predictions)
num_correct_class = 0
# 10, 20, 40, 180
angles = [0, 0, 0, 0]
#y_test and y_pred will be later used for "Confusion Matrix"
y_test=[]
y_pred=[]
for idx, nearest_index in enumerate(nearest_indices):
# Get neighbor classes
test_class = idx // test_set.shape[1]
nearest_index_class = nearest_index // template_set.shape[1]
y_test.append(test_class)
y_pred.append(nearest_index_class)
# Only consider correctly classified classes
if test_class == nearest_index_class:
num_correct_class += 1
# Angular difference between neighbors
test_pose = test_pose_set_flat[idx]
template_pose = template_pose_set_flat[nearest_index][0]
angle = calculate_angle_between(test_pose, template_pose)
# For histogram
if angle <= 10:
angles[0] += 1
if angle <= 20:
angles[1] += 1
if angle <= 40:
angles[2] += 1
if angle <= 180:
angles[3] += 1
# Finalize computations
accuracy = num_correct_class / test_set_flat.shape[0]
angles = np.array(angles) / test_set_flat.shape[0]
return (accuracy, angles, y_test, y_pred)
# Plots or saves histogram to a file
def plot_save_histogram(angles, filename=None):
x = np.arange(4)
fig, ax = plt.subplots()
plt.bar(x, angles)
plt.xticks(x, ('10%', '20%', '40%', '180%'))
if filename is not None:
plt.savefig(filename)
plt.close(fig)
else:
plt.show()
# Input for the network
x = tf.placeholder("float", [None, 64,64,3])
# Network parameteres
num_epoch = 30
num_epoch = 3
num_iters = 100
learning_rate = 0.001
batch_size = 960
batch_size = 128
# Network output
pred = conv_net(x)
###### Loss computation part
anchor = pred[0::3]
puller = pred[1::3]
pusher = pred[2::3]
diff_pos = anchor - puller
diff_neg = anchor - pusher
loss_triplets = tf.reduce_sum(tf.maximum(float(0), 1 - (tf.reduce_sum(tf.square(diff_neg), -1) / (tf.reduce_sum(tf.square(diff_pos), -1) + 0.01))))
loss_pairs = tf.reduce_sum(tf.reduce_sum(tf.square(diff_pos), -1))
cost = loss_triplets + loss_pairs
#########
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# History holders
loss_history_train = []
loss_history_val = []
accuracy_history_test = []
iter_cnt = 0
for i in range(num_epoch): # For each epoch
for batch_i in range(num_iters): # For each batch
iter_cnt += 1
# Get next batch
batch_x = next(batch_generator(batch_size))
# Run optimizer
opt = sess.run(optimizer, feed_dict={x: batch_x})
if iter_cnt % 10 == 0:
# Print train and validation losses
train_loss = sess.run(cost, feed_dict={x: batch_x})
loss_history_train.append(train_loss)
val_x = next(batch_generator(batch_size))
val_loss = sess.run(cost, feed_dict={x: val_x})
loss_history_val.append(val_loss)
print(iter_cnt, ": Train Loss: ", train_loss)
print(iter_cnt, ": Validation Loss: ", val_loss)
#if iter_cnt % 500 == 0:
if iter_cnt % 300 == 0:
# Build and save histogram
pred_template = sess.run(pred, feed_dict={x: template_set_flat})
pred_test = sess.run(pred, feed_dict={x: test_set_flat})
(test_acc, angles, c_test, c_pred) = measure_model_acc(pred_template, pred_test)
y_test=c_test
y_pred=c_pred
print("Accuracy: ", test_acc)
plot_save_histogram(angles, "histograms/hist_" + str(iter_cnt) + ".png")
accuracy_history_test.append(test_acc)
print("Epoch end!")
tf.train.Saver().save(sess, "./model/model.ckpt")
# summarize history for loss
plt.plot(loss_history_train)
plt.plot(loss_history_val)
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel("10th iteration")
plt.legend(['train', 'validation'], loc='upper right')
plt.savefig("loss_history.png")
plt.show()
# summarize history for loss
plt.plot(accuracy_history_test)
plt.title('model accuracy')
plt.ylabel('loss')
plt.xlabel("500th iteration")
plt.legend(['test'], loc='upper left')
plt.savefig("accuracy history.png")
plt.show()
# ======================================================================================
# get color for all classes
pallette = color_palette("reset")
colors = list(map(lambda idx: pallette[idx // test_set.shape[1]], range(len(pred_test))))
visualizer = PCADecomposition(scale=True, proj_dim=3, color = colors, size=(1080, 720))
visualizer.fit_transform(pred_test, colors)
visualizer.poof(outpath="./pca", dpi=300)
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
'''
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
'''
if normalize:
cm = (cm.astype('float') / cm.sum(axis=1)[:, np.newaxis])*100
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
plt.savefig("Confusion_Matrix.png")
print(y_test[:6])
y_test=np.array(y_test)
y_pred=np.array(y_pred)
class_names=["ape","benchvise","cam","cat","duck"]
cnf_matrix = confusion_matrix(y_test, y_pred)
np.set_printoptions(precision=2)
# Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
title='Normalized confusion matrix')
plt.show()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.bar",
"tensorflow.reshape",
"tensorflow.train.AdamOptimizer",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"numpy.arange",
"tensorflow.layers.max_pooling2d",
"glob.glob",
"matplotlib.pyplot.tight_layout",
"os.path.join",
"yellowbrick.style.palettes.color_palette",
"numpy.set_printoptions",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.close",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.colorbar",
"tensorflow.placeholder",
"sklearn.neighbors.NearestNeighbors",
"yellowbrick.features.pca.PCADecomposition",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"matplotlib.image.imread",
"matplotlib.pyplot.show",
"tensorflow.train.Saver",
"tensorflow.global_variables_initializer",
"matplotlib.pyplot.legend",
"tensorflow.Session",
"tensorflow.layers.conv2d",
"matplotlib.pyplot.ylabel",
"math.degrees",
"matplotlib.pyplot.plot",
"tensorflow.layers.dense",
"random.choice",
"math.acos",
"numpy.array",
"tensorflow.square",
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] |
[((3500, 3519), 'numpy.array', 'np.array', (['train_set'], {}), '(train_set)\n', (3508, 3519), True, 'import numpy as np\n'), ((3535, 3557), 'numpy.array', 'np.array', (['template_set'], {}), '(template_set)\n', (3543, 3557), True, 'import numpy as np\n'), ((3569, 3587), 'numpy.array', 'np.array', (['test_set'], {}), '(test_set)\n', (3577, 3587), True, 'import numpy as np\n'), ((3606, 3630), 'numpy.array', 'np.array', (['train_pose_set'], {}), '(train_pose_set)\n', (3614, 3630), True, 'import numpy as np\n'), ((3651, 3678), 'numpy.array', 'np.array', (['template_pose_set'], {}), '(template_pose_set)\n', (3659, 3678), True, 'import numpy as np\n'), ((3695, 3718), 'numpy.array', 'np.array', (['test_pose_set'], {}), '(test_pose_set)\n', (3703, 3718), True, 'import numpy as np\n'), ((10298, 10340), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, 64, 64, 3]'], {}), "('float', [None, 64, 64, 3])\n", (10312, 10340), True, 'import tensorflow as tf\n'), ((11025, 11058), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (11056, 11058), True, 'import tensorflow as tf\n'), ((12891, 12919), 'matplotlib.pyplot.plot', 'plt.plot', (['loss_history_train'], {}), '(loss_history_train)\n', (12899, 12919), True, 'import matplotlib.pyplot as plt\n'), ((12920, 12946), 'matplotlib.pyplot.plot', 'plt.plot', (['loss_history_val'], {}), '(loss_history_val)\n', (12928, 12946), True, 'import matplotlib.pyplot as plt\n'), ((12947, 12970), 'matplotlib.pyplot.title', 'plt.title', (['"""model loss"""'], {}), "('model loss')\n", (12956, 12970), True, 'import matplotlib.pyplot as plt\n'), ((12971, 12989), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""loss"""'], {}), "('loss')\n", (12981, 12989), True, 'import matplotlib.pyplot as plt\n'), ((12990, 13018), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""10th iteration"""'], {}), "('10th iteration')\n", (13000, 13018), True, 'import matplotlib.pyplot as plt\n'), ((13019, 13073), 'matplotlib.pyplot.legend', 'plt.legend', (["['train', 'validation']"], {'loc': '"""upper right"""'}), "(['train', 'validation'], loc='upper right')\n", (13029, 13073), True, 'import matplotlib.pyplot as plt\n'), ((13074, 13105), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""loss_history.png"""'], {}), "('loss_history.png')\n", (13085, 13105), True, 'import matplotlib.pyplot as plt\n'), ((13106, 13116), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13114, 13116), True, 'import matplotlib.pyplot as plt\n'), ((13147, 13178), 'matplotlib.pyplot.plot', 'plt.plot', (['accuracy_history_test'], {}), '(accuracy_history_test)\n', (13155, 13178), True, 'import matplotlib.pyplot as plt\n'), ((13179, 13206), 'matplotlib.pyplot.title', 'plt.title', (['"""model accuracy"""'], {}), "('model accuracy')\n", (13188, 13206), True, 'import matplotlib.pyplot as plt\n'), ((13207, 13225), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""loss"""'], {}), "('loss')\n", (13217, 13225), True, 'import matplotlib.pyplot as plt\n'), ((13226, 13255), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""500th iteration"""'], {}), "('500th iteration')\n", (13236, 13255), True, 'import matplotlib.pyplot as plt\n'), ((13256, 13294), 'matplotlib.pyplot.legend', 'plt.legend', (["['test']"], {'loc': '"""upper left"""'}), "(['test'], loc='upper left')\n", (13266, 13294), True, 'import matplotlib.pyplot as plt\n'), ((13295, 13330), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""accuracy history.png"""'], {}), "('accuracy history.png')\n", (13306, 13330), True, 'import matplotlib.pyplot as plt\n'), ((13331, 13341), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13339, 13341), True, 'import matplotlib.pyplot as plt\n'), ((13473, 13495), 'yellowbrick.style.palettes.color_palette', 'color_palette', (['"""reset"""'], {}), "('reset')\n", (13486, 13495), False, 'from yellowbrick.style.palettes import PALETTES, SEQUENCES, color_palette\n'), ((13600, 13672), 'yellowbrick.features.pca.PCADecomposition', 'PCADecomposition', ([], {'scale': '(True)', 'proj_dim': '(3)', 'color': 'colors', 'size': '(1080, 720)'}), '(scale=True, proj_dim=3, color=colors, size=(1080, 720))\n', (13616, 13672), False, 'from yellowbrick.features.pca import PCADecomposition\n'), ((14971, 14987), 'numpy.array', 'np.array', (['y_test'], {}), '(y_test)\n', (14979, 14987), True, 'import numpy as np\n'), ((14995, 15011), 'numpy.array', 'np.array', (['y_pred'], {}), '(y_pred)\n', (15003, 15011), True, 'import numpy as np\n'), ((15077, 15109), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (15093, 15109), False, 'from sklearn.metrics import confusion_matrix\n'), ((15110, 15142), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (15129, 15142), True, 'import numpy as np\n'), ((15179, 15191), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (15189, 15191), True, 'import matplotlib.pyplot as plt\n'), ((15323, 15333), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15331, 15333), True, 'import matplotlib.pyplot as plt\n'), ((4799, 4819), 'math.degrees', 'math.degrees', (['degree'], {}), '(degree)\n', (4811, 4819), False, 'import math\n'), ((7259, 7376), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', ([], {'inputs': 'x', 'filters': '(16)', 'kernel_size': '[8, 8]', 'padding': '"""VALID"""', 'use_bias': '(True)', 'activation': 'tf.nn.relu'}), "(inputs=x, filters=16, kernel_size=[8, 8], padding='VALID',\n use_bias=True, activation=tf.nn.relu)\n", (7275, 7376), True, 'import tensorflow as tf\n'), ((7427, 7515), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'conv1', 'pool_size': '[2, 2]', 'strides': '(2)', 'padding': '"""VALID"""'}), "(inputs=conv1, pool_size=[2, 2], strides=2, padding=\n 'VALID')\n", (7450, 7515), True, 'import tensorflow as tf\n'), ((7610, 7731), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', ([], {'inputs': 'pool1', 'filters': '(7)', 'kernel_size': '[5, 5]', 'padding': '"""VALID"""', 'use_bias': '(True)', 'activation': 'tf.nn.relu'}), "(inputs=pool1, filters=7, kernel_size=[5, 5], padding=\n 'VALID', use_bias=True, activation=tf.nn.relu)\n", (7626, 7731), True, 'import tensorflow as tf\n'), ((7781, 7869), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'conv2', 'pool_size': '[2, 2]', 'strides': '(2)', 'padding': '"""VALID"""'}), "(inputs=conv2, pool_size=[2, 2], strides=2, padding=\n 'VALID')\n", (7804, 7869), True, 'import tensorflow as tf\n'), ((7922, 7958), 'tensorflow.reshape', 'tf.reshape', (['pool2', '[-1, 12 * 12 * 7]'], {}), '(pool2, [-1, 12 * 12 * 7])\n', (7932, 7958), True, 'import tensorflow as tf\n'), ((8015, 8091), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'fc1', 'units': '(256)', 'activation': 'tf.nn.relu', 'use_bias': '(True)'}), '(inputs=fc1, units=256, activation=tf.nn.relu, use_bias=True)\n', (8030, 8091), True, 'import tensorflow as tf\n'), ((8174, 8226), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'fc1', 'units': '(16)', 'use_bias': '(True)'}), '(inputs=fc1, units=16, use_bias=True)\n', (8189, 8226), True, 'import tensorflow as tf\n'), ((10044, 10056), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (10053, 10056), True, 'import numpy as np\n'), ((10071, 10085), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (10083, 10085), True, 'import matplotlib.pyplot as plt\n'), ((10090, 10108), 'matplotlib.pyplot.bar', 'plt.bar', (['x', 'angles'], {}), '(x, angles)\n', (10097, 10108), True, 'import matplotlib.pyplot as plt\n'), ((10113, 10157), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', "('10%', '20%', '40%', '180%')"], {}), "(x, ('10%', '20%', '40%', '180%'))\n", (10123, 10157), True, 'import matplotlib.pyplot as plt\n'), ((11065, 11077), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (11075, 11077), True, 'import tensorflow as tf\n'), ((14338, 14382), 'matplotlib.pyplot.xticks', 'plt.xticks', (['tick_marks', 'classes'], {'rotation': '(45)'}), '(tick_marks, classes, rotation=45)\n', (14348, 14382), True, 'import matplotlib.pyplot as plt\n'), ((14387, 14418), 'matplotlib.pyplot.yticks', 'plt.yticks', (['tick_marks', 'classes'], {}), '(tick_marks, classes)\n', (14397, 14418), True, 'import matplotlib.pyplot as plt\n'), ((14423, 14473), 'matplotlib.pyplot.imshow', 'plt.imshow', (['cm'], {'interpolation': '"""nearest"""', 'cmap': 'cmap'}), "(cm, interpolation='nearest', cmap=cmap)\n", (14433, 14473), True, 'import matplotlib.pyplot as plt\n'), ((14478, 14494), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (14487, 14494), True, 'import matplotlib.pyplot as plt\n'), ((14499, 14513), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (14511, 14513), True, 'import matplotlib.pyplot as plt\n'), ((14823, 14847), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True label"""'], {}), "('True label')\n", (14833, 14847), True, 'import matplotlib.pyplot as plt\n'), ((14852, 14881), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted label"""'], {}), "('Predicted label')\n", (14862, 14881), True, 'import matplotlib.pyplot as plt\n'), ((14886, 14904), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (14902, 14904), True, 'import matplotlib.pyplot as plt\n'), ((14909, 14944), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Confusion_Matrix.png"""'], {}), "('Confusion_Matrix.png')\n", (14920, 14944), True, 'import matplotlib.pyplot as plt\n'), ((1509, 1563), 'os.path.join', 'os.path.join', (['"""dataset"""', 'folder', 'category', '"""poses.txt"""'], {}), "('dataset', folder, category, 'poses.txt')\n", (1521, 1563), False, 'import glob, os\n'), ((1754, 1804), 'os.path.join', 'os.path.join', (['"""dataset"""', 'folder', 'category', '"""*.png"""'], {}), "('dataset', folder, category, '*.png')\n", (1766, 1804), False, 'import glob, os\n'), ((1821, 1836), 'glob.glob', 'glob.glob', (['path'], {}), '(path)\n', (1830, 1836), False, 'import glob, os\n'), ((4763, 4785), 'math.acos', 'math.acos', (['dot_product'], {}), '(dot_product)\n', (4772, 4785), False, 'import math\n'), ((5011, 5048), 'numpy.random.randint', 'np.random.randint', (['(5)'], {'size': 'batch_size'}), '(5, size=batch_size)\n', (5028, 5048), True, 'import numpy as np\n'), ((5076, 5130), 'numpy.random.randint', 'np.random.randint', (['train_set.shape[1]'], {'size': 'batch_size'}), '(train_set.shape[1], size=batch_size)\n', (5093, 5130), True, 'import numpy as np\n'), ((9861, 9877), 'numpy.array', 'np.array', (['angles'], {}), '(angles)\n', (9869, 9877), True, 'import numpy as np\n'), ((10195, 10216), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (10206, 10216), True, 'import matplotlib.pyplot as plt\n'), ((10225, 10239), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (10234, 10239), True, 'import matplotlib.pyplot as plt\n'), ((10258, 10268), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10266, 10268), True, 'import matplotlib.pyplot as plt\n'), ((10837, 10856), 'tensorflow.square', 'tf.square', (['diff_pos'], {}), '(diff_pos)\n', (10846, 10856), True, 'import tensorflow as tf\n'), ((10921, 10972), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (10943, 10972), True, 'import tensorflow as tf\n'), ((2252, 2274), 'matplotlib.image.imread', 'mpimg.imread', (['filename'], {}), '(filename)\n', (2264, 2274), True, 'import matplotlib.image as mpimg\n'), ((4633, 4648), 'numpy.array', 'np.array', (['pose1'], {}), '(pose1)\n', (4641, 4648), True, 'import numpy as np\n'), ((4650, 4665), 'numpy.array', 'np.array', (['pose2'], {}), '(pose2)\n', (4658, 4665), True, 'import numpy as np\n'), ((6138, 6166), 'random.choice', 'random.choice', (['[True, False]'], {}), '([True, False])\n', (6151, 6166), False, 'import random\n'), ((7160, 7175), 'numpy.array', 'np.array', (['batch'], {}), '(batch)\n', (7168, 7175), True, 'import numpy as np\n'), ((8447, 8496), 'sklearn.neighbors.NearestNeighbors', 'NearestNeighbors', ([], {'n_neighbors': '(1)', 'algorithm': '"""auto"""'}), "(n_neighbors=1, algorithm='auto')\n", (8463, 8496), False, 'from sklearn.neighbors import NearestNeighbors\n'), ((12811, 12827), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (12825, 12827), True, 'import tensorflow as tf\n'), ((6609, 6629), 'numpy.random.randint', 'np.random.randint', (['(5)'], {}), '(5)\n', (6626, 6629), True, 'import numpy as np\n'), ((6764, 6784), 'numpy.random.randint', 'np.random.randint', (['(5)'], {}), '(5)\n', (6781, 6784), True, 'import numpy as np\n'), ((10718, 10737), 'tensorflow.square', 'tf.square', (['diff_neg'], {}), '(diff_neg)\n', (10727, 10737), True, 'import tensorflow as tf\n'), ((10760, 10779), 'tensorflow.square', 'tf.square', (['diff_pos'], {}), '(diff_pos)\n', (10769, 10779), True, 'import tensorflow as tf\n')]
|
r"""
Functions for the infinite sheds bifacial irradiance model.
"""
import numpy as np
import pandas as pd
from pvlib.tools import cosd, sind, tand
from pvlib.bifacial import utils
from pvlib.shading import masking_angle
from pvlib.irradiance import beam_component, aoi
def _vf_ground_sky_integ(surface_tilt, surface_azimuth, gcr, height,
pitch, max_rows=10, npoints=100):
"""
Integrated and per-point view factors from the ground to the sky at points
between interior rows of the array.
Parameters
----------
surface_tilt : numeric
Surface tilt angle in degrees from horizontal, e.g., surface facing up
= 0, surface facing horizon = 90. [degree]
surface_azimuth : numeric
Surface azimuth angles in decimal degrees east of north
(e.g. North = 0, South = 180, East = 90, West = 270).
``surface_azimuth`` must be >=0 and <=360.
gcr : float
Ratio of row slant length to row spacing (pitch). [unitless]
height : float
Height of the center point of the row above the ground; must be in the
same units as ``pitch``.
pitch : float
Distance between two rows. Must be in the same units as ``height``.
max_rows : int, default 10
Maximum number of rows to consider in front and behind the current row.
npoints : int, default 100
Number of points used to discretize distance along the ground.
Returns
-------
fgnd_sky : float
Integration of view factor over the length between adjacent, interior
rows. [unitless]
fz : ndarray
Fraction of distance from the previous row to the next row. [unitless]
fz_sky : ndarray
View factors at discrete points between adjacent, interior rows.
[unitless]
"""
# TODO: vectorize over surface_tilt
# Abuse utils._vf_ground_sky_2d by supplying surface_tilt in place
# of a signed rotation. This is OK because
# 1) z span the full distance between 2 rows, and
# 2) max_rows is set to be large upstream, and
# 3) _vf_ground_sky_2d considers [-max_rows, +max_rows]
# The VFs to the sky will thus be symmetric around z=0.5
z = np.linspace(0, 1, npoints)
rotation = np.atleast_1d(surface_tilt)
fz_sky = np.zeros((len(rotation), npoints))
for k, r in enumerate(rotation):
vf, _ = utils._vf_ground_sky_2d(z, r, gcr, pitch, height, max_rows)
fz_sky[k, :] = vf
# calculate the integrated view factor for all of the ground between rows
return np.trapz(fz_sky, z, axis=1)
def _poa_ground_shadows(poa_ground, f_gnd_beam, df, vf_gnd_sky):
"""
Reduce ground-reflected irradiance to the tilted plane (poa_ground) to
account for shadows on the ground.
Parameters
----------
poa_ground : numeric
Ground reflected irradiance on the tilted surface, assuming full GHI
illumination on all of the ground. [W/m^2]
f_gnd_beam : numeric
Fraction of the distance between rows that is illuminated (unshaded).
[unitless]
df : numeric
Diffuse fraction, the ratio of DHI to GHI. [unitless]
vf_gnd_sky : numeric
View factor from the ground to the sky, integrated along the distance
between rows. [unitless]
Returns
-------
poa_gnd_sky : numeric
Adjusted ground-reflected irradiance accounting for shadows on the
ground. [W/m^2]
"""
return poa_ground * (f_gnd_beam*(1 - df) + df*vf_gnd_sky)
def _vf_row_sky_integ(f_x, surface_tilt, gcr, npoints=100):
"""
Integrated view factors from the shaded and unshaded parts of
the row slant height to the sky.
Parameters
----------
f_x : numeric
Fraction of row slant height from the bottom that is shaded. [unitless]
surface_tilt : numeric
Surface tilt angle in degrees from horizontal, e.g., surface facing up
= 0, surface facing horizon = 90. [degree]
gcr : float
Ratio of row slant length to row spacing (pitch). [unitless]
npoints : int, default 100
Number of points for integration. [unitless]
Returns
-------
vf_shade_sky_integ : numeric
Integrated view factor from the shaded part of the row to the sky.
[unitless]
vf_noshade_sky_integ : numeric
Integrated view factor from the unshaded part of the row to the sky.
[unitless]
Notes
-----
The view factor to the sky at a point x along the row slant height is
given by
.. math ::
\\large{f_{sky} = \frac{1}{2} \\left(\\cos\\left(\\psi_t\\right) +
\\cos \\left(\\beta\\right) \\right)
where :math:`\\psi_t` is the angle from horizontal of the line from point
x to the top of the facing row, and :math:`\\beta` is the surface tilt.
View factors are integrated separately over shaded and unshaded portions
of the row slant height.
"""
# handle Series inputs
surface_tilt = np.array(surface_tilt)
cst = cosd(surface_tilt)
# shaded portion
x = np.linspace(0, f_x, num=npoints)
psi_t_shaded = masking_angle(surface_tilt, gcr, x)
y = 0.5 * (cosd(psi_t_shaded) + cst)
# integrate view factors from each point in the discretization. This is an
# improvement over the algorithm described in [2]
vf_shade_sky_integ = np.trapz(y, x, axis=0)
# unshaded portion
x = np.linspace(f_x, 1., num=npoints)
psi_t_unshaded = masking_angle(surface_tilt, gcr, x)
y = 0.5 * (cosd(psi_t_unshaded) + cst)
vf_noshade_sky_integ = np.trapz(y, x, axis=0)
return vf_shade_sky_integ, vf_noshade_sky_integ
def _poa_sky_diffuse_pv(f_x, dhi, vf_shade_sky_integ, vf_noshade_sky_integ):
"""
Sky diffuse POA from integrated view factors combined for both shaded and
unshaded parts of the surface.
Parameters
----------
f_x : numeric
Fraction of row slant height from the bottom that is shaded. [unitless]
dhi : numeric
Diffuse horizontal irradiance (DHI). [W/m^2]
vf_shade_sky_integ : numeric
Integrated view factor from the shaded part of the row to the sky.
[unitless]
vf_noshade_sky_integ : numeric
Integrated view factor from the unshaded part of the row to the sky.
[unitless]
Returns
-------
poa_sky_diffuse_pv : numeric
Total sky diffuse irradiance incident on the PV surface. [W/m^2]
"""
return dhi * (f_x * vf_shade_sky_integ + (1 - f_x) * vf_noshade_sky_integ)
def _ground_angle(x, surface_tilt, gcr):
"""
Angle from horizontal of the line from a point x on the row slant length
to the bottom of the facing row.
The angles are clockwise from horizontal, rather than the usual
counterclockwise direction.
Parameters
----------
x : numeric
fraction of row slant length from bottom, ``x = 0`` is at the row
bottom, ``x = 1`` is at the top of the row.
surface_tilt : numeric
Surface tilt angle in degrees from horizontal, e.g., surface facing up
= 0, surface facing horizon = 90. [degree]
gcr : float
ground coverage ratio, ratio of row slant length to row spacing.
[unitless]
Returns
-------
psi : numeric
Angle [degree].
"""
# : \\ \
# : \\ \
# : \\ \
# : \\ \ facing row
# : \\.___________\
# : \ ^*-. psi \
# : \ x *-. \
# : \ v *-.\
# : \<-----P---->\
x1 = x * sind(surface_tilt)
x2 = (x * cosd(surface_tilt) + 1 / gcr)
psi = np.arctan2(x1, x2) # do this first because it handles 0 / 0
return np.rad2deg(psi)
def _vf_row_ground(x, surface_tilt, gcr):
"""
View factor from a point x on the row to the ground.
Parameters
----------
x : numeric
Fraction of row slant height from the bottom. [unitless]
surface_tilt : numeric
Surface tilt angle in degrees from horizontal, e.g., surface facing up
= 0, surface facing horizon = 90. [degree]
gcr : float
Ground coverage ratio, ratio of row slant length to row spacing.
[unitless]
Returns
-------
vf : numeric
View factor from the point at x to the ground. [unitless]
"""
cst = cosd(surface_tilt)
# angle from horizontal at the point x on the row slant height to the
# bottom of the facing row
psi_t_shaded = _ground_angle(x, surface_tilt, gcr)
# view factor from the point on the row to the ground
return 0.5 * (cosd(psi_t_shaded) - cst)
def _vf_row_ground_integ(f_x, surface_tilt, gcr, npoints=100):
"""
View factors to the ground from shaded and unshaded parts of a row.
Parameters
----------
f_x : numeric
Fraction of row slant height from the bottom that is shaded. [unitless]
surface_tilt : numeric
Surface tilt angle in degrees from horizontal, e.g., surface facing up
= 0, surface facing horizon = 90. [degree]
gcr : float
Ground coverage ratio, ratio of row slant length to row spacing.
[unitless]
npoints : int, default 100
Number of points for integration. [unitless]
Returns
-------
vf_shade_ground_integ : numeric
View factor from the shaded portion of the row to the ground.
[unitless]
vf_noshade_ground_integ : numeric
View factor from the unshaded portion of the row to the ground.
[unitless]
Notes
-----
The view factor to the ground at a point x along the row slant height is
given by
.. math ::
\\large{f_{gr} = \frac{1}{2} \\left(\\cos\\left(\\psi_t\\right) -
\\cos \\left(\\beta\\right) \\right)
where :math:`\\psi_t` is the angle from horizontal of the line from point
x to the bottom of the facing row, and :math:`\\beta` is the surface tilt.
Each view factor is integrated over the relevant portion of the row
slant height.
"""
# handle Series inputs
surface_tilt = np.array(surface_tilt)
# shaded portion of row slant height
x = np.linspace(0, f_x, num=npoints)
# view factor from the point on the row to the ground
y = _vf_row_ground(x, surface_tilt, gcr)
# integrate view factors along the shaded portion of the row slant height.
# This is an improvement over the algorithm described in [2]
vf_shade_ground_integ = np.trapz(y, x, axis=0)
# unshaded portion of row slant height
x = np.linspace(f_x, 1., num=npoints)
# view factor from the point on the row to the ground
y = _vf_row_ground(x, surface_tilt, gcr)
# integrate view factors along the unshaded portion.
# This is an improvement over the algorithm described in [2]
vf_noshade_ground_integ = np.trapz(y, x, axis=0)
return vf_shade_ground_integ, vf_noshade_ground_integ
def _poa_ground_pv(f_x, poa_ground, f_gnd_pv_shade, f_gnd_pv_noshade):
"""
Reduce ground-reflected irradiance to account for limited view of the
ground from the row surface.
Parameters
----------
f_x : numeric
Fraction of row slant height from the bottom that is shaded. [unitless]
poa_ground : numeric
Ground-reflected irradiance that would reach the row surface if the
full ground was visible. poa_gnd_sky accounts for limited view of the
sky from the ground. [W/m^2]
f_gnd_pv_shade : numeric
fraction of ground visible from shaded part of PV surface. [unitless]
f_gnd_pv_noshade : numeric
fraction of ground visible from unshaded part of PV surface. [unitless]
Returns
-------
numeric
Ground diffuse irradiance on the row plane. [W/m^2]
"""
return poa_ground * (f_x * f_gnd_pv_shade + (1 - f_x) * f_gnd_pv_noshade)
def _shaded_fraction(solar_zenith, solar_azimuth, surface_tilt,
surface_azimuth, gcr):
"""
Calculate fraction (from the bottom) of row slant height that is shaded
from direct irradiance by the row in front toward the sun.
See [1], Eq. 14 and also [2], Eq. 32.
.. math::
F_x = \\max \\left( 0, \\min \\left(\\frac{\\text{GCR} \\cos \\theta
+ \\left( \\text{GCR} \\sin \\theta - \\tan \\beta_{c} \\right)
\\tan Z - 1}
{\\text{GCR} \\left( \\cos \\theta + \\sin \\theta \\tan Z \\right)},
1 \\right) \\right)
Parameters
----------
solar_zenith : numeric
Apparent (refraction-corrected) solar zenith. [degrees]
solar_azimuth : numeric
Solar azimuth. [degrees]
surface_tilt : numeric
Row tilt from horizontal, e.g. surface facing up = 0, surface facing
horizon = 90. [degrees]
surface_azimuth : numeric
Azimuth angle of the row surface. North=0, East=90, South=180,
West=270. [degrees]
gcr : numeric
Ground coverage ratio, which is the ratio of row slant length to row
spacing (pitch). [unitless]
Returns
-------
f_x : numeric
Fraction of row slant height from the bottom that is shaded from
direct irradiance.
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>., and Newmiller,
J. "Bifacial Performance Modeling in Large Arrays". 2019 IEEE 46th
Photovoltaic Specialists Conference (PVSC), 2019, pp. 1282-1287.
:doi:`10.1109/PVSC40753.2019.8980572`.
.. [2] <NAME> and <NAME>, "Slope-Aware Backtracking for
Single-Axis Trackers", Technical Report NREL/TP-5K00-76626, July 2020.
https://www.nrel.gov/docs/fy20osti/76626.pdf
"""
tan_phi = utils._solar_projection_tangent(
solar_zenith, solar_azimuth, surface_azimuth)
# length of shadow behind a row as a fraction of pitch
x = gcr * (sind(surface_tilt) * tan_phi + cosd(surface_tilt))
f_x = 1 - 1. / x
# set f_x to be 1 when sun is behind the array
ao = aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth)
f_x = np.where(ao < 90, f_x, 1.)
# when x < 1, the shadow is not long enough to fall on the row surface
f_x = np.where(x > 1., f_x, 0.)
return f_x
def get_irradiance_poa(surface_tilt, surface_azimuth, solar_zenith,
solar_azimuth, gcr, height, pitch, ghi, dhi, dni,
albedo, iam=1.0, npoints=100):
r"""
Calculate plane-of-array (POA) irradiance on one side of a row of modules.
The infinite sheds model [1] assumes the PV system comprises parallel,
evenly spaced rows on a level, horizontal surface. Rows can be on fixed
racking or single axis trackers. The model calculates irradiance at a
location far from the ends of any rows, in effect, assuming that the
rows (sheds) are infinitely long.
POA irradiance components include direct, diffuse and global (total).
Irradiance values are reduced to account for reflection of direct light,
but are not adjusted for solar spectrum or reduced by a module's
bifaciality factor.
Parameters
----------
surface_tilt : numeric
Tilt of the surface from horizontal. Must be between 0 and 180. For
example, for a fixed tilt module mounted at 30 degrees from
horizontal, use ``surface_tilt=30`` to get front-side irradiance and
``surface_tilt=150`` to get rear-side irradiance. [degree]
surface_azimuth : numeric
Surface azimuth in decimal degrees east of north
(e.g. North = 0, South = 180, East = 90, West = 270). [degree]
solar_zenith : numeric
Refraction-corrected solar zenith. [degree]
solar_azimuth : numeric
Solar azimuth. [degree]
gcr : float
Ground coverage ratio, ratio of row slant length to row spacing.
[unitless]
height : float
Height of the center point of the row above the ground; must be in the
same units as ``pitch``.
pitch : float
Distance between two rows; must be in the same units as ``height``.
ghi : numeric
Global horizontal irradiance. [W/m2]
dhi : numeric
Diffuse horizontal irradiance. [W/m2]
dni : numeric
Direct normal irradiance. [W/m2]
albedo : numeric
Surface albedo. [unitless]
iam : numeric, default 1.0
Incidence angle modifier, the fraction of direct irradiance incident
on the surface that is not reflected away. [unitless]
npoints : int, default 100
Number of points used to discretize distance along the ground.
Returns
-------
output : dict or DataFrame
Output is a DataFrame when input ghi is a Series. See Notes for
descriptions of content.
Notes
-----
Input parameters ``height`` and ``pitch`` must have the same unit.
``output`` always includes:
- ``poa_global`` : total POA irradiance. [W/m^2]
- ``poa_diffuse`` : total diffuse POA irradiance from all sources. [W/m^2]
- ``poa_direct`` : total direct POA irradiance. [W/m^2]
- ``poa_sky_diffuse`` : total sky diffuse irradiance on the plane of array.
[W/m^2]
- ``poa_ground_diffuse`` : total ground-reflected diffuse irradiance on the
plane of array. [W/m^2]
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>., and Newmiller,
J. "Bifacial Performance Modeling in Large Arrays". 2019 IEEE 46th
Photovoltaic Specialists Conference (PVSC), 2019, pp. 1282-1287.
:doi:`10.1109/PVSC40753.2019.8980572`.
See also
--------
get_irradiance
"""
# Calculate some geometric quantities
# rows to consider in front and behind current row
# ensures that view factors to the sky are computed to within 5 degrees
# of the horizon
max_rows = np.ceil(height / (pitch * tand(5)))
# fraction of ground between rows that is illuminated accounting for
# shade from panels. [1], Eq. 4
f_gnd_beam = utils._unshaded_ground_fraction(
surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, gcr)
# integrated view factor from the ground to the sky, integrated between
# adjacent rows interior to the array
# method differs from [1], Eq. 7 and Eq. 8; height is defined at row
# center rather than at row lower edge as in [1].
vf_gnd_sky = _vf_ground_sky_integ(
surface_tilt, surface_azimuth, gcr, height, pitch, max_rows, npoints)
# fraction of row slant height that is shaded from direct irradiance
f_x = _shaded_fraction(solar_zenith, solar_azimuth, surface_tilt,
surface_azimuth, gcr)
# Integrated view factors to the sky from the shaded and unshaded parts of
# the row slant height
# Differs from [1] Eq. 15 and Eq. 16. Here, we integrate over each
# interval (shaded or unshaded) rather than averaging values at each
# interval's end points.
vf_shade_sky, vf_noshade_sky = _vf_row_sky_integ(
f_x, surface_tilt, gcr, npoints)
# view factors from the ground to shaded and unshaded portions of the row
# slant height
# Differs from [1] Eq. 17 and Eq. 18. Here, we integrate over each
# interval (shaded or unshaded) rather than averaging values at each
# interval's end points.
f_gnd_pv_shade, f_gnd_pv_noshade = _vf_row_ground_integ(
f_x, surface_tilt, gcr, npoints)
# Total sky diffuse received by both shaded and unshaded portions
poa_sky_pv = _poa_sky_diffuse_pv(
f_x, dhi, vf_shade_sky, vf_noshade_sky)
# irradiance reflected from the ground before accounting for shadows
# and restricted views
# this is a deviation from [1], because the row to ground view factor
# is accounted for in a different manner
ground_diffuse = ghi * albedo
# diffuse fraction
diffuse_fraction = np.clip(dhi / ghi, 0., 1.)
# make diffuse fraction 0 when ghi is small
diffuse_fraction = np.where(ghi < 0.0001, 0., diffuse_fraction)
# Reduce ground-reflected irradiance because other rows in the array
# block irradiance from reaching the ground.
# [2], Eq. 9
ground_diffuse = _poa_ground_shadows(
ground_diffuse, f_gnd_beam, diffuse_fraction, vf_gnd_sky)
# Ground-reflected irradiance on the row surface accounting for
# the view to the ground. This deviates from [1], Eq. 10, 11 and
# subsequent. Here, the row to ground view factor is computed. In [1],
# the usual ground-reflected irradiance includes the single row to ground
# view factor (1 - cos(tilt))/2, and Eq. 10, 11 and later multiply
# this quantity by a ratio of view factors.
poa_gnd_pv = _poa_ground_pv(
f_x, ground_diffuse, f_gnd_pv_shade, f_gnd_pv_noshade)
# add sky and ground-reflected irradiance on the row by irradiance
# component
poa_diffuse = poa_gnd_pv + poa_sky_pv
# beam on plane, make an array for consistency with poa_diffuse
poa_beam = np.atleast_1d(beam_component(
surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, dni))
poa_direct = poa_beam * (1 - f_x) * iam # direct only on the unshaded part
poa_global = poa_direct + poa_diffuse
output = {
'poa_global': poa_global, 'poa_direct': poa_direct,
'poa_diffuse': poa_diffuse, 'poa_ground_diffuse': poa_gnd_pv,
'poa_sky_diffuse': poa_sky_pv}
if isinstance(poa_global, pd.Series):
output = pd.DataFrame(output)
return output
def get_irradiance(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,
gcr, height, pitch, ghi, dhi, dni,
albedo, iam_front=1.0, iam_back=1.0,
bifaciality=0.8, shade_factor=-0.02,
transmission_factor=0, npoints=100):
"""
Get front and rear irradiance using the infinite sheds model.
The infinite sheds model [1] assumes the PV system comprises parallel,
evenly spaced rows on a level, horizontal surface. Rows can be on fixed
racking or single axis trackers. The model calculates irradiance at a
location far from the ends of any rows, in effect, assuming that the
rows (sheds) are infinitely long.
The model accounts for the following effects:
- restricted view of the sky from module surfaces due to the nearby rows.
- restricted view of the ground from module surfaces due to nearby rows.
- restricted view of the sky from the ground due to rows.
- shading of module surfaces by nearby rows.
- shading of rear cells of a module by mounting structure and by
module features.
The model implicitly assumes that diffuse irradiance from the sky is
isotropic, and that module surfaces do not allow irradiance to transmit
through the module to the ground through gaps between cells.
Parameters
----------
surface_tilt : numeric
Tilt from horizontal of the front-side surface. [degree]
surface_azimuth : numeric
Surface azimuth in decimal degrees east of north
(e.g. North = 0, South = 180, East = 90, West = 270). [degree]
solar_zenith : numeric
Refraction-corrected solar zenith. [degree]
solar_azimuth : numeric
Solar azimuth. [degree]
gcr : float
Ground coverage ratio, ratio of row slant length to row spacing.
[unitless]
height : float
Height of the center point of the row above the ground; must be in the
same units as ``pitch``.
pitch : float
Distance between two rows; must be in the same units as ``height``.
ghi : numeric
Global horizontal irradiance. [W/m2]
dhi : numeric
Diffuse horizontal irradiance. [W/m2]
dni : numeric
Direct normal irradiance. [W/m2]
albedo : numeric
Surface albedo. [unitless]
iam_front : numeric, default 1.0
Incidence angle modifier, the fraction of direct irradiance incident
on the front surface that is not reflected away. [unitless]
iam_back : numeric, default 1.0
Incidence angle modifier, the fraction of direct irradiance incident
on the back surface that is not reflected away. [unitless]
bifaciality : numeric, default 0.8
Ratio of the efficiency of the module's rear surface to the efficiency
of the front surface. [unitless]
shade_factor : numeric, default -0.02
Fraction of back surface irradiance that is blocked by array mounting
structures. Negative value is a reduction in back irradiance.
[unitless]
transmission_factor : numeric, default 0.0
Fraction of irradiance on the back surface that does not reach the
module's cells due to module features such as busbars, junction box,
etc. A negative value is a reduction in back irradiance. [unitless]
npoints : int, default 100
Number of points used to discretize distance along the ground.
Returns
-------
output : dict or DataFrame
Output is a DataFrame when input ghi is a Series. See Notes for
descriptions of content.
Notes
-----
``output`` includes:
- ``poa_global`` : total irradiance reaching the module cells from both
front and back surfaces. [W/m^2]
- ``poa_front`` : total irradiance reaching the module cells from the front
surface. [W/m^2]
- ``poa_back`` : total irradiance reaching the module cells from the back
surface. [W/m^2]
- ``poa_front_direct`` : direct irradiance reaching the module cells from
the front surface. [W/m^2]
- ``poa_front_diffuse`` : total diffuse irradiance reaching the module
cells from the front surface. [W/m^2]
- ``poa_front_sky_diffuse`` : sky diffuse irradiance reaching the module
cells from the front surface. [W/m^2]
- ``poa_front_ground_diffuse`` : ground-reflected diffuse irradiance
reaching the module cells from the front surface. [W/m^2]
- ``poa_back_direct`` : direct irradiance reaching the module cells from
the back surface. [W/m^2]
- ``poa_back_diffuse`` : total diffuse irradiance reaching the module
cells from the back surface. [W/m^2]
- ``poa_back_sky_diffuse`` : sky diffuse irradiance reaching the module
cells from the back surface. [W/m^2]
- ``poa_back_ground_diffuse`` : ground-reflected diffuse irradiance
reaching the module cells from the back surface. [W/m^2]
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>., and Newmiller,
J. "Bifacial Performance Modeling in Large Arrays". 2019 IEEE 46th
Photovoltaic Specialists Conference (PVSC), 2019, pp. 1282-1287.
:doi:`10.1109/PVSC40753.2019.8980572`.
See also
--------
get_irradiance_poa
"""
# backside is rotated and flipped relative to front
backside_tilt, backside_sysaz = _backside(surface_tilt, surface_azimuth)
# front side POA irradiance
irrad_front = get_irradiance_poa(
surface_tilt=surface_tilt, surface_azimuth=surface_azimuth,
solar_zenith=solar_zenith, solar_azimuth=solar_azimuth,
gcr=gcr, height=height, pitch=pitch, ghi=ghi, dhi=dhi, dni=dni,
albedo=albedo, iam=iam_front, npoints=npoints)
# back side POA irradiance
irrad_back = get_irradiance_poa(
surface_tilt=backside_tilt, surface_azimuth=backside_sysaz,
solar_zenith=solar_zenith, solar_azimuth=solar_azimuth,
gcr=gcr, height=height, pitch=pitch, ghi=ghi, dhi=dhi, dni=dni,
albedo=albedo, iam=iam_back, npoints=npoints)
colmap_front = {
'poa_global': 'poa_front',
'poa_direct': 'poa_front_direct',
'poa_diffuse': 'poa_front_diffuse',
'poa_sky_diffuse': 'poa_front_sky_diffuse',
'poa_ground_diffuse': 'poa_front_ground_diffuse',
}
colmap_back = {
'poa_global': 'poa_back',
'poa_direct': 'poa_back_direct',
'poa_diffuse': 'poa_back_diffuse',
'poa_sky_diffuse': 'poa_back_sky_diffuse',
'poa_ground_diffuse': 'poa_back_ground_diffuse',
}
if isinstance(ghi, pd.Series):
irrad_front = irrad_front.rename(columns=colmap_front)
irrad_back = irrad_back.rename(columns=colmap_back)
output = pd.concat([irrad_front, irrad_back], axis=1)
else:
for old_key, new_key in colmap_front.items():
irrad_front[new_key] = irrad_front.pop(old_key)
for old_key, new_key in colmap_back.items():
irrad_back[new_key] = irrad_back.pop(old_key)
irrad_front.update(irrad_back)
output = irrad_front
effects = (1 + shade_factor) * (1 + transmission_factor)
output['poa_global'] = output['poa_front'] + \
output['poa_back'] * bifaciality * effects
return output
def _backside(tilt, surface_azimuth):
backside_tilt = 180. - tilt
backside_sysaz = (180. + surface_azimuth) % 360.
return backside_tilt, backside_sysaz
|
[
"numpy.arctan2",
"numpy.clip",
"pandas.DataFrame",
"pvlib.irradiance.aoi",
"pvlib.bifacial.utils._unshaded_ground_fraction",
"numpy.linspace",
"pvlib.shading.masking_angle",
"pandas.concat",
"pvlib.tools.tand",
"numpy.trapz",
"pvlib.irradiance.beam_component",
"pvlib.bifacial.utils._vf_ground_sky_2d",
"pvlib.tools.cosd",
"pvlib.bifacial.utils._solar_projection_tangent",
"numpy.rad2deg",
"numpy.where",
"numpy.array",
"pvlib.tools.sind",
"numpy.atleast_1d"
] |
[((2206, 2232), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'npoints'], {}), '(0, 1, npoints)\n', (2217, 2232), True, 'import numpy as np\n'), ((2248, 2275), 'numpy.atleast_1d', 'np.atleast_1d', (['surface_tilt'], {}), '(surface_tilt)\n', (2261, 2275), True, 'import numpy as np\n'), ((2552, 2579), 'numpy.trapz', 'np.trapz', (['fz_sky', 'z'], {'axis': '(1)'}), '(fz_sky, z, axis=1)\n', (2560, 2579), True, 'import numpy as np\n'), ((4983, 5005), 'numpy.array', 'np.array', (['surface_tilt'], {}), '(surface_tilt)\n', (4991, 5005), True, 'import numpy as np\n'), ((5016, 5034), 'pvlib.tools.cosd', 'cosd', (['surface_tilt'], {}), '(surface_tilt)\n', (5020, 5034), False, 'from pvlib.tools import cosd, sind, tand\n'), ((5064, 5096), 'numpy.linspace', 'np.linspace', (['(0)', 'f_x'], {'num': 'npoints'}), '(0, f_x, num=npoints)\n', (5075, 5096), True, 'import numpy as np\n'), ((5116, 5151), 'pvlib.shading.masking_angle', 'masking_angle', (['surface_tilt', 'gcr', 'x'], {}), '(surface_tilt, gcr, x)\n', (5129, 5151), False, 'from pvlib.shading import masking_angle\n'), ((5351, 5373), 'numpy.trapz', 'np.trapz', (['y', 'x'], {'axis': '(0)'}), '(y, x, axis=0)\n', (5359, 5373), True, 'import numpy as np\n'), ((5405, 5439), 'numpy.linspace', 'np.linspace', (['f_x', '(1.0)'], {'num': 'npoints'}), '(f_x, 1.0, num=npoints)\n', (5416, 5439), True, 'import numpy as np\n'), ((5460, 5495), 'pvlib.shading.masking_angle', 'masking_angle', (['surface_tilt', 'gcr', 'x'], {}), '(surface_tilt, gcr, x)\n', (5473, 5495), False, 'from pvlib.shading import masking_angle\n'), ((5566, 5588), 'numpy.trapz', 'np.trapz', (['y', 'x'], {'axis': '(0)'}), '(y, x, axis=0)\n', (5574, 5588), True, 'import numpy as np\n'), ((7656, 7674), 'numpy.arctan2', 'np.arctan2', (['x1', 'x2'], {}), '(x1, x2)\n', (7666, 7674), True, 'import numpy as np\n'), ((7728, 7743), 'numpy.rad2deg', 'np.rad2deg', (['psi'], {}), '(psi)\n', (7738, 7743), True, 'import numpy as np\n'), ((8357, 8375), 'pvlib.tools.cosd', 'cosd', (['surface_tilt'], {}), '(surface_tilt)\n', (8361, 8375), False, 'from pvlib.tools import cosd, sind, tand\n'), ((10089, 10111), 'numpy.array', 'np.array', (['surface_tilt'], {}), '(surface_tilt)\n', (10097, 10111), True, 'import numpy as np\n'), ((10161, 10193), 'numpy.linspace', 'np.linspace', (['(0)', 'f_x'], {'num': 'npoints'}), '(0, f_x, num=npoints)\n', (10172, 10193), True, 'import numpy as np\n'), ((10469, 10491), 'numpy.trapz', 'np.trapz', (['y', 'x'], {'axis': '(0)'}), '(y, x, axis=0)\n', (10477, 10491), True, 'import numpy as np\n'), ((10544, 10578), 'numpy.linspace', 'np.linspace', (['f_x', '(1.0)'], {'num': 'npoints'}), '(f_x, 1.0, num=npoints)\n', (10555, 10578), True, 'import numpy as np\n'), ((10833, 10855), 'numpy.trapz', 'np.trapz', (['y', 'x'], {'axis': '(0)'}), '(y, x, axis=0)\n', (10841, 10855), True, 'import numpy as np\n'), ((13659, 13736), 'pvlib.bifacial.utils._solar_projection_tangent', 'utils._solar_projection_tangent', (['solar_zenith', 'solar_azimuth', 'surface_azimuth'], {}), '(solar_zenith, solar_azimuth, surface_azimuth)\n', (13690, 13736), False, 'from pvlib.bifacial import utils\n'), ((13952, 14015), 'pvlib.irradiance.aoi', 'aoi', (['surface_tilt', 'surface_azimuth', 'solar_zenith', 'solar_azimuth'], {}), '(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth)\n', (13955, 14015), False, 'from pvlib.irradiance import beam_component, aoi\n'), ((14026, 14053), 'numpy.where', 'np.where', (['(ao < 90)', 'f_x', '(1.0)'], {}), '(ao < 90, f_x, 1.0)\n', (14034, 14053), True, 'import numpy as np\n'), ((14138, 14165), 'numpy.where', 'np.where', (['(x > 1.0)', 'f_x', '(0.0)'], {}), '(x > 1.0, f_x, 0.0)\n', (14146, 14165), True, 'import numpy as np\n'), ((17941, 18041), 'pvlib.bifacial.utils._unshaded_ground_fraction', 'utils._unshaded_ground_fraction', (['surface_tilt', 'surface_azimuth', 'solar_zenith', 'solar_azimuth', 'gcr'], {}), '(surface_tilt, surface_azimuth, solar_zenith,\n solar_azimuth, gcr)\n', (17972, 18041), False, 'from pvlib.bifacial import utils\n'), ((19807, 19835), 'numpy.clip', 'np.clip', (['(dhi / ghi)', '(0.0)', '(1.0)'], {}), '(dhi / ghi, 0.0, 1.0)\n', (19814, 19835), True, 'import numpy as np\n'), ((19905, 19950), 'numpy.where', 'np.where', (['(ghi < 0.0001)', '(0.0)', 'diffuse_fraction'], {}), '(ghi < 0.0001, 0.0, diffuse_fraction)\n', (19913, 19950), True, 'import numpy as np\n'), ((2377, 2436), 'pvlib.bifacial.utils._vf_ground_sky_2d', 'utils._vf_ground_sky_2d', (['z', 'r', 'gcr', 'pitch', 'height', 'max_rows'], {}), '(z, r, gcr, pitch, height, max_rows)\n', (2400, 2436), False, 'from pvlib.bifacial import utils\n'), ((7583, 7601), 'pvlib.tools.sind', 'sind', (['surface_tilt'], {}), '(surface_tilt)\n', (7587, 7601), False, 'from pvlib.tools import cosd, sind, tand\n'), ((20931, 21010), 'pvlib.irradiance.beam_component', 'beam_component', (['surface_tilt', 'surface_azimuth', 'solar_zenith', 'solar_azimuth', 'dni'], {}), '(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, dni)\n', (20945, 21010), False, 'from pvlib.irradiance import beam_component, aoi\n'), ((21387, 21407), 'pandas.DataFrame', 'pd.DataFrame', (['output'], {}), '(output)\n', (21399, 21407), True, 'import pandas as pd\n'), ((28197, 28241), 'pandas.concat', 'pd.concat', (['[irrad_front, irrad_back]'], {'axis': '(1)'}), '([irrad_front, irrad_back], axis=1)\n', (28206, 28241), True, 'import pandas as pd\n'), ((5167, 5185), 'pvlib.tools.cosd', 'cosd', (['psi_t_shaded'], {}), '(psi_t_shaded)\n', (5171, 5185), False, 'from pvlib.tools import cosd, sind, tand\n'), ((5511, 5531), 'pvlib.tools.cosd', 'cosd', (['psi_t_unshaded'], {}), '(psi_t_unshaded)\n', (5515, 5531), False, 'from pvlib.tools import cosd, sind, tand\n'), ((7616, 7634), 'pvlib.tools.cosd', 'cosd', (['surface_tilt'], {}), '(surface_tilt)\n', (7620, 7634), False, 'from pvlib.tools import cosd, sind, tand\n'), ((8612, 8630), 'pvlib.tools.cosd', 'cosd', (['psi_t_shaded'], {}), '(psi_t_shaded)\n', (8616, 8630), False, 'from pvlib.tools import cosd, sind, tand\n'), ((13851, 13869), 'pvlib.tools.cosd', 'cosd', (['surface_tilt'], {}), '(surface_tilt)\n', (13855, 13869), False, 'from pvlib.tools import cosd, sind, tand\n'), ((13820, 13838), 'pvlib.tools.sind', 'sind', (['surface_tilt'], {}), '(surface_tilt)\n', (13824, 13838), False, 'from pvlib.tools import cosd, sind, tand\n'), ((17805, 17812), 'pvlib.tools.tand', 'tand', (['(5)'], {}), '(5)\n', (17809, 17812), False, 'from pvlib.tools import cosd, sind, tand\n')]
|
import sys
import torch
import random
import numpy as np
import progressbar
from dataclass_utlis import load_response_id_dict, load_context_data, load_dev_data, process_text
UNK, PAD = '[UNK]', '[PAD]'
# pad_context(batch_context_id_list, padding_idx)
import pickle
def load_pickle_file(in_f):
with open(in_f, 'rb') as f:
data = pickle.load(f)
return data
class Tokenizer:
def __init__(self, word2id_path):
self.word2id_dict, self.id2word_dict = {}, {}
with open(word2id_path, 'r', encoding = 'utf8') as i:
lines = i.readlines()
for l in lines:
content_list = l.strip('\n').split()
token = content_list[0]
idx = int(content_list[1])
self.word2id_dict[token] = idx
self.id2word_dict[idx] = token
self.vocab_size = len(self.word2id_dict)
print ('vocab size is %d' % self.vocab_size)
self.unk_idx = self.word2id_dict[UNK]
self.padding_idx = self.word2id_dict[PAD]
def convert_tokens_to_ids(self, token_list):
res_list = []
for token in token_list:
try:
res_list.append(self.word2id_dict[token])
except KeyError:
res_list.append(self.unk_idx)
return res_list
def convert_ids_to_tokens(self, idx_list):
res_list = []
for idx in idx_list:
try:
res_list.append(self.id2word_dict[idx])
except KeyError:
res_list.append(UNK)
return res_list
def tokenize(self, text):
return text.strip('\n').strip().split()
class Data:
def __init__(self, train_context_path, train_true_response_path, response_index_path, negative_num,
dev_path, word2id_path, max_uttr_num, max_uttr_len, mips_config, negative_mode, train_context_vec_file,
all_response_vec_file):
self.max_uttr_num, self.max_uttr_len = max_uttr_num, max_uttr_len
self.negative_num = negative_num
self.tokenizer = Tokenizer(word2id_path)
self.train_context_id_list = load_context_data(train_context_path, self.max_uttr_num,
self.max_uttr_len, self.tokenizer)
self.train_context_text_list = []
with open(train_context_path, 'r', encoding = 'utf8') as i:
lines = i.readlines()
for l in lines:
self.train_context_text_list.append(l.strip('\n'))
self.train_num = len(self.train_context_id_list)
self.id_response_text_dict = {}
self.id_response_id_dict = {}
self.index_response_text_list = []
print ('Loading Response Index...')
with open(response_index_path, 'r', encoding = 'utf8') as i:
lines = i.readlines()
p = progressbar.ProgressBar(len(lines))
p.start()
for idx in range(len(lines)):
one_response_text = lines[idx].strip('\n')
self.index_response_text_list.append(one_response_text)
one_response_token_list = process_text(one_response_text, max_uttr_len, self.tokenizer)
one_response_id_list = self.tokenizer.convert_tokens_to_ids(one_response_token_list)
self.id_response_text_dict[idx] = one_response_text
self.id_response_id_dict[idx] = one_response_id_list
p.update(idx + 1)
p.finish()
print ('Response Index Loaded.')
self.index_response_idx_list = [num for num in range(len(self.id_response_text_dict))]
print ('Loading Reference Responses...')
self.train_true_response_id_list = []
self.train_reference_response_index_list = []
with open(train_true_response_path, 'r', encoding = 'utf8') as i:
lines = i.readlines()
for l in lines:
one_id = int(l.strip('\n'))
self.train_reference_response_index_list.append(one_id)
one_response_id_list = [self.id_response_id_dict[one_id]]
self.train_true_response_id_list.append(one_response_id_list)
assert np.array(self.train_true_response_id_list).shape == (self.train_num, 1, self.max_uttr_len)
print ('Reference Responses Loaded.')
self.negative_mode = negative_mode
if negative_mode == 'random_search':
pass
elif negative_mode == 'mips_search':
print ('Use Instance-Level Curriculum Learning.')
self.cutoff_threshold = mips_config['cutoff_threshold']
self.negative_selection_k = mips_config['negative_selection_k']
print ('Loading context vectors...')
self.train_context_vec = load_pickle_file(train_context_vec_file)
assert len(self.train_context_vec) == self.train_num
print ('Loading response index vectors...')
self.index_response_vec = load_pickle_file(all_response_vec_file)
assert len(self.index_response_vec) == len(self.index_response_text_list)
else:
raise Exception('Wrong Negative Mode!!!')
self.dev_context_id_list, self.dev_candi_response_id_list, self.dev_candi_response_label_list = \
load_dev_data(dev_path, self.max_uttr_num, self.max_uttr_len, self.tokenizer)
self.dev_num = len(self.dev_context_id_list)
print ('train number is %d, dev number is %d' % (self.train_num, self.dev_num))
self.train_idx_list = [i for i in range(self.train_num)]
self.dev_idx_list = [j for j in range(self.dev_num)]
self.dev_current_idx = 0
def select_response(self, context_vec, true_response_vec, candidate_response_vec, candidate_response_index,
cutoff_threshold, top_k):
'''
context_vec: bsz x embed_dim
true_response_vec: bsz x embed_dim
candidate_response_vec: bsz x candi_num x embed_dim
candidate_response_index: bsz x candi_num
'''
context_vec = torch.FloatTensor(context_vec)
true_response_vec = torch.FloatTensor(true_response_vec)
candidate_response_vec = torch.FloatTensor(candidate_response_vec)
bsz, embed_dim = context_vec.size()
_, candi_num, _ = candidate_response_vec.size()
true_scores = torch.sum(context_vec * true_response_vec, dim = -1).view(bsz, 1)
x = torch.unsqueeze(context_vec, 1)
assert x.size() == torch.Size([bsz, 1, embed_dim])
y = candidate_response_vec.transpose(1,2)
candi_scores = torch.matmul(x, y).squeeze(1)
assert candi_scores.size() == torch.Size([bsz, candi_num])
score_threshold = cutoff_threshold * true_scores # do not allow too high score
candi_scores = candi_scores - score_threshold
candi_scores = candi_scores.masked_fill(candi_scores>0, float('-inf')) # mask out the high score part
batch_top_scores, batch_top_indexs = torch.topk(candi_scores, k=top_k, dim = 1)
batch_top_indexs = batch_top_indexs.cpu().tolist()
result_index = []
for k in range(bsz):
one_select_index = batch_top_indexs[k]
one_candi_index = candidate_response_index[k]
one_res = []
for one_id in one_select_index:
one_res.append(one_candi_index[one_id])
result_index.append(one_res)
return result_index
def select_top_k_response(self, context_index_list, true_response_index_list, candi_response_index_list, top_k):
'''
context_index_list: bsz
true_response_index_list: bsz
candi_response_index_list: bsz x candi_num
'''
batch_context_vec = [self.train_context_vec[one_id] for one_id in context_index_list]
batch_true_response_vec = [self.index_response_vec[one_id] for one_id in true_response_index_list]
batch_candi_response_vec = []
for index_list in candi_response_index_list:
one_candi_response_vec = [self.index_response_vec[one_id] for one_id in index_list]
batch_candi_response_vec.append(one_candi_response_vec)
batch_select_response_index = self.select_response(batch_context_vec, batch_true_response_vec, batch_candi_response_vec,
candi_response_index_list, self.cutoff_threshold, top_k)
assert np.array(batch_select_response_index).shape == (len(context_index_list), top_k)
return batch_select_response_index
def get_next_train_batch(self, batch_size):
batch_idx_list = random.sample(self.train_idx_list, batch_size)
batch_context_id_list, batch_true_response_id_list, batch_negative_response_id_list = [], [], []
batch_sample_response_index_list, batch_true_response_index_list = [], []
for idx in batch_idx_list:
# context
one_context_id_list = self.train_context_id_list[idx]
batch_context_id_list.append(one_context_id_list)
# true response
one_true_response_id_list = self.train_true_response_id_list[idx]
batch_true_response_id_list.append(one_true_response_id_list)
one_true_response_index = self.train_reference_response_index_list[idx]
batch_true_response_index_list.append(one_true_response_index)
if self.negative_mode == 'random_search':
# random sampling negative cases
one_negative_sample_idx_list = random.sample(self.index_response_idx_list, self.negative_num)
elif self.negative_mode == 'mips_search':
one_negative_sample_idx_list = random.sample(self.index_response_idx_list, self.negative_selection_k)
else:
raise Exception('Wrong Search Method!!!')
while one_true_response_index in set(one_negative_sample_idx_list):
if self.negative_mode == 'random_search':
# random sampling negative cases
one_negative_sample_idx_list = random.sample(self.index_response_idx_list, self.negative_num)
elif self.negative_mode == 'mips_search':
one_negative_sample_idx_list = random.sample(self.index_response_idx_list, self.negative_selection_k)
else:
raise Exception('Wrong Search Method!!!')
batch_sample_response_index_list.append(one_negative_sample_idx_list)
if self.negative_mode == 'random_search':
pass
elif self.negative_mode == 'mips_search':
batch_context_index_list = batch_idx_list
batch_sample_response_index_list = self.select_top_k_response(batch_context_index_list, batch_true_response_index_list,
batch_sample_response_index_list, self.negative_num)
else:
raise Exception('Wrong Search Method!!!')
for one_sample_index_list in batch_sample_response_index_list:
one_sample_response_id = [self.id_response_id_dict[one_neg_id] for one_neg_id in one_sample_index_list]
batch_negative_response_id_list.append(one_sample_response_id)
assert np.array(batch_context_id_list).shape == (batch_size, self.max_uttr_num, self.max_uttr_len)
assert np.array(batch_true_response_id_list).shape == (batch_size, 1, self.max_uttr_len)
assert np.array(batch_negative_response_id_list).shape == (batch_size, self.negative_num, self.max_uttr_len)
return batch_context_id_list, batch_true_response_id_list, batch_negative_response_id_list
def get_next_dev_batch(self, batch_size):
'''
batch_context_list: bsz x uttr_num x uttr_len
batch_candidate_response_list: bsz x candi_num x uttr_len
batch_candidate_response_label_list: bsz x candi_num
'''
batch_context_list, batch_candidate_response_list, batch_candidate_response_label_list = [], [], []
if self.dev_current_idx + batch_size < self.dev_num - 1:
for i in range(batch_size):
curr_idx = self.dev_current_idx + i
one_context_id_list = self.dev_context_id_list[curr_idx]
batch_context_list.append(one_context_id_list)
one_candidate_response_id_list = self.dev_candi_response_id_list[curr_idx]
batch_candidate_response_list.append(one_candidate_response_id_list)
one_candidate_response_label_list = self.dev_candi_response_label_list[curr_idx]
batch_candidate_response_label_list.append(one_candidate_response_label_list)
self.dev_current_idx += batch_size
else:
for i in range(batch_size):
curr_idx = self.dev_current_idx + i
if curr_idx > self.dev_num - 1: # 对dev_current_idx重新赋值
curr_idx = 0
self.dev_current_idx = 0
else:
pass
one_context_id_list = self.dev_context_id_list[curr_idx]
batch_context_list.append(one_context_id_list)
one_candidate_response_id_list = self.dev_candi_response_id_list[curr_idx]
batch_candidate_response_list.append(one_candidate_response_id_list)
one_candidate_response_label_list = self.dev_candi_response_label_list[curr_idx]
batch_candidate_response_label_list.append(one_candidate_response_label_list)
self.dev_current_idx = 0
return batch_context_list, batch_candidate_response_list, batch_candidate_response_label_list
|
[
"dataclass_utlis.load_context_data",
"torch.topk",
"dataclass_utlis.process_text",
"random.sample",
"dataclass_utlis.load_dev_data",
"torch.FloatTensor",
"pickle.load",
"numpy.array",
"torch.Size",
"torch.unsqueeze",
"torch.matmul",
"torch.sum"
] |
[((343, 357), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (354, 357), False, 'import pickle\n'), ((2121, 2216), 'dataclass_utlis.load_context_data', 'load_context_data', (['train_context_path', 'self.max_uttr_num', 'self.max_uttr_len', 'self.tokenizer'], {}), '(train_context_path, self.max_uttr_num, self.max_uttr_len,\n self.tokenizer)\n', (2138, 2216), False, 'from dataclass_utlis import load_response_id_dict, load_context_data, load_dev_data, process_text\n'), ((5231, 5308), 'dataclass_utlis.load_dev_data', 'load_dev_data', (['dev_path', 'self.max_uttr_num', 'self.max_uttr_len', 'self.tokenizer'], {}), '(dev_path, self.max_uttr_num, self.max_uttr_len, self.tokenizer)\n', (5244, 5308), False, 'from dataclass_utlis import load_response_id_dict, load_context_data, load_dev_data, process_text\n'), ((6015, 6045), 'torch.FloatTensor', 'torch.FloatTensor', (['context_vec'], {}), '(context_vec)\n', (6032, 6045), False, 'import torch\n'), ((6074, 6110), 'torch.FloatTensor', 'torch.FloatTensor', (['true_response_vec'], {}), '(true_response_vec)\n', (6091, 6110), False, 'import torch\n'), ((6144, 6185), 'torch.FloatTensor', 'torch.FloatTensor', (['candidate_response_vec'], {}), '(candidate_response_vec)\n', (6161, 6185), False, 'import torch\n'), ((6386, 6417), 'torch.unsqueeze', 'torch.unsqueeze', (['context_vec', '(1)'], {}), '(context_vec, 1)\n', (6401, 6417), False, 'import torch\n'), ((6943, 6983), 'torch.topk', 'torch.topk', (['candi_scores'], {'k': 'top_k', 'dim': '(1)'}), '(candi_scores, k=top_k, dim=1)\n', (6953, 6983), False, 'import torch\n'), ((8547, 8593), 'random.sample', 'random.sample', (['self.train_idx_list', 'batch_size'], {}), '(self.train_idx_list, batch_size)\n', (8560, 8593), False, 'import random\n'), ((6445, 6476), 'torch.Size', 'torch.Size', (['[bsz, 1, embed_dim]'], {}), '([bsz, 1, embed_dim])\n', (6455, 6476), False, 'import torch\n'), ((6618, 6646), 'torch.Size', 'torch.Size', (['[bsz, candi_num]'], {}), '([bsz, candi_num])\n', (6628, 6646), False, 'import torch\n'), ((3080, 3141), 'dataclass_utlis.process_text', 'process_text', (['one_response_text', 'max_uttr_len', 'self.tokenizer'], {}), '(one_response_text, max_uttr_len, self.tokenizer)\n', (3092, 3141), False, 'from dataclass_utlis import load_response_id_dict, load_context_data, load_dev_data, process_text\n'), ((4142, 4184), 'numpy.array', 'np.array', (['self.train_true_response_id_list'], {}), '(self.train_true_response_id_list)\n', (4150, 4184), True, 'import numpy as np\n'), ((6308, 6358), 'torch.sum', 'torch.sum', (['(context_vec * true_response_vec)'], {'dim': '(-1)'}), '(context_vec * true_response_vec, dim=-1)\n', (6317, 6358), False, 'import torch\n'), ((6550, 6568), 'torch.matmul', 'torch.matmul', (['x', 'y'], {}), '(x, y)\n', (6562, 6568), False, 'import torch\n'), ((8350, 8387), 'numpy.array', 'np.array', (['batch_select_response_index'], {}), '(batch_select_response_index)\n', (8358, 8387), True, 'import numpy as np\n'), ((9457, 9519), 'random.sample', 'random.sample', (['self.index_response_idx_list', 'self.negative_num'], {}), '(self.index_response_idx_list, self.negative_num)\n', (9470, 9519), False, 'import random\n'), ((11198, 11229), 'numpy.array', 'np.array', (['batch_context_id_list'], {}), '(batch_context_id_list)\n', (11206, 11229), True, 'import numpy as np\n'), ((11305, 11342), 'numpy.array', 'np.array', (['batch_true_response_id_list'], {}), '(batch_true_response_id_list)\n', (11313, 11342), True, 'import numpy as np\n'), ((11402, 11443), 'numpy.array', 'np.array', (['batch_negative_response_id_list'], {}), '(batch_negative_response_id_list)\n', (11410, 11443), True, 'import numpy as np\n'), ((9621, 9691), 'random.sample', 'random.sample', (['self.index_response_idx_list', 'self.negative_selection_k'], {}), '(self.index_response_idx_list, self.negative_selection_k)\n', (9634, 9691), False, 'import random\n'), ((10011, 10073), 'random.sample', 'random.sample', (['self.index_response_idx_list', 'self.negative_num'], {}), '(self.index_response_idx_list, self.negative_num)\n', (10024, 10073), False, 'import random\n'), ((10183, 10253), 'random.sample', 'random.sample', (['self.index_response_idx_list', 'self.negative_selection_k'], {}), '(self.index_response_idx_list, self.negative_selection_k)\n', (10196, 10253), False, 'import random\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The CG algorithm for image reconstruction."""
import numpy as np
import time
class CGReco:
"""
Conjugate Gradient Optimization.
This class performs conjugate gradient based optimization given
some data and a operator derived from linop.Operator. The operator needs
to be set using the set_operator method prior to optimization.
Code is based on the Wikipedia entry
https://en.wikipedia.org/wiki/Conjugate_gradient_method
Attributes
----------
image_dim (int):
Dimension of the reconstructed image
num_coils (int):
Number of coils
do_incor (bool):
Flag to do intensity correction:
incor (np.complex64):
Intensity correction array
maxit (int):
Maximum number of CG iterations
lambd (float):
Weight of the Tikhonov regularization. Defaults to 0
tol (float):
Tolerance to terminate iterations. Defaults to 0
NSlice (ind):
Number of Slices
DTYPE (numpy.type):
The complex value precision. Defaults to complex64
DTYPE_real (numpy.type):
The real value precision. Defaults to float32
res (list):
List to store residual values
operator (linop.Operator):
MRI imaging operator to traverse from k-space to imagespace and
vice versa.
"""
def __init__(self, data_par, optimizer_par):
"""
CG object constructor.
Args
----
data_par (dict):
A python dict containing the necessary information to
setup the object. Needs to contain the image dimensions
(img_dim), number of coils (num_coils),
sampling points (num_reads) and read outs (num_proj) and the
complex coil sensitivities (Coils).
optimizer_par (dict):
Parameter containing the optimization related settings.
"""
self.image_dim = data_par["image_dimension"]
self.num_coils = data_par["num_coils"]
self.mask = data_par["mask"]
self.DTYPE = data_par["DTYPE"]
self.DTYPE_real = data_par["DTYPE_real"]
self.do_incor = data_par["do_intensity_scale"]
self.incor = data_par["in_scale"].astype(self.DTYPE)
self.maxit = optimizer_par["max_iter"]
self.lambd = optimizer_par["lambda"]
self.tol = optimizer_par["tolerance"]
self.res = []
self.operator = None
def set_operator(self, op):
"""
Set the linear operator for CG minimization.
This functions sets the linear operator to use for CG minimization. It
is mandatory to set an operator prior to minimization.
Args
----
op (linop.Operator):
The linear operator to be used for CG reconstruction.
"""
self.operator = op
def operator_lhs(self, inp):
"""
Compute the LHS of the normal equation.
This function computes the left hand side of the normal equation,
evaluation A^TA x on the input x.
Args
----
inp (numpy.Array):
The complex image space data.
Returns
-------
numpy.Array: Left hand side of CG normal equation
"""
assert self.operator is not None, \
"Please set an operator with the set_operation method"
return self.operator_rhs(self.operator.forward(inp))
def operator_rhs(self, inp):
"""
Compute the RHS of the normal equation.
This function computes the right hand side of the normal equation,
evaluation A^T b on the k-space data b.
Args
----
inp (numpy.Array):
The complex k-space data which is used as input.
Returns
-------
numpy.Array: Right hand side of CG normal equation
"""
assert self.operator is not None, \
"Please set an operator with the set_operation method"
return self.operator.adjoint(inp)
def kspace_filter(self, x):
"""
Perform k-space filtering.
This function filters out k-space points outside the acquired
trajectory, setting the corresponding k-space position to 0.
Args
----
x (numpy.Array):
The complex image-space data to filter.
Returns
-------
numpy.Array: Filtered image-space data.
"""
print("Performing k-space filtering")
kpoints = (np.arange(-np.floor(self.operator.grid_size/2),
np.ceil(self.operator.grid_size/2))
)/self.operator.grid_size
xx, yy = np.meshgrid(kpoints, kpoints)
gridmask = np.sqrt(xx**2+yy**2)
gridmask[np.abs(gridmask) > 0.5] = 1
gridmask[gridmask < 1] = 0
gridmask = ~gridmask.astype(bool)
gridcenter = self.operator.grid_size / 2
tmp = np.zeros(
(
x.shape[0],
self.operator.grid_size,
self.operator.grid_size),
dtype=self.operator.DTYPE
)
tmp[
...,
int(gridcenter-self.image_dim/2):
int(gridcenter+self.image_dim/2),
int(gridcenter-self.image_dim/2):
int(gridcenter+self.image_dim/2)
] = x
tmp = np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(
np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(
tmp, (-2, -1)), norm='ortho'),
(-2, -1))*gridmask, (-2, -1)),
norm='ortho'), (-2, -1))
x = tmp[
...,
int(gridcenter-self.image_dim/2):
int(gridcenter+self.image_dim/2),
int(gridcenter-self.image_dim/2):
int(gridcenter+self.image_dim/2)
]
return x
###############################################################################
# Start a Reconstruction ####################################################
# Call inner optimization ###################################################
# output: optimal value of x ################################################
###############################################################################
def optimize(self, data, guess=None):
"""
Perform CG minimization.
Check if operator is set prior to optimization. If no initial guess is
set, assume all zeros as initial image. Calls the _cg_solve function
for minimization itself. An optional Tikhonov regularization can be
enabled which adds a scaled identity matrix to the LHS
(A^T A + lambd*Id).
Args
----
data (numpy.Array):
The complex k-space data to fit.
guess (numpy.Array=None):
Optional initial guess for the image.
Returns
-------
numpy.Array:
final result of optimization,
including intermediate results for each CG setp
"""
if self.operator is None:
print("Please set an Linear operator "
"using the SetOperator method.")
return
if guess is None:
guess = np.zeros(
(
self.maxit+1,
self.image_dim,
self.image_dim
),
dtype=self.DTYPE
)
start = time.perf_counter()
result = self._cg_solve(
x=guess,
data=data,
iters=self.maxit,
lambd=self.lambd,
tol=self.tol
)
result[~np.isfinite(result)] = 0
end = time.perf_counter()-start
print("\n"+"-"*80)
print("Elapsed time: %f seconds" % (end))
print("-"*80)
if self.do_incor:
result = self.mask*result/self.incor
return (self.kspace_filter(result), self.res)
###############################################################################
# Conjugate Gradient optimization ###########################################
# input: initial guess x ####################################################
# number of iterations iters #########################################
# output: optimal value of x ################################################
###############################################################################
def _cg_solve(self, x, data, iters, lambd, tol):
"""
Conjugate gradient optimization.
This function implements the CG optimization. It is based on
https://en.wikipedia.org/wiki/Conjugate_gradient_method
Args
----
X (numpy.Array):
Initial guess for the image.
data (numpy.Array):
The complex k-space data to fit.
guess (numpy.Array):
Optional initial guess for the image.
iters (int):
Maximum number of CG steps.
lambd (float):
Regularization weight for Tikhonov regularizer.
tol (float):
Relative tolerance to terminate optimization.
Returns
-------
numpy.Array:
A numpy array containing the result of the
computation.
"""
b = np.zeros(
(
self.image_dim,
self.image_dim
),
self.DTYPE
)
Ax = np.zeros(
(
self.image_dim,
self.image_dim
),
self.DTYPE
)
b = self.operator_rhs(data)
residual = b
p = residual
delta = np.linalg.norm(residual) ** 2 / np.linalg.norm(b) ** 2
self.res.append(delta)
print("Initial Residuum: ", delta)
for i in range(iters):
Ax = self.operator_lhs(p)
Ax = Ax + lambd * p
alpha = np.vdot(residual, residual)/(np.vdot(p, Ax))
x[i + 1] = x[i] + alpha * p
residual_new = residual - alpha * Ax
delta = np.linalg.norm(residual_new) ** 2 / np.linalg.norm(b) ** 2
self.res.append(delta)
if delta < tol:
print("\nConverged after %i iterations to %1.3e." %
(i+1, delta))
x[0] = b
return x[:i+1, ...]
if not np.mod(i, 1):
print("Residuum at iter %i : %1.3e" % (i+1, delta), end='\r')
beta = (np.vdot(residual_new, residual_new) /
np.vdot(residual, residual))
p = residual_new + beta * p
(residual, residual_new) = (residual_new, residual)
x[0] = b
return x
|
[
"numpy.fft.ifftshift",
"numpy.meshgrid",
"numpy.abs",
"numpy.ceil",
"numpy.floor",
"numpy.zeros",
"time.perf_counter",
"numpy.isfinite",
"numpy.vdot",
"numpy.mod",
"numpy.linalg.norm",
"numpy.sqrt"
] |
[((4877, 4906), 'numpy.meshgrid', 'np.meshgrid', (['kpoints', 'kpoints'], {}), '(kpoints, kpoints)\n', (4888, 4906), True, 'import numpy as np\n'), ((4926, 4952), 'numpy.sqrt', 'np.sqrt', (['(xx ** 2 + yy ** 2)'], {}), '(xx ** 2 + yy ** 2)\n', (4933, 4952), True, 'import numpy as np\n'), ((5133, 5236), 'numpy.zeros', 'np.zeros', (['(x.shape[0], self.operator.grid_size, self.operator.grid_size)'], {'dtype': 'self.operator.DTYPE'}), '((x.shape[0], self.operator.grid_size, self.operator.grid_size),\n dtype=self.operator.DTYPE)\n', (5141, 5236), True, 'import numpy as np\n'), ((7685, 7704), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7702, 7704), False, 'import time\n'), ((9597, 9651), 'numpy.zeros', 'np.zeros', (['(self.image_dim, self.image_dim)', 'self.DTYPE'], {}), '((self.image_dim, self.image_dim), self.DTYPE)\n', (9605, 9651), True, 'import numpy as np\n'), ((9753, 9807), 'numpy.zeros', 'np.zeros', (['(self.image_dim, self.image_dim)', 'self.DTYPE'], {}), '((self.image_dim, self.image_dim), self.DTYPE)\n', (9761, 9807), True, 'import numpy as np\n'), ((7476, 7552), 'numpy.zeros', 'np.zeros', (['(self.maxit + 1, self.image_dim, self.image_dim)'], {'dtype': 'self.DTYPE'}), '((self.maxit + 1, self.image_dim, self.image_dim), dtype=self.DTYPE)\n', (7484, 7552), True, 'import numpy as np\n'), ((7936, 7955), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7953, 7955), False, 'import time\n'), ((4779, 4815), 'numpy.ceil', 'np.ceil', (['(self.operator.grid_size / 2)'], {}), '(self.operator.grid_size / 2)\n', (4786, 4815), True, 'import numpy as np\n'), ((4964, 4980), 'numpy.abs', 'np.abs', (['gridmask'], {}), '(gridmask)\n', (4970, 4980), True, 'import numpy as np\n'), ((7897, 7916), 'numpy.isfinite', 'np.isfinite', (['result'], {}), '(result)\n', (7908, 7916), True, 'import numpy as np\n'), ((9991, 10015), 'numpy.linalg.norm', 'np.linalg.norm', (['residual'], {}), '(residual)\n', (10005, 10015), True, 'import numpy as np\n'), ((10023, 10040), 'numpy.linalg.norm', 'np.linalg.norm', (['b'], {}), '(b)\n', (10037, 10040), True, 'import numpy as np\n'), ((10242, 10269), 'numpy.vdot', 'np.vdot', (['residual', 'residual'], {}), '(residual, residual)\n', (10249, 10269), True, 'import numpy as np\n'), ((10271, 10285), 'numpy.vdot', 'np.vdot', (['p', 'Ax'], {}), '(p, Ax)\n', (10278, 10285), True, 'import numpy as np\n'), ((10702, 10714), 'numpy.mod', 'np.mod', (['i', '(1)'], {}), '(i, 1)\n', (10708, 10714), True, 'import numpy as np\n'), ((10815, 10850), 'numpy.vdot', 'np.vdot', (['residual_new', 'residual_new'], {}), '(residual_new, residual_new)\n', (10822, 10850), True, 'import numpy as np\n'), ((10873, 10900), 'numpy.vdot', 'np.vdot', (['residual', 'residual'], {}), '(residual, residual)\n', (10880, 10900), True, 'import numpy as np\n'), ((4713, 4750), 'numpy.floor', 'np.floor', (['(self.operator.grid_size / 2)'], {}), '(self.operator.grid_size / 2)\n', (4721, 4750), True, 'import numpy as np\n'), ((10396, 10424), 'numpy.linalg.norm', 'np.linalg.norm', (['residual_new'], {}), '(residual_new)\n', (10410, 10424), True, 'import numpy as np\n'), ((10432, 10449), 'numpy.linalg.norm', 'np.linalg.norm', (['b'], {}), '(b)\n', (10446, 10449), True, 'import numpy as np\n'), ((5661, 5692), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['tmp', '(-2, -1)'], {}), '(tmp, (-2, -1))\n', (5677, 5692), True, 'import numpy as np\n')]
|
import numpy as np
import matplotlib.pyplot as plt
MAX_ITERS = 1000
DOUBLE_PRECISION_THRESHOLD = 1e-15
SINGLE_PRECISION_THRESHOLD = 1e-8
def newton_raphson(x_0, f, df):
x = np.copy(x_0)
# xs = [x_0]
for i in range(MAX_ITERS):
x_last = x
try:
x = x_last - np.dot(np.linalg.inv(df(x_last)), f(x_last))
except np.linalg.LinAlgError:
return np.zeros_like(x_0)
x_norm = np.linalg.norm(x)
abs_error = np.linalg.norm(x - x_last)
# if x_norm < SINGLE_PRECISION_THRESHOLD:
# error = abs_error
# else:
# error = abs_error / np.linalg.norm(x)
#print('\t i={}, error={}'.format(i, abs_error))
# xs.append(x)
if abs_error < SINGLE_PRECISION_THRESHOLD:
# xs = np.array(xs)
# plt.loglog(np.array([np.linalg.norm(x_) for x_ in xs[:-1]]), np.array([np.linalg.norm(x_) for x_ in xs[1:]]))
# xx = np.array([10**(-16), 10**(-1)])
# plt.loglog(xx, 10 * xx**2)
# plt.grid()
# plt.show()
return x
return x
def steepest_descent(x_0, f, df):
x = np.copy(x_0)
g = lambda x: np.sum(f(x)**2)
print(g(x_0))
for i in range(MAX_ITERS):
x_last = x
grad_g = 2*np.dot(df(x_last).T, f(x_last))
z = grad_g / np.linalg.norm(grad_g)
h = lambda alpha: g(x_last - alpha*z)
alpha_1 = 0.
alpha_3 = 1.
h_1 = h(alpha_1)
while h(alpha_3) > h_1:
alpha_3 /= 2.
alpha_2 = alpha_3 / 2.
h_2 = h(alpha_2)
h_3 = h(alpha_3)
a = h_1 / ((alpha_1 - alpha_2)*(alpha_1 - alpha_3))
b = h_2 / ((alpha_2 - alpha_1)*(alpha_2 - alpha_3))
c = h_3 / ((alpha_3 - alpha_1)*(alpha_3 - alpha_2))
alpha_opt = (a*(alpha_2 + alpha_3) + b*(alpha_1 + alpha_3) + c*(alpha_1 + alpha_2)) / (2*(a+b+c))
# h_2 = (h(alpha_2) - h_1) / alpha_2
# tilde_h_2 = (h(alpha_3) - h(alpha_2)) / (alpha_3 - alpha_2)
# h_3 = (tilde_h_2 - h_2) / alpha_3
# alpha_opt = (alpha_2 - h_2 / h_3) / 2.
x = x_last - alpha_opt * z
x_norm = np.linalg.norm(x)
abs_error = np.linalg.norm(x - x_last)
# if x_norm < SINGLE_PRECISION_THRESHOLD:
# error = abs_error
# else:
# error = abs_error / np.linalg.norm(x)
print('\t i={}, g_value={}, error={}'.format(i, g(x), abs_error))
if abs_error < SINGLE_PRECISION_THRESHOLD:
return x
print('OUT OF 1000 ITERATIONS')
return x
|
[
"numpy.zeros_like",
"numpy.linalg.norm",
"numpy.copy"
] |
[((179, 191), 'numpy.copy', 'np.copy', (['x_0'], {}), '(x_0)\n', (186, 191), True, 'import numpy as np\n'), ((1144, 1156), 'numpy.copy', 'np.copy', (['x_0'], {}), '(x_0)\n', (1151, 1156), True, 'import numpy as np\n'), ((434, 451), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (448, 451), True, 'import numpy as np\n'), ((472, 498), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - x_last)'], {}), '(x - x_last)\n', (486, 498), True, 'import numpy as np\n'), ((2148, 2165), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (2162, 2165), True, 'import numpy as np\n'), ((2186, 2212), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - x_last)'], {}), '(x - x_last)\n', (2200, 2212), True, 'import numpy as np\n'), ((1331, 1353), 'numpy.linalg.norm', 'np.linalg.norm', (['grad_g'], {}), '(grad_g)\n', (1345, 1353), True, 'import numpy as np\n'), ((398, 416), 'numpy.zeros_like', 'np.zeros_like', (['x_0'], {}), '(x_0)\n', (411, 416), True, 'import numpy as np\n')]
|
from Resnet_model import resnet101
from utils.data_utils import parser
from utils.plot_utils import ploy_rect
import tensorflow as tf
import argparse
import numpy as np
import cv2
# define clasify: background and car
LABELS = {
1: 'Person',
2: 'Bird',
3: 'Cat',
4: 'Cow',
5: 'Dog',
6: 'Horse',
7: 'Sheep',
8: 'Aeroplane',
9: 'Bicycle',
10: 'Boat',
11: 'Bus',
12: 'Car',
13: 'Motorbike',
14: 'Train',
15: 'Bottle',
16: 'Chair',
17: 'Diningtable',
18: 'Pottedplant',
19: 'Sofa',
20: 'TV'
}
Arg_parser = argparse.ArgumentParser(description="RetinaNet image test")
Arg_parser.add_argument("--Val_tfrecords", type=str, default='./tfrecords/voc2012/val.tfrecords', help="The path of val tfrecords")
Arg_parser.add_argument("--Restore_path", type=str, default='./checkpoint/good/RetinaNet.ckpt-80830', help="The checkpoint you restore")
Arg_parser.add_argument("--Compare", type=bool, default=False, help="If you want to see the comparision between gruondtruth and prediction")
args = Arg_parser.parse_args()
NUM_CLASS = 20
NUM_ANCHORS = 9
BATCH_SIZE = 10
IMAGE_SIZE = [224, 224]
SHUFFLE_SIZE = 500
NUM_PARALLEL = 10
with tf.Graph().as_default():
val_files = [args.Val_tfrecords]
val_dataset = tf.data.TFRecordDataset(val_files)
val_dataset = val_dataset.map(lambda x : parser(x, IMAGE_SIZE, 'val'), num_parallel_calls=NUM_PARALLEL)
val_dataset = val_dataset.batch(BATCH_SIZE).prefetch(BATCH_SIZE)
iterator = val_dataset.make_one_shot_iterator()
image, boxes, labels = iterator.get_next()
image.set_shape([None, IMAGE_SIZE[0], IMAGE_SIZE[1], 3])
with tf.variable_scope("yolov3"):
retinaNet = resnet101(NUM_CLASS, NUM_ANCHORS)
feature_maps, pred_class, pred_boxes = retinaNet.forward(image, is_training=False)
anchors = retinaNet.generate_anchors(feature_maps)
pred_boxes, pred_labels, pred_scores = retinaNet.predict(anchors, pred_class, pred_boxes)
eval_result = retinaNet.evaluate(pred_boxes, pred_labels, pred_scores, boxes, labels)
saver_restore = tf.train.Saver()
# Set session config
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.per_process_gpu_memory_fraction = 0.90
with tf.Session(config=config) as sess:
sess.run((tf.global_variables_initializer(), tf.local_variables_initializer()))
saver_restore.restore(sess, args.Restore_path)
TP_list, pred_label_list, gt_label_list = [], [], []
while True:
try:
if args.Compare:
# To see the true boxes and pred boxes
PIXEL_MEANS = np.array([[[122.7717, 115.9465, 102.9801]]])
PIXEL_STDV = [[[0.229, 0.224, 0.2254]]]
image_, pred_boxes_, pred_labels_, pred_scores_, boxes_ = sess.run([image, pred_boxes, pred_labels, pred_scores, boxes])
for i, single_boxes in enumerate(pred_boxes_):
ori_image = image_[i]
ori_image = (ori_image * PIXEL_STDV) + PIXEL_MEANS / 255.0
# rescale the coordinates to the original image
single_boxes[:, 0] = single_boxes[:, 0] * 416.0
single_boxes[:, 1] = single_boxes[:, 1] * 416.0
single_boxes[:, 2] = single_boxes[:, 2] * 416.0
single_boxes[:, 3] = single_boxes[:, 3] * 416.0
for j, box in enumerate(single_boxes):
if np.sum(box) != 0.0:
ploy_rect(ori_image, box, (255, 0, 0))
print("********************************")
print(box[0], " ", box[1], " ", box[2], " ", box[3], LABELS[pred_labels_[i, j]], pred_scores_[i, j])
# Get the trye box
true_boxes = boxes_[i]
true_boxes[:, 0] = true_boxes[:, 0]
true_boxes[:, 1] = true_boxes[:, 1]
true_boxes[:, 2] = true_boxes[:, 2]
true_boxes[:, 3] = true_boxes[:, 3]
for j, box in enumerate(true_boxes):
if np.sum(box) != 0.0:
ploy_rect(ori_image, box, (0, 0, 255))
print("********************************")
print(box[0], " ", box[1], " ", box[2], " ", box[3])
cv2.namedWindow('Detection_result', 0)
cv2.imshow('Detection_result', ori_image)
cv2.waitKey(0)
else:
eval_result_ = sess.run(eval_result)
TP_array, pred_label_array, gt_label_array = eval_result_
TP_list.append(TP_array)
pred_label_list.append(pred_label_array)
gt_label_list.append(gt_label_array)
except tf.errors.OutOfRangeError:
break
precision = np.sum(np.array(TP_list)) / np.sum(np.array(pred_label_list))
recall = np.sum(np.array(TP_list)) / np.sum(np.array(gt_label_list))
info = "===> precision: {:.3f}, recall: {:.3f}".format(precision, recall)
print(info)
|
[
"utils.plot_utils.ploy_rect",
"numpy.sum",
"argparse.ArgumentParser",
"tensorflow.train.Saver",
"tensorflow.data.TFRecordDataset",
"tensorflow.global_variables_initializer",
"cv2.waitKey",
"tensorflow.Session",
"tensorflow.variable_scope",
"utils.data_utils.parser",
"tensorflow.local_variables_initializer",
"tensorflow.ConfigProto",
"numpy.array",
"tensorflow.Graph",
"Resnet_model.resnet101",
"cv2.imshow",
"cv2.namedWindow"
] |
[((583, 642), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""RetinaNet image test"""'}), "(description='RetinaNet image test')\n", (606, 642), False, 'import argparse\n'), ((1284, 1318), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['val_files'], {}), '(val_files)\n', (1307, 1318), True, 'import tensorflow as tf\n'), ((2115, 2131), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (2129, 2131), True, 'import tensorflow as tf\n'), ((2175, 2216), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (2189, 2216), True, 'import tensorflow as tf\n'), ((1668, 1695), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""yolov3"""'], {}), "('yolov3')\n", (1685, 1695), True, 'import tensorflow as tf\n'), ((1717, 1750), 'Resnet_model.resnet101', 'resnet101', (['NUM_CLASS', 'NUM_ANCHORS'], {}), '(NUM_CLASS, NUM_ANCHORS)\n', (1726, 1750), False, 'from Resnet_model import resnet101\n'), ((2289, 2314), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (2299, 2314), True, 'import tensorflow as tf\n'), ((1204, 1214), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1212, 1214), True, 'import tensorflow as tf\n'), ((1364, 1392), 'utils.data_utils.parser', 'parser', (['x', 'IMAGE_SIZE', '"""val"""'], {}), "(x, IMAGE_SIZE, 'val')\n", (1370, 1392), False, 'from utils.data_utils import parser\n'), ((2342, 2375), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2373, 2375), True, 'import tensorflow as tf\n'), ((2377, 2409), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (2407, 2409), True, 'import tensorflow as tf\n'), ((5153, 5170), 'numpy.array', 'np.array', (['TP_list'], {}), '(TP_list)\n', (5161, 5170), True, 'import numpy as np\n'), ((5181, 5206), 'numpy.array', 'np.array', (['pred_label_list'], {}), '(pred_label_list)\n', (5189, 5206), True, 'import numpy as np\n'), ((5232, 5249), 'numpy.array', 'np.array', (['TP_list'], {}), '(TP_list)\n', (5240, 5249), True, 'import numpy as np\n'), ((5260, 5283), 'numpy.array', 'np.array', (['gt_label_list'], {}), '(gt_label_list)\n', (5268, 5283), True, 'import numpy as np\n'), ((2693, 2737), 'numpy.array', 'np.array', (['[[[122.7717, 115.9465, 102.9801]]]'], {}), '([[[122.7717, 115.9465, 102.9801]]])\n', (2701, 2737), True, 'import numpy as np\n'), ((4588, 4626), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Detection_result"""', '(0)'], {}), "('Detection_result', 0)\n", (4603, 4626), False, 'import cv2\n'), ((4651, 4692), 'cv2.imshow', 'cv2.imshow', (['"""Detection_result"""', 'ori_image'], {}), "('Detection_result', ori_image)\n", (4661, 4692), False, 'import cv2\n'), ((4717, 4731), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (4728, 4731), False, 'import cv2\n'), ((3591, 3602), 'numpy.sum', 'np.sum', (['box'], {}), '(box)\n', (3597, 3602), True, 'import numpy as np\n'), ((3643, 3681), 'utils.plot_utils.ploy_rect', 'ploy_rect', (['ori_image', 'box', '(255, 0, 0)'], {}), '(ori_image, box, (255, 0, 0))\n', (3652, 3681), False, 'from utils.plot_utils import ploy_rect\n'), ((4313, 4324), 'numpy.sum', 'np.sum', (['box'], {}), '(box)\n', (4319, 4324), True, 'import numpy as np\n'), ((4365, 4403), 'utils.plot_utils.ploy_rect', 'ploy_rect', (['ori_image', 'box', '(0, 0, 255)'], {}), '(ori_image, box, (0, 0, 255))\n', (4374, 4403), False, 'from utils.plot_utils import ploy_rect\n')]
|
import numpy as np
import pandas as pd
def get_daily_vol(close, span=100):
"""Estimate exponential average volatility"""
use_idx = close.index.searchsorted(close.index - pd.Timedelta(days=1))
use_idx = use_idx[use_idx > 0]
# Get rid of duplications in index
use_idx = np.unique(use_idx)
prev_idx = pd.Series(close.index[use_idx - 1], index=close.index[use_idx])
ret = close.loc[prev_idx.index] / close.loc[prev_idx.values].values - 1
vol = ret.ewm(span=span).std()
return vol
|
[
"pandas.Series",
"numpy.unique",
"pandas.Timedelta"
] |
[((290, 308), 'numpy.unique', 'np.unique', (['use_idx'], {}), '(use_idx)\n', (299, 308), True, 'import numpy as np\n'), ((324, 387), 'pandas.Series', 'pd.Series', (['close.index[use_idx - 1]'], {'index': 'close.index[use_idx]'}), '(close.index[use_idx - 1], index=close.index[use_idx])\n', (333, 387), True, 'import pandas as pd\n'), ((180, 200), 'pandas.Timedelta', 'pd.Timedelta', ([], {'days': '(1)'}), '(days=1)\n', (192, 200), True, 'import pandas as pd\n')]
|
import argparse
import os.path as osp
import os
import shutil
import tempfile
import numpy as np
import mmcv
import torch
import copy
import torch.distributed as dist
from mmcv.runner import load_checkpoint, get_dist_info
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmdet.apis import init_dist
from mmdet.core import results2json, coco_eval
from mmdet.datasets import build_dataloader, get_dataset
from mmdet.models import build_detector
from mmdet.core import tensor2imgs, get_classes
from PIL import Image
import matplotlib.cm as mpl_color_map
import tqdm
import cv2
# import stackprinter
# stackprinter.set_excepthook(style='darkbg2')
class CamExtractor():
"""
Extracts cam features from the model
"""
def __init__(self, model):
self.model = model
self.gradients = None
def save_gradient(self, grad):
self.gradients = grad
def forward_pass(self, img,img_meta, return_loss=False, rescale=True, ):
"""
Does a forward pass on convolutions, hooks the function at given layer
"""
img=img[0]
img=img.cuda()
img.requires_grad=True
img.register_hook(self.save_gradient)
img_meta=img_meta
x=self.model(return_loss=False, rescale=True,img=[img],img_meta=img_meta)
return x
def apply_colormap_on_image(org_im, activation_org, colormap_name):
"""
Apply heatmap on image
Args:
org_img (PIL img): Original image
activation_map (numpy arr): Activation map (grayscale) 0-255
colormap_name (str): Name of the colormap
"""
# Get colormap
activation=np.uint8(activation_org * 255)
color_map = mpl_color_map.get_cmap(colormap_name)
no_trans_heatmap = color_map(activation)
# Change alpha channel in colormap to make sure original image is displayed
heatmap = copy.copy(no_trans_heatmap)
heatmap[:, :, 3] = activation_org
heatmap = Image.fromarray((heatmap*255).astype(np.uint8))
no_trans_heatmap = Image.fromarray((no_trans_heatmap*255).astype(np.uint8))
# Apply heatmap on iamge
heatmap_on_image = Image.new("RGBA", org_im.size)
heatmap_on_image = Image.alpha_composite(heatmap_on_image, org_im.convert('RGBA'))
heatmap_on_image = Image.alpha_composite(heatmap_on_image, heatmap)
return no_trans_heatmap,heatmap, heatmap_on_image
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test detector')
# parser.add_argument('config', help='test config file path')
# parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--work_dir', help='word_dir store epoch')
parser.add_argument(
'--eval',
type=str,
nargs='+',
choices=['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints'],
help='eval types')
parser.add_argument('--show', action='store_true', help='show results')
parser.add_argument('--tmpdir', help='tmp dir for writing some results')
parser.add_argument('--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument('--std', type=float, default=0.001)
args = parser.parse_args()
return args
def main():
args = parse_args()
checkpoint = './workdir/chimp/retinanet_r50/tc_mode2_train7_test21/epoch_7.pth'
config='configs/chimp/chimptest.py'
videos_foloer = '/mnt/storage/scratch/rn18510/infer_videos/'
videos=os.listdir(videos_foloer)
videos=['2AwqiWB5Ud.mp4','2miYEJ2Ofx.mp4']
print('tcm evaling')
inputstd=args.std
print(inputstd)
cfg = mmcv.Config.fromfile(config)
if 'video' in cfg:
video_model=cfg.video
else:
video_model=False
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
cfg.data.val.test_mode = True
cfg.data.val.type='CHIMP_INFER'
cfg.data.val.snip_frame=3
cfg.data.val.how_sparse=1
init_dist(args.launcher, **cfg.dist_params)
model = build_detector(cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg,video=video_model)
load_checkpoint(model, checkpoint, map_location='cpu')
extractor =CamExtractor(model)
datasets=[]
data_loaders=[]
precess_videos=[]
for video in videos:
cfg.data.val.ann_file = os.path.join(videos_foloer,video)
dataset = get_dataset(cfg.data.val)
data_loader = build_dataloader(dataset,
imgs_per_gpu=1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=True,
shuffle=False,
video=video_model)
datasets.append(dataset)
data_loaders.append(data_loader)
precess_videos.append(video)
model = model.cuda()
#model = MMDataParallel(model, device_ids=[0])
model = MMDistributedDataParallel(model.cuda())
model.eval()
for m in range(len(precess_videos)):
data_loader=data_loaders[m]
precess_video=precess_videos[m]
mmcv.mkdir_or_exist(f'./results/example/cam_{inputstd}/{precess_video}/heatmap/')
mmcv.mkdir_or_exist(f'./results/example/cam_{inputstd}/{precess_video}/no_tran_heatmap/')
mmcv.mkdir_or_exist(f'./results/example/cam_{inputstd}/{precess_video}/heatmap_on_image/')
dataset=datasets[m]
for i, data in tqdm.tqdm(enumerate(data_loader)):
outs=extractor.forward_pass(return_loss=False, rescale=True, **data)
#outs = model(return_loss=False, rescale=True, **data)
classification = outs[0]
b,a,h,w=outs[0][0].shape
classification=[out.view(b,a,-1) for out in classification]
classification = torch.cat(classification,dim=2)
classification=classification.sigmoid()
mask=classification>0.3
one_hot_output=torch.zeros_like(classification)
one_hot_output[mask]=1
model.zero_grad()
classification.backward(gradient=one_hot_output, retain_graph=True)
weights=extractor.gradients[0].detach().cpu()
weights=weights.permute(0,2,3,1).numpy()
img_tensor = data['img'][0]
size=img_tensor.size(1)
img_metas = data['img_meta'][0].data[0]*size
imgs = tensor2imgs(img_tensor[0,...], **cfg.img_norm_cfg)
for j,cam in enumerate(weights):
img_meta=img_metas[j]
img = imgs[j]
#img=img.permute(1,2,0).numpy()
h, w, _ = img_meta['img_shape']
img_show = img[:h, :w, :]
img_show = mmcv.imrescale(img_show,1/img_meta['scale_factor'])
cv2.imwrite(f'./results/grad_sample/{precess_video}/org/{i}_{j}.jpg',img_show)
#print(img.shape)
img=Image.fromarray(np.array(img,dtype=np.uint8))
#print(cam.shape)
cam=cam.mean(axis=2)
# #cam basic knowledge
# print('min', cam.min())
# print('mean',cam.mean())
# print('max',cam.max())
# print('std',cam.std()) #around 0.012
std=inputstd
xtime=500
cam=abs(cam)-std
cam=np.where(cam>0,cam,0)
cam=np.where(cam<std*xtime,cam,std*xtime)
#apply 3 std ways
# cam_std=cam.std()
# cam_mean=cam.mean()
#cam = (cam - np.min(cam)) / (np.max(cam) - np.min(cam))
cam=cam/std/xtime
cam = np.uint8(cam * 255)
no_tran_heatmap,heatmap ,heatmap_on_image = apply_colormap_on_image(img, cam, 'Blues')
heatmap_on_image=cv2.cvtColor(np.array(heatmap_on_image),cv2.COLOR_RGBA2RGB)
no_tran_heatmap=cv2.cvtColor(np.array(no_tran_heatmap),cv2.COLOR_RGBA2RGB)
heatmap=cv2.cvtColor(np.array(heatmap),cv2.COLOR_RGBA2RGB)
heatmap_on_image = heatmap_on_image[:h, :w, :]
heatmap_on_image = mmcv.imrescale(heatmap_on_image,1/img_meta['scale_factor'])
no_tran_heatmap = no_tran_heatmap[:h, :w, :]
no_tran_heatmap = mmcv.imrescale(no_tran_heatmap,1/img_meta['scale_factor'])
heatmap = heatmap[:h, :w, :]
heatmap = mmcv.imrescale(heatmap,1/img_meta['scale_factor'])
cv2.imwrite(f'./results/example/cam_{inputstd}/{precess_video}/heatmap/{i}_{j}.jpg',heatmap)
cv2.imwrite(f'./results/example/cam_{inputstd}/{precess_video}/heatmap_on_image/{i}_{j}.jpg',heatmap_on_image)
cv2.imwrite(f'./results/example/cam_{inputstd}/{precess_video}/no_tran_heatmap/{i}_{j}.jpg',no_tran_heatmap)
if __name__ == "__main__":
main()
|
[
"PIL.Image.new",
"argparse.ArgumentParser",
"matplotlib.cm.get_cmap",
"mmcv.mkdir_or_exist",
"mmdet.datasets.get_dataset",
"torch.cat",
"mmcv.Config.fromfile",
"mmdet.core.tensor2imgs",
"os.path.join",
"mmdet.models.build_detector",
"cv2.imwrite",
"mmcv.imrescale",
"mmdet.apis.init_dist",
"mmdet.datasets.build_dataloader",
"numpy.uint8",
"torch.zeros_like",
"mmcv.runner.load_checkpoint",
"os.listdir",
"copy.copy",
"PIL.Image.alpha_composite",
"numpy.where",
"numpy.array"
] |
[((1656, 1686), 'numpy.uint8', 'np.uint8', (['(activation_org * 255)'], {}), '(activation_org * 255)\n', (1664, 1686), True, 'import numpy as np\n'), ((1703, 1740), 'matplotlib.cm.get_cmap', 'mpl_color_map.get_cmap', (['colormap_name'], {}), '(colormap_name)\n', (1725, 1740), True, 'import matplotlib.cm as mpl_color_map\n'), ((1880, 1907), 'copy.copy', 'copy.copy', (['no_trans_heatmap'], {}), '(no_trans_heatmap)\n', (1889, 1907), False, 'import copy\n'), ((2141, 2171), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', 'org_im.size'], {}), "('RGBA', org_im.size)\n", (2150, 2171), False, 'from PIL import Image\n'), ((2282, 2330), 'PIL.Image.alpha_composite', 'Image.alpha_composite', (['heatmap_on_image', 'heatmap'], {}), '(heatmap_on_image, heatmap)\n', (2303, 2330), False, 'from PIL import Image\n'), ((2417, 2475), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MMDet test detector"""'}), "(description='MMDet test detector')\n", (2440, 2475), False, 'import argparse\n'), ((3606, 3631), 'os.listdir', 'os.listdir', (['videos_foloer'], {}), '(videos_foloer)\n', (3616, 3631), False, 'import os\n'), ((3756, 3784), 'mmcv.Config.fromfile', 'mmcv.Config.fromfile', (['config'], {}), '(config)\n', (3776, 3784), False, 'import mmcv\n'), ((4127, 4170), 'mmdet.apis.init_dist', 'init_dist', (['args.launcher'], {}), '(args.launcher, **cfg.dist_params)\n', (4136, 4170), False, 'from mmdet.apis import init_dist\n'), ((4184, 4280), 'mmdet.models.build_detector', 'build_detector', (['cfg.model'], {'train_cfg': 'cfg.train_cfg', 'test_cfg': 'cfg.test_cfg', 'video': 'video_model'}), '(cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg,\n video=video_model)\n', (4198, 4280), False, 'from mmdet.models import build_detector\n'), ((4280, 4334), 'mmcv.runner.load_checkpoint', 'load_checkpoint', (['model', 'checkpoint'], {'map_location': '"""cpu"""'}), "(model, checkpoint, map_location='cpu')\n", (4295, 4334), False, 'from mmcv.runner import load_checkpoint, get_dist_info\n'), ((4486, 4520), 'os.path.join', 'os.path.join', (['videos_foloer', 'video'], {}), '(videos_foloer, video)\n', (4498, 4520), False, 'import os\n'), ((4538, 4563), 'mmdet.datasets.get_dataset', 'get_dataset', (['cfg.data.val'], {}), '(cfg.data.val)\n', (4549, 4563), False, 'from mmdet.datasets import build_dataloader, get_dataset\n'), ((4586, 4719), 'mmdet.datasets.build_dataloader', 'build_dataloader', (['dataset'], {'imgs_per_gpu': '(1)', 'workers_per_gpu': 'cfg.data.workers_per_gpu', 'dist': '(True)', 'shuffle': '(False)', 'video': 'video_model'}), '(dataset, imgs_per_gpu=1, workers_per_gpu=cfg.data.\n workers_per_gpu, dist=True, shuffle=False, video=video_model)\n', (4602, 4719), False, 'from mmdet.datasets import build_dataloader, get_dataset\n'), ((5298, 5384), 'mmcv.mkdir_or_exist', 'mmcv.mkdir_or_exist', (['f"""./results/example/cam_{inputstd}/{precess_video}/heatmap/"""'], {}), "(\n f'./results/example/cam_{inputstd}/{precess_video}/heatmap/')\n", (5317, 5384), False, 'import mmcv\n'), ((5388, 5482), 'mmcv.mkdir_or_exist', 'mmcv.mkdir_or_exist', (['f"""./results/example/cam_{inputstd}/{precess_video}/no_tran_heatmap/"""'], {}), "(\n f'./results/example/cam_{inputstd}/{precess_video}/no_tran_heatmap/')\n", (5407, 5482), False, 'import mmcv\n'), ((5486, 5581), 'mmcv.mkdir_or_exist', 'mmcv.mkdir_or_exist', (['f"""./results/example/cam_{inputstd}/{precess_video}/heatmap_on_image/"""'], {}), "(\n f'./results/example/cam_{inputstd}/{precess_video}/heatmap_on_image/')\n", (5505, 5581), False, 'import mmcv\n'), ((5986, 6018), 'torch.cat', 'torch.cat', (['classification'], {'dim': '(2)'}), '(classification, dim=2)\n', (5995, 6018), False, 'import torch\n'), ((6134, 6166), 'torch.zeros_like', 'torch.zeros_like', (['classification'], {}), '(classification)\n', (6150, 6166), False, 'import torch\n'), ((6576, 6627), 'mmdet.core.tensor2imgs', 'tensor2imgs', (['img_tensor[0, ...]'], {}), '(img_tensor[0, ...], **cfg.img_norm_cfg)\n', (6587, 6627), False, 'from mmdet.core import tensor2imgs, get_classes\n'), ((6905, 6959), 'mmcv.imrescale', 'mmcv.imrescale', (['img_show', "(1 / img_meta['scale_factor'])"], {}), "(img_show, 1 / img_meta['scale_factor'])\n", (6919, 6959), False, 'import mmcv\n'), ((6973, 7052), 'cv2.imwrite', 'cv2.imwrite', (['f"""./results/grad_sample/{precess_video}/org/{i}_{j}.jpg"""', 'img_show'], {}), "(f'./results/grad_sample/{precess_video}/org/{i}_{j}.jpg', img_show)\n", (6984, 7052), False, 'import cv2\n'), ((7552, 7577), 'numpy.where', 'np.where', (['(cam > 0)', 'cam', '(0)'], {}), '(cam > 0, cam, 0)\n', (7560, 7577), True, 'import numpy as np\n'), ((7594, 7639), 'numpy.where', 'np.where', (['(cam < std * xtime)', 'cam', '(std * xtime)'], {}), '(cam < std * xtime, cam, std * xtime)\n', (7602, 7639), True, 'import numpy as np\n'), ((7871, 7890), 'numpy.uint8', 'np.uint8', (['(cam * 255)'], {}), '(cam * 255)\n', (7879, 7890), True, 'import numpy as np\n'), ((8353, 8415), 'mmcv.imrescale', 'mmcv.imrescale', (['heatmap_on_image', "(1 / img_meta['scale_factor'])"], {}), "(heatmap_on_image, 1 / img_meta['scale_factor'])\n", (8367, 8415), False, 'import mmcv\n'), ((8509, 8570), 'mmcv.imrescale', 'mmcv.imrescale', (['no_tran_heatmap', "(1 / img_meta['scale_factor'])"], {}), "(no_tran_heatmap, 1 / img_meta['scale_factor'])\n", (8523, 8570), False, 'import mmcv\n'), ((8640, 8693), 'mmcv.imrescale', 'mmcv.imrescale', (['heatmap', "(1 / img_meta['scale_factor'])"], {}), "(heatmap, 1 / img_meta['scale_factor'])\n", (8654, 8693), False, 'import mmcv\n'), ((8708, 8810), 'cv2.imwrite', 'cv2.imwrite', (['f"""./results/example/cam_{inputstd}/{precess_video}/heatmap/{i}_{j}.jpg"""', 'heatmap'], {}), "(\n f'./results/example/cam_{inputstd}/{precess_video}/heatmap/{i}_{j}.jpg',\n heatmap)\n", (8719, 8810), False, 'import cv2\n'), ((8817, 8938), 'cv2.imwrite', 'cv2.imwrite', (['f"""./results/example/cam_{inputstd}/{precess_video}/heatmap_on_image/{i}_{j}.jpg"""', 'heatmap_on_image'], {}), "(\n f'./results/example/cam_{inputstd}/{precess_video}/heatmap_on_image/{i}_{j}.jpg'\n , heatmap_on_image)\n", (8828, 8938), False, 'import cv2\n'), ((8944, 9063), 'cv2.imwrite', 'cv2.imwrite', (['f"""./results/example/cam_{inputstd}/{precess_video}/no_tran_heatmap/{i}_{j}.jpg"""', 'no_tran_heatmap'], {}), "(\n f'./results/example/cam_{inputstd}/{precess_video}/no_tran_heatmap/{i}_{j}.jpg'\n , no_tran_heatmap)\n", (8955, 9063), False, 'import cv2\n'), ((7123, 7152), 'numpy.array', 'np.array', (['img'], {'dtype': 'np.uint8'}), '(img, dtype=np.uint8)\n', (7131, 7152), True, 'import numpy as np\n'), ((8041, 8067), 'numpy.array', 'np.array', (['heatmap_on_image'], {}), '(heatmap_on_image)\n', (8049, 8067), True, 'import numpy as np\n'), ((8133, 8158), 'numpy.array', 'np.array', (['no_tran_heatmap'], {}), '(no_tran_heatmap)\n', (8141, 8158), True, 'import numpy as np\n'), ((8216, 8233), 'numpy.array', 'np.array', (['heatmap'], {}), '(heatmap)\n', (8224, 8233), True, 'import numpy as np\n')]
|
from __future__ import print_function, division
import os
import numpy as np
from astropy.table import Table
from . import six
from .fit_info import FitInfo, FitInfoFile
from .extinction import Extinction
from .models import load_parameter_table
def write_parameters(input_fits, output_file, select_format=("N", 1), additional={}):
"""
Write out an ASCII file with the paramters for each source.
Parameters
----------
input_fits : str or :class:`sedfitter.fit_info.FitInfo` or iterable
This should be either a file containing the fit information, a
:class:`sedfitter.fit_info.FitInfo` instance, or an iterable containing
:class:`sedfitter.fit_info.FitInfo` instances.
output_file : str, optional
The output ASCII file containing the parameters
select_format : tuple, optional
Tuple specifying which fits should be output. See the documentation
for a description of the tuple syntax.
additional : dict, optional
A dictionary giving additional parameters for each model. This should
be a dictionary where each key is a parameter, and each value is a
dictionary mapping the model names to the parameter values.
"""
# Open input and output file
fin = FitInfoFile(input_fits, 'r')
fout = open(output_file, 'w')
# Read in table of parameters for model grid
t = load_parameter_table(fin.meta.model_dir)
t['MODEL_NAME'] = np.char.strip(t['MODEL_NAME'])
t.sort('MODEL_NAME')
# First header line
fout.write("source_name".center(30) + ' ')
fout.write("n_data".center(10) + ' ')
fout.write("n_fits".center(10) + ' ')
fout.write('\n')
# Second header line
fout.write('fit_id'.center(10) + ' ')
fout.write('model_name'.center(30) + ' ')
fout.write('chi2'.center(10) + ' ')
fout.write('av'.center(10) + ' ')
fout.write('scale'.center(10) + ' ')
for par in list(t.columns.keys()) + list(additional.keys()):
if par == 'MODEL_NAME':
continue
fout.write(par.lower().center(10) + ' ')
fout.write('\n')
fout.write('-' * (75 + 11 * (len(list(t.columns.keys()) + list(additional.keys())))))
fout.write('\n')
for info in fin:
# Filter fits
info.keep(select_format[0], select_format[1])
# Get filtered and sorted table of parameters
tsorted = info.filter_table(t, additional=additional)
fout.write("%30s " % info.source.name)
fout.write("%10i " % info.source.n_data)
fout.write("%10i " % info.n_fits)
fout.write("\n")
for fit_id in range(len(info.chi2)):
fout.write('%10i ' % (fit_id + 1))
fout.write('%30s ' % info.model_name[fit_id])
fout.write('%10.3f ' % info.chi2[fit_id])
fout.write('%10.3f ' % info.av[fit_id])
fout.write('%10.3f ' % info.sc[fit_id])
for par in tsorted.columns:
if par == 'MODEL_NAME':
continue
fout.write('%10.3e ' % (tsorted[par][fit_id]))
fout.write('\n')
# Close input and output files
fin.close()
fout.close()
fout.close()
|
[
"numpy.char.strip"
] |
[((1455, 1485), 'numpy.char.strip', 'np.char.strip', (["t['MODEL_NAME']"], {}), "(t['MODEL_NAME'])\n", (1468, 1485), True, 'import numpy as np\n')]
|
"""
Test the grid search for BNMTF, in grid_search_bnmtf.py
"""
import sys, os
project_location = os.path.dirname(__file__)+"/../../../"
sys.path.append(project_location)
from BNMTF.code.cross_validation.greedy_search_bnmtf import GreedySearch
from BNMTF.code.models.bnmtf_vb_optimised import bnmtf_vb_optimised
import numpy, pytest, random
classifier = bnmtf_vb_optimised
def test_init():
I,J = 10,9
values_K = [1,2,4,5]
values_L = [5,4,3]
R = 2*numpy.ones((I,J))
M = numpy.ones((I,J))
priors = { 'alpha':3, 'beta':4, 'lambdaF':5, 'lambdaS':6, 'lambdaG':7 }
initFG = 'exp'
initS = 'random'
iterations = 11
greedysearch = GreedySearch(classifier,values_K,values_L,R,M,priors,initS,initFG,iterations)
assert greedysearch.I == I
assert greedysearch.J == J
assert numpy.array_equal(greedysearch.values_K, values_K)
assert numpy.array_equal(greedysearch.values_L, values_L)
assert numpy.array_equal(greedysearch.R, R)
assert numpy.array_equal(greedysearch.M, M)
assert greedysearch.priors == priors
assert greedysearch.iterations == iterations
assert greedysearch.initS == initS
assert greedysearch.initFG == initFG
assert greedysearch.all_performances['BIC'] == []
assert greedysearch.all_performances['AIC'] == []
assert greedysearch.all_performances['loglikelihood'] == []
def test_search():
# Check whether we get no exceptions...
I,J = 10,9
values_K = [1,2,4,5]
values_L = [5,4,3]
R = 2*numpy.ones((I,J))
R[0,0] = 1
M = numpy.ones((I,J))
priors = { 'alpha':3, 'beta':4, 'lambdaF':5, 'lambdaS':6, 'lambdaG':7 }
initFG = 'exp'
initS = 'exp'
iterations = 1
search_metric = 'BIC'
numpy.random.seed(0)
random.seed(0)
greedysearch = GreedySearch(classifier,values_K,values_L,R,M,priors,initS,initFG,iterations)
greedysearch.search(search_metric)
with pytest.raises(AssertionError) as error:
greedysearch.all_values('FAIL')
assert str(error.value) == "Unrecognised metric name: FAIL."
# We go from: (1,5) -> (1,4) -> (1,3), and try 6 locations
assert len(greedysearch.all_values('BIC')) == 6
def test_all_values():
I,J = 10,9
values_K = [1,2,4,5]
values_L = [5,4,3]
R = 2*numpy.ones((I,J))
M = numpy.ones((I,J))
priors = { 'alpha':3, 'beta':4, 'lambdaF':5, 'lambdaS':6, 'lambdaG':7 }
initFG = 'exp'
initS = 'random'
iterations = 11
greedysearch = GreedySearch(classifier,values_K,values_L,R,M,priors,initS,initFG,iterations)
greedysearch.all_performances = {
'BIC' : [(1,2,10.),(2,2,20.),(2,3,30.),(2,4,40.),(5,3,20.)],
'AIC' : [(1,2,10.),(2,2,20.),(2,3,30.),(2,4,25.),(5,3,20.)],
'loglikelihood' : [(1,2,10.),(2,2,50.),(2,3,30.),(2,4,40.),(5,3,20.)]
}
assert numpy.array_equal(greedysearch.all_values('BIC'), [(1,2,10.),(2,2,20.),(2,3,30.),(2,4,40.),(5,3,20.)])
assert numpy.array_equal(greedysearch.all_values('AIC'), [(1,2,10.),(2,2,20.),(2,3,30.),(2,4,25.),(5,3,20.)])
assert numpy.array_equal(greedysearch.all_values('loglikelihood'), [(1,2,10.),(2,2,50.),(2,3,30.),(2,4,40.),(5,3,20.)])
with pytest.raises(AssertionError) as error:
greedysearch.all_values('FAIL')
assert str(error.value) == "Unrecognised metric name: FAIL."
def test_best_value():
I,J = 10,9
values_K = [1,2,4,5]
values_L = [5,4,3]
R = 2*numpy.ones((I,J))
M = numpy.ones((I,J))
priors = { 'alpha':3, 'beta':4, 'lambdaF':5, 'lambdaS':6, 'lambdaG':7 }
initFG = 'exp'
initS = 'random'
iterations = 11
greedysearch = GreedySearch(classifier,values_K,values_L,R,M,priors,initS,initFG,iterations)
greedysearch.all_performances = {
'BIC' : [(1,2,10.),(2,2,20.),(2,3,30.),(2,4,5.),(5,3,20.)],
'AIC' : [(1,2,10.),(2,2,20.),(2,3,4.),(2,4,25.),(5,3,20.)],
'loglikelihood' : [(1,2,10.),(2,2,8.),(2,3,30.),(2,4,40.),(5,3,20.)]
}
assert greedysearch.best_value('BIC') == (2,4)
assert greedysearch.best_value('AIC') == (2,3)
assert greedysearch.best_value('loglikelihood') == (2,2)
with pytest.raises(AssertionError) as error:
greedysearch.all_values('FAIL')
assert str(error.value) == "Unrecognised metric name: FAIL."
|
[
"sys.path.append",
"numpy.random.seed",
"os.path.dirname",
"numpy.ones",
"pytest.raises",
"random.seed",
"numpy.array_equal",
"BNMTF.code.cross_validation.greedy_search_bnmtf.GreedySearch"
] |
[((138, 171), 'sys.path.append', 'sys.path.append', (['project_location'], {}), '(project_location)\n', (153, 171), False, 'import sys, os\n'), ((99, 124), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (114, 124), False, 'import sys, os\n'), ((493, 511), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (503, 511), False, 'import numpy, pytest, random\n'), ((671, 760), 'BNMTF.code.cross_validation.greedy_search_bnmtf.GreedySearch', 'GreedySearch', (['classifier', 'values_K', 'values_L', 'R', 'M', 'priors', 'initS', 'initFG', 'iterations'], {}), '(classifier, values_K, values_L, R, M, priors, initS, initFG,\n iterations)\n', (683, 760), False, 'from BNMTF.code.cross_validation.greedy_search_bnmtf import GreedySearch\n'), ((822, 872), 'numpy.array_equal', 'numpy.array_equal', (['greedysearch.values_K', 'values_K'], {}), '(greedysearch.values_K, values_K)\n', (839, 872), False, 'import numpy, pytest, random\n'), ((884, 934), 'numpy.array_equal', 'numpy.array_equal', (['greedysearch.values_L', 'values_L'], {}), '(greedysearch.values_L, values_L)\n', (901, 934), False, 'import numpy, pytest, random\n'), ((946, 982), 'numpy.array_equal', 'numpy.array_equal', (['greedysearch.R', 'R'], {}), '(greedysearch.R, R)\n', (963, 982), False, 'import numpy, pytest, random\n'), ((994, 1030), 'numpy.array_equal', 'numpy.array_equal', (['greedysearch.M', 'M'], {}), '(greedysearch.M, M)\n', (1011, 1030), False, 'import numpy, pytest, random\n'), ((1560, 1578), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (1570, 1578), False, 'import numpy, pytest, random\n'), ((1745, 1765), 'numpy.random.seed', 'numpy.random.seed', (['(0)'], {}), '(0)\n', (1762, 1765), False, 'import numpy, pytest, random\n'), ((1770, 1784), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (1781, 1784), False, 'import numpy, pytest, random\n'), ((1804, 1893), 'BNMTF.code.cross_validation.greedy_search_bnmtf.GreedySearch', 'GreedySearch', (['classifier', 'values_K', 'values_L', 'R', 'M', 'priors', 'initS', 'initFG', 'iterations'], {}), '(classifier, values_K, values_L, R, M, priors, initS, initFG,\n iterations)\n', (1816, 1893), False, 'from BNMTF.code.cross_validation.greedy_search_bnmtf import GreedySearch\n'), ((2332, 2350), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (2342, 2350), False, 'import numpy, pytest, random\n'), ((2510, 2599), 'BNMTF.code.cross_validation.greedy_search_bnmtf.GreedySearch', 'GreedySearch', (['classifier', 'values_K', 'values_L', 'R', 'M', 'priors', 'initS', 'initFG', 'iterations'], {}), '(classifier, values_K, values_L, R, M, priors, initS, initFG,\n iterations)\n', (2522, 2599), False, 'from BNMTF.code.cross_validation.greedy_search_bnmtf import GreedySearch\n'), ((3486, 3504), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (3496, 3504), False, 'import numpy, pytest, random\n'), ((3664, 3753), 'BNMTF.code.cross_validation.greedy_search_bnmtf.GreedySearch', 'GreedySearch', (['classifier', 'values_K', 'values_L', 'R', 'M', 'priors', 'initS', 'initFG', 'iterations'], {}), '(classifier, values_K, values_L, R, M, priors, initS, initFG,\n iterations)\n', (3676, 3753), False, 'from BNMTF.code.cross_validation.greedy_search_bnmtf import GreedySearch\n'), ((467, 485), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (477, 485), False, 'import numpy, pytest, random\n'), ((1519, 1537), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (1529, 1537), False, 'import numpy, pytest, random\n'), ((1935, 1964), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (1948, 1964), False, 'import numpy, pytest, random\n'), ((2306, 2324), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (2316, 2324), False, 'import numpy, pytest, random\n'), ((3209, 3238), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (3222, 3238), False, 'import numpy, pytest, random\n'), ((3460, 3478), 'numpy.ones', 'numpy.ones', (['(I, J)'], {}), '((I, J))\n', (3470, 3478), False, 'import numpy, pytest, random\n'), ((4171, 4200), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (4184, 4200), False, 'import numpy, pytest, random\n')]
|
""" Base class for all systems in OpenMDAO."""
import sys
from fnmatch import fnmatch
from itertools import chain
from six import string_types, iteritems, itervalues
import numpy as np
from openmdao.core.mpi_wrap import MPI
from openmdao.core.options import OptionsDictionary
from collections import OrderedDict
from openmdao.core.vec_wrapper import _PlaceholderVecWrapper
class System(object):
""" Base class for systems in OpenMDAO. When building models, user should
inherit from `Group` or `Component`"""
def __init__(self):
self.name = ''
self.pathname = ''
self._params_dict = OrderedDict()
self._unknowns_dict = OrderedDict()
# specify which variables are promoted up to the parent. Wildcards
# are allowed.
self._promotes = ()
self.comm = None
# create placeholders for all of the vectors
self.unknowns = _PlaceholderVecWrapper('unknowns')
self.resids = _PlaceholderVecWrapper('resids')
self.params = _PlaceholderVecWrapper('params')
self.dunknowns = _PlaceholderVecWrapper('dunknowns')
self.dresids = _PlaceholderVecWrapper('dresids')
self.dparams = _PlaceholderVecWrapper('dparams')
# dicts of vectors used for parallel solution of multiple RHS
self.dumat = {}
self.dpmat = {}
self.drmat = {}
opt = self.fd_options = OptionsDictionary()
opt.add_option('force_fd', False,
desc="Set to True to finite difference this system.")
opt.add_option('form', 'forward',
values=['forward', 'backward', 'central', 'complex_step'],
desc="Finite difference mode. (forward, backward, central) "
"You can also set to 'complex_step' to peform the complex "
"step method if your components support it.")
opt.add_option("step_size", 1.0e-6,
desc="Default finite difference stepsize")
opt.add_option("step_type", 'absolute',
values=['absolute', 'relative'],
desc='Set to absolute, relative')
self._relevance = None
self._impl_factory = None
def __getitem__(self, name):
"""
Return the variable of the given name from this system.
Args
----
name : str
The name of the variable.
Returns
-------
value
The unflattened value of the given variable.
"""
msg = "Variable '%s' must be accessed from a containing Group"
raise RuntimeError(msg % name)
def _promoted(self, name):
"""Determine if the given variable name is being promoted from this
`System`.
Args
----
name : str
The name of a variable, relative to this `System`.
Returns
-------
bool
True if the named variable is being promoted from this `System`.
Raises
------
TypeError
if the promoted variable specifications are not in a valid format
"""
if isinstance(self._promotes, string_types):
raise TypeError("'%s' promotes must be specified as a list, "
"tuple or other iterator of strings, but '%s' was specified" %
(self.name, self._promotes))
for prom in self._promotes:
if fnmatch(name, prom):
for meta in chain(itervalues(self._params_dict),
itervalues(self._unknowns_dict)):
if name == meta.get('promoted_name'):
return True
return False
def check_setup(self, out_stream=sys.stdout):
"""Write a report to the given stream indicating any potential problems found
with the current configuration of this ``System``.
Args
----
out_stream : a file-like object, optional
Stream where report will be written.
"""
pass
def _check_promotes(self):
"""Check that the `System`s promotes are valid. Raise an Exception if there
are any promotes that do not match at least one variable in the `System`.
Raises
------
TypeError
if the promoted variable specifications are not in a valid format
RuntimeError
if a promoted variable specification does not match any variables
"""
if isinstance(self._promotes, string_types):
raise TypeError("'%s' promotes must be specified as a list, "
"tuple or other iterator of strings, but '%s' was specified" %
(self.name, self._promotes))
for prom in self._promotes:
for name, meta in chain(iteritems(self._params_dict),
iteritems(self._unknowns_dict)):
if 'promoted_name' in meta:
pname = meta['promoted_name']
else:
pname = name
if fnmatch(pname, prom):
break
else:
msg = "'%s' promotes '%s' but has no variables matching that specification"
raise RuntimeError(msg % (self.name, prom))
def subsystems(self, local=False, recurse=False, include_self=False):
""" Returns an iterator over subsystems. For `System`, this is an empty list.
Args
----
local : bool, optional
If True, only return those `Components` that are local. Default is False.
recurse : bool, optional
If True, return all `Components` in the system tree, subject to
the value of the local arg. Default is False.
typ : type, optional
If a class is specified here, only those subsystems that are instances
of that type will be returned. Default type is `System`.
include_self : bool, optional
If True, yield self before iterating over subsystems, assuming type
of self is appropriate. Default is False.
Returns
-------
iterator
Iterator over subsystems.
"""
if include_self:
yield self
def _setup_paths(self, parent_path):
"""Set the absolute pathname of each `System` in the tree.
Parameter
---------
parent_path : str
The pathname of the parent `System`, which is to be prepended to the
name of this child `System`.
"""
if parent_path:
self.pathname = '.'.join((parent_path, self.name))
else:
self.pathname = self.name
def clear_dparams(self):
""" Zeros out the dparams (dp) vector."""
for parallel_set in self._relevance.vars_of_interest():
for name in parallel_set:
if name in self.dpmat:
self.dpmat[name].vec[:] = 0.0
self.dpmat[None].vec[:] = 0.0
# Recurse to clear all dparams vectors.
for system in self.subsystems(local=True):
system.clear_dparams()
def solve_linear(self, dumat, drmat, vois, mode=None):
"""
Single linear solution applied to whatever input is sitting in
the rhs vector.
Args
----
dumat : dict of `VecWrappers`
In forward mode, each `VecWrapper` contains the incoming vector
for the states. There is one vector per quantity of interest for
this problem. In reverse mode, it contains the outgoing vector for
the states. (du)
drmat : `dict of VecWrappers`
`VecWrapper` containing either the outgoing result in forward mode
or the incoming vector in reverse mode. There is one vector per
quantity of interest for this problem. (dr)
vois : list of strings
List of all quantities of interest to key into the mats.
mode : string
Derivative mode, can be 'fwd' or 'rev', but generally should be
called without mode so that the user can set the mode in this
system's ln_solver.options.
"""
pass
def is_active(self):
"""
Returns
-------
bool
If running under MPI, returns True if this `System` has a valid
communicator. Always returns True if not running under MPI.
"""
return MPI is None or self.comm != MPI.COMM_NULL
def get_req_procs(self):
"""
Returns
-------
tuple
A tuple of the form (min_procs, max_procs), indicating the min and max
processors usable by this `System`.
"""
return (1, 1)
def _setup_communicators(self, comm):
"""
Assign communicator to this `System` and all of its subsystems.
Args
----
comm : an MPI communicator (real or fake)
The communicator being offered by the parent system.
"""
self.comm = comm
def _set_vars_as_remote(self):
"""
Set 'remote' attribute in metadata of all variables for this subsystem.
"""
for meta in itervalues(self._params_dict):
meta['remote'] = True
for meta in itervalues(self._unknowns_dict):
meta['remote'] = True
def fd_jacobian(self, params, unknowns, resids, step_size=None, form=None,
step_type=None, total_derivs=False, fd_params=None,
fd_unknowns=None):
"""Finite difference across all unknowns in this system w.r.t. all
incoming params.
Args
----
params : `VecWrapper`
`VecWrapper` containing parameters. (p)
unknowns : `VecWrapper`
`VecWrapper` containing outputs and states. (u)
resids : `VecWrapper`
`VecWrapper` containing residuals. (r)
step_size : float, optional
Override all other specifications of finite difference step size.
form : float, optional
Override all other specifications of form. Can be forward,
backward, or central.
step_type : float, optional
Override all other specifications of step_type. Can be absolute
or relative.
total_derivs : bool, optional
Set to true to calculate total derivatives. Otherwise, partial
derivatives are returned.
fd_params : list of strings, optional
List of parameter name strings with respect to which derivatives
are desired. This is used by problem to limit the derivatives that
are taken.
fd_unknowns : list of strings, optional
List of output or state name strings for derivatives to be
calculated. This is used by problem to limit the derivatives that
are taken.
Returns
-------
dict
Dictionary whose keys are tuples of the form ('unknown', 'param')
and whose values are ndarrays containing the derivative for that
tuple pair.
"""
# Params and Unknowns that we provide at this level.
if fd_params is None:
fd_params = self._get_fd_params()
if fd_unknowns is None:
fd_unknowns = self._get_fd_unknowns()
# Function call arguments have precedence over the system dict.
step_size = self.fd_options.get('step_size', step_size)
form = self.fd_options.get('form', form)
step_type = self.fd_options.get('step_type', step_type)
jac = {}
cache2 = None
# Prepare for calculating partial derivatives or total derivatives
if total_derivs == False:
run_model = self.apply_nonlinear
cache1 = resids.vec.copy()
resultvec = resids
states = [name for name, meta in iteritems(self.unknowns)
if meta.get('state')]
else:
run_model = self.solve_nonlinear
cache1 = unknowns.vec.copy()
resultvec = unknowns
states = []
# Compute gradient for this param or state.
for p_name in chain(fd_params, states):
# If our input is connected to a Paramcomp, then we need to twiddle
# the unknowns vector instead of the params vector.
param_src = self.connections.get(p_name)
if param_src is not None:
# Have to convert to promoted name to key into unknowns
if param_src not in self.unknowns:
param_src = self.unknowns.get_promoted_varname(param_src)
target_input = unknowns.flat[param_src]
else:
# Cases where the paramcomp is somewhere above us.
if p_name in states:
inputs = unknowns
else:
inputs = params
target_input = inputs.flat[p_name]
mydict = {}
if p_name in self._to_abs_pnames:
for val in itervalues(self._params_dict):
if val['promoted_name'] == p_name:
mydict = val
break
# Local settings for this var trump all
fdstep = mydict.get('fd_step_size', step_size)
fdtype = mydict.get('fd_step_type', step_type)
fdform = mydict.get('fd_form', form)
# Size our Inputs
p_size = np.size(target_input)
# Size our Outputs
for u_name in fd_unknowns:
u_size = np.size(unknowns[u_name])
jac[u_name, p_name] = np.zeros((u_size, p_size))
# Finite Difference each index in array
for idx in range(p_size):
# Relative or Absolute step size
if fdtype == 'relative':
step = target_input[idx] * fdstep
if step < fdstep:
step = fdstep
else:
step = fdstep
if fdform == 'forward':
target_input[idx] += step
run_model(params, unknowns, resids)
target_input[idx] -= step
# delta resid is delta unknown
resultvec.vec[:] -= cache1
resultvec.vec[:] *= (1.0/step)
elif fdform == 'backward':
target_input[idx] -= step
run_model(params, unknowns, resids)
target_input[idx] += step
# delta resid is delta unknown
resultvec.vec[:] -= cache1
resultvec.vec[:] *= (-1.0/step)
elif fdform == 'central':
target_input[idx] += step
run_model(params, unknowns, resids)
cache2 = resultvec.vec.copy()
target_input[idx] -= step
resultvec.vec[:] = cache1
target_input[idx] -= step
run_model(params, unknowns, resids)
# central difference formula
resultvec.vec[:] -= cache2
resultvec.vec[:] *= (-0.5/step)
target_input[idx] += step
for u_name in fd_unknowns:
jac[u_name, p_name][:, idx] = resultvec.flat[u_name]
# Restore old residual
resultvec.vec[:] = cache1
return jac
def _apply_linear_jac(self, params, unknowns, dparams, dunknowns, dresids, mode):
""" See apply_linear. This method allows the framework to override
any derivative specification in any `Component` or `Group` to perform
finite difference."""
if not self._jacobian_cache:
msg = ("No derivatives defined for Component '{name}'")
msg = msg.format(name=self.name)
raise ValueError(msg)
for key, J in iteritems(self._jacobian_cache):
unknown, param = key
# States are never in dparams.
if param in dparams:
arg_vec = dparams
elif param in dunknowns:
arg_vec = dunknowns
else:
continue
if unknown not in dresids:
continue
result = dresids[unknown]
# Vectors are flipped during adjoint
if mode == 'fwd':
dresids[unknown] += J.dot(arg_vec[param].flat).reshape(result.shape)
else:
arg_vec[param] += J.T.dot(result.flat).reshape(arg_vec[param].shape)
def _create_views(self, top_unknowns, parent, my_params,
var_of_interest=None):
"""
A manager of the data transfer of a possibly distributed collection of
variables. The variables are based on views into an existing
`VecWrapper`.
Args
----
top_unknowns : `VecWrapper`
The `Problem` level unknowns `VecWrapper`.
parent : `System`
The `System` which provides the `VecWrapper` on which to create views.
my_params : list
List of pathnames for parameters that this `Group` is
responsible for propagating.
relevance : `Relevance`
Object containing relevance info for each variable of interest.
var_of_interest : str
The name of a variable of interest.
Returns
-------
`VecTuple`
A namedtuple of six (6) `VecWrappers`:
unknowns, dunknowns, resids, dresids, params, dparams.
"""
comm = self.comm
unknowns_dict = self._unknowns_dict
params_dict = self._params_dict
voi = var_of_interest
relevance = self._relevance
# map promoted name in parent to corresponding promoted name in this view
umap = self._relname_map
if voi is None:
self.unknowns = parent.unknowns.get_view(self.pathname, comm, umap)
self.resids = parent.resids.get_view(self.pathname, comm, umap)
self.params = parent._impl_factory.create_tgt_vecwrapper(self.pathname, comm)
self.params.setup(parent.params, params_dict, top_unknowns,
my_params, self.connections, relevance=relevance,
store_byobjs=True)
self.dumat[voi] = parent.dumat[voi].get_view(self.pathname, comm, umap)
self.drmat[voi] = parent.drmat[voi].get_view(self.pathname, comm, umap)
self.dpmat[voi] = parent._impl_factory.create_tgt_vecwrapper(self.pathname, comm)
self.dpmat[voi].setup(parent.dpmat[voi], params_dict, top_unknowns,
my_params, self.connections,
relevance=relevance, var_of_interest=voi)
#def get_combined_jac(self, J):
#"""
#Take a J dict that's distributed, i.e., has different values across
#different MPI processes, and return a dict that contains all of the
#values from all of the processes. If values are duplicated, use the
#value from the lowest rank process. Note that J has a nested dict
#structure.
#Args
#----
#J : `dict`
#Distributed Jacobian
#Returns
#-------
#`dict`
#Local gathered Jacobian
#"""
#comm = self.comm
#if not self.is_active():
#return J
#myrank = comm.rank
#tups = []
## Gather a list of local tuples for J.
#for output, dct in iteritems(J):
#for param, value in iteritems(dct):
## Params are already only on this process. We need to add
## only outputs of components that are on this process.
#sub = getattr(self, output.partition('.')[0])
#if sub.is_active() and value is not None and value.size > 0:
#tups.append((output, param))
#dist_tups = comm.gather(tups, root=0)
#tupdict = {}
#if myrank == 0:
#for rank, tups in enumerate(dist_tups):
#for tup in tups:
#if not tup in tupdict:
#tupdict[tup] = rank
##get rid of tups from the root proc before bcast
#for tup, rank in iteritems(tupdict):
#if rank == 0:
#del tupdict[tup]
#tupdict = comm.bcast(tupdict, root=0)
#if myrank == 0:
#for (param, output), rank in iteritems(tupdict):
#J[param][output] = comm.recv(source=rank, tag=0)
#else:
#for (param, output), rank in iteritems(tupdict):
#if rank == myrank:
#comm.send(J[param][output], dest=0, tag=0)
## FIXME: rework some of this using knowledge of local_var_sizes in order
## to avoid any unnecessary data passing
## return the combined dict
#return comm.bcast(J, root=0)
def _get_var_pathname(self, name):
if self.pathname:
return '.'.join((self.pathname, name))
return name
|
[
"numpy.size",
"openmdao.core.options.OptionsDictionary",
"numpy.zeros",
"six.itervalues",
"openmdao.core.vec_wrapper._PlaceholderVecWrapper",
"collections.OrderedDict",
"six.iteritems",
"itertools.chain",
"fnmatch.fnmatch"
] |
[((625, 638), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (636, 638), False, 'from collections import OrderedDict\n'), ((669, 682), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (680, 682), False, 'from collections import OrderedDict\n'), ((915, 949), 'openmdao.core.vec_wrapper._PlaceholderVecWrapper', '_PlaceholderVecWrapper', (['"""unknowns"""'], {}), "('unknowns')\n", (937, 949), False, 'from openmdao.core.vec_wrapper import _PlaceholderVecWrapper\n'), ((972, 1004), 'openmdao.core.vec_wrapper._PlaceholderVecWrapper', '_PlaceholderVecWrapper', (['"""resids"""'], {}), "('resids')\n", (994, 1004), False, 'from openmdao.core.vec_wrapper import _PlaceholderVecWrapper\n'), ((1027, 1059), 'openmdao.core.vec_wrapper._PlaceholderVecWrapper', '_PlaceholderVecWrapper', (['"""params"""'], {}), "('params')\n", (1049, 1059), False, 'from openmdao.core.vec_wrapper import _PlaceholderVecWrapper\n'), ((1085, 1120), 'openmdao.core.vec_wrapper._PlaceholderVecWrapper', '_PlaceholderVecWrapper', (['"""dunknowns"""'], {}), "('dunknowns')\n", (1107, 1120), False, 'from openmdao.core.vec_wrapper import _PlaceholderVecWrapper\n'), ((1144, 1177), 'openmdao.core.vec_wrapper._PlaceholderVecWrapper', '_PlaceholderVecWrapper', (['"""dresids"""'], {}), "('dresids')\n", (1166, 1177), False, 'from openmdao.core.vec_wrapper import _PlaceholderVecWrapper\n'), ((1201, 1234), 'openmdao.core.vec_wrapper._PlaceholderVecWrapper', '_PlaceholderVecWrapper', (['"""dparams"""'], {}), "('dparams')\n", (1223, 1234), False, 'from openmdao.core.vec_wrapper import _PlaceholderVecWrapper\n'), ((1411, 1430), 'openmdao.core.options.OptionsDictionary', 'OptionsDictionary', ([], {}), '()\n', (1428, 1430), False, 'from openmdao.core.options import OptionsDictionary\n'), ((9349, 9378), 'six.itervalues', 'itervalues', (['self._params_dict'], {}), '(self._params_dict)\n', (9359, 9378), False, 'from six import string_types, iteritems, itervalues\n'), ((9435, 9466), 'six.itervalues', 'itervalues', (['self._unknowns_dict'], {}), '(self._unknowns_dict)\n', (9445, 9466), False, 'from six import string_types, iteritems, itervalues\n'), ((12389, 12413), 'itertools.chain', 'chain', (['fd_params', 'states'], {}), '(fd_params, states)\n', (12394, 12413), False, 'from itertools import chain\n'), ((16256, 16287), 'six.iteritems', 'iteritems', (['self._jacobian_cache'], {}), '(self._jacobian_cache)\n', (16265, 16287), False, 'from six import string_types, iteritems, itervalues\n'), ((3491, 3510), 'fnmatch.fnmatch', 'fnmatch', (['name', 'prom'], {}), '(name, prom)\n', (3498, 3510), False, 'from fnmatch import fnmatch\n'), ((13704, 13725), 'numpy.size', 'np.size', (['target_input'], {}), '(target_input)\n', (13711, 13725), True, 'import numpy as np\n'), ((4893, 4921), 'six.iteritems', 'iteritems', (['self._params_dict'], {}), '(self._params_dict)\n', (4902, 4921), False, 'from six import string_types, iteritems, itervalues\n'), ((4959, 4989), 'six.iteritems', 'iteritems', (['self._unknowns_dict'], {}), '(self._unknowns_dict)\n', (4968, 4989), False, 'from six import string_types, iteritems, itervalues\n'), ((5160, 5180), 'fnmatch.fnmatch', 'fnmatch', (['pname', 'prom'], {}), '(pname, prom)\n', (5167, 5180), False, 'from fnmatch import fnmatch\n'), ((13279, 13308), 'six.itervalues', 'itervalues', (['self._params_dict'], {}), '(self._params_dict)\n', (13289, 13308), False, 'from six import string_types, iteritems, itervalues\n'), ((13822, 13847), 'numpy.size', 'np.size', (['unknowns[u_name]'], {}), '(unknowns[u_name])\n', (13829, 13847), True, 'import numpy as np\n'), ((13886, 13912), 'numpy.zeros', 'np.zeros', (['(u_size, p_size)'], {}), '((u_size, p_size))\n', (13894, 13912), True, 'import numpy as np\n'), ((3546, 3575), 'six.itervalues', 'itervalues', (['self._params_dict'], {}), '(self._params_dict)\n', (3556, 3575), False, 'from six import string_types, iteritems, itervalues\n'), ((3611, 3642), 'six.itervalues', 'itervalues', (['self._unknowns_dict'], {}), '(self._unknowns_dict)\n', (3621, 3642), False, 'from six import string_types, iteritems, itervalues\n'), ((12083, 12107), 'six.iteritems', 'iteritems', (['self.unknowns'], {}), '(self.unknowns)\n', (12092, 12107), False, 'from six import string_types, iteritems, itervalues\n')]
|
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from akg.utils import kernel_exec as utils
from tests.common.tensorio import compare_tensor
from tests.common.test_op import conv_ad_v2
from tests.common.test_run.conv_utils import conv_forward_naive
from tests.common.test_run.conv_utils import random_gaussian
from . import conv_filter_ad_run, conv_input_ad_run
def compare_5D(out_data, expect):
return compare_tensor(out_data, expect, rtol=1e-3, atol=1e-3, equal_nan=True)
def conv_ad_v2_run(case_num, fmap_shape, filter_shape, pad_, stride_, dilation_,
use_bias=False, bypass_l1=False, dump_data=False, Tile=None, attrs=None):
if Tile is None:
Tile = [0, 0, 0, 0, 0]
if (case_num == 1):
mod_data, mod_weight = conv_ad_v2.conv_01(fmap_shape, filter_shape, pad_, stride_, dilation_,
tile_hh=Tile[0], tile_coco=Tile[1], tile_mm=Tile[2], tile_kk=Tile[3],
tile_nn=Tile[4], use_bias=False, block_size=16, conv_dtype='float16')
in_n, in_c, in_h, in_w = fmap_shape
k_n, k_c, k_h, k_w = filter_shape
pad_h, pad_w, pad_l, pad_r = pad_
s_h, s_w = stride_
d_h, d_w = dilation_
o_n = in_n
o_c = k_n
o_h = 1 + (in_h + 2 * pad_h - (k_h - 1) * d_h - 1) // s_h
o_w = 1 + (in_w + 2 * pad_w - (k_w - 1) * d_w - 1) // s_w
Head_strided_shape = (o_n, o_c, (o_h - 1) * s_h + 1, (o_w - 1) * s_w + 1)
B_flip_shape = (k_c, k_n, k_h, k_w)
fmap_data_01, filter_data_01, expect = gen_data(Head_strided_shape, B_flip_shape, k_h - 1, 1, 1)
out_data_01 = np.full(expect.shape, 0, 'float16')
input = (fmap_data_01, filter_data_01)
args = (fmap_data_01, filter_data_01, out_data_01)
out_data = utils.mod_launch(mod_data, args, expect=expect)
assert_res = compare_5D(out_data, expect)
return input, out_data, expect, assert_res
elif (case_num == 2):
mod_data, mod_weight,\
mod_transpose_data, mod_transpose_convert_head,\
mod_head_strided, mod_weight_flipped = conv_ad_v2.conv_02(fmap_shape, filter_shape, pad_, stride_, dilation_,
tile_hh=Tile[0], tile_coco=Tile[1],
tile_mm=Tile[2], tile_kk=Tile[3],
tile_nn=Tile[4], bypass_l1=bypass_l1,
use_bias=False, block_size=16,
conv_dtype='float16')
in_n, in_c, in_h, in_w = fmap_shape
k_n, k_c, k_h, k_w = filter_shape
pad_h, pad_w, pad_l, pad_r = pad_
s_h, s_w = stride_
d_h, d_w = dilation_
block_size = 16
o_n = in_n
o_c = k_n
o_h = 1 + (in_h + 2 * pad_h - (k_h - 1) * d_h - 1) // s_h
o_w = 1 + (in_w + 2 * pad_w - (k_w - 1) * d_w - 1) // s_w
# Test the kernel generated for backward_DATA
Head_strided_shape = (o_n, o_c, (o_h - 1) * s_h + 1, (o_w - 1) * s_w + 1)
B_flip_shape = (k_c, k_n, k_h, k_w)
fmap_data_01, filter_data_01, expect = gen_data(Head_strided_shape, B_flip_shape, k_h - 1, 1, 1, strided=s_h)
if (s_h <= 1):
Head_origin_5D = fmap_data_01
else:
Head_origin_5D = np.full((o_n, o_c // block_size, o_h, o_w, block_size), 0, 'float16')
for i0 in range(Head_origin_5D.shape[0]):
for i1 in range(Head_origin_5D.shape[1]):
for i2 in range(Head_origin_5D.shape[2]):
for i3 in range(Head_origin_5D.shape[3]):
for i4 in range(Head_origin_5D.shape[4]):
Head_origin_5D[i0, i1, i2, i3, i4] = fmap_data_01[i0, i1, i2 * s_h, i3 * s_w, i4]
B_origin_Fractal = np.flip(np.flip(filter_data_01, 1), 2)\
.reshape((k_n // block_size, k_h, k_w, k_c // block_size, block_size, block_size))
B_origin_Fractal = np.transpose(B_origin_Fractal, (3, 1, 2, 0, 5, 4))\
.reshape((k_c // block_size * k_h * k_w, k_n // block_size, block_size, block_size))
B_flipped_Fractal = np.reshape(filter_data_01, (k_n // block_size, k_h, k_w, k_c // block_size, block_size, block_size))
B_flipped_Fractal = np.reshape(B_flipped_Fractal, (k_n // block_size * k_h * k_w, k_c // block_size, block_size, block_size))
out_data_01 = np.full(expect.shape, 0, 'float16')
input = (fmap_data_01, filter_data_01)
args = (fmap_data_01, filter_data_01, out_data_01)
out_data = utils.mod_launch(mod_data, args, expect=expect)
assert_res = compare_5D(out_data, expect)
H_strided = np.full((o_n, o_c // block_size, (o_h - 1) * s_h + 1, (o_w - 1) * s_w + 1, block_size), 0, 'float16')
H_strided = utils.mod_launch(mod_head_strided, (Head_origin_5D, H_strided), expect=expect)
B_flipped = np.full((k_n // block_size * k_h * k_w, k_c // block_size, block_size, block_size), 0, 'float16')
B_flipped = utils.mod_launch(mod_weight_flipped, (B_origin_Fractal, B_flipped), expect=expect)
assert_res &= compare_5D(H_strided, fmap_data_01)
tmp1 = B_flipped_Fractal.reshape(-1).copy()
tmp2 = B_flipped.reshape(-1).copy()
ind = []
for i in range(len(tmp1)):
if (np.abs(tmp1[i] - tmp2[i]) > 0.05):
ind.append(i)
print("Len of bad indices: ", len(ind))
assert_res &= (len(ind) == 0)
print("Test result for backward_DATA = ", assert_res)
# Test the kernel generated for backward_WEIGHT
X_shape = (in_n, in_c, in_h, in_w)
X_transposed_shape = (in_c, in_n, in_h, in_w)
Head_shape = (o_n, o_c, o_h, o_w)
Head_transposed_shape = (o_c, o_n, o_h, o_w)
H_trans_fractal_shape = (o_c // block_size * o_h * o_w, o_n // block_size, block_size, block_size)
fmap_data_02, filter_data_02, expect_02 = gen_data(X_transposed_shape, Head_transposed_shape, 0, 1, s_h)
X_origin_5D = np.reshape(fmap_data_02, (in_c // block_size, block_size, in_n // block_size, in_h, in_w, block_size))\
.transpose((2, 5, 0, 3, 4, 1)).reshape((in_n, in_c // block_size, in_h, in_w, block_size))
H_origin_5D = np.reshape(filter_data_02, (o_n // block_size, o_h, o_w, o_c // block_size, block_size, block_size))\
.transpose((0, 5, 3, 1, 2, 4)).reshape((o_n, o_c // block_size, o_h, o_w, block_size))
out_data_02 = np.full(expect_02.shape, 0, 'float16')
input_02 = (fmap_data_02, filter_data_02)
args_02 = (fmap_data_02, filter_data_02, out_data_02)
out_data_02 = utils.mod_launch(mod_weight, args_02, expect=expect_02)
assert_res &= compare_5D(out_data_02, expect_02)
X_trans = np.full(fmap_data_02.shape, 0, 'float16')
X_trans = utils.mod_launch(mod_transpose_data, (X_origin_5D, X_trans))
H_trans = np.full(H_trans_fractal_shape, 0, 'float16')
H_trans = utils.mod_launch(mod_transpose_convert_head, (H_origin_5D, H_trans))
Conv_trans = np.full(expect_02.shape, 0, 'float16')
Conv_trans = utils.mod_launch(mod_weight, (X_trans, H_trans, Conv_trans))
assert_res &= compare_5D(Conv_trans, expect_02)
print("Test result for backward_DATA and WEIGHT = ", assert_res)
return input_02, out_data_02, expect_02, assert_res
elif (case_num == 3):
return conv_input_ad_run.conv_input_ad_run(fmap_shape, filter_shape, pad_, stride_, dilation_)
else:
return conv_filter_ad_run.conv_filter_ad_run(fmap_shape, filter_shape, pad_, stride_, dilation_)
def gen_data(fm_shape, w_shape, pad, stride, dilation, strided=-1):
IN, IC, IH, IW = fm_shape
C0 = 16
IC = ((IC + C0 - 1) // C0) * C0
WN, WC, WH, WW = w_shape
WN = ((WN + C0 - 1) // C0) * C0
WC = ((WC + C0 - 1) // C0) * C0
ON = IN
OC = WN
WHD = (WH - 1) * dilation + 1
WWD = (WW - 1) * dilation + 1
OH = (IH + 2 * pad - WHD) // stride + 1
OW = (IW + 2 * pad - WWD) // stride + 1
if (strided <= 1):
x = random_gaussian((IN, IC, IH, IW), miu=1, sigma=0.1).astype(np.float16)
else:
x_tmp = random_gaussian((IN, IC, (IH // strided + 1), (IW // strided + 1)), miu=1, sigma=0.1).astype(np.float16)
x = np.full((IN, IC, IH, IW), 0, dtype=np.float16)
for i0 in range(x_tmp.shape[0]):
for i1 in range(x_tmp.shape[1]):
for i2 in range(x_tmp.shape[2]):
for i3 in range(x_tmp.shape[3]):
x[i0, i1, i2 * strided, i3 * strided] = x_tmp[i0, i1, i2, i3]
w = random_gaussian((WN, WC, WH, WW), miu=0.5, sigma=0.01).astype(np.float16)
conv_param = {'stride': stride, 'pad': pad, 'dilation': dilation}
out = conv_forward_naive(x, w, None, conv_param)
# transpose to 5D - NC1HWC0
feature = x.reshape(IN, IC // C0, C0, IH, IW).transpose(0, 1, 3, 4, 2).copy()
# transpose to 5D - C1HWNC0
filter = w.reshape(WN, WC // C0, C0, WH, WW).transpose(1, 3, 4, 0, 2).copy()
# transpose to 5D - NC1HWC0
output = out.reshape(ON, OC // C0, C0, OH, OW).transpose(0, 1, 3, 4, 2).copy()
return feature, filter, output
|
[
"numpy.full",
"tests.common.tensorio.compare_tensor",
"tests.common.test_op.conv_ad_v2.conv_01",
"tests.common.test_run.conv_utils.random_gaussian",
"tests.common.test_op.conv_ad_v2.conv_02",
"numpy.abs",
"numpy.flip",
"tests.common.test_run.conv_utils.conv_forward_naive",
"numpy.transpose",
"numpy.reshape",
"akg.utils.kernel_exec.mod_launch"
] |
[((967, 1039), 'tests.common.tensorio.compare_tensor', 'compare_tensor', (['out_data', 'expect'], {'rtol': '(0.001)', 'atol': '(0.001)', 'equal_nan': '(True)'}), '(out_data, expect, rtol=0.001, atol=0.001, equal_nan=True)\n', (981, 1039), False, 'from tests.common.tensorio import compare_tensor\n'), ((9682, 9724), 'tests.common.test_run.conv_utils.conv_forward_naive', 'conv_forward_naive', (['x', 'w', 'None', 'conv_param'], {}), '(x, w, None, conv_param)\n', (9700, 9724), False, 'from tests.common.test_run.conv_utils import conv_forward_naive\n'), ((1322, 1540), 'tests.common.test_op.conv_ad_v2.conv_01', 'conv_ad_v2.conv_01', (['fmap_shape', 'filter_shape', 'pad_', 'stride_', 'dilation_'], {'tile_hh': 'Tile[0]', 'tile_coco': 'Tile[1]', 'tile_mm': 'Tile[2]', 'tile_kk': 'Tile[3]', 'tile_nn': 'Tile[4]', 'use_bias': '(False)', 'block_size': '(16)', 'conv_dtype': '"""float16"""'}), "(fmap_shape, filter_shape, pad_, stride_, dilation_,\n tile_hh=Tile[0], tile_coco=Tile[1], tile_mm=Tile[2], tile_kk=Tile[3],\n tile_nn=Tile[4], use_bias=False, block_size=16, conv_dtype='float16')\n", (1340, 1540), False, 'from tests.common.test_op import conv_ad_v2\n'), ((2244, 2279), 'numpy.full', 'np.full', (['expect.shape', '(0)', '"""float16"""'], {}), "(expect.shape, 0, 'float16')\n", (2251, 2279), True, 'import numpy as np\n'), ((2405, 2452), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_data', 'args'], {'expect': 'expect'}), '(mod_data, args, expect=expect)\n', (2421, 2452), True, 'from akg.utils import kernel_exec as utils\n'), ((9197, 9243), 'numpy.full', 'np.full', (['(IN, IC, IH, IW)', '(0)'], {'dtype': 'np.float16'}), '((IN, IC, IH, IW), 0, dtype=np.float16)\n', (9204, 9243), True, 'import numpy as np\n'), ((2726, 2969), 'tests.common.test_op.conv_ad_v2.conv_02', 'conv_ad_v2.conv_02', (['fmap_shape', 'filter_shape', 'pad_', 'stride_', 'dilation_'], {'tile_hh': 'Tile[0]', 'tile_coco': 'Tile[1]', 'tile_mm': 'Tile[2]', 'tile_kk': 'Tile[3]', 'tile_nn': 'Tile[4]', 'bypass_l1': 'bypass_l1', 'use_bias': '(False)', 'block_size': '(16)', 'conv_dtype': '"""float16"""'}), "(fmap_shape, filter_shape, pad_, stride_, dilation_,\n tile_hh=Tile[0], tile_coco=Tile[1], tile_mm=Tile[2], tile_kk=Tile[3],\n tile_nn=Tile[4], bypass_l1=bypass_l1, use_bias=False, block_size=16,\n conv_dtype='float16')\n", (2744, 2969), False, 'from tests.common.test_op import conv_ad_v2\n'), ((4990, 5094), 'numpy.reshape', 'np.reshape', (['filter_data_01', '(k_n // block_size, k_h, k_w, k_c // block_size, block_size, block_size)'], {}), '(filter_data_01, (k_n // block_size, k_h, k_w, k_c // block_size,\n block_size, block_size))\n', (5000, 5094), True, 'import numpy as np\n'), ((5119, 5228), 'numpy.reshape', 'np.reshape', (['B_flipped_Fractal', '(k_n // block_size * k_h * k_w, k_c // block_size, block_size, block_size)'], {}), '(B_flipped_Fractal, (k_n // block_size * k_h * k_w, k_c //\n block_size, block_size, block_size))\n', (5129, 5228), True, 'import numpy as np\n'), ((5248, 5283), 'numpy.full', 'np.full', (['expect.shape', '(0)', '"""float16"""'], {}), "(expect.shape, 0, 'float16')\n", (5255, 5283), True, 'import numpy as np\n'), ((5409, 5456), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_data', 'args'], {'expect': 'expect'}), '(mod_data, args, expect=expect)\n', (5425, 5456), True, 'from akg.utils import kernel_exec as utils\n'), ((5529, 5634), 'numpy.full', 'np.full', (['(o_n, o_c // block_size, (o_h - 1) * s_h + 1, (o_w - 1) * s_w + 1, block_size)', '(0)', '"""float16"""'], {}), "((o_n, o_c // block_size, (o_h - 1) * s_h + 1, (o_w - 1) * s_w + 1,\n block_size), 0, 'float16')\n", (5536, 5634), True, 'import numpy as np\n'), ((5651, 5729), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_head_strided', '(Head_origin_5D, H_strided)'], {'expect': 'expect'}), '(mod_head_strided, (Head_origin_5D, H_strided), expect=expect)\n', (5667, 5729), True, 'from akg.utils import kernel_exec as utils\n'), ((5751, 5852), 'numpy.full', 'np.full', (['(k_n // block_size * k_h * k_w, k_c // block_size, block_size, block_size)', '(0)', '"""float16"""'], {}), "((k_n // block_size * k_h * k_w, k_c // block_size, block_size,\n block_size), 0, 'float16')\n", (5758, 5852), True, 'import numpy as np\n'), ((5869, 5956), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_weight_flipped', '(B_origin_Fractal, B_flipped)'], {'expect': 'expect'}), '(mod_weight_flipped, (B_origin_Fractal, B_flipped), expect=\n expect)\n', (5885, 5956), True, 'from akg.utils import kernel_exec as utils\n'), ((7358, 7396), 'numpy.full', 'np.full', (['expect_02.shape', '(0)', '"""float16"""'], {}), "(expect_02.shape, 0, 'float16')\n", (7365, 7396), True, 'import numpy as np\n'), ((7531, 7586), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_weight', 'args_02'], {'expect': 'expect_02'}), '(mod_weight, args_02, expect=expect_02)\n', (7547, 7586), True, 'from akg.utils import kernel_exec as utils\n'), ((7664, 7705), 'numpy.full', 'np.full', (['fmap_data_02.shape', '(0)', '"""float16"""'], {}), "(fmap_data_02.shape, 0, 'float16')\n", (7671, 7705), True, 'import numpy as np\n'), ((7724, 7784), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_transpose_data', '(X_origin_5D, X_trans)'], {}), '(mod_transpose_data, (X_origin_5D, X_trans))\n', (7740, 7784), True, 'from akg.utils import kernel_exec as utils\n'), ((7804, 7848), 'numpy.full', 'np.full', (['H_trans_fractal_shape', '(0)', '"""float16"""'], {}), "(H_trans_fractal_shape, 0, 'float16')\n", (7811, 7848), True, 'import numpy as np\n'), ((7867, 7935), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_transpose_convert_head', '(H_origin_5D, H_trans)'], {}), '(mod_transpose_convert_head, (H_origin_5D, H_trans))\n', (7883, 7935), True, 'from akg.utils import kernel_exec as utils\n'), ((7958, 7996), 'numpy.full', 'np.full', (['expect_02.shape', '(0)', '"""float16"""'], {}), "(expect_02.shape, 0, 'float16')\n", (7965, 7996), True, 'import numpy as np\n'), ((8018, 8078), 'akg.utils.kernel_exec.mod_launch', 'utils.mod_launch', (['mod_weight', '(X_trans, H_trans, Conv_trans)'], {}), '(mod_weight, (X_trans, H_trans, Conv_trans))\n', (8034, 8078), True, 'from akg.utils import kernel_exec as utils\n'), ((9527, 9581), 'tests.common.test_run.conv_utils.random_gaussian', 'random_gaussian', (['(WN, WC, WH, WW)'], {'miu': '(0.5)', 'sigma': '(0.01)'}), '((WN, WC, WH, WW), miu=0.5, sigma=0.01)\n', (9542, 9581), False, 'from tests.common.test_run.conv_utils import random_gaussian\n'), ((4095, 4164), 'numpy.full', 'np.full', (['(o_n, o_c // block_size, o_h, o_w, block_size)', '(0)', '"""float16"""'], {}), "((o_n, o_c // block_size, o_h, o_w, block_size), 0, 'float16')\n", (4102, 4164), True, 'import numpy as np\n'), ((8983, 9034), 'tests.common.test_run.conv_utils.random_gaussian', 'random_gaussian', (['(IN, IC, IH, IW)'], {'miu': '(1)', 'sigma': '(0.1)'}), '((IN, IC, IH, IW), miu=1, sigma=0.1)\n', (8998, 9034), False, 'from tests.common.test_run.conv_utils import random_gaussian\n'), ((9080, 9165), 'tests.common.test_run.conv_utils.random_gaussian', 'random_gaussian', (['(IN, IC, IH // strided + 1, IW // strided + 1)'], {'miu': '(1)', 'sigma': '(0.1)'}), '((IN, IC, IH // strided + 1, IW // strided + 1), miu=1,\n sigma=0.1)\n', (9095, 9165), False, 'from tests.common.test_run.conv_utils import random_gaussian\n'), ((4795, 4845), 'numpy.transpose', 'np.transpose', (['B_origin_Fractal', '(3, 1, 2, 0, 5, 4)'], {}), '(B_origin_Fractal, (3, 1, 2, 0, 5, 4))\n', (4807, 4845), True, 'import numpy as np\n'), ((6175, 6200), 'numpy.abs', 'np.abs', (['(tmp1[i] - tmp2[i])'], {}), '(tmp1[i] - tmp2[i])\n', (6181, 6200), True, 'import numpy as np\n'), ((4624, 4650), 'numpy.flip', 'np.flip', (['filter_data_01', '(1)'], {}), '(filter_data_01, 1)\n', (4631, 4650), True, 'import numpy as np\n'), ((6881, 6987), 'numpy.reshape', 'np.reshape', (['fmap_data_02', '(in_c // block_size, block_size, in_n // block_size, in_h, in_w, block_size)'], {}), '(fmap_data_02, (in_c // block_size, block_size, in_n //\n block_size, in_h, in_w, block_size))\n', (6891, 6987), True, 'import numpy as np\n'), ((7122, 7226), 'numpy.reshape', 'np.reshape', (['filter_data_02', '(o_n // block_size, o_h, o_w, o_c // block_size, block_size, block_size)'], {}), '(filter_data_02, (o_n // block_size, o_h, o_w, o_c // block_size,\n block_size, block_size))\n', (7132, 7226), True, 'import numpy as np\n')]
|
import torch
import torch.onnx as onnx
import torchvision.models as models
import os
import os.path as path
from tempfile import mkdtemp
import numpy as np
#import matplotlib.pyplot as plt
#from skimage.transform import rotate
import torch
torch.manual_seed(0)
import random
random.seed(0)
import nibabel as nib
from nilearn.image import resample_img
np.random.seed(0)
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import transforms, datasets, models
from torch.utils import data
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import time
import csv
num_class = 3
num_channel = 1
#slices = 155 # Number of slices per each 3D image (original image)
slices = 78 # Number of slices per each 3D image (resampled image)
class BRaTSDataset(Dataset):
def __init__(self, transform=None):
# Input images
data_path = 'data/MICCAI_BraTS2020_TrainingData'
images_path = next(os.walk(data_path))[1]
images_path.sort()
flair_files = []
seg_files = []
t1_files = []
t1ce_files = []
t2_files = []
for p in images_path:
file_path = os.path.join(data_path, p)
file_names= os.listdir(file_path)
file_names.sort()
flair_files.append(
os.path.join(
file_path, file_names[0]))
seg_files.append(
os.path.join(
file_path, file_names[1]))
t1_files.append(
os.path.join(
file_path, file_names[2]))
t1ce_files.append(
os.path.join(
file_path, file_names[3]))
t2_files.append(
os.path.join(
file_path, file_names[4]))
#slices = 155 # Number of slices per each 3D image (original image)
#slices = 78 # Number of slices per each 3D image (resampled image)
numberOfFiles = len(flair_files)
#numberOfFiles = 7
numberOfFiles = 100
dataShuffle = random.sample(list(range(0,len(flair_files))), k=numberOfFiles)
indexes = numberOfFiles * slices
#tempFileName1 = path.join(mkdtemp(), 'newfile1.dat')
#tempFileName2 = path.join(mkdtemp(), 'newfile2.dat')
tempFileName1 = 'newfile1.dat'
tempFileName2 = 'newfile2.dat'
#self.input_images = np.memmap('a.array', dtype='float64', mode='w+', shape=(1,240,240,indexes))
#self.target_masks = np.memmap('b.array', dtype='float64', mode='w+', shape=(1,240,240,indexes))
self.input_images = np.memmap(tempFileName1, dtype='float64', mode='w+', shape=(num_channel,120,120,indexes))
#self.input_images = np.zeros((4,240,240,indexes))
self.target_masks = np.memmap(tempFileName2, dtype='float64', mode='w+', shape=(1,120,120,indexes))
#self.target_masks = np.zeros((1,240,240,indexes))
for i in range(numberOfFiles):
self.input_images[0, :, :, i*slices:(slices+i*slices)] =\
resample_img(nib.load(flair_files[dataShuffle[i]]), target_affine=np.eye(3)*2., interpolation='nearest').get_fdata()[:120,:120,:]
"""self.input_images[1, :, :, i*slices:(slices+i*slices)] =\
resample_img(nib.load(t1_files[dataShuffle[i]]), target_affine=np.eye(3)*2., interpolation='nearest').get_fdata()[:120,:120,:]
self.input_images[2, :, :, i*slices:(slices+i*slices)] =\
resample_img(nib.load(t1ce_files[dataShuffle[i]]), target_affine=np.eye(3)*2., interpolation='nearest').get_fdata()[:120,:120,:]
self.input_images[3, :, :, i*slices:(slices+i*slices)] =\
resample_img(nib.load(t2_files[dataShuffle[i]]), target_affine=np.eye(3)*2., interpolation='nearest').get_fdata()[:120,:120,:]"""
self.target_masks[0, :, :, i*slices:(slices+i*slices)] =\
resample_img(nib.load(seg_files[dataShuffle[i]]), target_affine=np.eye(3)*2., interpolation='nearest').get_fdata()[:120,:120,:]
self.input_images = np.transpose(self.input_images,(3, 1, 2, 0))
self.target_masks = np.transpose(self.target_masks, (3, 0, 1, 2))
### one hot encoding
self.target_masks[self.target_masks==4] = 3
self.target_masks = F.one_hot(torch.as_tensor(self.target_masks).long(),4)
self.target_masks = torch.transpose(self.target_masks, 1, 4)
self.target_masks = self.target_masks[:,:,:,:,0]
self.target_masks = self.target_masks[:,1:4,:,:]
self.target_masks = self.target_masks.float()
self.transform = transform
def __len__(self):
return len(self.input_images)
def __getitem__(self, idx):
image = self.input_images[idx]
mask = self.target_masks[idx]
if self.transform:
image = self.transform(image)
return [image, mask]
########
# Define UNet
##########################
# Conv2d as in the original implementation has kernel_size = 3,
# but padding = 1 while original implementation padding = 0
def double_conv(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, 3, padding=1),
nn.ReLU(inplace=True)
)
class UNet(nn.Module):
def __init__(self, num_class, num_channel):
super().__init__()
# initialize neural network layers
self.dconv_down1 = double_conv(num_channel, 64)
self.dconv_down2 = double_conv(64, 128)
self.dconv_down3 = double_conv(128, 256)
self.dconv_down4 = double_conv(256, 512)
self.maxpool = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.dconv_up3 = double_conv(256 + 512, 256)
self.dconv_up2 = double_conv(128 + 256, 128)
self.dconv_up1 = double_conv(128 + 64, 64)
self.conv_last = nn.Conv2d(64, num_class, 1)
def forward(self, x):
# impolements operations on input data
# down convolution part
conv1 = self.dconv_down1(x) #
x = self.maxpool(conv1)
conv2 = self.dconv_down2(x) #
x = self.maxpool(conv2)
conv3 = self.dconv_down3(x) #
x = self.maxpool(conv3)
x = self.dconv_down4(x)
# up convolution part
# this is doing an upsampling (neearest algorithm) so it is not learning any parameters
x = self.upsample(x)
x = torch.cat([x, conv3], dim=1)
x = self.dconv_up3(x)
x = self.upsample(x)
x = torch.cat([x, conv2], dim=1)
x = self.dconv_up2(x)
x = self.upsample(x)
x = torch.cat([x, conv1], dim=1)
x = self.dconv_up1(x)
out = self.conv_last(x)
return out
########
# Instantiate UNet model
##########################
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('device', device)
model = UNet(num_class, num_channel)
model = model.to(device)
print(model)
from torchsummary import summary
summary(model, input_size=(1, 120, 120))
#################
# Define the main training loop
######################################
from collections import defaultdict
import torch.nn.functional as F
checkpoint_path = "checkpoint.pth"
class DiceLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(DiceLoss, self).__init__()
def forward(self, inputs, targets, smooth=1):
#comment out if your model contains a sigmoid or equivalent activation layer
#inputs = F.sigmoid(inputs)
inputs = inputs.contiguous()
targets = targets.contiguous()
intersection = (inputs * targets).sum(dim=2).sum(dim=2)
dice = (2. * intersection + smooth)/(inputs.sum(dim=2).sum(dim=2) + targets.sum(dim=2).sum(dim=2) + smooth)
loss = 1 - dice
return loss.mean()
class DiceBCELoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(DiceBCELoss, self).__init__()
def forward(self, pred, target, metrics, bce_weight=0.5):
#comment out if your model contains a sigmoid or equivalent activation layer
#(binary_cross_entropy_with_logits has a sigmoid)
#inputs = F.sigmoid(inputs)
bce = F.binary_cross_entropy_with_logits(pred, target)
pred = torch.sigmoid(pred)
diceloss = DiceLoss()
dice = diceloss(pred, target)
loss = bce * bce_weight + dice * (1 - bce_weight)
metrics['bce'] += bce.data.cpu().numpy() * target.size(0)
metrics['dice'] += dice.data.cpu().numpy() * target.size(0)
metrics['loss'] += loss.data.cpu().numpy() * target.size(0)
return loss
def print_metrics(metrics, epoch_samples, phase):
outputs = []
for k in metrics.keys():
outputs.append("{}: {:4f}".format(k, metrics[k] / epoch_samples))
print("{}: {}".format(phase, ", ".join(outputs)))
def training_loop(model, optimizer, scheduler):
time0 = time.time()
model.train() # Set model to training mode
metrics = defaultdict(float)
epoch_samples = 0
for inputs, labels in trainLoader:
inputs = inputs.float() # change
inputs = inputs.to(device)
#labels[labels==4] = 3
#labels = F.one_hot(labels.to(torch.int64),4)
#labels = torch.transpose(labels, 1, 4)
#labels = labels[:,:,:,:,0]
#labels = labels[:,1:4,:,:]
labels = labels.float()
labels = labels.to(device)
# Backpropagation
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(True):
outputs = model(inputs)
calcLoss = DiceBCELoss()
loss = calcLoss(outputs, labels, metrics)
loss.backward()
optimizer.step()
# statistics
epoch_samples += inputs.size(0)
print_metrics(metrics, epoch_samples, phase='train')
epoch_loss = metrics['loss'] / epoch_samples
scheduler.step()
for param_group in optimizer.param_groups:
print("LR", param_group['lr'])
for k in metrics.keys():
metrics[k] = metrics[k] / epoch_samples
return model, metrics
def validation_loop(model, optimizer):
global best_loss
model.eval() # Set model to evaluate mode
metrics = defaultdict(float)
epoch_samples = 0
for inputs, labels in valLoader:
inputs = inputs.float() # change
inputs = inputs.to(device)
#labels[labels==4] = 3
#labels = F.one_hot(labels.to(torch.int64),4)
#labels = torch.transpose(labels, 1, 4)
#labels = labels[:,:,:,:,0]
#labels = labels[:,1:4,:,:]
labels = labels.float()
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(False):
outputs = model(inputs)
calcLoss = DiceBCELoss()
loss = calcLoss(outputs, labels, metrics)
# statistics
epoch_samples += inputs.size(0)
print_metrics(metrics, epoch_samples, phase='val')
epoch_loss = metrics['loss'] / epoch_samples
# save the model weights
if epoch_loss < best_loss:
print(f"saving best model to {checkpoint_path}")
best_loss = epoch_loss
torch.save(model.state_dict(), checkpoint_path)
model.load_state_dict(torch.load(checkpoint_path))
for k in metrics.keys():
metrics[k] = metrics[k] / epoch_samples
return model, metrics
def test_loop(model):
global best_loss
model.eval() # Set model to evaluate mode
metrics = defaultdict(float)
epoch_samples = 0
for inputs, labels in testLoader:
inputs = inputs.float()
inputs = inputs.to(device)
#labels[labels==4] = 3
#labels = F.one_hot(labels.to(torch.int64),4)
#labels = torch.transpose(labels, 1, 4)
#labels = labels[:,:,:,:,0]
#labels = labels[:,1:4,:,:]
labels = labels.float()
labels = labels.to(device)
# forward
# track history if only in train
with torch.set_grad_enabled(False):
outputs = model(inputs)
calcLoss = DiceBCELoss()
loss = calcLoss(outputs, labels, metrics)
# statistics
epoch_samples += inputs.size(0)
print_metrics(metrics, epoch_samples, phase='test')
for k in metrics.keys():
metrics[k] = metrics[k] / epoch_samples
return metrics
from os.path import exists
class Log:
def __init__(self, path, header):
self.path = path
self.header = header
file_exists = exists(path)
if(not file_exists):
with open(path, 'w', encoding='UTF8', newline='') as f:
# create the csv writer
writer = csv.writer(f)
# write header to the csv file
writer.writerow(header)
else:
pass
def addRow(self, row):
with open(self.path, 'a+', encoding='UTF8', newline='') as f:
# create the csv writer
writer = csv.writer(f)
# write a row to the csv file
writer.writerow(row)
######################
# Training
################################
###########
# Data set
####
transform = transforms.Compose([
transforms.ToTensor()
])
braTSDataset = BRaTSDataset(transform = transform)
##########
# Cross validation
####
'''
|---- train ------------------------|- val --|- test -|
|---- train ------|- val --|- test -|--- train -------|
|- val --|- test -|--------------------- train -------|
'''
K = 3 # number of folds
import random
random.seed(0)
# definning the size of each split
fold_size = []
for i in range(K-1):
#div = int(len(braTSDataset)/3) # if does not matter if I take images from same images in different splits
div = int((len(braTSDataset)/3)/slices)*slices # make each split from different images
fold_size.append(div)
fold_size.append(len(braTSDataset) - np.sum(fold_size))
print("fold_size: ", str(fold_size))
# the next line is commented in orther to produce data from different images
#dataShuffle = random.sample(list(range(0,len(braTSDataset))), k=len(braTSDataset))
dataShuffle = range(0,len(braTSDataset))
folds = []
for i in range(0,K):
i1 = int(np.sum(fold_size[0:i]))
i2 = int(np.sum(fold_size[0:i+1]))
folds.append(dataShuffle[i1:i2])
fold_sets = []
for i in range(K):
fold_sets.append(Subset(braTSDataset, folds[i]))
for k in range(K):
checkpoint_path = "checkpoint(" + str(k) + ").pth"
# divide and multiply by the number of slices to make a mulple of number slices
val_size = int((len(fold_sets[k])*2/3)/slices)*slices
test_size = len(fold_sets[k]) - val_size
print("val_size: ", str(val_size), "test_size: ", str(test_size))
val_set = Subset(fold_sets[k], np.arange(0,val_size))
test_set = Subset(fold_sets[k], np.arange(val_size,len(fold_sets[k])))
if k == 0:
train_set = fold_sets[1]
s = 2
else:
train_set = fold_sets[0]
s = 1
for i in range(s,K):
if i == k:
pass
else:
train_set = torch.utils.data.ConcatDataset([train_set, fold_sets[i]])
batch_size = 25
trainLoader = DataLoader(train_set, batch_size=batch_size, shuffle=False, num_workers=0)
valLoader = DataLoader(val_set, batch_size=batch_size, shuffle=False, num_workers=0)
testLoader = DataLoader(test_set, batch_size=batch_size, shuffle=False, num_workers=0)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = UNet(num_class, num_channel).to(device)
header = ['fold', 'epoch', 'phase', 'time', 'bce', 'dice', 'loss']
csvPath = 'log.csv'
log = Log(csvPath, header)
optimizer_ft = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-3)
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=51, gamma=0.1)
num_epochs = 50
best_loss = 1e10
for epoch in range(num_epochs):
since_0 = time.time()
print("Fold ", k, end = " ")
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
model, metrics = training_loop(model, optimizer_ft, exp_lr_scheduler)
newRow = [k, epoch, 'train', time.time()-since_0, metrics['bce'], metrics['dice'], metrics['loss']]
log.addRow(newRow)
since_1 = time.time()
model, metrics = validation_loop(model, optimizer_ft)
newRow = [k, epoch, 'val', time.time()-since_1, metrics['bce'], metrics['dice'], metrics['loss']]
log.addRow(newRow)
time_elapsed = time.time() - since_0
print('{:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
print('Best val loss: {:4f}'.format(best_loss))
since = time.time()
metrics = test_loop(model)
newRow = [k, 0, 'test', time.time()-since, metrics['bce'], metrics['dice'], metrics['loss']]
log.addRow(newRow)
|
[
"numpy.random.seed",
"torch.optim.lr_scheduler.StepLR",
"numpy.sum",
"os.walk",
"torch.cat",
"collections.defaultdict",
"torchsummary.summary",
"numpy.arange",
"os.path.join",
"numpy.eye",
"torch.utils.data.DataLoader",
"torch.load",
"numpy.transpose",
"torch.nn.functional.binary_cross_entropy_with_logits",
"os.path.exists",
"torchvision.transforms.ToTensor",
"torch.nn.Upsample",
"random.seed",
"torch.utils.data.ConcatDataset",
"csv.writer",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.cuda.is_available",
"torch.set_grad_enabled",
"torch.nn.MaxPool2d",
"numpy.memmap",
"os.listdir",
"torch.utils.data.Subset",
"torch.nn.ReLU",
"nibabel.load",
"time.time",
"torch.sigmoid",
"torch.as_tensor",
"torch.transpose"
] |
[((244, 264), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (261, 264), False, 'import torch\n'), ((280, 294), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (291, 294), False, 'import random\n'), ((359, 376), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (373, 376), True, 'import numpy as np\n'), ((7589, 7629), 'torchsummary.summary', 'summary', (['model'], {'input_size': '(1, 120, 120)'}), '(model, input_size=(1, 120, 120))\n', (7596, 7629), False, 'from torchsummary import summary\n'), ((14609, 14623), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (14620, 14623), False, 'import random\n'), ((9605, 9616), 'time.time', 'time.time', ([], {}), '()\n', (9614, 9616), False, 'import time\n'), ((9680, 9698), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (9691, 9698), False, 'from collections import defaultdict\n'), ((11103, 11121), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (11114, 11121), False, 'from collections import defaultdict\n'), ((12503, 12521), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (12514, 12521), False, 'from collections import defaultdict\n'), ((16251, 16325), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(train_set, batch_size=batch_size, shuffle=False, num_workers=0)\n', (16261, 16325), False, 'from torch.utils.data import Dataset, DataLoader, Subset\n'), ((16342, 16414), 'torch.utils.data.DataLoader', 'DataLoader', (['val_set'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(val_set, batch_size=batch_size, shuffle=False, num_workers=0)\n', (16352, 16414), False, 'from torch.utils.data import Dataset, DataLoader, Subset\n'), ((16432, 16505), 'torch.utils.data.DataLoader', 'DataLoader', (['test_set'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(test_set, batch_size=batch_size, shuffle=False, num_workers=0)\n', (16442, 16505), False, 'from torch.utils.data import Dataset, DataLoader, Subset\n'), ((16874, 16932), 'torch.optim.lr_scheduler.StepLR', 'lr_scheduler.StepLR', (['optimizer_ft'], {'step_size': '(51)', 'gamma': '(0.1)'}), '(optimizer_ft, step_size=51, gamma=0.1)\n', (16893, 16932), False, 'from torch.optim import lr_scheduler\n'), ((17801, 17812), 'time.time', 'time.time', ([], {}), '()\n', (17810, 17812), False, 'import time\n'), ((2760, 2857), 'numpy.memmap', 'np.memmap', (['tempFileName1'], {'dtype': '"""float64"""', 'mode': '"""w+"""', 'shape': '(num_channel, 120, 120, indexes)'}), "(tempFileName1, dtype='float64', mode='w+', shape=(num_channel, \n 120, 120, indexes))\n", (2769, 2857), True, 'import numpy as np\n'), ((2946, 3032), 'numpy.memmap', 'np.memmap', (['tempFileName2'], {'dtype': '"""float64"""', 'mode': '"""w+"""', 'shape': '(1, 120, 120, indexes)'}), "(tempFileName2, dtype='float64', mode='w+', shape=(1, 120, 120,\n indexes))\n", (2955, 3032), True, 'import numpy as np\n'), ((4259, 4304), 'numpy.transpose', 'np.transpose', (['self.input_images', '(3, 1, 2, 0)'], {}), '(self.input_images, (3, 1, 2, 0))\n', (4271, 4304), True, 'import numpy as np\n'), ((4332, 4377), 'numpy.transpose', 'np.transpose', (['self.target_masks', '(3, 0, 1, 2)'], {}), '(self.target_masks, (3, 0, 1, 2))\n', (4344, 4377), True, 'import numpy as np\n'), ((4587, 4627), 'torch.transpose', 'torch.transpose', (['self.target_masks', '(1)', '(4)'], {}), '(self.target_masks, 1, 4)\n', (4602, 4627), False, 'import torch\n'), ((5388, 5438), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels', '(3)'], {'padding': '(1)'}), '(in_channels, out_channels, 3, padding=1)\n', (5397, 5438), True, 'import torch.nn as nn\n'), ((5448, 5469), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5455, 5469), True, 'import torch.nn as nn\n'), ((5488, 5539), 'torch.nn.Conv2d', 'nn.Conv2d', (['out_channels', 'out_channels', '(3)'], {'padding': '(1)'}), '(out_channels, out_channels, 3, padding=1)\n', (5497, 5539), True, 'import torch.nn as nn\n'), ((5549, 5570), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5556, 5570), True, 'import torch.nn as nn\n'), ((5982, 6019), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)'}), '(kernel_size=2, stride=2)\n', (5994, 6019), True, 'import torch.nn as nn\n'), ((6048, 6112), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2)', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(scale_factor=2, mode='bilinear', align_corners=True)\n", (6059, 6112), True, 'import torch.nn as nn\n'), ((6321, 6348), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', 'num_class', '(1)'], {}), '(64, num_class, 1)\n', (6330, 6348), True, 'import torch.nn as nn\n'), ((6936, 6964), 'torch.cat', 'torch.cat', (['[x, conv3]'], {'dim': '(1)'}), '([x, conv3], dim=1)\n', (6945, 6964), False, 'import torch\n'), ((7063, 7091), 'torch.cat', 'torch.cat', (['[x, conv2]'], {'dim': '(1)'}), '([x, conv2], dim=1)\n', (7072, 7091), False, 'import torch\n'), ((7172, 7200), 'torch.cat', 'torch.cat', (['[x, conv1]'], {'dim': '(1)'}), '([x, conv1], dim=1)\n', (7181, 7200), False, 'import torch\n'), ((7415, 7440), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7438, 7440), False, 'import torch\n'), ((8872, 8920), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['pred', 'target'], {}), '(pred, target)\n', (8906, 8920), True, 'import torch.nn.functional as F\n'), ((8937, 8956), 'torch.sigmoid', 'torch.sigmoid', (['pred'], {}), '(pred)\n', (8950, 8956), False, 'import torch\n'), ((12265, 12292), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (12275, 12292), False, 'import torch\n'), ((13553, 13565), 'os.path.exists', 'exists', (['path'], {}), '(path)\n', (13559, 13565), False, 'from os.path import exists\n'), ((14279, 14300), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (14298, 14300), False, 'from torchvision import transforms, datasets, models\n'), ((14962, 14979), 'numpy.sum', 'np.sum', (['fold_size'], {}), '(fold_size)\n', (14968, 14979), True, 'import numpy as np\n'), ((15269, 15291), 'numpy.sum', 'np.sum', (['fold_size[0:i]'], {}), '(fold_size[0:i])\n', (15275, 15291), True, 'import numpy as np\n'), ((15306, 15332), 'numpy.sum', 'np.sum', (['fold_size[0:i + 1]'], {}), '(fold_size[0:i + 1])\n', (15312, 15332), True, 'import numpy as np\n'), ((15425, 15455), 'torch.utils.data.Subset', 'Subset', (['braTSDataset', 'folds[i]'], {}), '(braTSDataset, folds[i])\n', (15431, 15455), False, 'from torch.utils.data import Dataset, DataLoader, Subset\n'), ((15829, 15851), 'numpy.arange', 'np.arange', (['(0)', 'val_size'], {}), '(0, val_size)\n', (15838, 15851), True, 'import numpy as np\n'), ((16534, 16559), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (16557, 16559), False, 'import torch\n'), ((17039, 17050), 'time.time', 'time.time', ([], {}), '()\n', (17048, 17050), False, 'import time\n'), ((17406, 17417), 'time.time', 'time.time', ([], {}), '()\n', (17415, 17417), False, 'import time\n'), ((1235, 1261), 'os.path.join', 'os.path.join', (['data_path', 'p'], {}), '(data_path, p)\n', (1247, 1261), False, 'import os\n'), ((1286, 1307), 'os.listdir', 'os.listdir', (['file_path'], {}), '(file_path)\n', (1296, 1307), False, 'import os\n'), ((10335, 10363), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (10357, 10363), False, 'import torch\n'), ((11688, 11717), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (11710, 11717), False, 'import torch\n'), ((13010, 13039), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (13032, 13039), False, 'import torch\n'), ((14025, 14038), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (14035, 14038), False, 'import csv\n'), ((16145, 16202), 'torch.utils.data.ConcatDataset', 'torch.utils.data.ConcatDataset', (['[train_set, fold_sets[i]]'], {}), '([train_set, fold_sets[i]])\n', (16175, 16202), False, 'import torch\n'), ((17636, 17647), 'time.time', 'time.time', ([], {}), '()\n', (17645, 17647), False, 'import time\n'), ((17876, 17887), 'time.time', 'time.time', ([], {}), '()\n', (17885, 17887), False, 'import time\n'), ((999, 1017), 'os.walk', 'os.walk', (['data_path'], {}), '(data_path)\n', (1006, 1017), False, 'import os\n'), ((1386, 1424), 'os.path.join', 'os.path.join', (['file_path', 'file_names[0]'], {}), '(file_path, file_names[0])\n', (1398, 1424), False, 'import os\n'), ((1493, 1531), 'os.path.join', 'os.path.join', (['file_path', 'file_names[1]'], {}), '(file_path, file_names[1])\n', (1505, 1531), False, 'import os\n'), ((1599, 1637), 'os.path.join', 'os.path.join', (['file_path', 'file_names[2]'], {}), '(file_path, file_names[2])\n', (1611, 1637), False, 'import os\n'), ((1707, 1745), 'os.path.join', 'os.path.join', (['file_path', 'file_names[3]'], {}), '(file_path, file_names[3])\n', (1719, 1745), False, 'import os\n'), ((1813, 1851), 'os.path.join', 'os.path.join', (['file_path', 'file_names[4]'], {}), '(file_path, file_names[4])\n', (1825, 1851), False, 'import os\n'), ((13730, 13743), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (13740, 13743), False, 'import csv\n'), ((17290, 17301), 'time.time', 'time.time', ([], {}), '()\n', (17299, 17301), False, 'import time\n'), ((17515, 17526), 'time.time', 'time.time', ([], {}), '()\n', (17524, 17526), False, 'import time\n'), ((4506, 4540), 'torch.as_tensor', 'torch.as_tensor', (['self.target_masks'], {}), '(self.target_masks)\n', (4521, 4540), False, 'import torch\n'), ((3240, 3277), 'nibabel.load', 'nib.load', (['flair_files[dataShuffle[i]]'], {}), '(flair_files[dataShuffle[i]])\n', (3248, 3277), True, 'import nibabel as nib\n'), ((4116, 4151), 'nibabel.load', 'nib.load', (['seg_files[dataShuffle[i]]'], {}), '(seg_files[dataShuffle[i]])\n', (4124, 4151), True, 'import nibabel as nib\n'), ((3293, 3302), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (3299, 3302), True, 'import numpy as np\n'), ((4167, 4176), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (4173, 4176), True, 'import numpy as np\n')]
|
"""
This code is largely take from <NAME>'s Github
https://github.com/mdeff/cnn_graph/blob/master/nips2016/mnist.ipynb.
"""
import numpy as np
import scipy.sparse as sp
from sklearn.model_selection import train_test_split
from sklearn.neighbors import kneighbors_graph
from tensorflow.keras.datasets import mnist as m
MNIST_SIZE = 28
def load_data(k=8, noise_level=0.0):
"""
Loads the MNIST dataset and a K-NN graph to perform graph signal
classification, as described by [Defferrard et al. (2016)](https://arxiv.org/abs/1606.09375).
The K-NN graph is statically determined from a regular grid of pixels using
the 2d coordinates.
The node features of each graph are the MNIST digits vectorized and rescaled
to [0, 1].
Two nodes are connected if they are neighbours according to the K-NN graph.
Labels are the MNIST class associated to each sample.
:param k: int, number of neighbours for each node;
:param noise_level: fraction of edges to flip (from 0 to 1 and vice versa);
:return:
- X_train, y_train: training node features and labels;
- X_val, y_val: validation node features and labels;
- X_test, y_test: test node features and labels;
- A: adjacency matrix of the grid;
"""
A = _mnist_grid_graph(k)
A = _flip_random_edges(A, noise_level).astype(np.float32)
(X_train, y_train), (X_test, y_test) = m.load_data()
X_train, X_test = X_train / 255.0, X_test / 255.0
X_train = X_train.reshape(-1, MNIST_SIZE ** 2)
X_test = X_test.reshape(-1, MNIST_SIZE ** 2)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=10000)
return X_train, y_train, X_val, y_val, X_test, y_test, A
def _grid_coordinates(side):
"""
Returns 2D coordinates for a square grid of equally spaced nodes.
:param side: int, the side of the grid (i.e., the grid has side * side nodes).
:return: np.array of shape (side * side, 2).
"""
M = side ** 2
x = np.linspace(0, 1, side, dtype=np.float32)
y = np.linspace(0, 1, side, dtype=np.float32)
xx, yy = np.meshgrid(x, y)
z = np.empty((M, 2), np.float32)
z[:, 0] = xx.reshape(M)
z[:, 1] = yy.reshape(M)
return z
def _get_adj_from_data(X, k, **kwargs):
"""
Computes adjacency matrix of a K-NN graph from the given data.
:param X: rank 1 np.array, the 2D coordinates of pixels on the grid.
:param kwargs: kwargs for sklearn.neighbors.kneighbors_graph (see docs
[here](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.kneighbors_graph.html)).
:return: scipy sparse matrix.
"""
A = kneighbors_graph(X, k, **kwargs).toarray()
A = sp.csr_matrix(np.maximum(A, A.T))
return A
def _mnist_grid_graph(k):
"""
Get the adjacency matrix for the KNN graph.
:param k: int, number of neighbours for each node;
:return:
"""
X = _grid_coordinates(MNIST_SIZE)
A = _get_adj_from_data(
X, k, mode='connectivity', metric='euclidean', include_self=False
)
return A
def _flip_random_edges(A, percent):
"""
Flips values of A randomly.
:param A: binary scipy sparse matrix.
:param percent: percent of the edges to flip.
:return: binary scipy sparse matrix.
"""
if not A.shape[0] == A.shape[1]:
raise ValueError('A must be a square matrix.')
dtype = A.dtype
A = sp.lil_matrix(A).astype(np.bool)
n_elem = A.shape[0] ** 2
n_elem_to_flip = round(percent * n_elem)
unique_idx = np.random.choice(n_elem, replace=False, size=n_elem_to_flip)
row_idx = unique_idx // A.shape[0]
col_idx = unique_idx % A.shape[0]
idxs = np.stack((row_idx, col_idx)).T
for i in idxs:
i = tuple(i)
A[i] = np.logical_not(A[i])
A = A.tocsr().astype(dtype)
A.eliminate_zeros()
return A
|
[
"numpy.stack",
"numpy.meshgrid",
"numpy.maximum",
"sklearn.model_selection.train_test_split",
"numpy.empty",
"numpy.logical_not",
"tensorflow.keras.datasets.mnist.load_data",
"scipy.sparse.lil_matrix",
"numpy.linspace",
"numpy.random.choice",
"sklearn.neighbors.kneighbors_graph"
] |
[((1406, 1419), 'tensorflow.keras.datasets.mnist.load_data', 'm.load_data', ([], {}), '()\n', (1417, 1419), True, 'from tensorflow.keras.datasets import mnist as m\n'), ((1612, 1663), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_train', 'y_train'], {'test_size': '(10000)'}), '(X_train, y_train, test_size=10000)\n', (1628, 1663), False, 'from sklearn.model_selection import train_test_split\n'), ((2001, 2042), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'side'], {'dtype': 'np.float32'}), '(0, 1, side, dtype=np.float32)\n', (2012, 2042), True, 'import numpy as np\n'), ((2051, 2092), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'side'], {'dtype': 'np.float32'}), '(0, 1, side, dtype=np.float32)\n', (2062, 2092), True, 'import numpy as np\n'), ((2106, 2123), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (2117, 2123), True, 'import numpy as np\n'), ((2132, 2160), 'numpy.empty', 'np.empty', (['(M, 2)', 'np.float32'], {}), '((M, 2), np.float32)\n', (2140, 2160), True, 'import numpy as np\n'), ((3531, 3591), 'numpy.random.choice', 'np.random.choice', (['n_elem'], {'replace': '(False)', 'size': 'n_elem_to_flip'}), '(n_elem, replace=False, size=n_elem_to_flip)\n', (3547, 3591), True, 'import numpy as np\n'), ((2714, 2732), 'numpy.maximum', 'np.maximum', (['A', 'A.T'], {}), '(A, A.T)\n', (2724, 2732), True, 'import numpy as np\n'), ((3680, 3708), 'numpy.stack', 'np.stack', (['(row_idx, col_idx)'], {}), '((row_idx, col_idx))\n', (3688, 3708), True, 'import numpy as np\n'), ((3766, 3786), 'numpy.logical_not', 'np.logical_not', (['A[i]'], {}), '(A[i])\n', (3780, 3786), True, 'import numpy as np\n'), ((2649, 2681), 'sklearn.neighbors.kneighbors_graph', 'kneighbors_graph', (['X', 'k'], {}), '(X, k, **kwargs)\n', (2665, 2681), False, 'from sklearn.neighbors import kneighbors_graph\n'), ((3407, 3423), 'scipy.sparse.lil_matrix', 'sp.lil_matrix', (['A'], {}), '(A)\n', (3420, 3423), True, 'import scipy.sparse as sp\n')]
|
import os
import pdb
import os.path as osp
import sys
sys.path[0] = os.getcwd()
import cv2
import copy
import json
import yaml
import logging
import argparse
from tqdm import tqdm
from itertools import groupby
import pycocotools.mask as mask_utils
import numpy as np
import torch
from torchvision.transforms import transforms as T
from utils.log import logger
from utils.meter import Timer
from utils.mask import pts2array
import data.video as videodataset
from utils import visualize as vis
from utils.io import mkdir_if_missing
from core.association import matching
from tracker.mot.pose import PoseAssociationTracker
def identical(a, b):
if len(a) == len(b):
arra = pts2array(a)
arrb = pts2array(b)
if np.abs(arra-arrb).sum() < 1e-2:
return True
return False
def fuse_result(res, jpath):
with open(jpath, 'r') as f:
obsj = json.load(f)
obsj_fused = copy.deepcopy(obsj)
for t, inpj in enumerate(obsj['annolist']):
skltns, ids = res[t][2], res[t][3]
nobj_ori = len(obsj['annolist'][t]['annorect'])
for i in range(nobj_ori):
obsj_fused['annolist'][t]['annorect'][i]['track_id'] = [1000]
for j, skltn in enumerate(skltns):
match = identical(obsj['annolist'][t]['annorect'][i]['annopoints'][0]['point'], skltn)
if match:
obsj_fused['annolist'][t]['annorect'][i]['track_id'] = [ids[j],]
return obsj_fused
def eval_seq(opt, dataloader, save_dir=None):
if save_dir:
mkdir_if_missing(save_dir)
tracker = PoseAssociationTracker(opt)
timer = Timer()
results = []
for frame_id, (img, obs, img0, _) in enumerate(dataloader):
# run tracking
timer.tic()
online_targets = tracker.update(img, img0, obs)
online_tlwhs = []
online_ids = []
online_poses = []
for t in online_targets:
tlwh = t.tlwh
tid = t.track_id
online_tlwhs.append(tlwh)
online_ids.append(tid)
online_poses.append(t.pose)
timer.toc()
# save results
results.append((frame_id + 1, online_tlwhs, online_poses, online_ids))
if save_dir is not None:
online_im = vis.plot_tracking(img0, online_tlwhs,
online_ids, frame_id=frame_id, fps=1. / timer.average_time)
if save_dir is not None:
cv2.imwrite(os.path.join(
save_dir, '{:05d}.jpg'.format(frame_id)), online_im)
return results, timer.average_time, timer.calls
def main(opt):
logger.setLevel(logging.INFO)
result_root = opt.out_root
result_json_root = osp.join(result_root, 'json')
mkdir_if_missing(result_json_root)
transforms= T.Compose([T.ToTensor(), T.Normalize(opt.im_mean, opt.im_std)])
obs_root = osp.join(opt.data_root, 'obs', opt.split, opt.obid)
obs_jpaths = [osp.join(obs_root, o) for o in os.listdir(obs_root)]
obs_jpaths = sorted([o for o in obs_jpaths if o.endswith('.json')])
# run tracking
accs = []
timer_avgs, timer_calls = [], []
for i, obs_jpath in enumerate(obs_jpaths):
seqname = obs_jpath.split('/')[-1].split('.')[0]
output_dir = osp.join(result_root, 'frame', seqname)
dataloader = videodataset.LoadImagesAndPoseObs(obs_jpath, opt)
seq_res, ta, tc = eval_seq(opt, dataloader, save_dir=output_dir)
seq_json = fuse_result(seq_res, obs_jpath)
with open(osp.join(result_json_root, "{}.json".format(seqname)), 'w') as f:
json.dump(seq_json, f)
timer_avgs.append(ta)
timer_calls.append(tc)
# eval
logger.info('Evaluate seq: {}'.format(seqname))
if opt.save_videos:
output_video_path = osp.join(output_dir, '{}.mp4'.format(seqname))
cmd_str = 'ffmpeg -f image2 -i {}/%05d.jpg -c:v copy {}'.format(output_dir, output_video_path)
os.system(cmd_str)
timer_avgs = np.asarray(timer_avgs)
timer_calls = np.asarray(timer_calls)
all_time = np.dot(timer_avgs, timer_calls)
avg_time = all_time / np.sum(timer_calls)
logger.info('Time elapsed: {:.2f} seconds, FPS: {:.2f}'.format(all_time, 1.0 / avg_time))
cmd_str = ('python ./eval/poseval/evaluate.py --groundTruth={}/posetrack_data/annotations/{} '
'--predictions={}/ --evalPoseTracking'.format(opt.data_root, opt.split, result_json_root))
os.system(cmd_str)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='', required=True, type=str)
opt = parser.parse_args()
with open(opt.config) as f:
common_args = yaml.load(f)
for k, v in common_args['common'].items():
setattr(opt, k, v)
for k, v in common_args['posetrack'].items():
setattr(opt, k, v)
opt.out_root = osp.join('results/pose', opt.exp_name)
opt.out_file = osp.join('results/pose', opt.exp_name + '.json')
print(opt, end='\n\n')
main(opt)
|
[
"yaml.load",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.abs",
"os.path.join",
"tracker.mot.pose.PoseAssociationTracker",
"json.dump",
"copy.deepcopy",
"utils.meter.Timer",
"numpy.asarray",
"os.system",
"torchvision.transforms.transforms.ToTensor",
"data.video.LoadImagesAndPoseObs",
"numpy.dot",
"os.listdir",
"utils.mask.pts2array",
"json.load",
"os.getcwd",
"utils.log.logger.setLevel",
"torchvision.transforms.transforms.Normalize",
"utils.visualize.plot_tracking",
"utils.io.mkdir_if_missing"
] |
[((72, 83), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (81, 83), False, 'import os\n'), ((959, 978), 'copy.deepcopy', 'copy.deepcopy', (['obsj'], {}), '(obsj)\n', (972, 978), False, 'import copy\n'), ((1647, 1674), 'tracker.mot.pose.PoseAssociationTracker', 'PoseAssociationTracker', (['opt'], {}), '(opt)\n', (1669, 1674), False, 'from tracker.mot.pose import PoseAssociationTracker\n'), ((1689, 1696), 'utils.meter.Timer', 'Timer', ([], {}), '()\n', (1694, 1696), False, 'from utils.meter import Timer\n'), ((2695, 2724), 'utils.log.logger.setLevel', 'logger.setLevel', (['logging.INFO'], {}), '(logging.INFO)\n', (2710, 2724), False, 'from utils.log import logger\n'), ((2782, 2811), 'os.path.join', 'osp.join', (['result_root', '"""json"""'], {}), "(result_root, 'json')\n", (2790, 2811), True, 'import os.path as osp\n'), ((2817, 2851), 'utils.io.mkdir_if_missing', 'mkdir_if_missing', (['result_json_root'], {}), '(result_json_root)\n', (2833, 2851), False, 'from utils.io import mkdir_if_missing\n'), ((2951, 3002), 'os.path.join', 'osp.join', (['opt.data_root', '"""obs"""', 'opt.split', 'opt.obid'], {}), "(opt.data_root, 'obs', opt.split, opt.obid)\n", (2959, 3002), True, 'import os.path as osp\n'), ((4122, 4144), 'numpy.asarray', 'np.asarray', (['timer_avgs'], {}), '(timer_avgs)\n', (4132, 4144), True, 'import numpy as np\n'), ((4164, 4187), 'numpy.asarray', 'np.asarray', (['timer_calls'], {}), '(timer_calls)\n', (4174, 4187), True, 'import numpy as np\n'), ((4204, 4235), 'numpy.dot', 'np.dot', (['timer_avgs', 'timer_calls'], {}), '(timer_avgs, timer_calls)\n', (4210, 4235), True, 'import numpy as np\n'), ((4592, 4610), 'os.system', 'os.system', (['cmd_str'], {}), '(cmd_str)\n', (4601, 4610), False, 'import os\n'), ((4657, 4682), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4680, 4682), False, 'import argparse\n'), ((5039, 5077), 'os.path.join', 'osp.join', (['"""results/pose"""', 'opt.exp_name'], {}), "('results/pose', opt.exp_name)\n", (5047, 5077), True, 'import os.path as osp\n'), ((5098, 5146), 'os.path.join', 'osp.join', (['"""results/pose"""', "(opt.exp_name + '.json')"], {}), "('results/pose', opt.exp_name + '.json')\n", (5106, 5146), True, 'import os.path as osp\n'), ((716, 728), 'utils.mask.pts2array', 'pts2array', (['a'], {}), '(a)\n', (725, 728), False, 'from utils.mask import pts2array\n'), ((745, 757), 'utils.mask.pts2array', 'pts2array', (['b'], {}), '(b)\n', (754, 757), False, 'from utils.mask import pts2array\n'), ((926, 938), 'json.load', 'json.load', (['f'], {}), '(f)\n', (935, 938), False, 'import json\n'), ((1605, 1631), 'utils.io.mkdir_if_missing', 'mkdir_if_missing', (['save_dir'], {}), '(save_dir)\n', (1621, 1631), False, 'from utils.io import mkdir_if_missing\n'), ((3022, 3043), 'os.path.join', 'osp.join', (['obs_root', 'o'], {}), '(obs_root, o)\n', (3030, 3043), True, 'import os.path as osp\n'), ((3351, 3390), 'os.path.join', 'osp.join', (['result_root', '"""frame"""', 'seqname'], {}), "(result_root, 'frame', seqname)\n", (3359, 3390), True, 'import os.path as osp\n'), ((3413, 3462), 'data.video.LoadImagesAndPoseObs', 'videodataset.LoadImagesAndPoseObs', (['obs_jpath', 'opt'], {}), '(obs_jpath, opt)\n', (3446, 3462), True, 'import data.video as videodataset\n'), ((4263, 4282), 'numpy.sum', 'np.sum', (['timer_calls'], {}), '(timer_calls)\n', (4269, 4282), True, 'import numpy as np\n'), ((4844, 4856), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (4853, 4856), False, 'import yaml\n'), ((2354, 2457), 'utils.visualize.plot_tracking', 'vis.plot_tracking', (['img0', 'online_tlwhs', 'online_ids'], {'frame_id': 'frame_id', 'fps': '(1.0 / timer.average_time)'}), '(img0, online_tlwhs, online_ids, frame_id=frame_id, fps=\n 1.0 / timer.average_time)\n', (2371, 2457), True, 'from utils import visualize as vis\n'), ((2880, 2892), 'torchvision.transforms.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (2890, 2892), True, 'from torchvision.transforms import transforms as T\n'), ((2894, 2930), 'torchvision.transforms.transforms.Normalize', 'T.Normalize', (['opt.im_mean', 'opt.im_std'], {}), '(opt.im_mean, opt.im_std)\n', (2905, 2930), True, 'from torchvision.transforms import transforms as T\n'), ((3053, 3073), 'os.listdir', 'os.listdir', (['obs_root'], {}), '(obs_root)\n', (3063, 3073), False, 'import os\n'), ((3688, 3710), 'json.dump', 'json.dump', (['seq_json', 'f'], {}), '(seq_json, f)\n', (3697, 3710), False, 'import json\n'), ((4079, 4097), 'os.system', 'os.system', (['cmd_str'], {}), '(cmd_str)\n', (4088, 4097), False, 'import os\n'), ((770, 789), 'numpy.abs', 'np.abs', (['(arra - arrb)'], {}), '(arra - arrb)\n', (776, 789), True, 'import numpy as np\n')]
|
import networkx as nx
import csv
from scipy import sparse as sp
from scipy.sparse import csgraph
import scipy.sparse.linalg as splinalg
import numpy as np
import pandas as pd
import warnings
import collections as cole
from .cpp import *
import random
import gzip
import bz2
import lzma
import multiprocessing as mp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import LineCollection
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from matplotlib.colors import to_rgb,to_rgba
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
from collections import defaultdict
from .GraphDrawing import GraphDrawing
def _load_from_shared(sabuf, dtype, shape):
return np.frombuffer(sabuf, dtype=dtype).reshape(shape)
""" Create shared memory that can be passed to a child process,
wrapped in a numpy array."""
def _copy_to_shared(a):
# determine the numpy type of a.
dtype = a.dtype
shape = a.shape
sabuf = mp.RawArray(ctypes.c_uint8, a.nbytes)
sa = _load_from_shared(sabuf, dtype, shape)
np.copyto(sa, a) # make a copy
return sa, (sabuf, dtype, shape)
class GraphLocal:
"""
This class implements graph loading from an edgelist, gml or graphml and provides methods that operate on the graph.
Attributes
----------
adjacency_matrix : scipy csr matrix
ai : numpy vector
CSC format index pointer array, its data type is determined by "itype" during initialization
aj : numpy vector
CSC format index array, its data type is determined by "vtype" during initialization
_num_vertices : int
Number of vertices
_num_edges : int
Number of edges
_weighted : boolean
Declares if it is a weighted graph or not
d : float64 numpy vector
Degrees vector
dn : float64 numpy vector
Component-wise reciprocal of degrees vector
d_sqrt : float64 numpy vector
Component-wise square root of degrees vector
dn_sqrt : float64 numpy vector
Component-wise reciprocal of sqaure root degrees vector
vol_G : float64 numpy vector
Volume of graph
components : list of sets
Each set contains the indices of a connected component of the graph
number_of_components : int
Number of connected components of the graph
bicomponents : list of sets
Each set contains the indices of a biconnected component of the graph
number_of_bicomponents : int
Number of connected components of the graph
core_numbers : dictionary
Core number for each vertex
Methods
-------
read_graph(filename, file_type='edgelist', separator='\t')
Reads the graph from a file
compute_statistics()
Computes statistics for the graph
connected_components()
Computes the connected components of the graph
is_disconnected()
Checks if graph is connected
biconnected_components():
Computes the biconnected components of the graph
core_number()
Returns the core number for each vertex
neighbors(vertex)
Returns a list with the neighbors of the given vertex
list_to_gl(source,target)
Create a GraphLocal object from edge list
"""
def __init__(self,
filename = None,
file_type='edgelist',
separator='\t',
remove_whitespace=False,header=False, headerrow=None,
vtype=np.uint32,itype=np.uint32):
"""
Initializes the graph from a gml or a edgelist file and initializes the attributes of the class.
Parameters
----------
See read_graph for a description of the parameters.
"""
if filename != None:
self.read_graph(filename, file_type = file_type, separator = separator, remove_whitespace = remove_whitespace,
header = header, headerrow = headerrow, vtype=vtype, itype=itype)
def __eq__(self,other):
if not isinstance(other, GraphLocal):
return NotImplemented
return np.array_equal(self.ai,other.ai) and np.array_equal(self.aj,other.aj) and np.array_equal(self.adjacency_matrix.data,other.adjacency_matrix.data)
def read_graph(self, filename, file_type='edgelist', separator='\t', remove_whitespace=False, header=False, headerrow=None, vtype=np.uint32, itype=np.uint32):
"""
Reads the graph from an edgelist, gml or graphml file and initializes the class attribute adjacency_matrix.
Parameters
----------
filename : string
Name of the file, for example 'JohnsHopkins.edgelist', 'JohnsHopkins.gml', 'JohnsHopkins.graphml'.
file_type : string
Type of file. Currently only 'edgelist', 'gml' and 'graphml' are supported.
Default = 'edgelist'
separator : string
used if file_type = 'edgelist'
Default = '\t'
remove_whitespace : bool
set it to be True when there is more than one kinds of separators in the file
Default = False
header : bool
This lets the first line of the file contain a set of heade
information that should be ignore_index
Default = False
headerrow : int
Use which row as column names. This argument takes precidence over
the header=True using headerrow = 0
Default = None
vtype
numpy integer type of CSC format index array
Default = np.uint32
itype
numpy integer type of CSC format index pointer array
Default = np.uint32
"""
if file_type == 'edgelist':
#dtype = {0:'int32', 1:'int32', 2:'float64'}
if header and headerrow is None:
headerrow = 0
if remove_whitespace:
df = pd.read_csv(filename, header=headerrow, delim_whitespace=remove_whitespace)
else:
df = pd.read_csv(filename, sep=separator, header=headerrow, delim_whitespace=remove_whitespace)
cols = [0,1,2]
if header != None:
cols = list(df.columns)
source = df[cols[0]].values
target = df[cols[1]].values
if df.shape[1] == 2:
weights = np.ones(source.shape[0])
elif df.shape[1] == 3:
weights = df[cols[2]].values
else:
raise Exception('GraphLocal.read_graph: df.shape[1] not in (2, 3)')
self._num_vertices = max(source.max() + 1, target.max()+1)
#self.adjacency_matrix = source, target, weights
self.adjacency_matrix = sp.csr_matrix((weights.astype(np.float64), (source, target)), shape=(self._num_vertices, self._num_vertices))
elif file_type == 'gml':
warnings.warn("Loading a gml is not efficient, we suggest using an edgelist format for this API.")
G = nx.read_gml(filename).to_undirected()
self.adjacency_matrix = nx.adjacency_matrix(G).astype(np.float64)
self._num_vertices = nx.number_of_nodes(G)
elif file_type == 'graphml':
warnings.warn("Loading a graphml is not efficient, we suggest using an edgelist format for this API.")
G = nx.read_graphml(filename).to_undirected()
self.adjacency_matrix = nx.adjacency_matrix(G).astype(np.float64)
self._num_vertices = nx.number_of_nodes(G)
else:
print('This file type is not supported')
return
self._weighted = False
for i in self.adjacency_matrix.data:
if i != 1:
self._weighted = True
break
is_symmetric = (self.adjacency_matrix != self.adjacency_matrix.T).sum() == 0
if not is_symmetric:
# Symmetrize matrix, choosing larger weight
sel = self.adjacency_matrix.T > self.adjacency_matrix
self.adjacency_matrix = self.adjacency_matrix - self.adjacency_matrix.multiply(sel) + self.adjacency_matrix.T.multiply(sel)
assert (self.adjacency_matrix != self.adjacency_matrix.T).sum() == 0
self._num_edges = self.adjacency_matrix.nnz
self.compute_statistics()
self.ai = itype(self.adjacency_matrix.indptr)
self.aj = vtype(self.adjacency_matrix.indices)
@classmethod
def from_networkx(cls,G):
"""
Create a GraphLocal object from a networkx graph.
Paramters
---------
G
The networkx graph.
"""
if G.is_directed() == True:
raise Exception("from_networkx requires an undirected graph, use G.to_undirected()")
rval = cls()
rval.adjacency_matrix = nx.adjacency_matrix(G).astype(np.float64)
rval._num_vertices = nx.number_of_nodes(G)
# TODO, use this in the read_graph
rval._weighted = False
for i in rval.adjacency_matrix.data:
if i != 1:
rval._weighted = True
break
# automatically determine sizes
if G.number_of_nodes() < 4294967295:
vtype = np.uint32
else:
vtype = np.int64
if 2*G.number_of_edges() < 4294967295:
itype = np.uint32
else:
itype = np.int64
rval._num_edges = rval.adjacency_matrix.nnz
rval.compute_statistics()
rval.ai = itype(rval.adjacency_matrix.indptr)
rval.aj = vtype(rval.adjacency_matrix.indices)
return rval
@classmethod
def from_sparse_adjacency(cls,A):
"""
Create a GraphLocal object from a sparse adjacency matrix.
Paramters
---------
A
Adjacency matrix.
"""
self = cls()
self.adjacency_matrix = A.copy()
self._num_vertices = A.shape[0]
self._num_edges = A.nnz
# TODO, use this in the read_graph
self._weighted = False
for i in self.adjacency_matrix.data:
if i != 1:
self._weighted = True
break
# automatically determine sizes
if self._num_vertices < 4294967295:
vtype = np.uint32
else:
vtype = np.int64
if 2*self._num_edges < 4294967295:
itype = np.uint32
else:
itype = np.int64
self.compute_statistics()
self.ai = itype(self.adjacency_matrix.indptr)
self.aj = vtype(self.adjacency_matrix.indices)
return self
def renew_data(self,A):
"""
Update data because the adjacency matrix changed
Paramters
---------
A
Adjacency matrix.
"""
self._num_edges = A.nnz
# TODO, use this in the read_graph
self._weighted = False
for i in self.adjacency_matrix.data:
if i != 1:
self._weighted = True
break
# automatically determine sizes
if self._num_vertices < 4294967295:
vtype = np.uint32
else:
vtype = np.int64
if 2*self._num_edges < 4294967295:
itype = np.uint32
else:
itype = np.int64
self.compute_statistics()
self.ai = itype(self.adjacency_matrix.indptr)
self.aj = vtype(self.adjacency_matrix.indices)
def list_to_gl(self,source,target,weights,vtype=np.uint32, itype=np.uint32):
"""
Create a GraphLocal object from edge list.
Parameters
----------
source
A numpy array of sources for the edges
target
A numpy array of targets for the edges
weights
A numpy array of weights for the edges
vtype
numpy integer type of CSC format index array
Default = np.uint32
itype
numpy integer type of CSC format index pointer array
Default = np.uint32
"""
# TODO, fix this up to avoid duplicating code with read...
source = np.array(source,dtype=vtype)
target = np.array(target,dtype=vtype)
weights = np.array(weights,dtype=np.double)
self._num_edges = len(source)
self._num_vertices = max(source.max() + 1, target.max()+1)
self.adjacency_matrix = sp.csr_matrix((weights.astype(np.float64), (source, target)), shape=(self._num_vertices, self._num_vertices))
self._weighted = False
for i in self.adjacency_matrix.data:
if i != 1:
self._weighted = True
break
is_symmetric = (self.adjacency_matrix != self.adjacency_matrix.T).sum() == 0
if not is_symmetric:
# Symmetrize matrix, choosing larger weight
sel = self.adjacency_matrix.T > self.adjacency_matrix
self.adjacency_matrix = self.adjacency_matrix - self.adjacency_matrix.multiply(sel) + self.adjacency_matrix.T.multiply(sel)
assert (self.adjacency_matrix != self.adjacency_matrix.T).sum() == 0
self._num_edges = self.adjacency_matrix.nnz
self.compute_statistics()
self.ai = itype(self.adjacency_matrix.indptr)
self.aj = vtype(self.adjacency_matrix.indices)
def discard_weights(self):
""" Discard any weights that were loaded from the data file.
This sets all the weights associated with each edge to 1.0,
which is our "no weight" case."""
self.adjacency_matrix.data.fill(1.0)
self._weighted = False
self.compute_statistics()
def compute_statistics(self):
"""
Computes statistics for the graph. It updates the class attributes.
The user needs to read the graph first before calling
this method by calling the read_graph method from this class.
"""
self.d = np.ravel(self.adjacency_matrix.sum(axis=1))
self.dn = np.zeros(self._num_vertices)
self.dn[self.d != 0] = 1.0 / self.d[self.d != 0]
self.d_sqrt = np.sqrt(self.d)
self.dn_sqrt = np.sqrt(self.dn)
self.vol_G = np.sum(self.d)
def to_shared(self):
""" Re-create the graph data with multiprocessing compatible
shared-memory arrays that can be passed to child-processes.
This returns a dictionary that allows the graph to be
re-created in a child-process from that variable and
the method "from_shared"
At this moment, this doesn't send any data from components,
core_numbers, or biconnected_components
"""
sgraphvars = {}
self.ai, sgraphvars["ai"] = _copy_to_shared(self.ai)
self.aj, sgraphvars["aj"] = _copy_to_shared(self.aj)
self.d, sgraphvars["d"] = _copy_to_shared(self.d)
self.dn, sgraphvars["dn"] = _copy_to_shared(self.dn)
self.d_sqrt, sgraphvars["d_sqrt"] = _copy_to_shared(self.d_sqrt)
self.dn_sqrt, sgraphvars["dn_sqrt"] = _copy_to_shared(self.dn_sqrt)
self.adjacency_matrix.data, sgraphvars["a"] = _copy_to_shared(self.adjacency_matrix.data)
# this will rebuild without copying
# so that copies should all be accessing exactly the same
# arrays for caching
self.adjacency_matrix = sp.csr_matrix(
(self.adjacency_matrix.data, self.aj, self.ai),
shape=(self._num_vertices, self._num_vertices))
# scalars
sgraphvars["n"] = self._num_vertices
sgraphvars["m"] = self._num_edges
sgraphvars["vol"] = self.vol_G
sgraphvars["weighted"] = self._weighted
return sgraphvars
@classmethod
def from_shared(cls, sgraphvars):
""" Return a graph object from the output of "to_shared". """
g = cls()
g._num_vertices = sgraphvars["n"]
g._num_edges = sgraphvars["m"]
g._weighted = sgraphvars["weighted"]
g.vol_G = sgraphvars["vol"]
g.ai = _load_from_shared(*sgraphvars["ai"])
g.aj = _load_from_shared(*sgraphvars["aj"])
g.adjacency_matrix = sp.csr_matrix(
(_load_from_shared(*sgraphvars["a"]), g.aj, g.ai),
shape=(g._num_vertices, g._num_vertices))
g.d = _load_from_shared(*sgraphvars["d"])
g.dn = _load_from_shared(*sgraphvars["dn"])
g.d_sqrt = _load_from_shared(*sgraphvars["d_sqrt"])
g.dn_sqrt = _load_from_shared(*sgraphvars["dn_sqrt"])
return g
def connected_components(self):
"""
Computes the connected components of the graph. It stores the results in class attributes components
and number_of_components. The user needs to call read the graph
first before calling this function by calling the read_graph function from this class.
"""
output = csgraph.connected_components(self.adjacency_matrix,directed=False)
self.components = output[1]
self.number_of_components = output[0]
print('There are ', self.number_of_components, ' connected components in the graph')
def is_disconnected(self):
"""
The output can be accessed from the graph object that calls this function.
Checks if the graph is a disconnected graph. It prints the result as a comment and
returns True if the graph is disconnected, or false otherwise. The user needs to
call read the graph first before calling this function by calling the read_graph function from this class.
This function calls Networkx.
Returns
-------
True
If connected
False
If disconnected
"""
if self.d == []:
print('The graph has to be read first.')
return
self.connected_components()
if self.number_of_components > 1:
print('The graph is a disconnected graph.')
return True
else:
print('The graph is not a disconnected graph.')
return False
def biconnected_components(self):
"""
Computes the biconnected components of the graph. It stores the results in class attributes bicomponents
and number_of_bicomponents. The user needs to call read the graph first before calling this
function by calling the read_graph function from this class. This function calls Networkx.
"""
warnings.warn("Warning, biconnected_components is not efficiently implemented.")
g_nx = nx.from_scipy_sparse_matrix(self.adjacency_matrix)
self.bicomponents = list(nx.biconnected_components(g_nx))
self.number_of_bicomponents = len(self.bicomponents)
def core_number(self):
"""
Returns the core number for each vertex. A k-core is a maximal
subgraph that contains nodes of degree k or more. The core number of a node
is the largest value k of a k-core containing that node. The user needs to
call read the graph first before calling this function by calling the read_graph
function from this class. The output can be accessed from the graph object that
calls this function. It stores the results in class attribute core_numbers.
"""
warnings.warn("Warning, core_number is not efficiently implemented.")
g_nx = nx.from_scipy_sparse_matrix(self.adjacency_matrix)
self.core_numbers = nx.core_number(g_nx)
def neighbors(self,vertex):
"""
Returns a list with the neighbors of the given vertex.
"""
# this will be faster since we store the arrays ourselves.
return self.aj[self.ai[vertex]:self.ai[vertex+1]].tolist()
#return self.adjacency_matrix[:,vertex].nonzero()[0].tolist()
def compute_conductance(self,R,cpp=True):
"""
Return conductance of a set of vertices.
"""
records = self.set_scores(R,cpp=cpp)
return records["cond"]
def set_scores(self,R,cpp=True):
"""
Return various metrics of a set of vertices.
"""
voltrue,cut = 0,0
if cpp:
voltrue, cut = set_scores_cpp(self._num_vertices,self.ai,self.aj,self.adjacency_matrix.data,self.d,R,self._weighted)
else:
voltrue = sum(self.d[R])
v_ones_R = np.zeros(self._num_vertices)
v_ones_R[R] = 1
cut = voltrue - np.dot(v_ones_R,self.adjacency_matrix.dot(v_ones_R.T))
voleff = min(voltrue,self.vol_G - voltrue)
sizetrue = len(R)
sizeeff = sizetrue
if voleff < voltrue:
sizeeff = self._num_vertices - sizetrue
# remove the stuff we don't want returned...
del R
del self
if not cpp:
del v_ones_R
del cpp
edgestrue = voltrue - cut
edgeseff = voleff - cut
cond = cut / voleff if voleff != 0 else 1
isop = cut / sizeeff if sizeeff != 0 else 1
# make a dictionary out of local variables
return locals()
def largest_component(self):
self.connected_components()
if self.number_of_components == 1:
#self.compute_statistics()
return self
else:
# find nodes of largest component
counter=cole.Counter(self.components)
maxccnodes = []
what_key = counter.most_common(1)[0][0]
for i in range(self._num_vertices):
if what_key == self.components[i]:
maxccnodes.append(i)
# biggest component by len of it's list of nodes
#maxccnodes = max(self.components, key=len)
#maxccnodes = list(maxccnodes)
warnings.warn("The graph has multiple (%i) components, using the largest with %i / %i nodes"%(
self.number_of_components, len(maxccnodes), self._num_vertices))
g_copy = GraphLocal()
g_copy.adjacency_matrix = self.adjacency_matrix[maxccnodes,:].tocsc()[:,maxccnodes].tocsr()
g_copy._num_vertices = len(maxccnodes) # AHH!
g_copy.compute_statistics()
g_copy._weighted = self._weighted
dt = np.dtype(self.ai[0])
itype = np.int64 if dt.name == 'int64' else np.uint32
dt = np.dtype(self.aj[0])
vtype = np.int64 if dt.name == 'int64' else np.uint32
g_copy.ai = itype(g_copy.adjacency_matrix.indptr)
g_copy.aj = vtype(g_copy.adjacency_matrix.indices)
g_copy._num_edges = g_copy.adjacency_matrix.nnz
return g_copy
def local_extrema(self,vals,strict=False,reverse=False):
"""
Find extrema in a graph based on a set of values.
Parameters
----------
vals: Sequence[float]
a feature value per node used to find the ex against each other, i.e. conductance
strict: bool
If True, find a set of vertices where vals(i) < vals(j) for all neighbors N(j)
i.e. local minima in the space of the graph
If False, find a set of vertices where vals(i) <= vals(j) for all neighbors N(j)
i.e. local minima in the space of the graph
reverse: bool
if True, then find local maxima, if False then find local minima
(by default, this is false, so we find local minima)
Returns
-------
minverts: Sequence[int]
the set of vertices
minvals: Sequence[float]
the set of min values
"""
n = self.adjacency_matrix.shape[0]
minverts = []
ai = self.ai
aj = self.aj
factor = 1.0
if reverse:
factor = -1.0
for i in range(n):
vali = factor*vals[i]
lmin = True
for nzi in range(ai[i],ai[i+1]):
v = aj[nzi]
if v == i:
continue # skip self-loops
if strict:
if vali < factor*vals[v]:
continue
else:
lmin = False
else:
if vali <= factor*vals[v]:
continue
else:
lmin = False
if lmin == False:
break # break out of the loop
if lmin:
minverts.append(i)
minvals = vals[minverts]
return minverts, minvals
@staticmethod
def _plotting(drawing,edgecolor,edgealpha,linewidth,is_3d,**kwargs):
"""
private function to do the plotting
"**kwargs" represents all possible optional parameters of "scatter" function
in matplotlib.pyplot
"""
drawing.scatter(**kwargs)
drawing.plot(color=edgecolor,alpha=edgealpha,linewidths=linewidth)
axs = drawing.ax
axs.autoscale()
if is_3d == 3:
# Set the initial view
axs.view_init(30, angle)
def draw(self,coords,alpha=1.0,nodesize=5,linewidth=1,
nodealpha=1.0,edgealpha=1.0,edgecolor='k',nodemarker='o',
axs=None,fig=None,values=None,cm=None,valuecenter=None,angle=30,
figsize=None,nodecolor='r'):
"""
Standard drawing function when having single cluster
Parameters
----------
coords: a n-by-2 or n-by-3 array with coordinates for each node of the graph.
Optional parameters
------------------
alpha: float (1.0 by default)
the overall alpha scaling of the plot, [0,1]
nodealpha: float (1.0 by default)
the overall node alpha scaling of the plot, [0, 1]
edgealpha: float (1.0 by default)
the overall edge alpha scaling of the plot, [0, 1]
nodecolor: string or RGB ('r' by default)
edgecolor: string or RGB ('k' by default)
setcolor: string or RGB ('y' by default)
nodemarker: string ('o' by default)
nodesize: float (5.0 by default)
linewidth: float (1.0 by default)
axs,fig: None,None (default)
by default it will create a new figure, or this will plot in axs if not None.
values: Sequence[float] (None by default)
used to determine node colors in a colormap, should have the same length as coords
valuecenter: often used with values together to determine vmin and vmax of colormap
offset = max(abs(values-valuecenter))
vmax = valuecenter + offset
vmin = valuecenter - offset
cm: string or colormap object (None by default)
figsize: tuple (None by default)
angle: float (30 by default)
set initial view angle when drawing 3d
Returns
-------
A GraphDrawing object
"""
drawing = GraphDrawing(self,coords,ax=axs,figsize=figsize)
if values is not None:
values = np.asarray(values)
if values.ndim == 2:
node_color_list = np.reshape(values,len(coords))
else:
node_color_list = values
vmin = min(node_color_list)
vmax = max(node_color_list)
if cm is not None:
cm = plt.get_cmap(cm)
else:
if valuecenter is not None:
#when both values and valuecenter are provided, use PuOr colormap to determine colors
cm = plt.get_cmap("PuOr")
offset = max(abs(node_color_list-valuecenter))
vmax = valuecenter + offset
vmin = valuecenter - offset
else:
cm = plt.get_cmap("magma")
self._plotting(drawing,edgecolor,edgealpha,linewidth,len(coords[0])==3,c=node_color_list,alpha=alpha*nodealpha,
edgecolors='none',s=nodesize,marker=nodemarker,zorder=2,cmap=cm,vmin=vmin,vmax=vmax)
else:
self._plotting(drawing,edgecolor,edgealpha,linewidth,len(coords[0])==3,c=nodecolor,alpha=alpha*nodealpha,
edgecolors='none',s=nodesize,marker=nodemarker,zorder=2)
return drawing
def draw_groups(self,coords,groups,alpha=1.0,nodesize_list=[],linewidth=1,
nodealpha=1.0,edgealpha=0.01,edgecolor='k',nodemarker_list=[],node_color_list=[],nodeorder_list=[],axs=None,
fig=None,cm=None,angle=30,figsize=None):
"""
Standard drawing function when having multiple clusters
Parameters
----------
coords: a n-by-2 or n-by-3 array with coordinates for each node of the graph.
groups: list[list] or list, for the first case, each sublist represents a cluster
for the second case, list must have the same length as the number of nodes and
nodes with the number are in the same cluster
Optional parameters
------------------
alpha: float (1.0 by default)
the overall alpha scaling of the plot, [0,1]
nodealpha: float (1.0 by default)
the overall node alpha scaling of the plot, [0, 1]
edgealpha: float (1.0 by default)
the overall edge alpha scaling of the plot, [0, 1]
nodecolor_list: list of string or RGB ('r' by default)
edgecolor: string or RGB ('k' by default)
nodemarker_list: list of strings ('o' by default)
nodesize_list: list of floats (5.0 by default)
linewidth: float (1.0 by default)
axs,fig: None,None (default)
by default it will create a new figure, or this will plot in axs if not None.
cm: string or colormap object (None by default)
figsize: tuple (None by default)
angle: float (30 by default)
set initial view angle when drawing 3d
Returns
-------
A GraphDrawing object
"""
#when values are not provided, use tab20 or gist_ncar colormap to determine colors
number_of_colors = 1
l_initial_node_color_list = len(node_color_list)
l_initial_nodesize_list = len(nodesize_list)
l_initial_nodemarker_list = len(nodemarker_list)
l_initial_nodeorder_list = len(nodeorder_list)
if l_initial_node_color_list == 0:
node_color_list = np.zeros(self._num_vertices)
if l_initial_nodesize_list == 0:
nodesize_list = 25*np.ones(self._num_vertices)
if l_initial_nodemarker_list == 0:
nodemarker_list = 'o'
if l_initial_nodeorder_list == 0:
nodeorder_list = 2
groups = np.asarray(groups)
if groups.ndim == 1:
#convert 1-d group to a 2-d representation
grp_dict = defaultdict(list)
for idx,key in enumerate(groups):
grp_dict[key].append(idx)
groups = np.asarray(list(grp_dict.values()))
number_of_colors += len(groups)
#separate the color for different groups as far as we can
if l_initial_node_color_list == 0:
for i,g in enumerate(groups):
node_color_list[g] = (1+i)*1.0/(number_of_colors-1)
if number_of_colors <= 20:
cm = plt.get_cmap("tab20b")
else:
cm = plt.get_cmap("gist_ncar")
vmin = 0.0
vmax = 1.0
drawing = GraphDrawing(self,coords,ax=axs,figsize=figsize)
#m = ScalarMappable(norm=Normalize(vmin=vmin,vmax=vmax), cmap=cm)
#rgba_list = m.to_rgba(node_color_list,alpha=alpha*nodealpha)
self._plotting(drawing,edgecolor,edgealpha,linewidth,len(coords[0])==3,s=nodesize_list,marker=nodemarker_list,zorder=nodeorder_list,cmap=cm,vmin=vmin,vmax=vmax,alpha=alpha*nodealpha,edgecolors='none',c=node_color_list)
return drawing
"""
def draw_2d(self,pos,axs,cm,nodemarker='o',nodesize=5,edgealpha=0.01,linewidth=1,
node_color_list=None,edgecolor='k',nodecolor='r',node_list=None,nodelist_in=None,
nodelist_out=None,setalpha=1.0,nodealpha=1.0,use_values=False,vmin=0.0,vmax=1.0):
if use_values:
axs.scatter([p[0] for p in pos[nodelist_in]],[p[1] for p in pos[nodelist_in]],c=node_color_list[nodelist_in],
s=nodesize,marker=nodemarker,cmap=cm,norm=Normalize(vmin=vmin,vmax=vmax),alpha=setalpha,zorder=2)
axs.scatter([p[0] for p in pos[nodelist_out]],[p[1] for p in pos[nodelist_out]],c=node_color_list[nodelist_out],
s=nodesize,marker=nodemarker,cmap=cm,norm=Normalize(vmin=vmin,vmax=vmax),alpha=nodealpha,zorder=2)
else:
if node_color_list is not None:
axs.scatter([p[0] for p in pos],[p[1] for p in pos],c=node_color_list,s=nodesize,marker=nodemarker,
cmap=cm,norm=Normalize(vmin=vmin,vmax=vmax),zorder=2)
else:
axs.scatter([p[0] for p in pos],[p[1] for p in pos],c=nodecolor,s=nodesize,marker=nodemarker,zorder=2)
node_list = range(self._num_vertices) if node_list is None else node_list
edge_pos = []
for i in node_list:
self._push_edges_for_node(i,self.aj[self.ai[i]:self.ai[i+1]],pos,edge_pos)
edge_pos = np.asarray(edge_pos)
edge_collection = LineCollection(edge_pos,colors=to_rgba(edgecolor,edgealpha),linewidths=linewidth)
#make sure edges are at the bottom
edge_collection.set_zorder(1)
axs.add_collection(edge_collection)
axs.autoscale()
def draw_3d(self,pos,axs,cm,nodemarker='o',nodesize=5,edgealpha=0.01,linewidth=1,
node_color_list=None,angle=30,edgecolor='k',nodecolor='r',node_list=None,
nodelist_in=None,nodelist_out=None,setalpha=1.0,nodealpha=1.0,use_values=False,vmin=0.0,vmax=1.0):
if use_values:
axs.scatter([p[0] for p in pos[nodelist_in]],[p[1] for p in pos[nodelist_in]],[p[2] for p in pos[nodelist_in]],c=node_color_list[nodelist_in],
s=nodesize,marker=nodemarker,cmap=cm,norm=Normalize(vmin=vmin,vmax=vmax),zorder=2,alpha=setalpha)
axs.scatter([p[0] for p in pos[nodelist_out]],[p[1] for p in pos[nodelist_out]],[p[2] for p in pos[nodelist_out]],c=node_color_list[nodelist_out],
s=nodesize,marker=nodemarker,cmap=cm,norm=Normalize(vmin=vmin,vmax=vmax),zorder=2,alpha=nodealpha)
else:
if node_color_list is not None:
axs.scatter([p[0] for p in pos],[p[1] for p in pos],[p[2] for p in pos],c=node_color_list,
s=nodesize,marker=nodemarker,cmap=cm,norm=Normalize(vmin=vmin,vmax=vmax),zorder=2)
else:
axs.scatter([p[0] for p in pos],[p[1] for p in pos],[p[2] for p in pos],c=nodecolor,
s=nodesize,marker=nodemarker,zorder=2)
node_list = range(self._num_vertices) if node_list is None else node_list
edge_pos = []
for i in node_list:
self._push_edges_for_node(i,self.aj[self.ai[i]:self.ai[i+1]],pos,edge_pos)
edge_pos = np.asarray(edge_pos)
edge_collection = Line3DCollection(edge_pos,colors=to_rgba(edgecolor,edgealpha),linewidths=linewidth)
#make sure edges are at the bottom
edge_collection.set_zorder(1)
axs.add_collection(edge_collection)
axs.autoscale()
# Set the initial view
axs.view_init(30, angle)
"""
|
[
"networkx.from_scipy_sparse_matrix",
"numpy.sum",
"pandas.read_csv",
"numpy.ones",
"collections.defaultdict",
"scipy.sparse.csgraph.connected_components",
"networkx.adjacency_matrix",
"collections.Counter",
"multiprocessing.RawArray",
"matplotlib.pyplot.get_cmap",
"numpy.frombuffer",
"numpy.asarray",
"networkx.read_graphml",
"scipy.sparse.csr_matrix",
"numpy.copyto",
"networkx.read_gml",
"networkx.core_number",
"networkx.number_of_nodes",
"numpy.dtype",
"numpy.zeros",
"numpy.array",
"networkx.biconnected_components",
"numpy.array_equal",
"warnings.warn",
"numpy.sqrt"
] |
[((1065, 1102), 'multiprocessing.RawArray', 'mp.RawArray', (['ctypes.c_uint8', 'a.nbytes'], {}), '(ctypes.c_uint8, a.nbytes)\n', (1076, 1102), True, 'import multiprocessing as mp\n'), ((1155, 1171), 'numpy.copyto', 'np.copyto', (['sa', 'a'], {}), '(sa, a)\n', (1164, 1171), True, 'import numpy as np\n'), ((8946, 8967), 'networkx.number_of_nodes', 'nx.number_of_nodes', (['G'], {}), '(G)\n', (8964, 8967), True, 'import networkx as nx\n'), ((12204, 12233), 'numpy.array', 'np.array', (['source'], {'dtype': 'vtype'}), '(source, dtype=vtype)\n', (12212, 12233), True, 'import numpy as np\n'), ((12250, 12279), 'numpy.array', 'np.array', (['target'], {'dtype': 'vtype'}), '(target, dtype=vtype)\n', (12258, 12279), True, 'import numpy as np\n'), ((12297, 12331), 'numpy.array', 'np.array', (['weights'], {'dtype': 'np.double'}), '(weights, dtype=np.double)\n', (12305, 12331), True, 'import numpy as np\n'), ((14054, 14082), 'numpy.zeros', 'np.zeros', (['self._num_vertices'], {}), '(self._num_vertices)\n', (14062, 14082), True, 'import numpy as np\n'), ((14162, 14177), 'numpy.sqrt', 'np.sqrt', (['self.d'], {}), '(self.d)\n', (14169, 14177), True, 'import numpy as np\n'), ((14201, 14217), 'numpy.sqrt', 'np.sqrt', (['self.dn'], {}), '(self.dn)\n', (14208, 14217), True, 'import numpy as np\n'), ((14239, 14253), 'numpy.sum', 'np.sum', (['self.d'], {}), '(self.d)\n', (14245, 14253), True, 'import numpy as np\n'), ((15387, 15501), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['(self.adjacency_matrix.data, self.aj, self.ai)'], {'shape': '(self._num_vertices, self._num_vertices)'}), '((self.adjacency_matrix.data, self.aj, self.ai), shape=(self.\n _num_vertices, self._num_vertices))\n', (15400, 15501), True, 'from scipy import sparse as sp\n'), ((16909, 16976), 'scipy.sparse.csgraph.connected_components', 'csgraph.connected_components', (['self.adjacency_matrix'], {'directed': '(False)'}), '(self.adjacency_matrix, directed=False)\n', (16937, 16976), False, 'from scipy.sparse import csgraph\n'), ((18481, 18566), 'warnings.warn', 'warnings.warn', (['"""Warning, biconnected_components is not efficiently implemented."""'], {}), "('Warning, biconnected_components is not efficiently implemented.'\n )\n", (18494, 18566), False, 'import warnings\n'), ((18578, 18628), 'networkx.from_scipy_sparse_matrix', 'nx.from_scipy_sparse_matrix', (['self.adjacency_matrix'], {}), '(self.adjacency_matrix)\n', (18605, 18628), True, 'import networkx as nx\n'), ((19317, 19386), 'warnings.warn', 'warnings.warn', (['"""Warning, core_number is not efficiently implemented."""'], {}), "('Warning, core_number is not efficiently implemented.')\n", (19330, 19386), False, 'import warnings\n'), ((19403, 19453), 'networkx.from_scipy_sparse_matrix', 'nx.from_scipy_sparse_matrix', (['self.adjacency_matrix'], {}), '(self.adjacency_matrix)\n', (19430, 19453), True, 'import networkx as nx\n'), ((19483, 19503), 'networkx.core_number', 'nx.core_number', (['g_nx'], {}), '(g_nx)\n', (19497, 19503), True, 'import networkx as nx\n'), ((30747, 30765), 'numpy.asarray', 'np.asarray', (['groups'], {}), '(groups)\n', (30757, 30765), True, 'import numpy as np\n'), ((809, 842), 'numpy.frombuffer', 'np.frombuffer', (['sabuf'], {'dtype': 'dtype'}), '(sabuf, dtype=dtype)\n', (822, 842), True, 'import numpy as np\n'), ((4155, 4188), 'numpy.array_equal', 'np.array_equal', (['self.ai', 'other.ai'], {}), '(self.ai, other.ai)\n', (4169, 4188), True, 'import numpy as np\n'), ((4192, 4225), 'numpy.array_equal', 'np.array_equal', (['self.aj', 'other.aj'], {}), '(self.aj, other.aj)\n', (4206, 4225), True, 'import numpy as np\n'), ((4229, 4300), 'numpy.array_equal', 'np.array_equal', (['self.adjacency_matrix.data', 'other.adjacency_matrix.data'], {}), '(self.adjacency_matrix.data, other.adjacency_matrix.data)\n', (4243, 4300), True, 'import numpy as np\n'), ((18663, 18694), 'networkx.biconnected_components', 'nx.biconnected_components', (['g_nx'], {}), '(g_nx)\n', (18688, 18694), True, 'import networkx as nx\n'), ((20386, 20414), 'numpy.zeros', 'np.zeros', (['self._num_vertices'], {}), '(self._num_vertices)\n', (20394, 20414), True, 'import numpy as np\n'), ((21360, 21389), 'collections.Counter', 'cole.Counter', (['self.components'], {}), '(self.components)\n', (21372, 21389), True, 'import collections as cole\n'), ((22265, 22285), 'numpy.dtype', 'np.dtype', (['self.ai[0]'], {}), '(self.ai[0])\n', (22273, 22285), True, 'import numpy as np\n'), ((22369, 22389), 'numpy.dtype', 'np.dtype', (['self.aj[0]'], {}), '(self.aj[0])\n', (22377, 22389), True, 'import numpy as np\n'), ((27068, 27086), 'numpy.asarray', 'np.asarray', (['values'], {}), '(values)\n', (27078, 27086), True, 'import numpy as np\n'), ((30438, 30466), 'numpy.zeros', 'np.zeros', (['self._num_vertices'], {}), '(self._num_vertices)\n', (30446, 30466), True, 'import numpy as np\n'), ((30873, 30890), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (30884, 30890), False, 'from collections import defaultdict\n'), ((31347, 31369), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""tab20b"""'], {}), "('tab20b')\n", (31359, 31369), True, 'import matplotlib.pyplot as plt\n'), ((31401, 31426), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""gist_ncar"""'], {}), "('gist_ncar')\n", (31413, 31426), True, 'import matplotlib.pyplot as plt\n'), ((5978, 6053), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'header': 'headerrow', 'delim_whitespace': 'remove_whitespace'}), '(filename, header=headerrow, delim_whitespace=remove_whitespace)\n', (5989, 6053), True, 'import pandas as pd\n'), ((6093, 6188), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': 'separator', 'header': 'headerrow', 'delim_whitespace': 'remove_whitespace'}), '(filename, sep=separator, header=headerrow, delim_whitespace=\n remove_whitespace)\n', (6104, 6188), True, 'import pandas as pd\n'), ((6421, 6445), 'numpy.ones', 'np.ones', (['source.shape[0]'], {}), '(source.shape[0])\n', (6428, 6445), True, 'import numpy as np\n'), ((6953, 7061), 'warnings.warn', 'warnings.warn', (['"""Loading a gml is not efficient, we suggest using an edgelist format for this API."""'], {}), "(\n 'Loading a gml is not efficient, we suggest using an edgelist format for this API.'\n )\n", (6966, 7061), False, 'import warnings\n'), ((7217, 7238), 'networkx.number_of_nodes', 'nx.number_of_nodes', (['G'], {}), '(G)\n', (7235, 7238), True, 'import networkx as nx\n'), ((8875, 8897), 'networkx.adjacency_matrix', 'nx.adjacency_matrix', (['G'], {}), '(G)\n', (8894, 8897), True, 'import networkx as nx\n'), ((27376, 27392), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['cm'], {}), '(cm)\n', (27388, 27392), True, 'import matplotlib.pyplot as plt\n'), ((30539, 30566), 'numpy.ones', 'np.ones', (['self._num_vertices'], {}), '(self._num_vertices)\n', (30546, 30566), True, 'import numpy as np\n'), ((7289, 7401), 'warnings.warn', 'warnings.warn', (['"""Loading a graphml is not efficient, we suggest using an edgelist format for this API."""'], {}), "(\n 'Loading a graphml is not efficient, we suggest using an edgelist format for this API.'\n )\n", (7302, 7401), False, 'import warnings\n'), ((7561, 7582), 'networkx.number_of_nodes', 'nx.number_of_nodes', (['G'], {}), '(G)\n', (7579, 7582), True, 'import networkx as nx\n'), ((27586, 27606), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""PuOr"""'], {}), "('PuOr')\n", (27598, 27606), True, 'import matplotlib.pyplot as plt\n'), ((27817, 27838), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""magma"""'], {}), "('magma')\n", (27829, 27838), True, 'import matplotlib.pyplot as plt\n'), ((7068, 7089), 'networkx.read_gml', 'nx.read_gml', (['filename'], {}), '(filename)\n', (7079, 7089), True, 'import networkx as nx\n'), ((7142, 7164), 'networkx.adjacency_matrix', 'nx.adjacency_matrix', (['G'], {}), '(G)\n', (7161, 7164), True, 'import networkx as nx\n'), ((7408, 7433), 'networkx.read_graphml', 'nx.read_graphml', (['filename'], {}), '(filename)\n', (7423, 7433), True, 'import networkx as nx\n'), ((7486, 7508), 'networkx.adjacency_matrix', 'nx.adjacency_matrix', (['G'], {}), '(G)\n', (7505, 7508), True, 'import networkx as nx\n')]
|
from aiida.parsers import Parser
from aiida.orm import Dict
from aiida.common import OutputParsingError
from aiida.common import exceptions
# See the LICENSE.txt and AUTHORS.txt files.
class STMOutputParsingError(OutputParsingError):
pass
#---------------------------
class STMParser(Parser):
"""
Parser for the output of the "plstm" program in the Siesta distribution.
"""
_version = "Dev-post1.1.1"
def parse(self, **kwargs):
"""
Receives in input a dictionary of retrieved nodes.
Does all the logic here.
"""
from aiida.engine import ExitCode
try:
output_folder = self.retrieved
except exceptions.NotExistent:
return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER
filename_plot = None
for element in output_folder.list_object_names():
if ".STM" in element:
filename_plot = element
if filename_plot is None:
return self.exit_codes.ERROR_OUTPUT_PLOT_MISSING
old_version = True
if "LDOS" in filename_plot:
old_version = False
if old_version and self.node.inputs.spin_option.value != "q":
self.node.logger.warning(
"Spin option different from 'q' was requested in "
"input, but the plstm version used for the calculation do not implement spin support. "
"The parsed STM data refers to the total charge option."
)
try:
plot_contents = output_folder.get_object_content(filename_plot)
except (IOError, OSError):
return self.exit_codes.ERROR_OUTPUT_PLOT_READ
# Save grid_X, grid_Y, and STM arrays in an ArrayData object
try:
stm_data = get_stm_data(plot_contents)
except (IOError, OSError):
return self.exit_codes.ERROR_CREATION_STM_ARRAY
self.out('stm_array', stm_data)
parser_info = {}
parser_info['parser_info'] = 'AiiDA STM(Siesta) Parser V. {}'.format(self._version)
parser_info['parser_warnings'] = []
parser_info['output_data_filename'] = filename_plot
# Possibly put here some parsed data from the stm.out file
# (but it is not very interesting)
result_dict = {}
# Add parser info dictionary
parsed_dict = dict(list(result_dict.items()) + list(parser_info.items()))
output_data = Dict(dict=parsed_dict)
self.out('output_parameters', output_data)
return ExitCode(0)
def get_stm_data(plot_contents):
"""
Parses the STM plot file to get an Array object with
X, Y, and Z arrays in the 'meshgrid'
setting, as in the example code:
import numpy as np
xlist = np.linspace(-3.0, 3.0, 3)
ylist = np.linspace(-3.0, 3.0, 4)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
X:
[[-3. 0. 3.]
[-3. 0. 3.]
[-3. 0. 3.]
[-3. 0. 3.]]
Y:
[[-3. -3. -3.]
[-1. -1. -1.]
[ 1. 1. 1.]
[ 3. 3. 3.]]
Z:
[[ 4.24264069 3. 4.24264069]
[ 3.16227766 1. 3.16227766]
[ 3.16227766 1. 3.16227766]
[ 4.24264069 3. 4.24264069]]
These can then be used in matplotlib to get a contour plot.
:param plot_contents: the contents of the *.STM file as a string
:return: `aiida.orm.ArrayData` instance representing the STM contour.
"""
import numpy as np
from itertools import groupby
from aiida.orm import ArrayData
# aiida.CH.STM or aiida.CC.STM...
data = plot_contents.split('\n')
data = [i.split() for i in data]
# The data in the file is organized in "lines" parallel to the Y axes
# (that is, for constant X) separated by blank lines.
# In the following we use the 'groupby' function to get at the individual
# blocks one by one, and set the appropriate arrays.
# I am not sure about the mechanics of groupby,
# so repeat
xx = [] #pylint: disable=invalid-name
yy = [] #pylint: disable=invalid-name
zz = [] #pylint: disable=invalid-name
#
# Function to separate the blocks
h = lambda x: len(x) == 0 #pylint: disable=invalid-name
#
for k, v in groupby(data, h):
if not k:
xx.append([i[0] for i in v])
for k, v in groupby(data, h):
if not k:
yy.append([i[1] for i in v])
for k, v in groupby(data, h):
if not k:
zz.append([i[2] for i in v])
# Now, transpose, since x runs fastest in our fortran code,
# the opposite convention of the meshgrid paradigm.
arrayx = np.array(xx, dtype=float).transpose()
arrayy = np.array(yy, dtype=float).transpose()
arrayz = np.array(zz, dtype=float).transpose()
arraydata = ArrayData()
arraydata.set_array('grid_X', np.array(arrayx))
arraydata.set_array('grid_Y', np.array(arrayy))
arraydata.set_array('STM', np.array(arrayz))
return arraydata
|
[
"aiida.orm.Dict",
"numpy.array",
"itertools.groupby",
"aiida.orm.ArrayData",
"aiida.engine.ExitCode"
] |
[((4255, 4271), 'itertools.groupby', 'groupby', (['data', 'h'], {}), '(data, h)\n', (4262, 4271), False, 'from itertools import groupby\n'), ((4348, 4364), 'itertools.groupby', 'groupby', (['data', 'h'], {}), '(data, h)\n', (4355, 4364), False, 'from itertools import groupby\n'), ((4441, 4457), 'itertools.groupby', 'groupby', (['data', 'h'], {}), '(data, h)\n', (4448, 4457), False, 'from itertools import groupby\n'), ((4810, 4821), 'aiida.orm.ArrayData', 'ArrayData', ([], {}), '()\n', (4819, 4821), False, 'from aiida.orm import ArrayData\n'), ((2450, 2472), 'aiida.orm.Dict', 'Dict', ([], {'dict': 'parsed_dict'}), '(dict=parsed_dict)\n', (2454, 2472), False, 'from aiida.orm import Dict\n'), ((2540, 2551), 'aiida.engine.ExitCode', 'ExitCode', (['(0)'], {}), '(0)\n', (2548, 2551), False, 'from aiida.engine import ExitCode\n'), ((4856, 4872), 'numpy.array', 'np.array', (['arrayx'], {}), '(arrayx)\n', (4864, 4872), True, 'import numpy as np\n'), ((4908, 4924), 'numpy.array', 'np.array', (['arrayy'], {}), '(arrayy)\n', (4916, 4924), True, 'import numpy as np\n'), ((4957, 4973), 'numpy.array', 'np.array', (['arrayz'], {}), '(arrayz)\n', (4965, 4973), True, 'import numpy as np\n'), ((4653, 4678), 'numpy.array', 'np.array', (['xx'], {'dtype': 'float'}), '(xx, dtype=float)\n', (4661, 4678), True, 'import numpy as np\n'), ((4704, 4729), 'numpy.array', 'np.array', (['yy'], {'dtype': 'float'}), '(yy, dtype=float)\n', (4712, 4729), True, 'import numpy as np\n'), ((4755, 4780), 'numpy.array', 'np.array', (['zz'], {'dtype': 'float'}), '(zz, dtype=float)\n', (4763, 4780), True, 'import numpy as np\n')]
|
"""
Noteworthy util functions
1. bandpass_default: default bandpass filter
2. phaseT: calculate phase time series
3. ampT: calculate amplitude time series
4. findpt - find peaks and troughs of oscillations
* _removeboundaryextrema - ignore peaks and troughs along the edge of the signal
5. f_psd - calculate PSD with one of a few methods
This library contains oscillatory metrics
1. inter_peak_interval - calculate distribution of period lengths of an oscillation
1b estimate_periods - use both the peak and trough intervals to estimate the period
2. peak_voltage - calculate distribution of extrema voltage values
3. bandpow - calculate the power in a frequency band
4. amplitude_variance - calculate variance in the oscillation amplitude
5. frequency_variance - calculate variance in the oscillation frequency
6. lagged coherence - measure of rhythmicity in Fransen et al. 2015
7. oscdetect_ampth - identify periods of oscillations (bursts) in the data using raw voltage thresholds
7a oscdetect_thresh - Detect oscillations using method in Feingold 2015
7b oscdetect_magnorm - Detect oscillations using normalized magnitude of band to broadband
7c signal_to_bursts - extract burst periods from a signal using 1 chosen oscdetect method
7d oscdetect_whitten - extract oscillations using the method described in Whitten et al. 2011
8 bursts_count - count # of bursts
8a bursts_durations - distribution of burst durations
8b bursts_fraction - fraction of time oscillating
9. wfpha - estimate phase of an oscillation using a waveform-based approach
10. slope - calculate slope of the power spectrum
"""
from __future__ import division
import numpy as np
from scipy import signal
import scipy as sp
import math
from sklearn import linear_model
import matplotlib.pyplot as plt
def bandpass_default(x, f_range, Fs, rmv_edge = True, w = 3, plot_frequency_response = False, Ntaps = None):
"""
Default bandpass filter
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest
Fs : float
The sampling rate
w : float
Length of filter order, in cycles. Filter order = ceil(Fs * w / f_range[0])
rmv_edge : bool
if True, remove edge artifacts
plot_frequency_response : bool
if True, plot the frequency response of the filter
Ntaps : int
Length of filter; overrides 'w' parameter.
MUST BE ODD. Or value is increased by 1.
Returns
-------
x_filt : array-like 1d
filtered time series
taps : array-like 1d
filter kernel
"""
# Default Ntaps as w if not provided
if Ntaps is None:
Ntaps = np.ceil(Fs*w/f_range[0])
# Force Ntaps to be odd
if Ntaps % 2 == 0:
Ntaps = Ntaps + 1
taps = sp.signal.firwin(Ntaps, np.array(f_range) / (Fs/2.), pass_zero=False)
# Apply filter
x_filt = np.convolve(taps,x,'same')
# Plot frequency response
if plot_frequency_response:
w, h = signal.freqz(taps)
import matplotlib.pyplot as plt
plt.figure(figsize=(10,5))
plt.subplot(1,2,2)
plt.title('Kernel')
plt.plot(taps)
plt.subplot(1,2,1)
plt.plot(w*Fs/(2.*np.pi), 20 * np.log10(abs(h)), 'b')
plt.title('Frequency response')
plt.ylabel('Attenuation (dB)', color='b')
plt.xlabel('Frequency (Hz)')
# Remove edge artifacts
N_rmv = int(Ntaps/2.)
if rmv_edge:
return x_filt[N_rmv:-N_rmv], Ntaps
else:
return x_filt, taps
def notch_default(x, cf, bw, Fs, order = 3):
nyq_rate = Fs / 2.
f_range = [cf - bw / 2., cf + bw / 2.]
Wn = (f_range[0] / nyq_rate, f_range[1] / nyq_rate)
b, a = sp.signal.butter(order, Wn, 'bandstop')
return sp.signal.filtfilt(b, a, x)
def phaseT(x, frange, Fs, rmv_edge = False, filter_fn=None, filter_kwargs=None):
"""
Calculate the phase and amplitude time series
Parameters
----------
x : array-like, 1d
time series
frange : (low, high), Hz
The frequency filtering range
Fs : float, Hz
The sampling rate
filter_fn : function
The filtering function, `filterfn(x, f_range, filter_kwargs)`
filter_kwargs : dict
Keyword parameters to pass to `filterfn(.)`
Returns
-------
pha : array-like, 1d
Time series of phase
"""
if filter_fn is None:
filter_fn = bandpass_default
if filter_kwargs is None:
filter_kwargs = {}
# Filter signal
xn, taps = filter_fn(x, frange, Fs, rmv_edge=rmv_edge, **filter_kwargs)
pha = np.angle(sp.signal.hilbert(xn))
return pha
def ampT(x, frange, Fs, rmv_edge = False, filter_fn=None, filter_kwargs=None, run_fasthilbert=False):
"""
Calculate the amplitude time series
Parameters
----------
x : array-like, 1d
time series
frange : (low, high), Hz
The frequency filtering range
Fs : float, Hz
The sampling rate
filter_fn : function
The filtering function, `filterfn(x, f_range, filter_kwargs)`
filter_kwargs : dict
Keyword parameters to pass to `filterfn(.)`
Returns
-------
amp : array-like, 1d
Time series of phase
"""
if filter_fn is None:
filter_fn = bandpass_default
if filter_kwargs is None:
filter_kwargs = {}
# Filter signal
xn, taps = filter_fn(x, frange, Fs, rmv_edge=rmv_edge, **filter_kwargs)
if run_fasthilbert:
amp = np.abs(fasthilbert(xn))
else:
amp = np.abs(sp.signal.hilbert(xn))
return amp
def fasthilbert(x, axis=-1):
"""
Redefinition of scipy.signal.hilbert, which is very slow for some lengths
of the signal x. This version zero-pads the signal to the next power of 2
for speed.
"""
x = np.array(x)
N = x.shape[axis]
N2 = 2**(int(math.log(len(x), 2)) + 1)
Xf = np.fft.fft(x, N2, axis=axis)
h = np.zeros(N2)
h[0] = 1
h[1:(N2 + 1) // 2] = 2
x = np.fft.ifft(Xf * h, axis=axis)
return x[:N]
def findpt(x, f_range, Fs, boundary = None, forcestart = 'peak',
filter_fn = bandpass_default, filter_kwargs = {}):
"""
Calculate peaks and troughs over time series
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest, used to find
zerocrossings of the oscillation
Fs : float
The sampling rate (default = 1000Hz)
boundary : int
distance from edge of recording that an extrema must be in order to be
accepted (in number of samples)
forcestart : str or None
if 'peak', then force the output to begin with a peak and end in a trough
if 'trough', then force the output to begin with a trough and end in peak
if None, force nothing
filter_fn : filter function with required inputs (x, f_range, Fs, rmv_edge)
function to use to filter original time series, x
filter_kwargs : dict
keyword arguments to the filter_fn
Returns
-------
Ps : array-like 1d
indices at which oscillatory peaks occur in the input signal x
Ts : array-like 1d
indices at which oscillatory troughs occur in the input signal x
"""
# Default boundary value as 1 cycle length
if boundary is None:
boundary = int(np.ceil(Fs/float(f_range[0])))
# Filter signal
xn, taps = filter_fn(x, f_range, Fs, rmv_edge=False, **filter_kwargs)
# Find zero crosses
def fzerofall(data):
pos = data > 0
return (pos[:-1] & ~pos[1:]).nonzero()[0]
def fzerorise(data):
pos = data < 0
return (pos[:-1] & ~pos[1:]).nonzero()[0]
zeroriseN = fzerorise(xn)
zerofallN = fzerofall(xn)
# Calculate # peaks and troughs
if zeroriseN[-1] > zerofallN[-1]:
P = len(zeroriseN) - 1
T = len(zerofallN)
else:
P = len(zeroriseN)
T = len(zerofallN) - 1
# Calculate peak samples
Ps = np.zeros(P, dtype=int)
for p in range(P):
# Calculate the sample range between the most recent zero rise
# and the next zero fall
mrzerorise = zeroriseN[p]
nfzerofall = zerofallN[zerofallN > mrzerorise][0]
Ps[p] = np.argmax(x[mrzerorise:nfzerofall]) + mrzerorise
# Calculate trough samples
Ts = np.zeros(T, dtype=int)
for tr in range(T):
# Calculate the sample range between the most recent zero fall
# and the next zero rise
mrzerofall = zerofallN[tr]
nfzerorise = zeroriseN[zeroriseN > mrzerofall][0]
Ts[tr] = np.argmin(x[mrzerofall:nfzerorise]) + mrzerofall
if boundary > 0:
Ps = _removeboundaryextrema(x, Ps, boundary)
Ts = _removeboundaryextrema(x, Ts, boundary)
# Assure equal # of peaks and troughs by starting with a peak and ending with a trough
if forcestart == 'peak':
if Ps[0] > Ts[0]:
Ts = Ts[1:]
if Ps[-1] > Ts[-1]:
Ps = Ps[:-1]
elif forcestart == 'trough':
if Ts[0] > Ps[0]:
Ps = Ps[1:]
if Ts[-1] > Ps[-1]:
Ts = Ts[:-1]
elif forcestart is None:
pass
else:
raise ValueError('Parameter forcestart is invalid')
return Ps, Ts
def f_psd(x, Fs, method,
Hzmed=0, welch_params={'window':'hanning','nperseg':1000,'noverlap':None}):
'''
Calculate the power spectrum of a signal
Parameters
----------
x : array
temporal signal
Fs : integer
sampling rate
method : str in ['fftmed','welch']
Method for calculating PSD
Hzmed : float
relevant if method == 'fftmed'
Frequency width of the median filter
welch_params : dict
relevant if method == 'welch'
Parameters to sp.signal.welch
Returns
-------
f : array
frequencies corresponding to the PSD output
psd : array
power spectrum
'''
if method == 'fftmed':
# Calculate frequencies
N = len(x)
f = np.arange(0,Fs/2,Fs/N)
# Calculate PSD
rawfft = np.fft.fft(x)
psd = np.abs(rawfft[:len(f)])**2
# Median filter
if Hzmed > 0:
sampmed = np.argmin(np.abs(f-Hzmed/2.0))
psd = signal.medfilt(psd,sampmed*2+1)
elif method == 'welch':
f, psd = sp.signal.welch(x, fs=Fs, **welch_params)
else:
raise ValueError('input for PSD method not recognized')
return f, psd
def _removeboundaryextrema(x, Es, boundaryS):
"""
Remove extrema close to the boundary of the recording
Parameters
----------
x : array-like 1d
voltage time series
Es : array-like 1d
time points of oscillatory peaks or troughs
boundaryS : int
Number of samples around the boundary to reject extrema
Returns
-------
newEs : array-like 1d
extremas that are not too close to boundary
"""
# Calculate number of samples
nS = len(x)
# Reject extrema too close to boundary
SampLims = (boundaryS, nS-boundaryS)
E = len(Es)
todelete = []
for e in range(E):
if np.logical_or(Es[e]<SampLims[0],Es[e]>SampLims[1]):
todelete = np.append(todelete,e)
newEs = np.delete(Es,todelete)
return newEs
def inter_peak_interval(Ps):
"""
Find the distribution of the period durations of neural oscillations as in Hentsche EJN 2007 Fig2
Parameters
----------
Ps : array-like 1d
Arrays of extrema time points
Returns
-------
periods : array-like 1d
series of intervals between peaks
"""
return np.diff(Ps)
def estimate_period(x, f_range, Fs, returnPsTs = False):
"""
Estimate the length of the period (in samples) of an oscillatory process in signal x in the range f_range
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest, used to find
zerocrossings of the oscillation
Fs : float
The sampling rate (default = 1000Hz)
returnPsTs : boolean
if True, return peak and trough indices
Returns
-------
period : int
Estimate of period in samples
"""
# Calculate peaks and troughs
boundary = int(np.ceil(Fs/float(2*f_range[0])))
Ps, Ts = findpt(x, f_range, Fs, boundary = boundary)
# Calculate period
if len(Ps) >= len(Ts):
period = (Ps[-1] - Ps[0])/(len(Ps)-1)
else:
period = (Ts[-1] - Ts[0])/(len(Ts)-1)
if returnPsTs:
return period, Ps, Ts
else:
return period
def peak_voltage(x, Ps):
"""
Calculate the distribution of voltage of the extrema as in Hentsche EJN 2007 Fig2
Note that this function only returns data while the signal was identified to be in an oscillation,
using the default oscillation detector
Parameters
----------
x : array-like 1d
voltage time series
Ps : array-like 1d
Arrays of extrema time points
Returns
-------
peak_voltages : array-like 1d
distribution of the peak voltage values
"""
return x[Ps]
def bandpow(x, Fs, flim):
'''
Calculate the power in a frequency range
Parameters
----------
x : array-like 1d
voltage time series
Fs : float
sampling rate
flim : (lo, hi)
limits of frequency range
Returns
-------
pow : float
power in the range
'''
# Calculate PSD
N = len(x)
f = np.arange(0,Fs/2,Fs/N)
rawfft = np.fft.fft(x)
psd = np.abs(rawfft[:len(f)])**2
# Calculate power
fidx = np.logical_and(f>=flim[0],f<=flim[1])
return np.sum(psd[fidx])/np.float(len(f)*2)
def amplitude_variance(x, Fs, flim):
'''
Calculate the variance in the oscillation amplitude
Parameters
----------
x : array-like 1d
voltage time series
Fs : float
sampling rate
flim : (lo, hi)
limits of frequency range
Returns
-------
pow : float
power in the range
'''
# Calculate amplitude
amp = ampT(x, flim, Fs)
return np.var(amp)
def frequency_variance(x, Fs, flim):
'''
Calculate the variance in the instantaneous frequency
NOTE: This function assumes monotonic phase, so a phase slip will be processed as a very high frequency
Parameters
----------
x : array-like 1d
voltage time series
Fs : float
sampling rate
flim : (lo, hi)
limits of frequency range
Returns
-------
pow : float
power in the range
'''
# Calculate amplitude
pha = phaseT(x, flim, Fs)
phadiff = np.diff(pha)
phadiff[phadiff<0] = phadiff[phadiff<0]+2*np.pi
inst_freq = Fs*phadiff/(2*np.pi)
return np.var(inst_freq)
def lagged_coherence(x, frange, Fs, N_cycles=3, f_step=1, return_spectrum=False):
"""
Quantify the rhythmicity of a time series using lagged coherence.
Return the mean lagged coherence in the frequency range as an
estimate of rhythmicity.
As in Fransen et al. 2015
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest, used to find
zerocrossings of the oscillation
Fs : float
The sampling rate (default = 1000Hz)
N_cycles : float
Number of cycles of the frequency of interest to be used in lagged coherence calculate
f_step : float, Hz
step size to calculate lagged coherence in the frequency range.
return_spectrum : bool
if True, return the lagged coherence for all frequency values. otherwise, only return mean
fourier_or_wavelet : string {'fourier', 'wavelet'}
NOT IMPLEMENTED. ONLY FOURIER
method for estimating phase.
fourier: calculate fourier coefficients for each time window. hanning tpaer.
wavelet: multiply each window by a N-cycle wavelet
Returns
-------
rhythmicity : float
mean lagged coherence value in the frequency range of interest
"""
# Identify Fourier components of interest
freqs = np.arange(frange[0],frange[1]+f_step,f_step)
# Calculate lagged coherence for each frequency
F = len(freqs)
lcs = np.zeros(F)
for i,f in enumerate(freqs):
lcs[i] = _lagged_coherence_1freq(x, f, Fs, N_cycles=N_cycles, f_step=f_step)
if return_spectrum:
return lcs
else:
return np.mean(lcs)
def _lagged_coherence_1freq(x, f, Fs, N_cycles=3, f_step=1):
"""Calculate lagged coherence of x at frequency f using the hanning-taper FFT method"""
Nsamp = int(np.ceil(N_cycles*Fs / f))
# For each N-cycle chunk, calculate phase
chunks = _nonoverlapping_chunks(x,Nsamp)
C = len(chunks)
hann_window = signal.hanning(Nsamp)
fourier_f = np.fft.fftfreq(Nsamp,1/float(Fs))
fourier_f_idx = _arg_closest_value(fourier_f,f)
fourier_coefsoi = np.zeros(C,dtype=complex)
for i2, c in enumerate(chunks):
fourier_coef = np.fft.fft(c*hann_window)
fourier_coefsoi[i2] = fourier_coef[fourier_f_idx]
lcs_num = 0
for i2 in range(C-1):
lcs_num += fourier_coefsoi[i2]*np.conj(fourier_coefsoi[i2+1])
lcs_denom = np.sqrt(np.sum(np.abs(fourier_coefsoi[:-1])**2)*np.sum(np.abs(fourier_coefsoi[1:])**2))
return np.abs(lcs_num/lcs_denom)
def _nonoverlapping_chunks(x, N):
"""Split x into nonoverlapping chunks of length N"""
Nchunks = int(np.floor(len(x)/float(N)))
chunks = np.reshape(x[:int(Nchunks*N)],(Nchunks,int(N)))
return chunks
def _arg_closest_value(x, val):
"""Find the index of closest value in x to val"""
return np.argmin(np.abs(x-val))
def oscdetect_ampth(x, f_range, Fs, thresh_hi, thresh_lo,
min_osc_periods = 3, filter_fn = bandpass_default, filter_kwargs = {}, return_amp=False):
"""
Detect the time range of oscillations in a certain frequency band.
* METHOD: Set 2 VOLTAGE thresholds.
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest
Fs : float
The sampling rate
thresh_hi : float
minimum magnitude-normalized value in order to force an oscillatory period
thresh_lo : float
minimum magnitude-normalized value to be included in an existing oscillatory period
magnitude : string in ('power', 'amplitude')
metric of magnitude used for thresholding
baseline : string in ('median', 'mean')
metric to normalize magnitude used for thresholding
min_osc_periods : float
minimum length of an oscillatory period in terms of the period length of f_range[0]
filter_fn : filter function with required inputs (x, f_range, Fs, rmv_edge)
function to use to filter original time series, x
filter_kwargs : dict
keyword arguments to the filter_fn
Returns
-------
isosc : array-like 1d
binary time series. 1 = in oscillation; 0 = not in oscillation
taps : array-like 1d
filter kernel
"""
# Filter signal
x_filt, taps = filter_fn(x, f_range, Fs, rmv_edge=False, **filter_kwargs)
# Quantify magnitude of the signal
x_amplitude = np.abs(sp.signal.hilbert(x_filt))
# Identify time periods of oscillation
isosc = _2threshold_split(x_amplitude, thresh_hi, thresh_lo)
# Remove short time periods of oscillation
min_period_length = int(np.ceil(min_osc_periods*Fs/f_range[0]))
isosc_noshort = _rmv_short_periods(isosc, min_period_length)
if return_amp:
return isosc_noshort, taps, x_amplitude
else:
return isosc_noshort, taps
def _2threshold_split(x, thresh_hi, thresh_lo):
"""Identify periods of a time series that are above thresh_lo and have at least one value above thresh_hi"""
# Find all values above thresh_hi
x[[0,-1]] = 0 # To avoid bug in later loop, do not allow first or last index to start off as 1
idx_over_hi = np.where(x >= thresh_hi)[0]
# Initialize values in identified period
positive = np.zeros(len(x))
positive[idx_over_hi] = 1
# Iteratively test if a value is above thresh_lo if it is not currently in an identified period
lenx = len(x)
for i in idx_over_hi:
j_down = i-1
if positive[j_down] == 0:
j_down_done = False
while j_down_done is False:
if x[j_down] >= thresh_lo:
positive[j_down] = 1
j_down -= 1
if j_down < 0:
j_down_done = True
else:
j_down_done = True
j_up = i+1
if positive[j_up] == 0:
j_up_done = False
while j_up_done is False:
if x[j_up] >= thresh_lo:
positive[j_up] = 1
j_up += 1
if j_up >= lenx:
j_up_done = True
else:
j_up_done = True
return positive
def _rmv_short_periods(x, N):
"""Remove periods that ==1 for less than N samples"""
if np.sum(x)==0:
return x
osc_changes = np.diff(1*x)
osc_starts = np.where(osc_changes==1)[0]
osc_ends = np.where(osc_changes==-1)[0]
if len(osc_starts)==0:
osc_starts = [0]
if len(osc_ends)==0:
osc_ends = [len(osc_changes)]
if osc_ends[0] < osc_starts[0]:
osc_starts = np.insert(osc_starts, 0, 0)
if osc_ends[-1] < osc_starts[-1]:
osc_ends = np.append(osc_ends, len(osc_changes))
osc_length = osc_ends - osc_starts
osc_starts_long = osc_starts[osc_length>=N]
osc_ends_long = osc_ends[osc_length>=N]
is_osc = np.zeros(len(x))
for osc in range(len(osc_starts_long)):
is_osc[osc_starts_long[osc]:osc_ends_long[osc]] = 1
return is_osc
def oscdetect_thresh(x, f_range, Fs, thresh_hi = 3, thresh_lo = 1.5, magnitude = 'power', baseline = 'median',
min_osc_periods = 3, filter_fn = bandpass_default, filter_kwargs = {}, return_normmag=False):
"""
Detect the time range of oscillations in a certain frequency band.
Based on Feingold 2015 PNAS Fig. 4
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest
Fs : float
The sampling rate
thresh_hi : float
minimum magnitude-normalized value in order to force an oscillatory period
thresh_lo : float
minimum magnitude-normalized value to be included in an existing oscillatory period
magnitude : string in ('power', 'amplitude')
metric of magnitude used for thresholding
baseline : string in ('median', 'mean')
metric to normalize magnitude used for thresholding
min_osc_periods : float
minimum length of an oscillatory period in terms of the period length of f_range[0]
filter_fn : filter function with required inputs (x, f_range, Fs, rmv_edge)
function to use to filter original time series, x
filter_kwargs : dict
keyword arguments to the filter_fn
Returns
-------
isosc : array-like 1d
binary time series. 1 = in oscillation; 0 = not in oscillation
taps : array-like 1d
filter kernel
"""
# Filter signal
x_filt, taps = filter_fn(x, f_range, Fs, rmv_edge=False, **filter_kwargs)
# Quantify magnitude of the signal
## Calculate amplitude
x_amplitude = np.abs(sp.signal.hilbert(x_filt))
## Set magnitude as power or amplitude
if magnitude == 'power':
x_magnitude = x_amplitude**2
elif magnitude == 'amplitude':
x_magnitude = x_amplitude
else:
raise ValueError("Invalid 'magnitude' parameter")
# Calculate normalized magnitude
if baseline == 'median':
norm_mag = x_magnitude / np.median(x_magnitude)
elif baseline == 'mean':
norm_mag = x_magnitude / np.mean(x_magnitude)
else:
raise ValueError("Invalid 'baseline' parameter")
# Identify time periods of oscillation
isosc = _2threshold_split(norm_mag, thresh_hi, thresh_lo)
# Remove short time periods of oscillation
min_period_length = int(np.ceil(min_osc_periods*Fs/f_range[0]))
isosc_noshort = _rmv_short_periods(isosc, min_period_length)
if return_normmag:
return isosc_noshort, taps, norm_mag
else:
return isosc_noshort, taps
def oscdetect_magnorm(x, f_range, Fs, thresh_hi = .3, thresh_lo = .1, magnitude = 'power', thresh_bandpow_pc = 20,
min_osc_periods = 3, filter_fn = bandpass_default, filter_kwargs = {'w':7}):
"""
Detect the time range of oscillations in a certain frequency band.
Based on Feingold 2015 PNAS Fig. 4 except normalize the magnitude measure by the overall power or amplitude
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest
Fs : float
The sampling rate
thresh_hi : float
minimum magnitude fraction needed in order to force an oscillatory period
thresh_lo : float
minimum magnitude fraction needed to be included in an existing oscillatory period
magnitude : string in ('power', 'amplitude')
metric of magnitude used for thresholding
thresh_bandpow_pc : float (0 to 100)
percentile cutoff for
min_osc_periods : float
minimum length of an oscillatory period in terms of the period length of f_range[0]
filter_fn : filter function with required inputs (x, f_range, Fs, rmv_edge)
function to use to filter original time series, x
filter_kwargs : dict
keyword arguments to the filter_fn
Returns
-------
isosc : array-like 1d
binary time series. 1 = in oscillation; 0 = not in oscillation
taps : array-like 1d
filter kernel
"""
# Filter signal
x_filt, taps = filter_fn(x, f_range, Fs, rmv_edge=False, **filter_kwargs)
# Quantify magnitude of the signal
## Calculate amplitude
x_amplitude = np.abs(sp.signal.hilbert(x_filt))
## Calculate overall signal amplitude
## NOTE: I'm pretty sure this is right, not 100% sure
taps_env = np.abs(sp.signal.hilbert(taps)) # This is the amplitude of the filter
x_overallamplitude = np.abs(np.convolve(np.abs(x), taps_env, mode='same')) # The amplitude at a point in time is a measure of the neural activity with a decaying weight over time like that of the amplitude of the filter
## Set magnitude as power or amplitude
if magnitude == 'power':
frac_magnitude = (x_amplitude/x_overallamplitude)**2
elif magnitude == 'amplitude':
frac_magnitude = (x_amplitude/x_overallamplitude)
else:
raise ValueError("Invalid 'magnitude' parameter")
# Identify time periods of oscillation
isosc = _2threshold_split_magnorm(frac_magnitude, thresh_hi, thresh_lo, x_amplitude, thresh_bandpow_pc)
# Remove short time periods of oscillation
min_period_length = int(np.ceil(min_osc_periods*Fs/f_range[0]))
isosc_noshort = _rmv_short_periods(isosc, min_period_length)
return isosc_noshort, taps
def _2threshold_split_magnorm(frac_mag, thresh_hi, thresh_lo, band_mag, thresh_bandpow_pc):
"""Identify periods of a time series that are above thresh_lo and have at least one value above thresh_hi.
There is the additional requirement that the band magnitude must be above a chosen percentile threshold."""
# Find all values above thresh_hi
frac_mag[[0,-1]] = 0 # To avoid bug in later loop, do not allow first or last index to start off as 1
bandmagpc = np.percentile(band_mag,thresh_bandpow_pc)
idx_over_hi = np.where(np.logical_and(frac_mag >= thresh_hi, band_mag >= bandmagpc))[0]
if len(idx_over_hi) == 0:
raise ValueError('No oscillatory periods found. Change thresh_hi or bandmagpc parameters.')
# Initialize values in identified period
positive = np.zeros(len(frac_mag))
positive[idx_over_hi] = 1
# Iteratively test if a value is above thresh_lo if it is not currently in an identified period
lenx = len(frac_mag)
for i in idx_over_hi:
j_down = i-1
if positive[j_down] == 0:
j_down_done = False
while j_down_done is False:
if np.logical_and(frac_mag[j_down] >= thresh_lo,band_mag[j_down] >= bandmagpc):
positive[j_down] = 1
j_down -= 1
if j_down < 0:
j_down_done = True
else:
j_down_done = True
j_up = i+1
if positive[j_up] == 0:
j_up_done = False
while j_up_done is False:
if np.logical_and(frac_mag[j_up] >= thresh_lo,band_mag[j_up] >= bandmagpc):
positive[j_up] = 1
j_up += 1
if j_up >= lenx:
j_up_done = True
else:
j_up_done = True
return positive
def oscdetect_whitten(x, f_range, Fs, f_slope,
window_size_slope = 1000, window_size_spec = 1000,
filter_fn = bandpass_default, filter_kwargs = {},
return_powerts=False, percentile_thresh = .95,
plot_spectral_slope_fit = False, plot_powerts = False,
return_oscbounds = False):
"""
Detect the time range of oscillations in a certain frequency band.
Based on Whitten et al. 2011
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest
Fs : float
The sampling rate
f_slope : (low, high), Hz
Frequency range over which to estimate slope
window_size_slope : int
window size used when calculating power spectrum used to find baseline power (by fitting line)
window_size_spec : int
window size used when calculating power time series (spectrogram)
filter_fn : filter function with required inputs (x, f_range, Fs, rmv_edge)
function to use to filter original time series, x
filter_kwargs : dict
keyword arguments to the filter_fn
return_powerts : bool
if True, output the power time series and plots of psd and interpolation
percentile_thresh : int (0 to 1)
the probability of the chi-square distribution at which to cut off oscillation
plot_spectral_slope_fit : bool
if True, plot the linear fit in the power spectrum
plot_powerts : bool
if True, plot the power time series and original time series for the first 5000 samples
return_oscbounds : bool
if True, isntead of returning a boolean time series as the
Returns
-------
isosc : array-like 1d
binary time series. 1 = in oscillation; 0 = not in oscillation
if return_oscbounds is true: this is 2 lists with the start and end burst samples
"""
# Calculate power spectrum to find baseline power
welch_params={'window':'hanning','nperseg':window_size_slope,'noverlap':None}
f, psd = f_psd(x, Fs, 'welch', welch_params=welch_params)
# Calculate slope around frequency band
f_sampleslope = f[np.logical_or(np.logical_and(f>=f_slope[0][0],f<=f_slope[0][1]),
np.logical_and(f>=f_slope[1][0],f<=f_slope[1][1]))]
slope_val, fit_logf, fit_logpower = spectral_slope(f, psd, f_sampleslope = f_sampleslope)
# Confirm slope fit is reasonable
if plot_spectral_slope_fit:
plt.figure(figsize=(6,3))
plt.loglog(f,psd,'k-')
plt.loglog(10**fit_logf, 10**fit_logpower,'r--')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power (uV^2/Hz)')
# Intepolate 1/f over the oscillation period
fn_interp = sp.interpolate.interp1d(fit_logf, fit_logpower)
f_osc_log = np.log10(np.arange(f_range[0],f_range[1]+1))
p_interp_log = fn_interp(f_osc_log)
# Calculate power threshold
meanpower = 10**p_interp_log
powthresh = np.mean(sp.stats.chi2.ppf(percentile_thresh,2)*meanpower/2.)
# Calculate spectrogram and power time series
# Note that these spectral statistics are calculated using the 'psd' mode common to both 'spectrogram' and 'welch' in scipy.signal
f, t_spec, x_spec_pre = sp.signal.spectrogram(x, fs=Fs, window='hanning', nperseg=window_size_spec, noverlap=window_size_spec-1, mode='psd')
# pad spectrogram with 0s to match the original time series
t = np.arange(0,len(x)/float(Fs),1/float(Fs))
x_spec = np.zeros((len(f),len(t)))
tidx_start = np.where(np.abs(t-t_spec[0])<1/float(10*Fs))[0][0]
x_spec[:,tidx_start:tidx_start+len(t_spec)]=x_spec_pre
# Calculate instantaneous power
fidx_band = np.where(np.logical_and(f>=f_range[0],f<=f_range[1]))[0]
x_bandpow = np.mean(x_spec[fidx_band],axis=0)
# Visualize bandpower time series
if plot_powerts:
tmax = np.min((len(x_bandpow),5000))
samp_plt=range(0, tmax)
plt.figure(figsize=(10,4))
plt.subplot(2,1,1)
plt.plot(x[samp_plt],'k')
plt.ylabel('Voltage (uV)')
plt.subplot(2,1,2)
plt.semilogy(x_bandpow[samp_plt],'r')
plt.semilogy(range(tmax),[powthresh]*tmax,'k--')
plt.ylabel('Band power')
plt.xlabel('Time (samples)')
# Threshold power time series to find time periods of an oscillation
isosc = x_bandpow > powthresh
# Reject oscillations that are too short
min_burst_length = int(np.ceil(3 * Fs / float(f_range[1]))) # 3 cycles of fastest freq
isosc_noshort, osc_starts, osc_ends = _rmv_short_periods_whitten(isosc, min_burst_length)
if return_oscbounds:
if return_powerts:
return osc_starts, osc_ends, x_bandpow
return osc_starts, osc_ends
else:
if return_powerts:
return isosc_noshort, x_bandpow
return isosc_noshort
def _rmv_short_periods_whitten(x, N):
"""Remove periods that ==1 for less than N samples"""
if np.sum(x)==0:
return x
osc_changes = np.diff(1*x)
osc_starts = np.where(osc_changes==1)[0]
osc_ends = np.where(osc_changes==-1)[0]
if len(osc_starts)==0:
osc_starts = [0]
if len(osc_ends)==0:
osc_ends = [len(osc_changes)]
if osc_ends[0] < osc_starts[0]:
osc_starts = np.insert(osc_starts, 0, 0)
if osc_ends[-1] < osc_starts[-1]:
osc_ends = np.append(osc_ends, len(osc_changes))
osc_length = osc_ends - osc_starts
osc_starts_long = osc_starts[osc_length>=N]
osc_ends_long = osc_ends[osc_length>=N]
is_osc = np.zeros(len(x))
for osc in range(len(osc_starts_long)):
is_osc[osc_starts_long[osc]:osc_ends_long[osc]] = 1
return is_osc, osc_starts_long, osc_ends_long
def signal_to_bursts(x, f_range, Fs, burst_fn = None, burst_kwargs = None):
"""
Separate a signal into time periods of oscillatory bursts
Parameters
----------
x : array-like 1d
voltage time series
f_range : (low, high), Hz
frequency range for narrowband signal of interest
Fs : float
The sampling rate
burst_fn : burst detector function with required inputs (x, f_range, Fs, rmv_edge)
function to use to filter original time series, x
burst_kwargs : dict
keyword arguments to the burst_fn
Returns
-------
x_bursts : numpy array of array-like 1d
array of each bursting period in x
burst_filter : array-like 1d
filter kernel used in identifying bursts
"""
# Initialize burst detection parameters
if burst_fn is None:
burst_fn = oscdetect_thresh
if burst_kwargs is None:
burst_kwargs = {}
# Apply burst detection
isburst, burst_filter = burst_fn(x, f_range, Fs, **burst_kwargs)
# Confirm burst detection
if np.sum(isburst) == 0:
print('No bursts detected. Adjust burst detector settings or reject signal.')
return None, None
# Separate x into bursts
x_bursts = _binarytochunk(x, isburst)
return x_bursts, burst_filter
def _binarytochunk(x, binary_array):
"""Outputs chunks of x in which binary_array is continuously 1"""
# Find beginnings and ends of bursts
binary_diffs = np.diff(binary_array)
binary_diffs = np.insert(binary_diffs, 0, 0)
begin_bursts = np.where(binary_diffs == 1)[0]
end_bursts = np.where(binary_diffs == -1)[0]
# Identify if bursts lie at the beginning or end of recording
if begin_bursts[0] > end_bursts[0]:
begin_bursts = np.insert(begin_bursts, 0, 0)
if begin_bursts[-1] > end_bursts[-1]:
end_bursts = np.append(end_bursts, len(x))
# Make array of each burst
Nbursts = len(begin_bursts)
bursts = np.zeros(Nbursts, dtype=object)
for b in range(Nbursts):
bursts[b] = x[begin_bursts[b]:end_bursts[b]]
return bursts
def bursts_count(bursts_binary):
"""Calculate number of bursts based off the binary burst indicator"""
# Find beginnings and ends of bursts
if np.sum(bursts_binary)==0:
return 0
binary_diffs = np.diff(bursts_binary)
binary_diffs = np.insert(binary_diffs, 0, 0)
begin_bursts = np.where(binary_diffs == 1)[0]
end_bursts = np.where(binary_diffs == -1)[0]
if len(begin_bursts)==0:
begin_bursts = [0]
if len(end_bursts)==0:
end_bursts = [len(binary_diffs)]
# Identify if bursts lie at the beginning or end of recording
if begin_bursts[0] > end_bursts[0]:
begin_bursts = np.insert(begin_bursts, 0, 0)
return len(begin_bursts)
def bursts_fraction(bursts_binary):
"""Calculate fraction of time bursting"""
return np.mean(bursts_binary)
def bursts_durations(bursts_binary, Fs):
"""Calculate the duration of each burst"""
# Find beginnings and ends of bursts
if np.sum(bursts_binary)==0:
return 0
binary_diffs = np.diff(bursts_binary)
binary_diffs = np.insert(binary_diffs, 0, 0)
begin_bursts = np.where(binary_diffs == 1)[0]
end_bursts = np.where(binary_diffs == -1)[0]
if len(begin_bursts)==0:
begin_bursts = [0]
if len(end_bursts)==0:
end_bursts = [len(binary_diffs)]
# Identify if bursts lie at the beginning or end of recording
if begin_bursts[0] > end_bursts[0]:
begin_bursts = np.insert(begin_bursts, 0, 0)
if begin_bursts[-1] > end_bursts[-1]:
end_bursts = np.append(end_bursts, len(bursts_binary))
# Make array of each burst
Nbursts = len(begin_bursts)
lens = np.zeros(Nbursts, dtype=object)
for b in range(Nbursts):
lens[b] = end_bursts[b] - begin_bursts[b]
lens = lens/float(Fs)
return lens
def wfpha(x, Ps, Ts):
"""
Use peaks and troughs calculated with findpt to calculate an instantaneous
phase estimate over time
Parameters
----------
x : array-like 1d
voltage time series
Ps : array-like 1d
time points of oscillatory peaks
Ts : array-like 1d
time points of oscillatory troughs
Returns
-------
pha : array-like 1d
instantaneous phase
"""
# Initialize phase array
L = len(x)
pha = np.empty(L)
pha[:] = np.NAN
pha[Ps] = 0
pha[Ts] = -np.pi
# Interpolate to find all phases
marks = np.logical_not(np.isnan(pha))
t = np.arange(L)
marksT = t[marks]
M = len(marksT)
for m in range(M - 1):
idx1 = marksT[m]
idx2 = marksT[m + 1]
val1 = pha[idx1]
val2 = pha[idx2]
if val2 <= val1:
val2 = val2 + 2 * np.pi
phatemp = np.linspace(val1, val2, idx2 - idx1 + 1)
pha[idx1:idx2] = phatemp[:-1]
# Interpolate the boundaries with the same rate of change as the adjacent
# sections
idx = np.where(np.logical_not(np.isnan(pha)))[0][0]
val = pha[idx]
dval = pha[idx + 1] - val
startval = val - dval * idx
# .5 for nonambiguity in arange length
pha[:idx] = np.arange(startval, val - dval * .5, dval)
idx = np.where(np.logical_not(np.isnan(pha)))[0][-1]
val = pha[idx]
dval = val - pha[idx - 1]
dval = np.angle(np.exp(1j * dval)) # Trestrict dval to between -pi and pi
# .5 for nonambiguity in arange length
endval = val + dval * (len(pha) - idx - .5)
pha[idx:] = np.arange(val, endval, dval)
# Restrict phase between -pi and pi
pha = np.angle(np.exp(1j * pha))
return pha
def slope(f, psd, fslopelim = (80,200), flatten_thresh = 0):
'''
Calculate the slope of the power spectrum
Parameters
----------
f : array
frequencies corresponding to power spectrum
psd : array
power spectrum
fslopelim : 2-element list
frequency range to fit slope
flatten_thresh : float
See foof.utils
Returns
-------
slope : float
slope of psd
slopelineP : array
linear fit of the PSD in log-log space (includes information of offset)
slopelineF : array
frequency array corresponding to slopebyf
'''
fslopeidx = np.logical_and(f>=fslopelim[0],f<=fslopelim[1])
slopelineF = f[fslopeidx]
x = np.log10(slopelineF)
y = np.log10(psd[fslopeidx])
from sklearn import linear_model
lm = linear_model.RANSACRegressor(random_state=42)
lm.fit(x[:, np.newaxis], y)
slopelineP = lm.predict(x[:, np.newaxis])
psd_flat = y - slopelineP.flatten()
mask = (psd_flat / psd_flat.max()) < flatten_thresh
psd_flat[mask] = 0
slopes = lm.estimator_.coef_
slopes = slopes[0]
return slopes, slopelineP, slopelineF
def spectral_slope(f, psd, f_sampleslope = np.arange(80,200), flatten_thresh = 0):
'''
Calculate the slope of the power spectrum
NOTE:
This is an update to the 'slope' function that should be deprecated
Parameters
----------
f : array
frequencies corresponding to power spectrum
psd : array
power spectrum
fslopelim : 2-element list
frequency range to fit slope
flatten_thresh : float
See foof.utils
Returns
-------
slope_value : float
slope of psd (chi)
fit_logf : array
linear fit of the PSD in log-log space (includes information of offset)
fit_logpower : array
frequency array corresponding to slopebyf
'''
# Define frequency and power values to fit in log-log space
fit_logf = np.log10(f_sampleslope)
y = np.log10(psd[f_sampleslope.astype(int)])
# Fit a linear model
lm = linear_model.RANSACRegressor(random_state=42)
lm.fit(fit_logf[:, np.newaxis], y)
# Find the line of best fit using the provided frequencies
fit_logpower = lm.predict(fit_logf[:, np.newaxis])
psd_flat = y - fit_logpower.flatten()
mask = (psd_flat / psd_flat.max()) < flatten_thresh
psd_flat[mask] = 0
# Find the chi value
slope_value = lm.estimator_.coef_
slope_value = slope_value[0]
return slope_value, fit_logf, fit_logpower
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.loglog",
"numpy.abs",
"numpy.sum",
"scipy.signal.welch",
"numpy.argmax",
"numpy.empty",
"numpy.isnan",
"numpy.argmin",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.exp",
"scipy.interpolate.interp1d",
"numpy.convolve",
"numpy.fft.fft",
"scipy.signal.medfilt",
"numpy.insert",
"numpy.append",
"numpy.linspace",
"numpy.log10",
"matplotlib.pyplot.semilogy",
"numpy.var",
"scipy.signal.butter",
"numpy.fft.ifft",
"numpy.conj",
"sklearn.linear_model.RANSACRegressor",
"scipy.signal.hanning",
"numpy.ceil",
"numpy.median",
"scipy.stats.chi2.ppf",
"numpy.percentile",
"matplotlib.pyplot.ylabel",
"scipy.signal.freqz",
"numpy.delete",
"matplotlib.pyplot.subplot",
"scipy.signal.filtfilt",
"numpy.logical_and",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.diff",
"numpy.array",
"numpy.logical_or",
"scipy.signal.spectrogram",
"scipy.signal.hilbert",
"numpy.where",
"matplotlib.pyplot.xlabel"
] |
[((2967, 2995), 'numpy.convolve', 'np.convolve', (['taps', 'x', '"""same"""'], {}), "(taps, x, 'same')\n", (2978, 2995), True, 'import numpy as np\n'), ((3815, 3854), 'scipy.signal.butter', 'sp.signal.butter', (['order', 'Wn', '"""bandstop"""'], {}), "(order, Wn, 'bandstop')\n", (3831, 3854), True, 'import scipy as sp\n'), ((3866, 3893), 'scipy.signal.filtfilt', 'sp.signal.filtfilt', (['b', 'a', 'x'], {}), '(b, a, x)\n', (3884, 3893), True, 'import scipy as sp\n'), ((5965, 5976), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (5973, 5976), True, 'import numpy as np\n'), ((6051, 6079), 'numpy.fft.fft', 'np.fft.fft', (['x', 'N2'], {'axis': 'axis'}), '(x, N2, axis=axis)\n', (6061, 6079), True, 'import numpy as np\n'), ((6088, 6100), 'numpy.zeros', 'np.zeros', (['N2'], {}), '(N2)\n', (6096, 6100), True, 'import numpy as np\n'), ((6150, 6180), 'numpy.fft.ifft', 'np.fft.ifft', (['(Xf * h)'], {'axis': 'axis'}), '(Xf * h, axis=axis)\n', (6161, 6180), True, 'import numpy as np\n'), ((8215, 8237), 'numpy.zeros', 'np.zeros', (['P'], {'dtype': 'int'}), '(P, dtype=int)\n', (8223, 8237), True, 'import numpy as np\n'), ((8563, 8585), 'numpy.zeros', 'np.zeros', (['T'], {'dtype': 'int'}), '(T, dtype=int)\n', (8571, 8585), True, 'import numpy as np\n'), ((11629, 11652), 'numpy.delete', 'np.delete', (['Es', 'todelete'], {}), '(Es, todelete)\n', (11638, 11652), True, 'import numpy as np\n'), ((12038, 12049), 'numpy.diff', 'np.diff', (['Ps'], {}), '(Ps)\n', (12045, 12049), True, 'import numpy as np\n'), ((14031, 14059), 'numpy.arange', 'np.arange', (['(0)', '(Fs / 2)', '(Fs / N)'], {}), '(0, Fs / 2, Fs / N)\n', (14040, 14059), True, 'import numpy as np\n'), ((14067, 14080), 'numpy.fft.fft', 'np.fft.fft', (['x'], {}), '(x)\n', (14077, 14080), True, 'import numpy as np\n'), ((14156, 14198), 'numpy.logical_and', 'np.logical_and', (['(f >= flim[0])', '(f <= flim[1])'], {}), '(f >= flim[0], f <= flim[1])\n', (14170, 14198), True, 'import numpy as np\n'), ((14683, 14694), 'numpy.var', 'np.var', (['amp'], {}), '(amp)\n', (14689, 14694), True, 'import numpy as np\n'), ((15256, 15268), 'numpy.diff', 'np.diff', (['pha'], {}), '(pha)\n', (15263, 15268), True, 'import numpy as np\n'), ((15369, 15386), 'numpy.var', 'np.var', (['inst_freq'], {}), '(inst_freq)\n', (15375, 15386), True, 'import numpy as np\n'), ((16776, 16824), 'numpy.arange', 'np.arange', (['frange[0]', '(frange[1] + f_step)', 'f_step'], {}), '(frange[0], frange[1] + f_step, f_step)\n', (16785, 16824), True, 'import numpy as np\n'), ((16907, 16918), 'numpy.zeros', 'np.zeros', (['F'], {}), '(F)\n', (16915, 16918), True, 'import numpy as np\n'), ((17461, 17482), 'scipy.signal.hanning', 'signal.hanning', (['Nsamp'], {}), '(Nsamp)\n', (17475, 17482), False, 'from scipy import signal\n'), ((17607, 17633), 'numpy.zeros', 'np.zeros', (['C'], {'dtype': 'complex'}), '(C, dtype=complex)\n', (17615, 17633), True, 'import numpy as np\n'), ((18013, 18040), 'numpy.abs', 'np.abs', (['(lcs_num / lcs_denom)'], {}), '(lcs_num / lcs_denom)\n', (18019, 18040), True, 'import numpy as np\n'), ((22016, 22030), 'numpy.diff', 'np.diff', (['(1 * x)'], {}), '(1 * x)\n', (22023, 22030), True, 'import numpy as np\n'), ((28685, 28727), 'numpy.percentile', 'np.percentile', (['band_mag', 'thresh_bandpow_pc'], {}), '(band_mag, thresh_bandpow_pc)\n', (28698, 28727), True, 'import numpy as np\n'), ((32993, 33040), 'scipy.interpolate.interp1d', 'sp.interpolate.interp1d', (['fit_logf', 'fit_logpower'], {}), '(fit_logf, fit_logpower)\n', (33016, 33040), True, 'import scipy as sp\n'), ((33507, 33629), 'scipy.signal.spectrogram', 'sp.signal.spectrogram', (['x'], {'fs': 'Fs', 'window': '"""hanning"""', 'nperseg': 'window_size_spec', 'noverlap': '(window_size_spec - 1)', 'mode': '"""psd"""'}), "(x, fs=Fs, window='hanning', nperseg=window_size_spec,\n noverlap=window_size_spec - 1, mode='psd')\n", (33528, 33629), True, 'import scipy as sp\n'), ((34039, 34073), 'numpy.mean', 'np.mean', (['x_spec[fidx_band]'], {'axis': '(0)'}), '(x_spec[fidx_band], axis=0)\n', (34046, 34073), True, 'import numpy as np\n'), ((35314, 35328), 'numpy.diff', 'np.diff', (['(1 * x)'], {}), '(1 * x)\n', (35321, 35328), True, 'import numpy as np\n'), ((37557, 37578), 'numpy.diff', 'np.diff', (['binary_array'], {}), '(binary_array)\n', (37564, 37578), True, 'import numpy as np\n'), ((37598, 37627), 'numpy.insert', 'np.insert', (['binary_diffs', '(0)', '(0)'], {}), '(binary_diffs, 0, 0)\n', (37607, 37627), True, 'import numpy as np\n'), ((38069, 38100), 'numpy.zeros', 'np.zeros', (['Nbursts'], {'dtype': 'object'}), '(Nbursts, dtype=object)\n', (38077, 38100), True, 'import numpy as np\n'), ((38438, 38460), 'numpy.diff', 'np.diff', (['bursts_binary'], {}), '(bursts_binary)\n', (38445, 38460), True, 'import numpy as np\n'), ((38480, 38509), 'numpy.insert', 'np.insert', (['binary_diffs', '(0)', '(0)'], {}), '(binary_diffs, 0, 0)\n', (38489, 38509), True, 'import numpy as np\n'), ((39029, 39051), 'numpy.mean', 'np.mean', (['bursts_binary'], {}), '(bursts_binary)\n', (39036, 39051), True, 'import numpy as np\n'), ((39269, 39291), 'numpy.diff', 'np.diff', (['bursts_binary'], {}), '(bursts_binary)\n', (39276, 39291), True, 'import numpy as np\n'), ((39311, 39340), 'numpy.insert', 'np.insert', (['binary_diffs', '(0)', '(0)'], {}), '(binary_diffs, 0, 0)\n', (39320, 39340), True, 'import numpy as np\n'), ((39917, 39948), 'numpy.zeros', 'np.zeros', (['Nbursts'], {'dtype': 'object'}), '(Nbursts, dtype=object)\n', (39925, 39948), True, 'import numpy as np\n'), ((40577, 40588), 'numpy.empty', 'np.empty', (['L'], {}), '(L)\n', (40585, 40588), True, 'import numpy as np\n'), ((40739, 40751), 'numpy.arange', 'np.arange', (['L'], {}), '(L)\n', (40748, 40751), True, 'import numpy as np\n'), ((41375, 41418), 'numpy.arange', 'np.arange', (['startval', '(val - dval * 0.5)', 'dval'], {}), '(startval, val - dval * 0.5, dval)\n', (41384, 41418), True, 'import numpy as np\n'), ((41711, 41739), 'numpy.arange', 'np.arange', (['val', 'endval', 'dval'], {}), '(val, endval, dval)\n', (41720, 41739), True, 'import numpy as np\n'), ((42494, 42546), 'numpy.logical_and', 'np.logical_and', (['(f >= fslopelim[0])', '(f <= fslopelim[1])'], {}), '(f >= fslopelim[0], f <= fslopelim[1])\n', (42508, 42546), True, 'import numpy as np\n'), ((42585, 42605), 'numpy.log10', 'np.log10', (['slopelineF'], {}), '(slopelineF)\n', (42593, 42605), True, 'import numpy as np\n'), ((42614, 42638), 'numpy.log10', 'np.log10', (['psd[fslopeidx]'], {}), '(psd[fslopeidx])\n', (42622, 42638), True, 'import numpy as np\n'), ((42686, 42731), 'sklearn.linear_model.RANSACRegressor', 'linear_model.RANSACRegressor', ([], {'random_state': '(42)'}), '(random_state=42)\n', (42714, 42731), False, 'from sklearn import linear_model\n'), ((43081, 43099), 'numpy.arange', 'np.arange', (['(80)', '(200)'], {}), '(80, 200)\n', (43090, 43099), True, 'import numpy as np\n'), ((43876, 43899), 'numpy.log10', 'np.log10', (['f_sampleslope'], {}), '(f_sampleslope)\n', (43884, 43899), True, 'import numpy as np\n'), ((43984, 44029), 'sklearn.linear_model.RANSACRegressor', 'linear_model.RANSACRegressor', ([], {'random_state': '(42)'}), '(random_state=42)\n', (44012, 44029), False, 'from sklearn import linear_model\n'), ((2742, 2770), 'numpy.ceil', 'np.ceil', (['(Fs * w / f_range[0])'], {}), '(Fs * w / f_range[0])\n', (2749, 2770), True, 'import numpy as np\n'), ((3076, 3094), 'scipy.signal.freqz', 'signal.freqz', (['taps'], {}), '(taps)\n', (3088, 3094), False, 'from scipy import signal\n'), ((3152, 3179), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (3162, 3179), True, 'import matplotlib.pyplot as plt\n'), ((3187, 3207), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (3198, 3207), True, 'import matplotlib.pyplot as plt\n'), ((3214, 3233), 'matplotlib.pyplot.title', 'plt.title', (['"""Kernel"""'], {}), "('Kernel')\n", (3223, 3233), True, 'import matplotlib.pyplot as plt\n'), ((3242, 3256), 'matplotlib.pyplot.plot', 'plt.plot', (['taps'], {}), '(taps)\n', (3250, 3256), True, 'import matplotlib.pyplot as plt\n'), ((3274, 3294), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (3285, 3294), True, 'import matplotlib.pyplot as plt\n'), ((3363, 3394), 'matplotlib.pyplot.title', 'plt.title', (['"""Frequency response"""'], {}), "('Frequency response')\n", (3372, 3394), True, 'import matplotlib.pyplot as plt\n'), ((3403, 3444), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Attenuation (dB)"""'], {'color': '"""b"""'}), "('Attenuation (dB)', color='b')\n", (3413, 3444), True, 'import matplotlib.pyplot as plt\n'), ((3453, 3481), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency (Hz)"""'], {}), "('Frequency (Hz)')\n", (3463, 3481), True, 'import matplotlib.pyplot as plt\n'), ((4735, 4756), 'scipy.signal.hilbert', 'sp.signal.hilbert', (['xn'], {}), '(xn)\n', (4752, 4756), True, 'import scipy as sp\n'), ((10317, 10345), 'numpy.arange', 'np.arange', (['(0)', '(Fs / 2)', '(Fs / N)'], {}), '(0, Fs / 2, Fs / N)\n', (10326, 10345), True, 'import numpy as np\n'), ((10390, 10403), 'numpy.fft.fft', 'np.fft.fft', (['x'], {}), '(x)\n', (10400, 10403), True, 'import numpy as np\n'), ((11507, 11562), 'numpy.logical_or', 'np.logical_or', (['(Es[e] < SampLims[0])', '(Es[e] > SampLims[1])'], {}), '(Es[e] < SampLims[0], Es[e] > SampLims[1])\n', (11520, 11562), True, 'import numpy as np\n'), ((14205, 14222), 'numpy.sum', 'np.sum', (['psd[fidx]'], {}), '(psd[fidx])\n', (14211, 14222), True, 'import numpy as np\n'), ((17114, 17126), 'numpy.mean', 'np.mean', (['lcs'], {}), '(lcs)\n', (17121, 17126), True, 'import numpy as np\n'), ((17306, 17332), 'numpy.ceil', 'np.ceil', (['(N_cycles * Fs / f)'], {}), '(N_cycles * Fs / f)\n', (17313, 17332), True, 'import numpy as np\n'), ((17692, 17719), 'numpy.fft.fft', 'np.fft.fft', (['(c * hann_window)'], {}), '(c * hann_window)\n', (17702, 17719), True, 'import numpy as np\n'), ((18373, 18388), 'numpy.abs', 'np.abs', (['(x - val)'], {}), '(x - val)\n', (18379, 18388), True, 'import numpy as np\n'), ((20004, 20029), 'scipy.signal.hilbert', 'sp.signal.hilbert', (['x_filt'], {}), '(x_filt)\n', (20021, 20029), True, 'import scipy as sp\n'), ((20220, 20262), 'numpy.ceil', 'np.ceil', (['(min_osc_periods * Fs / f_range[0])'], {}), '(min_osc_periods * Fs / f_range[0])\n', (20227, 20262), True, 'import numpy as np\n'), ((20777, 20801), 'numpy.where', 'np.where', (['(x >= thresh_hi)'], {}), '(x >= thresh_hi)\n', (20785, 20801), True, 'import numpy as np\n'), ((21958, 21967), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (21964, 21967), True, 'import numpy as np\n'), ((22046, 22072), 'numpy.where', 'np.where', (['(osc_changes == 1)'], {}), '(osc_changes == 1)\n', (22054, 22072), True, 'import numpy as np\n'), ((22089, 22116), 'numpy.where', 'np.where', (['(osc_changes == -1)'], {}), '(osc_changes == -1)\n', (22097, 22116), True, 'import numpy as np\n'), ((22292, 22319), 'numpy.insert', 'np.insert', (['osc_starts', '(0)', '(0)'], {}), '(osc_starts, 0, 0)\n', (22301, 22319), True, 'import numpy as np\n'), ((24399, 24424), 'scipy.signal.hilbert', 'sp.signal.hilbert', (['x_filt'], {}), '(x_filt)\n', (24416, 24424), True, 'import scipy as sp\n'), ((25139, 25181), 'numpy.ceil', 'np.ceil', (['(min_osc_periods * Fs / f_range[0])'], {}), '(min_osc_periods * Fs / f_range[0])\n', (25146, 25181), True, 'import numpy as np\n'), ((27084, 27109), 'scipy.signal.hilbert', 'sp.signal.hilbert', (['x_filt'], {}), '(x_filt)\n', (27101, 27109), True, 'import scipy as sp\n'), ((27233, 27256), 'scipy.signal.hilbert', 'sp.signal.hilbert', (['taps'], {}), '(taps)\n', (27250, 27256), True, 'import scipy as sp\n'), ((28054, 28096), 'numpy.ceil', 'np.ceil', (['(min_osc_periods * Fs / f_range[0])'], {}), '(min_osc_periods * Fs / f_range[0])\n', (28061, 28096), True, 'import numpy as np\n'), ((32730, 32756), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 3)'}), '(figsize=(6, 3))\n', (32740, 32756), True, 'import matplotlib.pyplot as plt\n'), ((32764, 32788), 'matplotlib.pyplot.loglog', 'plt.loglog', (['f', 'psd', '"""k-"""'], {}), "(f, psd, 'k-')\n", (32774, 32788), True, 'import matplotlib.pyplot as plt\n'), ((32795, 32848), 'matplotlib.pyplot.loglog', 'plt.loglog', (['(10 ** fit_logf)', '(10 ** fit_logpower)', '"""r--"""'], {}), "(10 ** fit_logf, 10 ** fit_logpower, 'r--')\n", (32805, 32848), True, 'import matplotlib.pyplot as plt\n'), ((32852, 32880), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency (Hz)"""'], {}), "('Frequency (Hz)')\n", (32862, 32880), True, 'import matplotlib.pyplot as plt\n'), ((32889, 32918), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power (uV^2/Hz)"""'], {}), "('Power (uV^2/Hz)')\n", (32899, 32918), True, 'import matplotlib.pyplot as plt\n'), ((33066, 33103), 'numpy.arange', 'np.arange', (['f_range[0]', '(f_range[1] + 1)'], {}), '(f_range[0], f_range[1] + 1)\n', (33075, 33103), True, 'import numpy as np\n'), ((34222, 34249), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4)'}), '(figsize=(10, 4))\n', (34232, 34249), True, 'import matplotlib.pyplot as plt\n'), ((34257, 34277), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (34268, 34277), True, 'import matplotlib.pyplot as plt\n'), ((34284, 34310), 'matplotlib.pyplot.plot', 'plt.plot', (['x[samp_plt]', '"""k"""'], {}), "(x[samp_plt], 'k')\n", (34292, 34310), True, 'import matplotlib.pyplot as plt\n'), ((34318, 34344), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Voltage (uV)"""'], {}), "('Voltage (uV)')\n", (34328, 34344), True, 'import matplotlib.pyplot as plt\n'), ((34353, 34373), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (34364, 34373), True, 'import matplotlib.pyplot as plt\n'), ((34380, 34418), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['x_bandpow[samp_plt]', '"""r"""'], {}), "(x_bandpow[samp_plt], 'r')\n", (34392, 34418), True, 'import matplotlib.pyplot as plt\n'), ((34483, 34507), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Band power"""'], {}), "('Band power')\n", (34493, 34507), True, 'import matplotlib.pyplot as plt\n'), ((34516, 34544), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (samples)"""'], {}), "('Time (samples)')\n", (34526, 34544), True, 'import matplotlib.pyplot as plt\n'), ((35256, 35265), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (35262, 35265), True, 'import numpy as np\n'), ((35344, 35370), 'numpy.where', 'np.where', (['(osc_changes == 1)'], {}), '(osc_changes == 1)\n', (35352, 35370), True, 'import numpy as np\n'), ((35387, 35414), 'numpy.where', 'np.where', (['(osc_changes == -1)'], {}), '(osc_changes == -1)\n', (35395, 35414), True, 'import numpy as np\n'), ((35594, 35621), 'numpy.insert', 'np.insert', (['osc_starts', '(0)', '(0)'], {}), '(osc_starts, 0, 0)\n', (35603, 35621), True, 'import numpy as np\n'), ((37131, 37146), 'numpy.sum', 'np.sum', (['isburst'], {}), '(isburst)\n', (37137, 37146), True, 'import numpy as np\n'), ((37647, 37674), 'numpy.where', 'np.where', (['(binary_diffs == 1)'], {}), '(binary_diffs == 1)\n', (37655, 37674), True, 'import numpy as np\n'), ((37695, 37723), 'numpy.where', 'np.where', (['(binary_diffs == -1)'], {}), '(binary_diffs == -1)\n', (37703, 37723), True, 'import numpy as np\n'), ((37861, 37890), 'numpy.insert', 'np.insert', (['begin_bursts', '(0)', '(0)'], {}), '(begin_bursts, 0, 0)\n', (37870, 37890), True, 'import numpy as np\n'), ((38367, 38388), 'numpy.sum', 'np.sum', (['bursts_binary'], {}), '(bursts_binary)\n', (38373, 38388), True, 'import numpy as np\n'), ((38529, 38556), 'numpy.where', 'np.where', (['(binary_diffs == 1)'], {}), '(binary_diffs == 1)\n', (38537, 38556), True, 'import numpy as np\n'), ((38577, 38605), 'numpy.where', 'np.where', (['(binary_diffs == -1)'], {}), '(binary_diffs == -1)\n', (38585, 38605), True, 'import numpy as np\n'), ((38867, 38896), 'numpy.insert', 'np.insert', (['begin_bursts', '(0)', '(0)'], {}), '(begin_bursts, 0, 0)\n', (38876, 38896), True, 'import numpy as np\n'), ((39198, 39219), 'numpy.sum', 'np.sum', (['bursts_binary'], {}), '(bursts_binary)\n', (39204, 39219), True, 'import numpy as np\n'), ((39360, 39387), 'numpy.where', 'np.where', (['(binary_diffs == 1)'], {}), '(binary_diffs == 1)\n', (39368, 39387), True, 'import numpy as np\n'), ((39408, 39436), 'numpy.where', 'np.where', (['(binary_diffs == -1)'], {}), '(binary_diffs == -1)\n', (39416, 39436), True, 'import numpy as np\n'), ((39699, 39728), 'numpy.insert', 'np.insert', (['begin_bursts', '(0)', '(0)'], {}), '(begin_bursts, 0, 0)\n', (39708, 39728), True, 'import numpy as np\n'), ((40716, 40729), 'numpy.isnan', 'np.isnan', (['pha'], {}), '(pha)\n', (40724, 40729), True, 'import numpy as np\n'), ((41006, 41046), 'numpy.linspace', 'np.linspace', (['val1', 'val2', '(idx2 - idx1 + 1)'], {}), '(val1, val2, idx2 - idx1 + 1)\n', (41017, 41046), True, 'import numpy as np\n'), ((41545, 41564), 'numpy.exp', 'np.exp', (['(1.0j * dval)'], {}), '(1.0j * dval)\n', (41551, 41564), True, 'import numpy as np\n'), ((41800, 41818), 'numpy.exp', 'np.exp', (['(1.0j * pha)'], {}), '(1.0j * pha)\n', (41806, 41818), True, 'import numpy as np\n'), ((2884, 2901), 'numpy.array', 'np.array', (['f_range'], {}), '(f_range)\n', (2892, 2901), True, 'import numpy as np\n'), ((5696, 5717), 'scipy.signal.hilbert', 'sp.signal.hilbert', (['xn'], {}), '(xn)\n', (5713, 5717), True, 'import scipy as sp\n'), ((8473, 8508), 'numpy.argmax', 'np.argmax', (['x[mrzerorise:nfzerofall]'], {}), '(x[mrzerorise:nfzerofall])\n', (8482, 8508), True, 'import numpy as np\n'), ((8824, 8859), 'numpy.argmin', 'np.argmin', (['x[mrzerofall:nfzerorise]'], {}), '(x[mrzerofall:nfzerorise])\n', (8833, 8859), True, 'import numpy as np\n'), ((10567, 10603), 'scipy.signal.medfilt', 'signal.medfilt', (['psd', '(sampmed * 2 + 1)'], {}), '(psd, sampmed * 2 + 1)\n', (10581, 10603), False, 'from scipy import signal\n'), ((10657, 10698), 'scipy.signal.welch', 'sp.signal.welch', (['x'], {'fs': 'Fs'}), '(x, fs=Fs, **welch_params)\n', (10672, 10698), True, 'import scipy as sp\n'), ((11582, 11604), 'numpy.append', 'np.append', (['todelete', 'e'], {}), '(todelete, e)\n', (11591, 11604), True, 'import numpy as np\n'), ((17867, 17899), 'numpy.conj', 'np.conj', (['fourier_coefsoi[i2 + 1]'], {}), '(fourier_coefsoi[i2 + 1])\n', (17874, 17899), True, 'import numpy as np\n'), ((24780, 24802), 'numpy.median', 'np.median', (['x_magnitude'], {}), '(x_magnitude)\n', (24789, 24802), True, 'import numpy as np\n'), ((27340, 27349), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (27346, 27349), True, 'import numpy as np\n'), ((28754, 28814), 'numpy.logical_and', 'np.logical_and', (['(frac_mag >= thresh_hi)', '(band_mag >= bandmagpc)'], {}), '(frac_mag >= thresh_hi, band_mag >= bandmagpc)\n', (28768, 28814), True, 'import numpy as np\n'), ((32415, 32469), 'numpy.logical_and', 'np.logical_and', (['(f >= f_slope[0][0])', '(f <= f_slope[0][1])'], {}), '(f >= f_slope[0][0], f <= f_slope[0][1])\n', (32429, 32469), True, 'import numpy as np\n'), ((32501, 32555), 'numpy.logical_and', 'np.logical_and', (['(f >= f_slope[1][0])', '(f <= f_slope[1][1])'], {}), '(f >= f_slope[1][0], f <= f_slope[1][1])\n', (32515, 32555), True, 'import numpy as np\n'), ((33975, 34023), 'numpy.logical_and', 'np.logical_and', (['(f >= f_range[0])', '(f <= f_range[1])'], {}), '(f >= f_range[0], f <= f_range[1])\n', (33989, 34023), True, 'import numpy as np\n'), ((10528, 10551), 'numpy.abs', 'np.abs', (['(f - Hzmed / 2.0)'], {}), '(f - Hzmed / 2.0)\n', (10534, 10551), True, 'import numpy as np\n'), ((24865, 24885), 'numpy.mean', 'np.mean', (['x_magnitude'], {}), '(x_magnitude)\n', (24872, 24885), True, 'import numpy as np\n'), ((29366, 29442), 'numpy.logical_and', 'np.logical_and', (['(frac_mag[j_down] >= thresh_lo)', '(band_mag[j_down] >= bandmagpc)'], {}), '(frac_mag[j_down] >= thresh_lo, band_mag[j_down] >= bandmagpc)\n', (29380, 29442), True, 'import numpy as np\n'), ((29814, 29886), 'numpy.logical_and', 'np.logical_and', (['(frac_mag[j_up] >= thresh_lo)', '(band_mag[j_up] >= bandmagpc)'], {}), '(frac_mag[j_up] >= thresh_lo, band_mag[j_up] >= bandmagpc)\n', (29828, 29886), True, 'import numpy as np\n'), ((33236, 33275), 'scipy.stats.chi2.ppf', 'sp.stats.chi2.ppf', (['percentile_thresh', '(2)'], {}), '(percentile_thresh, 2)\n', (33253, 33275), True, 'import scipy as sp\n'), ((17929, 17957), 'numpy.abs', 'np.abs', (['fourier_coefsoi[:-1]'], {}), '(fourier_coefsoi[:-1])\n', (17935, 17957), True, 'import numpy as np\n'), ((17969, 17996), 'numpy.abs', 'np.abs', (['fourier_coefsoi[1:]'], {}), '(fourier_coefsoi[1:])\n', (17975, 17996), True, 'import numpy as np\n'), ((33808, 33829), 'numpy.abs', 'np.abs', (['(t - t_spec[0])'], {}), '(t - t_spec[0])\n', (33814, 33829), True, 'import numpy as np\n'), ((41213, 41226), 'numpy.isnan', 'np.isnan', (['pha'], {}), '(pha)\n', (41221, 41226), True, 'import numpy as np\n'), ((41453, 41466), 'numpy.isnan', 'np.isnan', (['pha'], {}), '(pha)\n', (41461, 41466), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
parse mp4 'colr' lazily
=======================
"""
# import standard libraries
import os
from struct import unpack, pack
from pathlib import Path
import shutil
# import third-party libraries
from numpy.testing._private.utils import assert_equal
# import my libraries
# information
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2020 - <NAME>'
__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = '<NAME>'
__email__ = 'toru.ver.11 at-sign gmail.com'
__all__ = []
def read_size(fp):
"""
Parameters
----------
fp : BufferedReader
file instance? the position is the begining of the box.
"""
size = unpack('>I', fp.read(4))[0]
if size == 0:
raise ValueError('extended size is not supported')
else:
return size
def read_box_type(fp):
"""
Parameters
----------
fp : BufferedReader
file instance?
the position is 4 byte from the beginning of the box.
"""
box_type = unpack('4s', fp.read(4))[0].decode()
return box_type
def seek_fp_type_end_to_box_start(fp):
fp.seek(-8, 1)
def read_box_type_and_type(fp):
"""
Parameters
----------
fp : BufferedReader
file instance? the position is the begining of the box.
Returns
-------
size : int
a box size
type : strings
a box type
"""
size = read_size(fp)
box_type = read_box_type(fp)
seek_fp_type_end_to_box_start(fp)
return size, box_type
def is_end_of_file(fp):
"""
check if it is the end of file.
"""
read_size = 8
dummy = fp.read(8)
if len(dummy) != read_size:
return True
else:
fp.seek(-read_size, 1)
return False
def get_moov_data(fp, address, size):
fp.seek(address)
data = fp.read(size)
return data
def get_moov_address_and_size(fp):
"""
Parameters
----------
fp : BufferedReader
file instance.
"""
fp.seek(0)
size = 0
address = None
for idx in range(10):
fp.seek(size, 1)
if is_end_of_file(fp):
print("Warning: 'moov' is not found.")
break
size, box_type = read_box_type_and_type(fp)
if box_type == 'moov':
address = fp.tell()
print(f"'moov' is found at 0x{address:016X}")
break
return address, size
def search_colour_info_start_address(fp):
"""
search the start address of the `colour_primaries` in the 'colr' box.
Parameters
----------
fp : BufferedReader
file instance.
"""
fp.seek(0)
moov_address, moov_size = get_moov_address_and_size(fp)
moov_data = get_moov_data(fp, moov_address, moov_size)
colour_tag_address = moov_data.find('colr'.encode())
colour_type_address = moov_data.find('nclx'.encode())
if (colour_type_address - colour_tag_address) != 4:
print("Error: 'colr' or 'nclx' is not found.")
return None
colour_info_start_address = colour_type_address + 4 + moov_address
print(f"'colr' info address is 0x{colour_info_start_address:08X}")
return colour_info_start_address
def get_colour_characteristics(fp):
colour_info_address = search_colour_info_start_address(fp)
fp.seek(colour_info_address)
colour_binary_data = fp.read(6)
colour_primaries, transfer_characteristics, matrix_coefficients\
= unpack('>HHH', colour_binary_data)
return colour_primaries, transfer_characteristics, matrix_coefficients
def set_colour_characteristics(
fp, colour_primaries, transfer_characteristics, matrix_coefficients):
colour_info_address = search_colour_info_start_address(fp)
fp.seek(colour_info_address)
data = pack(
'>HHH', colour_primaries, transfer_characteristics, matrix_coefficients
)
fp.write(data)
def make_dst_fname(src_fname, suffix="9_16_9"):
"""
Examples
--------
>>> make_dst_fname(src_fname="./video/hoge.mp4", suffix="9_16_9")
"./video/hoge_9_16_9.mp4"
"""
src_path = Path(src_fname)
parent = str(src_path.parent)
ext = src_path.suffix
stem = src_path.stem
dst_path_str = parent + '/' + stem + "_" + suffix + ext
return dst_path_str
def rewrite_colr_box(
src_fname, colour_primaries, transfer_characteristics,
matrix_coefficients):
"""
rewrite the 'colr' box parametes.
Paramters
---------
src_fname : strings
source file name.
colour_primaries : int
1: BT.709, 9: BT.2020
transfer_characteristics : int
1: BT.709, 16: ST 2084, 17: ARIB STD-B67
matrix_coefficients : int
1: BT.709, 9: BT.2020
"""
suffix = f"colr_{colour_primaries}_{transfer_characteristics}"
suffix += f"_{matrix_coefficients}"
dst_fname = make_dst_fname(src_fname=src_fname, suffix=suffix)
shutil.copyfile(src_fname, dst_fname)
fp = open(dst_fname, 'rb+')
set_colour_characteristics(
fp, colour_primaries, transfer_characteristics,
matrix_coefficients)
fp.close()
def test_rewrite_colour_parameters():
src_fname = "./video/BT2020-ST2084_H264.mp4"
dst_fname = make_dst_fname(src_fname, suffix='colr_10_17_10')
print(dst_fname)
shutil.copyfile(src_fname, dst_fname)
fp = open(dst_fname, 'rb+')
colour_primaries, transfer_characteristics, matrix_coefficients\
= get_colour_characteristics(fp)
print(colour_primaries, transfer_characteristics, matrix_coefficients)
set_colour_characteristics(fp, 10, 17, 10)
def test_get_colour_characteristics():
src_fname = "./video/BT2020-ST2084_H264.mp4"
fp = open(src_fname, 'rb')
colour_primaries, transfer_characteristics, matrix_coefficients\
= get_colour_characteristics(fp)
print(colour_primaries, transfer_characteristics, matrix_coefficients)
assert_equal(colour_primaries, 9)
assert_equal(transfer_characteristics, 16)
assert_equal(matrix_coefficients, 9)
def test_set_colour_characteristics():
colour_primaries_i = 10
transfer_characteristics_i = 15
matrix_coefficients_i = 8
src_fname = "./video/BT2020-ST2084_H264.mp4"
dst_fname = make_dst_fname(src_fname, suffix='colr_9_15_8')
shutil.copyfile(src_fname, dst_fname)
fp = open(dst_fname, 'rb+')
set_colour_characteristics(
fp, colour_primaries_i, transfer_characteristics_i,
matrix_coefficients_i)
fp.close()
fp = open(dst_fname, 'rb')
colour_primaries_o, transfer_characteristics_o, matrix_coefficients_o\
= get_colour_characteristics(fp)
print(
colour_primaries_o, transfer_characteristics_o, matrix_coefficients_o)
assert_equal(colour_primaries_i, colour_primaries_o)
assert_equal(transfer_characteristics_i, transfer_characteristics_o)
assert_equal(matrix_coefficients_i, matrix_coefficients_o)
def lazy_tests():
test_get_colour_characteristics()
test_set_colour_characteristics()
if __name__ == '__main__':
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# lazy_tests()
# test_rewrite_colour_parameters()
# rewrite_colr_box(
# src_fname='./video/BT2020-ST2084_H264_Resolve.mp4',
# colour_primaries=9, transfer_characteristics=16, matrix_coefficients=9)
fname_list = [
# './video/BT2020-ST2084_H264_command.mp4',
# './video/src_grad_tp_1920x1080_b-size_64_DV17_HDR10.mp4',
# './video/src_grad_tp_1920x1080_b-size_64_ffmpeg_HDR10.mp4',
'./video/src_grad_tp_1920x1080_b-size_64_ffmpeg.mp4'
]
for fname in fname_list:
rewrite_colr_box(
src_fname=fname,
colour_primaries=9, transfer_characteristics=16,
matrix_coefficients=9)
|
[
"numpy.testing._private.utils.assert_equal",
"os.path.abspath",
"struct.unpack",
"struct.pack",
"pathlib.Path",
"shutil.copyfile"
] |
[((3450, 3484), 'struct.unpack', 'unpack', (['""">HHH"""', 'colour_binary_data'], {}), "('>HHH', colour_binary_data)\n", (3456, 3484), False, 'from struct import unpack, pack\n'), ((3780, 3857), 'struct.pack', 'pack', (['""">HHH"""', 'colour_primaries', 'transfer_characteristics', 'matrix_coefficients'], {}), "('>HHH', colour_primaries, transfer_characteristics, matrix_coefficients)\n", (3784, 3857), False, 'from struct import unpack, pack\n'), ((4098, 4113), 'pathlib.Path', 'Path', (['src_fname'], {}), '(src_fname)\n', (4102, 4113), False, 'from pathlib import Path\n'), ((4913, 4950), 'shutil.copyfile', 'shutil.copyfile', (['src_fname', 'dst_fname'], {}), '(src_fname, dst_fname)\n', (4928, 4950), False, 'import shutil\n'), ((5295, 5332), 'shutil.copyfile', 'shutil.copyfile', (['src_fname', 'dst_fname'], {}), '(src_fname, dst_fname)\n', (5310, 5332), False, 'import shutil\n'), ((5907, 5940), 'numpy.testing._private.utils.assert_equal', 'assert_equal', (['colour_primaries', '(9)'], {}), '(colour_primaries, 9)\n', (5919, 5940), False, 'from numpy.testing._private.utils import assert_equal\n'), ((5945, 5987), 'numpy.testing._private.utils.assert_equal', 'assert_equal', (['transfer_characteristics', '(16)'], {}), '(transfer_characteristics, 16)\n', (5957, 5987), False, 'from numpy.testing._private.utils import assert_equal\n'), ((5992, 6028), 'numpy.testing._private.utils.assert_equal', 'assert_equal', (['matrix_coefficients', '(9)'], {}), '(matrix_coefficients, 9)\n', (6004, 6028), False, 'from numpy.testing._private.utils import assert_equal\n'), ((6281, 6318), 'shutil.copyfile', 'shutil.copyfile', (['src_fname', 'dst_fname'], {}), '(src_fname, dst_fname)\n', (6296, 6318), False, 'import shutil\n'), ((6730, 6782), 'numpy.testing._private.utils.assert_equal', 'assert_equal', (['colour_primaries_i', 'colour_primaries_o'], {}), '(colour_primaries_i, colour_primaries_o)\n', (6742, 6782), False, 'from numpy.testing._private.utils import assert_equal\n'), ((6787, 6855), 'numpy.testing._private.utils.assert_equal', 'assert_equal', (['transfer_characteristics_i', 'transfer_characteristics_o'], {}), '(transfer_characteristics_i, transfer_characteristics_o)\n', (6799, 6855), False, 'from numpy.testing._private.utils import assert_equal\n'), ((6860, 6918), 'numpy.testing._private.utils.assert_equal', 'assert_equal', (['matrix_coefficients_i', 'matrix_coefficients_o'], {}), '(matrix_coefficients_i, matrix_coefficients_o)\n', (6872, 6918), False, 'from numpy.testing._private.utils import assert_equal\n'), ((7073, 7098), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (7088, 7098), False, 'import os\n')]
|
"""
Newman Model
-----------------------
This module contains a functions for generating random graph
using configuration model. In configuration model, one represents
a graph using degree sequence. The actual graph is obtained by randomly
connecting stubs of vertices.
"""
import sys, os, math
import numpy as np
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def degree_sequence_regular(n, k):
"""
Generates a degree sequnce following k-regular distribution
:param n: Number of vertices.
:param k: The parameter k for k-regular distribution
:return: A list containing n integers representing degrees of vertices following k-regular distribution.
"""
return [k] * n
def degree_sequence_lognormal(n, mu, sigma):
"""
Generates a degree sequnce following k-regular distribution
:param n: Number of vertices.
:param mu: The parameter mu for lognormal distribution
:param sigma: The parameter sigma for lognormal distribution
:return: A list containing n integers representing degrees of vertices following lognormal distribution
"""
degree_seq = np.random.normal(mu, sigma, size=n)
return degree_seq
def configure_sequence(degree_seq):
"""
Given a degree sequence, creates a random graph following configuration
model, i.e., by connecting stubs of vertices.
:param degree_seq: the degree sequence of a graph
:return: A set of tuples, representing the edges.
"""
def pick_stub():
explored = set(range(len(degree_seq)))
# eliminate all that are zero, and pick one
# create new list containing indices
non_zero_stubs = [i for i, d in enumerate(degree_seq) if d > 0]
if len(non_zero_stubs) == 0: raise Exception("Something went wrong")
# pick a random index of a list
random_index = np.random.randint(low=0, high=len(non_zero_stubs))
return non_zero_stubs[random_index]
d_m = sum(degree_seq)
edges = []
while d_m > 0:
# pick a two random integers
# denoting id of stub
# end connect them if they are not zero
f_stub, s_stub = pick_stub(), pick_stub()
d_m -= 2
# basically, vertices f_stub, s_stub are connected
degree_seq[f_stub] -= 1
degree_seq[s_stub] -= 1
edges.append((f_stub, s_stub))
return edges
def irregular_edge_count(edges):
"""
Computes ratio of multiedges and loops and simple edges
:param edges: A list of tuples representing the set of edges of a graph.
:return: The ratio described above.
"""
unique_edges = set()
loop_counter, multi_edge_cnt = 0, 0
for e in edges:
u, v = e
# check if it is a loop
if u == v: loop_counter += 1
# check if it is multiedge
if (u, v) in unique_edges or (v, u) in unique_edges: multi_edge_cnt += 1
else: unique_edges.add(e)
return float(loop_counter + multi_edge_cnt) / float(len(edges))
|
[
"os.path.abspath",
"numpy.random.normal"
] |
[((1141, 1176), 'numpy.random.normal', 'np.random.normal', (['mu', 'sigma'], {'size': 'n'}), '(mu, sigma, size=n)\n', (1157, 1176), True, 'import numpy as np\n'), ((364, 389), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (379, 389), False, 'import sys, os, math\n')]
|
import os
import sys
import glob
import time
import copy
import logging
import argparse
import random
import numpy as np
import utils
import lightgbm as lgb
from nasbench import api
parser = argparse.ArgumentParser()
# Basic model parameters.
parser.add_argument('--data', type=str, default='data')
parser.add_argument('--output_dir', type=str, default='outputs')
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--n', type=int, default=1000)
parser.add_argument('--k', type=int, default=1000)
parser.add_argument('--iterations', type=int, default=1)
parser.add_argument('--lr', type=float, default=0.05)
parser.add_argument('--leaves', type=int, default=31)
parser.add_argument('--num_boost_round', type=int, default=100)
args = parser.parse_args()
utils.create_exp_dir(args.output_dir, scripts_to_save=glob.glob('*.py'))
log_format = '%(asctime)s %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format=log_format, datefmt='%m/%d %I:%M:%S %p')
def main():
random.seed(args.seed)
np.random.seed(args.seed)
logging.info("Args = %s", args)
nasbench = api.NASBench(os.path.join(args.data, 'nasbench_only108.tfrecord'))
arch_pool, seq_pool, valid_accs = utils.generate_arch(args.n, nasbench, need_perf=True)
feature_name = utils.get_feature_name()
params = {
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': {'l2'},
'num_leaves': args.leaves,
'learning_rate': args.lr,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': 0
}
sorted_indices = np.argsort(valid_accs)[::-1]
arch_pool = [arch_pool[i] for i in sorted_indices]
seq_pool = [seq_pool[i] for i in sorted_indices]
valid_accs = [valid_accs[i] for i in sorted_indices]
with open(os.path.join(args.output_dir, 'arch_pool.{}'.format(0)), 'w') as f:
for arch, seq, valid_acc in zip(arch_pool, seq_pool, valid_accs):
f.write('{}\t{}\t{}\t{}\n'.format(arch.matrix, arch.ops, seq, valid_acc))
mean_val = 0.908192
std_val = 0.023961
for i in range(args.iterations):
logging.info('Iteration {}'.format(i+1))
normed_valid_accs = [(i-mean_val)/std_val for i in valid_accs]
train_x = np.array(seq_pool)
train_y = np.array(normed_valid_accs)
# Train GBDT-NAS
logging.info('Train GBDT-NAS')
lgb_train = lgb.Dataset(train_x, train_y)
gbm = lgb.train(params, lgb_train, feature_name=feature_name, num_boost_round=args.num_boost_round)
gbm.save_model(os.path.join(args.output_dir, 'model.txt'))
all_arch, all_seq = utils.generate_arch(None, nasbench)
logging.info('Totally {} archs from the search space'.format(len(all_seq)))
all_pred = gbm.predict(np.array(all_seq), num_iteration=gbm.best_iteration)
sorted_indices = np.argsort(all_pred)[::-1]
all_arch = [all_arch[i] for i in sorted_indices]
all_seq = [all_seq[i] for i in sorted_indices]
new_arch, new_seq, new_valid_acc = [], [], []
for arch, seq in zip(all_arch, all_seq):
if seq in seq_pool:
continue
new_arch.append(arch)
new_seq.append(seq)
new_valid_acc.append(nasbench.query(arch)['validation_accuracy'])
if len(new_arch) >= args.k:
break
arch_pool += new_arch
seq_pool += new_seq
valid_accs += new_valid_acc
sorted_indices = np.argsort(valid_accs)[::-1]
arch_pool = [arch_pool[i] for i in sorted_indices]
seq_pool = [seq_pool[i] for i in sorted_indices]
valid_accs = [valid_accs[i] for i in sorted_indices]
with open(os.path.join(args.output_dir, 'arch_pool.{}'.format(i+1)), 'w') as f:
for arch, seq, va in zip(arch_pool, seq_pool, valid_accs):
f.write('{}\t{}\t{}\t{}\n'.format(arch.matrix, arch.ops, seq, va))
logging.info('Finish Searching\n')
with open(os.path.join(args.output_dir, 'arch_pool.final'), 'w') as f:
for i in range(10):
arch, seq, valid_acc = arch_pool[i], seq_pool[i], valid_accs[i]
fs, cs = nasbench.get_metrics_from_spec(arch)
test_acc = np.mean([cs[108][i]['final_test_accuracy'] for i in range(3)])
f.write('{}\t{}\t{}\t{}\t{}\n'.format(arch.matrix, arch.ops, seq, valid_acc, test_acc))
print('{}\t{}\tvalid acc: {}\tmean test acc: {}\n'.format(arch.matrix, arch.ops, valid_acc, test_acc))
if __name__ == '__main__':
main()
|
[
"numpy.random.seed",
"argparse.ArgumentParser",
"logging.basicConfig",
"lightgbm.train",
"lightgbm.Dataset",
"numpy.argsort",
"logging.info",
"random.seed",
"numpy.array",
"glob.glob",
"os.path.join",
"utils.generate_arch",
"utils.get_feature_name"
] |
[((207, 232), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (230, 232), False, 'import argparse\n'), ((919, 1030), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO', 'format': 'log_format', 'datefmt': '"""%m/%d %I:%M:%S %p"""'}), "(stream=sys.stdout, level=logging.INFO, format=\n log_format, datefmt='%m/%d %I:%M:%S %p')\n", (938, 1030), False, 'import logging\n'), ((1053, 1075), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (1064, 1075), False, 'import random\n'), ((1081, 1106), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1095, 1106), True, 'import numpy as np\n'), ((1118, 1149), 'logging.info', 'logging.info', (['"""Args = %s"""', 'args'], {}), "('Args = %s', args)\n", (1130, 1149), False, 'import logging\n'), ((1276, 1329), 'utils.generate_arch', 'utils.generate_arch', (['args.n', 'nasbench'], {'need_perf': '(True)'}), '(args.n, nasbench, need_perf=True)\n', (1295, 1329), False, 'import utils\n'), ((1350, 1374), 'utils.get_feature_name', 'utils.get_feature_name', ([], {}), '()\n', (1372, 1374), False, 'import utils\n'), ((4127, 4161), 'logging.info', 'logging.info', (['"""Finish Searching\n"""'], {}), "('Finish Searching\\n')\n", (4139, 4161), False, 'import logging\n'), ((859, 876), 'glob.glob', 'glob.glob', (['"""*.py"""'], {}), "('*.py')\n", (868, 876), False, 'import glob\n'), ((1181, 1233), 'os.path.join', 'os.path.join', (['args.data', '"""nasbench_only108.tfrecord"""'], {}), "(args.data, 'nasbench_only108.tfrecord')\n", (1193, 1233), False, 'import os\n'), ((1708, 1730), 'numpy.argsort', 'np.argsort', (['valid_accs'], {}), '(valid_accs)\n', (1718, 1730), True, 'import numpy as np\n'), ((2378, 2396), 'numpy.array', 'np.array', (['seq_pool'], {}), '(seq_pool)\n', (2386, 2396), True, 'import numpy as np\n'), ((2416, 2443), 'numpy.array', 'np.array', (['normed_valid_accs'], {}), '(normed_valid_accs)\n', (2424, 2443), True, 'import numpy as np\n'), ((2489, 2519), 'logging.info', 'logging.info', (['"""Train GBDT-NAS"""'], {}), "('Train GBDT-NAS')\n", (2501, 2519), False, 'import logging\n'), ((2541, 2570), 'lightgbm.Dataset', 'lgb.Dataset', (['train_x', 'train_y'], {}), '(train_x, train_y)\n', (2552, 2570), True, 'import lightgbm as lgb\n'), ((2588, 2686), 'lightgbm.train', 'lgb.train', (['params', 'lgb_train'], {'feature_name': 'feature_name', 'num_boost_round': 'args.num_boost_round'}), '(params, lgb_train, feature_name=feature_name, num_boost_round=\n args.num_boost_round)\n', (2597, 2686), True, 'import lightgbm as lgb\n'), ((2785, 2820), 'utils.generate_arch', 'utils.generate_arch', (['None', 'nasbench'], {}), '(None, nasbench)\n', (2804, 2820), False, 'import utils\n'), ((2706, 2748), 'os.path.join', 'os.path.join', (['args.output_dir', '"""model.txt"""'], {}), "(args.output_dir, 'model.txt')\n", (2718, 2748), False, 'import os\n'), ((2938, 2955), 'numpy.array', 'np.array', (['all_seq'], {}), '(all_seq)\n', (2946, 2955), True, 'import numpy as np\n'), ((3017, 3037), 'numpy.argsort', 'np.argsort', (['all_pred'], {}), '(all_pred)\n', (3027, 3037), True, 'import numpy as np\n'), ((3666, 3688), 'numpy.argsort', 'np.argsort', (['valid_accs'], {}), '(valid_accs)\n', (3676, 3688), True, 'import numpy as np\n'), ((4181, 4229), 'os.path.join', 'os.path.join', (['args.output_dir', '"""arch_pool.final"""'], {}), "(args.output_dir, 'arch_pool.final')\n", (4193, 4229), False, 'import os\n')]
|
import pytest
import vaex
pytest.importorskip("sklearn")
from vaex.ml.sklearn import SKLearnPredictor
import numpy as np
# Regressions
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.svm import SVR
from sklearn.ensemble import AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor
# Classifiers
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier
models_regression = [LinearRegression(),
Ridge(random_state=42, max_iter=100),
Lasso(random_state=42, max_iter=100),
SVR(gamma='scale'),
AdaBoostRegressor(random_state=42, n_estimators=10),
GradientBoostingRegressor(random_state=42, max_depth=3, n_estimators=10),
RandomForestRegressor(n_estimators=10, random_state=42, max_depth=3)]
models_classification = [LogisticRegression(solver='lbfgs', max_iter=100, random_state=42),
SVC(gamma='scale', max_iter=100),
AdaBoostClassifier(random_state=42, n_estimators=10),
GradientBoostingClassifier(random_state=42, max_depth=3, n_estimators=10),
RandomForestClassifier(n_estimators=10, random_state=42, max_depth=3)]
def test_sklearn_estimator():
ds = vaex.ml.datasets.load_iris()
features = ['sepal_length', 'sepal_width', 'petal_length']
train, test = ds.ml.train_test_split(verbose=False)
model = SKLearnPredictor(model=LinearRegression(), features=features, prediction_name='pred')
model.fit(train, train.petal_width)
prediction = model.predict(test)
test = model.transform(test)
np.testing.assert_array_almost_equal(test.pred.values, prediction, decimal=5)
# Transfer the state of train to ds
train = model.transform(train)
state = train.state_get()
ds.state_set(state)
assert ds.pred.values.shape == (150,)
def test_sklearn_estimator_virtual_columns():
ds = vaex.ml.datasets.load_iris()
ds['x'] = ds.sepal_length * 1
ds['y'] = ds.sepal_width * 1
ds['w'] = ds.petal_length * 1
ds['z'] = ds.petal_width * 1
train, test = ds.ml.train_test_split(test_size=0.2, verbose=False)
features = ['x', 'y', 'z']
model = SKLearnPredictor(model=LinearRegression(), features=features, prediction_name='pred')
model.fit(ds, ds.w)
ds = model.transform(ds)
assert ds.pred.values.shape == (150,)
def test_sklearn_estimator_serialize(tmpdir):
ds = vaex.ml.datasets.load_iris()
features = ['sepal_length', 'sepal_width', 'petal_length']
model = SKLearnPredictor(model=LinearRegression(), features=features, prediction_name='pred')
model.fit(ds, ds.petal_width)
pipeline = vaex.ml.Pipeline([model])
pipeline.save(str(tmpdir.join('test.json')))
pipeline.load(str(tmpdir.join('test.json')))
model = SKLearnPredictor(model=LinearRegression(), features=features, prediction_name='pred')
model.fit(ds, ds.petal_width)
model.state_set(model.state_get())
pipeline = vaex.ml.Pipeline([model])
pipeline.save(str(tmpdir.join('test.json')))
pipeline.load(str(tmpdir.join('test.json')))
def test_sklearn_estimator_regression_validation():
ds = vaex.ml.datasets.load_iris()
train, test = ds.ml.train_test_split(verbose=False)
features = ['sepal_length', 'sepal_width', 'petal_length']
# Dense features
Xtrain = train[features].values
Xtest = test[features].values
ytrain = train.petal_width.values
for model in models_regression:
# vaex
vaex_model = SKLearnPredictor(model=model, features=features, prediction_name='pred')
vaex_model.fit(train, train.petal_width)
test = vaex_model.transform(test)
# sklearn
model.fit(Xtrain, ytrain)
skl_pred = model.predict(Xtest)
np.testing.assert_array_almost_equal(test.pred.values, skl_pred, decimal=5)
def test_sklearn_estimator_pipeline():
ds = vaex.ml.datasets.load_iris()
train, test = ds.ml.train_test_split(verbose=False)
# Add virtual columns
train['sepal_virtual'] = np.sqrt(train.sepal_length**2 + train.sepal_width**2)
train['petal_scaled'] = train.petal_length * 0.2
# Do a pca
features = ['sepal_virtual', 'petal_scaled']
pca = train.ml.pca(n_components=2, features=features)
train = pca.transform(train)
# Do state transfer
st = train.ml.state_transfer()
# now apply the model
features = ['sepal_virtual', 'petal_scaled']
model = SKLearnPredictor(model=LinearRegression(), features=features, prediction_name='pred')
model.fit(train, train.petal_width)
# Create a pipeline
pipeline = vaex.ml.Pipeline([st, model])
# Use the pipeline
pred = pipeline.predict(test)
df_trans = pipeline.transform(test)
# WARNING: on windows/appveyor this gives slightly different results
# do we fully understand why? I also have the same results on my osx laptop
# sklearn 0.21.1 (scikit-learn-0.21.2 is installed on windows) so it might be a
# version related thing
np.testing.assert_array_almost_equal(pred, df_trans.pred.values)
def test_sklearn_estimator_classification_validation():
ds = vaex.ml.datasets.load_titanic()
train, test = ds.ml.train_test_split(verbose=False)
features = ['pclass', 'parch', 'sibsp']
# Dense features
Xtrain = train[features].values
Xtest = test[features].values
ytrain = train.survived.values
for model in models_classification:
# vaex
vaex_model = SKLearnPredictor(model=model, features=features, prediction_name='pred')
vaex_model.fit(train, train.survived)
test = vaex_model.transform(test)
# scikit-learn
model.fit(Xtrain, ytrain)
skl_pred = model.predict(Xtest)
assert np.all(skl_pred == test.pred.values)
|
[
"vaex.ml.Pipeline",
"sklearn.ensemble.GradientBoostingRegressor",
"sklearn.svm.SVC",
"numpy.testing.assert_array_almost_equal",
"sklearn.linear_model.Ridge",
"sklearn.linear_model.Lasso",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.ensemble.RandomForestRegressor",
"sklearn.linear_model.LinearRegression",
"sklearn.linear_model.LogisticRegression",
"vaex.ml.datasets.load_titanic",
"vaex.ml.datasets.load_iris",
"numpy.all",
"pytest.importorskip",
"sklearn.svm.SVR",
"sklearn.ensemble.AdaBoostRegressor",
"sklearn.ensemble.GradientBoostingClassifier",
"vaex.ml.sklearn.SKLearnPredictor",
"numpy.sqrt"
] |
[((26, 56), 'pytest.importorskip', 'pytest.importorskip', (['"""sklearn"""'], {}), "('sklearn')\n", (45, 56), False, 'import pytest\n'), ((544, 562), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (560, 562), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n'), ((585, 621), 'sklearn.linear_model.Ridge', 'Ridge', ([], {'random_state': '(42)', 'max_iter': '(100)'}), '(random_state=42, max_iter=100)\n', (590, 621), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n'), ((644, 680), 'sklearn.linear_model.Lasso', 'Lasso', ([], {'random_state': '(42)', 'max_iter': '(100)'}), '(random_state=42, max_iter=100)\n', (649, 680), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n'), ((703, 721), 'sklearn.svm.SVR', 'SVR', ([], {'gamma': '"""scale"""'}), "(gamma='scale')\n", (706, 721), False, 'from sklearn.svm import SVR\n'), ((744, 795), 'sklearn.ensemble.AdaBoostRegressor', 'AdaBoostRegressor', ([], {'random_state': '(42)', 'n_estimators': '(10)'}), '(random_state=42, n_estimators=10)\n', (761, 795), False, 'from sklearn.ensemble import AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor\n'), ((818, 890), 'sklearn.ensemble.GradientBoostingRegressor', 'GradientBoostingRegressor', ([], {'random_state': '(42)', 'max_depth': '(3)', 'n_estimators': '(10)'}), '(random_state=42, max_depth=3, n_estimators=10)\n', (843, 890), False, 'from sklearn.ensemble import AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor\n'), ((913, 981), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(10)', 'random_state': '(42)', 'max_depth': '(3)'}), '(n_estimators=10, random_state=42, max_depth=3)\n', (934, 981), False, 'from sklearn.ensemble import AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor\n'), ((1009, 1074), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'solver': '"""lbfgs"""', 'max_iter': '(100)', 'random_state': '(42)'}), "(solver='lbfgs', max_iter=100, random_state=42)\n", (1027, 1074), False, 'from sklearn.linear_model import LogisticRegression\n'), ((1101, 1133), 'sklearn.svm.SVC', 'SVC', ([], {'gamma': '"""scale"""', 'max_iter': '(100)'}), "(gamma='scale', max_iter=100)\n", (1104, 1133), False, 'from sklearn.svm import SVC\n'), ((1160, 1212), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {'random_state': '(42)', 'n_estimators': '(10)'}), '(random_state=42, n_estimators=10)\n', (1178, 1212), False, 'from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier\n'), ((1239, 1312), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'random_state': '(42)', 'max_depth': '(3)', 'n_estimators': '(10)'}), '(random_state=42, max_depth=3, n_estimators=10)\n', (1265, 1312), False, 'from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier\n'), ((1339, 1408), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(10)', 'random_state': '(42)', 'max_depth': '(3)'}), '(n_estimators=10, random_state=42, max_depth=3)\n', (1361, 1408), False, 'from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier\n'), ((1451, 1479), 'vaex.ml.datasets.load_iris', 'vaex.ml.datasets.load_iris', ([], {}), '()\n', (1477, 1479), False, 'import vaex\n'), ((1813, 1890), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['test.pred.values', 'prediction'], {'decimal': '(5)'}), '(test.pred.values, prediction, decimal=5)\n', (1849, 1890), True, 'import numpy as np\n'), ((2120, 2148), 'vaex.ml.datasets.load_iris', 'vaex.ml.datasets.load_iris', ([], {}), '()\n', (2146, 2148), False, 'import vaex\n'), ((2635, 2663), 'vaex.ml.datasets.load_iris', 'vaex.ml.datasets.load_iris', ([], {}), '()\n', (2661, 2663), False, 'import vaex\n'), ((2876, 2901), 'vaex.ml.Pipeline', 'vaex.ml.Pipeline', (['[model]'], {}), '([model])\n', (2892, 2901), False, 'import vaex\n'), ((3188, 3213), 'vaex.ml.Pipeline', 'vaex.ml.Pipeline', (['[model]'], {}), '([model])\n', (3204, 3213), False, 'import vaex\n'), ((3375, 3403), 'vaex.ml.datasets.load_iris', 'vaex.ml.datasets.load_iris', ([], {}), '()\n', (3401, 3403), False, 'import vaex\n'), ((4119, 4147), 'vaex.ml.datasets.load_iris', 'vaex.ml.datasets.load_iris', ([], {}), '()\n', (4145, 4147), False, 'import vaex\n'), ((4259, 4316), 'numpy.sqrt', 'np.sqrt', (['(train.sepal_length ** 2 + train.sepal_width ** 2)'], {}), '(train.sepal_length ** 2 + train.sepal_width ** 2)\n', (4266, 4316), True, 'import numpy as np\n'), ((4832, 4861), 'vaex.ml.Pipeline', 'vaex.ml.Pipeline', (['[st, model]'], {}), '([st, model])\n', (4848, 4861), False, 'import vaex\n'), ((5229, 5293), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['pred', 'df_trans.pred.values'], {}), '(pred, df_trans.pred.values)\n', (5265, 5293), True, 'import numpy as np\n'), ((5361, 5392), 'vaex.ml.datasets.load_titanic', 'vaex.ml.datasets.load_titanic', ([], {}), '()\n', (5390, 5392), False, 'import vaex\n'), ((3727, 3799), 'vaex.ml.sklearn.SKLearnPredictor', 'SKLearnPredictor', ([], {'model': 'model', 'features': 'features', 'prediction_name': '"""pred"""'}), "(model=model, features=features, prediction_name='pred')\n", (3743, 3799), False, 'from vaex.ml.sklearn import SKLearnPredictor\n'), ((3993, 4068), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['test.pred.values', 'skl_pred'], {'decimal': '(5)'}), '(test.pred.values, skl_pred, decimal=5)\n', (4029, 4068), True, 'import numpy as np\n'), ((5699, 5771), 'vaex.ml.sklearn.SKLearnPredictor', 'SKLearnPredictor', ([], {'model': 'model', 'features': 'features', 'prediction_name': '"""pred"""'}), "(model=model, features=features, prediction_name='pred')\n", (5715, 5771), False, 'from vaex.ml.sklearn import SKLearnPredictor\n'), ((5974, 6010), 'numpy.all', 'np.all', (['(skl_pred == test.pred.values)'], {}), '(skl_pred == test.pred.values)\n', (5980, 6010), True, 'import numpy as np\n'), ((1636, 1654), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (1652, 1654), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n'), ((2420, 2438), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (2436, 2438), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n'), ((2763, 2781), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (2779, 2781), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n'), ((3036, 3054), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (3052, 3054), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n'), ((4690, 4708), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (4706, 4708), False, 'from sklearn.linear_model import LinearRegression, Ridge, Lasso\n')]
|
from abc import ABCMeta, abstractmethod
import ConnectTools as CT
import numpy as np
# Class to control connectivity maps / to determine whether transitions have occured
class StructureMap:
def __init__(self, mol):
self.criteriaMet = False
@abstractmethod
def reinitialise(self, mol):
pass
@abstractmethod
def update(self, mol):
pass
class BBFS(StructureMap):
def __init__(self,mol):
self.dRef = CT.refBonds(mol)
self.C = CT.bondMatrix(self.dRef, mol)
self.transitionIndices = np.zeros(3)
self.criteriaMet = False
@abstractmethod
def update(self, mol):
size = len(mol.get_positions())
self.criteriaMet = False
# Loop over all atoms
for i in range(0,size):
bond = 0
nonbond = 1000
a_1 = 0
a_2 = 0
for j in range(0,size):
# Get distances between all atoms bonded to i
if self.C[i][j] == 1:
newbond = max(bond,mol.get_distance(i,j)/(self.dRef[i][j]*1.2))
#Store Index corresponding to current largest bond
if newbond > bond:
a_1 = j
bond = newbond
elif self.C[i][j] == 0:
newnonbond = min(nonbond, mol.get_distance(i,j)/(self.dRef[i][j]*1.2))
if newnonbond < nonbond:
a_2 = j
nonbond = newnonbond
if bond > nonbond:
self.criteriaMet = True
self.ind1 = a_1 + 1
self.ind2 = i + 1
self.ind3 = a_2 + 1
self.transitionIndices = [a_1, i, a_2]
@abstractmethod
def reinitialise(self, mol):
self.dRef = CT.refBonds(mol)
self.C = CT.bondMatrix(self.dRef, mol)
self.transitionIdices = np.zeros(3)
def ReactionType(self, mol):
oldbonds = np.count_nonzero(self.C)
self.dRef = CT.refBonds(mol)
self.C = CT.bondMatrix(self.dRef, mol)
newbonds = np.count_nonzero(self.C)
if oldbonds > newbonds:
reacType = 'Dissociation'
if oldbonds < newbonds:
reacType = 'Association'
if oldbonds == newbonds:
reacType = 'Isomerisation'
return reacType
|
[
"numpy.count_nonzero",
"ConnectTools.refBonds",
"numpy.zeros",
"ConnectTools.bondMatrix"
] |
[((466, 482), 'ConnectTools.refBonds', 'CT.refBonds', (['mol'], {}), '(mol)\n', (477, 482), True, 'import ConnectTools as CT\n'), ((500, 529), 'ConnectTools.bondMatrix', 'CT.bondMatrix', (['self.dRef', 'mol'], {}), '(self.dRef, mol)\n', (513, 529), True, 'import ConnectTools as CT\n'), ((563, 574), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (571, 574), True, 'import numpy as np\n'), ((1832, 1848), 'ConnectTools.refBonds', 'CT.refBonds', (['mol'], {}), '(mol)\n', (1843, 1848), True, 'import ConnectTools as CT\n'), ((1866, 1895), 'ConnectTools.bondMatrix', 'CT.bondMatrix', (['self.dRef', 'mol'], {}), '(self.dRef, mol)\n', (1879, 1895), True, 'import ConnectTools as CT\n'), ((1928, 1939), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1936, 1939), True, 'import numpy as np\n'), ((1993, 2017), 'numpy.count_nonzero', 'np.count_nonzero', (['self.C'], {}), '(self.C)\n', (2009, 2017), True, 'import numpy as np\n'), ((2038, 2054), 'ConnectTools.refBonds', 'CT.refBonds', (['mol'], {}), '(mol)\n', (2049, 2054), True, 'import ConnectTools as CT\n'), ((2072, 2101), 'ConnectTools.bondMatrix', 'CT.bondMatrix', (['self.dRef', 'mol'], {}), '(self.dRef, mol)\n', (2085, 2101), True, 'import ConnectTools as CT\n'), ((2121, 2145), 'numpy.count_nonzero', 'np.count_nonzero', (['self.C'], {}), '(self.C)\n', (2137, 2145), True, 'import numpy as np\n')]
|
from ..utils import get_data_filename
#TODO add need off omm parmed decorator: https://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators
def minimise_energy_all_confs(mol, models = None, epsilon = 4, allow_undefined_stereo = True, **kwargs ):
from simtk import unit
from simtk.openmm import LangevinIntegrator
from simtk.openmm.app import Simulation, HBonds, NoCutoff
from rdkit import Chem
from rdkit.Geometry import Point3D
import mlddec
import copy
import tqdm
mol = Chem.AddHs(mol, addCoords = True)
if models is None:
models = mlddec.load_models(epsilon)
charges = mlddec.get_charges(mol, models)
from openforcefield.utils.toolkits import RDKitToolkitWrapper, ToolkitRegistry
from openforcefield.topology import Molecule, Topology
from openforcefield.typing.engines.smirnoff import ForceField
# from openforcefield.typing.engines.smirnoff.forcefield import PME
import parmed
import numpy as np
forcefield = ForceField(get_data_filename("modified_smirnoff99Frosst.offxml")) #FIXME better way of identifying file location
tmp = copy.deepcopy(mol)
tmp.RemoveAllConformers() #XXX workround for speed beacuse seemingly openforcefield records all conformer informations, which takes a long time. but I think this is a ill-practice
molecule = Molecule.from_rdkit(tmp, allow_undefined_stereo = allow_undefined_stereo)
molecule.partial_charges = unit.Quantity(np.array(charges), unit.elementary_charge)
topology = Topology.from_molecules(molecule)
openmm_system = forcefield.create_openmm_system(topology, charge_from_molecules= [molecule])
structure = parmed.openmm.topsystem.load_topology(topology.to_openmm(), openmm_system)
system = structure.createSystem(nonbondedMethod=NoCutoff, nonbondedCutoff=1*unit.nanometer, constraints=HBonds)
integrator = LangevinIntegrator(273*unit.kelvin, 1/unit.picosecond, 0.002*unit.picoseconds)
simulation = Simulation(structure.topology, system, integrator)
out_mol = copy.deepcopy(mol)
for i in tqdm.tqdm(range(out_mol.GetNumConformers())):
conf = mol.GetConformer(i)
structure.coordinates = unit.Quantity(np.array([np.array(conf.GetAtomPosition(i)) for i in range(mol.GetNumAtoms())]), unit.angstroms)
simulation.context.setPositions(structure.positions)
simulation.minimizeEnergy()
# simulation.step(1)
coords = simulation.context.getState(getPositions = True).getPositions(asNumpy = True).value_in_unit(unit.angstrom)
conf = out_mol.GetConformer(i)
for j in range(out_mol.GetNumAtoms()):
conf.SetAtomPosition(j, Point3D(*coords[j]))
return out_mol
# def parameterise_molecule(mol, which_conf = -1, models = None, epsilon = 4, allow_undefined_stereo = True, **kwargs):
# """
# which_conf : when -1 write out multiple parmed structures, one for each conformer
# """
# from rdkit import Chem
# import mlddec
# mol = Chem.AddHs(mol, addCoords = True)
#
# if models is None:
# models = mlddec.load_models(epsilon)
# charges = mlddec.get_charges(mol, models)
#
#
# from openforcefield.utils.toolkits import RDKitToolkitWrapper, ToolkitRegistry
# from openforcefield.topology import Molecule, Topology
# from openforcefield.typing.engines.smirnoff import ForceField
# # from openforcefield.typing.engines.smirnoff.forcefield import PME
#
# import parmed
# import numpy as np
#
# forcefield = ForceField('test_forcefields/smirnoff99Frosst.offxml')
#
# # molecule = Molecule.from_rdkit(mol, allow_undefined_stereo = True)
# molecule = Molecule.from_rdkit(mol, allow_undefined_stereo = allow_undefined_stereo)
# molecule.partial_charges = Quantity(np.array(charges), elementary_charge)
# topology = Topology.from_molecules(molecule)
# openmm_system = forcefield.create_openmm_system(topology, charge_from_molecules= [molecule])
#
#
# if which_conf == -1 : #TODO better design here
# for i in range(mol.GetNumConformers()):
# conf = mol.GetConformer(which_conf)
# positions = Quantity(np.array([np.array(conf.GetAtomPosition(i)) for i in range(mol.GetNumAtoms())]), angstroms)
# structure = parmed.openmm.topsystem.load_topology(topology.to_openmm(), openmm_system, positions)
# yield structure
#
# else:
# conf = mol.GetConformer(which_conf)
# positions = Quantity(np.array([np.array(conf.GetAtomPosition(i)) for i in range(mol.GetNumAtoms())]), angstroms)
#
# structure = parmed.openmm.topsystem.load_topology(topology.to_openmm(), openmm_system, positions)
# yield structure
#
# def parameterise_molecule_am1bcc(mol, which_conf = 0, allow_undefined_stereo = True, **kwargs):
# from rdkit import Chem
# mol = Chem.AddHs(mol, addCoords = True)
#
# from openforcefield.topology import Molecule, Topology
# from openforcefield.typing.engines.smirnoff import ForceField
# # from openforcefield.typing.engines.smirnoff.forcefield import PME
# from openforcefield.utils.toolkits import AmberToolsToolkitWrapper
#
# import parmed
# import numpy as np
#
# forcefield = ForceField('test_forcefields/smirnoff99Frosst.offxml')
#
# # molecule = Molecule.from_rdkit(mol, allow_undefined_stereo = True)
# molecule = Molecule.from_rdkit(mol, allow_undefined_stereo = allow_undefined_stereo)
#
# molecule.compute_partial_charges_am1bcc(toolkit_registry = AmberToolsToolkitWrapper())
#
# topology = Topology.from_molecules(molecule)
# openmm_system = forcefield.create_openmm_system(topology, charge_from_molecules= [molecule])
#
#
# conf = mol.GetConformer(which_conf)
# positions = Quantity(np.array([np.array(conf.GetAtomPosition(i)) for i in range(mol.GetNumAtoms())]), angstroms)
#
# structure = parmed.openmm.topsystem.load_topology(topology.to_openmm(), openmm_system, positions)
# return structure
#
#
# def minimise_energy(structure, output_name, **kwargs):
# # structure = parameterise_molecule_am1bcc(mol, **kwargs)
#
# system = structure.createSystem(nonbondedMethod=NoCutoff, nonbondedCutoff=1*nanometer, constraints=HBonds)
#
# integrator = LangevinIntegrator(273*kelvin, 1/picosecond, 0.002*picoseconds)
# simulation = Simulation(structure.topology, system, integrator)
# simulation.context.setPositions(structure.positions)
#
# simulation.minimizeEnergy()
#
# simulation.reporters.append(PDBReporter(output_name, 1))
# simulation.step(1)
# return simulation
#
# def simulate_vacuum(structure, output_name, num_frames = 10):
# """
# writes out every 10 ps
# """
# # structure = parameterise_molecule(mol)
#
# system = structure.createSystem(nonbondedMethod=NoCutoff, nonbondedCutoff=1*nanometer, constraints=HBonds)
#
# integrator = LangevinIntegrator(1*kelvin, 1/picosecond, 0.002*picoseconds)
# simulation = Simulation(structure.topology, system, integrator)
# simulation.context.setPositions(structure.positions)
#
#
# simulation.minimizeEnergy(maxIterations = 50)
#
# step = 5000
# # step = 5
# simulation.reporters.append(PDBReporter(output_name, step))
# simulation.step(step * num_frames)
|
[
"copy.deepcopy",
"openforcefield.topology.Molecule.from_rdkit",
"simtk.openmm.app.Simulation",
"rdkit.Geometry.Point3D",
"openforcefield.topology.Topology.from_molecules",
"mlddec.load_models",
"numpy.array",
"mlddec.get_charges",
"rdkit.Chem.AddHs",
"simtk.openmm.LangevinIntegrator"
] |
[((534, 565), 'rdkit.Chem.AddHs', 'Chem.AddHs', (['mol'], {'addCoords': '(True)'}), '(mol, addCoords=True)\n', (544, 565), False, 'from rdkit import Chem\n'), ((652, 683), 'mlddec.get_charges', 'mlddec.get_charges', (['mol', 'models'], {}), '(mol, models)\n', (670, 683), False, 'import mlddec\n'), ((1149, 1167), 'copy.deepcopy', 'copy.deepcopy', (['mol'], {}), '(mol)\n', (1162, 1167), False, 'import copy\n'), ((1368, 1439), 'openforcefield.topology.Molecule.from_rdkit', 'Molecule.from_rdkit', (['tmp'], {'allow_undefined_stereo': 'allow_undefined_stereo'}), '(tmp, allow_undefined_stereo=allow_undefined_stereo)\n', (1387, 1439), False, 'from openforcefield.topology import Molecule, Topology\n'), ((1545, 1578), 'openforcefield.topology.Topology.from_molecules', 'Topology.from_molecules', (['molecule'], {}), '(molecule)\n', (1568, 1578), False, 'from openforcefield.topology import Molecule, Topology\n'), ((1904, 1993), 'simtk.openmm.LangevinIntegrator', 'LangevinIntegrator', (['(273 * unit.kelvin)', '(1 / unit.picosecond)', '(0.002 * unit.picoseconds)'], {}), '(273 * unit.kelvin, 1 / unit.picosecond, 0.002 * unit.\n picoseconds)\n', (1922, 1993), False, 'from simtk.openmm import LangevinIntegrator\n'), ((2000, 2050), 'simtk.openmm.app.Simulation', 'Simulation', (['structure.topology', 'system', 'integrator'], {}), '(structure.topology, system, integrator)\n', (2010, 2050), False, 'from simtk.openmm.app import Simulation, HBonds, NoCutoff\n'), ((2066, 2084), 'copy.deepcopy', 'copy.deepcopy', (['mol'], {}), '(mol)\n', (2079, 2084), False, 'import copy\n'), ((610, 637), 'mlddec.load_models', 'mlddec.load_models', (['epsilon'], {}), '(epsilon)\n', (628, 637), False, 'import mlddec\n'), ((1487, 1504), 'numpy.array', 'np.array', (['charges'], {}), '(charges)\n', (1495, 1504), True, 'import numpy as np\n'), ((2698, 2717), 'rdkit.Geometry.Point3D', 'Point3D', (['*coords[j]'], {}), '(*coords[j])\n', (2705, 2717), False, 'from rdkit.Geometry import Point3D\n')]
|
import sys
import math
from PIL import Image
import numpy as np
def main(path, input_width, input_height):
input_width = int(input_width)
input_height = int(input_height)
im = Image.open(path)
im = im.resize((128,128), Image.ANTIALIAS)
width, height = im.size
horizontal_num = math.ceil(input_width / width)
vertical_num = math.ceil(input_height / height)
a = range(0, horizontal_num)
lst = [path for i in a]
images = map(Image.open, lst)
widths, heights = zip(*(i.size for i in images))
new_im = Image.new('RGB', (input_width, input_height))
x_offset = 0
y_offset = 0
images0 = map(Image.open, lst)
for y in range(0, horizontal_num):
for x in range(0, vertical_num):
new_im.paste(im, (x_offset, y_offset))
y_offset += im.size[1]
x_offset += im.size[0]
y_offset = 0
img_array = np.array(new_im)
return img_array
# new_im.save('cropped_1.jpg')
if __name__ == '__main__':
path = sys.argv[1]
input_width = sys.argv[2]
input_height = sys.argv[3]
main(path, input_width, input_height)
|
[
"math.ceil",
"PIL.Image.new",
"numpy.array",
"PIL.Image.open"
] |
[((194, 210), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (204, 210), False, 'from PIL import Image\n'), ((312, 342), 'math.ceil', 'math.ceil', (['(input_width / width)'], {}), '(input_width / width)\n', (321, 342), False, 'import math\n'), ((362, 394), 'math.ceil', 'math.ceil', (['(input_height / height)'], {}), '(input_height / height)\n', (371, 394), False, 'import math\n'), ((563, 608), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(input_width, input_height)'], {}), "('RGB', (input_width, input_height))\n", (572, 608), False, 'from PIL import Image\n'), ((915, 931), 'numpy.array', 'np.array', (['new_im'], {}), '(new_im)\n', (923, 931), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
import logging
import numpy as np
from sklearn.metrics import accuracy_score
from lichee import plugin
from .metrics_base import BaseMetrics
@plugin.register_plugin(plugin.PluginType.MODULE_METRICS, "Accuracy")
class AccuracyMetrics(BaseMetrics):
"""define accuracy metric that measures single-label or multi-label classification problem
Attributes
----------
total_labels: List[np.ndarray]
collected classification labels
total_logits: List[np.ndarray]
collected classification logits
"""
def __init__(self):
super(AccuracyMetrics, self).__init__()
def calc(self, threshold=0.5):
"""accumulate classification results and calculate accuracy metric value
Parameters
----------
threshold: float
classification threshold
Returns
------
res_info: Dict[str, Dict[str, float]]
a dict containing classification accuracy,
number of correct samples
and number of total samples
"""
labels = np.concatenate(self.total_labels, axis=0)
logits = np.concatenate(self.total_logits, axis=0)
if len(labels.shape) == 2:
# multilabel
pred = (logits >= threshold)
elif len(labels.shape) == 1:
pred = np.argmax(logits, axis=1)
else:
raise Exception("AccuracyMetrics: not supported labels")
correct_sum = int(accuracy_score(labels, pred, normalize=False))
num_sample = int(pred.shape[0])
logging.info("Acc. (Correct/Total): {:.4f} ({}/{}) ".format(correct_sum / num_sample, correct_sum, num_sample))
res_info = {
"Acc": {
"value": correct_sum / num_sample,
"correct": correct_sum,
"total": num_sample
}
}
self.total_labels, self.total_logits = [], []
return res_info
def name(self):
return "Accuracy"
|
[
"sklearn.metrics.accuracy_score",
"lichee.plugin.register_plugin",
"numpy.concatenate",
"numpy.argmax"
] |
[((169, 237), 'lichee.plugin.register_plugin', 'plugin.register_plugin', (['plugin.PluginType.MODULE_METRICS', '"""Accuracy"""'], {}), "(plugin.PluginType.MODULE_METRICS, 'Accuracy')\n", (191, 237), False, 'from lichee import plugin\n'), ((1088, 1129), 'numpy.concatenate', 'np.concatenate', (['self.total_labels'], {'axis': '(0)'}), '(self.total_labels, axis=0)\n', (1102, 1129), True, 'import numpy as np\n'), ((1147, 1188), 'numpy.concatenate', 'np.concatenate', (['self.total_logits'], {'axis': '(0)'}), '(self.total_logits, axis=0)\n', (1161, 1188), True, 'import numpy as np\n'), ((1483, 1528), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['labels', 'pred'], {'normalize': '(False)'}), '(labels, pred, normalize=False)\n', (1497, 1528), False, 'from sklearn.metrics import accuracy_score\n'), ((1347, 1372), 'numpy.argmax', 'np.argmax', (['logits'], {'axis': '(1)'}), '(logits, axis=1)\n', (1356, 1372), True, 'import numpy as np\n')]
|
from django.shortcuts import render
from django.http import HttpResponse
from .models import Customer,Drone,Order, Depot
import pandas as pd
import numpy as np
from scipy.spatial.distance import squareform, pdist
from haversine import haversine
from .vrp import *
# Create your views here.
def maps(request):
n = len(Customer.objects.all())
drone = Drone.objects.get(name = "Test drone")
depot = Depot.objects.get(name = "Test Depot")
depot_lat = depot.lat
depot_long = depot.long
input_data={}
input_data['instance_name'] = "Django integration trial"
input_data['Number_of_customers'] = n
input_data['max_vehicle_number'] = drone.number
input_data['vehicle_capacity'] = drone.capacity
coords={}
loc = {}
coords["lat"]=depot_lat
coords["long"]=depot_long
loc["coordinates"] = coords.copy()
loc["demand"] = 0
input_data['depot']=loc.copy()
all_points = np.array([[coords["lat"],coords["long"]]])
# print(input_data)
customers = []
for order in Order.objects.all():
coords["lat"]=order.customer.lat
coords["long"] = order.customer.long
customers.append([order.customer.lat,order.customer.long])
loc["coordinates"] = coords.copy()
loc["demand"]=order.weight
input_data['customer_{}'.format(order.order_id)]=loc.copy()
all_points = np.append(all_points,[[coords["lat"], coords["long"]]],axis=0)
print(input_data)
# Calculating distance matrix
dist_matrix = squareform(pdist(all_points, metric=haversine))
input_data["distance_matrix"] = dist_matrix
# print(dist_matrix)
drone_params = {
'weight': drone.weight,
'capacity': drone.capacity,
'number': drone.number,
'bat_consum_perkm_perkg': drone.battery_consumption_perKM_perKg,
'takeoff_landing': drone.takeoff_landing_consumption,
}
nsgaObj = nsgaAlgo(input_data,drone_params)
# Setting internal variables
print(nsgaObj.json_instance)
# Running Algorithm
route=[]
if request.method == "POST":
if "calculation" in request.POST:
nsgaObj.runMain()
route = nsgaObj.get_solution()
request.session['route'] = route
request.session.modified = True
elif "animation" in request.POST:
route = request.session['route']
colorset=["#000000","#0066ff","#cc0000","#009900","#6600cc","#cc00cc","#009999"]
route_with_color = zip(route,colorset)
context ={
"route": route,
"depot": [depot_lat,depot_long],
"num_of_drones": len(route),
"customers": customers,
"route_with_color": route_with_color,
}
return render(request,'maps.html',context = context)
# return HttpResponse(str(route_with_color))
def index(request):
drone = Drone.objects.get(name="Test drone")
depot = Depot.objects.get(name="Test Depot")
payload_capacity = drone.capacity - drone.weight
if request.method == "POST":
print(request.POST)
if "update_drone" in request.POST:
drone.battery = request.POST.get("battery")
drone.weight = request.POST.get("weight")
drone.capacity = float(request.POST.get("capacity"))+float(drone.weight)
drone.battery_consumption_perKM_perKg = request.POST.get("battery_consumption")
drone.takeoff_landing_consumption = request.POST.get("takeofflanding")
drone.number = request.POST.get("number")
drone.save()
payload_capacity = request.POST.get("capacity")
elif "update_warehouse" in request.POST:
depot.lat = request.POST.get("lat")
depot.long = request.POST.get("long")
depot.save()
depot_lat = depot.lat
depot_long = depot.long
return render(request,'index.html',context={
"drone":drone,
"payload_capacity": payload_capacity,
"depot_lat":depot_lat,
"depot_long":depot_long,
})
def warehouse(request):
return render(request,'profile.html',context={})
def orders(request):
orders = Order.objects.all()
return render(request,'table.html',context={"orders": orders})
|
[
"django.shortcuts.render",
"numpy.append",
"numpy.array",
"scipy.spatial.distance.pdist"
] |
[((926, 969), 'numpy.array', 'np.array', (["[[coords['lat'], coords['long']]]"], {}), "([[coords['lat'], coords['long']]])\n", (934, 969), True, 'import numpy as np\n'), ((2708, 2753), 'django.shortcuts.render', 'render', (['request', '"""maps.html"""'], {'context': 'context'}), "(request, 'maps.html', context=context)\n", (2714, 2753), False, 'from django.shortcuts import render\n'), ((3826, 3973), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {'context': "{'drone': drone, 'payload_capacity': payload_capacity, 'depot_lat':\n depot_lat, 'depot_long': depot_long}"}), "(request, 'index.html', context={'drone': drone, 'payload_capacity':\n payload_capacity, 'depot_lat': depot_lat, 'depot_long': depot_long})\n", (3832, 3973), False, 'from django.shortcuts import render\n'), ((4040, 4083), 'django.shortcuts.render', 'render', (['request', '"""profile.html"""'], {'context': '{}'}), "(request, 'profile.html', context={})\n", (4046, 4083), False, 'from django.shortcuts import render\n'), ((4148, 4205), 'django.shortcuts.render', 'render', (['request', '"""table.html"""'], {'context': "{'orders': orders}"}), "(request, 'table.html', context={'orders': orders})\n", (4154, 4205), False, 'from django.shortcuts import render\n'), ((1370, 1434), 'numpy.append', 'np.append', (['all_points', "[[coords['lat'], coords['long']]]"], {'axis': '(0)'}), "(all_points, [[coords['lat'], coords['long']]], axis=0)\n", (1379, 1434), True, 'import numpy as np\n'), ((1519, 1554), 'scipy.spatial.distance.pdist', 'pdist', (['all_points'], {'metric': 'haversine'}), '(all_points, metric=haversine)\n', (1524, 1554), False, 'from scipy.spatial.distance import squareform, pdist\n')]
|
#! /usr/bin/env python
import macrodensity as md
import math
import numpy as np
import matplotlib.pyplot as plt
#------------------------------------------------------------------
# READING
# Get the two potentials and change them to a planar average.
# This section should not be altered
#------------------------------------------------------------------
# SLAB
vasp_pot, NGX, NGY, NGZ, Lattice = md.read_vasp_density('CHGCAR.Slab')
mag_a,mag_b,mag_c,vec_a,vec_b,vec_c = md.matrix_2_abc(Lattice)
resolution_x = mag_a/NGX
resolution_y = mag_b/NGY
resolution_z = mag_c/NGZ
Volume = md.get_volume(vec_a,vec_b,vec_c)
grid_pot_slab, electrons_slab = md.density_2_grid(vasp_pot,NGX,NGY,NGZ,True,Volume)
# Save the lattce vectors for use later
Vector_A = [vec_a,vec_b,vec_c]
#----------------------------------------------------------------------------------
# CONVERT TO PLANAR DENSITIES
#----------------------------------------------------------------------------------
planar_slab = md.planar_average(grid_pot_slab,NGX,NGY,NGZ)
# BULK
vasp_pot, NGX, NGY, NGZ, Lattice = md.read_vasp_density('CHGCAR.Bulk')
mag_a,mag_b,mag_c,vec_a,vec_b,vec_c = md.matrix_2_abc(Lattice)
resolution_x = mag_a/NGX
resolution_y = mag_b/NGY
resolution_z = mag_c/NGZ
# Save the lattce vectors for use later
Vector_B = [vec_a,vec_b,vec_c]
Volume = md.get_volume(vec_a,vec_b,vec_c)
#----------------------------------------------------------------------------------
# CONVERT TO PLANAR DENSITIES
#----------------------------------------------------------------------------------
grid_pot_bulk, electrons_bulk = md.density_2_grid(vasp_pot,NGX,NGY,NGZ,True,Volume)
planar_bulk = md.planar_average(grid_pot_bulk,NGX,NGY,NGZ)
#----------------------------------------------------------------------------------
# FINISHED READING
#----------------------------------------------------------------------------------
# GET RATIO OF NUMBERS OF ELECTRONS
#----------------------------------------------------------------------------------
elect_ratio = int(electrons_slab/electrons_bulk)
#----------------------------------------------------------------------------------
# SPLINE THE TWO GENERATING A DISTANCE ON ABSCISSA
#----------------------------------------------------------------------------------
slab, bulk = md.matched_spline_generate(planar_slab,planar_bulk,Vector_A[2],Vector_B[1])
#----------------------------------------------------------------------------------
# EXTEND THE BULK POTENTIAL TO MATCH THE ELECTRON NUMBERS
#----------------------------------------------------------------------------------
bulk = md.extend_potential(bulk,elect_ratio,Vector_B[1])
#----------------------------------------------------------------------------------
# MATCH THE RESOLUTIONS OF THE TWO
#----------------------------------------------------------------------------------
slab, bulk = md.match_resolution(slab, bulk)
plt.plot(bulk[:,1])
plt.show()
#----------------------------------------------------------------------------------
# TRANSLATE THE BULK POTENTIAL TO GET OVERLAP
#----------------------------------------------------------------------------------
bulk_trans = md.translate_grid(bulk, 3.13,True,np.dot(Vector_B[1],elect_ratio),0.42)
bulk_trans = md.translate_grid(bulk_trans, 6.57,False,np.dot(Vector_B[1],elect_ratio),0.42)
slab_trans = md.translate_grid(slab, 6.5653,True,Vector_A[2])
#potential_difference = md.diff_potentials(pot_slab_orig,bulk_extd,10,40,tol=0.04)
#plt.plot(bulk[:,0],bulk[:,1])
## PLOT THE POTENTIALS, THIS IS A CHECK THAT THEY HAVE ALIGNED CORRECTLY
#plt.plot(bulk_trans[:,0],bulk_trans[:,1],)
#plt.plot(slab_trans[:,0],slab_trans[:,1],)
#plt.show()
##------------------------------------------------------------------
## SET THE CHARGE DENSITY TO ZERO OUTSIDE THE BULK
bulk_vacuum = md.bulk_vac(bulk_trans, slab_trans)
plt.plot(bulk_vacuum[:,0],bulk_vacuum[:,1])
plt.plot(slab_trans[:,0],slab_trans[:,1],)
plt.show()
# GET THE DIFFERENCES (within a numerical tolerence)
difference = md.subs_potentials(slab_trans,bulk_vacuum,tol=0.01)
difference = md.spline_generate(difference)
plt.plot(difference[:,0],difference[:,1])
#plt.plot(difference[:,0],difference[:,1])
plt.show()
|
[
"macrodensity.matrix_2_abc",
"macrodensity.translate_grid",
"macrodensity.get_volume",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"macrodensity.match_resolution",
"macrodensity.matched_spline_generate",
"macrodensity.read_vasp_density",
"macrodensity.density_2_grid",
"macrodensity.extend_potential",
"macrodensity.bulk_vac",
"macrodensity.subs_potentials",
"macrodensity.spline_generate",
"macrodensity.planar_average",
"numpy.dot"
] |
[((406, 441), 'macrodensity.read_vasp_density', 'md.read_vasp_density', (['"""CHGCAR.Slab"""'], {}), "('CHGCAR.Slab')\n", (426, 441), True, 'import macrodensity as md\n'), ((480, 504), 'macrodensity.matrix_2_abc', 'md.matrix_2_abc', (['Lattice'], {}), '(Lattice)\n', (495, 504), True, 'import macrodensity as md\n'), ((589, 623), 'macrodensity.get_volume', 'md.get_volume', (['vec_a', 'vec_b', 'vec_c'], {}), '(vec_a, vec_b, vec_c)\n', (602, 623), True, 'import macrodensity as md\n'), ((654, 710), 'macrodensity.density_2_grid', 'md.density_2_grid', (['vasp_pot', 'NGX', 'NGY', 'NGZ', '(True)', 'Volume'], {}), '(vasp_pot, NGX, NGY, NGZ, True, Volume)\n', (671, 710), True, 'import macrodensity as md\n'), ((989, 1036), 'macrodensity.planar_average', 'md.planar_average', (['grid_pot_slab', 'NGX', 'NGY', 'NGZ'], {}), '(grid_pot_slab, NGX, NGY, NGZ)\n', (1006, 1036), True, 'import macrodensity as md\n'), ((1076, 1111), 'macrodensity.read_vasp_density', 'md.read_vasp_density', (['"""CHGCAR.Bulk"""'], {}), "('CHGCAR.Bulk')\n", (1096, 1111), True, 'import macrodensity as md\n'), ((1150, 1174), 'macrodensity.matrix_2_abc', 'md.matrix_2_abc', (['Lattice'], {}), '(Lattice)\n', (1165, 1174), True, 'import macrodensity as md\n'), ((1330, 1364), 'macrodensity.get_volume', 'md.get_volume', (['vec_a', 'vec_b', 'vec_c'], {}), '(vec_a, vec_b, vec_c)\n', (1343, 1364), True, 'import macrodensity as md\n'), ((1593, 1649), 'macrodensity.density_2_grid', 'md.density_2_grid', (['vasp_pot', 'NGX', 'NGY', 'NGZ', '(True)', 'Volume'], {}), '(vasp_pot, NGX, NGY, NGZ, True, Volume)\n', (1610, 1649), True, 'import macrodensity as md\n'), ((1659, 1706), 'macrodensity.planar_average', 'md.planar_average', (['grid_pot_bulk', 'NGX', 'NGY', 'NGZ'], {}), '(grid_pot_bulk, NGX, NGY, NGZ)\n', (1676, 1706), True, 'import macrodensity as md\n'), ((2292, 2370), 'macrodensity.matched_spline_generate', 'md.matched_spline_generate', (['planar_slab', 'planar_bulk', 'Vector_A[2]', 'Vector_B[1]'], {}), '(planar_slab, planar_bulk, Vector_A[2], Vector_B[1])\n', (2318, 2370), True, 'import macrodensity as md\n'), ((2601, 2652), 'macrodensity.extend_potential', 'md.extend_potential', (['bulk', 'elect_ratio', 'Vector_B[1]'], {}), '(bulk, elect_ratio, Vector_B[1])\n', (2620, 2652), True, 'import macrodensity as md\n'), ((2867, 2898), 'macrodensity.match_resolution', 'md.match_resolution', (['slab', 'bulk'], {}), '(slab, bulk)\n', (2886, 2898), True, 'import macrodensity as md\n'), ((2899, 2919), 'matplotlib.pyplot.plot', 'plt.plot', (['bulk[:, 1]'], {}), '(bulk[:, 1])\n', (2907, 2919), True, 'import matplotlib.pyplot as plt\n'), ((2919, 2929), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2927, 2929), True, 'import matplotlib.pyplot as plt\n'), ((3334, 3384), 'macrodensity.translate_grid', 'md.translate_grid', (['slab', '(6.5653)', '(True)', 'Vector_A[2]'], {}), '(slab, 6.5653, True, Vector_A[2])\n', (3351, 3384), True, 'import macrodensity as md\n'), ((3805, 3840), 'macrodensity.bulk_vac', 'md.bulk_vac', (['bulk_trans', 'slab_trans'], {}), '(bulk_trans, slab_trans)\n', (3816, 3840), True, 'import macrodensity as md\n'), ((3841, 3887), 'matplotlib.pyplot.plot', 'plt.plot', (['bulk_vacuum[:, 0]', 'bulk_vacuum[:, 1]'], {}), '(bulk_vacuum[:, 0], bulk_vacuum[:, 1])\n', (3849, 3887), True, 'import matplotlib.pyplot as plt\n'), ((3885, 3929), 'matplotlib.pyplot.plot', 'plt.plot', (['slab_trans[:, 0]', 'slab_trans[:, 1]'], {}), '(slab_trans[:, 0], slab_trans[:, 1])\n', (3893, 3929), True, 'import matplotlib.pyplot as plt\n'), ((3928, 3938), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3936, 3938), True, 'import matplotlib.pyplot as plt\n'), ((4005, 4058), 'macrodensity.subs_potentials', 'md.subs_potentials', (['slab_trans', 'bulk_vacuum'], {'tol': '(0.01)'}), '(slab_trans, bulk_vacuum, tol=0.01)\n', (4023, 4058), True, 'import macrodensity as md\n'), ((4070, 4100), 'macrodensity.spline_generate', 'md.spline_generate', (['difference'], {}), '(difference)\n', (4088, 4100), True, 'import macrodensity as md\n'), ((4101, 4145), 'matplotlib.pyplot.plot', 'plt.plot', (['difference[:, 0]', 'difference[:, 1]'], {}), '(difference[:, 0], difference[:, 1])\n', (4109, 4145), True, 'import matplotlib.pyplot as plt\n'), ((4191, 4201), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4199, 4201), True, 'import matplotlib.pyplot as plt\n'), ((3191, 3223), 'numpy.dot', 'np.dot', (['Vector_B[1]', 'elect_ratio'], {}), '(Vector_B[1], elect_ratio)\n', (3197, 3223), True, 'import numpy as np\n'), ((3283, 3315), 'numpy.dot', 'np.dot', (['Vector_B[1]', 'elect_ratio'], {}), '(Vector_B[1], elect_ratio)\n', (3289, 3315), True, 'import numpy as np\n')]
|
import numpy as np
keys = np.array(['HX', 'HY', 'A0', 'A1', 'A2', 'A3', 'N', 'E', 'S', 'W', 'THL', 'THR', 'TL', 'TR', 'TL2', 'TR3', 'M' ,'ST', 'SL'])
outputs = {'HX': 0, 'HY': 0, 'A0': 0, 'A1': 0, 'A2': 0, 'A3': 0, 'N': 0, 'E': 0, 'S': 0, 'W': 0, 'THL': 0, 'THR': 0, 'TL': 0, 'TR': 0, 'TL2': 0, 'TR3': 0, 'M': 0, 'ST': 0, 'SL': 0}
def loop_translate(keys, outputs):
new_a = map(outputs.get, keys)
return new_a
print (list(loop_translate(keys, outputs)))
|
[
"numpy.array"
] |
[((27, 154), 'numpy.array', 'np.array', (["['HX', 'HY', 'A0', 'A1', 'A2', 'A3', 'N', 'E', 'S', 'W', 'THL', 'THR', 'TL',\n 'TR', 'TL2', 'TR3', 'M', 'ST', 'SL']"], {}), "(['HX', 'HY', 'A0', 'A1', 'A2', 'A3', 'N', 'E', 'S', 'W', 'THL',\n 'THR', 'TL', 'TR', 'TL2', 'TR3', 'M', 'ST', 'SL'])\n", (35, 154), True, 'import numpy as np\n')]
|
# mlp-attention_03
# {'val_loss': [
# 0.8321127831733865, 0.8149616334763244, 0.8080661035819032, 0.8043228179784596, 0.8002183685173205,
# 0.7972857836676045, 0.793001569427853, 0.7924909000240787, 0.7921270519020359, 0.7874714549603654,
# 0.7854632683025837, 0.7836462063538413, 0.7816860973027518, 0.7811260843474584, 0.7826188791772042,
# 0.7800090469637393, 0.7793066135596607, 0.7784056678202643, 0.7783930039180803, 0.7800617894507442
# ],
# 'val_mean_squared_error': [
# 0.8321127831733865, 0.8149616334763244, 0.8080661035819032, 0.8043228179784596, 0.8002183685173205,
# 0.7972857836676045, 0.793001569427853, 0.7924909000240787, 0.7921270519020359, 0.7874714549603654,
# 0.7854632683025837, 0.7836462063538413, 0.7816860973027518, 0.7811260843474584, 0.7826188791772042,
# 0.7800090469637393, 0.7793066135596607, 0.7784056678202643, 0.7783930039180803, 0.7800617894507442
# ],
# 'loss': [
# 1.2129996511072807, 0.8089207498588716, 0.7925854784378688, 0.7837273693483895, 0.7770178057682471,
# 0.7712283459233497, 0.7657942494154589, 0.7617266936164807, 0.7575358347528671, 0.7536763259070509,
# 0.7502327760970651, 0.746288952394418, 0.7429369581147989, 0.7393621096899098, 0.7362319128615927,
# 0.73318466221791, 0.7307932809421275, 0.7283218859352288, 0.726398458615269, 0.7244027269489683
# ],
# 'mean_squared_error': [
# 1.2129996511072807, 0.8089207498588716, 0.7925854784378688, 0.7837273693483895, 0.7770178057682471,
# 0.7712283459233497, 0.7657942494154589, 0.7617266936164807, 0.7575358347528671, 0.7536763259070509,
# 0.7502327760970651, 0.746288952394418, 0.7429369581147989, 0.7393621096899098, 0.7362319128615927,
# 0.73318466221791, 0.7307932809421275, 0.7283218859352288, 0.726398458615269, 0.7244027269489683
# ]}
# 0.7800090469637393
# 0.8832
from surprise import Dataset
from sklearn.model_selection import train_test_split
from keras.models import Model
from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply
from keras import optimizers, losses, metrics
import numpy as np
def get_data():
data = Dataset.load_builtin('ml-1m')
data_set = data.build_full_trainset()
# print(data_set.n_items)
# print(data_set.n_users)
x = []
y = []
for u, i, r in data_set.all_ratings():
x.append((u, i))
y.append(r)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
return X_train, X_test, y_train, y_test
class Mlp:
def __init__(self):
self.items = 3706
self.users = 6040
def data(self):
X_train, X_test, self.y_train, self.y_test = get_data()
self.X_train_u = []
self.X_train_i = []
self.X_test_u = []
self.X_test_i = []
for u, i in X_train:
self.X_train_u.append(u)
self.X_train_i.append(i)
for u, i in X_test:
self.X_test_u.append(u)
self.X_test_i.append(i)
def inference(self):
u_inputs = Input(shape=(1,), name='u_input_op')
i_inputs = Input(shape=(1,), name='i_input_op')
u_embedding = Embedding(input_dim=self.users, output_dim=32, input_length=1, name='u_embedding_op')(u_inputs)
i_embedding = Embedding(input_dim=self.items, output_dim=32, input_length=1, name='i_embedding_op')(i_inputs)
u_flatten = Flatten(name='u_flatten_op')(u_embedding)
i_flatten = Flatten(name='i_flatten_op')(i_embedding)
attention_u = Dense(32, activation='softmax', name='attention_vec_u')(u_flatten)
attention_u_mul = multiply([u_flatten, attention_u], name='attention_mul_u')
attention_i = Dense(32, activation='softmax', name='attention_vec_i')(i_flatten)
attention_i_mul = multiply([i_flatten, attention_i], name='attention_mul_i')
u_i_concat = concatenate([attention_u_mul, attention_i_mul], name='concat_op')
attention_u_i = Dense(64, activation='softmax', name='attention_vec_u_i')(u_i_concat)
attention_u_i_mul = multiply([u_i_concat, attention_u_i], name='attention_mul_u_i')
dense_1 = Dense(32, activation='relu', name='dense_1_op')(attention_u_i_mul)
dense_2 = Dense(16, activation='relu', name='dense_2_op')(dense_1)
dense_3 = Dense(8, activation='relu', name='dense_3_op')(dense_2)
output = Dense(1, name='output_op')(dense_3)
self.model = Model(inputs=[u_inputs, i_inputs], outputs=output)
def compile(self):
self.model.summary()
self.model.compile(
optimizer=optimizers.Adam(),
loss=losses.mean_squared_error,
metrics=[metrics.mean_squared_error]
)
def train(self):
self.his = self.model.fit(
x=[np.asarray(self.X_train_u), np.asarray(self.X_train_i)],
y=np.asarray(self.y_train),
validation_data=([np.asarray(self.X_test_u), np.asarray(self.X_test_i)], np.asarray(self.y_test)),
epochs=20,
batch_size=256
)
def predict(self):
self.model.predict()
def build(self):
self.data()
self.inference()
self.compile()
self.train()
if __name__ == '__main__':
mlp_model = Mlp()
mlp_model.build()
print(mlp_model.his.history)
|
[
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"keras.layers.Flatten",
"surprise.Dataset.load_builtin",
"keras.models.Model",
"keras.optimizers.Adam",
"keras.layers.multiply",
"keras.layers.Dense",
"keras.layers.Embedding",
"keras.layers.Input",
"keras.layers.concatenate"
] |
[((2063, 2092), 'surprise.Dataset.load_builtin', 'Dataset.load_builtin', (['"""ml-1m"""'], {}), "('ml-1m')\n", (2083, 2092), False, 'from surprise import Dataset\n'), ((2344, 2398), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.2)', 'random_state': '(42)'}), '(x, y, test_size=0.2, random_state=42)\n', (2360, 2398), False, 'from sklearn.model_selection import train_test_split\n'), ((2976, 3012), 'keras.layers.Input', 'Input', ([], {'shape': '(1,)', 'name': '"""u_input_op"""'}), "(shape=(1,), name='u_input_op')\n", (2981, 3012), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3032, 3068), 'keras.layers.Input', 'Input', ([], {'shape': '(1,)', 'name': '"""i_input_op"""'}), "(shape=(1,), name='i_input_op')\n", (3037, 3068), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3544, 3602), 'keras.layers.multiply', 'multiply', (['[u_flatten, attention_u]'], {'name': '"""attention_mul_u"""'}), "([u_flatten, attention_u], name='attention_mul_u')\n", (3552, 3602), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3718, 3776), 'keras.layers.multiply', 'multiply', (['[i_flatten, attention_i]'], {'name': '"""attention_mul_i"""'}), "([i_flatten, attention_i], name='attention_mul_i')\n", (3726, 3776), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3798, 3863), 'keras.layers.concatenate', 'concatenate', (['[attention_u_mul, attention_i_mul]'], {'name': '"""concat_op"""'}), "([attention_u_mul, attention_i_mul], name='concat_op')\n", (3809, 3863), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3986, 4049), 'keras.layers.multiply', 'multiply', (['[u_i_concat, attention_u_i]'], {'name': '"""attention_mul_u_i"""'}), "([u_i_concat, attention_u_i], name='attention_mul_u_i')\n", (3994, 4049), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((4358, 4408), 'keras.models.Model', 'Model', ([], {'inputs': '[u_inputs, i_inputs]', 'outputs': 'output'}), '(inputs=[u_inputs, i_inputs], outputs=output)\n', (4363, 4408), False, 'from keras.models import Model\n'), ((3091, 3181), 'keras.layers.Embedding', 'Embedding', ([], {'input_dim': 'self.users', 'output_dim': '(32)', 'input_length': '(1)', 'name': '"""u_embedding_op"""'}), "(input_dim=self.users, output_dim=32, input_length=1, name=\n 'u_embedding_op')\n", (3100, 3181), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3209, 3299), 'keras.layers.Embedding', 'Embedding', ([], {'input_dim': 'self.items', 'output_dim': '(32)', 'input_length': '(1)', 'name': '"""i_embedding_op"""'}), "(input_dim=self.items, output_dim=32, input_length=1, name=\n 'i_embedding_op')\n", (3218, 3299), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3325, 3353), 'keras.layers.Flatten', 'Flatten', ([], {'name': '"""u_flatten_op"""'}), "(name='u_flatten_op')\n", (3332, 3353), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3387, 3415), 'keras.layers.Flatten', 'Flatten', ([], {'name': '"""i_flatten_op"""'}), "(name='i_flatten_op')\n", (3394, 3415), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3451, 3506), 'keras.layers.Dense', 'Dense', (['(32)'], {'activation': '"""softmax"""', 'name': '"""attention_vec_u"""'}), "(32, activation='softmax', name='attention_vec_u')\n", (3456, 3506), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3625, 3680), 'keras.layers.Dense', 'Dense', (['(32)'], {'activation': '"""softmax"""', 'name': '"""attention_vec_i"""'}), "(32, activation='softmax', name='attention_vec_i')\n", (3630, 3680), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((3888, 3945), 'keras.layers.Dense', 'Dense', (['(64)'], {'activation': '"""softmax"""', 'name': '"""attention_vec_u_i"""'}), "(64, activation='softmax', name='attention_vec_u_i')\n", (3893, 3945), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((4068, 4115), 'keras.layers.Dense', 'Dense', (['(32)'], {'activation': '"""relu"""', 'name': '"""dense_1_op"""'}), "(32, activation='relu', name='dense_1_op')\n", (4073, 4115), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((4153, 4200), 'keras.layers.Dense', 'Dense', (['(16)'], {'activation': '"""relu"""', 'name': '"""dense_2_op"""'}), "(16, activation='relu', name='dense_2_op')\n", (4158, 4200), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((4228, 4274), 'keras.layers.Dense', 'Dense', (['(8)'], {'activation': '"""relu"""', 'name': '"""dense_3_op"""'}), "(8, activation='relu', name='dense_3_op')\n", (4233, 4274), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((4301, 4327), 'keras.layers.Dense', 'Dense', (['(1)'], {'name': '"""output_op"""'}), "(1, name='output_op')\n", (4306, 4327), False, 'from keras.layers import Dense, Embedding, Input, concatenate, Flatten, multiply\n'), ((4512, 4529), 'keras.optimizers.Adam', 'optimizers.Adam', ([], {}), '()\n', (4527, 4529), False, 'from keras import optimizers, losses, metrics\n'), ((4777, 4801), 'numpy.asarray', 'np.asarray', (['self.y_train'], {}), '(self.y_train)\n', (4787, 4801), True, 'import numpy as np\n'), ((4706, 4732), 'numpy.asarray', 'np.asarray', (['self.X_train_u'], {}), '(self.X_train_u)\n', (4716, 4732), True, 'import numpy as np\n'), ((4734, 4760), 'numpy.asarray', 'np.asarray', (['self.X_train_i'], {}), '(self.X_train_i)\n', (4744, 4760), True, 'import numpy as np\n'), ((4888, 4911), 'numpy.asarray', 'np.asarray', (['self.y_test'], {}), '(self.y_test)\n', (4898, 4911), True, 'import numpy as np\n'), ((4833, 4858), 'numpy.asarray', 'np.asarray', (['self.X_test_u'], {}), '(self.X_test_u)\n', (4843, 4858), True, 'import numpy as np\n'), ((4860, 4885), 'numpy.asarray', 'np.asarray', (['self.X_test_i'], {}), '(self.X_test_i)\n', (4870, 4885), True, 'import numpy as np\n')]
|
import multiprocessing
import time
import numpy as np
from MulticoreTSNE import MulticoreTSNE as TSNE
from sklearn.decomposition import PCA
from . import image_util
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import BytesIO as StringIO # Python 3.x
def tsne_image(
features, images, img_res=64, res=4000, background_color=255, max_feature_size=-1, labels=None, point_radius=20, n_threads=0
):
"""
Embeds images via tsne into a scatter plot.
Parameters
---------
features: numpy array
Features to visualize
images: list or numpy array
Corresponding images to features.
img_res: int
Resolution to embed images at
res: int
Size of embedding image in pixels
background_color: float or numpy array
Background color value
max_feature_size: int
If input_feature_size > max_feature_size> 0, features are first
reduced using PCA to the desired size.
point_radius: int
Size of the circle for the label image.
n_threads: int
Number of threads to use for t-SNE
labels: List or numpy array if provided
Label for each image for drawing circle image.
"""
features = np.asarray(features, dtype=np.float32)
assert len(features.shape) == 2
print("Starting TSNE")
s_time = time.time()
if 0 < max_feature_size < features.shape[-1]:
pca = PCA(n_components=max_feature_size)
features = pca.fit_transform(features)
if n_threads <= 0:
n_threads = multiprocessing.cpu_count()
model = TSNE(n_components=2, verbose=1, random_state=0, n_jobs=n_threads)
f2d = model.fit_transform(features)
print("TSNE done.", (time.time() - s_time))
print("Starting drawing.")
x_coords = f2d[:, 0]
y_coords = f2d[:, 1]
return image_util.draw_images_at_locations(images, x_coords, y_coords, img_res, res, background_color, labels, point_radius)
|
[
"numpy.asarray",
"time.time",
"sklearn.decomposition.PCA",
"MulticoreTSNE.MulticoreTSNE",
"multiprocessing.cpu_count"
] |
[((1255, 1293), 'numpy.asarray', 'np.asarray', (['features'], {'dtype': 'np.float32'}), '(features, dtype=np.float32)\n', (1265, 1293), True, 'import numpy as np\n'), ((1371, 1382), 'time.time', 'time.time', ([], {}), '()\n', (1380, 1382), False, 'import time\n'), ((1613, 1678), 'MulticoreTSNE.MulticoreTSNE', 'TSNE', ([], {'n_components': '(2)', 'verbose': '(1)', 'random_state': '(0)', 'n_jobs': 'n_threads'}), '(n_components=2, verbose=1, random_state=0, n_jobs=n_threads)\n', (1617, 1678), True, 'from MulticoreTSNE import MulticoreTSNE as TSNE\n'), ((1447, 1481), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'max_feature_size'}), '(n_components=max_feature_size)\n', (1450, 1481), False, 'from sklearn.decomposition import PCA\n'), ((1573, 1600), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (1598, 1600), False, 'import multiprocessing\n'), ((1745, 1756), 'time.time', 'time.time', ([], {}), '()\n', (1754, 1756), False, 'import time\n')]
|
""" 1st phase of the analysis """
from trackme.tracking.analytics.multifactor_analysis import pearson_correlation, pointbiserial_correlation
from typing import List, Tuple
from trackme.tracking.crud.tracking import filter_entries, get_time_horizon, collect_attributes_ids
from trackme.tracking.crud.tracking_validation import is_attribute_binary
from trackme.tracking.models.tracking import TrackingActivity as TA
import statsmodels
import statsmodels.api as sm
from statsmodels.stats.stattools import durbin_watson
import numpy as np
def detect_autocorrelation(input_data: List[int]) -> Tuple[bool, List[float]]:
"""
Compute auto correlation for up to max_lag day difference
Durbin-Watson test is for lag of 1 (0-4 value)
H0 - errors are serially uncorrelated
d = 2 indicates no autocorrelation, << 2 substantial positive, >> substantial negative
"""
is_autocor = True if durbin_watson(input_data) != 2 else False
auocor = statsmodels.tsa.stattools.pacf(input_data, nlags=7, alpha=0.01)[0].tolist()
return is_autocor, auocor
def detect_trend(input_data: List[int]) -> List[float]:
"""
Why using this filter: trend should be as smooth as it gets, thus rather simple model:
https://www.statsmodels.org/dev/generated/statsmodels.tsa.filters.hp_filter.hpfilter.html
Decomposes given time series into trend and cyclic component
via Hodrick-Prescott filter
returns (trend)"""
hpcycles = sm.tsa.filters.hpfilter(input_data, 1600 * 3 ** 4)
return hpcycles[1].tolist()
# TODO: breaking points are a complex topic -> will be implemented in a later feature
# def detect_breaking_points(input_data: List[float]) -> List[int]:
# """based on first derivative collect obvious (hardcoded threshold) changes
# return indexes of the changes in the row
# """
# breaking_points = []
# might_be_break = []
# changes = np.gradient(input_data)
# changes = np.gradient(changes)
# for i in range(2, len(changes) - 1):
# # False = <0, True >0
# previous_sign = False if changes[i - 2] - changes[i - 1] < 0 else True
# current_sign = False if changes[i - 1] - changes[i] < 0 else True
# next_sign = False if changes[i] - changes[i + 1] < 0 else True
# # if sign has changed, it might be a breaking point
# if previous_sign is not current_sign and current_sign is next_sign:
# might_be_break.append(i)
# if len(might_be_break) >= 1:
# breaking_points.append(might_be_break[0])
# for i in range(1, len(might_be_break)):
# if might_be_break[i] > breaking_points[-1] + 21:
# breaking_points.append(might_be_break[i])
#
# x = [i for i in range(0, len(changes))]
# markers_on = breaking_points
# plt.plot(x, changes, "-gD", markevery=markers_on)
# plt.show()
# # TODO: bullet proof this approach. Not entirely sure about this approach =(
# return breaking_points
#
#
# def detect_breaking_points_raw(input_data: List[int]):
# # algo = rpt.Pelt(model="rbf").fit(np.array(input_data))
# # algo = rpt.Window(model="l2").fit(np.array(input_data))
# algo = rpt.Dynp(model="l1", min_size=7, jump=2).fit(np.array(input_data))
# # algo = rpt.Binseg(model="l2").fit(np.array(input_data))
# result = algo.predict(n_bkps=4)
# return result
DAYS = {0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday", 6: "Sunday"}
async def simple_statistics(input_data: List[TA], user_id: int, attribute_id: int) -> dict:
"""When not there is not enough data to run analysis show:
1. structure of estimates - count of entries per day of the week
5. time frame for this attribute - earliest date and latest date of the entry
"""
def base_stats(key: int) -> Tuple[float, float, float]:
"""get min, max and avg for weekday"""
array = []
for item in input_data:
if item.created_at.weekday() == key:
array.append(item.estimation)
if bool(array):
return (min(array), max(array), np.mean(array))
return (0, 0, 0)
res = {}
res["total"] = len(input_data)
estimations = [i.estimation for i in input_data if i.estimation is not None]
binary = False if len(estimations) > 0 else True
tmp = {int(i): 0 for i in DAYS.keys()}
for i in input_data:
weekday = int(i.created_at.weekday())
new_value = tmp[weekday]
tmp[weekday] = new_value + 1
# This probably requires more memory due to duplicate objects stats and later clone
stats = []
for key in tmp.keys():
if not binary:
base = base_stats(key)
stats.append({"count": tmp[key], "min": base[0], "max": base[1], "avg": base[2], "day": DAYS[key]})
else:
stats.append({"count": tmp[key], "day": DAYS[key]})
res["time_structure"] = stats # type: ignore
# get earliest date and latest date from crud
dates = await get_time_horizon(user_id=user_id, attribute_id=attribute_id)
res["start"] = dates[0]
res["end"] = dates[1]
return res
async def collect_report(user_id: int, attribute_id: int) -> dict:
"""detect trend, breaking points"""
res = {}
res["enough_data"] = True
ts_raw = await filter_entries(
user_id=user_id, topics=None, start=None, end=None, attribute=attribute_id, comments=None, ts=True
)
tse = [t.estimation for t in ts_raw if t.estimation is not None]
tsd = [t.created_at for t in ts_raw if t.created_at is not None]
# (arbitrary number) 2 weeks worth of data can show you some dependencies
res["recap"] = await simple_statistics(ts_raw, user_id, attribute_id) # type: ignore
if len(tse) < 2 * 7 + 1:
res["enough_data"] = False
return res
trend = detect_trend(tse)
res["trend"] = [(trend[i], tsd[i]) for i in range(0, len(trend))] # type: ignore
autocor = detect_autocorrelation(tse)
res["autocorrelation"] = {
"is_autocorrelated": autocor[0],
"autocorrelaton_estimates": autocor[1][1:8],
} # type: ignore
# multiple correlations
res["multifactor"] = {} # type: ignore
is_main_factor_binary = await is_attribute_binary(attribute_id, user_id)
if not is_main_factor_binary:
res["multifactor"]["pearson"] = [] # type: ignore
# continuous_factor vs continuous_factors correlation
continuous_factors = await collect_attributes_ids(user_id, binary=False)
for a in continuous_factors:
is_binary = await is_attribute_binary(a, user_id)
if is_binary:
continuous_factors.remove(a)
continuous_factors.remove(attribute_id)
for factor in continuous_factors:
raw_second = await filter_entries(
user_id=user_id, topics=None, start=None, end=None, attribute=factor, comments=None, ts=True
)
res["multifactor"]["pearson"].append({factor: pearson_correlation(ts_raw, raw_second)}) # type: ignore
# continuous_factor vs binary_factors correlation
res["multifactor"]["pbsr"] = [] # type: ignore
binary_factors = await collect_attributes_ids(user_id, binary=True)
for factor in binary_factors:
raw_second = await filter_entries(
user_id=user_id, topics=None, start=None, end=None, attribute=factor, comments=None, ts=True
)
res["multifactor"]["pbsr"].append({factor: pointbiserial_correlation(ts_raw, raw_second)}) # type: ignore
# binary_factors vs binary_factors correlation: TBI
else:
return res
return res
|
[
"trackme.tracking.crud.tracking_validation.is_attribute_binary",
"trackme.tracking.crud.tracking.collect_attributes_ids",
"statsmodels.stats.stattools.durbin_watson",
"trackme.tracking.crud.tracking.get_time_horizon",
"statsmodels.tsa.stattools.pacf",
"trackme.tracking.analytics.multifactor_analysis.pearson_correlation",
"trackme.tracking.crud.tracking.filter_entries",
"numpy.mean",
"trackme.tracking.analytics.multifactor_analysis.pointbiserial_correlation",
"statsmodels.api.tsa.filters.hpfilter"
] |
[((1450, 1500), 'statsmodels.api.tsa.filters.hpfilter', 'sm.tsa.filters.hpfilter', (['input_data', '(1600 * 3 ** 4)'], {}), '(input_data, 1600 * 3 ** 4)\n', (1473, 1500), True, 'import statsmodels.api as sm\n'), ((5008, 5068), 'trackme.tracking.crud.tracking.get_time_horizon', 'get_time_horizon', ([], {'user_id': 'user_id', 'attribute_id': 'attribute_id'}), '(user_id=user_id, attribute_id=attribute_id)\n', (5024, 5068), False, 'from trackme.tracking.crud.tracking import filter_entries, get_time_horizon, collect_attributes_ids\n'), ((5309, 5427), 'trackme.tracking.crud.tracking.filter_entries', 'filter_entries', ([], {'user_id': 'user_id', 'topics': 'None', 'start': 'None', 'end': 'None', 'attribute': 'attribute_id', 'comments': 'None', 'ts': '(True)'}), '(user_id=user_id, topics=None, start=None, end=None,\n attribute=attribute_id, comments=None, ts=True)\n', (5323, 5427), False, 'from trackme.tracking.crud.tracking import filter_entries, get_time_horizon, collect_attributes_ids\n'), ((6242, 6284), 'trackme.tracking.crud.tracking_validation.is_attribute_binary', 'is_attribute_binary', (['attribute_id', 'user_id'], {}), '(attribute_id, user_id)\n', (6261, 6284), False, 'from trackme.tracking.crud.tracking_validation import is_attribute_binary\n'), ((903, 928), 'statsmodels.stats.stattools.durbin_watson', 'durbin_watson', (['input_data'], {}), '(input_data)\n', (916, 928), False, 'from statsmodels.stats.stattools import durbin_watson\n'), ((6475, 6520), 'trackme.tracking.crud.tracking.collect_attributes_ids', 'collect_attributes_ids', (['user_id'], {'binary': '(False)'}), '(user_id, binary=False)\n', (6497, 6520), False, 'from trackme.tracking.crud.tracking import filter_entries, get_time_horizon, collect_attributes_ids\n'), ((7213, 7257), 'trackme.tracking.crud.tracking.collect_attributes_ids', 'collect_attributes_ids', (['user_id'], {'binary': '(True)'}), '(user_id, binary=True)\n', (7235, 7257), False, 'from trackme.tracking.crud.tracking import filter_entries, get_time_horizon, collect_attributes_ids\n'), ((958, 1021), 'statsmodels.tsa.stattools.pacf', 'statsmodels.tsa.stattools.pacf', (['input_data'], {'nlags': '(7)', 'alpha': '(0.01)'}), '(input_data, nlags=7, alpha=0.01)\n', (988, 1021), False, 'import statsmodels\n'), ((4104, 4118), 'numpy.mean', 'np.mean', (['array'], {}), '(array)\n', (4111, 4118), True, 'import numpy as np\n'), ((6588, 6619), 'trackme.tracking.crud.tracking_validation.is_attribute_binary', 'is_attribute_binary', (['a', 'user_id'], {}), '(a, user_id)\n', (6607, 6619), False, 'from trackme.tracking.crud.tracking_validation import is_attribute_binary\n'), ((6812, 6924), 'trackme.tracking.crud.tracking.filter_entries', 'filter_entries', ([], {'user_id': 'user_id', 'topics': 'None', 'start': 'None', 'end': 'None', 'attribute': 'factor', 'comments': 'None', 'ts': '(True)'}), '(user_id=user_id, topics=None, start=None, end=None,\n attribute=factor, comments=None, ts=True)\n', (6826, 6924), False, 'from trackme.tracking.crud.tracking import filter_entries, get_time_horizon, collect_attributes_ids\n'), ((7327, 7439), 'trackme.tracking.crud.tracking.filter_entries', 'filter_entries', ([], {'user_id': 'user_id', 'topics': 'None', 'start': 'None', 'end': 'None', 'attribute': 'factor', 'comments': 'None', 'ts': '(True)'}), '(user_id=user_id, topics=None, start=None, end=None,\n attribute=factor, comments=None, ts=True)\n', (7341, 7439), False, 'from trackme.tracking.crud.tracking import filter_entries, get_time_horizon, collect_attributes_ids\n'), ((7009, 7048), 'trackme.tracking.analytics.multifactor_analysis.pearson_correlation', 'pearson_correlation', (['ts_raw', 'raw_second'], {}), '(ts_raw, raw_second)\n', (7028, 7048), False, 'from trackme.tracking.analytics.multifactor_analysis import pearson_correlation, pointbiserial_correlation\n'), ((7521, 7566), 'trackme.tracking.analytics.multifactor_analysis.pointbiserial_correlation', 'pointbiserial_correlation', (['ts_raw', 'raw_second'], {}), '(ts_raw, raw_second)\n', (7546, 7566), False, 'from trackme.tracking.analytics.multifactor_analysis import pearson_correlation, pointbiserial_correlation\n')]
|
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def linear(x, *params):
y = np.zeros_like(x)
k = params[0]
y0 = params[1]
y = y0 + k * x
return y
def linearFitter(x, y, *y0):
guess = [1, 0]
if len(y0) == 0:
try:
print("Try fitting without bounds")
popt, pcov = curve_fit(linear, x, y, p0=guess)
except:
print("Cannot fit")
popt = guess
pcov = 0
else:
y0 = y0[0]
try:
popt, pcov = curve_fit(linear, x, y, p0=guess, bounds=([-np.inf, y0-0.001], [np.inf, y0+0.001]))
except ValueError:
print("Cannot fit with bounds")
try:
print("Try fitting without bounds")
popt, pcov = curve_fit(linear, x, y, p0=guess)
except:
print("Still cannot fit")
popt = guess
pcov = 0
except RuntimeError:
print("The least-squares minimization failed")
popt = guess
pcov = 0
return popt, pcov
def pickPeak(center, guess):
m = []
for n in np.arange(0, len(guess), 3):
diff = [abs(x-guess[n]) for x in center]
m.extend([diff.index(min(diff))])
return m
def singleGaussian(x, *params):
y = np.zeros_like(x)
ctr = params[0]
amp = params[1]
wid = params[2]
y0 = params[3]
y = y0 + amp * np.exp( -((x - ctr)/wid)**2)
return y
def singleGaussianFitter(cbins, counts, pts):
binNum = cbins.shape[0]
binSize = cbins[1]-cbins[0]
guess = np.zeros(4)
guess[0] = pts[0]
guess[1] = 300
guess[2] = 1.0
guess[3] = pts[1]
##These are global fitting constraints
lB = [0, 0, 0, guess[3]*0.8]
hB = [np.inf, np.inf, np.inf, guess[3]*1.2]
try:
popt, pcov = curve_fit(singleGaussian, cbins, counts, p0=guess, bounds=(lB, hB))
except ValueError:
print("Cannot fit with bounds")
try:
print("Try fitting without bounds")
popt, pcov = curve_fit(singleGaussian, cbins, counts, p0=guess)
except:
print("Still cannot fit")
popt = guess
pcov = 0
except RuntimeError:
print("The least-squares minimization failed")
popt = guess
pcov = 0
return popt, pcov
##y0 is fixed to zero in this function
def multipleGaussian(x, *params):
y = np.zeros_like(x)
for i in np.arange(0, len(params), 3):
ctr = params[i]
amp = params[i+1]
wid = params[i+2]
y = y + amp * np.exp( -((x - ctr)/wid)**2)
return y
##This can take variable numbers of peaks
def multipleGaussianFitter(cbins, counts, pts):
binNum = cbins.shape[0]
binSize = cbins[1]-cbins[0]
guess = np.zeros(3*len(pts))
for n in np.arange(len(pts)):
guess[3*n] = pts[n][0]
guess[3*n+1] = pts[n][1]
guess[3*n+2] = 3*binSize
##These are global fitting constraints
lowBound = [[0.02, 0, 0], [0.20, 0, 0], [0.50, 0, 0]]
highBound = [[0.07, np.inf, np.inf], [0.23, np.inf, np.inf], [0.53, np.inf, np.inf]]
##Figure out how many and which sets of bounds to use
lB = []
hB = []
m = pickPeak([0.04, 0.20, 0.51], guess)
for n in m:
lB.extend(lowBound[n])
hB.extend(highBound[n])
try:
popt, pcov = curve_fit(multipleGaussian, cbins, counts, p0=guess, bounds=(lB, hB))
except ValueError:
print("Cannot fit with bounds")
try:
print("Try fitting without bounds")
popt, pcov = curve_fit(multipleGaussian, cbins, counts, p0=guess)
except:
print("Still cannot fit")
popt = guess
pcov = 0
except RuntimeError:
print("The least-squares minimization failed")
popt = guess
pcov = 0
return popt, pcov
def multipleGaussianPlotter(ccbins, popt):
m = pickPeak([0.04, 0.20, 0.51], popt)
colors = ['b', 'g', '#db1d1d']
for n in np.arange(len(m)):
params = popt[3*n:3*n+3]
fit = multipleGaussian(ccbins, *params)
plt.plot(ccbins, fit, linewidth=1.5, color=colors[m[n]])
fit = multipleGaussian(ccbins, *popt)
plt.plot(ccbins, fit, linewidth=1.5, color='k')
def exponential(x, *params):
y = np.zeros_like(x)
amp = params[0]
tau = params[1]
y0 = params[2]
y = y0 + amp * np.exp(-x/tau)
return y
def exponentialFitter(cbins, counts):
binNum = cbins.shape[0]
binSize = cbins[1]-cbins[0]
guess = np.zeros(3)
guess[0] = np.max(counts)
guess[1] = 3*binSize
guess[2] = 0.0
##These are global fitting constraints
lB = [0, 0, 0]
hB = [np.inf, np.inf, np.min(counts)]
try:
popt, pcov = curve_fit(exponential, cbins[np.argmax(counts):], counts[np.argmax(counts):], \
p0=guess, bounds=(lB, hB))
except ValueError:
print("Cannot fit with bounds")
try:
print("Try fitting without bounds")
popt, pcov = curve_fit(exponential, cbins[2:], counts[2:], p0=guess)
except:
print("Still cannot fit")
popt = guess
pcov = 0
except RuntimeError:
print("The least-squares minimization failed")
popt = guess
pcov = 0
return popt, pcov
|
[
"numpy.zeros_like",
"matplotlib.pyplot.plot",
"numpy.argmax",
"numpy.zeros",
"scipy.optimize.curve_fit",
"numpy.max",
"numpy.min",
"numpy.exp"
] |
[((126, 142), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (139, 142), True, 'import numpy as np\n'), ((1395, 1411), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (1408, 1411), True, 'import numpy as np\n'), ((1684, 1695), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1692, 1695), True, 'import numpy as np\n'), ((2559, 2575), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (2572, 2575), True, 'import numpy as np\n'), ((4443, 4490), 'matplotlib.pyplot.plot', 'plt.plot', (['ccbins', 'fit'], {'linewidth': '(1.5)', 'color': '"""k"""'}), "(ccbins, fit, linewidth=1.5, color='k')\n", (4451, 4490), True, 'import matplotlib.pyplot as plt\n'), ((4532, 4548), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (4545, 4548), True, 'import numpy as np\n'), ((4778, 4789), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (4786, 4789), True, 'import numpy as np\n'), ((4806, 4820), 'numpy.max', 'np.max', (['counts'], {}), '(counts)\n', (4812, 4820), True, 'import numpy as np\n'), ((1949, 2016), 'scipy.optimize.curve_fit', 'curve_fit', (['singleGaussian', 'cbins', 'counts'], {'p0': 'guess', 'bounds': '(lB, hB)'}), '(singleGaussian, cbins, counts, p0=guess, bounds=(lB, hB))\n', (1958, 2016), False, 'from scipy.optimize import curve_fit\n'), ((3539, 3608), 'scipy.optimize.curve_fit', 'curve_fit', (['multipleGaussian', 'cbins', 'counts'], {'p0': 'guess', 'bounds': '(lB, hB)'}), '(multipleGaussian, cbins, counts, p0=guess, bounds=(lB, hB))\n', (3548, 3608), False, 'from scipy.optimize import curve_fit\n'), ((4332, 4388), 'matplotlib.pyplot.plot', 'plt.plot', (['ccbins', 'fit'], {'linewidth': '(1.5)', 'color': 'colors[m[n]]'}), '(ccbins, fit, linewidth=1.5, color=colors[m[n]])\n', (4340, 4388), True, 'import matplotlib.pyplot as plt\n'), ((4960, 4974), 'numpy.min', 'np.min', (['counts'], {}), '(counts)\n', (4966, 4974), True, 'import numpy as np\n'), ((379, 412), 'scipy.optimize.curve_fit', 'curve_fit', (['linear', 'x', 'y'], {'p0': 'guess'}), '(linear, x, y, p0=guess)\n', (388, 412), False, 'from scipy.optimize import curve_fit\n'), ((582, 674), 'scipy.optimize.curve_fit', 'curve_fit', (['linear', 'x', 'y'], {'p0': 'guess', 'bounds': '([-np.inf, y0 - 0.001], [np.inf, y0 + 0.001])'}), '(linear, x, y, p0=guess, bounds=([-np.inf, y0 - 0.001], [np.inf, \n y0 + 0.001]))\n', (591, 674), False, 'from scipy.optimize import curve_fit\n'), ((1515, 1546), 'numpy.exp', 'np.exp', (['(-((x - ctr) / wid) ** 2)'], {}), '(-((x - ctr) / wid) ** 2)\n', (1521, 1546), True, 'import numpy as np\n'), ((4631, 4647), 'numpy.exp', 'np.exp', (['(-x / tau)'], {}), '(-x / tau)\n', (4637, 4647), True, 'import numpy as np\n'), ((2171, 2221), 'scipy.optimize.curve_fit', 'curve_fit', (['singleGaussian', 'cbins', 'counts'], {'p0': 'guess'}), '(singleGaussian, cbins, counts, p0=guess)\n', (2180, 2221), False, 'from scipy.optimize import curve_fit\n'), ((2722, 2753), 'numpy.exp', 'np.exp', (['(-((x - ctr) / wid) ** 2)'], {}), '(-((x - ctr) / wid) ** 2)\n', (2728, 2753), True, 'import numpy as np\n'), ((3763, 3815), 'scipy.optimize.curve_fit', 'curve_fit', (['multipleGaussian', 'cbins', 'counts'], {'p0': 'guess'}), '(multipleGaussian, cbins, counts, p0=guess)\n', (3772, 3815), False, 'from scipy.optimize import curve_fit\n'), ((5303, 5358), 'scipy.optimize.curve_fit', 'curve_fit', (['exponential', 'cbins[2:]', 'counts[2:]'], {'p0': 'guess'}), '(exponential, cbins[2:], counts[2:], p0=guess)\n', (5312, 5358), False, 'from scipy.optimize import curve_fit\n'), ((840, 873), 'scipy.optimize.curve_fit', 'curve_fit', (['linear', 'x', 'y'], {'p0': 'guess'}), '(linear, x, y, p0=guess)\n', (849, 873), False, 'from scipy.optimize import curve_fit\n'), ((5039, 5056), 'numpy.argmax', 'np.argmax', (['counts'], {}), '(counts)\n', (5048, 5056), True, 'import numpy as np\n'), ((5067, 5084), 'numpy.argmax', 'np.argmax', (['counts'], {}), '(counts)\n', (5076, 5084), True, 'import numpy as np\n')]
|
import matplotlib.pyplot as plt
import numpy as np
import os
fileNameList = ['results_C1-BHD_0_16_0_0_-30000_30000_5000.txt', 'results_C1-BHD_0_16_16_0_-30000_30000_5000.txt', 'results_C1-SU2_0_16_0_0_-30000_30000_5000.txt', 'results_C1-SU2_16_16_32_0_-30000_30000_5000.txt', 'results_C1-SU2_32_16_16_0_-30000_30000_5000.txt', 'results_C1-SU2_32_16_48_0_-30000_30000_5000.txt']
for fileName in fileNameList:
#get metadata
parts = fileName.split('_')
FEroot=parts[1]
DACstart=parts[2]
DACnum=parts[3]
ADCstart=parts[4]
driveADC=parts[5]
offsetStart=parts[6]
offsetStop=parts[7]
offsetStep=parts[8].split('.')[0]
plotfolder = 'Plots/' + FEroot +'/'
#+ '_'.join([str(v) for v in [FEroot, DACstart, DACnum, ADCstart, driveADC]]) + '/'
if not os.path.exists(plotfolder):
os.makedirs(plotfolder)
rawDataSum = np.loadtxt(fileName)
rawData = np.loadtxt(fileName).T
numChan = len(rawData) - 1 #the number of channels
offsetVal=rawData[0]/10
#data = np.delete(rawData, 0)
plt.figure(figsize=(10,6.5))
for set in reversed(range(len(rawDataSum))):
xchan=range(int(DACstart),numChan+int(DACstart), 1)
ydata=list(np.delete((rawDataSum[set]/10), 0, axis=None))
plt.plot(xchan, ydata, linestyle='None', markersize = 7.0, marker='.', label=str(offsetVal[set]))
#plt.plot(np.full((1, len(rawData[set+1])), set+1)[0], rawData[set+1]/10, linestyle='None', markersize = 7.0,marker='.')
plt.xticks(np.arange(int(DACstart), numChan+int(DACstart)+1, 1.0))
plt.yticks(np.arange(-1500, 1500, 250))
plt.xlabel('DAC Channel')
plt.ylabel('Response')
plt.title(FEroot + ', DAC Channels ' + DACstart + '-' + str(int(DACstart)+int(DACnum)-1) + ' Connected to Respective ADC Channels ' + ADCstart + '-' + str(int(ADCstart)+int(DACnum)-1))
plt.grid(True)
#plt.legend()
plt.legend(title='Offsets', bbox_to_anchor=(1.0, 1), loc='upper left')
plt.savefig(plotfolder + 'ChRespSummary_' + '_'.join([str(v) for v in [FEroot, DACstart, DACnum, ADCstart, driveADC, offsetStart, offsetStop, offsetStep]]) + '.pdf', bbox_inches = 'tight', pad_inches = 0.2)
#plt.show()
plt.close()
for k in range(numChan):
fig, (ax1, rem, ax12) = plt.subplots(3, sharex=True,figsize=(10,6.5), gridspec_kw={'height_ratios':[2,0.1,0.75]})
ax1.title.set_text(FEroot + ', DAC Channel ' + str(int(DACstart)+k) + ' Connected to ADC Channel ' + str(int(ADCstart)+k))
# make expected data
t = np.arange(-3000, 4000, 1000)
s = t/2
ax1.plot(t, s, linewidth = 1, color='xkcd:azure', label='Expected Response (0.5 Gain)')
ax1.plot(offsetVal, rawData[k+1]/10, color='r', markersize = 7.0,marker='.', label='Measured Response')
ax1.legend()
ax1.grid(which='minor',axis='both')
ax1.grid(which='major',axis='both')
ax1.set(ylabel='Channel Response')
rem.remove()
# plot channel response diffrence
diffrence=(rawData[k+1]/10)-((offsetVal)/2)
ax12.title.set_text('Diffrence Between Expected Response and Measured Response' )
ax12.plot([-3000,3000], [0,0], color='xkcd:azure', linewidth = 1, label='Ideal response')
ax12.plot(offsetVal, diffrence, color='g', markersize = 7.0,marker='.', label='Measured - Expected Response')
secondMax=np.partition(diffrence.flatten(), -2)[-2]
secondMin=np.partition(diffrence.flatten(), -2)[2]
ax12.set_ylim(min([-0.5,secondMin-(abs(secondMin)*0.2)]), secondMax*1.2)
ax12.set(ylabel='Diffrence', xlabel='Offest')
ax12.grid(which='minor',axis='both')
ax12.grid(which='major',axis='both')
#ax12.legend()
plt.subplots_adjust(top=None,bottom=None, hspace=0.075)
plt.savefig(plotfolder + 'ChResp_' + '_'.join([str(v) for v in [FEroot, 'DAC',str(int(DACstart)+k), 'ADC',str(int(ADCstart)+k)]]) + '.pdf', bbox_inches = 'tight', pad_inches = 0.2)
plt.close
#plt.show()
'''
for k in range(numChan):
plt.figure(figsize=(8,5))
#make expected data
t = np.arange(-3000, 4000, 1000)
s = t/2
plt.plot(t, s, linewidth = 1, color='xkcd:azure', label='expected response (0.5 Gain)')
plt.plot(offsetVal, rawData[k+1]/10, color='r', markersize = 7.0,marker='.', label='Measured Response')
plt.xlabel('Offset')
plt.ylabel('Channel Response')
plt.title(FEroot + ', DAC Channel ' + str(int(DACstart)+k) + ', ADC Channel ' + str(int(ADCstart)+k))
plt.grid(True)
plt.legend()
plt.savefig(plotfolder + 'ChResp_' + '_'.join([str(v) for v in [FEroot, 'DAC',str(int(DACstart)+k), 'ADC',str(int(ADCstart)+k)]]) + '.pdf')
#plt.show()
plt.close()
#plot channel response diffrence
diffrence=(rawData[k+1]/10)-((offsetVal)/2)
plt.figure(figsize=(8,5))
plt.plot([-3000,3000], [0,0], color='xkcd:azure', label='expected response')
plt.plot(offsetVal, diffrence, color='r', markersize = 7.0,marker='.', label='Channel Response Diffrence')
#plt.yscale('log')
secondMax=np.partition(diffrence.flatten(), -2)[-2]
secondMin=np.partition(diffrence.flatten(), 2)[2]
plt.ylim(min([-0.5,secondMin-(abs(secondMin)*0.5)]), secondMax*1.2)
plt.xlabel('Offset')
plt.ylabel('Channel Response - Expected Response')
plt.title( 'Diffrence: ' + FEroot + ', DAC Channel ' + str(int(DACstart)+k) + ', ADC Channel ' + str(int(ADCstart)+k))
plt.grid(True)
plt.legend()
plt.savefig(plotfolder + 'ChRespDiff_' + '_'.join([str(v) for v in [FEroot, 'DAC',str(int(DACstart)+k), 'ADC',str(int(ADCstart)+k)]]) + '.pdf')
#plt.show()
plt.close()
'''
|
[
"os.makedirs",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"os.path.exists",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.loadtxt",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"numpy.delete"
] |
[((873, 893), 'numpy.loadtxt', 'np.loadtxt', (['fileName'], {}), '(fileName)\n', (883, 893), True, 'import numpy as np\n'), ((1054, 1083), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6.5)'}), '(figsize=(10, 6.5))\n', (1064, 1083), True, 'import matplotlib.pyplot as plt\n'), ((1609, 1634), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""DAC Channel"""'], {}), "('DAC Channel')\n", (1619, 1634), True, 'import matplotlib.pyplot as plt\n'), ((1639, 1661), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Response"""'], {}), "('Response')\n", (1649, 1661), True, 'import matplotlib.pyplot as plt\n'), ((1855, 1869), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (1863, 1869), True, 'import matplotlib.pyplot as plt\n'), ((1892, 1962), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""Offsets"""', 'bbox_to_anchor': '(1.0, 1)', 'loc': '"""upper left"""'}), "(title='Offsets', bbox_to_anchor=(1.0, 1), loc='upper left')\n", (1902, 1962), True, 'import matplotlib.pyplot as plt\n'), ((2194, 2205), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2203, 2205), True, 'import matplotlib.pyplot as plt\n'), ((795, 821), 'os.path.exists', 'os.path.exists', (['plotfolder'], {}), '(plotfolder)\n', (809, 821), False, 'import os\n'), ((831, 854), 'os.makedirs', 'os.makedirs', (['plotfolder'], {}), '(plotfolder)\n', (842, 854), False, 'import os\n'), ((908, 928), 'numpy.loadtxt', 'np.loadtxt', (['fileName'], {}), '(fileName)\n', (918, 928), True, 'import numpy as np\n'), ((1576, 1603), 'numpy.arange', 'np.arange', (['(-1500)', '(1500)', '(250)'], {}), '(-1500, 1500, 250)\n', (1585, 1603), True, 'import numpy as np\n'), ((2269, 2368), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)'], {'sharex': '(True)', 'figsize': '(10, 6.5)', 'gridspec_kw': "{'height_ratios': [2, 0.1, 0.75]}"}), "(3, sharex=True, figsize=(10, 6.5), gridspec_kw={\n 'height_ratios': [2, 0.1, 0.75]})\n", (2281, 2368), True, 'import matplotlib.pyplot as plt\n'), ((2549, 2577), 'numpy.arange', 'np.arange', (['(-3000)', '(4000)', '(1000)'], {}), '(-3000, 4000, 1000)\n', (2558, 2577), True, 'import numpy as np\n'), ((3835, 3891), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': 'None', 'bottom': 'None', 'hspace': '(0.075)'}), '(top=None, bottom=None, hspace=0.075)\n', (3854, 3891), True, 'import matplotlib.pyplot as plt\n'), ((1211, 1256), 'numpy.delete', 'np.delete', (['(rawDataSum[set] / 10)', '(0)'], {'axis': 'None'}), '(rawDataSum[set] / 10, 0, axis=None)\n', (1220, 1256), True, 'import numpy as np\n')]
|
"""Common features for the models."""
# Licensed under the 3-clause BSD license.
# http://opensource.org/licenses/BSD-3-Clause
#
# Copyright (C) 2014 <NAME>
# All rights reserved.
import numpy as np
from scipy.special import erfinv, logit
# ====== Linear regression uncertainity parameters =============================
# The target coefficient of determination
R_SQUARED = 0.5
# ====== Classification uncertainity parameters ================================
# ------ Provided values -------------------------
# Classification percentage threshold
P_0 = 0.2
# Tail probability threshold
GAMMA_0 = 0.01
# Min linear predictor term standard deviation
SIGMA_F0 = 0.25
# ------ Precalculated values --------------------
ERFINVGAMMA0 = erfinv(2*GAMMA_0-1)
LOGITP0 = logit(P_0)
# Max deviation: |alpha + beta'*x| <= DELTA_MAX
DELTA_MAX = np.sqrt(2)*SIGMA_F0*ERFINVGAMMA0 - LOGITP0
def rand_corr_vine(d, alpha=2, beta=2, pmin=-0.8, pmax=0.8, seed=None):
"""Create random correlation matrix using modified vine method.
Each partial corelation is distributed according to Beta(alpha, beta)
shifted and scaled to [pmin, pmax]. This method could be further optimised.
Does not necessarily return pos-def matrix if high correlations are
imposed.
Reference:
Lewandowski, Kurowicka, and Joe, 2009, "Generating random
correlation matrices based on vines and extended onion method"
"""
if isinstance(seed, np.random.RandomState):
rand_state = seed
else:
rand_state = np.random.RandomState(seed)
# Sample partial correlations into upper triangular
P = np.empty((d,d))
uinds = np.triu_indices(d, 1)
betas = rand_state.beta(alpha, beta, size=len(uinds[0]))
betas *= pmax - pmin
betas += pmin
P[uinds] = betas
# Store the square of the upper triangular in the lower triangular
np.square(betas, out=betas)
P.T[uinds] = betas
# Release memory
del(betas, uinds)
# Output array
C = np.eye(d)
# Convert partial correlations to raw correlations
for i in range(d-1):
for j in range(i+1,d):
cur = P[i,j]
for k in range(i-1,-1,-1):
cur *= np.sqrt((1 - P[i,k])*(1 - P[j,k]))
cur += P[k,i]*P[k,j]
C[i,j] = cur
C[j,i] = cur
# Release memory
del(P)
# Permute the order of variables
perm = rand_state.permutation(d)
C = C[np.ix_(perm,perm)]
return C
def calc_input_param_lin_reg(beta, sigma, Sigma_x=None):
"""Calculate suitable sigma_x for linear regression models.
Parameters
----------
beta : float or ndarray
The explanatory variable coefficient of size (J,D), (D,) or (), where J
is the number of groups and D is the number of input dimensions.
sigma : float
The noise standard deviation.
Sigma_x : ndarray
The covariance structure of the input variable:
Cov(x) = sigma_x * Sigma_x.
If not provided or None, Sigma_x is considered as an identity matrix.
Returns
-------
sigma_x : float or ndarray
If beta is two dimensional, sigma_x is calculated for each group.
Otherwise a single value is returned.
"""
beta = np.asarray(beta)
if Sigma_x is not None and ( beta.ndim == 0 or beta.shape[-1] <= 1 ):
raise ValueError("Input dimension has to be greater than 1 "
"if Sigma is provided")
if beta.ndim == 0 or beta.shape[-1] == 1:
# One dimensional input
if beta.ndim == 2:
beta = beta[:,0]
elif beta.ndim == 1:
beta = beta[0]
out = np.asarray(np.abs(beta))
np.divide(np.sqrt(R_SQUARED/(1-R_SQUARED))*sigma, out, out=out)
else:
# Multidimensional input
if Sigma_x is None:
out = np.asarray(np.sum(np.square(beta), axis=-1))
else:
out = beta.dot(Sigma_x)
out *= beta
out = np.asarray(np.sum(out, axis=-1))
out *= 1 - R_SQUARED
np.divide(R_SQUARED, out, out=out)
np.sqrt(out, out=out)
out *= sigma
return out[()]
def calc_input_param_classification(alpha, beta, Sigma_x=None):
"""Calculate suitable mu_x and sigma_x for classification models.
Parameters
----------
alpha : float or ndarray
The intercept coefficient of size (J) or (), where J is the number of
groups.
beta : float or ndarray
The explanatory variable coefficient of size (J,D), (D,) or (), where J
is the number of groups and D is the number of input dimensions.
Sigma_x : ndarray
The covariance structure of the input variable:
Cov(x) = sigma_x * Sigma_x.
If not provided or None, Sigma_x is considered as an identity matrix.
Returns
-------
mu_x, sigma_x : float or ndarray
If beta is two dimensional and/or alpha is one dimensional, params are
calculated for each group. Otherwise single values are returned.
"""
# Check arguments
alpha = np.asarray(alpha)
beta = np.asarray(beta)
if alpha.ndim > 1 or beta.ndim > 2:
raise ValueError("Dimension of input arguments is too big")
if alpha.ndim == 1 and alpha.shape[0] != 1:
J = alpha.shape[0]
elif beta.ndim == 2 and beta.shape[0] != 1:
J = beta.shape[0]
else:
J = 1
if alpha.ndim == 0 and beta.ndim < 2:
scalar_output = True
else:
scalar_output = False
if Sigma_x is not None and ( beta.ndim == 0 or beta.shape[-1] <= 1 ):
raise ValueError("Input dimension has to be greater than 1 "
"if Sigma is provided")
# Process
if J == 1:
# Single group
alpha = np.squeeze(alpha)[()]
beta = np.squeeze(beta)
if np.abs(alpha) < DELTA_MAX:
# No mean adjustment needed
mu_x = 0
if beta.ndim == 1:
if Sigma_x is None:
ssbeta = np.sqrt(2*np.sum(np.square(beta)))
else:
ssbeta = beta.dot(Sigma_x)
ssbeta *= beta
ssbeta = np.sqrt(2*np.sum(ssbeta))
else:
# Only one input dimension
ssbeta = np.sqrt(2)*np.abs(beta)
sigma_x = (LOGITP0 + np.abs(alpha))/(ERFINVGAMMA0*ssbeta)
else:
# Mean adjustment needed
if alpha > 0:
mu_x = (DELTA_MAX -alpha)/np.sum(beta)
else:
mu_x = (-DELTA_MAX -alpha)/np.sum(beta)
if beta.ndim == 1:
if Sigma_x is None:
ssbeta = np.sqrt(np.sum(np.square(beta)))
else:
ssbeta = beta.dot(Sigma_x)
ssbeta *= beta
ssbeta = np.sqrt(np.sum(ssbeta))
else:
# Only one input dimension
ssbeta = np.abs(beta)
sigma_x = SIGMA_F0/ssbeta
if not scalar_output:
mu_x = np.asarray([mu_x])
sigma_x = np.asarray([sigma_x])
else:
# Multiple groups
alpha = np.squeeze(alpha)
if beta.ndim == 2 and beta.shape[0] == 1:
beta = beta[0]
if beta.ndim == 0:
beta = beta[np.newaxis]
if alpha.ndim == 0:
# Common alpha: beta.ndim == 2
if np.abs(alpha) < DELTA_MAX:
# No mean adjustment needed
mu_x = np.zeros(J)
if beta.shape[1] != 1:
if Sigma_x is None:
sigma_x = np.sum(np.square(beta), axis=-1)
else:
sigma_x = beta.dot(Sigma_x)
sigma_x *= beta
sigma_x = np.sum(sigma_x, axis=-1)
sigma_x *= 2
np.sqrt(sigma_x, out=sigma_x)
else:
# Only one input dimension
sigma_x = np.sqrt(2)*np.abs(beta[:,0])
sigma_x *= ERFINVGAMMA0
np.divide(LOGITP0 + np.abs(alpha), sigma_x, out=sigma_x)
else:
# Mean adjustment needed
mu_x = np.sum(beta, axis=-1)
if alpha > 0:
np.divide(DELTA_MAX -alpha, mu_x, out=mu_x)
else:
np.divide(-DELTA_MAX -alpha, mu_x, out=mu_x)
if beta.shape[1] != 1:
if Sigma_x is None:
sigma_x = np.sum(np.square(beta), axis=-1)
else:
sigma_x = beta.dot(Sigma_x)
sigma_x *= beta
sigma_x = np.sum(sigma_x, axis=-1)
np.sqrt(sigma_x, out=sigma_x)
else:
# Only one input dimension
sigma_x = np.abs(beta[:,0]).copy()
np.divide(SIGMA_F0, sigma_x, out=sigma_x)
elif beta.ndim == 1:
# Common beta: alpha.ndim == 1
sbeta = np.sum(beta)
if beta.shape[0] != 1:
if Sigma_x is None:
ssbeta = np.sqrt(np.sum(np.square(beta)))
else:
ssbeta = beta.dot(Sigma_x)
ssbeta *= beta
ssbeta = np.sqrt(np.sum(ssbeta))
else:
ssbeta = np.abs(beta)
divisor = np.sqrt(2) * ERFINVGAMMA0 * ssbeta
mu_x = np.zeros(J)
sigma_x = np.empty(J)
for j in range(J):
if np.abs(alpha[j]) < DELTA_MAX:
# No mean adjustment needed
sigma_x[j] = (LOGITP0 + np.abs(alpha[j])) / divisor
else:
# Mean adjustment needed
if alpha[j] > 0:
mu_x[j] = (DELTA_MAX -alpha[j])/sbeta
else:
mu_x[j] = (-DELTA_MAX -alpha[j])/sbeta
sigma_x[j] = SIGMA_F0/ssbeta
else:
# Multiple alpha and beta: alpha.ndim == 1 and beta.ndim == 2
sbeta = np.sum(beta, axis=-1)
if beta.shape[1] != 1:
if Sigma_x is None:
ssbeta = np.sqrt(np.sum(np.square(beta), axis=-1))
else:
ssbeta = beta.dot(Sigma_x)
ssbeta *= beta
ssbeta = np.sqrt(np.sum(ssbeta, axis=-1))
else:
ssbeta = np.abs(beta[:,0])
divisor = np.sqrt(2) * ERFINVGAMMA0 * ssbeta
mu_x = np.zeros(J)
sigma_x = np.empty(J)
for j in range(J):
if np.abs(alpha[j]) < DELTA_MAX:
# No mean adjustment needed
sigma_x[j] = (LOGITP0 + np.abs(alpha[j])) / divisor[j]
else:
# Mean adjustment needed
if alpha[j] > 0:
mu_x[j] = (DELTA_MAX -alpha[j])/sbeta[j]
else:
mu_x[j] = (-DELTA_MAX -alpha[j])/sbeta[j]
sigma_x[j] = SIGMA_F0/ssbeta[j]
return mu_x, sigma_x
class data(object):
"""Data simulated from the hierarchical models.
Attributes
----------
X : ndarray
Explanatory variable
y : ndarray
Response variable data
X_param : dict
Parameters of the distribution of X.
y_true : ndarray
The true expected values of the response variable at X
Nj : ndarray
Number of observations in each group
N : int
Total number of observations
J : int
Number of hierarchical groups
j_lim : ndarray
Index limits of the partitions of the observations:
y[j_lim[j]:j_lim[j+1]] belong to group j.
j_ind : ndarray
The group index of each observation
true_values : dict
True values of `phi` and other inferred variables
"""
def __init__(self, X, y, X_param, y_true, Nj, j_lim, j_ind, true_values):
self.X = X
self.y = y
self.y_true = y_true
self.Nj = Nj
self.N = np.sum(Nj)
self.J = Nj.shape[0]
self.j_lim = j_lim
self.j_ind = j_ind
self.true_values = true_values
self.X_param = X_param
def calc_uncertainty(self):
"""Calculate the uncertainty in the response variable.
Returns: uncertainty_global, uncertainty_group
"""
y = self.y
y_true = self.y_true
j_lim = self.j_lim
Nj = self.Nj
if issubclass(y.dtype.type, np.integer):
# Categorial: percentage of wrong classes
uncertainty_global = np.count_nonzero(y_true != y)/self.N
uncertainty_group = np.empty(self.J)
for j in range(self.J):
uncertainty_group[j] = (
np.count_nonzero(
y_true[j_lim[j]:j_lim[j+1]] != y[j_lim[j]:j_lim[j+1]]
) / Nj[j]
)
else:
# Continuous: R squared
sst = np.sum(np.square(y - np.mean(y)))
sse = np.sum(np.square(y - y_true))
uncertainty_global = 1 - sse/sst
uncertainty_group = np.empty(self.J)
for j in range(self.J):
sst = np.sum(np.square(
y[j_lim[j]:j_lim[j+1]] - np.mean(y[j_lim[j]:j_lim[j+1]])
))
sse = np.sum(np.square(
y[j_lim[j]:j_lim[j+1]] - y_true[j_lim[j]:j_lim[j+1]]
))
uncertainty_group[j] = 1 - sse/sst
return uncertainty_global, uncertainty_group
|
[
"numpy.divide",
"numpy.sum",
"numpy.abs",
"numpy.count_nonzero",
"numpy.empty",
"numpy.asarray",
"numpy.square",
"scipy.special.erfinv",
"numpy.triu_indices",
"numpy.random.RandomState",
"numpy.ix_",
"numpy.zeros",
"scipy.special.logit",
"numpy.mean",
"numpy.squeeze",
"numpy.eye",
"numpy.sqrt"
] |
[((737, 760), 'scipy.special.erfinv', 'erfinv', (['(2 * GAMMA_0 - 1)'], {}), '(2 * GAMMA_0 - 1)\n', (743, 760), False, 'from scipy.special import erfinv, logit\n'), ((767, 777), 'scipy.special.logit', 'logit', (['P_0'], {}), '(P_0)\n', (772, 777), False, 'from scipy.special import erfinv, logit\n'), ((1614, 1630), 'numpy.empty', 'np.empty', (['(d, d)'], {}), '((d, d))\n', (1622, 1630), True, 'import numpy as np\n'), ((1642, 1663), 'numpy.triu_indices', 'np.triu_indices', (['d', '(1)'], {}), '(d, 1)\n', (1657, 1663), True, 'import numpy as np\n'), ((1864, 1891), 'numpy.square', 'np.square', (['betas'], {'out': 'betas'}), '(betas, out=betas)\n', (1873, 1891), True, 'import numpy as np\n'), ((1985, 1994), 'numpy.eye', 'np.eye', (['d'], {}), '(d)\n', (1991, 1994), True, 'import numpy as np\n'), ((3248, 3264), 'numpy.asarray', 'np.asarray', (['beta'], {}), '(beta)\n', (3258, 3264), True, 'import numpy as np\n'), ((5085, 5102), 'numpy.asarray', 'np.asarray', (['alpha'], {}), '(alpha)\n', (5095, 5102), True, 'import numpy as np\n'), ((5114, 5130), 'numpy.asarray', 'np.asarray', (['beta'], {}), '(beta)\n', (5124, 5130), True, 'import numpy as np\n'), ((1522, 1549), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (1543, 1549), True, 'import numpy as np\n'), ((2431, 2449), 'numpy.ix_', 'np.ix_', (['perm', 'perm'], {}), '(perm, perm)\n', (2437, 2449), True, 'import numpy as np\n'), ((4054, 4088), 'numpy.divide', 'np.divide', (['R_SQUARED', 'out'], {'out': 'out'}), '(R_SQUARED, out, out=out)\n', (4063, 4088), True, 'import numpy as np\n'), ((4097, 4118), 'numpy.sqrt', 'np.sqrt', (['out'], {'out': 'out'}), '(out, out=out)\n', (4104, 4118), True, 'import numpy as np\n'), ((5837, 5853), 'numpy.squeeze', 'np.squeeze', (['beta'], {}), '(beta)\n', (5847, 5853), True, 'import numpy as np\n'), ((7217, 7234), 'numpy.squeeze', 'np.squeeze', (['alpha'], {}), '(alpha)\n', (7227, 7234), True, 'import numpy as np\n'), ((12280, 12290), 'numpy.sum', 'np.sum', (['Nj'], {}), '(Nj)\n', (12286, 12290), True, 'import numpy as np\n'), ((838, 848), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (845, 848), True, 'import numpy as np\n'), ((3672, 3684), 'numpy.abs', 'np.abs', (['beta'], {}), '(beta)\n', (3678, 3684), True, 'import numpy as np\n'), ((5800, 5817), 'numpy.squeeze', 'np.squeeze', (['alpha'], {}), '(alpha)\n', (5810, 5817), True, 'import numpy as np\n'), ((5865, 5878), 'numpy.abs', 'np.abs', (['alpha'], {}), '(alpha)\n', (5871, 5878), True, 'import numpy as np\n'), ((7101, 7119), 'numpy.asarray', 'np.asarray', (['[mu_x]'], {}), '([mu_x])\n', (7111, 7119), True, 'import numpy as np\n'), ((7142, 7163), 'numpy.asarray', 'np.asarray', (['[sigma_x]'], {}), '([sigma_x])\n', (7152, 7163), True, 'import numpy as np\n'), ((12910, 12926), 'numpy.empty', 'np.empty', (['self.J'], {}), '(self.J)\n', (12918, 12926), True, 'import numpy as np\n'), ((13395, 13411), 'numpy.empty', 'np.empty', (['self.J'], {}), '(self.J)\n', (13403, 13411), True, 'import numpy as np\n'), ((2193, 2231), 'numpy.sqrt', 'np.sqrt', (['((1 - P[i, k]) * (1 - P[j, k]))'], {}), '((1 - P[i, k]) * (1 - P[j, k]))\n', (2200, 2231), True, 'import numpy as np\n'), ((3704, 3740), 'numpy.sqrt', 'np.sqrt', (['(R_SQUARED / (1 - R_SQUARED))'], {}), '(R_SQUARED / (1 - R_SQUARED))\n', (3711, 3740), True, 'import numpy as np\n'), ((3995, 4015), 'numpy.sum', 'np.sum', (['out'], {'axis': '(-1)'}), '(out, axis=-1)\n', (4001, 4015), True, 'import numpy as np\n'), ((7001, 7013), 'numpy.abs', 'np.abs', (['beta'], {}), '(beta)\n', (7007, 7013), True, 'import numpy as np\n'), ((7462, 7475), 'numpy.abs', 'np.abs', (['alpha'], {}), '(alpha)\n', (7468, 7475), True, 'import numpy as np\n'), ((7556, 7567), 'numpy.zeros', 'np.zeros', (['J'], {}), '(J)\n', (7564, 7567), True, 'import numpy as np\n'), ((8297, 8318), 'numpy.sum', 'np.sum', (['beta'], {'axis': '(-1)'}), '(beta, axis=-1)\n', (8303, 8318), True, 'import numpy as np\n'), ((9013, 9054), 'numpy.divide', 'np.divide', (['SIGMA_F0', 'sigma_x'], {'out': 'sigma_x'}), '(SIGMA_F0, sigma_x, out=sigma_x)\n', (9022, 9054), True, 'import numpy as np\n'), ((9148, 9160), 'numpy.sum', 'np.sum', (['beta'], {}), '(beta)\n', (9154, 9160), True, 'import numpy as np\n'), ((9583, 9594), 'numpy.zeros', 'np.zeros', (['J'], {}), '(J)\n', (9591, 9594), True, 'import numpy as np\n'), ((9617, 9628), 'numpy.empty', 'np.empty', (['J'], {}), '(J)\n', (9625, 9628), True, 'import numpy as np\n'), ((10242, 10263), 'numpy.sum', 'np.sum', (['beta'], {'axis': '(-1)'}), '(beta, axis=-1)\n', (10248, 10263), True, 'import numpy as np\n'), ((10709, 10720), 'numpy.zeros', 'np.zeros', (['J'], {}), '(J)\n', (10717, 10720), True, 'import numpy as np\n'), ((10743, 10754), 'numpy.empty', 'np.empty', (['J'], {}), '(J)\n', (10751, 10754), True, 'import numpy as np\n'), ((12841, 12870), 'numpy.count_nonzero', 'np.count_nonzero', (['(y_true != y)'], {}), '(y_true != y)\n', (12857, 12870), True, 'import numpy as np\n'), ((13295, 13316), 'numpy.square', 'np.square', (['(y - y_true)'], {}), '(y - y_true)\n', (13304, 13316), True, 'import numpy as np\n'), ((3865, 3880), 'numpy.square', 'np.square', (['beta'], {}), '(beta)\n', (3874, 3880), True, 'import numpy as np\n'), ((6329, 6339), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6336, 6339), True, 'import numpy as np\n'), ((6340, 6352), 'numpy.abs', 'np.abs', (['beta'], {}), '(beta)\n', (6346, 6352), True, 'import numpy as np\n'), ((6386, 6399), 'numpy.abs', 'np.abs', (['alpha'], {}), '(alpha)\n', (6392, 6399), True, 'import numpy as np\n'), ((6542, 6554), 'numpy.sum', 'np.sum', (['beta'], {}), '(beta)\n', (6548, 6554), True, 'import numpy as np\n'), ((6616, 6628), 'numpy.sum', 'np.sum', (['beta'], {}), '(beta)\n', (6622, 6628), True, 'import numpy as np\n'), ((7944, 7973), 'numpy.sqrt', 'np.sqrt', (['sigma_x'], {'out': 'sigma_x'}), '(sigma_x, out=sigma_x)\n', (7951, 7973), True, 'import numpy as np\n'), ((8369, 8413), 'numpy.divide', 'np.divide', (['(DELTA_MAX - alpha)', 'mu_x'], {'out': 'mu_x'}), '(DELTA_MAX - alpha, mu_x, out=mu_x)\n', (8378, 8413), True, 'import numpy as np\n'), ((8455, 8500), 'numpy.divide', 'np.divide', (['(-DELTA_MAX - alpha)', 'mu_x'], {'out': 'mu_x'}), '(-DELTA_MAX - alpha, mu_x, out=mu_x)\n', (8464, 8500), True, 'import numpy as np\n'), ((8843, 8872), 'numpy.sqrt', 'np.sqrt', (['sigma_x'], {'out': 'sigma_x'}), '(sigma_x, out=sigma_x)\n', (8850, 8872), True, 'import numpy as np\n'), ((9494, 9506), 'numpy.abs', 'np.abs', (['beta'], {}), '(beta)\n', (9500, 9506), True, 'import numpy as np\n'), ((10615, 10633), 'numpy.abs', 'np.abs', (['beta[:, 0]'], {}), '(beta[:, 0])\n', (10621, 10633), True, 'import numpy as np\n'), ((13024, 13099), 'numpy.count_nonzero', 'np.count_nonzero', (['(y_true[j_lim[j]:j_lim[j + 1]] != y[j_lim[j]:j_lim[j + 1]])'], {}), '(y_true[j_lim[j]:j_lim[j + 1]] != y[j_lim[j]:j_lim[j + 1]])\n', (13040, 13099), True, 'import numpy as np\n'), ((13613, 13680), 'numpy.square', 'np.square', (['(y[j_lim[j]:j_lim[j + 1]] - y_true[j_lim[j]:j_lim[j + 1]])'], {}), '(y[j_lim[j]:j_lim[j + 1]] - y_true[j_lim[j]:j_lim[j + 1]])\n', (13622, 13680), True, 'import numpy as np\n'), ((6899, 6913), 'numpy.sum', 'np.sum', (['ssbeta'], {}), '(ssbeta)\n', (6905, 6913), True, 'import numpy as np\n'), ((7866, 7890), 'numpy.sum', 'np.sum', (['sigma_x'], {'axis': '(-1)'}), '(sigma_x, axis=-1)\n', (7872, 7890), True, 'import numpy as np\n'), ((8073, 8083), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (8080, 8083), True, 'import numpy as np\n'), ((8084, 8102), 'numpy.abs', 'np.abs', (['beta[:, 0]'], {}), '(beta[:, 0])\n', (8090, 8102), True, 'import numpy as np\n'), ((8178, 8191), 'numpy.abs', 'np.abs', (['alpha'], {}), '(alpha)\n', (8184, 8191), True, 'import numpy as np\n'), ((8798, 8822), 'numpy.sum', 'np.sum', (['sigma_x'], {'axis': '(-1)'}), '(sigma_x, axis=-1)\n', (8804, 8822), True, 'import numpy as np\n'), ((9529, 9539), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (9536, 9539), True, 'import numpy as np\n'), ((9679, 9695), 'numpy.abs', 'np.abs', (['alpha[j]'], {}), '(alpha[j])\n', (9685, 9695), True, 'import numpy as np\n'), ((10655, 10665), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (10662, 10665), True, 'import numpy as np\n'), ((10805, 10821), 'numpy.abs', 'np.abs', (['alpha[j]'], {}), '(alpha[j])\n', (10811, 10821), True, 'import numpy as np\n'), ((13257, 13267), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (13264, 13267), True, 'import numpy as np\n'), ((6227, 6241), 'numpy.sum', 'np.sum', (['ssbeta'], {}), '(ssbeta)\n', (6233, 6241), True, 'import numpy as np\n'), ((6740, 6755), 'numpy.square', 'np.square', (['beta'], {}), '(beta)\n', (6749, 6755), True, 'import numpy as np\n'), ((7688, 7703), 'numpy.square', 'np.square', (['beta'], {}), '(beta)\n', (7697, 7703), True, 'import numpy as np\n'), ((8620, 8635), 'numpy.square', 'np.square', (['beta'], {}), '(beta)\n', (8629, 8635), True, 'import numpy as np\n'), ((8972, 8990), 'numpy.abs', 'np.abs', (['beta[:, 0]'], {}), '(beta[:, 0])\n', (8978, 8990), True, 'import numpy as np\n'), ((9435, 9449), 'numpy.sum', 'np.sum', (['ssbeta'], {}), '(ssbeta)\n', (9441, 9449), True, 'import numpy as np\n'), ((10547, 10570), 'numpy.sum', 'np.sum', (['ssbeta'], {'axis': '(-1)'}), '(ssbeta, axis=-1)\n', (10553, 10570), True, 'import numpy as np\n'), ((13533, 13566), 'numpy.mean', 'np.mean', (['y[j_lim[j]:j_lim[j + 1]]'], {}), '(y[j_lim[j]:j_lim[j + 1]])\n', (13540, 13566), True, 'import numpy as np\n'), ((6066, 6081), 'numpy.square', 'np.square', (['beta'], {}), '(beta)\n', (6075, 6081), True, 'import numpy as np\n'), ((9276, 9291), 'numpy.square', 'np.square', (['beta'], {}), '(beta)\n', (9285, 9291), True, 'import numpy as np\n'), ((9801, 9817), 'numpy.abs', 'np.abs', (['alpha[j]'], {}), '(alpha[j])\n', (9807, 9817), True, 'import numpy as np\n'), ((10379, 10394), 'numpy.square', 'np.square', (['beta'], {}), '(beta)\n', (10388, 10394), True, 'import numpy as np\n'), ((10927, 10943), 'numpy.abs', 'np.abs', (['alpha[j]'], {}), '(alpha[j])\n', (10933, 10943), True, 'import numpy as np\n')]
|
import numpy as np
from time import time
import re
from pmesh.pm import ParticleMesh
from nbodykit.lab import BigFileCatalog, MultipleSpeciesCatalog, FFTPower
#
#
#Global, fixed things
scratch1 = '/global/cscratch1/sd/yfeng1/m3127/'
scratch2 = '/global/cscratch1/sd/chmodi/m3127/H1mass/'
project = '/project/projectdirs/m3127/H1mass/'
cosmodef = {'omegam':0.309167, 'h':0.677, 'omegab':0.048}
alist = [0.1429,0.1538,0.1667,0.1818,0.2000,0.2222,0.2500,0.2857,0.3333]
#Parameters, box size, number of mesh cells, simulation, ...
bs, nc = 256, 512
ncsim, sim, prefix = 2560, 'highres/%d-9100-fixed'%2560, 'highres'
pm = ParticleMesh(BoxSize=bs, Nmesh=[nc, nc, nc])
rank = pm.comm.rank
wsize = pm.comm.size
if rank == 0: print('World size = ', wsize)
# This should be imported once from a "central" place.
def HI_hod(mhalo,aa):
"""Returns the 21cm "mass" for a box of halo masses."""
zp1 = 1.0/aa
zz = zp1-1
alp = 1.0
alp = (1+2*zz)/(2+2*zz)
mcut= 1e9*( 1.8 + 15*(3*aa)**8 )
norm= 3e5*(1+(3.5/zz)**6)
xx = mhalo/mcut+1e-10
mHI = xx**alp * np.exp(-1/xx)
mHI*= norm
return(mHI)
#
if __name__=="__main__":
if rank == 0: print('Starting')
if bs == 1024:
censuff = '-16node'
satsuff='-m1_5p0min-alpha_0p8-16node'
elif bs == 256:
censuff = ''
satsuff='-m1_5p0min-alpha_0p8'
pks = []
for aa in alist[:2]:
if rank ==0 : print('For z = %0.2f'%(1/aa-1))
#cencat = BigFileCatalog(scratch2+sim+'/fastpm_%0.4f/cencat'%aa+censuff)
cencat = BigFileCatalog(scratch1+sim+'/fastpm_%0.4f/LL-0.200'%aa)
mp = cencat.attrs['M0'][0]*1e10
cencat['Mass'] = cencat['Length'] * mp
#cencat['HImass'] = HI_hod(cencat['Mass'],aa)
h1mesh = pm.paint(cencat['Position'], mass=cencat['Mass'])
#h1mesh = pm.paint(cencat['Position'])
print('Rank, mesh.cmean() : ', rank, h1mesh.cmean())
h1mesh /= h1mesh.cmean()
#
pkh1h1 = FFTPower(h1mesh,mode='1d').power
# Extract the quantities we want and write the file.
kk = pkh1h1['k']
sn = pkh1h1.attrs['shotnoise']
pk = np.abs(pkh1h1['power'])
pks.append(pk)
#if rank ==0 :
header = 'k, P(k, z) : %s'%alist[:2]
tosave = np.concatenate((kk.reshape(-1, 1), np.array(pks).T), axis=-1)
if rank == 0: print(tosave[:5])
np.savetxt('../data/pkdebug2-%d.txt'%wsize, tosave, header=header)
|
[
"nbodykit.lab.BigFileCatalog",
"numpy.abs",
"nbodykit.lab.FFTPower",
"numpy.savetxt",
"pmesh.pm.ParticleMesh",
"numpy.array",
"numpy.exp"
] |
[((627, 671), 'pmesh.pm.ParticleMesh', 'ParticleMesh', ([], {'BoxSize': 'bs', 'Nmesh': '[nc, nc, nc]'}), '(BoxSize=bs, Nmesh=[nc, nc, nc])\n', (639, 671), False, 'from pmesh.pm import ParticleMesh\n'), ((2414, 2482), 'numpy.savetxt', 'np.savetxt', (["('../data/pkdebug2-%d.txt' % wsize)", 'tosave'], {'header': 'header'}), "('../data/pkdebug2-%d.txt' % wsize, tosave, header=header)\n", (2424, 2482), True, 'import numpy as np\n'), ((1084, 1099), 'numpy.exp', 'np.exp', (['(-1 / xx)'], {}), '(-1 / xx)\n', (1090, 1099), True, 'import numpy as np\n'), ((1574, 1636), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(scratch1 + sim + '/fastpm_%0.4f/LL-0.200' % aa)"], {}), "(scratch1 + sim + '/fastpm_%0.4f/LL-0.200' % aa)\n", (1588, 1636), False, 'from nbodykit.lab import BigFileCatalog, MultipleSpeciesCatalog, FFTPower\n'), ((2190, 2213), 'numpy.abs', 'np.abs', (["pkh1h1['power']"], {}), "(pkh1h1['power'])\n", (2196, 2213), True, 'import numpy as np\n'), ((2012, 2039), 'nbodykit.lab.FFTPower', 'FFTPower', (['h1mesh'], {'mode': '"""1d"""'}), "(h1mesh, mode='1d')\n", (2020, 2039), False, 'from nbodykit.lab import BigFileCatalog, MultipleSpeciesCatalog, FFTPower\n'), ((2347, 2360), 'numpy.array', 'np.array', (['pks'], {}), '(pks)\n', (2355, 2360), True, 'import numpy as np\n')]
|
from __future__ import print_function
import unittest
import numpy.testing as npt
from .context import SimulationHydro
class TestBasic(unittest.TestCase):
@staticmethod
def test_cons_to_primitive():
a = SimulationHydro.SimulationHydro()
test_primitive = [0, 0.4, 1.4]
con = [1, 0, 1]
prim = a.get_prim(con)
print(prim)
npt.assert_allclose(prim, test_primitive, rtol=1e-5)
@staticmethod
def test_riemann():
a = SimulationHydro.SimulationHydro()
left = [1, 0.0, 1.4]
right = left
test_flux = [0, 0.56, 0]
flux = a.riemann_solver(left, right)
npt.assert_allclose(flux, test_flux, rtol=1e-5)
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"numpy.testing.assert_allclose"
] |
[((740, 755), 'unittest.main', 'unittest.main', ([], {}), '()\n', (753, 755), False, 'import unittest\n'), ((380, 433), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['prim', 'test_primitive'], {'rtol': '(1e-05)'}), '(prim, test_primitive, rtol=1e-05)\n', (399, 433), True, 'import numpy.testing as npt\n'), ((659, 707), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['flux', 'test_flux'], {'rtol': '(1e-05)'}), '(flux, test_flux, rtol=1e-05)\n', (678, 707), True, 'import numpy.testing as npt\n')]
|
"""Setting a parameter by cross-validation
=======================================================
Here we set the number of features selected in an Anova-SVC approach to
maximize the cross-validation score.
After separating 2 sessions for validation, we vary that parameter and
measure the cross-validation score. We also measure the prediction score
on the left-out validation data. As we can see, the two scores vary by a
significant amount: this is due to sampling noise in cross validation,
and choosing the parameter k to maximize the cross-validation score,
might not maximize the score on left-out data.
Thus using data to maximize a cross-validation score computed on that
same data is likely to optimistic and lead to an overfit.
The proper approach is known as a "nested cross-validation". It consists
in doing cross-validation loops to set the model parameters inside the
cross-validation loop used to judge the prediction performance: the
parameters are set separately on each fold, never using the data used to
measure performance.
For decoding task, in nilearn, this can be done using the
:class:`nilearn.decoding.Decoder` object, that will automatically select
the best parameters of an estimator from a grid of parameter values.
One difficulty is that the Decoder object is a composite estimator: a
pipeline of feature selection followed by Support Vector Machine. Tuning
the SVM's parameters is already done automatically inside the Decoder, but
performing cross-validation for the feature selection must be done
manually.
"""
###########################################################################
# Load the Haxby dataset
# -----------------------
from nilearn import datasets
# by default 2nd subject data will be fetched on which we run our analysis
haxby_dataset = datasets.fetch_haxby()
fmri_img = haxby_dataset.func[0]
mask_img = haxby_dataset.mask
# print basic information on the dataset
print('Mask nifti image (3D) is located at: %s' % haxby_dataset.mask)
print('Functional nifti image (4D) are located at: %s' % haxby_dataset.func[0])
# Load the behavioral data
import pandas as pd
labels = pd.read_csv(haxby_dataset.session_target[0], sep=" ")
y = labels['labels']
# Keep only data corresponding to shoes or bottles
from nilearn.image import index_img
condition_mask = y.isin(['shoe', 'bottle'])
fmri_niimgs = index_img(fmri_img, condition_mask)
y = y[condition_mask]
session = labels['chunks'][condition_mask]
###########################################################################
# ANOVA pipeline with :class:`nilearn.decoding.Decoder` object
# ------------------------------------------------------------
#
# Nilearn Decoder object aims to provide smooth user experience by acting as a
# pipeline of several tasks: preprocessing with NiftiMasker, reducing dimension
# by selecting only relevant features with ANOVA -- a classical univariate
# feature selection based on F-test, and then decoding with different types of
# estimators (in this example is Support Vector Machine with a linear kernel)
# on nested cross-validation.
from nilearn.decoding import Decoder
# Here screening_percentile is set to 2 percent, meaning around 800
# features will be selected with ANOVA.
decoder = Decoder(estimator='svc', cv=5, mask=mask_img,
smoothing_fwhm=4, standardize=True,
screening_percentile=2)
###########################################################################
# Fit the Decoder and predict the reponses
# -------------------------------------------------
# As a complete pipeline by itself, decoder will perform cross-validation
# for the estimator, in this case Support Vector Machine. We can output the
# best parameters selected for each cross-validation fold. See
# https://scikit-learn.org/stable/modules/cross_validation.html for an
# excellent explanation of how cross-validation works.
#
# First we fit the Decoder
decoder.fit(fmri_niimgs, y)
for i, (param, cv_score) in enumerate(zip(decoder.cv_params_['shoe']['C'],
decoder.cv_scores_['shoe'])):
print("Fold %d | Best SVM parameter: %.1f with score: %.3f" % (i + 1,
param, cv_score))
# Output the prediction with Decoder
y_pred = decoder.predict(fmri_niimgs)
###########################################################################
# Compute prediction scores with different values of screening percentile
# -----------------------------------------------------------------------
import numpy as np
screening_percentile_range = [2, 4, 8, 16, 32, 64]
cv_scores = []
val_scores = []
for sp in screening_percentile_range:
decoder = Decoder(estimator='svc', mask=mask_img,
smoothing_fwhm=4, cv=3, standardize=True,
screening_percentile=sp)
decoder.fit(index_img(fmri_niimgs, session < 10),
y[session < 10])
cv_scores.append(np.mean(decoder.cv_scores_['bottle']))
print("Sreening Percentile: %.3f" % sp)
print("Mean CV score: %.4f" % cv_scores[-1])
y_pred = decoder.predict(index_img(fmri_niimgs, session == 10))
val_scores.append(np.mean(y_pred == y[session == 10]))
print("Validation score: %.4f" % val_scores[-1])
###########################################################################
# Nested cross-validation
# -----------------------
# We are going to tune the parameter 'screening_percentile' in the
# pipeline.
from sklearn.model_selection import KFold
cv = KFold(n_splits=3)
nested_cv_scores = []
for train, test in cv.split(session):
y_train = np.array(y)[train]
y_test = np.array(y)[test]
val_scores = []
for sp in screening_percentile_range:
decoder = Decoder(estimator='svc', mask=mask_img,
smoothing_fwhm=4, cv=3, standardize=True,
screening_percentile=sp)
decoder.fit(index_img(fmri_niimgs, train), y_train)
y_pred = decoder.predict(index_img(fmri_niimgs, test))
val_scores.append(np.mean(y_pred == y_test))
nested_cv_scores.append(np.max(val_scores))
print("Nested CV score: %.4f" % np.mean(nested_cv_scores))
###########################################################################
# Plot the prediction scores using matplotlib
# ---------------------------------------------
from matplotlib import pyplot as plt
from nilearn.plotting import show
plt.figure(figsize=(6, 4))
plt.plot(cv_scores, label='Cross validation scores')
plt.plot(val_scores, label='Left-out validation data scores')
plt.xticks(np.arange(len(screening_percentile_range)),
screening_percentile_range)
plt.axis('tight')
plt.xlabel('ANOVA screening percentile')
plt.axhline(np.mean(nested_cv_scores),
label='Nested cross-validation',
color='r')
plt.legend(loc='best', frameon=False)
show()
|
[
"nilearn.image.index_img",
"matplotlib.pyplot.plot",
"nilearn.plotting.show",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"nilearn.datasets.fetch_haxby",
"matplotlib.pyplot.axis",
"sklearn.model_selection.KFold",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"nilearn.decoding.Decoder",
"numpy.max",
"matplotlib.pyplot.xlabel"
] |
[((1800, 1822), 'nilearn.datasets.fetch_haxby', 'datasets.fetch_haxby', ([], {}), '()\n', (1820, 1822), False, 'from nilearn import datasets\n'), ((2135, 2188), 'pandas.read_csv', 'pd.read_csv', (['haxby_dataset.session_target[0]'], {'sep': '""" """'}), "(haxby_dataset.session_target[0], sep=' ')\n", (2146, 2188), True, 'import pandas as pd\n'), ((2358, 2393), 'nilearn.image.index_img', 'index_img', (['fmri_img', 'condition_mask'], {}), '(fmri_img, condition_mask)\n', (2367, 2393), False, 'from nilearn.image import index_img\n'), ((3240, 3350), 'nilearn.decoding.Decoder', 'Decoder', ([], {'estimator': '"""svc"""', 'cv': '(5)', 'mask': 'mask_img', 'smoothing_fwhm': '(4)', 'standardize': '(True)', 'screening_percentile': '(2)'}), "(estimator='svc', cv=5, mask=mask_img, smoothing_fwhm=4, standardize\n =True, screening_percentile=2)\n", (3247, 3350), False, 'from nilearn.decoding import Decoder\n'), ((5485, 5502), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(3)'}), '(n_splits=3)\n', (5490, 5502), False, 'from sklearn.model_selection import KFold\n'), ((6400, 6426), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (6410, 6426), True, 'from matplotlib import pyplot as plt\n'), ((6427, 6479), 'matplotlib.pyplot.plot', 'plt.plot', (['cv_scores'], {'label': '"""Cross validation scores"""'}), "(cv_scores, label='Cross validation scores')\n", (6435, 6479), True, 'from matplotlib import pyplot as plt\n'), ((6480, 6541), 'matplotlib.pyplot.plot', 'plt.plot', (['val_scores'], {'label': '"""Left-out validation data scores"""'}), "(val_scores, label='Left-out validation data scores')\n", (6488, 6541), True, 'from matplotlib import pyplot as plt\n'), ((6636, 6653), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (6644, 6653), True, 'from matplotlib import pyplot as plt\n'), ((6654, 6694), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""ANOVA screening percentile"""'], {}), "('ANOVA screening percentile')\n", (6664, 6694), True, 'from matplotlib import pyplot as plt\n'), ((6804, 6841), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'frameon': '(False)'}), "(loc='best', frameon=False)\n", (6814, 6841), True, 'from matplotlib import pyplot as plt\n'), ((6842, 6848), 'nilearn.plotting.show', 'show', ([], {}), '()\n', (6846, 6848), False, 'from nilearn.plotting import show\n'), ((4658, 4769), 'nilearn.decoding.Decoder', 'Decoder', ([], {'estimator': '"""svc"""', 'mask': 'mask_img', 'smoothing_fwhm': '(4)', 'cv': '(3)', 'standardize': '(True)', 'screening_percentile': 'sp'}), "(estimator='svc', mask=mask_img, smoothing_fwhm=4, cv=3, standardize\n =True, screening_percentile=sp)\n", (4665, 4769), False, 'from nilearn.decoding import Decoder\n'), ((6708, 6733), 'numpy.mean', 'np.mean', (['nested_cv_scores'], {}), '(nested_cv_scores)\n', (6715, 6733), True, 'import numpy as np\n'), ((4825, 4861), 'nilearn.image.index_img', 'index_img', (['fmri_niimgs', '(session < 10)'], {}), '(fmri_niimgs, session < 10)\n', (4834, 4861), False, 'from nilearn.image import index_img\n'), ((4917, 4954), 'numpy.mean', 'np.mean', (["decoder.cv_scores_['bottle']"], {}), "(decoder.cv_scores_['bottle'])\n", (4924, 4954), True, 'import numpy as np\n'), ((5079, 5116), 'nilearn.image.index_img', 'index_img', (['fmri_niimgs', '(session == 10)'], {}), '(fmri_niimgs, session == 10)\n', (5088, 5116), False, 'from nilearn.image import index_img\n'), ((5140, 5175), 'numpy.mean', 'np.mean', (['(y_pred == y[session == 10])'], {}), '(y_pred == y[session == 10])\n', (5147, 5175), True, 'import numpy as np\n'), ((5578, 5589), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (5586, 5589), True, 'import numpy as np\n'), ((5610, 5621), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (5618, 5621), True, 'import numpy as np\n'), ((5709, 5820), 'nilearn.decoding.Decoder', 'Decoder', ([], {'estimator': '"""svc"""', 'mask': 'mask_img', 'smoothing_fwhm': '(4)', 'cv': '(3)', 'standardize': '(True)', 'screening_percentile': 'sp'}), "(estimator='svc', mask=mask_img, smoothing_fwhm=4, cv=3, standardize\n =True, screening_percentile=sp)\n", (5716, 5820), False, 'from nilearn.decoding import Decoder\n'), ((6073, 6091), 'numpy.max', 'np.max', (['val_scores'], {}), '(val_scores)\n', (6079, 6091), True, 'import numpy as np\n'), ((6126, 6151), 'numpy.mean', 'np.mean', (['nested_cv_scores'], {}), '(nested_cv_scores)\n', (6133, 6151), True, 'import numpy as np\n'), ((5888, 5917), 'nilearn.image.index_img', 'index_img', (['fmri_niimgs', 'train'], {}), '(fmri_niimgs, train)\n', (5897, 5917), False, 'from nilearn.image import index_img\n'), ((5961, 5989), 'nilearn.image.index_img', 'index_img', (['fmri_niimgs', 'test'], {}), '(fmri_niimgs, test)\n', (5970, 5989), False, 'from nilearn.image import index_img\n'), ((6017, 6042), 'numpy.mean', 'np.mean', (['(y_pred == y_test)'], {}), '(y_pred == y_test)\n', (6024, 6042), True, 'import numpy as np\n')]
|
import argparse
import datetime
import json
import math
import os
import pdb
import pickle
import random
import sys
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
from config import model_conf, special_toks, train_conf
from dataset import FastDataset
from models import BlindStatelessLSTM, MultiAttentiveTransformer
from utilities import DataParallelV2, Logger, plotting_loss
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4,5" # specify which GPU(s) to be used
torch.autograd.set_detect_anomaly(True)
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
def instantiate_model(args, out_vocab, device):
"""
if args.model == 'blindstateless':
return BlindStatelessLSTM(word_embeddings_path=args.embeddings,
pad_token=special_toks['pad_token'],
unk_token=special_toks['unk_token'],
seed=train_conf['seed'],
OOV_corrections=False,
freeze_embeddings=True)
"""
if args.model == 'matransformer':
if args.from_checkpoint is not None:
with open(os.path.join(args.from_checkpoint, 'state_dict.pt'), 'rb') as fp:
state_dict = torch.load(fp)
with open(os.path.join(args.from_checkpoint, 'model_conf.json'), 'rb') as fp:
loaded_conf = json.load(fp)
loaded_conf.pop('dropout_prob')
model_conf.update(loaded_conf)
model = MultiAttentiveTransformer(**model_conf,
seed=train_conf['seed'],
device=device,
out_vocab=out_vocab,
**special_toks)
if args.from_checkpoint is not None:
model.load_state_dict(state_dict)
print('Model loaded from {}'.format(args.from_checkpoint))
return model
else:
raise Exception('Model not present!')
def plotting(epochs, losses_trend, checkpoint_dir=None):
epoch_list = np.arange(1, epochs+1)
losses = [(losses_trend['train'], 'blue', 'train'),
(losses_trend['dev'], 'red', 'validation')]
loss_path = os.path.join(checkpoint_dir, 'global_loss_plot') if checkpoint_dir is not None else None
plotting_loss(x_values=epoch_list, save_path=loss_path, functions=losses, plot_title='Global loss trend', x_label='epochs', y_label='loss')
def move_batch_to_device(batch, device):
for key in batch.keys():
if key == 'history':
raise Exception('Not implemented')
batch[key] = batch[key].to(device)
def visualize_output(request, responses, item, id2word, genid2word, vocab_logits, device):
shifted_targets = torch.cat((responses[:, 1:], torch.zeros((responses.shape[0], 1), dtype=torch.long).to(device)), dim=-1)
rand_idx = random.randint(0, shifted_targets.shape[0]-1)
eff_len = shifted_targets[rand_idx][shifted_targets[rand_idx] != 0].shape[0]
"""
inp = ' '.join([id2word[inp_id.item()] for inp_id in responses[rand_idx] if inp_id != vocab['[PAD]']])
print('input: {}'.format(inp))
"""
req = ' '.join([id2word[req_id.item()] for req_id in request[rand_idx] if req_id != 0])
print('user: {}'.format(req))
out = ' '.join([id2word[out_id.item()] for out_id in shifted_targets[rand_idx] if out_id !=0])
print('wizard: {}'.format(out))
item = ' '.join([id2word[item_id.item()] for item_id in item[rand_idx] if item_id !=0])
print('item: {}'.format(item))
gens = torch.argmax(torch.nn.functional.softmax(vocab_logits, dim=-1), dim=-1)
gen = ' '.join([genid2word[gen_id.item()] for gen_id in gens[:, :eff_len][rand_idx]])
print('generated: {}'.format(gen))
def forward_step(model, batch, generative_targets, response_criterion, device):
move_batch_to_device(batch, device)
generative_targets = generative_targets.to(device)
vocab_logits = model(**batch,
history=None,
actions=None,
attributes=None,
candidates=None,
candidates_mask=None,
candidates_token_type=None)
#keep the loss outside the forward: complex to compute the mean with a weighted loss
response_loss = response_criterion(vocab_logits.view(vocab_logits.shape[0]*vocab_logits.shape[1], -1),
generative_targets.view(vocab_logits.shape[0]*vocab_logits.shape[1]))
p = random.randint(0, 9)
if p > 8:
try:
vocab = model.vocab
id2word = model.id2word
genid2word = model.genid2word
except:
vocab = model.module.vocab
id2word = model.module.id2word
genid2word = model.module.genid2word
visualize_output(request=batch['utterances'], responses=batch['responses'], item=batch['focus'], id2word=id2word, genid2word=genid2word, vocab_logits=vocab_logits, device=device)
return response_loss
def train(train_dataset, dev_dataset, args, device):
# prepare checkpoint folder
if args.checkpoints:
curr_date = datetime.datetime.now().isoformat().split('.')[0]
checkpoint_dir = os.path.join(train_conf['ckpt_folder'], curr_date)
os.makedirs(checkpoint_dir, exist_ok=True)
# prepare logger to redirect both on file and stdout
sys.stdout = Logger(os.path.join(checkpoint_dir, 'train.log'))
sys.stderr = Logger(os.path.join(checkpoint_dir, 'err.log'))
print('device used: {}'.format(str(device)))
print('batch used: {}'.format(args.batch_size))
print('lr used: {}'.format(train_conf['lr']))
print('weight decay: {}'.format(train_conf['weight_decay']))
print('TRAINING DATASET: {}'.format(train_dataset))
print('VALIDATION DATASET: {}'.format(dev_dataset))
with open(args.generative_vocab, 'rb') as fp:
gen_vocab = dict(torch.load(fp))
bert2genid, inv_freqs = gen_vocab['vocab'], gen_vocab['inv_freqs']
if args.checkpoints:
torch.save(bert2genid, os.path.join(checkpoint_dir, 'bert2genid.pkl'))
print('GENERATIVE VOCABULARY SIZE: {}'.format(len(bert2genid)))
# prepare model
#response_criterion = torch.nn.CrossEntropyLoss(ignore_index=0, weight=inv_freqs/inv_freqs.sum()).to(device)
response_criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device)
model = instantiate_model(args, out_vocab=bert2genid, device=device)
vocab = model.vocab
if args.checkpoints:
with open(os.path.join(checkpoint_dir, 'model_conf.json'), 'w+') as fp:
json.dump(model_conf, fp)
# work on multiple GPUs when available
if torch.cuda.device_count() > 1:
model = DataParallelV2(model)
model.to(device)
print('using {} GPU(s): {}'.format(torch.cuda.device_count(), os.environ["CUDA_VISIBLE_DEVICES"]))
print('MODEL NAME: {}'.format(args.model))
print('NETWORK: {}'.format(model))
# prepare DataLoader
params = {'batch_size': args.batch_size,
'shuffle': True,
'num_workers': 0,
'pin_memory': True}
collate_fn = model.collate_fn if torch.cuda.device_count() <= 1 else model.module.collate_fn
trainloader = DataLoader(train_dataset, **params, collate_fn=collate_fn)
devloader = DataLoader(dev_dataset, **params, collate_fn=collate_fn)
#prepare optimizer
#optimizer = torch.optim.Adam(params=model.parameters(), lr=train_conf['lr'])
optimizer = torch.optim.Adam(params=model.parameters(), lr=train_conf['lr'], weight_decay=train_conf['weight_decay'])
#scheduler1 = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones = list(range(500, 500*5, 100)), gamma = 0.1)
scheduler1 = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones = list(range(25, 100, 50)), gamma = 0.1)
scheduler2 = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=.1, patience=12, threshold=1e-3, cooldown=2, verbose=True)
#prepare containers for statistics
losses_trend = {'train': [],
'dev': []}
#candidates_pools_size = 100 if train_conf['distractors_sampling'] < 0 else train_conf['distractors_sampling'] + 1
#print('candidates\' pool size: {}'.format(candidates_pools_size))
#accumulation_steps = 8
best_loss = math.inf
global_step = 0
start_t = time.time()
for epoch in range(args.epochs):
ep_start = time.time()
model.train()
curr_epoch_losses = []
for batch_idx, (dial_ids, turns, batch, generative_targets) in enumerate(trainloader):
global_step += 1
step_start = time.time()
response_loss = forward_step(model,
batch=batch,
response_criterion=response_criterion,
generative_targets=generative_targets,
device=device)
optimizer.zero_grad()
#averaging losses from various GPUs by dividing by the batch size
response_loss.mean().backward()
#torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optimizer.step()
step_end = time.time()
h_count = (step_end-step_start) /60 /60
m_count = ((step_end-step_start)/60) % 60
s_count = (step_end-step_start) % 60
print('step {}, loss: {}, time: {}h:{}m:{}s'.format(global_step, round(response_loss.mean().item(), 4), round(h_count), round(m_count), round(s_count)))
"""
if (batch_idx+1) % accumulation_steps == 0:
optimizer.step()
optimizer.zero_grad()
#torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
#step_end = time.time()
print('step {}, loss: {}'.format(global_step, round(response_loss.item()*accumulation_steps, 4)))
p = random.randint(0, 9)
if p > 8:
h_count = (step_end-step_start) /60 /60
m_count = ((step_end-step_start)/60) % 60
s_count = (step_end-step_start) % 60
print('step {}, loss: {}, time: {}h:{}m:{}s'.format(global_step, round(response_loss.mean().item(), 4), round(h_count), round(m_count), round(s_count)))
"""
#scheduler1.step()
#scheduler2.step(response_loss.item())
curr_epoch_losses.append(response_loss.mean().item())
losses_trend['train'].append(np.mean(curr_epoch_losses))
model.eval()
curr_epoch_losses = []
with torch.no_grad():
for curr_step, (dial_ids, turns, batch, generative_targets) in enumerate(devloader):
response_loss = forward_step(model,
batch=batch,
response_criterion=response_criterion,
generative_targets=generative_targets,
device=device)
curr_epoch_losses.append(response_loss.mean().item())
losses_trend['dev'].append(np.mean(curr_epoch_losses))
# save checkpoint if best model
if losses_trend['dev'][-1] < best_loss:
best_loss = losses_trend['dev'][-1]
if args.checkpoints:
try:
state_dict = model.cpu().module.state_dict()
except AttributeError:
state_dict = model.cpu().state_dict()
torch.save(state_dict, os.path.join(checkpoint_dir, 'state_dict.pt'))
#torch.save(model.cpu().state_dict(), os.path.join(checkpoint_dir, 'state_dict.pt'))
model.to(device)
ep_end = time.time()
ep_h_count = (ep_end-ep_start) /60 /60
ep_m_count = ((ep_end-ep_start)/60) % 60
ep_s_count = (ep_end-ep_start) % 60
time_str = '{}h:{}m:{}s'.format(round(ep_h_count), round(ep_m_count), round(ep_s_count))
print('EPOCH #{} :: train_loss = {:.4f} ; dev_loss = {:.4f} ; (lr={}); --time: {}'.format(epoch+1,
losses_trend['train'][-1],
losses_trend['dev'][-1],
optimizer.param_groups[0]['lr'],
time_str))
#TODO uncomment
#scheduler1.step()
scheduler2.step(losses_trend['dev'][-1])
end_t = time.time()
h_count = (end_t-start_t) /60 /60
m_count = ((end_t-start_t)/60) % 60
s_count = (end_t-start_t) % 60
print('training time: {}h:{}m:{}s'.format(round(h_count), round(m_count), round(s_count)))
if not args.checkpoints:
checkpoint_dir = None
plotting(epochs=args.epochs, losses_trend=losses_trend, checkpoint_dir=checkpoint_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"--model",
type=str,
choices=['blindstateless', 'blindstateful', 'matransformer'],
required=True,
help="Type of the model (options: 'blindstateless', 'blindstateful', 'matransformer')")
parser.add_argument(
"--data",
type=str,
required=True,
help="Path to preprocessed training data file .dat")
parser.add_argument(
"--eval",
type=str,
required=True,
help="Path to preprocessed eval data file .dat")
parser.add_argument(
"--metadata_ids",
type=str,
required=True,
help="Path to metadata ids file")
parser.add_argument(
"--generative_vocab",
type=str,
required=True,
help="Path to generative vocabulary file")
parser.add_argument(
"--batch_size",
required=True,
type=int,
help="Batch size")
parser.add_argument(
"--epochs",
required=True,
type=int,
help="Number of epochs")
parser.add_argument(
"--from_checkpoint",
type=str,
required=False,
default=None,
help="Path to checkpoint to load")
parser.add_argument(
"--checkpoints",
action='store_true',
default=False,
required=False,
help="Flag to enable checkpoint saving for best model, logs and plots")
parser.add_argument(
"--cuda",
action='store_true',
default=False,
required=False,
help="flag to use cuda")
args = parser.parse_args()
if not args.checkpoints:
print('************ NO CHECKPOINT SAVE !!! ************')
train_dataset = FastDataset(dat_path=args.data, metadata_ids_path= args.metadata_ids, distractors_sampling=train_conf['distractors_sampling'])
dev_dataset = FastDataset(dat_path=args.eval, metadata_ids_path= args.metadata_ids, distractors_sampling=train_conf['distractors_sampling']) #? sampling on eval
print('TRAIN DATA LEN: {}'.format(len(train_dataset)))
device = torch.device('cuda:0'.format(args.cuda) if torch.cuda.is_available() and args.cuda else 'cpu')
train(train_dataset, dev_dataset, args, device)
|
[
"argparse.ArgumentParser",
"torch.cuda.device_count",
"numpy.mean",
"torch.autograd.set_detect_anomaly",
"numpy.arange",
"utilities.DataParallelV2",
"utilities.plotting_loss",
"torch.no_grad",
"os.path.join",
"random.randint",
"torch.utils.data.DataLoader",
"config.model_conf.update",
"torch.load",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.zeros",
"datetime.datetime.now",
"json.dump",
"torch.cuda.is_available",
"json.load",
"os.makedirs",
"dataset.FastDataset",
"torch.nn.CrossEntropyLoss",
"time.time",
"models.MultiAttentiveTransformer",
"torch.nn.functional.softmax"
] |
[((543, 582), 'torch.autograd.set_detect_anomaly', 'torch.autograd.set_detect_anomaly', (['(True)'], {}), '(True)\n', (576, 582), False, 'import torch\n'), ((2155, 2179), 'numpy.arange', 'np.arange', (['(1)', '(epochs + 1)'], {}), '(1, epochs + 1)\n', (2164, 2179), True, 'import numpy as np\n'), ((2405, 2548), 'utilities.plotting_loss', 'plotting_loss', ([], {'x_values': 'epoch_list', 'save_path': 'loss_path', 'functions': 'losses', 'plot_title': '"""Global loss trend"""', 'x_label': '"""epochs"""', 'y_label': '"""loss"""'}), "(x_values=epoch_list, save_path=loss_path, functions=losses,\n plot_title='Global loss trend', x_label='epochs', y_label='loss')\n", (2418, 2548), False, 'from utilities import DataParallelV2, Logger, plotting_loss\n'), ((2971, 3018), 'random.randint', 'random.randint', (['(0)', '(shifted_targets.shape[0] - 1)'], {}), '(0, shifted_targets.shape[0] - 1)\n', (2985, 3018), False, 'import random\n'), ((4646, 4666), 'random.randint', 'random.randint', (['(0)', '(9)'], {}), '(0, 9)\n', (4660, 4666), False, 'import random\n'), ((7397, 7455), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'collate_fn': 'collate_fn'}), '(train_dataset, **params, collate_fn=collate_fn)\n', (7407, 7455), False, 'from torch.utils.data import DataLoader\n'), ((7472, 7528), 'torch.utils.data.DataLoader', 'DataLoader', (['dev_dataset'], {'collate_fn': 'collate_fn'}), '(dev_dataset, **params, collate_fn=collate_fn)\n', (7482, 7528), False, 'from torch.utils.data import DataLoader\n'), ((8014, 8140), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'torch.optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'factor': '(0.1)', 'patience': '(12)', 'threshold': '(0.001)', 'cooldown': '(2)', 'verbose': '(True)'}), '(optimizer, factor=0.1, patience=\n 12, threshold=0.001, cooldown=2, verbose=True)\n', (8056, 8140), False, 'import torch\n'), ((8517, 8528), 'time.time', 'time.time', ([], {}), '()\n', (8526, 8528), False, 'import time\n'), ((12892, 12903), 'time.time', 'time.time', ([], {}), '()\n', (12901, 12903), False, 'import time\n'), ((13308, 13333), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (13331, 13333), False, 'import argparse\n'), ((15056, 15185), 'dataset.FastDataset', 'FastDataset', ([], {'dat_path': 'args.data', 'metadata_ids_path': 'args.metadata_ids', 'distractors_sampling': "train_conf['distractors_sampling']"}), "(dat_path=args.data, metadata_ids_path=args.metadata_ids,\n distractors_sampling=train_conf['distractors_sampling'])\n", (15067, 15185), False, 'from dataset import FastDataset\n'), ((15201, 15330), 'dataset.FastDataset', 'FastDataset', ([], {'dat_path': 'args.eval', 'metadata_ids_path': 'args.metadata_ids', 'distractors_sampling': "train_conf['distractors_sampling']"}), "(dat_path=args.eval, metadata_ids_path=args.metadata_ids,\n distractors_sampling=train_conf['distractors_sampling'])\n", (15212, 15330), False, 'from dataset import FastDataset\n'), ((1595, 1716), 'models.MultiAttentiveTransformer', 'MultiAttentiveTransformer', ([], {'seed': "train_conf['seed']", 'device': 'device', 'out_vocab': 'out_vocab'}), "(**model_conf, seed=train_conf['seed'], device=\n device, out_vocab=out_vocab, **special_toks)\n", (1620, 1716), False, 'from models import BlindStatelessLSTM, MultiAttentiveTransformer\n'), ((2312, 2360), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""global_loss_plot"""'], {}), "(checkpoint_dir, 'global_loss_plot')\n", (2324, 2360), False, 'import os\n'), ((3671, 3720), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['vocab_logits'], {'dim': '(-1)'}), '(vocab_logits, dim=-1)\n', (3698, 3720), False, 'import torch\n'), ((5372, 5422), 'os.path.join', 'os.path.join', (["train_conf['ckpt_folder']", 'curr_date'], {}), "(train_conf['ckpt_folder'], curr_date)\n", (5384, 5422), False, 'import os\n'), ((5431, 5473), 'os.makedirs', 'os.makedirs', (['checkpoint_dir'], {'exist_ok': '(True)'}), '(checkpoint_dir, exist_ok=True)\n', (5442, 5473), False, 'import os\n'), ((6841, 6866), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (6864, 6866), False, 'import torch\n'), ((6888, 6909), 'utilities.DataParallelV2', 'DataParallelV2', (['model'], {}), '(model)\n', (6902, 6909), False, 'from utilities import DataParallelV2, Logger, plotting_loss\n'), ((8585, 8596), 'time.time', 'time.time', ([], {}), '()\n', (8594, 8596), False, 'import time\n'), ((11989, 12000), 'time.time', 'time.time', ([], {}), '()\n', (11998, 12000), False, 'import time\n'), ((1547, 1577), 'config.model_conf.update', 'model_conf.update', (['loaded_conf'], {}), '(loaded_conf)\n', (1564, 1577), False, 'from config import model_conf, special_toks, train_conf\n'), ((5563, 5604), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""train.log"""'], {}), "(checkpoint_dir, 'train.log')\n", (5575, 5604), False, 'import os\n'), ((5634, 5673), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""err.log"""'], {}), "(checkpoint_dir, 'err.log')\n", (5646, 5673), False, 'import os\n'), ((6080, 6094), 'torch.load', 'torch.load', (['fp'], {}), '(fp)\n', (6090, 6094), False, 'import torch\n'), ((6223, 6269), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""bert2genid.pkl"""'], {}), "(checkpoint_dir, 'bert2genid.pkl')\n", (6235, 6269), False, 'import os\n'), ((6498, 6539), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'ignore_index': '(0)'}), '(ignore_index=0)\n', (6523, 6539), False, 'import torch\n'), ((6765, 6790), 'json.dump', 'json.dump', (['model_conf', 'fp'], {}), '(model_conf, fp)\n', (6774, 6790), False, 'import json\n'), ((6970, 6995), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (6993, 6995), False, 'import torch\n'), ((7319, 7344), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (7342, 7344), False, 'import torch\n'), ((8799, 8810), 'time.time', 'time.time', ([], {}), '()\n', (8808, 8810), False, 'import time\n'), ((9403, 9414), 'time.time', 'time.time', ([], {}), '()\n', (9412, 9414), False, 'import time\n'), ((10727, 10753), 'numpy.mean', 'np.mean', (['curr_epoch_losses'], {}), '(curr_epoch_losses)\n', (10734, 10753), True, 'import numpy as np\n'), ((10821, 10836), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10834, 10836), False, 'import torch\n'), ((11376, 11402), 'numpy.mean', 'np.mean', (['curr_epoch_losses'], {}), '(curr_epoch_losses)\n', (11383, 11402), True, 'import numpy as np\n'), ((1342, 1356), 'torch.load', 'torch.load', (['fp'], {}), '(fp)\n', (1352, 1356), False, 'import torch\n'), ((1477, 1490), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (1486, 1490), False, 'import json\n'), ((6691, 6738), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""model_conf.json"""'], {}), "(checkpoint_dir, 'model_conf.json')\n", (6703, 6738), False, 'import os\n'), ((15463, 15488), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (15486, 15488), False, 'import torch\n'), ((1247, 1298), 'os.path.join', 'os.path.join', (['args.from_checkpoint', '"""state_dict.pt"""'], {}), "(args.from_checkpoint, 'state_dict.pt')\n", (1259, 1298), False, 'import os\n'), ((1379, 1432), 'os.path.join', 'os.path.join', (['args.from_checkpoint', '"""model_conf.json"""'], {}), "(args.from_checkpoint, 'model_conf.json')\n", (1391, 1432), False, 'import os\n'), ((2880, 2934), 'torch.zeros', 'torch.zeros', (['(responses.shape[0], 1)'], {'dtype': 'torch.long'}), '((responses.shape[0], 1), dtype=torch.long)\n', (2891, 2934), False, 'import torch\n'), ((11795, 11840), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""state_dict.pt"""'], {}), "(checkpoint_dir, 'state_dict.pt')\n", (11807, 11840), False, 'import os\n'), ((5297, 5320), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (5318, 5320), False, 'import datetime\n')]
|
import os
import requests
import base64
import logging
import datetime
import hashlib
from pathlib import Path
import tempfile
import traceback
from synthesizer.inference import Synthesizer
from encoder import inference as encoder
from vocoder import inference as vocoder
import numpy as np
import librosa
logging.basicConfig(level=10, format="%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s")
log = logging.getLogger("voice_cloning")
def clone(audio=None, audio_url=None, sentence=""):
try:
if not 10 <= len(sentence.split(" ")) <= 30:
return {"audio": b"Sentence is invalid! (length must be 10 to 30 words)"}
audio_data = audio
if audio_url:
# Link
if "http://" in audio_url or "https://" in audio_url:
header = {'User-Agent': 'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:9.0) Gecko/20100101 Firefox/10.0'}
# Check if audio file has less than 5Mb
r = requests.head(audio_url, headers=header, allow_redirects=True)
size = r.headers.get('content-length', 0)
size = int(size) / float(1 << 20)
log.info("File size: {:.2f} Mb".format(size))
if size > 5:
return {"audio": b"Input audio file is too large! (max 5Mb)"}
r = requests.get(audio_url, headers=header, allow_redirects=True)
audio_data = r.content
# Base64
elif len(audio_url) > 500:
audio_data = base64.b64decode(audio_url)
audio_path = generate_uid() + ".audio"
with open(audio_path, "wb") as f:
f.write(audio_data)
# Load the models one by one.
log.info("Preparing the encoder, the synthesizer and the vocoder...")
encoder.load_model(Path("rtvc/encoder/saved_models/pretrained.pt"))
synthesizer = Synthesizer(Path("rtvc/synthesizer/saved_models/logs-pretrained/taco_pretrained"))
vocoder.load_model(Path("rtvc/vocoder/saved_models/pretrained/pretrained.pt"))
# Computing the embedding
original_wav, sampling_rate = librosa.load(audio_path)
preprocessed_wav = encoder.preprocess_wav(original_wav, sampling_rate)
log.info("Loaded file successfully")
if os.path.exists(audio_path):
os.remove(audio_path)
embed = encoder.embed_utterance(preprocessed_wav)
log.info("Created the embedding")
specs = synthesizer.synthesize_spectrograms([sentence], [embed])
spec = np.concatenate(specs, axis=1)
# spec = specs[0]
log.info("Created the mel spectrogram")
# Generating the waveform
log.info("Synthesizing the waveform:")
generated_wav = vocoder.infer_waveform(spec, progress_callback=lambda *args: None)
# Post-generation
# There's a bug with sounddevice that makes the audio cut one second earlier, so we
# pad it.
generated_wav = np.pad(generated_wav,
(0, synthesizer.sample_rate),
mode="constant")
# Save it on the disk
fp = tempfile.TemporaryFile()
librosa.output.write_wav(fp, generated_wav.astype(np.float32), synthesizer.sample_rate)
return {"audio": fp.read()}
except Exception as e:
log.error(e)
traceback.print_exc()
return {"audio": b"Fail"}
def generate_uid():
# Setting a hash accordingly to the timestamp
seed = "{}".format(datetime.datetime.now())
m = hashlib.sha256()
m.update(seed.encode("utf-8"))
m = m.hexdigest()
# Returns only the first and the last 10 hex
return m[:10] + m[-10:]
|
[
"numpy.pad",
"os.remove",
"traceback.print_exc",
"requests.head",
"numpy.concatenate",
"logging.basicConfig",
"os.path.exists",
"datetime.datetime.now",
"base64.b64decode",
"encoder.inference.embed_utterance",
"hashlib.sha256",
"vocoder.inference.infer_waveform",
"tempfile.TemporaryFile",
"librosa.load",
"pathlib.Path",
"requests.get",
"encoder.inference.preprocess_wav",
"logging.getLogger"
] |
[((308, 408), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': '(10)', 'format': '"""%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s"""'}), "(level=10, format=\n '%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s')\n", (327, 408), False, 'import logging\n'), ((410, 444), 'logging.getLogger', 'logging.getLogger', (['"""voice_cloning"""'], {}), "('voice_cloning')\n", (427, 444), False, 'import logging\n'), ((3563, 3579), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (3577, 3579), False, 'import hashlib\n'), ((2139, 2163), 'librosa.load', 'librosa.load', (['audio_path'], {}), '(audio_path)\n', (2151, 2163), False, 'import librosa\n'), ((2191, 2242), 'encoder.inference.preprocess_wav', 'encoder.preprocess_wav', (['original_wav', 'sampling_rate'], {}), '(original_wav, sampling_rate)\n', (2213, 2242), True, 'from encoder import inference as encoder\n'), ((2300, 2326), 'os.path.exists', 'os.path.exists', (['audio_path'], {}), '(audio_path)\n', (2314, 2326), False, 'import os\n'), ((2379, 2420), 'encoder.inference.embed_utterance', 'encoder.embed_utterance', (['preprocessed_wav'], {}), '(preprocessed_wav)\n', (2402, 2420), True, 'from encoder import inference as encoder\n'), ((2552, 2581), 'numpy.concatenate', 'np.concatenate', (['specs'], {'axis': '(1)'}), '(specs, axis=1)\n', (2566, 2581), True, 'import numpy as np\n'), ((2762, 2828), 'vocoder.inference.infer_waveform', 'vocoder.infer_waveform', (['spec'], {'progress_callback': '(lambda *args: None)'}), '(spec, progress_callback=lambda *args: None)\n', (2784, 2828), True, 'from vocoder import inference as vocoder\n'), ((2990, 3058), 'numpy.pad', 'np.pad', (['generated_wav', '(0, synthesizer.sample_rate)'], {'mode': '"""constant"""'}), "(generated_wav, (0, synthesizer.sample_rate), mode='constant')\n", (2996, 3058), True, 'import numpy as np\n'), ((3165, 3189), 'tempfile.TemporaryFile', 'tempfile.TemporaryFile', ([], {}), '()\n', (3187, 3189), False, 'import tempfile\n'), ((3530, 3553), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3551, 3553), False, 'import datetime\n'), ((1825, 1872), 'pathlib.Path', 'Path', (['"""rtvc/encoder/saved_models/pretrained.pt"""'], {}), "('rtvc/encoder/saved_models/pretrained.pt')\n", (1829, 1872), False, 'from pathlib import Path\n'), ((1908, 1977), 'pathlib.Path', 'Path', (['"""rtvc/synthesizer/saved_models/logs-pretrained/taco_pretrained"""'], {}), "('rtvc/synthesizer/saved_models/logs-pretrained/taco_pretrained')\n", (1912, 1977), False, 'from pathlib import Path\n'), ((2006, 2064), 'pathlib.Path', 'Path', (['"""rtvc/vocoder/saved_models/pretrained/pretrained.pt"""'], {}), "('rtvc/vocoder/saved_models/pretrained/pretrained.pt')\n", (2010, 2064), False, 'from pathlib import Path\n'), ((2340, 2361), 'os.remove', 'os.remove', (['audio_path'], {}), '(audio_path)\n', (2349, 2361), False, 'import os\n'), ((3379, 3400), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (3398, 3400), False, 'import traceback\n'), ((977, 1039), 'requests.head', 'requests.head', (['audio_url'], {'headers': 'header', 'allow_redirects': '(True)'}), '(audio_url, headers=header, allow_redirects=True)\n', (990, 1039), False, 'import requests\n'), ((1341, 1402), 'requests.get', 'requests.get', (['audio_url'], {'headers': 'header', 'allow_redirects': '(True)'}), '(audio_url, headers=header, allow_redirects=True)\n', (1353, 1402), False, 'import requests\n'), ((1531, 1558), 'base64.b64decode', 'base64.b64decode', (['audio_url'], {}), '(audio_url)\n', (1547, 1558), False, 'import base64\n')]
|
"""A module for extracting structured data from Vision Card screenshots."""
import re
import sys
import cv2
import imutils
import numpy
import pytesseract
import requests # for downloading images
from PIL import Image
from vision_card_common import VisionCard
class VisionCardOcrUtils:
"""Utilities for working with Optical Character Recognition (OCR) for Vision Cards"""
# Ignore any party ability that is a string shorter than this length, usually
# garbage from OCR gone awry.
MIN_PARTY_ABILITY_STRING_LENGTH_SANITY = 4
# Ignore any bestowed ability that is a string shorter than this length, usually
# garbage from OCR gone awry.
MIN_BESTOWED_ABILITY_STRING_LENGTH_SANITY = 4
# If true, hints the OCR to be better at finding lines by tiling the "Cost" section of the stats panel horizontally.
__USE_LATCHON_HACK = True
@staticmethod
def downloadScreenshotFromUrl(url):
"""Download a vision card screenshot from the specified URL and return as an OpenCV image object."""
try:
pilImage = Image.open(requests.get(url, stream=True).raw)
opencvImage = cv2.cvtColor(numpy.array(pilImage), cv2.COLOR_RGB2BGR)
return opencvImage
except Exception as e:
print(str(e))
# pylint: disable=raise-missing-from
raise Exception('Error while downloading or converting image: ' + url) # deliberately low on details as this may be surfaced online.
@staticmethod
def loadScreenshotFromFilesystem(path: str):
"""Load a vision card screenshot from the local filesystem and return as an OpenCV image object."""
return cv2.imread(path)
@staticmethod
def extractRawTextFromVisionCard(vision_card_image, debug_vision_card:VisionCard = None) -> (str, str):
"""Get the raw, unstructured text from a vision card (basically the raw OCR dump string).
If debug_vision_card is a VisionCard object, retains the intermediate images as debug information attached to that object.
Returns a tuple of raw (card name text, card stats text) strings. These strings will need to be interpreted and cleaned of
OCR mistakes / garbage.
Returns a tuple of two strings, with the first string being the raw text extracted from the card info
section (card name, etc) and the second string being the raw text extracted from the card stats section
(stats, abilities granted, etc).
"""
height, width, _ = vision_card_image.shape # ignored third element of the tuple is 'channels'
# For vision cards, the screen is divided into left and right. The right side
# always contains artwork. Drop it to reduce the contour iteration that will
# be needed.
vision_card_image = vision_card_image[0:height, 0:int(width/2)]
# Convert the resized image to grayscale, blur it slightly, and threshold it
# to set up the input to the contour finder.
gray_image = cv2.cvtColor(vision_card_image, cv2.COLOR_BGR2GRAY)
if debug_vision_card is not None:
debug_vision_card.debug_image_step1_gray = Image.fromarray(gray_image)
blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)
if debug_vision_card is not None:
debug_vision_card.debug_image_step2_blurred = Image.fromarray(blurred_image)
thresholded_image = cv2.threshold(blurred_image, 70, 255, cv2.THRESH_BINARY)[1]
if debug_vision_card is not None:
debug_vision_card.debug_image_step3_thresholded = Image.fromarray(thresholded_image)
# Find and enumerate all the contours.
contours = cv2.findContours(thresholded_image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)
largestContour = None
largestArea = 0
largestX = None
largestY = None
largestW = None
largestH = None
# loop over the contours
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
area = w*h
if largestArea >= area:
continue
largestX = x
largestY = y
largestW = w
largestH = h
largestArea = area
largestContour = contour
if largestContour is None:
raise Exception("No contours in image!")
# Now on to text isolation
# The name of the unit appears above the area where the stats are, just above buttons for
# "Stats" and "Information". It appears that the unit name is always aligned vertically with
# the top of the vision card, and that is the anchor point for the layout. So from here an
# HTML-like table layout begins with one row containing the unit's rarity and name, then the
# next row containing the stats and information boxes, and the third (and largest) row
# contains all the stats we want to extract.
# This table-like thing appears to be vertically floating in the center of the screen, with
# any excess empty space appearing strictly above the unit name or below the stats table,
# i.e. the three rows of data are kept together with no additional vertical space no matter
# how much extra vertical space there is.
# The top of the screen is reserved for the status bar and appears to have the same vertical
# proportions as the rows for the unit name and the stats/information buttons. So to recap:
# [player status bar, vertical size = X]
# [any excess vertical space]
# [unit name bar, vertical size ~= X]
# [stats/information bar, vertical size ~=X]
# Thus... if we take the area above the stats table, and remove the top 1/3, we should just
# about always end up with the very first text being the unit rarity + unit name row.
# Notably, long vision card names will overflow horizontal edge of the stats table and can
# extend out to the center of the screen. So include the whole area up to where the original
# center-cut was made, at width/2.
# Finally, the unit rarity logo causes problems and is interpeted as garbage due to the
# cursive script and color gradients. Fortunately the size of the logo appears to be in fixed
# proportion to the size of the stats box, with the text always starting at the same position
# relative to the left edge of the stats box no matter which logo (N, R, SR, MR or UR) is
# used. For a stats panel about 420px wide the logo is about 75 pixels wide (about 18% of the
# total width). So we will remove the left-most 18% of the space as well.
info_bounds_logo_ratio = 0.18
info_bounds_pad_left = (int) (info_bounds_logo_ratio * largestW)
info_bounds_x = largestX + info_bounds_pad_left
info_bounds_y = (int) (largestY * .33)
info_bounds_w = ((int) (width/2)) - info_bounds_x
info_bounds_h = (int) (largestY * .67)
# Crop and invert the image, we need black on white.
# Note that cropping via slicing has x values first, then y values
stats_cropped_gray_image = gray_image[largestY:(largestY+largestH), largestX:(largestX+largestW)]
info_cropped_gray_image = gray_image[info_bounds_y:(info_bounds_y+info_bounds_h), info_bounds_x:(info_bounds_x+info_bounds_w)]
if debug_vision_card is not None:
debug_vision_card.stats_debug_image_step4_cropped_gray = Image.fromarray(stats_cropped_gray_image)
debug_vision_card.info_debug_image_step4_cropped_gray = Image.fromarray(info_cropped_gray_image)
stats_cropped_gray_inverted_image = cv2.bitwise_not(stats_cropped_gray_image)
info_cropped_gray_inverted_image = cv2.bitwise_not(info_cropped_gray_image)
if debug_vision_card is not None:
debug_vision_card.stats_debug_image_step5_cropped_gray_inverted = Image.fromarray(stats_cropped_gray_inverted_image)
debug_vision_card.info_debug_image_step5_cropped_gray_inverted = Image.fromarray(info_cropped_gray_inverted_image)
# Find only the darkest parts of the image, which should now be the text.
stats_lower_bound_hsv_value = 0
stats_upper_bound_hsv_value = 80
# For the info area the text is pure white on a dark background normally. There is a unit logo with the text.
# To try and eliminate the logo, be EXTREMELY restrictive on the HSV value here. Only almost-pure white (255,255,255) should
# be considered at all. Everything else should be thrown out.
info_lower_bound_hsv_value = 0
info_upper_bound_hsv_value = 80
stats_text_mask = cv2.inRange(stats_cropped_gray_inverted_image, stats_lower_bound_hsv_value, stats_upper_bound_hsv_value)
info_text_mask = cv2.inRange(info_cropped_gray_inverted_image, info_lower_bound_hsv_value, info_upper_bound_hsv_value)
stats_text_mask = cv2.bitwise_not(stats_text_mask)
info_text_mask = cv2.bitwise_not(info_text_mask)
stats_final_ocr_input_image = stats_text_mask
info_final_ocr_input_image = info_text_mask
# Now convert back to a regular Python image from CV2.
stats_converted_final_ocr_input_image = Image.fromarray(stats_final_ocr_input_image)
info_converted_final_ocr_input_image = Image.fromarray(info_final_ocr_input_image)
# The Latch-On Hack
# Now a strange tweak. Many vision cards, particularly of the more common rarities, have few stats. This results in lots
# of empty space in the stats table and can cause the OCR to be unable to "latch on" to the fact that we want it to find
# distinct lines of text. To fix this, we can add some text to the image - but what to add, and where, and how to match
# the font and DPI? The "Cost ##" chunk of text near the top of the stats section holds the key. After the inRange()
# operations above, the level bar will have been removed, leaving the area to the right of the "cost" section totally
# empty. The cost section itself consists of the word "Cost", and then a number, and conveniently it takes up just a bit
# less than the left 1/3 of the stats area. It occupies about the top 15.5% of the image as well. Using this knowledge,
# we can grab a rectangle starting at (0,0) and extending to x=33.3%, y=15.5% of the image height and then copy and
# paste it twice, each time moving 1/3 of the image to the right. The result is that we'll have three sets of "Cost ##"
# in the top row, but this will magically have the same font and color as the currently-masked text, and the OCR will
# "latch on" much better with that junk row in place.
if VisionCardOcrUtils.__USE_LATCHON_HACK is True:
latchon_hack_height_ratio = .155
latchon_hack_width_ratio = .3333
stats_area_height, stats_area_width = stats_text_mask.shape[:2]
latchon_hack_height = int(stats_area_height * latchon_hack_height_ratio)
latchon_hack_width = int(stats_area_width * latchon_hack_width_ratio)
latchon_hack_region = stats_converted_final_ocr_input_image.crop((0, 0, latchon_hack_width, latchon_hack_height)) # left, upper, right, lower)
stats_converted_final_ocr_input_image.paste(latchon_hack_region, (latchon_hack_width, 0))
stats_converted_final_ocr_input_image.paste(latchon_hack_region, (latchon_hack_width * 2, 0))
if debug_vision_card is not None:
debug_vision_card.stats_debug_image_step6_converted_final_ocr_input_image = stats_converted_final_ocr_input_image
debug_vision_card.info_debug_image_step6_converted_final_ocr_input_image = info_converted_final_ocr_input_image
# And last but not least... extract the text from that image.
stats_extracted_text = pytesseract.image_to_string(stats_converted_final_ocr_input_image)
info_extracted_text = pytesseract.image_to_string(info_converted_final_ocr_input_image)
if debug_vision_card is not None:
debug_vision_card.stats_debug_raw_text = stats_extracted_text
debug_vision_card.info_debug_raw_text = info_extracted_text
return (info_extracted_text, stats_extracted_text)
@staticmethod
def bindStats(stat_tuples_list, vision_card):
"""Binds 0 or more (stat_name, stat_value) tuples from the specified list to the specified vision card."""
for stat_tuple in stat_tuples_list:
VisionCardOcrUtils.bindStat(stat_tuple[0], stat_tuple[1], vision_card)
@staticmethod
def isStatName(text) -> bool:
"""Returns True if and only if the specified text is a valid name of a stat on a vision card.
Stats are COST, HP, DEF, TP, SPR, AP, DEX, ATK, AGI, MAG and LUCK.
"""
stat_names = {'COST', 'HP', 'DEF', 'TP', 'SPR', 'AP', 'DEX', 'ATK', 'AGI', 'MAG', 'LUCK'}
return text.upper() in stat_names
@staticmethod
def bindStat(stat_name, stat_value, vision_card):
"""Binds the value of the stat having the specified name to the specified vision card.
Raises an exception if the stat name does not conform to any of the standard stat names.
"""
stat_name = stat_name.upper()
if stat_name == 'COST':
vision_card.Cost = stat_value
elif stat_name == 'HP':
vision_card.HP = stat_value
elif stat_name == 'DEF':
vision_card.DEF = stat_value
elif stat_name == 'TP':
vision_card.TP = stat_value
elif stat_name == 'SPR':
vision_card.SPR = stat_value
elif stat_name == 'AP':
vision_card.AP = stat_value
elif stat_name == 'DEX':
vision_card.DEX = stat_value
elif stat_name == 'ATK':
vision_card.ATK = stat_value
elif stat_name == 'AGI':
vision_card.AGI = stat_value
elif stat_name == 'MAG':
vision_card.MAG = stat_value
elif stat_name == 'LUCK':
vision_card.Luck = stat_value
elif stat_name.startswith('PARTY ABILITY'):
vision_card.PartyAbility = stat_value
elif stat_name.startswith('BESTOWED EFFECTS'):
vision_card.BestowedEffects = [stat_value]
else:
raise Exception('Unknown stat name: "{0}"'.format(stat_name))
@staticmethod
def intOrNone(rawValueString) -> int:
"""Parse a raw value string and return either the integer it represents, or None if it does not represent an integer."""
try:
return int(rawValueString, 10)
except ValueError:
return None
@staticmethod
def coerceMalformedCardName(raw_string: str) -> str:
"""Given a card name that may be very close to a real card name, tries to coerce
optically-close-matches to a valid card name and returns it.
For example, if the given string contains a right single quotation mark (0x2019 / ’),
this method will normalize it to a standard apostrophe (0x27 / ').
"""
return raw_string.replace('\u2019', "'")
@staticmethod
def coerceMalformedStatNames(raw_uppercase_strings: [str]) -> [str]:
"""Given an array of things that are possibly stat names, all uppercase, tries to coerce
optically-close-matches to a valid stat name.
Returns an array of the same size, with any close-matches coerced to their canonical form.
For example, if given the string 'AGL' this method will coerce it to "AGI"
"""
result = []
for raw_uppercase_string in raw_uppercase_strings:
if raw_uppercase_string == 'AGL':
result.append('AGI')
else:
result.append(raw_uppercase_string)
return result
@staticmethod
def fuzzyStatExtract(raw_line) -> []:
""" Try to permissively parse a line of stats that might include garbage.
The only assumption is that the text for the NAME of the stat has been correctly parsed.
Numbers that are trash (e.g. a greater-than sign, a non-ascii character, etc) will be normalized
to None. The return is a list of tuples of (stat name, stat value).
Note that it is still possible for this method to return trash if the input is mangled in new
and terrifying ways, such as there being spaces stuck inside of words, or OCR garbage that gets
misinterpreted as numbers where there should have been blank space or a hyphen, etc.
Most of the common cases are all handled below specifically, and this should account for the
vast majority of text encountered. Any case that can't be normalized will raise an exception.
"""
# The only characters that should appear in stats are letters and numbers. Throw everyhing else
# away, this takes care of noise in the image that might cause a spurious '.' or similar to
# appear where it should not be. The code below gracefully handles the absence of a value.
baked = ''
for _, one_char in enumerate(raw_line):
if one_char.isalnum():
baked += one_char
else:
baked += ' '
# Strip whitespace from the sides, upper-case, and then split on whitespace.
substrings = VisionCardOcrUtils.coerceMalformedStatNames(baked.upper().strip().split())
num_substrings = len(substrings)
# There are only a few possibilities, and they depend on the length of the substrings array
# In all cases the first word must be a valid stat.
if not VisionCardOcrUtils.isStatName(substrings[0]):
raise Exception('First word must consist of only letters')
# For debugging nasty case issues below, re-enable these lines:
_debug_cases = True
if _debug_cases:
print('baked line: ' + baked)
print('num substrings: ' + str(num_substrings))
# Length 6: Special case: The Latch-On Hack
# As described in extractRawTextFromVisionCard(...) later, there is a special hack made to
# "hint" the OCR library to treat the text in the card as full lines of text. To do this the
# "Cost ##" section of the stats image is tiled horizontally, creating a 6-tuple of
# ('Cost', <value>, 'Cost', <value>, 'Cost', <value>) across an entire line.
# Detect this case and restore sanity.
if num_substrings == 6 and substrings[0] == 'COST' and substrings[2] == 'COST' and substrings[4] == 'COST':
substrings = [substrings[0], substrings[1]]
num_substrings = 2
print('special case: latch-on hack line')
# And then fall through to regular processing code.
# Length 1: Just a name, with no number (implies value is nothing)
if num_substrings == 1:
return [(substrings[0], None)] # example: "Cost -"
# Now the possibility of numbers also exists.
# Length 2:
# Case 2.1: A name and an integer value (one valid tuple)
# Case 2.2: Two names and no integer values (OCR lost the first and second value)
# Case 2.3: A name and garbage (OCR misread the second value)
if num_substrings == 2:
if substrings[1].isdecimal(): # Case 2.1
if _debug_cases: print('Case 2.1') # pylint: disable=multiple-statements
return [(substrings[0], VisionCardOcrUtils.intOrNone(substrings[1]))]
if VisionCardOcrUtils.isStatName(substrings[1]): # Case 2.2
if _debug_cases: print('Case 2.2') # pylint: disable=multiple-statements
return [(substrings[0], None), (substrings[1], None)] # example "ATK - AGI -"
if _debug_cases: print('Case 2.3') # pylint: disable=multiple-statements
return [(substrings[0], None)] # case 2.3
# Length 3:
# Case 3.1: A name, an integer, and another name (OCR lost the second value)
# Case 3.2: A name, a name, and a value (OCR lost the first value)
# Case 3.3: A name, a name, and garbage (OCR lost the first value and misread the second value)
# Case 3.4: A name, garbage, and another name (OCR misread the first value and lost the second value)
if num_substrings == 3:
if substrings[1].isdecimal() and VisionCardOcrUtils.isStatName(substrings[2]): # Case 3.1
if _debug_cases: print('Case 3.1') # pylint: disable=multiple-statements
return [(substrings[0], VisionCardOcrUtils.intOrNone(substrings[1])), (substrings[2], None)]
if VisionCardOcrUtils.isStatName(substrings[1]) and substrings[2].isdecimal(): # Case 3.2
if _debug_cases: print('Case 3.2') # pylint: disable=multiple-statements
return [(substrings[0], None), (substrings[1], VisionCardOcrUtils.intOrNone(substrings[2]))]
if VisionCardOcrUtils.isStatName(substrings[1]): # Case 3.3
if _debug_cases: print('Case 3.3') # pylint: disable=multiple-statements
return [(substrings[0], None), (substrings[1], None)]
if VisionCardOcrUtils.isStatName(substrings[2]): # Case 3.4
if _debug_cases: print('Case 3.4') # pylint: disable=multiple-statements
return [(substrings[0], None), (substrings[2], None)]
# Length 4:
# Case 4.1: A name, an integer, another name, and an integer (happy case)
# Case 4.2: A name, an integer, another name, and garbage (OCR lost the final value)
# Case 4.3: A name, another name, anything... (uncecoverable garbage: OCR has got more than one value after the second name)
# Case 4.4: A name, garbage, another name, and an integer (OCR misread the first value)
# Case 4.5: A name, garbage, another name, and garbage (OCR misread the final value)
if num_substrings == 4:
if substrings[1].isdecimal() and VisionCardOcrUtils.isStatName(substrings[2]) and substrings[3].isdecimal(): # Case 4.1 (Happy case)
if _debug_cases: print('Case 4.1') # pylint: disable=multiple-statements
return [(substrings[0], VisionCardOcrUtils.intOrNone(substrings[1])), (substrings[2], VisionCardOcrUtils.intOrNone(substrings[3]))]
if substrings[1].isdecimal() and VisionCardOcrUtils.isStatName(substrings[2]): # Case 4.2
if _debug_cases: print('Case 4.2') # pylint: disable=multiple-statements
return [(substrings[0], VisionCardOcrUtils.intOrNone(substrings[1])), (substrings[2], None)]
if VisionCardOcrUtils.isStatName(substrings[1]): # Case 4.3
if _debug_cases: print('Case 4.3') # pylint: disable=multiple-statements
raise Exception('Malformed input')
if VisionCardOcrUtils.isStatName(substrings[2]) and substrings[3].isdecimal(): # Case 4.4
if _debug_cases: print('Case 4.4') # pylint: disable=multiple-statements
return [(substrings[0], None), (substrings[2], VisionCardOcrUtils.intOrNone(substrings[3]))]
if VisionCardOcrUtils.isStatName(substrings[2]): # Case 4.5
if _debug_cases: print('Case 4.5') # pylint: disable=multiple-statements
return [(substrings[0], None), (substrings[2], None)]
# Anything else (5 groups in the split, anything that fell past 4.5 above, etc) cannot be handled. Give up.
print('Problematic line: ' + raw_line)
print('Substrings: ' + str(substrings))
raise Exception('Malformed input')
@staticmethod
def extractVisionCardFromScreenshot(vision_card_image, is_debug = False) -> VisionCard:
"""Fully process and extract structured, well-defined text from a Vision Card image.
If is_debug == True, also captures debugging information.
"""
# After the first major vision card update, it became possible for additional stats to be
# boosted by vision cards. Thus the raw text changed, and now has a more complex form.
# An example of the raw text is below, note that the order is fixed and should not vary:
# ---- BEGIN RAW DUMP ----
# Cost 50
# HP 211 DEF -
# TP - SPR -
# AP - DEX _
# ATK 81 AGI -
# MAG 56 Luck -
# Party Ability Cau
#
# ATK Up 30%
#
# Bestowed Effects
#
# Acquired JP Up 50%
# TTR
#
# Awakening Bonus Resistance Display
# ---- END RAW DUMP ----
# Note that the "Cau" in "Party Ability Cau" is garbage from the icon that was added to the
# vision card display showing the type of boost that the text described. Additionally, the
# text is surrounded by garbage both before the "Cost 50" and after the "Acquired JP Up 50%"
# due to (on top) the level gauge / star rating and (on bottom) awakening bonus / resistance
# display buttons.
#
# Also, Bestowed Effects can contain multiple lines. Each line is a different effect.
#
# Thus text processing starts at the line that starts with "Cost" and finishes at the line that
# starts with "Awakening Bonus"
# A state machine will be used to accumulate the necessary strings for processing.
AT_START = 0
IN_PARTY_ABILITY = 1
IN_BESTOWED_EFFECTS = 2
DONE = 3
progress = AT_START
result = VisionCard()
raw_info_text, raw_stats_text = VisionCardOcrUtils.extractRawTextFromVisionCard(vision_card_image, result if is_debug else None)
# TODO: Remove these when the code is more bullet-proof
print('raw info text from card:' + raw_info_text)
print('raw stats text from card:' + raw_stats_text)
result.Name = VisionCardOcrUtils.coerceMalformedCardName(raw_info_text.splitlines(keepends=False)[0].strip())
# This regex is used to ignore trash from OCR that might appear at the boundaries of the party/bestowed ability boxes.
safe_effects_regex = re.compile(r'^[a-zA-Z0-9 \+\-\%\&]+$')
for line in raw_stats_text.splitlines(keepends=False):
line = line.strip()
if not line:
continue
upper = line.upper()
if progress == AT_START:
if upper.startswith('COST') or \
upper.startswith('HP') or \
upper.startswith('TP') or \
upper.startswith('AP') or \
upper.startswith('ATK') or \
upper.startswith('MAG'):
try:
VisionCardOcrUtils.bindStats(VisionCardOcrUtils.fuzzyStatExtract(line), result)
# pylint: disable=broad-except
except Exception as ex:
result.error_messages.append(str(ex))
return result
elif upper.startswith('PARTY'):
progress = IN_PARTY_ABILITY
elif progress == IN_PARTY_ABILITY:
if upper.startswith('BESTOWED EFFECTS'):
progress = IN_BESTOWED_EFFECTS
elif len(upper) < VisionCardOcrUtils.MIN_PARTY_ABILITY_STRING_LENGTH_SANITY:
pass # Ignore trash, such as the "Cau" in the example above, if it appears on its own line.
elif result.PartyAbility is not None: # should not happen, party ability is only one line of text
result.error_messages.append('Found multiple party ability lines in vision card')
return result
elif safe_effects_regex.match(line):
result.PartyAbility = line
elif progress == IN_BESTOWED_EFFECTS:
if upper.startswith('AWAKENING BONUS'):
progress = DONE
elif len(upper) < VisionCardOcrUtils.MIN_BESTOWED_ABILITY_STRING_LENGTH_SANITY:
pass # Ignore trash, such as the "TTR" in the example above, if it appears on its own line.
elif safe_effects_regex.match(line):
result.BestowedEffects.append(line)
elif progress == DONE:
break
if len(result.error_messages) == 0:
result.successfully_extracted = True
return result
@staticmethod
def mergeDebugImages(card: VisionCard) -> Image:
"""Merge all of the debugging images into one and return it."""
return VisionCardOcrUtils.stitchImages([
card.debug_image_step1_gray,
card.debug_image_step2_blurred,
card.debug_image_step3_thresholded,
card.stats_debug_image_step4_cropped_gray,
card.stats_debug_image_step5_cropped_gray_inverted,
card.stats_debug_image_step6_converted_final_ocr_input_image,
card.info_debug_image_step4_cropped_gray,
card.info_debug_image_step5_cropped_gray_inverted,
card.info_debug_image_step6_converted_final_ocr_input_image])
@staticmethod
def stitchImages(images):
"""Combine images horizontally, into a single large image."""
total_width = 0
max_height = 0
for one_image in images:
total_width += one_image.width
max_height = max(max_height, one_image.height)
result = Image.new('RGB', (total_width, max_height))
left_pad = 0
for one_image in images:
result.paste(one_image, (left_pad, 0))
left_pad += one_image.width
return result
@staticmethod
def invokeStandalone(path):
"""For local/standalone running, a method that can process an image from the filesystem or a URL."""
vision_card_image = None
if path.startswith('http'):
# Read image from the specified URL (e.g., image uploaded to a Discord channel)
vision_card_image = VisionCardOcrUtils.downloadScreenshotFromUrl(path)
else:
# Read image from the specified path
vision_card_image = VisionCardOcrUtils.loadScreenshotFromFilesystem(sys.argv[1])
vision_card = VisionCardOcrUtils.extractVisionCardFromScreenshot(vision_card_image, True)
debug_image = VisionCardOcrUtils.mergeDebugImages(vision_card)
debug_image.save('debug.png')
print(vision_card)
if __name__ == "__main__":
VisionCardOcrUtils.invokeStandalone(sys.argv[1])
|
[
"cv2.GaussianBlur",
"PIL.Image.new",
"cv2.bitwise_not",
"vision_card_common.VisionCard",
"cv2.cvtColor",
"cv2.threshold",
"pytesseract.image_to_string",
"cv2.imread",
"numpy.array",
"requests.get",
"imutils.grab_contours",
"PIL.Image.fromarray",
"cv2.boundingRect",
"cv2.inRange",
"re.compile"
] |
[((1669, 1685), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1679, 1685), False, 'import cv2\n'), ((3009, 3060), 'cv2.cvtColor', 'cv2.cvtColor', (['vision_card_image', 'cv2.COLOR_BGR2GRAY'], {}), '(vision_card_image, cv2.COLOR_BGR2GRAY)\n', (3021, 3060), False, 'import cv2\n'), ((3210, 3249), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['gray_image', '(5, 5)', '(0)'], {}), '(gray_image, (5, 5), 0)\n', (3226, 3249), False, 'import cv2\n'), ((3781, 3812), 'imutils.grab_contours', 'imutils.grab_contours', (['contours'], {}), '(contours)\n', (3802, 3812), False, 'import imutils\n'), ((7764, 7805), 'cv2.bitwise_not', 'cv2.bitwise_not', (['stats_cropped_gray_image'], {}), '(stats_cropped_gray_image)\n', (7779, 7805), False, 'import cv2\n'), ((7849, 7889), 'cv2.bitwise_not', 'cv2.bitwise_not', (['info_cropped_gray_image'], {}), '(info_cropped_gray_image)\n', (7864, 7889), False, 'import cv2\n'), ((8778, 8886), 'cv2.inRange', 'cv2.inRange', (['stats_cropped_gray_inverted_image', 'stats_lower_bound_hsv_value', 'stats_upper_bound_hsv_value'], {}), '(stats_cropped_gray_inverted_image, stats_lower_bound_hsv_value,\n stats_upper_bound_hsv_value)\n', (8789, 8886), False, 'import cv2\n'), ((8908, 9013), 'cv2.inRange', 'cv2.inRange', (['info_cropped_gray_inverted_image', 'info_lower_bound_hsv_value', 'info_upper_bound_hsv_value'], {}), '(info_cropped_gray_inverted_image, info_lower_bound_hsv_value,\n info_upper_bound_hsv_value)\n', (8919, 9013), False, 'import cv2\n'), ((9036, 9068), 'cv2.bitwise_not', 'cv2.bitwise_not', (['stats_text_mask'], {}), '(stats_text_mask)\n', (9051, 9068), False, 'import cv2\n'), ((9094, 9125), 'cv2.bitwise_not', 'cv2.bitwise_not', (['info_text_mask'], {}), '(info_text_mask)\n', (9109, 9125), False, 'import cv2\n'), ((9344, 9388), 'PIL.Image.fromarray', 'Image.fromarray', (['stats_final_ocr_input_image'], {}), '(stats_final_ocr_input_image)\n', (9359, 9388), False, 'from PIL import Image\n'), ((9436, 9479), 'PIL.Image.fromarray', 'Image.fromarray', (['info_final_ocr_input_image'], {}), '(info_final_ocr_input_image)\n', (9451, 9479), False, 'from PIL import Image\n'), ((11992, 12058), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['stats_converted_final_ocr_input_image'], {}), '(stats_converted_final_ocr_input_image)\n', (12019, 12058), False, 'import pytesseract\n'), ((12089, 12154), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['info_converted_final_ocr_input_image'], {}), '(info_converted_final_ocr_input_image)\n', (12116, 12154), False, 'import pytesseract\n'), ((25696, 25708), 'vision_card_common.VisionCard', 'VisionCard', ([], {}), '()\n', (25706, 25708), False, 'from vision_card_common import VisionCard\n'), ((26302, 26343), 're.compile', 're.compile', (['"""^[a-zA-Z0-9 \\\\+\\\\-\\\\%\\\\&]+$"""'], {}), "('^[a-zA-Z0-9 \\\\+\\\\-\\\\%\\\\&]+$')\n", (26312, 26343), False, 'import re\n'), ((29613, 29656), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(total_width, max_height)'], {}), "('RGB', (total_width, max_height))\n", (29622, 29656), False, 'from PIL import Image\n'), ((3158, 3185), 'PIL.Image.fromarray', 'Image.fromarray', (['gray_image'], {}), '(gray_image)\n', (3173, 3185), False, 'from PIL import Image\n'), ((3350, 3380), 'PIL.Image.fromarray', 'Image.fromarray', (['blurred_image'], {}), '(blurred_image)\n', (3365, 3380), False, 'from PIL import Image\n'), ((3409, 3465), 'cv2.threshold', 'cv2.threshold', (['blurred_image', '(70)', '(255)', 'cv2.THRESH_BINARY'], {}), '(blurred_image, 70, 255, cv2.THRESH_BINARY)\n', (3422, 3465), False, 'import cv2\n'), ((3573, 3607), 'PIL.Image.fromarray', 'Image.fromarray', (['thresholded_image'], {}), '(thresholded_image)\n', (3588, 3607), False, 'from PIL import Image\n'), ((4056, 4081), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (4072, 4081), False, 'import cv2\n'), ((7569, 7610), 'PIL.Image.fromarray', 'Image.fromarray', (['stats_cropped_gray_image'], {}), '(stats_cropped_gray_image)\n', (7584, 7610), False, 'from PIL import Image\n'), ((7679, 7719), 'PIL.Image.fromarray', 'Image.fromarray', (['info_cropped_gray_image'], {}), '(info_cropped_gray_image)\n', (7694, 7719), False, 'from PIL import Image\n'), ((8010, 8060), 'PIL.Image.fromarray', 'Image.fromarray', (['stats_cropped_gray_inverted_image'], {}), '(stats_cropped_gray_inverted_image)\n', (8025, 8060), False, 'from PIL import Image\n'), ((8138, 8187), 'PIL.Image.fromarray', 'Image.fromarray', (['info_cropped_gray_inverted_image'], {}), '(info_cropped_gray_inverted_image)\n', (8153, 8187), False, 'from PIL import Image\n'), ((1154, 1175), 'numpy.array', 'numpy.array', (['pilImage'], {}), '(pilImage)\n', (1165, 1175), False, 'import numpy\n'), ((1079, 1109), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n', (1091, 1109), False, 'import requests\n')]
|
# -*- coding: utf-8 -*-
"""
i_comp.py generated by WhatsOpt 1.8.2
"""
import numpy as np
from i_comp_base import ICompBase
class IComp(ICompBase):
""" An OpenMDAO component to encapsulate IComp discipline """
def compute(self, inputs, outputs):
""" IComp computation """
if self._impl:
# Docking mechanism: use implementation if referenced in .whatsopt_dock.yml file
self._impl.compute(inputs, outputs)
else:
outputs['I'] = np.ones((50,))
# Reminder: inputs of compute()
#
# inputs['h'] -> shape: (50,), type: Float
# To declare partial derivatives computation ...
#
# def setup(self):
# super(IComp, self).setup()
# self.declare_partials('*', '*')
#
# def compute_partials(self, inputs, partials):
# """ Jacobian for IComp """
#
# partials['I', 'h'] = np.zeros((50, 50))
|
[
"numpy.ones"
] |
[((519, 533), 'numpy.ones', 'np.ones', (['(50,)'], {}), '((50,))\n', (526, 533), True, 'import numpy as np\n')]
|
import glob, os
import pandas as pd
import numpy as np
import mmcv
from mmdet.apis import init_detector, inference_detector
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='Предварительная разметка видео. Результатом является csv файл с номером кадра и боксами на нем')
parser.add_argument('config', help='Конфиг по которому обучалась модель')
parser.add_argument('checkpoint', help='Файл с весами предобученной модели')
parser.add_argument('workdir', help='Папка с видеофайлами')
parser.add_argument('video', help='Название видео')
parser.add_argument('outdir', help='Директория, куда сохраняем файл с результатами')
parser.add_argument('--iou_thr', default=0.3, help='Порог, после которого бокс попадает в файл')
args = parser.parse_args()
return args
def labelling_video(config, checkpoint, work_dir, video, outdir, iou_thr):
'''
Формат данных предварительной разметки:
C(x,y) -> координаты центра бокса
w -> ширина
h -> высота
logs -> комментарий (опционально)
'''
csv_file = str(video) + '_layout.csv'
model = init_detector(config, checkpoint, device='cuda:0')
print(os.path.join(work_dir, video))
video_reader = mmcv.VideoReader(os.path.join(work_dir, video))
print(video_reader._frame_cnt)
if not os.path.exists(outdir):
os.mkdir(outdir)
layout = []
count = 0
for frame in mmcv.track_iter_progress(video_reader):
result = inference_detector(model, frame)
for i in range(len(result[0])):
if result[0][i][4] < iou_thr:
break
elif result[0][i][4] >= iou_thr:
layout.append(np.insert(result[0][i][:4], 0, count))
count += 1
layout_df = pd.DataFrame(layout, columns=['frame', 'x', 'y', 'x2', 'y2'])
layout_df['w'] = abs(layout_df['x2'] - layout_df['x'])
layout_df['h'] = abs(layout_df['y2'] - layout_df['y'])
layout_df['logs'] = np.nan
layout_df = layout_df.drop(columns=['x2', 'y2'])
layout_df = layout_df.astype({'frame' : 'int32', 'x' : 'int32', 'y' : 'int32', 'w' : 'int32', 'h' : 'int32'})
layout_df.to_csv(os.path.join(work_dir, csv_file), index=False)
if __name__ == '__main__':
args = parse_args()
if args.video == '*.mp4':
for some_video in os.listdir(args.workdir):
if some_video.endswith(".mp4"):
#for some_video in glob.glob(os.path.join(args.workdir, args.video)):
print(f'Started to process video {some_video}')
labelling_video(config=args.config,
checkpoint=args.checkpoint,
work_dir=args.workdir,
video=some_video,
outdir=args.outdir,
iou_thr=args.iou_thr)
else:
labelling_video(config=args.config,
checkpoint=args.checkpoint,
work_dir=args.workdir,
video=args.video,
outdir=args.outdir,
iou_thr=args.iou_thr)
|
[
"pandas.DataFrame",
"os.mkdir",
"argparse.ArgumentParser",
"mmdet.apis.init_detector",
"os.path.exists",
"mmdet.apis.inference_detector",
"numpy.insert",
"mmcv.track_iter_progress",
"os.path.join",
"os.listdir"
] |
[((174, 317), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Предварительная разметка видео. Результатом является csv файл с номером кадра и боксами на нем"""'}), "(description=\n 'Предварительная разметка видео. Результатом является csv файл с номером кадра и боксами на нем'\n )\n", (197, 317), False, 'import argparse\n'), ((1142, 1192), 'mmdet.apis.init_detector', 'init_detector', (['config', 'checkpoint'], {'device': '"""cuda:0"""'}), "(config, checkpoint, device='cuda:0')\n", (1155, 1192), False, 'from mmdet.apis import init_detector, inference_detector\n'), ((1444, 1482), 'mmcv.track_iter_progress', 'mmcv.track_iter_progress', (['video_reader'], {}), '(video_reader)\n', (1468, 1482), False, 'import mmcv\n'), ((1788, 1849), 'pandas.DataFrame', 'pd.DataFrame', (['layout'], {'columns': "['frame', 'x', 'y', 'x2', 'y2']"}), "(layout, columns=['frame', 'x', 'y', 'x2', 'y2'])\n", (1800, 1849), True, 'import pandas as pd\n'), ((1203, 1232), 'os.path.join', 'os.path.join', (['work_dir', 'video'], {}), '(work_dir, video)\n', (1215, 1232), False, 'import glob, os\n'), ((1270, 1299), 'os.path.join', 'os.path.join', (['work_dir', 'video'], {}), '(work_dir, video)\n', (1282, 1299), False, 'import glob, os\n'), ((1347, 1369), 'os.path.exists', 'os.path.exists', (['outdir'], {}), '(outdir)\n', (1361, 1369), False, 'import glob, os\n'), ((1379, 1395), 'os.mkdir', 'os.mkdir', (['outdir'], {}), '(outdir)\n', (1387, 1395), False, 'import glob, os\n'), ((1501, 1533), 'mmdet.apis.inference_detector', 'inference_detector', (['model', 'frame'], {}), '(model, frame)\n', (1519, 1533), False, 'from mmdet.apis import init_detector, inference_detector\n'), ((2187, 2219), 'os.path.join', 'os.path.join', (['work_dir', 'csv_file'], {}), '(work_dir, csv_file)\n', (2199, 2219), False, 'import glob, os\n'), ((2342, 2366), 'os.listdir', 'os.listdir', (['args.workdir'], {}), '(args.workdir)\n', (2352, 2366), False, 'import glob, os\n'), ((1713, 1750), 'numpy.insert', 'np.insert', (['result[0][i][:4]', '(0)', 'count'], {}), '(result[0][i][:4], 0, count)\n', (1722, 1750), True, 'import numpy as np\n')]
|
# Install the following packages (pip3 install <NAME>) before running the study code:
# seaborn
# torch
# pandas
# pystan
# arviz
import pickle
import random
import numpy as np
import pandas as pd
from generate_data import generate_data
import matplotlib.pyplot as plt
import matplotlib
import os
import time
import subprocess
import webbrowser
from machine_education_interactive_test import ts_teach_user_study, rollout_onestep_la, \
noeducate_rollout_onestep_la
#matplotlib.use('TkAgg') # Using TkAgg to set window position
def cls():
os.system('cls' if os.name=='nt' else 'clear') # To clear the console
if not os.path.exists('Results'):
os.makedirs('Results')
#window = plt.get_current_fig_manager().window
#screen_x, screen_y = window.wm_maxsize() # Screen dimensions
#dpi = plt.figure("Test").dpi # DPI used by plt
#plt.close(fig="Test")
#fig_height = round((screen_y - 100)/(2*dpi)) #Target height of each plt figure
#fig_width = fig_height*4/3 # Target width
#Set up the two plt figures on the screen at the start of the study.
#plt.interactive(True)
fig, (ax1, ax2) = plt.subplots(2, 1)
webbrowser.open("https://forms.gle/AkY5xLrPzxN43Dry7", new=2)
input("Please complete the consent form. Press ENTER to continue.")
user_id = int(input("Please input a user id"))
user_group = int(input("Please input the user group (0 or 1 or 2)"))
webbrowser.open("https://forms.gle/pvhY9BMs8BToytBw7", new=2)
input("Please complete the first part of the questionnaire. Press ENTER to continue")
if user_group == 2:
#subprocess.Popen(['open','Material/Full_Tutorial.pdf']) # Open full tutorial for group 2 (pre-trained users)
os.system("start Material/Full_Tutorial.pdf")
else:
#subprocess.Popen(['open','Material/Basic_Tutorial.pdf']) # Basic tutorial for group 0 (no-training) and group 1 (AI-trained)
os.system("start Material/Basic_Tutorial.pdf")
input("Please go through the tutorial carefully. Press ENTER to continue")
input("Please complete the next part of the questionnaire (in your browser window). Press ENTER to continue")
#For user group i, the user gets tutoring teacher if groups_tutor_or_not[i] == True.
groups_tutor_or_not = [False, True, True]
#Use the user id as the seed.
np.random.seed(user_id)
### BELOW IS IMPORTANT EXPERIMENT PARAMETERS ###
#Educability and cost. Should be tuned if there are issues.
e = 0.30
theta_1 = 0.5
# Pairs of (nr. of non-collinear variables, nr. of collinear variables).
# In increasing difficulty.
# difficulty = [(8,2), (6,4), (5,5), (4,6), (2,8)]
difficulty = [(5,3), (4,4), (3,5)]
#How many different datasets will the user face? We discussed 5 last time.
n_tasks = len(difficulty)
random.shuffle(difficulty) # Shuffle the order
#FORGET ABOUT THESE
W_typezero=(7.0, 0.0)
W_typeone=(7.0, -7.0)
experiment_results = []
csv_frames = []
for t in range(n_tasks):
if groups_tutor_or_not[user_group] is True:
pfunc = rollout_onestep_la
else:
pfunc = noeducate_rollout_onestep_la
cls()
input("Task #{} out of {}. Press ENTER to begin.".format(t+1,n_tasks))
#if t == 0:
# Set up plots before first task.
#plt.figure("X-Y",figsize=(fig_width, fig_height))
#plt.get_current_fig_manager().window.wm_geometry("+{}+{}".format(round(screen_x-fig_width*dpi),0)) # move the window
#plt.figure("X-X",figsize=(fig_width, fig_height))
#plt.get_current_fig_manager().window.wm_geometry("+{}+{}".format(round(screen_x-fig_width*dpi),round(screen_y/2 + 10))) # move the window
training_dataset = generate_data(n_noncollinear=difficulty[t][0], n_collinear=difficulty[t][1], n=100)
test_datasets = [generate_data(n_noncollinear=difficulty[t][0], n_collinear=difficulty[t][1], n=100) for _ in range(10)]
test_datasets.append(training_dataset)
pickle_return , csv_return =ts_teach_user_study(ax1=ax1, ax2=ax2, educability=e, dataset=training_dataset,
W_typezero = W_typezero,
W_typeone = W_typeone,
planning_function=pfunc,
n_interactions=16,
test_datasets=test_datasets,
n_training_noncollinear=difficulty[t][0],
n_training_collinear=difficulty[t][1], theta_1=theta_1,
theta_2=1 - theta_1, user_id = user_id, group_id = user_group, task_id = t)
experiment_results.append(pickle_return)
experiment_results[-1]["order_of_difficulty"] = difficulty[t]
experiment_results[-1]["tutor_or_not"] = groups_tutor_or_not[user_group]
experiment_results[-1]["group_id"] = user_group
experiment_results[-1]["user_id"] = user_id
experiment_results[-1]["educability"] = e
experiment_results[-1]["theta_1"] = theta_1
csv_frames.append(csv_return)
#plt.figure("X-Y")
#plt.clf()
#plt.figure("X-X")
#plt.clf()
ax1.cla()
ax2.cla()
input("End of task. Please take a short break. Press ENTER to continue.")
# csv_frames.append(difficulty)
with open("Results/participant{}_group{}_{}.csv".format(user_id, user_group,time.time()),
'wb') as pickle_file:
pickle.dump(experiment_results, pickle_file)
csv_df = pd.concat(csv_frames, ignore_index = True)
csv_df.to_csv("Results/participant{}_group{}_{}.csv".format(user_id, user_group,time.time()), sep=',')
input("Please complete the final part of the questionnaire (in your browser window). Press ENTER to finish the study.")
|
[
"webbrowser.open",
"generate_data.generate_data",
"numpy.random.seed",
"os.makedirs",
"pickle.dump",
"random.shuffle",
"os.path.exists",
"os.system",
"time.time",
"machine_education_interactive_test.ts_teach_user_study",
"matplotlib.pyplot.subplots",
"pandas.concat"
] |
[((1099, 1117), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (1111, 1117), True, 'import matplotlib.pyplot as plt\n'), ((1120, 1181), 'webbrowser.open', 'webbrowser.open', (['"""https://forms.gle/AkY5xLrPzxN43Dry7"""'], {'new': '(2)'}), "('https://forms.gle/AkY5xLrPzxN43Dry7', new=2)\n", (1135, 1181), False, 'import webbrowser\n'), ((1369, 1430), 'webbrowser.open', 'webbrowser.open', (['"""https://forms.gle/pvhY9BMs8BToytBw7"""'], {'new': '(2)'}), "('https://forms.gle/pvhY9BMs8BToytBw7', new=2)\n", (1384, 1430), False, 'import webbrowser\n'), ((2239, 2262), 'numpy.random.seed', 'np.random.seed', (['user_id'], {}), '(user_id)\n', (2253, 2262), True, 'import numpy as np\n'), ((2691, 2717), 'random.shuffle', 'random.shuffle', (['difficulty'], {}), '(difficulty)\n', (2705, 2717), False, 'import random\n'), ((5528, 5568), 'pandas.concat', 'pd.concat', (['csv_frames'], {'ignore_index': '(True)'}), '(csv_frames, ignore_index=True)\n', (5537, 5568), True, 'import pandas as pd\n'), ((548, 596), 'os.system', 'os.system', (["('cls' if os.name == 'nt' else 'clear')"], {}), "('cls' if os.name == 'nt' else 'clear')\n", (557, 596), False, 'import os\n'), ((626, 651), 'os.path.exists', 'os.path.exists', (['"""Results"""'], {}), "('Results')\n", (640, 651), False, 'import os\n'), ((657, 679), 'os.makedirs', 'os.makedirs', (['"""Results"""'], {}), "('Results')\n", (668, 679), False, 'import os\n'), ((1658, 1703), 'os.system', 'os.system', (['"""start Material/Full_Tutorial.pdf"""'], {}), "('start Material/Full_Tutorial.pdf')\n", (1667, 1703), False, 'import os\n'), ((1844, 1890), 'os.system', 'os.system', (['"""start Material/Basic_Tutorial.pdf"""'], {}), "('start Material/Basic_Tutorial.pdf')\n", (1853, 1890), False, 'import os\n'), ((3565, 3652), 'generate_data.generate_data', 'generate_data', ([], {'n_noncollinear': 'difficulty[t][0]', 'n_collinear': 'difficulty[t][1]', 'n': '(100)'}), '(n_noncollinear=difficulty[t][0], n_collinear=difficulty[t][1],\n n=100)\n', (3578, 3652), False, 'from generate_data import generate_data\n'), ((3850, 4235), 'machine_education_interactive_test.ts_teach_user_study', 'ts_teach_user_study', ([], {'ax1': 'ax1', 'ax2': 'ax2', 'educability': 'e', 'dataset': 'training_dataset', 'W_typezero': 'W_typezero', 'W_typeone': 'W_typeone', 'planning_function': 'pfunc', 'n_interactions': '(16)', 'test_datasets': 'test_datasets', 'n_training_noncollinear': 'difficulty[t][0]', 'n_training_collinear': 'difficulty[t][1]', 'theta_1': 'theta_1', 'theta_2': '(1 - theta_1)', 'user_id': 'user_id', 'group_id': 'user_group', 'task_id': 't'}), '(ax1=ax1, ax2=ax2, educability=e, dataset=\n training_dataset, W_typezero=W_typezero, W_typeone=W_typeone,\n planning_function=pfunc, n_interactions=16, test_datasets=test_datasets,\n n_training_noncollinear=difficulty[t][0], n_training_collinear=\n difficulty[t][1], theta_1=theta_1, theta_2=1 - theta_1, user_id=user_id,\n group_id=user_group, task_id=t)\n', (3869, 4235), False, 'from machine_education_interactive_test import ts_teach_user_study, rollout_onestep_la, noeducate_rollout_onestep_la\n'), ((5473, 5517), 'pickle.dump', 'pickle.dump', (['experiment_results', 'pickle_file'], {}), '(experiment_results, pickle_file)\n', (5484, 5517), False, 'import pickle\n'), ((3670, 3757), 'generate_data.generate_data', 'generate_data', ([], {'n_noncollinear': 'difficulty[t][0]', 'n_collinear': 'difficulty[t][1]', 'n': '(100)'}), '(n_noncollinear=difficulty[t][0], n_collinear=difficulty[t][1],\n n=100)\n', (3683, 3757), False, 'from generate_data import generate_data\n'), ((5651, 5662), 'time.time', 'time.time', ([], {}), '()\n', (5660, 5662), False, 'import time\n'), ((5423, 5434), 'time.time', 'time.time', ([], {}), '()\n', (5432, 5434), False, 'import time\n')]
|
'''mclotstrats.py: A simple Monte Carlo algorithm for lottery games
Developed using Pythonista for iPhone/iPad
(c) <NAME>, 2017
*Lottery customization: no. of balls (balls) in lottery; lowest (low) and highest (high) numbers in lottery
*Game customization: number of lotteries played (N); number of tickets played (ticketN) per N lottery
'''
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from t4exer import factorial as fac
#N=int(fac(49)/(fac(6)*fac(49-6)))
def mcG(N=100,balls=3,low=1,high=49,ticketN=1):
#developer: <NAME>
#with plt.xkcd():
x=np.linspace(0,N,N)
# L_draw=sample(balls,low,high)
ballpop=range(low,high+1)
ticket=np.zeros([ticketN,balls])
ticketcorr=np.zeros([ticketN,balls])
for p in range(0,ticketN):
ticket[p]=random.sample(ballpop,balls)
# lottery numbers for tickets bought
ticketcorr[p]=np.sort(ticket[p])
sum_winners=np.zeros(N)
for j in range(0,N):
# player_game=sample(balls,low,high)
winners=np.zeros(ticketN)
ballpop=range(low,high+1)
L_draw=random.sample(ballpop,balls)
L_drawsort=np.sort(L_draw)
print('lottery draw #{}: {}'.format(j+1,L_draw))
for i in range(0,ticketN):
if np.array_equal(ticketcorr[i],L_drawsort)==True:
winners[i]=1
else:
winners[i]=0
sum_winners[j]=np.sum(winners)
grandsum_winners=np.sum(sum_winners)
print ('____________________________________________________')
print ('number of times played: ', N)
print ('tickets bought per played lottery: ', ticketN)
print ('winning tickets: ',ticket)
print ('lottery winning timeline: ',sum_winners)
print ('# times won: ',grandsum_winners)
print ('investment for $1 lottery: $', N*ticketN*1)
plt.ylabel("winning tickets")
plt.xlim(-0.2,N+0.2)
#plt.ylim(-0.2)
plt.xlabel("Lottery timeline")
plt.title("Lottery Draw")
plt.plot(x,sum_winners,'o',color='magenta')
plt.show()
# plt.clf()
# plt.cla()
# plt.close()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.sum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"random.sample",
"numpy.zeros",
"numpy.sort",
"numpy.linspace",
"numpy.array_equal",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] |
[((593, 613), 'numpy.linspace', 'np.linspace', (['(0)', 'N', 'N'], {}), '(0, N, N)\n', (604, 613), True, 'import numpy as np\n'), ((683, 709), 'numpy.zeros', 'np.zeros', (['[ticketN, balls]'], {}), '([ticketN, balls])\n', (691, 709), True, 'import numpy as np\n'), ((722, 748), 'numpy.zeros', 'np.zeros', (['[ticketN, balls]'], {}), '([ticketN, balls])\n', (730, 748), True, 'import numpy as np\n'), ((910, 921), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (918, 921), True, 'import numpy as np\n'), ((1368, 1387), 'numpy.sum', 'np.sum', (['sum_winners'], {}), '(sum_winners)\n', (1374, 1387), True, 'import numpy as np\n'), ((1746, 1775), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""winning tickets"""'], {}), "('winning tickets')\n", (1756, 1775), True, 'import matplotlib.pyplot as plt\n'), ((1778, 1801), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-0.2)', '(N + 0.2)'], {}), '(-0.2, N + 0.2)\n', (1786, 1801), True, 'import matplotlib.pyplot as plt\n'), ((1819, 1849), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Lottery timeline"""'], {}), "('Lottery timeline')\n", (1829, 1849), True, 'import matplotlib.pyplot as plt\n'), ((1852, 1877), 'matplotlib.pyplot.title', 'plt.title', (['"""Lottery Draw"""'], {}), "('Lottery Draw')\n", (1861, 1877), True, 'import matplotlib.pyplot as plt\n'), ((1881, 1927), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'sum_winners', '"""o"""'], {'color': '"""magenta"""'}), "(x, sum_winners, 'o', color='magenta')\n", (1889, 1927), True, 'import matplotlib.pyplot as plt\n'), ((1927, 1937), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1935, 1937), True, 'import matplotlib.pyplot as plt\n'), ((791, 820), 'random.sample', 'random.sample', (['ballpop', 'balls'], {}), '(ballpop, balls)\n', (804, 820), False, 'import random\n'), ((875, 893), 'numpy.sort', 'np.sort', (['ticket[p]'], {}), '(ticket[p])\n', (882, 893), True, 'import numpy as np\n'), ((999, 1016), 'numpy.zeros', 'np.zeros', (['ticketN'], {}), '(ticketN)\n', (1007, 1016), True, 'import numpy as np\n'), ((1058, 1087), 'random.sample', 'random.sample', (['ballpop', 'balls'], {}), '(ballpop, balls)\n', (1071, 1087), False, 'import random\n'), ((1102, 1117), 'numpy.sort', 'np.sort', (['L_draw'], {}), '(L_draw)\n', (1109, 1117), True, 'import numpy as np\n'), ((1333, 1348), 'numpy.sum', 'np.sum', (['winners'], {}), '(winners)\n', (1339, 1348), True, 'import numpy as np\n'), ((1211, 1252), 'numpy.array_equal', 'np.array_equal', (['ticketcorr[i]', 'L_drawsort'], {}), '(ticketcorr[i], L_drawsort)\n', (1225, 1252), True, 'import numpy as np\n')]
|
import numpy as np
from minkf import utils
def kf_predict(xest, Cest, M, Q, u=None):
"""
Prediction step of the Kalman filter, xp = M*xest + u + Q.
Parameters
----------
xest: np.array of length n, posterior estimate for the current time
Cest: np.array of shape (n, n), posterior covariance for the current step
M: np.array of shape (n, n), dynamics model matrix
Q: np.array of shape (n, n), model error covariance matrix
u: np.array of length n, optional control input
Returns
-------
xp, Cp: predicted mean and covariance
"""
xp = M.dot(xest) if u is None else M.dot(xest) + u
Cp = M.dot(Cest.dot(M.T)) + Q
return xp, Cp
def kf_update(y, xp, Cp, K, R):
"""
Update step of the Kalman filter
Parameters
----------
y: np.array of length m, observation vector, if there are any NaNs in the
vector, the observation is considered missing
xp: np.array of length n, predicted (prior) mean
Cp: np.array of shape (n, n), predicted (prior) covariance
K: np.array of shape (m, n), observation model matrix
R: np.array of shape (m, m), observation error covariance
Returns
-------
xest, Cest: estimated mean and covariance
"""
CpKT = Cp.dot(K.T)
obs_precision = K.dot(CpKT) + R
G = utils.rsolve(obs_precision, CpKT)
obs_missing = np.any(np.isnan(y))
xest = xp + G.dot(y-K.dot(xp)) if not obs_missing else xp
I_GK = np.eye(Cp.shape[0])-G.dot(K)
Cest = I_GK.dot(Cp) if not obs_missing else Cp
return xest, Cest
def run_filter(
y, x0, Cest0, M, K, Q, R,
u=None, likelihood=False, predict_y=False
):
"""
Run the Kalman filter.
Parameters
----------
y: list of np.arrays of length m, observation vectors
x0: np.array of length n, initial state
Cest0: np.array of shape (n, n), initial covariance
M: np.array or list of np.arrays of shape (n, n), dynamics model matrices
K: np.array or list of np.arrays of shape (m, n), observation model matrices
Q: np.array or list of np.arrays of shape (n, n), model error covariances
R: np.array or list of np.arrays of shape (m, m), obs error covariances
u: list of np.arrays of length n, optional control inputs
likelihood: bool, calculate likelihood along with the filtering
predict_y: bool, include predicted observations and covariance
Returns
-------
results dict = {
'x': estimated states
'C': covariances for the estimated states
'loglike': log-likelihood of the data if calculated, None otherwise
'xp': predicted means (helper variables for further calculations)
'Cp': predicted covariances (helpers for further calculations)
'yp': observation predicted at the predicted mean state
'Cyp': covariance of predicted observation
}
"""
xest = x0
Cest = Cest0
nobs = len(y)
# transform inputs into lists of np.arrays (unless they already are)
Mlist = M if type(M) == list else nobs * [M]
Klist = K if type(K) == list else nobs * [K]
Qlist = Q if type(Q) == list else nobs * [Q]
Rlist = R if type(R) == list else nobs * [R]
uList = u if type(u) == list else nobs * [u]
# space for saving end results
xp_all = nobs * [None]
Cp_all = nobs * [None]
xest_all = nobs * [None]
Cest_all = nobs * [None]
loglike = 0 if likelihood else None
yp_all = nobs * [None] if predict_y else None
Cyp_all = nobs * [None] if predict_y else None
for i in range(nobs):
Ki = Klist[i]
Ri = Rlist[i]
xp, Cp = kf_predict(xest, Cest, Mlist[i], Qlist[i], u=uList[i])
xest, Cest = kf_update(y[i], xp, Cp, Ki, Ri)
xp_all[i] = xp
Cp_all[i] = Cp
xest_all[i] = xest
Cest_all[i] = Cest
if likelihood:
yp = Ki.dot(xp)
Cyp = Ki.dot(Cp).dot(Ki.T) + Ri
loglike += utils.normal_log_pdf(y[i], yp, Cyp) if not np.any(np.isnan(y[i])) else 0.0
if predict_y:
yp_all[i] = yp
Cyp_all[i] = Cyp
results = {
'xp': xp_all,
'Cp': Cp_all,
'yp': yp_all,
'Cyp': Cyp_all,
'x': xest_all,
'C': Cest_all,
'loglike': loglike
}
return results
def run_smoother(y, x0, Cest0, M, K, Q, R, u=None):
"""
Run the Kalman smoother.
Parameters
----------
y: list of np.arrays of length m, observation vectors
x0: np.array of length n, initial state
Cest0: np.array of shape (n, n), initial covariance
M: np.array or list of np.arrays of shape (n, n), dynamics model matrices
K: np.array or list of np.arrays of shape (m, n), observation model matrices
Q: np.array or list of np.arrays of shape (n, n), model error covariances
R: np.array or list of np.arrays of shape (m, m), obs error covariances
u: list of np.arrays of length n, optional control inputs
Returns
-------
results dict = {
'x': smoothed states
'C': covariances for the smoothed states
}
"""
# run the filter first
kf_res = run_filter(y, x0, Cest0, M, K, Q, R, u=u)
xest = kf_res['x']
Cest = kf_res['C']
xp = kf_res['xp']
Cp = kf_res['Cp']
nobs = len(y)
xs = nobs * [None]
Cs = nobs * [None]
xs[-1] = xest[-1]
Cs[-1] = Cest[-1]
# transform inputs into lists of np.arrays (unless they already are)
Mlist = M if type(M) == list else nobs * [M]
# backward recursion
for i in range(nobs-2, -1, -1):
G = utils.rsolve(Cp[i+1], Cest[i].dot(Mlist[i+1].T))
xs[i] = xest[i] + G.dot(xs[i+1] - xp[i+1])
Cs[i] = Cest[i] + G.dot(Cs[i+1] - Cp[i+1]).dot(G.T)
results = {
'x': xs,
'C': Cs
}
return results
def sample(res_kf, M, Q, u=None, nsamples=1):
"""
Sample from the posterior of the states given the observations.
Parameters
----------
res_kf: results dict from the Kalman filter run
M: np.array or list of np.arrays of shape (n, n), dynamics model matrices
Q: np.array or list of np.arrays of shape (n, n), model error covariances
u: list of np.arrays of length n, optional control inputs
nsamples: int, number of samples generated
Returns
-------
list of state samples
"""
nobs = len(res_kf['x'])
ns = len(res_kf['x'][0])
Mlist = M if type(M) == list else nobs * [M]
Qlist = Q if type(M) == list else nobs * [Q]
uList = u if u is not None else nobs * [np.zeros(ns)]
MP_k = [M.dot(P) for M, P in zip(Mlist, res_kf['C'])]
MtQinv = [utils.rsolve(Q, M.T) for M, Q in zip(Mlist, Qlist)]
Sig_k = [P - MP.T.dot(np.linalg.solve(MP.dot(M.T) + Q, MP))
for P, MP, Q in zip(res_kf['C'], MP_k, Qlist)]
def sample_one():
xsample = np.zeros((nobs, ns))
xsample[-1] = np.random.multivariate_normal(
res_kf['x'][-1], res_kf['C'][-1]
)
for i in reversed(range(nobs-1)):
mu_i = Sig_k[i].dot(
MtQinv[i].dot(
xsample[i+1, :]-uList[i]
) + np.linalg.solve(res_kf['C'][i], res_kf['x'][i])
)
xsample[i] = np.random.multivariate_normal(mu_i, Sig_k[i])
return np.squeeze(xsample)
return [sample_one() for i in range(nsamples)]
|
[
"minkf.utils.normal_log_pdf",
"numpy.zeros",
"numpy.isnan",
"numpy.random.multivariate_normal",
"numpy.squeeze",
"numpy.eye",
"minkf.utils.rsolve",
"numpy.linalg.solve"
] |
[((1314, 1347), 'minkf.utils.rsolve', 'utils.rsolve', (['obs_precision', 'CpKT'], {}), '(obs_precision, CpKT)\n', (1326, 1347), False, 'from minkf import utils\n'), ((1374, 1385), 'numpy.isnan', 'np.isnan', (['y'], {}), '(y)\n', (1382, 1385), True, 'import numpy as np\n'), ((1460, 1479), 'numpy.eye', 'np.eye', (['Cp.shape[0]'], {}), '(Cp.shape[0])\n', (1466, 1479), True, 'import numpy as np\n'), ((6652, 6672), 'minkf.utils.rsolve', 'utils.rsolve', (['Q', 'M.T'], {}), '(Q, M.T)\n', (6664, 6672), False, 'from minkf import utils\n'), ((6870, 6890), 'numpy.zeros', 'np.zeros', (['(nobs, ns)'], {}), '((nobs, ns))\n', (6878, 6890), True, 'import numpy as np\n'), ((6913, 6976), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (["res_kf['x'][-1]", "res_kf['C'][-1]"], {}), "(res_kf['x'][-1], res_kf['C'][-1])\n", (6942, 6976), True, 'import numpy as np\n'), ((7320, 7339), 'numpy.squeeze', 'np.squeeze', (['xsample'], {}), '(xsample)\n', (7330, 7339), True, 'import numpy as np\n'), ((7258, 7303), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mu_i', 'Sig_k[i]'], {}), '(mu_i, Sig_k[i])\n', (7287, 7303), True, 'import numpy as np\n'), ((3953, 3988), 'minkf.utils.normal_log_pdf', 'utils.normal_log_pdf', (['y[i]', 'yp', 'Cyp'], {}), '(y[i], yp, Cyp)\n', (3973, 3988), False, 'from minkf import utils\n'), ((6565, 6577), 'numpy.zeros', 'np.zeros', (['ns'], {}), '(ns)\n', (6573, 6577), True, 'import numpy as np\n'), ((7171, 7218), 'numpy.linalg.solve', 'np.linalg.solve', (["res_kf['C'][i]", "res_kf['x'][i]"], {}), "(res_kf['C'][i], res_kf['x'][i])\n", (7186, 7218), True, 'import numpy as np\n'), ((4003, 4017), 'numpy.isnan', 'np.isnan', (['y[i]'], {}), '(y[i])\n', (4011, 4017), True, 'import numpy as np\n')]
|
# Copyright 2019, The Jelly Bean World Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
from __future__ import absolute_import, division, print_function
from math import ceil, floor, pi
from .direction import Direction
try:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection, PatchCollection
from matplotlib.patches import Circle, Rectangle, RegularPolygon
modules_loaded = True
except ImportError:
modules_loaded = False
__all__ = ['MapVisualizerError', 'MapVisualizer']
AGENT_RADIUS = 0.5
ITEM_RADIUS = 0.4
MAXIMUM_SCENT = 0.9
_FIGURE_COUNTER = 1
class MapVisualizerError(Exception):
pass
def agent_position(direction):
if direction == Direction.UP:
return (0, -0.1), 0
elif direction == Direction.DOWN:
return (0, 0.1), pi
elif direction == Direction.LEFT:
return (0.1, 0), pi/2
elif direction == Direction.RIGHT:
return (-0.1, 0), 3*pi/2
class MapVisualizer(object):
def __init__(self, sim, sim_config, bottom_left, top_right, show_agent_perspective=True, SAVE_DIR='./render_folder'):
global _FIGURE_COUNTER
if not modules_loaded:
raise ImportError("numpy and matplotlib are required to use MapVisualizer.")
plt.ion()
self._sim = sim
self._config = sim_config
self._xlim = [bottom_left[0], top_right[0]]
self._ylim = [bottom_left[1], top_right[1]]
self._fignum = 'MapVisualizer Figure ' + str(_FIGURE_COUNTER)
_FIGURE_COUNTER += 1
if show_agent_perspective:
self._fig, axes = plt.subplots(nrows=1, ncols=2, num=self._fignum)
self._ax = axes[0]
self._ax_agent = axes[1]
self._fig.set_size_inches((18, 9))
else:
self._fig, self._ax = plt.subplots(num=self._fignum)
self._ax_agent = None
self._fig.set_size_inches((9, 9))
self._fig.tight_layout()
# used for saving the renderings
self.ctr = 0
self.SAVE_DIR = SAVE_DIR
def __del__(self):
plt.close(self._fig)
def set_viewbox(self, bottom_left, top_right):
self._xlim = [bottom_left[0], top_right[0]]
self._ylim = [bottom_left[1], top_right[1]]
def draw(self):
if not plt.fignum_exists(self._fignum):
raise MapVisualizerError('The figure is closed')
map = self._sim._map((int(floor(self._xlim[0])), int(floor(self._ylim[0]))), (int(ceil(self._xlim[1])), int(ceil(self._ylim[1]))))
n = self._config.patch_size
self._ax.clear()
self._ax.set_xlim(self._xlim)
self._ax.set_ylim(self._ylim)
for patch in map:
(patch_position, fixed, scent, vision, items, agents) = patch
color = (0, 0, 0, 0.3) if fixed else (0, 0, 0, 0.1)
vertical_lines = np.empty((n + 1, 2, 2))
vertical_lines[:,0,0] = patch_position[0]*n + np.arange(n + 1) - 0.5
vertical_lines[:,0,1] = patch_position[1]*n - 0.5
vertical_lines[:,1,0] = patch_position[0]*n + np.arange(n + 1) - 0.5
vertical_lines[:,1,1] = patch_position[1]*n + n - 0.5
vertical_line_col = LineCollection(vertical_lines, colors=color, linewidths=0.4, linestyle='solid')
self._ax.add_collection(vertical_line_col)
horizontal_lines = np.empty((n + 1, 2, 2))
horizontal_lines[:,0,0] = patch_position[0]*n - 0.5
horizontal_lines[:,0,1] = patch_position[1]*n + np.arange(n + 1) - 0.5
horizontal_lines[:,1,0] = patch_position[0]*n + n - 0.5
horizontal_lines[:,1,1] = patch_position[1]*n + np.arange(n + 1) - 0.5
horizontal_line_col = LineCollection(horizontal_lines, colors=color, linewidths=0.4, linestyle='solid')
self._ax.add_collection(horizontal_line_col)
patches = []
for agent in agents:
(agent_pos, angle) = agent_position(Direction(agent[2]))
patches.append(RegularPolygon((agent[0] + agent_pos[0], agent[1] + agent_pos[1]), 3,
radius=AGENT_RADIUS, orientation=angle, facecolor=self._config.agent_color,
edgecolor=(0,0,0), linestyle='solid', linewidth=0.4))
for item in items:
(type, position) = item
if (self._config.items[type].blocks_movement):
patches.append(Rectangle((position[0] - 0.5, position[1] - 0.5), 1.0, 1.0,
facecolor=self._config.items[type].color, edgecolor=(0,0,0), linestyle='solid', linewidth = 0.4))
else:
patches.append(Circle(position, ITEM_RADIUS, facecolor=self._config.items[type].color,
edgecolor=(0,0,0), linestyle='solid', linewidth=0.4))
# convert 'scent' to a numpy array and transform into a subtractive color space (so zero is white)
scent_img = np.clip(np.log(scent**0.4 + 1) / MAXIMUM_SCENT, 0.0, 1.0)
scent_img = 1.0 - 0.5 * np.dot(scent_img, np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]))
self._ax.imshow(np.rot90(scent_img),
extent=(patch_position[0]*n - 0.5, patch_position[0]*n + n - 0.5,
patch_position[1]*n - 0.5, patch_position[1]*n + n - 0.5))
self._ax.add_collection(PatchCollection(patches, match_original=True))
# draw the agent's perspective
if self._ax_agent != None and len(self._sim.agents) > 0:
agent_ids = sorted(self._sim.agents.keys())
agent = self._sim.agents[agent_ids[0]]
R = self._config.vision_range
self._ax_agent.clear()
self._ax_agent.set_xlim([-R - 0.5, R + 0.5])
self._ax_agent.set_ylim([-R - 0.5, R + 0.5])
vertical_lines = np.empty((2*R, 2, 2))
vertical_lines[:,0,0] = np.arange(2*R) - R + 0.5
vertical_lines[:,0,1] = -R - 0.5
vertical_lines[:,1,0] = np.arange(2*R) - R + 0.5
vertical_lines[:,1,1] = R + 0.5
vertical_line_col = LineCollection(vertical_lines, colors=(0, 0, 0, 0.3), linewidths=0.4, linestyle='solid')
self._ax_agent.add_collection(vertical_line_col)
horizontal_lines = np.empty((2*R, 2, 2))
horizontal_lines[:,0,0] = -R - 0.5
horizontal_lines[:,0,1] = np.arange(2*R) - R + 0.5
horizontal_lines[:,1,0] = R + 0.5
horizontal_lines[:,1,1] = np.arange(2*R) - R + 0.5
horizontal_line_col = LineCollection(horizontal_lines, colors=(0, 0, 0, 0.3), linewidths=0.4, linestyle='solid')
self._ax_agent.add_collection(horizontal_line_col)
# convert 'vision' to a numpy array and transform into a subtractive color space (so zero is white)
vision_img = agent.vision()
vision_img = 1.0 - 0.5 * np.dot(vision_img, np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]))
self._ax_agent.imshow(np.rot90(vision_img),
extent=(-R - 0.5, R + 0.5, -R - 0.5, R + 0.5))
patches = []
(agent_pos, angle) = agent_position(Direction.UP)
patches.append(RegularPolygon(agent_pos, 3, radius=AGENT_RADIUS, orientation=angle,
facecolor=self._config.agent_color, edgecolor=(0,0,0), linestyle='solid', linewidth=0.4))
self._ax_agent.add_collection(PatchCollection(patches, match_original=True))
self._pause(1.0e-16)
# save the figure
self.ctr += 1
plt.savefig('{}/vis_step_{}'.format(self.SAVE_DIR, self.ctr))
plt.draw()
self._xlim = self._ax.get_xlim()
self._ylim = self._ax.get_ylim()
def _pause(self, interval):
backend = plt.rcParams['backend']
if backend in matplotlib.rcsetup.interactive_bk:
figManager = matplotlib._pylab_helpers.Gcf.get_active()
if figManager is not None:
canvas = figManager.canvas
if canvas.figure.stale:
canvas.draw()
canvas.start_event_loop(interval)
return
|
[
"matplotlib.pyplot.fignum_exists",
"matplotlib.collections.LineCollection",
"matplotlib.patches.RegularPolygon",
"numpy.log",
"math.ceil",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.close",
"numpy.empty",
"math.floor",
"matplotlib.patches.Circle",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.ion",
"numpy.rot90",
"numpy.arange",
"numpy.array",
"matplotlib.collections.PatchCollection",
"matplotlib.pyplot.subplots",
"matplotlib._pylab_helpers.Gcf.get_active"
] |
[((1834, 1843), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1841, 1843), True, 'import matplotlib.pyplot as plt\n'), ((2654, 2674), 'matplotlib.pyplot.close', 'plt.close', (['self._fig'], {}), '(self._fig)\n', (2663, 2674), True, 'import matplotlib.pyplot as plt\n'), ((8243, 8253), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (8251, 8253), True, 'import matplotlib.pyplot as plt\n'), ((2170, 2218), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'num': 'self._fignum'}), '(nrows=1, ncols=2, num=self._fignum)\n', (2182, 2218), True, 'import matplotlib.pyplot as plt\n'), ((2382, 2412), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'num': 'self._fignum'}), '(num=self._fignum)\n', (2394, 2412), True, 'import matplotlib.pyplot as plt\n'), ((2867, 2898), 'matplotlib.pyplot.fignum_exists', 'plt.fignum_exists', (['self._fignum'], {}), '(self._fignum)\n', (2884, 2898), True, 'import matplotlib.pyplot as plt\n'), ((3431, 3454), 'numpy.empty', 'np.empty', (['(n + 1, 2, 2)'], {}), '((n + 1, 2, 2))\n', (3439, 3454), True, 'import numpy as np\n'), ((3777, 3856), 'matplotlib.collections.LineCollection', 'LineCollection', (['vertical_lines'], {'colors': 'color', 'linewidths': '(0.4)', 'linestyle': '"""solid"""'}), "(vertical_lines, colors=color, linewidths=0.4, linestyle='solid')\n", (3791, 3856), False, 'from matplotlib.collections import LineCollection, PatchCollection\n'), ((3944, 3967), 'numpy.empty', 'np.empty', (['(n + 1, 2, 2)'], {}), '((n + 1, 2, 2))\n', (3952, 3967), True, 'import numpy as np\n'), ((4300, 4386), 'matplotlib.collections.LineCollection', 'LineCollection', (['horizontal_lines'], {'colors': 'color', 'linewidths': '(0.4)', 'linestyle': '"""solid"""'}), "(horizontal_lines, colors=color, linewidths=0.4, linestyle=\n 'solid')\n", (4314, 4386), False, 'from matplotlib.collections import LineCollection, PatchCollection\n'), ((6448, 6471), 'numpy.empty', 'np.empty', (['(2 * R, 2, 2)'], {}), '((2 * R, 2, 2))\n', (6456, 6471), True, 'import numpy as np\n'), ((6713, 6805), 'matplotlib.collections.LineCollection', 'LineCollection', (['vertical_lines'], {'colors': '(0, 0, 0, 0.3)', 'linewidths': '(0.4)', 'linestyle': '"""solid"""'}), "(vertical_lines, colors=(0, 0, 0, 0.3), linewidths=0.4,\n linestyle='solid')\n", (6727, 6805), False, 'from matplotlib.collections import LineCollection, PatchCollection\n'), ((6895, 6918), 'numpy.empty', 'np.empty', (['(2 * R, 2, 2)'], {}), '((2 * R, 2, 2))\n', (6903, 6918), True, 'import numpy as np\n'), ((7170, 7264), 'matplotlib.collections.LineCollection', 'LineCollection', (['horizontal_lines'], {'colors': '(0, 0, 0, 0.3)', 'linewidths': '(0.4)', 'linestyle': '"""solid"""'}), "(horizontal_lines, colors=(0, 0, 0, 0.3), linewidths=0.4,\n linestyle='solid')\n", (7184, 7264), False, 'from matplotlib.collections import LineCollection, PatchCollection\n'), ((8493, 8535), 'matplotlib._pylab_helpers.Gcf.get_active', 'matplotlib._pylab_helpers.Gcf.get_active', ([], {}), '()\n', (8533, 8535), False, 'import matplotlib\n'), ((5737, 5756), 'numpy.rot90', 'np.rot90', (['scent_img'], {}), '(scent_img)\n', (5745, 5756), True, 'import numpy as np\n'), ((5968, 6013), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['patches'], {'match_original': '(True)'}), '(patches, match_original=True)\n', (5983, 6013), False, 'from matplotlib.collections import LineCollection, PatchCollection\n'), ((7612, 7632), 'numpy.rot90', 'np.rot90', (['vision_img'], {}), '(vision_img)\n', (7620, 7632), True, 'import numpy as np\n'), ((7816, 7984), 'matplotlib.patches.RegularPolygon', 'RegularPolygon', (['agent_pos', '(3)'], {'radius': 'AGENT_RADIUS', 'orientation': 'angle', 'facecolor': 'self._config.agent_color', 'edgecolor': '(0, 0, 0)', 'linestyle': '"""solid"""', 'linewidth': '(0.4)'}), "(agent_pos, 3, radius=AGENT_RADIUS, orientation=angle,\n facecolor=self._config.agent_color, edgecolor=(0, 0, 0), linestyle=\n 'solid', linewidth=0.4)\n", (7830, 7984), False, 'from matplotlib.patches import Circle, Rectangle, RegularPolygon\n'), ((8038, 8083), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['patches'], {'match_original': '(True)'}), '(patches, match_original=True)\n', (8053, 8083), False, 'from matplotlib.collections import LineCollection, PatchCollection\n'), ((2995, 3015), 'math.floor', 'floor', (['self._xlim[0]'], {}), '(self._xlim[0])\n', (3000, 3015), False, 'from math import ceil, floor, pi\n'), ((3022, 3042), 'math.floor', 'floor', (['self._ylim[0]'], {}), '(self._ylim[0])\n', (3027, 3042), False, 'from math import ceil, floor, pi\n'), ((3051, 3070), 'math.ceil', 'ceil', (['self._xlim[1]'], {}), '(self._xlim[1])\n', (3055, 3070), False, 'from math import ceil, floor, pi\n'), ((3077, 3096), 'math.ceil', 'ceil', (['self._ylim[1]'], {}), '(self._ylim[1])\n', (3081, 3096), False, 'from math import ceil, floor, pi\n'), ((3513, 3529), 'numpy.arange', 'np.arange', (['(n + 1)'], {}), '(n + 1)\n', (3522, 3529), True, 'import numpy as np\n'), ((3656, 3672), 'numpy.arange', 'np.arange', (['(n + 1)'], {}), '(n + 1)\n', (3665, 3672), True, 'import numpy as np\n'), ((4092, 4108), 'numpy.arange', 'np.arange', (['(n + 1)'], {}), '(n + 1)\n', (4101, 4108), True, 'import numpy as np\n'), ((4243, 4259), 'numpy.arange', 'np.arange', (['(n + 1)'], {}), '(n + 1)\n', (4252, 4259), True, 'import numpy as np\n'), ((4602, 4811), 'matplotlib.patches.RegularPolygon', 'RegularPolygon', (['(agent[0] + agent_pos[0], agent[1] + agent_pos[1])', '(3)'], {'radius': 'AGENT_RADIUS', 'orientation': 'angle', 'facecolor': 'self._config.agent_color', 'edgecolor': '(0, 0, 0)', 'linestyle': '"""solid"""', 'linewidth': '(0.4)'}), "((agent[0] + agent_pos[0], agent[1] + agent_pos[1]), 3,\n radius=AGENT_RADIUS, orientation=angle, facecolor=self._config.\n agent_color, edgecolor=(0, 0, 0), linestyle='solid', linewidth=0.4)\n", (4616, 4811), False, 'from matplotlib.patches import Circle, Rectangle, RegularPolygon\n'), ((5560, 5584), 'numpy.log', 'np.log', (['(scent ** 0.4 + 1)'], {}), '(scent ** 0.4 + 1)\n', (5566, 5584), True, 'import numpy as np\n'), ((6506, 6522), 'numpy.arange', 'np.arange', (['(2 * R)'], {}), '(2 * R)\n', (6515, 6522), True, 'import numpy as np\n'), ((6612, 6628), 'numpy.arange', 'np.arange', (['(2 * R)'], {}), '(2 * R)\n', (6621, 6628), True, 'import numpy as np\n'), ((7002, 7018), 'numpy.arange', 'np.arange', (['(2 * R)'], {}), '(2 * R)\n', (7011, 7018), True, 'import numpy as np\n'), ((7111, 7127), 'numpy.arange', 'np.arange', (['(2 * R)'], {}), '(2 * R)\n', (7120, 7127), True, 'import numpy as np\n'), ((5019, 5184), 'matplotlib.patches.Rectangle', 'Rectangle', (['(position[0] - 0.5, position[1] - 0.5)', '(1.0)', '(1.0)'], {'facecolor': 'self._config.items[type].color', 'edgecolor': '(0, 0, 0)', 'linestyle': '"""solid"""', 'linewidth': '(0.4)'}), "((position[0] - 0.5, position[1] - 0.5), 1.0, 1.0, facecolor=self.\n _config.items[type].color, edgecolor=(0, 0, 0), linestyle='solid',\n linewidth=0.4)\n", (5028, 5184), False, 'from matplotlib.patches import Circle, Rectangle, RegularPolygon\n'), ((5262, 5392), 'matplotlib.patches.Circle', 'Circle', (['position', 'ITEM_RADIUS'], {'facecolor': 'self._config.items[type].color', 'edgecolor': '(0, 0, 0)', 'linestyle': '"""solid"""', 'linewidth': '(0.4)'}), "(position, ITEM_RADIUS, facecolor=self._config.items[type].color,\n edgecolor=(0, 0, 0), linestyle='solid', linewidth=0.4)\n", (5268, 5392), False, 'from matplotlib.patches import Circle, Rectangle, RegularPolygon\n'), ((5664, 5707), 'numpy.array', 'np.array', (['[[0, 1, 1], [1, 0, 1], [1, 1, 0]]'], {}), '([[0, 1, 1], [1, 0, 1], [1, 1, 0]])\n', (5672, 5707), True, 'import numpy as np\n'), ((7533, 7576), 'numpy.array', 'np.array', (['[[0, 1, 1], [1, 0, 1], [1, 1, 0]]'], {}), '([[0, 1, 1], [1, 0, 1], [1, 1, 0]])\n', (7541, 7576), True, 'import numpy as np\n')]
|
import sys
import os
import pathlib
import psutil
import numpy
from pin_lookup import pin
def compCrawl():
"""Finds local removable partitions. No associated unit test.
:returns: list of paths of removable partitions
"""
allPartitions = psutil.disk_partitions()
maybeDASHRpartitions = []
for sdiskpart in allPartitions:
if sdiskpart[3] == 'rw,removable':
maybeDASHRpartitions.append(sdiskpart[1])
return maybeDASHRpartitions
def findSNs(maybeDASHRpartitions):
"""Finds serial numbers associated with DASHRs with data.
:param maybeDASHRpartitions: array of partitions that may be DASHRs
:returns: list of serial numbers or PINs as strings
"""
DASHRlut = {}
for possibleDASHR in maybeDASHRpartitions:
hold = determineDASHRs(possibleDASHR)
if hold is not False:
try:
pin_num = pin(hold)
DASHRlut[pin_num] = possibleDASHR
except FileNotFoundError:
DASHRlut[int(hold)] = possibleDASHR
return DASHRlut
def determineDASHRs(maybeDASHRpartition):
"""Determines whether partition is a DASHR.
:param maybeDASHRpartition: paths of all local removable drives
:returns: int serial number if partition starts with L and ends with BIN
"""
for path, subdirs, files in os.walk(maybeDASHRpartition):
for name in files:
if name[0] == "L" and name[-3:] == "BIN":
return readSN(pathlib.PurePath(path, name).as_posix())
return False
def readSN(path):
"""Reads serial number from .BIN file.
:param path: string path of particular .BIN file
:returns SN: integer serial number
"""
return numpy.fromfile(path, dtype="uint32")[104]
|
[
"psutil.disk_partitions",
"pin_lookup.pin",
"numpy.fromfile",
"os.walk",
"pathlib.PurePath"
] |
[((256, 280), 'psutil.disk_partitions', 'psutil.disk_partitions', ([], {}), '()\n', (278, 280), False, 'import psutil\n'), ((1344, 1372), 'os.walk', 'os.walk', (['maybeDASHRpartition'], {}), '(maybeDASHRpartition)\n', (1351, 1372), False, 'import os\n'), ((1718, 1754), 'numpy.fromfile', 'numpy.fromfile', (['path'], {'dtype': '"""uint32"""'}), "(path, dtype='uint32')\n", (1732, 1754), False, 'import numpy\n'), ((896, 905), 'pin_lookup.pin', 'pin', (['hold'], {}), '(hold)\n', (899, 905), False, 'from pin_lookup import pin\n'), ((1485, 1513), 'pathlib.PurePath', 'pathlib.PurePath', (['path', 'name'], {}), '(path, name)\n', (1501, 1513), False, 'import pathlib\n')]
|
import cv2
import numpy as np
print('done')
frameWidth=640
frameHeight=480
cap=cv2.VideoCapture(1)
cap.set(3,frameHeight)
cap.set(4,frameWidth)
cap.set(10,150)
myColors=[ [97,167,171,107,255,255],
[16,85,141,151,255,213],
[75,91,224,179,255,255],
[37,64,0,95,255,255]
]
#blue,yellow
# [30,64,232,162,255,255]#green [97,167,171,107,255,255]#blue[5,107,0,19,255,255], #orange
# [133,56,0,159,156,255],#purple
# [57,76,0,100,255,255],#green
# [90,48,0,118,255,255]
myColorValues=[[190,125,5],
[0,255,255],
[65,92,242],
[44,209,104]
]
myPoints = [] ## [x , y , colorId ]
def findColor(img,myColors,myColorValues):
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
count = 0
newPoints=[]
for color in myColors:
lower = np.array(color[0:3])
upper = np.array(color[3:6])
mask = cv2.inRange(imgHSV,lower,upper)
x,y=getContours(mask)
cv2.circle(imgResult,(x,y),15,myColorValues[count],cv2.FILLED)
if x!=0 and y!=0:
newPoints.append([x,y,count])
count +=1
#cv2.imshow(str(color[0]),mask)
return newPoints
def getContours(img):
contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
x,y,w,h = 0,0,0,0
for cnt in contours:
area = cv2.contourArea(cnt)
if area>500:
#cv2.drawContours(imgResult, cnt, -1, (255, 0, 0), 3)
peri = cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,0.02*peri,True)
x, y, w, h = cv2.boundingRect(approx)
return x+w//2,y
def drawOnCanvas(myPoints,myColorValues):
for point in myPoints:
cv2.circle(imgResult, (point[0], point[1]), 10, myColorValues[point[2]], cv2.FILLED)
while True:
success, img = cap.read()
imgResult = img.copy()
newPoints = findColor(img, myColors,myColorValues)
if len(newPoints)!=0:
for newP in newPoints:
myPoints.append(newP)
if len(myPoints)!=0:
drawOnCanvas(myPoints,myColorValues)
cv2.imshow("Result", imgResult)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
|
[
"cv2.boundingRect",
"cv2.contourArea",
"cv2.circle",
"cv2.approxPolyDP",
"cv2.cvtColor",
"cv2.arcLength",
"cv2.waitKey",
"cv2.VideoCapture",
"numpy.array",
"cv2.imshow",
"cv2.inRange",
"cv2.findContours"
] |
[((88, 107), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(1)'], {}), '(1)\n', (104, 107), False, 'import cv2\n'), ((811, 847), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (823, 847), False, 'import cv2\n'), ((1339, 1402), 'cv2.findContours', 'cv2.findContours', (['img', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_NONE'], {}), '(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n', (1355, 1402), False, 'import cv2\n'), ((2225, 2256), 'cv2.imshow', 'cv2.imshow', (['"""Result"""', 'imgResult'], {}), "('Result', imgResult)\n", (2235, 2256), False, 'import cv2\n'), ((926, 946), 'numpy.array', 'np.array', (['color[0:3]'], {}), '(color[0:3])\n', (934, 946), True, 'import numpy as np\n'), ((964, 984), 'numpy.array', 'np.array', (['color[3:6]'], {}), '(color[3:6])\n', (972, 984), True, 'import numpy as np\n'), ((1001, 1034), 'cv2.inRange', 'cv2.inRange', (['imgHSV', 'lower', 'upper'], {}), '(imgHSV, lower, upper)\n', (1012, 1034), False, 'import cv2\n'), ((1073, 1140), 'cv2.circle', 'cv2.circle', (['imgResult', '(x, y)', '(15)', 'myColorValues[count]', 'cv2.FILLED'], {}), '(imgResult, (x, y), 15, myColorValues[count], cv2.FILLED)\n', (1083, 1140), False, 'import cv2\n'), ((1466, 1486), 'cv2.contourArea', 'cv2.contourArea', (['cnt'], {}), '(cnt)\n', (1481, 1486), False, 'import cv2\n'), ((1833, 1921), 'cv2.circle', 'cv2.circle', (['imgResult', '(point[0], point[1])', '(10)', 'myColorValues[point[2]]', 'cv2.FILLED'], {}), '(imgResult, (point[0], point[1]), 10, myColorValues[point[2]],\n cv2.FILLED)\n', (1843, 1921), False, 'import cv2\n'), ((1596, 1620), 'cv2.arcLength', 'cv2.arcLength', (['cnt', '(True)'], {}), '(cnt, True)\n', (1609, 1620), False, 'import cv2\n'), ((1642, 1682), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['cnt', '(0.02 * peri)', '(True)'], {}), '(cnt, 0.02 * peri, True)\n', (1658, 1682), False, 'import cv2\n'), ((1705, 1729), 'cv2.boundingRect', 'cv2.boundingRect', (['approx'], {}), '(approx)\n', (1721, 1729), False, 'import cv2\n'), ((2265, 2279), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2276, 2279), False, 'import cv2\n')]
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from scipy.ndimage import filters
import casatools
import os.path
tb = casatools.table()
ms = casatools.ms()
nall2nant = lambda nall: max(np.round(np.roots([1/2., 1/2., -nall]), 0).astype(int)) # nant calc from cross+auto
def corr_flagfrac(msfile, showplot=False, saveplot=False):
""" Make matrix plot of flagging fraction of cross corrlations
"""
ms.open(msfile)
nspw = len(ms.getspectralwindowinfo())
ms.close()
tb.open(msfile, nomodify=True)
flagcol = tb.getcol('FLAG')
npol, nchan, nblnspw = flagcol.shape
nall = nblnspw//nspw
nant = nall2nant(nall)
print('Data shape: {0} bls, {1} ants, {2} chans/spw, {3} spw, {4} pol'
.format(nall, nant, nchan, nspw, npol))
flagmat = np.zeros((nant, nant, nchan, npol), dtype=bool)
ant1, ant2 = np.triu_indices(nant)
flagcol = flagcol.transpose()
for ind in range(len(ant1)):
flagmat[ant1[ind], ant2[ind]] = flagcol[ind]
corrmat = flagmat.reshape(nant, nant, -1)
corrmat_frac = np.sum(corrmat, axis=2)/corrmat.shape[2]
# plot
if showplot or saveplot:
im = plt.matshow(corrmat_frac, norm=LogNorm(vmin=1.e-4, vmax=1))
plt.colorbar(im)
if showplot:
plt.show()
elif saveplot:
plt.savefig('corrmat.png')
tb.close()
return corrmat_frac
|
[
"numpy.roots",
"numpy.sum",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.triu_indices",
"matplotlib.pyplot.colorbar",
"matplotlib.colors.LogNorm",
"casatools.ms",
"casatools.table",
"matplotlib.pyplot.savefig"
] |
[((161, 178), 'casatools.table', 'casatools.table', ([], {}), '()\n', (176, 178), False, 'import casatools\n'), ((184, 198), 'casatools.ms', 'casatools.ms', ([], {}), '()\n', (196, 198), False, 'import casatools\n'), ((830, 877), 'numpy.zeros', 'np.zeros', (['(nant, nant, nchan, npol)'], {'dtype': 'bool'}), '((nant, nant, nchan, npol), dtype=bool)\n', (838, 877), True, 'import numpy as np\n'), ((895, 916), 'numpy.triu_indices', 'np.triu_indices', (['nant'], {}), '(nant)\n', (910, 916), True, 'import numpy as np\n'), ((1102, 1125), 'numpy.sum', 'np.sum', (['corrmat'], {'axis': '(2)'}), '(corrmat, axis=2)\n', (1108, 1125), True, 'import numpy as np\n'), ((1265, 1281), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {}), '(im)\n', (1277, 1281), True, 'import matplotlib.pyplot as plt\n'), ((1315, 1325), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1323, 1325), True, 'import matplotlib.pyplot as plt\n'), ((1228, 1256), 'matplotlib.colors.LogNorm', 'LogNorm', ([], {'vmin': '(0.0001)', 'vmax': '(1)'}), '(vmin=0.0001, vmax=1)\n', (1235, 1256), False, 'from matplotlib.colors import LogNorm\n'), ((1361, 1387), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""corrmat.png"""'], {}), "('corrmat.png')\n", (1372, 1387), True, 'import matplotlib.pyplot as plt\n'), ((239, 274), 'numpy.roots', 'np.roots', (['[1 / 2.0, 1 / 2.0, -nall]'], {}), '([1 / 2.0, 1 / 2.0, -nall])\n', (247, 274), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
# This script has been initiated with the goal of making an inference based on Livox Mid 40 range image
# Work initiated by: Vice, 03.09.2021
import argparse
import yaml
from shutil import copyfile
import os
import shutil
import torch
import torch.backends.cudnn as cudnn
import imp
import time
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
from parser_for_one import *
import open3d as o3d
# SqueezeSegV3 specific imports
#from tasks.semantic.modules.segmentator import *
#from tasks.semantic.modules.trainer import *
#from tasks.semantic.postproc.KNN import KNN
# Livox scan
#livox_raw_pcd = o3d.io.read_point_cloud("./data/lidar_screenshot_clean.pcd", print_progress = True) # Load the point cloud
livox_raw_pcd = o3d.io.read_point_cloud("./data/cropped_1.pcd", print_progress = True) # Load the point cloud
livox_scan = np.asarray(livox_raw_pcd.points) # Convert to numpy
print("At the entry, livox scan is in shape: ", np.shape(livox_scan))
# Parameters
datadir = "../sample_data/" # LiDAR data - raw
logdir = '../sample_output/' # Output folder
modeldir = '../../SSGV3-21-20210701T140552Z-001/SSGV3-21/' # Pre-trained model folder
# Does the model folder exist?
if os.path.isdir(modeldir):
print("model folder exists! Using model from %s" % (modeldir))
else:
print("model folder doesnt exist! Can't infer...")
quit()
# Open the arch config file of the pre-trained model
try:
print("Opening arch config file from %s" % modeldir)
ARCH = yaml.safe_load(open(modeldir + "/arch_cfg.yaml", 'r'))
except Exception as e:
print(e)
print("Error opening arch yaml file.")
quit()
# Open data config file of the pre-trained model
try:
print("Opening data config file from %s" % modeldir)
DATA = yaml.safe_load(open(modeldir + "/data_cfg.yaml", 'r'))
except Exception as e:
print(e)
print("Error opening data yaml file.")
quit()
# Create the output folder
try:
if os.path.isdir(logdir):
shutil.rmtree(logdir)
os.makedirs(logdir)
os.makedirs(os.path.join(logdir, "sequences"))
for seq in DATA["split"]["sample"]:
seq = '{0:02d}'.format(int(seq))
print("sample_list",seq)
os.makedirs(os.path.join(logdir,"sequences", str(seq)))
os.makedirs(os.path.join(logdir,"sequences", str(seq), "predictions"))
except Exception as e:
print(e)
print("Error creating log directory. Check permissions!")
raise
except Exception as e:
print(e)
print("Error creating log directory. Check permissions!")
quit()
# Create a parser and get the data
parser = Parser(root=datadir,
# This is what determines the behavior of the parser
# It expects to load the data to make the inference (test), not training or validation!
train_sequences=None,
valid_sequences=None,
test_sequences=DATA["split"]["sample"],
labels=DATA["labels"],
color_map=DATA["color_map"],
learning_map=DATA["learning_map"],
learning_map_inv=DATA["learning_map_inv"],
sensor=ARCH["dataset"]["sensor"],
max_points=ARCH["dataset"]["max_points"],
batch_size=1,
workers=ARCH["train"]["workers"],
livox_scan = livox_scan,
gt=False, # Ground truth - include labels?
shuffle_train=False)
test = parser.get_test_set() # This returns one DataLoader Object - it is a Python iterator returning tuples
test_size = parser.get_test_size() # Number of samples in the DataLoader object. Every sample (tuple) contains all the data from one LiDAR scan
test_iterator = iter(test) # This returns an iterator for the DataLoader Object.
first = next(test_iterator) # This returns a first element of the iterator. It contains 15 elements, listed below:
"""
proj, proj_mask, proj_labels, unproj_labels, path_seq, path_name,
proj_x, proj_y, proj_range, unproj_range, proj_xyz, unproj_xyz, proj_remission, unproj_remissions, unproj_n_points
"""
# Projection
proj = first[0].numpy() # Convert the projection and projection mask to numpy
proj_mask = first[1].numpy()
proj = np.squeeze(proj) # Remove ones
proj_mask = np.squeeze(proj_mask)
print(proj_mask)
# Plot the projections
plt.figure()
plt.title("Projection mask")
plt.imshow(proj_mask)
plt.figure()
plt.title("Projection layer 1")
plt.imshow(proj[0])
plt.figure()
plt.title("Projection layer 2")
plt.imshow(proj[1])
plt.figure()
plt.title("Projection layer 3")
plt.imshow(proj[2])
plt.figure()
plt.title("Projection layer 4")
plt.imshow(proj[3])
plt.figure()
plt.title("Projection layer 5")
plt.imshow(proj[4])
plt.show()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"os.makedirs",
"os.path.isdir",
"matplotlib.pyplot.imshow",
"numpy.asarray",
"open3d.io.read_point_cloud",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.squeeze",
"shutil.rmtree",
"os.path.join"
] |
[((844, 912), 'open3d.io.read_point_cloud', 'o3d.io.read_point_cloud', (['"""./data/cropped_1.pcd"""'], {'print_progress': '(True)'}), "('./data/cropped_1.pcd', print_progress=True)\n", (867, 912), True, 'import open3d as o3d\n'), ((951, 983), 'numpy.asarray', 'np.asarray', (['livox_raw_pcd.points'], {}), '(livox_raw_pcd.points)\n', (961, 983), True, 'import numpy as np\n'), ((1302, 1325), 'os.path.isdir', 'os.path.isdir', (['modeldir'], {}), '(modeldir)\n', (1315, 1325), False, 'import os\n'), ((4600, 4616), 'numpy.squeeze', 'np.squeeze', (['proj'], {}), '(proj)\n', (4610, 4616), True, 'import numpy as np\n'), ((4643, 4664), 'numpy.squeeze', 'np.squeeze', (['proj_mask'], {}), '(proj_mask)\n', (4653, 4664), True, 'import numpy as np\n'), ((4708, 4720), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4718, 4720), True, 'import matplotlib.pyplot as plt\n'), ((4721, 4749), 'matplotlib.pyplot.title', 'plt.title', (['"""Projection mask"""'], {}), "('Projection mask')\n", (4730, 4749), True, 'import matplotlib.pyplot as plt\n'), ((4750, 4771), 'matplotlib.pyplot.imshow', 'plt.imshow', (['proj_mask'], {}), '(proj_mask)\n', (4760, 4771), True, 'import matplotlib.pyplot as plt\n'), ((4773, 4785), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4783, 4785), True, 'import matplotlib.pyplot as plt\n'), ((4786, 4817), 'matplotlib.pyplot.title', 'plt.title', (['"""Projection layer 1"""'], {}), "('Projection layer 1')\n", (4795, 4817), True, 'import matplotlib.pyplot as plt\n'), ((4818, 4837), 'matplotlib.pyplot.imshow', 'plt.imshow', (['proj[0]'], {}), '(proj[0])\n', (4828, 4837), True, 'import matplotlib.pyplot as plt\n'), ((4839, 4851), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4849, 4851), True, 'import matplotlib.pyplot as plt\n'), ((4852, 4883), 'matplotlib.pyplot.title', 'plt.title', (['"""Projection layer 2"""'], {}), "('Projection layer 2')\n", (4861, 4883), True, 'import matplotlib.pyplot as plt\n'), ((4884, 4903), 'matplotlib.pyplot.imshow', 'plt.imshow', (['proj[1]'], {}), '(proj[1])\n', (4894, 4903), True, 'import matplotlib.pyplot as plt\n'), ((4905, 4917), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4915, 4917), True, 'import matplotlib.pyplot as plt\n'), ((4918, 4949), 'matplotlib.pyplot.title', 'plt.title', (['"""Projection layer 3"""'], {}), "('Projection layer 3')\n", (4927, 4949), True, 'import matplotlib.pyplot as plt\n'), ((4950, 4969), 'matplotlib.pyplot.imshow', 'plt.imshow', (['proj[2]'], {}), '(proj[2])\n', (4960, 4969), True, 'import matplotlib.pyplot as plt\n'), ((4971, 4983), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4981, 4983), True, 'import matplotlib.pyplot as plt\n'), ((4984, 5015), 'matplotlib.pyplot.title', 'plt.title', (['"""Projection layer 4"""'], {}), "('Projection layer 4')\n", (4993, 5015), True, 'import matplotlib.pyplot as plt\n'), ((5016, 5035), 'matplotlib.pyplot.imshow', 'plt.imshow', (['proj[3]'], {}), '(proj[3])\n', (5026, 5035), True, 'import matplotlib.pyplot as plt\n'), ((5037, 5049), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5047, 5049), True, 'import matplotlib.pyplot as plt\n'), ((5050, 5081), 'matplotlib.pyplot.title', 'plt.title', (['"""Projection layer 5"""'], {}), "('Projection layer 5')\n", (5059, 5081), True, 'import matplotlib.pyplot as plt\n'), ((5082, 5101), 'matplotlib.pyplot.imshow', 'plt.imshow', (['proj[4]'], {}), '(proj[4])\n', (5092, 5101), True, 'import matplotlib.pyplot as plt\n'), ((5103, 5113), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5111, 5113), True, 'import matplotlib.pyplot as plt\n'), ((1053, 1073), 'numpy.shape', 'np.shape', (['livox_scan'], {}), '(livox_scan)\n', (1061, 1073), True, 'import numpy as np\n'), ((2046, 2067), 'os.path.isdir', 'os.path.isdir', (['logdir'], {}), '(logdir)\n', (2059, 2067), False, 'import os\n'), ((2103, 2122), 'os.makedirs', 'os.makedirs', (['logdir'], {}), '(logdir)\n', (2114, 2122), False, 'import os\n'), ((2077, 2098), 'shutil.rmtree', 'shutil.rmtree', (['logdir'], {}), '(logdir)\n', (2090, 2098), False, 'import shutil\n'), ((2139, 2172), 'os.path.join', 'os.path.join', (['logdir', '"""sequences"""'], {}), "(logdir, 'sequences')\n", (2151, 2172), False, 'import os\n')]
|
import pandas as pd
import numpy as np
import keras
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional
from keras.models import load_model
import random
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from keras.callbacks import ModelCheckpoint,LearningRateScheduler
from utilize import *
import time
import os
import tensorflow as tf
import keras.backend.tensorflow_backend as KTF
# Device
os.environ["CUDA_VISIBLE_DEVICES"]="0"
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
KTF.set_session(sess)
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
# save trajectory images
save_less=30 # num of images 1
save_more=100 # num of images 2
save_train_cases=False
save_result_cases=False
save_m=True # save model
cate="" # which data set to use. Becaus I utilize different data sets to train stage-1 model, stage-2 model and Social LSTM model.
#Simply set it to "" if use the general data set to train LSTM model
# learning params
continue_flag=False
model_path="./checkpoints/best_weights"+cate+".h5"
EPOCH=60
BATCH_SIZE=128
LR=0.000125
# LR=0.000125/2
# LR=0.000125/4
# settings
train_frames=10
# attr_list=[2,3,4,5,6,8] #namely, Local_X,Local_Y,acceleration,velocity,Lane_ID,heading angle theta
attr_list=[2,3,5,6,7,9]
attr_num=len(attr_list)
class_num=3
TRAIN_NUM=10000
# save directory
save_img_dir="./img_"+cate+"/"
if not os.path.exists(save_img_dir):
os.mkdir(save_img_dir)
save_model_dir="./checkpoints/"
model_name="best_weights"+cate+".h5"
# model_name="best_weights_re"+cate+".h5"
dataset_root="./data/"
specific1="train"
specific2="train"
df = pd.read_csv(dataset_root+specific1+"/train"+cate+".csv")
df2=pd.read_csv(dataset_root+specific2+"/train"+cate+".csv")
print(df.shape)
print(df2.shape)
#label position = 9
label=df.iloc[:,-1].values
label2=df2.iloc[:,-1].values
data_num=int(len(label)/train_frames)
data_num2=int(len(label2)/train_frames)
data=df.iloc[:,attr_list].values
data2=df2.iloc[:,attr_list].values
data=np.reshape(data,[data_num,train_frames,attr_num])
data2=np.reshape(data2,[data_num2,train_frames,attr_num])
print("Data_number for training:",data_num)
print("Data_number for testing:",data_num2)
#add label
train_label=pro_list(data_num=data_num,train_list=label,pred=train_frames)
test_label=pro_list(data_num=data_num2,train_list=label2,pred=train_frames)
#print proportion
#0 = keep lane, 1 = turn left, 2 = turn right
#train arrays
check_train_data_l=[]
check_train_data_r=[]
check_train_data_kl=[]
turn_left_train=[]
turn_right_train=[]
keep_lane_train=[]
cnt0=cnt1=cnt2=0
for i in range(len(train_label)):
if train_label[i]==0:
cnt0+=1
keep_lane_train.append(data[i])
check_train_data_kl.append(i)
elif train_label[i]==1:
cnt1+=1
turn_left_train.append(data[i])
check_train_data_l.append(i)
elif train_label[i]==2:
cnt2+=1
turn_right_train.append(data[i])
check_train_data_r.append(i)
print("Train-record Proportion:(keep lane, left, right)",cnt0,cnt1,cnt2)
#save training case for inspection
#=============================save training case for inspection============================= can just ignore
if(save_train_cases==True):
print("Saving training data(left):")
if not os.path.exists(save_img_dir+"train_l"):
os.mkdir(save_img_dir+"train_l")
for i in range(save_less):
q_id=check_train_data_l[i]
case1=df[q_id*train_frames:(q_id+1)*train_frames]
fig = plt.figure()
for j in range(train_frames):
plt.scatter(case1['Local_X'].values[j],case1['Local_Y'].values[j])
fig.suptitle(str(case1['Vehicle_ID'].values[-1])+' '+str(case1['Frame_ID'].values[-1]))
plt.savefig(save_img_dir+"train_l/l{}.png".format(i))
plt.close(fig)
print("Saving training data(right):")
if not os.path.exists(save_img_dir+"train_r"):
os.mkdir(save_img_dir+"train_r")
for i in range(save_less):
q_id=check_train_data_r[i]
case1=df[q_id*train_frames:(q_id+1)*train_frames]
fig = plt.figure()
for j in range(train_frames):
plt.scatter(case1['Local_X'].values[j],case1['Local_Y'].values[j])
fig.suptitle(str(case1['Vehicle_ID'].values[-1])+' '+str(case1['Frame_ID'].values[-1]))
plt.savefig(save_img_dir+"train_r/r{}.png".format(i))
plt.close(fig)
print("Saving training data(keep lane):")
if not os.path.exists(save_img_dir+"train_kl"):
os.mkdir(save_img_dir+"train_kl")
for i in range(save_less):
q_id=check_train_data_kl[i]
case1=df[q_id*train_frames:(q_id+1)*train_frames]
fig = plt.figure()
for j in range(train_frames):
plt.scatter(case1['Local_X'].values[j],case1['Local_Y'].values[j])
fig.suptitle(str(case1['Vehicle_ID'].values[-1])+' '+str(case1['Frame_ID'].values[-1]))
plt.savefig(save_img_dir+"train_kl/kl{}.png".format(i))
plt.close(fig)
#test arrays
test_order0=[]
test_order1=[]
test_order2=[]
turn_left_test=[]
turn_right_test=[]
keep_lane_test=[]
cnt0=cnt1=cnt2=0
for i in range(len(test_label)):
if test_label[i]==0:
cnt0+=1
keep_lane_test.append(data2[i])
test_order0.append(i)
elif test_label[i]==1:
cnt1+=1
turn_left_test.append(data2[i])
test_order1.append(i)
elif test_label[i]==2:
cnt2+=1
turn_right_test.append(data2[i])
test_order2.append(i)
print("Test-record Proportion:(keep lane, left, right)",cnt0,cnt1,cnt2)
#data balanced
#num=min(len(keep_lane_train),len(turn_left_train),len(turn_right_train))
num=len(keep_lane_train)
#fetch data frome the pool
print("Training data description:")
d0_train,l0_train=sampling_from_pool(keep_lane_train,[[1,0,0]],num)
d1_train,l1_train=sampling_from_pool(turn_left_train,[[0,1,0]],num)
d2_train,l2_train=sampling_from_pool(turn_right_train,[[0,0,1]],num)
data,train_label=combineData(d0_train, l0_train, d1_train, l1_train, d2_train, l2_train,"Train")
print("Testing data description:")
d0_test,l0_test=sampling_from_pool(keep_lane_test,[[1,0,0]],len(keep_lane_test))
d1_test,l1_test=sampling_from_pool(turn_left_test,[[0,1,0]],len(turn_left_test))
d2_test,l2_test=sampling_from_pool(turn_right_test,[[0,0,1]],len(turn_right_test))
test_order=test_order0+test_order1+test_order2
print(test_order[-20:])
data2,test_label=combineData(d0_test,l0_test,d1_test,l1_test,d2_test, l2_test,"Test")
def get_data(data,label,random_sample=False):
data,label=shuffle(data,label)
return data,label
def get_train_data(data,label,train_data_num=TRAIN_NUM,random_sample=False):
data,label=shuffle(data,label)
return data,label
def get_test_data(data,label,random_sample=False):
return data,label
def buildManyToOneModel(shape,class_num,LR):
model = Sequential()
# model.add(LSTM(128, input_length=shape[1], input_dim=shape[2]))
# model.add(Dropout(0.5))
model.add(LSTM(128, input_shape=(shape[1],shape[2]),return_sequences=True))
model.add(Dropout(0.5))
model.add(LSTM(128,return_sequences=False))
model.add(Dropout(0.5))
model.add(Dense(class_num,activation='softmax'))
op=keras.optimizers.Adam(lr=LR)
model.compile(loss="categorical_crossentropy", optimizer=op, metrics=['accuracy'])
model.summary()
return model
def buildManyToOneModel_single(shape,class_num,LR):
model = Sequential()
# model.add(LSTM(128, input_length=shape[1], input_dim=shape[2]))
# model.add(Dropout(0.5))
model.add(LSTM(128, input_shape=(shape[1],shape[2]),return_sequences=False))
model.add(Dropout(0.5))
model.add(Dense(class_num,activation='softmax'))
op=keras.optimizers.Adam(lr=LR)
model.compile(loss="categorical_crossentropy", optimizer=op, metrics=['accuracy'])
model.summary()
return model
def buildManyToOneModel_Bi(shape,class_num,LR):
print("Bidirectional model")
model = Sequential()
model.add(Bidirectional(LSTM(128,return_sequences=True),input_shape=(shape[1],shape[2])))
model.add(Dropout(0.5))
model.add(LSTM(128,return_sequences=False))
model.add(Dropout(0.5))
model.add(Dense(class_num,activation='softmax'))
op=keras.optimizers.Adam(lr=LR)
model.compile(loss="categorical_crossentropy", optimizer=op, metrics=['accuracy'])
model.summary()
return model
#self split into 2 set or use trainset and testset
# if(specific2==specific1):
# X,y=get_data(data=data,label=train_label)
# x_train,x_test,y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# print("Train and test composition:")
# print(len(X))
# print(len(x_train))
# print(len(x_test))
# else:
x_train,y_train=get_train_data(data=data,label=train_label,train_data_num=TRAIN_NUM)
x_test,y_test=get_test_data(data=data2,label=test_label)
print("Train and test composition:")
print(len(x_train))
print(len(x_test))
print(y_train[:10])
if(continue_flag==True):
model=load_model(model_path)
else:
# model = buildManyToOneModel(x_train.shape,class_num,LR)
model = buildManyToOneModel_Bi(x_train.shape,class_num,LR)
#training process
t1=time.time()
def scheduler(epoch):
if epoch % 35 == 0 and epoch != 0:
lr = K.get_value(model.optimizer.lr)
K.set_value(model.optimizer.lr, lr * 0.1)
print("lr changed to {}".format(lr * 0.1))
return K.get_value(model.optimizer.lr)
reduce_lr = LearningRateScheduler(scheduler)
if(save_m==True):
checkpoint = ModelCheckpoint(filepath=save_model_dir+model_name,monitor='val_acc',mode='auto' ,save_best_only='True')
callback_lists=[checkpoint]
model.fit(x_train, y_train, epochs=EPOCH, batch_size=BATCH_SIZE,validation_data=(x_test, y_test),callbacks=[checkpoint])
else:
model.fit(x_train, y_train, epochs=EPOCH, batch_size=BATCH_SIZE,validation_data=(x_test, y_test),callbacks=[])
t2=time.time()
print(t2-t1)
result=model.predict(x_test)
#testing process
loss, accuracy = model.evaluate(x_test,y_test)
print("Loss, Acc:",loss,accuracy)
true_category=np.argmax(y_test,axis=1)
pred_category=np.argmax(result,axis=1)
m=confusion_matrix(true_category,pred_category)
print(m)
acc_list=[]
for i in range(len(m)):
tot=0
for j in range(len(m[i])):
tot+=m[i][j]
acc=float(m[i][i])/float(tot)
acc_list.append(acc)
print(acc_list)
print("Count of absolute possibility value:")
#count for absolute value
fg1=0
fg2=0
for i in range(len(result)):
if(np.max(result[i])>=0.8):
fg1+=1
else:
fg2+=1
print(fg1,fg2)
|
[
"keras.models.load_model",
"os.mkdir",
"sklearn.metrics.confusion_matrix",
"numpy.argmax",
"pandas.read_csv",
"tensorflow.ConfigProto",
"matplotlib.pyplot.figure",
"keras.callbacks.LearningRateScheduler",
"keras.backend.tensorflow_backend.set_session",
"matplotlib.pyplot.close",
"os.path.exists",
"numpy.max",
"numpy.reshape",
"keras.callbacks.ModelCheckpoint",
"keras.layers.Dropout",
"tensorflow.Session",
"keras.optimizers.Adam",
"keras.layers.LSTM",
"matplotlib.pyplot.scatter",
"time.time",
"tensorflow.python.client.device_lib.list_local_devices",
"keras.layers.Dense",
"keras.models.Sequential"
] |
[((621, 637), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (635, 637), True, 'import tensorflow as tf\n'), ((685, 710), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (695, 710), True, 'import tensorflow as tf\n'), ((711, 732), 'keras.backend.tensorflow_backend.set_session', 'KTF.set_session', (['sess'], {}), '(sess)\n', (726, 732), True, 'import keras.backend.tensorflow_backend as KTF\n'), ((1836, 1900), 'pandas.read_csv', 'pd.read_csv', (["(dataset_root + specific1 + '/train' + cate + '.csv')"], {}), "(dataset_root + specific1 + '/train' + cate + '.csv')\n", (1847, 1900), True, 'import pandas as pd\n'), ((1897, 1961), 'pandas.read_csv', 'pd.read_csv', (["(dataset_root + specific2 + '/train' + cate + '.csv')"], {}), "(dataset_root + specific2 + '/train' + cate + '.csv')\n", (1908, 1961), True, 'import pandas as pd\n'), ((2217, 2269), 'numpy.reshape', 'np.reshape', (['data', '[data_num, train_frames, attr_num]'], {}), '(data, [data_num, train_frames, attr_num])\n', (2227, 2269), True, 'import numpy as np\n'), ((2273, 2327), 'numpy.reshape', 'np.reshape', (['data2', '[data_num2, train_frames, attr_num]'], {}), '(data2, [data_num2, train_frames, attr_num])\n', (2283, 2327), True, 'import numpy as np\n'), ((9323, 9334), 'time.time', 'time.time', ([], {}), '()\n', (9332, 9334), False, 'import time\n'), ((9597, 9629), 'keras.callbacks.LearningRateScheduler', 'LearningRateScheduler', (['scheduler'], {}), '(scheduler)\n', (9618, 9629), False, 'from keras.callbacks import ModelCheckpoint, LearningRateScheduler\n'), ((10051, 10062), 'time.time', 'time.time', ([], {}), '()\n', (10060, 10062), False, 'import time\n'), ((10218, 10243), 'numpy.argmax', 'np.argmax', (['y_test'], {'axis': '(1)'}), '(y_test, axis=1)\n', (10227, 10243), True, 'import numpy as np\n'), ((10257, 10282), 'numpy.argmax', 'np.argmax', (['result'], {'axis': '(1)'}), '(result, axis=1)\n', (10266, 10282), True, 'import numpy as np\n'), ((10284, 10330), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['true_category', 'pred_category'], {}), '(true_category, pred_category)\n', (10300, 10330), False, 'from sklearn.metrics import confusion_matrix\n'), ((787, 818), 'tensorflow.python.client.device_lib.list_local_devices', 'device_lib.list_local_devices', ([], {}), '()\n', (816, 818), False, 'from tensorflow.python.client import device_lib\n'), ((1603, 1631), 'os.path.exists', 'os.path.exists', (['save_img_dir'], {}), '(save_img_dir)\n', (1617, 1631), False, 'import os\n'), ((1637, 1659), 'os.mkdir', 'os.mkdir', (['save_img_dir'], {}), '(save_img_dir)\n', (1645, 1659), False, 'import os\n'), ((7061, 7073), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (7071, 7073), False, 'from keras.models import Sequential\n'), ((7403, 7431), 'keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'lr': 'LR'}), '(lr=LR)\n', (7424, 7431), False, 'import keras\n'), ((7613, 7625), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (7623, 7625), False, 'from keras.models import Sequential\n'), ((7884, 7912), 'keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'lr': 'LR'}), '(lr=LR)\n', (7905, 7912), False, 'import keras\n'), ((8121, 8133), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (8131, 8133), False, 'from keras.models import Sequential\n'), ((8381, 8409), 'keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'lr': 'LR'}), '(lr=LR)\n', (8402, 8409), False, 'import keras\n'), ((9145, 9167), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (9155, 9167), False, 'from keras.models import load_model\n'), ((9665, 9777), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': '(save_model_dir + model_name)', 'monitor': '"""val_acc"""', 'mode': '"""auto"""', 'save_best_only': '"""True"""'}), "(filepath=save_model_dir + model_name, monitor='val_acc',\n mode='auto', save_best_only='True')\n", (9680, 9777), False, 'from keras.callbacks import ModelCheckpoint, LearningRateScheduler\n'), ((3494, 3534), 'os.path.exists', 'os.path.exists', (["(save_img_dir + 'train_l')"], {}), "(save_img_dir + 'train_l')\n", (3508, 3534), False, 'import os\n'), ((3542, 3576), 'os.mkdir', 'os.mkdir', (["(save_img_dir + 'train_l')"], {}), "(save_img_dir + 'train_l')\n", (3550, 3576), False, 'import os\n'), ((3713, 3725), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3723, 3725), True, 'import matplotlib.pyplot as plt\n'), ((4009, 4023), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4018, 4023), True, 'import matplotlib.pyplot as plt\n'), ((4077, 4117), 'os.path.exists', 'os.path.exists', (["(save_img_dir + 'train_r')"], {}), "(save_img_dir + 'train_r')\n", (4091, 4117), False, 'import os\n'), ((4125, 4159), 'os.mkdir', 'os.mkdir', (["(save_img_dir + 'train_r')"], {}), "(save_img_dir + 'train_r')\n", (4133, 4159), False, 'import os\n'), ((4296, 4308), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4306, 4308), True, 'import matplotlib.pyplot as plt\n'), ((4592, 4606), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4601, 4606), True, 'import matplotlib.pyplot as plt\n'), ((4664, 4705), 'os.path.exists', 'os.path.exists', (["(save_img_dir + 'train_kl')"], {}), "(save_img_dir + 'train_kl')\n", (4678, 4705), False, 'import os\n'), ((4713, 4748), 'os.mkdir', 'os.mkdir', (["(save_img_dir + 'train_kl')"], {}), "(save_img_dir + 'train_kl')\n", (4721, 4748), False, 'import os\n'), ((4886, 4898), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4896, 4898), True, 'import matplotlib.pyplot as plt\n'), ((5184, 5198), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (5193, 5198), True, 'import matplotlib.pyplot as plt\n'), ((7182, 7248), 'keras.layers.LSTM', 'LSTM', (['(128)'], {'input_shape': '(shape[1], shape[2])', 'return_sequences': '(True)'}), '(128, input_shape=(shape[1], shape[2]), return_sequences=True)\n', (7186, 7248), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((7260, 7272), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (7267, 7272), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((7286, 7319), 'keras.layers.LSTM', 'LSTM', (['(128)'], {'return_sequences': '(False)'}), '(128, return_sequences=False)\n', (7290, 7319), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((7332, 7344), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (7339, 7344), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((7358, 7396), 'keras.layers.Dense', 'Dense', (['class_num'], {'activation': '"""softmax"""'}), "(class_num, activation='softmax')\n", (7363, 7396), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((7734, 7801), 'keras.layers.LSTM', 'LSTM', (['(128)'], {'input_shape': '(shape[1], shape[2])', 'return_sequences': '(False)'}), '(128, input_shape=(shape[1], shape[2]), return_sequences=False)\n', (7738, 7801), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((7813, 7825), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (7820, 7825), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((7839, 7877), 'keras.layers.Dense', 'Dense', (['class_num'], {'activation': '"""softmax"""'}), "(class_num, activation='softmax')\n", (7844, 7877), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((8238, 8250), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (8245, 8250), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((8264, 8297), 'keras.layers.LSTM', 'LSTM', (['(128)'], {'return_sequences': '(False)'}), '(128, return_sequences=False)\n', (8268, 8297), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((8310, 8322), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (8317, 8322), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((8336, 8374), 'keras.layers.Dense', 'Dense', (['class_num'], {'activation': '"""softmax"""'}), "(class_num, activation='softmax')\n", (8341, 8374), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n'), ((10633, 10650), 'numpy.max', 'np.max', (['result[i]'], {}), '(result[i])\n', (10639, 10650), True, 'import numpy as np\n'), ((3776, 3843), 'matplotlib.pyplot.scatter', 'plt.scatter', (["case1['Local_X'].values[j]", "case1['Local_Y'].values[j]"], {}), "(case1['Local_X'].values[j], case1['Local_Y'].values[j])\n", (3787, 3843), True, 'import matplotlib.pyplot as plt\n'), ((4359, 4426), 'matplotlib.pyplot.scatter', 'plt.scatter', (["case1['Local_X'].values[j]", "case1['Local_Y'].values[j]"], {}), "(case1['Local_X'].values[j], case1['Local_Y'].values[j])\n", (4370, 4426), True, 'import matplotlib.pyplot as plt\n'), ((4949, 5016), 'matplotlib.pyplot.scatter', 'plt.scatter', (["case1['Local_X'].values[j]", "case1['Local_Y'].values[j]"], {}), "(case1['Local_X'].values[j], case1['Local_Y'].values[j])\n", (4960, 5016), True, 'import matplotlib.pyplot as plt\n'), ((8160, 8192), 'keras.layers.LSTM', 'LSTM', (['(128)'], {'return_sequences': '(True)'}), '(128, return_sequences=True)\n', (8164, 8192), False, 'from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector, Bidirectional\n')]
|
import numpy as np
import matplotlib.pyplot as plt
import gc
save_path='/home/asap7772/cog/images/'
paths = [
# ('/nfs/kun1/users/asap7772/prior_data/task_singleneut_Widow250DoubleDrawerGraspNeutral-v0_10K_save_all_noise_0.1_2021-03-25T22-52-59_9750.npy', 'coll_task'),
# ('/nfs/kun1/users/asap7772/cog_data/drawer_task.npy', 'public_task'),
# ('/nfs/kun1/users/asap7772/cog_data/closed_drawer_prior.npy', 'public_prior'),
# ('/nfs/kun1/users/asap7772/prior_data/coglike_prior_Widow250DoubleDrawerOpenGraspNeutral-v0_10K_save_all_noise_0.1_2021-04-03T17-32-00_10000.npy', 'cog_like_prior'),
('/nfs/kun1/users/asap7772/prior_data/coglike_task_Widow250DoubleDrawerGraspNeutral-v0_10K_save_all_noise_0.1_2021-04-03T17-32-05_10000.npy', 'cog_like_task'),
]
for p, fname in paths:
print(fname)
with open(p, 'rb') as f:
gc.collect()
data = np.load(f, allow_pickle=True)
import ipdb; ipdb.set_trace()
bins = [i * .1 for i in range(11)]
actions = np.array([np.array(data[i]['actions']) for i in range(len(data))])
neut_acts = actions.reshape(-1,actions.shape[-1])[:,-1]
plt.figure()
plt.title('hist for ' + fname)
plt.hist(neut_acts, bins=bins)
plt.savefig(save_path + 'hist' + fname + '.png')
plt.close()
|
[
"matplotlib.pyplot.title",
"numpy.load",
"matplotlib.pyplot.hist",
"ipdb.set_trace",
"matplotlib.pyplot.close",
"gc.collect",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.savefig"
] |
[((856, 868), 'gc.collect', 'gc.collect', ([], {}), '()\n', (866, 868), False, 'import gc\n'), ((884, 913), 'numpy.load', 'np.load', (['f'], {'allow_pickle': '(True)'}), '(f, allow_pickle=True)\n', (891, 913), True, 'import numpy as np\n'), ((935, 951), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (949, 951), False, 'import ipdb\n'), ((1154, 1166), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1164, 1166), True, 'import matplotlib.pyplot as plt\n'), ((1175, 1205), 'matplotlib.pyplot.title', 'plt.title', (["('hist for ' + fname)"], {}), "('hist for ' + fname)\n", (1184, 1205), True, 'import matplotlib.pyplot as plt\n'), ((1214, 1244), 'matplotlib.pyplot.hist', 'plt.hist', (['neut_acts'], {'bins': 'bins'}), '(neut_acts, bins=bins)\n', (1222, 1244), True, 'import matplotlib.pyplot as plt\n'), ((1253, 1301), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(save_path + 'hist' + fname + '.png')"], {}), "(save_path + 'hist' + fname + '.png')\n", (1264, 1301), True, 'import matplotlib.pyplot as plt\n'), ((1310, 1321), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1319, 1321), True, 'import matplotlib.pyplot as plt\n'), ((1024, 1052), 'numpy.array', 'np.array', (["data[i]['actions']"], {}), "(data[i]['actions'])\n", (1032, 1052), True, 'import numpy as np\n')]
|
import casadi as ca
import casadi.tools as ca_tools
import gym
import highway_env
import numpy as np
import torch
from nets import CLPP
from MPC.casadi_mul_shooting import get_first_action
import time
import matplotlib.pyplot as plt
T = 0.1 # sampling time [s]
N = 50 # prediction horizon
accel_max = 1
omega_max = np.pi/6
clpp = torch.load("pp_model.pkl")
clpp.eval = True
clde = torch.load("de_model.pkl")
em = np.load("embedding.npy")
em = torch.Tensor(em)
z = torch.LongTensor([0])
hidden = em[z.item()]
hidden = hidden.unsqueeze(0)
env = gym.make("myenv-r1-v0")
labels_index = np.arange(9).reshape(3, 3)
N = 50
lanes_count = env.config["lanes_count"]
lane_id = np.random.choice(np.arange(lanes_count))
v_lane_id = ("a", "b", 1)
# positon_x = np.random.choice(np.arange(0, env.road.network.get_lane(v_lane_id).length, 5))
positon_x = 0
# positon_y = np.random.choice(np.arange(-2, 2.1, 0.5))
positon_y = 0
heading = env.road.network.get_lane(v_lane_id).heading_at(positon_x)
speed = 10
env.config["v_x"] = positon_x
env.config["v_y"] = positon_y
env.config["v_h"] = heading
env.config["v_s"] = speed
env.config["v_lane_id"] = v_lane_id
env.config["action"] = {'type': 'ContinuousAction'},
env.reset()
def get_hat(env, z):
p = env.vehicle.position
i_h = env.vehicle.heading
i_s = env.vehicle.speed
s0 = [p[0], p[1], i_h, i_s]
s0 = np.array(s0)
s0 = torch.Tensor(s0)
s0 = s0.unsqueeze(0)
x_road, y_road = env.vehicle.target_lane_position(p)
ss = x_road + y_road
ss = np.array(ss)
ss = torch.Tensor(ss)
ss = ss.unsqueeze(0)
label = z
s_hat, _, _, _, _ = clpp(s0, ss, label, em)
u_hat = clde(s0, ss, hidden)
s_hat = s_hat.squeeze(0)
u_hat = u_hat.squeeze(0)
s0 = s0.squeeze(0)
s_hat = s_hat.detach().cpu().numpy()
u_hat = u_hat.detach().cpu().numpy()
s0 = s0.detach().cpu().numpy()
x_f = s_hat.reshape(4, 50)[:, -1]
print("原本的终端是 ", x_f)
x_f_local_x, x_f_local_y = env.road.network.get_lane(v_lane_id).local_coordinates(np.array([x_f[0], x_f[1]]))
x_f_local_y = np.clip(x_f_local_y, -4, 4)
x_f_xy = env.road.network.get_lane(v_lane_id).position(x_f_local_x, x_f_local_y)
x_f[0] = x_f_xy[0]
x_f[1] = x_f_xy[1]
x_f[2] = env.road.network.get_lane(v_lane_id).heading_at(x_f_xy[0])
print("现在的终端是 ", x_f)
return s0, ss, s_hat, u_hat, x_f
s0, ss, s_hat, u_hat, x_f = get_hat(env, z)
action, u_e, x_e = get_first_action(s0, u_hat, s_hat, z.item(), x_f)
plt.figure(1)
plt.plot(x_e[:, 0], x_e[:, 1])
plt.figure(2)
dd = s_hat.reshape(4, 50)
plt.plot(dd[0,:], dd[1,:])
plt.show()
for i in range(N):
action = u_e[i, :]
obs, reward, terminal, info = env.step(action)
env.render()
time.sleep(0.1)
env.close()
|
[
"numpy.load",
"matplotlib.pyplot.show",
"gym.make",
"matplotlib.pyplot.plot",
"torch.LongTensor",
"torch.load",
"numpy.clip",
"time.sleep",
"matplotlib.pyplot.figure",
"torch.Tensor",
"numpy.arange",
"numpy.array"
] |
[((334, 360), 'torch.load', 'torch.load', (['"""pp_model.pkl"""'], {}), "('pp_model.pkl')\n", (344, 360), False, 'import torch\n'), ((385, 411), 'torch.load', 'torch.load', (['"""de_model.pkl"""'], {}), "('de_model.pkl')\n", (395, 411), False, 'import torch\n'), ((417, 441), 'numpy.load', 'np.load', (['"""embedding.npy"""'], {}), "('embedding.npy')\n", (424, 441), True, 'import numpy as np\n'), ((447, 463), 'torch.Tensor', 'torch.Tensor', (['em'], {}), '(em)\n', (459, 463), False, 'import torch\n'), ((469, 490), 'torch.LongTensor', 'torch.LongTensor', (['[0]'], {}), '([0])\n', (485, 490), False, 'import torch\n'), ((549, 572), 'gym.make', 'gym.make', (['"""myenv-r1-v0"""'], {}), "('myenv-r1-v0')\n", (557, 572), False, 'import gym\n'), ((2481, 2494), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (2491, 2494), True, 'import matplotlib.pyplot as plt\n'), ((2495, 2525), 'matplotlib.pyplot.plot', 'plt.plot', (['x_e[:, 0]', 'x_e[:, 1]'], {}), '(x_e[:, 0], x_e[:, 1])\n', (2503, 2525), True, 'import matplotlib.pyplot as plt\n'), ((2526, 2539), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (2536, 2539), True, 'import matplotlib.pyplot as plt\n'), ((2566, 2594), 'matplotlib.pyplot.plot', 'plt.plot', (['dd[0, :]', 'dd[1, :]'], {}), '(dd[0, :], dd[1, :])\n', (2574, 2594), True, 'import matplotlib.pyplot as plt\n'), ((2593, 2603), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2601, 2603), True, 'import matplotlib.pyplot as plt\n'), ((689, 711), 'numpy.arange', 'np.arange', (['lanes_count'], {}), '(lanes_count)\n', (698, 711), True, 'import numpy as np\n'), ((1361, 1373), 'numpy.array', 'np.array', (['s0'], {}), '(s0)\n', (1369, 1373), True, 'import numpy as np\n'), ((1383, 1399), 'torch.Tensor', 'torch.Tensor', (['s0'], {}), '(s0)\n', (1395, 1399), False, 'import torch\n'), ((1516, 1528), 'numpy.array', 'np.array', (['ss'], {}), '(ss)\n', (1524, 1528), True, 'import numpy as np\n'), ((1538, 1554), 'torch.Tensor', 'torch.Tensor', (['ss'], {}), '(ss)\n', (1550, 1554), False, 'import torch\n'), ((2071, 2098), 'numpy.clip', 'np.clip', (['x_f_local_y', '(-4)', '(4)'], {}), '(x_f_local_y, -4, 4)\n', (2078, 2098), True, 'import numpy as np\n'), ((2721, 2736), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (2731, 2736), False, 'import time\n'), ((588, 600), 'numpy.arange', 'np.arange', (['(9)'], {}), '(9)\n', (597, 600), True, 'import numpy as np\n'), ((2025, 2051), 'numpy.array', 'np.array', (['[x_f[0], x_f[1]]'], {}), '([x_f[0], x_f[1]])\n', (2033, 2051), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
import numpy as nump
import matplotlib.pyplot as py
import sys,os
import pickle
from matplotlib import rc
#rc('font', **{'family': 'sans-serif', 'sans-serif': ['Times']})
rc('text', usetex=True)
strategies=["Analytic","Automatic","Numeric"]
colors={}
colors["Analytic"]="blue"
colors["Automatic"]="red"
colors["Numeric"]="green"
output={}
#loading
for strategy in strategies:
output[strategy]={}
strategy_path = "data/output1/"+strategy
if not os.path.isdir(strategy_path):
continue
all_txts=[f for f in os.listdir(strategy_path) if os.path.isfile(os.path.join(strategy_path,f))]
all_txts.sort()
for np_str in all_txts:
np = int(np_str.split("__")[0])
output[strategy][np]={}
np_txt = open("data/output1/"+strategy+"/"+np_str, "r")
np_contents = np_txt.readlines()
for i, np_line in enumerate(np_contents):
if i==0: continue
Seed = float(np_line.split()[0])
output[strategy][np][Seed] = {}
output[strategy][np][Seed]["hid1"]=int(np_line.split()[2])
output[strategy][np][Seed]["chi2"]=float(np_line.split()[3])
output[strategy][np][Seed]["time"]=float(np_line.split()[4])
#py.figure(figsize=(20, 10))
ax = py.subplot(111)
ax2 = ax.twiny()
texts=r""
DictOutput={}
for strategy in strategies:
strategy_path = "data/output1/"+strategy
if not os.path.isdir(strategy_path):
continue
nps = []
neurones = []
BestTimes = []
for i, np in enumerate(sorted(output[strategy].keys())):
times = []
BestChi2 = 9999
BestSeed = 0
for Seed in output[strategy][np].keys():
if output[strategy][np][Seed]["chi2"] < BestChi2 and output[strategy][np][Seed]["chi2"]<1.0:
BestSeed = Seed
BestChi2 = output[strategy][np][Seed]["chi2"]
if BestChi2 == 9999:
continue
BestTimes.append(output[strategy][np][BestSeed]["time"])
nps.append(np)
neurones.append(output[strategy][np][BestSeed]["hid1"])
if np==22 or i == len(output[strategy].keys())-1:
xp = nump.linspace(0,np,100)
yp = nump.zeros(100)+output[strategy][np][BestSeed]["time"]
ax.plot(xp, yp, ls='--', color=colors[strategy], lw=1, alpha=0.5)
ax.plot(nps, BestTimes, ls='-', color=colors[strategy],label=strategy, lw=3)
#a, b = nump.polyfit(nps, BestTimes, 1) # , w=nump.sqrt(BestTimes))
#linreg = a*nump.array(nps)+b
#ax.plot(nps, linreg, ls='--',
# color='black', lw=1)
#
#if strategy != "Analytic":
# texts += "\n"
#
#if b<0:
# texts += "$t^{"+strategy+"}= " + \
# str(round(a, 3))+"p "+str(round(b, 1))+"$"
#else:
# texts += "$t^{"+strategy+"}= " + \
# str(round(a, 3))+"p + "+str(round(b, 1))+"$"
DictOutput[strategy] = {}
DictOutput[strategy]["nps"] = nps
DictOutput[strategy]["BestTimes"] = BestTimes
with open('data/output1/BestTimes.pickle', 'wb') as handle:
pickle.dump(DictOutput, handle, protocol=pickle.HIGHEST_PROTOCOL)
props = dict(boxstyle='square', facecolor='white', edgecolor='gray', alpha=0.5)
ax.text(0.62, 0.48, texts, transform=ax.transAxes, fontsize=12,
verticalalignment='top', bbox=props)
ax.set_xlabel('Parameters', fontsize=12)
ax.set_ylabel(r'Time$(s)$ [1k\,\,iterations]', fontsize=12)
ax.set_xlim(left=10)
#ax.set_ylim(bottom=1, top=400)
xticks = []
new_xticks = []
prev_np=0
for i,np in enumerate(nps):
if i==0 or np-prev_np>6:
xticks.append(np)
new_xticks.append(neurones[i])
prev_np=np
ax.set_xticks(xticks)
ax.tick_params(which='both', direction='in', labelsize=12)
ax.set_xticklabels(xticks, rotation=45)
ax2.set_xlim(ax.get_xlim())
ax2.set_xticks(xticks)
ax2.set_xticklabels(new_xticks)
ax2.tick_params(which='both', direction='in', labelsize=12)
ax2.set_xlabel(r"Middle neurones", fontsize=12)
# these are matplotlib.patch.Patch properties
props = dict(boxstyle='square', facecolor='white', edgecolor='gray', alpha=0.5)
# place a text box in upper left in axes coords
text = r"$N_{data} = 1000$"
ax.text(0.035, 0.78, text, transform=ax.transAxes, fontsize=12,
verticalalignment='top', bbox=props)
ax.set_yscale('log')
ax.legend(loc='upper left')
print("produced results/P10_time.pdf ...")
py.savefig('results/P10_time.pdf')
py.cla()
py.clf()
|
[
"matplotlib.pyplot.subplot",
"matplotlib.rc",
"pickle.dump",
"matplotlib.pyplot.clf",
"os.path.isdir",
"numpy.zeros",
"matplotlib.pyplot.cla",
"numpy.linspace",
"os.path.join",
"os.listdir",
"matplotlib.pyplot.savefig"
] |
[((193, 216), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (195, 216), False, 'from matplotlib import rc\n'), ((1282, 1297), 'matplotlib.pyplot.subplot', 'py.subplot', (['(111)'], {}), '(111)\n', (1292, 1297), True, 'import matplotlib.pyplot as py\n'), ((4418, 4452), 'matplotlib.pyplot.savefig', 'py.savefig', (['"""results/P10_time.pdf"""'], {}), "('results/P10_time.pdf')\n", (4428, 4452), True, 'import matplotlib.pyplot as py\n'), ((4453, 4461), 'matplotlib.pyplot.cla', 'py.cla', ([], {}), '()\n', (4459, 4461), True, 'import matplotlib.pyplot as py\n'), ((4462, 4470), 'matplotlib.pyplot.clf', 'py.clf', ([], {}), '()\n', (4468, 4470), True, 'import matplotlib.pyplot as py\n'), ((3103, 3168), 'pickle.dump', 'pickle.dump', (['DictOutput', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(DictOutput, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (3114, 3168), False, 'import pickle\n'), ((481, 509), 'os.path.isdir', 'os.path.isdir', (['strategy_path'], {}), '(strategy_path)\n', (494, 509), False, 'import sys, os\n'), ((1428, 1456), 'os.path.isdir', 'os.path.isdir', (['strategy_path'], {}), '(strategy_path)\n', (1441, 1456), False, 'import sys, os\n'), ((559, 584), 'os.listdir', 'os.listdir', (['strategy_path'], {}), '(strategy_path)\n', (569, 584), False, 'import sys, os\n'), ((2189, 2214), 'numpy.linspace', 'nump.linspace', (['(0)', 'np', '(100)'], {}), '(0, np, 100)\n', (2202, 2214), True, 'import numpy as nump\n'), ((603, 633), 'os.path.join', 'os.path.join', (['strategy_path', 'f'], {}), '(strategy_path, f)\n', (615, 633), False, 'import sys, os\n'), ((2230, 2245), 'numpy.zeros', 'nump.zeros', (['(100)'], {}), '(100)\n', (2240, 2245), True, 'import numpy as nump\n')]
|
import glob
import cv2
import math
import numpy as np
from sklearn.model_selection import train_test_split
#import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from skimage.filters import threshold_mean
from skimage import data
from skimage.filters import try_all_threshold
from skimage.feature import greycomatrix, greycoprops
from skimage import io, color
from skimage import feature, io
from sklearn import preprocessing
import FeatureExtraction as Features
def helperFunction(arr,index):
sum = 0.0
for i in range(4):
sum = sum + arr.item(index, i)
sum = sum/4.0
return sum
arr = []
flag1 = 1
def trainImage(image_list):
global arr
global flag1
arr.clear()
for index in range(len(image_list)):
img = io.imread(image_list[index], as_grey=True)
infile = cv2.imread(image_list[index])
infile = infile[:, :, 0]
hues = (np.array(infile) / 255.) * 179
outimageHSV = np.array([[[b, 255, 255] for b in a] for a in hues]).astype(int)
outimageHSV = np.uint8(outimageHSV)
outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR)
rgb = io.imread(image_list[index])
lab = color.rgb2lab(rgb)
outimageBGR = lab
for i in range(outimageBGR.shape[0]):
for j in range(outimageBGR.shape[1]):
sum = 0
for k in range(outimageBGR.shape[2]):
sum = sum + outimageBGR[i][j][k]
sum = sum / (3 * 255)
if(i<img.shape[0] and j<img.shape[1]):
img[i][j] = sum
S = preprocessing.MinMaxScaler((0, 19)).fit_transform(img).astype(int)
Grauwertmatrix = feature.greycomatrix(S, [1, 2, 3], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=20,
symmetric=False, normed=True)
arr.append(feature.greycoprops(Grauwertmatrix, 'contrast'))
arr.append(feature.greycoprops(Grauwertmatrix, 'correlation'))
arr.append(feature.greycoprops(Grauwertmatrix, 'homogeneity'))
arr.append(feature.greycoprops(Grauwertmatrix, 'ASM'))
arr.append(feature.greycoprops(Grauwertmatrix, 'energy'))
arr.append(feature.greycoprops(Grauwertmatrix, 'dissimilarity'))
arr.append(Features.sumOfSquares(Grauwertmatrix))
arr.append(Features.sumAverage(Grauwertmatrix))
arr.append(Features.sumVariance(Grauwertmatrix))
arr.append(Features.Entropy(Grauwertmatrix))
arr.append(Features.sumEntropy(Grauwertmatrix))
arr.append(Features.differenceVariance(Grauwertmatrix))
arr.append(Features.differenceEntropy(Grauwertmatrix))
arr.append(Features.informationMeasureOfCorelation1(Grauwertmatrix))
arr.append(Features.informationMeasureOfCorelation2(Grauwertmatrix))
flag1 = 1
arr1 = []
flag = 1
def testImage(image_list):
global arr1
global flag
arr1.clear()
for index in range(len(image_list)):
img = io.imread(image_list[index], as_grey=True)
infile = cv2.imread(image_list[index])
infile = infile[:, :, 0]
hues = (np.array(infile) / 255.) * 179
outimageHSV = np.array([[[b, 255, 255] for b in a] for a in hues]).astype(int)
outimageHSV = np.uint8(outimageHSV)
outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR)
rgb = io.imread(image_list[index])
lab = color.rgb2lab(rgb)
outimageBGR = lab
for i in range(outimageBGR.shape[0]):
for j in range(outimageBGR.shape[1]):
sum = 0
for k in range(outimageBGR.shape[2]):
sum = sum + outimageBGR[i][j][k]
sum = sum / (3 * 255)
if (i < img.shape[0] and j < img.shape[1]):
img[i][j] = sum
S = preprocessing.MinMaxScaler((0, 19)).fit_transform(img).astype(int)
Grauwertmatrix = feature.greycomatrix(S, [1, 2, 3], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=20,
symmetric=False, normed=True)
arr1.append(feature.greycoprops(Grauwertmatrix, 'contrast'))
arr1.append(feature.greycoprops(Grauwertmatrix, 'correlation'))
arr1.append(feature.greycoprops(Grauwertmatrix, 'homogeneity'))
arr1.append(feature.greycoprops(Grauwertmatrix, 'ASM'))
arr1.append(feature.greycoprops(Grauwertmatrix, 'energy'))
arr1.append(feature.greycoprops(Grauwertmatrix, 'dissimilarity'))
arr1.append(Features.sumOfSquares(Grauwertmatrix))
arr1.append(Features.sumAverage(Grauwertmatrix))
arr1.append(Features.sumVariance(Grauwertmatrix))
arr1.append(Features.Entropy(Grauwertmatrix))
arr1.append(Features.sumEntropy(Grauwertmatrix))
arr1.append(Features.differenceVariance(Grauwertmatrix))
arr1.append(Features.differenceEntropy(Grauwertmatrix))
arr1.append(Features.informationMeasureOfCorelation1(Grauwertmatrix))
arr1.append(Features.informationMeasureOfCorelation2(Grauwertmatrix))
flag = 1
#print("After applying GLCM the features are : ")
def GLCM(Matrix,index,mask,flag):
global arr
global arr1
if(flag==0):#training
id = 0
for i in range(3):
for j in range(len(arr)):
if( (mask & (1<<j)) == 0 ):
continue
ret = helperFunction(arr[index*15+j],i)
Matrix[id][index] = ret
id = id + 1
else :#testing
id = 0
for i in range(3):
for j in range(len(arr)):
if ((mask & (1 << j)) == 0):
continue
ret = helperFunction(arr1[index*15+j], i)
Matrix[id][index] = ret
id = id + 1
|
[
"numpy.uint8",
"FeatureExtraction.Entropy",
"FeatureExtraction.sumEntropy",
"FeatureExtraction.informationMeasureOfCorelation1",
"cv2.cvtColor",
"skimage.feature.greycoprops",
"FeatureExtraction.informationMeasureOfCorelation2",
"FeatureExtraction.sumOfSquares",
"FeatureExtraction.sumVariance",
"sklearn.preprocessing.MinMaxScaler",
"FeatureExtraction.differenceEntropy",
"skimage.feature.greycomatrix",
"cv2.imread",
"numpy.array",
"FeatureExtraction.differenceVariance",
"FeatureExtraction.sumAverage",
"skimage.io.imread",
"skimage.color.rgb2lab"
] |
[((880, 922), 'skimage.io.imread', 'io.imread', (['image_list[index]'], {'as_grey': '(True)'}), '(image_list[index], as_grey=True)\n', (889, 922), False, 'from skimage import feature, io\n'), ((941, 970), 'cv2.imread', 'cv2.imread', (['image_list[index]'], {}), '(image_list[index])\n', (951, 970), False, 'import cv2\n'), ((1160, 1181), 'numpy.uint8', 'np.uint8', (['outimageHSV'], {}), '(outimageHSV)\n', (1168, 1181), True, 'import numpy as np\n'), ((1205, 1249), 'cv2.cvtColor', 'cv2.cvtColor', (['outimageHSV', 'cv2.COLOR_HSV2BGR'], {}), '(outimageHSV, cv2.COLOR_HSV2BGR)\n', (1217, 1249), False, 'import cv2\n'), ((1265, 1293), 'skimage.io.imread', 'io.imread', (['image_list[index]'], {}), '(image_list[index])\n', (1274, 1293), False, 'from skimage import feature, io\n'), ((1308, 1326), 'skimage.color.rgb2lab', 'color.rgb2lab', (['rgb'], {}), '(rgb)\n', (1321, 1326), False, 'from skimage import io, color\n'), ((1816, 1937), 'skimage.feature.greycomatrix', 'feature.greycomatrix', (['S', '[1, 2, 3]', '[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4]'], {'levels': '(20)', 'symmetric': '(False)', 'normed': '(True)'}), '(S, [1, 2, 3], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4],\n levels=20, symmetric=False, normed=True)\n', (1836, 1937), False, 'from skimage import feature, io\n'), ((3121, 3163), 'skimage.io.imread', 'io.imread', (['image_list[index]'], {'as_grey': '(True)'}), '(image_list[index], as_grey=True)\n', (3130, 3163), False, 'from skimage import feature, io\n'), ((3182, 3211), 'cv2.imread', 'cv2.imread', (['image_list[index]'], {}), '(image_list[index])\n', (3192, 3211), False, 'import cv2\n'), ((3401, 3422), 'numpy.uint8', 'np.uint8', (['outimageHSV'], {}), '(outimageHSV)\n', (3409, 3422), True, 'import numpy as np\n'), ((3446, 3490), 'cv2.cvtColor', 'cv2.cvtColor', (['outimageHSV', 'cv2.COLOR_HSV2BGR'], {}), '(outimageHSV, cv2.COLOR_HSV2BGR)\n', (3458, 3490), False, 'import cv2\n'), ((3507, 3535), 'skimage.io.imread', 'io.imread', (['image_list[index]'], {}), '(image_list[index])\n', (3516, 3535), False, 'from skimage import feature, io\n'), ((3550, 3568), 'skimage.color.rgb2lab', 'color.rgb2lab', (['rgb'], {}), '(rgb)\n', (3563, 3568), False, 'from skimage import io, color\n'), ((4064, 4185), 'skimage.feature.greycomatrix', 'feature.greycomatrix', (['S', '[1, 2, 3]', '[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4]'], {'levels': '(20)', 'symmetric': '(False)', 'normed': '(True)'}), '(S, [1, 2, 3], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4],\n levels=20, symmetric=False, normed=True)\n', (4084, 4185), False, 'from skimage import feature, io\n'), ((2001, 2048), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""contrast"""'], {}), "(Grauwertmatrix, 'contrast')\n", (2020, 2048), False, 'from skimage import feature, io\n'), ((2069, 2119), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""correlation"""'], {}), "(Grauwertmatrix, 'correlation')\n", (2088, 2119), False, 'from skimage import feature, io\n'), ((2140, 2190), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""homogeneity"""'], {}), "(Grauwertmatrix, 'homogeneity')\n", (2159, 2190), False, 'from skimage import feature, io\n'), ((2211, 2253), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""ASM"""'], {}), "(Grauwertmatrix, 'ASM')\n", (2230, 2253), False, 'from skimage import feature, io\n'), ((2274, 2319), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""energy"""'], {}), "(Grauwertmatrix, 'energy')\n", (2293, 2319), False, 'from skimage import feature, io\n'), ((2340, 2392), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""dissimilarity"""'], {}), "(Grauwertmatrix, 'dissimilarity')\n", (2359, 2392), False, 'from skimage import feature, io\n'), ((2413, 2450), 'FeatureExtraction.sumOfSquares', 'Features.sumOfSquares', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2434, 2450), True, 'import FeatureExtraction as Features\n'), ((2471, 2506), 'FeatureExtraction.sumAverage', 'Features.sumAverage', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2490, 2506), True, 'import FeatureExtraction as Features\n'), ((2527, 2563), 'FeatureExtraction.sumVariance', 'Features.sumVariance', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2547, 2563), True, 'import FeatureExtraction as Features\n'), ((2584, 2616), 'FeatureExtraction.Entropy', 'Features.Entropy', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2600, 2616), True, 'import FeatureExtraction as Features\n'), ((2637, 2672), 'FeatureExtraction.sumEntropy', 'Features.sumEntropy', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2656, 2672), True, 'import FeatureExtraction as Features\n'), ((2693, 2736), 'FeatureExtraction.differenceVariance', 'Features.differenceVariance', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2720, 2736), True, 'import FeatureExtraction as Features\n'), ((2757, 2799), 'FeatureExtraction.differenceEntropy', 'Features.differenceEntropy', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2783, 2799), True, 'import FeatureExtraction as Features\n'), ((2820, 2876), 'FeatureExtraction.informationMeasureOfCorelation1', 'Features.informationMeasureOfCorelation1', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2860, 2876), True, 'import FeatureExtraction as Features\n'), ((2897, 2953), 'FeatureExtraction.informationMeasureOfCorelation2', 'Features.informationMeasureOfCorelation2', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (2937, 2953), True, 'import FeatureExtraction as Features\n'), ((4249, 4296), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""contrast"""'], {}), "(Grauwertmatrix, 'contrast')\n", (4268, 4296), False, 'from skimage import feature, io\n'), ((4318, 4368), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""correlation"""'], {}), "(Grauwertmatrix, 'correlation')\n", (4337, 4368), False, 'from skimage import feature, io\n'), ((4390, 4440), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""homogeneity"""'], {}), "(Grauwertmatrix, 'homogeneity')\n", (4409, 4440), False, 'from skimage import feature, io\n'), ((4462, 4504), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""ASM"""'], {}), "(Grauwertmatrix, 'ASM')\n", (4481, 4504), False, 'from skimage import feature, io\n'), ((4526, 4571), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""energy"""'], {}), "(Grauwertmatrix, 'energy')\n", (4545, 4571), False, 'from skimage import feature, io\n'), ((4593, 4645), 'skimage.feature.greycoprops', 'feature.greycoprops', (['Grauwertmatrix', '"""dissimilarity"""'], {}), "(Grauwertmatrix, 'dissimilarity')\n", (4612, 4645), False, 'from skimage import feature, io\n'), ((4667, 4704), 'FeatureExtraction.sumOfSquares', 'Features.sumOfSquares', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (4688, 4704), True, 'import FeatureExtraction as Features\n'), ((4726, 4761), 'FeatureExtraction.sumAverage', 'Features.sumAverage', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (4745, 4761), True, 'import FeatureExtraction as Features\n'), ((4783, 4819), 'FeatureExtraction.sumVariance', 'Features.sumVariance', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (4803, 4819), True, 'import FeatureExtraction as Features\n'), ((4841, 4873), 'FeatureExtraction.Entropy', 'Features.Entropy', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (4857, 4873), True, 'import FeatureExtraction as Features\n'), ((4895, 4930), 'FeatureExtraction.sumEntropy', 'Features.sumEntropy', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (4914, 4930), True, 'import FeatureExtraction as Features\n'), ((4952, 4995), 'FeatureExtraction.differenceVariance', 'Features.differenceVariance', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (4979, 4995), True, 'import FeatureExtraction as Features\n'), ((5017, 5059), 'FeatureExtraction.differenceEntropy', 'Features.differenceEntropy', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (5043, 5059), True, 'import FeatureExtraction as Features\n'), ((5081, 5137), 'FeatureExtraction.informationMeasureOfCorelation1', 'Features.informationMeasureOfCorelation1', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (5121, 5137), True, 'import FeatureExtraction as Features\n'), ((5159, 5215), 'FeatureExtraction.informationMeasureOfCorelation2', 'Features.informationMeasureOfCorelation2', (['Grauwertmatrix'], {}), '(Grauwertmatrix)\n', (5199, 5215), True, 'import FeatureExtraction as Features\n'), ((1020, 1036), 'numpy.array', 'np.array', (['infile'], {}), '(infile)\n', (1028, 1036), True, 'import numpy as np\n'), ((1073, 1125), 'numpy.array', 'np.array', (['[[[b, 255, 255] for b in a] for a in hues]'], {}), '([[[b, 255, 255] for b in a] for a in hues])\n', (1081, 1125), True, 'import numpy as np\n'), ((3261, 3277), 'numpy.array', 'np.array', (['infile'], {}), '(infile)\n', (3269, 3277), True, 'import numpy as np\n'), ((3314, 3366), 'numpy.array', 'np.array', (['[[[b, 255, 255] for b in a] for a in hues]'], {}), '([[[b, 255, 255] for b in a] for a in hues])\n', (3322, 3366), True, 'import numpy as np\n'), ((1724, 1759), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', (['(0, 19)'], {}), '((0, 19))\n', (1750, 1759), False, 'from sklearn import preprocessing\n'), ((3972, 4007), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', (['(0, 19)'], {}), '((0, 19))\n', (3998, 4007), False, 'from sklearn import preprocessing\n')]
|
"""
Geometry container base class.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
import os
from yt.extern.six.moves import cPickle
import weakref
from yt.utilities.on_demand_imports import _h5py as h5py
import numpy as np
from yt.config import ytcfg
from yt.funcs import iterable
from yt.units.yt_array import \
YTArray, uconcatenate
from yt.utilities.io_handler import io_registry
from yt.utilities.logger import ytLogger as mylog
from yt.utilities.parallel_tools.parallel_analysis_interface import \
ParallelAnalysisInterface, parallel_root_only
from yt.utilities.exceptions import YTFieldNotFound
class Index(ParallelAnalysisInterface):
"""The base index class"""
_global_mesh = True
_unsupported_objects = ()
_index_properties = ()
def __init__(self, ds, dataset_type):
ParallelAnalysisInterface.__init__(self)
self.dataset = weakref.proxy(ds)
self.ds = self.dataset
self._initialize_state_variables()
mylog.debug("Initializing data storage.")
self._initialize_data_storage()
mylog.debug("Setting up domain geometry.")
self._setup_geometry()
mylog.debug("Initializing data grid data IO")
self._setup_data_io()
# Note that this falls under the "geometry" object since it's
# potentially quite expensive, and should be done with the indexing.
mylog.debug("Detecting fields.")
self._detect_output_fields()
def _initialize_state_variables(self):
self._parallel_locking = False
self._data_file = None
self._data_mode = None
self.num_grids = None
def _initialize_data_storage(self):
if not ytcfg.getboolean('yt','serialize'): return
fn = self.ds.storage_filename
if fn is None:
if os.path.isfile(os.path.join(self.directory,
"%s.yt" % self.ds.unique_identifier)):
fn = os.path.join(self.directory,"%s.yt" % self.ds.unique_identifier)
else:
fn = os.path.join(self.directory,
"%s.yt" % self.dataset.basename)
dir_to_check = os.path.dirname(fn)
if dir_to_check == '':
dir_to_check = '.'
# We have four options:
# Writeable, does not exist : create, open as append
# Writeable, does exist : open as append
# Not writeable, does not exist : do not attempt to open
# Not writeable, does exist : open as read-only
exists = os.path.isfile(fn)
if not exists:
writeable = os.access(dir_to_check, os.W_OK)
else:
writeable = os.access(fn, os.W_OK)
writeable = writeable and not ytcfg.getboolean('yt','onlydeserialize')
# We now have our conditional stuff
self.comm.barrier()
if not writeable and not exists: return
if writeable:
try:
if not exists: self.__create_data_file(fn)
self._data_mode = 'a'
except IOError:
self._data_mode = None
return
else:
self._data_mode = 'r'
self.__data_filename = fn
self._data_file = h5py.File(fn, self._data_mode)
def __create_data_file(self, fn):
# Note that this used to be parallel_root_only; it no longer is,
# because we have better logic to decide who owns the file.
f = h5py.File(fn, 'a')
f.close()
def _setup_data_io(self):
if getattr(self, "io", None) is not None: return
self.io = io_registry[self.dataset_type](self.dataset)
@parallel_root_only
def save_data(self, array, node, name, set_attr=None, force=False, passthrough = False):
"""
Arbitrary numpy data will be saved to the region in the datafile
described by *node* and *name*. If data file does not exist, it throws
no error and simply does not save.
"""
if self._data_mode != 'a': return
try:
node_loc = self._data_file[node]
if name in node_loc and force:
mylog.info("Overwriting node %s/%s", node, name)
del self._data_file[node][name]
elif name in node_loc and passthrough:
return
except Exception: pass
myGroup = self._data_file['/']
for q in node.split('/'):
if q: myGroup = myGroup.require_group(q)
arr = myGroup.create_dataset(name,data=array)
if set_attr is not None:
for i, j in set_attr.items(): arr.attrs[i] = j
self._data_file.flush()
def _reload_data_file(self, *args, **kwargs):
if self._data_file is None: return
self._data_file.close()
del self._data_file
self._data_file = h5py.File(self.__data_filename, self._data_mode)
def save_object(self, obj, name):
"""
Save an object (*obj*) to the data_file using the Pickle protocol,
under the name *name* on the node /Objects.
"""
s = cPickle.dumps(obj, protocol=-1)
self.save_data(np.array(s, dtype='c'), "/Objects", name, force = True)
def load_object(self, name):
"""
Load and return and object from the data_file using the Pickle protocol,
under the name *name* on the node /Objects.
"""
obj = self.get_data("/Objects", name)
if obj is None:
return
obj = cPickle.loads(obj.value)
if iterable(obj) and len(obj) == 2:
obj = obj[1] # Just the object, not the ds
if hasattr(obj, '_fix_pickle'): obj._fix_pickle()
return obj
def get_data(self, node, name):
"""
Return the dataset with a given *name* located at *node* in the
datafile.
"""
if self._data_file is None:
return None
if node[0] != "/": node = "/%s" % node
myGroup = self._data_file['/']
for group in node.split('/'):
if group:
if group not in myGroup:
return None
myGroup = myGroup[group]
if name not in myGroup:
return None
full_name = "%s/%s" % (node, name)
try:
return self._data_file[full_name][:]
except TypeError:
return self._data_file[full_name]
def _get_particle_type_counts(self):
# this is implemented by subclasses
raise NotImplementedError
def _close_data_file(self):
if self._data_file:
self._data_file.close()
del self._data_file
self._data_file = None
def _split_fields(self, fields):
# This will split fields into either generated or read fields
fields_to_read, fields_to_generate = [], []
for ftype, fname in fields:
if fname in self.field_list or (ftype, fname) in self.field_list:
fields_to_read.append((ftype, fname))
elif fname in self.ds.derived_field_list or (ftype, fname) in self.ds.derived_field_list:
fields_to_generate.append((ftype, fname))
else:
raise YTFieldNotFound((ftype,fname), self.ds)
return fields_to_read, fields_to_generate
def _read_particle_fields(self, fields, dobj, chunk = None):
if len(fields) == 0: return {}, []
fields_to_read, fields_to_generate = self._split_fields(fields)
if len(fields_to_read) == 0:
return {}, fields_to_generate
selector = dobj.selector
if chunk is None:
self._identify_base_chunk(dobj)
fields_to_return = self.io._read_particle_selection(
self._chunk_io(dobj, cache = False),
selector,
fields_to_read)
return fields_to_return, fields_to_generate
def _read_fluid_fields(self, fields, dobj, chunk = None):
if len(fields) == 0: return {}, []
fields_to_read, fields_to_generate = self._split_fields(fields)
if len(fields_to_read) == 0:
return {}, fields_to_generate
selector = dobj.selector
if chunk is None:
self._identify_base_chunk(dobj)
chunk_size = dobj.size
else:
chunk_size = chunk.data_size
fields_to_return = self.io._read_fluid_selection(
self._chunk_io(dobj),
selector,
fields_to_read,
chunk_size)
return fields_to_return, fields_to_generate
def _chunk(self, dobj, chunking_style, ngz = 0, **kwargs):
# A chunk is either None or (grids, size)
if dobj._current_chunk is None:
self._identify_base_chunk(dobj)
if ngz != 0 and chunking_style != "spatial":
raise NotImplementedError
if chunking_style == "all":
return self._chunk_all(dobj, **kwargs)
elif chunking_style == "spatial":
return self._chunk_spatial(dobj, ngz, **kwargs)
elif chunking_style == "io":
return self._chunk_io(dobj, **kwargs)
else:
raise NotImplementedError
def cached_property(func):
n = '_%s' % func.__name__
def cached_func(self):
if self._cache and getattr(self, n, None) is not None:
return getattr(self, n)
if self.data_size is None:
tr = self._accumulate_values(n[1:])
else:
tr = func(self)
if self._cache:
setattr(self, n, tr)
return tr
return property(cached_func)
class YTDataChunk(object):
def __init__(self, dobj, chunk_type, objs, data_size = None,
field_type = None, cache = False, fast_index = None):
self.dobj = dobj
self.chunk_type = chunk_type
self.objs = objs
self.data_size = data_size
self._field_type = field_type
self._cache = cache
self._fast_index = fast_index
def _accumulate_values(self, method):
# We call this generically. It's somewhat slower, since we're doing
# costly getattr functions, but this allows us to generalize.
mname = "select_%s" % method
arrs = []
for obj in self._fast_index or self.objs:
f = getattr(obj, mname)
arrs.append(f(self.dobj))
if method == "dtcoords":
arrs = [arr[0] for arr in arrs]
elif method == "tcoords":
arrs = [arr[1] for arr in arrs]
arrs = uconcatenate(arrs)
self.data_size = arrs.shape[0]
return arrs
@cached_property
def fcoords(self):
if self._fast_index is not None:
ci = self._fast_index.select_fcoords(
self.dobj.selector, self.data_size)
ci = YTArray(ci, input_units = "code_length",
registry = self.dobj.ds.unit_registry)
return ci
ci = np.empty((self.data_size, 3), dtype='float64')
ci = YTArray(ci, input_units = "code_length",
registry = self.dobj.ds.unit_registry)
if self.data_size == 0: return ci
ind = 0
for obj in self._fast_index or self.objs:
c = obj.select_fcoords(self.dobj)
if c.shape[0] == 0: continue
ci[ind:ind+c.shape[0], :] = c
ind += c.shape[0]
return ci
@cached_property
def icoords(self):
if self._fast_index is not None:
ci = self._fast_index.select_icoords(
self.dobj.selector, self.data_size)
return ci
ci = np.empty((self.data_size, 3), dtype='int64')
if self.data_size == 0: return ci
ind = 0
for obj in self._fast_index or self.objs:
c = obj.select_icoords(self.dobj)
if c.shape[0] == 0: continue
ci[ind:ind+c.shape[0], :] = c
ind += c.shape[0]
return ci
@cached_property
def fwidth(self):
if self._fast_index is not None:
ci = self._fast_index.select_fwidth(
self.dobj.selector, self.data_size)
ci = YTArray(ci, input_units = "code_length",
registry = self.dobj.ds.unit_registry)
return ci
ci = np.empty((self.data_size, 3), dtype='float64')
ci = YTArray(ci, input_units = "code_length",
registry = self.dobj.ds.unit_registry)
if self.data_size == 0: return ci
ind = 0
for obj in self._fast_index or self.objs:
c = obj.select_fwidth(self.dobj)
if c.shape[0] == 0: continue
ci[ind:ind+c.shape[0], :] = c
ind += c.shape[0]
return ci
@cached_property
def ires(self):
if self._fast_index is not None:
ci = self._fast_index.select_ires(
self.dobj.selector, self.data_size)
return ci
ci = np.empty(self.data_size, dtype='int64')
if self.data_size == 0: return ci
ind = 0
for obj in self._fast_index or self.objs:
c = obj.select_ires(self.dobj)
if c.shape == 0: continue
ci[ind:ind+c.size] = c
ind += c.size
return ci
@cached_property
def tcoords(self):
self.dtcoords
return self._tcoords
@cached_property
def dtcoords(self):
ct = np.empty(self.data_size, dtype='float64')
cdt = np.empty(self.data_size, dtype='float64')
self._tcoords = ct # Se this for tcoords
if self.data_size == 0: return cdt
ind = 0
for obj in self._fast_index or self.objs:
gdt, gt = obj.select_tcoords(self.dobj)
if gt.size == 0: continue
ct[ind:ind+gt.size] = gt
cdt[ind:ind+gdt.size] = gdt
ind += gt.size
return cdt
@cached_property
def fcoords_vertex(self):
nodes_per_elem = self.dobj.index.meshes[0].connectivity_indices.shape[1]
dim = self.dobj.ds.dimensionality
ci = np.empty((self.data_size, nodes_per_elem, dim), dtype='float64')
ci = YTArray(ci, input_units = "code_length",
registry = self.dobj.ds.unit_registry)
if self.data_size == 0: return ci
ind = 0
for obj in self.objs:
c = obj.select_fcoords_vertex(self.dobj)
if c.shape[0] == 0: continue
ci[ind:ind+c.shape[0], :, :] = c
ind += c.shape[0]
return ci
class ChunkDataCache(object):
def __init__(self, base_iter, preload_fields, geometry_handler,
max_length = 256):
# At some point, max_length should instead become a heuristic function,
# potentially looking at estimated memory usage. Note that this never
# initializes the iterator; it assumes the iterator is already created,
# and it calls next() on it.
self.base_iter = base_iter.__iter__()
self.queue = []
self.max_length = max_length
self.preload_fields = preload_fields
self.geometry_handler = geometry_handler
self.cache = {}
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
if len(self.queue) == 0:
for i in range(self.max_length):
try:
self.queue.append(next(self.base_iter))
except StopIteration:
break
# If it's still zero ...
if len(self.queue) == 0: raise StopIteration
chunk = YTDataChunk(None, "cache", self.queue, cache=False)
self.cache = self.geometry_handler.io._read_chunk_data(
chunk, self.preload_fields) or {}
g = self.queue.pop(0)
g._initialize_cache(self.cache.pop(g.id, {}))
return g
def is_curvilinear(geo):
# tell geometry is curvilinear or not
if geo in ["polar", "cylindrical", "spherical"]:
return True
else:
return False
|
[
"yt.config.ytcfg.getboolean",
"yt.funcs.iterable",
"yt.utilities.logger.ytLogger.debug",
"yt.utilities.on_demand_imports._h5py.File",
"yt.utilities.exceptions.YTFieldNotFound",
"yt.utilities.logger.ytLogger.info",
"numpy.empty",
"os.path.dirname",
"os.path.isfile",
"numpy.array",
"yt.units.yt_array.uconcatenate",
"weakref.proxy",
"yt.extern.six.moves.cPickle.dumps",
"yt.extern.six.moves.cPickle.loads",
"yt.units.yt_array.YTArray",
"os.path.join",
"os.access",
"yt.utilities.parallel_tools.parallel_analysis_interface.ParallelAnalysisInterface.__init__"
] |
[((1120, 1160), 'yt.utilities.parallel_tools.parallel_analysis_interface.ParallelAnalysisInterface.__init__', 'ParallelAnalysisInterface.__init__', (['self'], {}), '(self)\n', (1154, 1160), False, 'from yt.utilities.parallel_tools.parallel_analysis_interface import ParallelAnalysisInterface, parallel_root_only\n'), ((1184, 1201), 'weakref.proxy', 'weakref.proxy', (['ds'], {}), '(ds)\n', (1197, 1201), False, 'import weakref\n'), ((1286, 1327), 'yt.utilities.logger.ytLogger.debug', 'mylog.debug', (['"""Initializing data storage."""'], {}), "('Initializing data storage.')\n", (1297, 1327), True, 'from yt.utilities.logger import ytLogger as mylog\n'), ((1377, 1419), 'yt.utilities.logger.ytLogger.debug', 'mylog.debug', (['"""Setting up domain geometry."""'], {}), "('Setting up domain geometry.')\n", (1388, 1419), True, 'from yt.utilities.logger import ytLogger as mylog\n'), ((1460, 1505), 'yt.utilities.logger.ytLogger.debug', 'mylog.debug', (['"""Initializing data grid data IO"""'], {}), "('Initializing data grid data IO')\n", (1471, 1505), True, 'from yt.utilities.logger import ytLogger as mylog\n'), ((1692, 1724), 'yt.utilities.logger.ytLogger.debug', 'mylog.debug', (['"""Detecting fields."""'], {}), "('Detecting fields.')\n", (1703, 1724), True, 'from yt.utilities.logger import ytLogger as mylog\n'), ((2461, 2480), 'os.path.dirname', 'os.path.dirname', (['fn'], {}), '(fn)\n', (2476, 2480), False, 'import os\n'), ((2855, 2873), 'os.path.isfile', 'os.path.isfile', (['fn'], {}), '(fn)\n', (2869, 2873), False, 'import os\n'), ((3549, 3579), 'yt.utilities.on_demand_imports._h5py.File', 'h5py.File', (['fn', 'self._data_mode'], {}), '(fn, self._data_mode)\n', (3558, 3579), True, 'from yt.utilities.on_demand_imports import _h5py as h5py\n'), ((3772, 3790), 'yt.utilities.on_demand_imports._h5py.File', 'h5py.File', (['fn', '"""a"""'], {}), "(fn, 'a')\n", (3781, 3790), True, 'from yt.utilities.on_demand_imports import _h5py as h5py\n'), ((5144, 5192), 'yt.utilities.on_demand_imports._h5py.File', 'h5py.File', (['self.__data_filename', 'self._data_mode'], {}), '(self.__data_filename, self._data_mode)\n', (5153, 5192), True, 'from yt.utilities.on_demand_imports import _h5py as h5py\n'), ((5395, 5426), 'yt.extern.six.moves.cPickle.dumps', 'cPickle.dumps', (['obj'], {'protocol': '(-1)'}), '(obj, protocol=-1)\n', (5408, 5426), False, 'from yt.extern.six.moves import cPickle\n'), ((5800, 5824), 'yt.extern.six.moves.cPickle.loads', 'cPickle.loads', (['obj.value'], {}), '(obj.value)\n', (5813, 5824), False, 'from yt.extern.six.moves import cPickle\n'), ((10817, 10835), 'yt.units.yt_array.uconcatenate', 'uconcatenate', (['arrs'], {}), '(arrs)\n', (10829, 10835), False, 'from yt.units.yt_array import YTArray, uconcatenate\n'), ((11240, 11286), 'numpy.empty', 'np.empty', (['(self.data_size, 3)'], {'dtype': '"""float64"""'}), "((self.data_size, 3), dtype='float64')\n", (11248, 11286), True, 'import numpy as np\n'), ((11300, 11375), 'yt.units.yt_array.YTArray', 'YTArray', (['ci'], {'input_units': '"""code_length"""', 'registry': 'self.dobj.ds.unit_registry'}), "(ci, input_units='code_length', registry=self.dobj.ds.unit_registry)\n", (11307, 11375), False, 'from yt.units.yt_array import YTArray, uconcatenate\n'), ((11909, 11953), 'numpy.empty', 'np.empty', (['(self.data_size, 3)'], {'dtype': '"""int64"""'}), "((self.data_size, 3), dtype='int64')\n", (11917, 11953), True, 'import numpy as np\n'), ((12582, 12628), 'numpy.empty', 'np.empty', (['(self.data_size, 3)'], {'dtype': '"""float64"""'}), "((self.data_size, 3), dtype='float64')\n", (12590, 12628), True, 'import numpy as np\n'), ((12642, 12717), 'yt.units.yt_array.YTArray', 'YTArray', (['ci'], {'input_units': '"""code_length"""', 'registry': 'self.dobj.ds.unit_registry'}), "(ci, input_units='code_length', registry=self.dobj.ds.unit_registry)\n", (12649, 12717), False, 'from yt.units.yt_array import YTArray, uconcatenate\n'), ((13244, 13283), 'numpy.empty', 'np.empty', (['self.data_size'], {'dtype': '"""int64"""'}), "(self.data_size, dtype='int64')\n", (13252, 13283), True, 'import numpy as np\n'), ((13707, 13748), 'numpy.empty', 'np.empty', (['self.data_size'], {'dtype': '"""float64"""'}), "(self.data_size, dtype='float64')\n", (13715, 13748), True, 'import numpy as np\n'), ((13763, 13804), 'numpy.empty', 'np.empty', (['self.data_size'], {'dtype': '"""float64"""'}), "(self.data_size, dtype='float64')\n", (13771, 13804), True, 'import numpy as np\n'), ((14364, 14428), 'numpy.empty', 'np.empty', (['(self.data_size, nodes_per_elem, dim)'], {'dtype': '"""float64"""'}), "((self.data_size, nodes_per_elem, dim), dtype='float64')\n", (14372, 14428), True, 'import numpy as np\n'), ((14442, 14517), 'yt.units.yt_array.YTArray', 'YTArray', (['ci'], {'input_units': '"""code_length"""', 'registry': 'self.dobj.ds.unit_registry'}), "(ci, input_units='code_length', registry=self.dobj.ds.unit_registry)\n", (14449, 14517), False, 'from yt.units.yt_array import YTArray, uconcatenate\n'), ((1993, 2028), 'yt.config.ytcfg.getboolean', 'ytcfg.getboolean', (['"""yt"""', '"""serialize"""'], {}), "('yt', 'serialize')\n", (2009, 2028), False, 'from yt.config import ytcfg\n'), ((2921, 2953), 'os.access', 'os.access', (['dir_to_check', 'os.W_OK'], {}), '(dir_to_check, os.W_OK)\n', (2930, 2953), False, 'import os\n'), ((2992, 3014), 'os.access', 'os.access', (['fn', 'os.W_OK'], {}), '(fn, os.W_OK)\n', (3001, 3014), False, 'import os\n'), ((5450, 5472), 'numpy.array', 'np.array', (['s'], {'dtype': '"""c"""'}), "(s, dtype='c')\n", (5458, 5472), True, 'import numpy as np\n'), ((5836, 5849), 'yt.funcs.iterable', 'iterable', (['obj'], {}), '(obj)\n', (5844, 5849), False, 'from yt.funcs import iterable\n'), ((11100, 11175), 'yt.units.yt_array.YTArray', 'YTArray', (['ci'], {'input_units': '"""code_length"""', 'registry': 'self.dobj.ds.unit_registry'}), "(ci, input_units='code_length', registry=self.dobj.ds.unit_registry)\n", (11107, 11175), False, 'from yt.units.yt_array import YTArray, uconcatenate\n'), ((12442, 12517), 'yt.units.yt_array.YTArray', 'YTArray', (['ci'], {'input_units': '"""code_length"""', 'registry': 'self.dobj.ds.unit_registry'}), "(ci, input_units='code_length', registry=self.dobj.ds.unit_registry)\n", (12449, 12517), False, 'from yt.units.yt_array import YTArray, uconcatenate\n'), ((2127, 2192), 'os.path.join', 'os.path.join', (['self.directory', "('%s.yt' % self.ds.unique_identifier)"], {}), "(self.directory, '%s.yt' % self.ds.unique_identifier)\n", (2139, 2192), False, 'import os\n'), ((2248, 2313), 'os.path.join', 'os.path.join', (['self.directory', "('%s.yt' % self.ds.unique_identifier)"], {}), "(self.directory, '%s.yt' % self.ds.unique_identifier)\n", (2260, 2313), False, 'import os\n'), ((2352, 2413), 'os.path.join', 'os.path.join', (['self.directory', "('%s.yt' % self.dataset.basename)"], {}), "(self.directory, '%s.yt' % self.dataset.basename)\n", (2364, 2413), False, 'import os\n'), ((3053, 3094), 'yt.config.ytcfg.getboolean', 'ytcfg.getboolean', (['"""yt"""', '"""onlydeserialize"""'], {}), "('yt', 'onlydeserialize')\n", (3069, 3094), False, 'from yt.config import ytcfg\n'), ((4458, 4506), 'yt.utilities.logger.ytLogger.info', 'mylog.info', (['"""Overwriting node %s/%s"""', 'node', 'name'], {}), "('Overwriting node %s/%s', node, name)\n", (4468, 4506), True, 'from yt.utilities.logger import ytLogger as mylog\n'), ((7519, 7559), 'yt.utilities.exceptions.YTFieldNotFound', 'YTFieldNotFound', (['(ftype, fname)', 'self.ds'], {}), '((ftype, fname), self.ds)\n', (7534, 7559), False, 'from yt.utilities.exceptions import YTFieldNotFound\n')]
|
import time
import numpy as np
import scipy.io as sio
import h5py
from sklearn.datasets import load_svmlight_file
from sklearn.cluster import KMeans
f = h5py.File('/code/BIDMach/data/MNIST8M/all.mat','r')
t0 = time.time()
data = f.get('/all') # Get a certain dataset
X = np.array(data)
t1 = time.time()
t_read = t1 - t0
print("Finished reading in " + repr(t_read) + " secs")
batch_size = 10
kmeans = KMeans(n_clusters=256, init='random', n_init=1, max_iter=10, tol=0.0001, precompute_distances=False, verbose=0, random_state=None, copy_x=False, n_jobs=1)
kmeans.fit(X)
t2 = time.time()
t_batch = t2 - t1
print("compute time " + repr(t_batch) + " secs")
|
[
"sklearn.cluster.KMeans",
"h5py.File",
"numpy.array",
"time.time"
] |
[((155, 207), 'h5py.File', 'h5py.File', (['"""/code/BIDMach/data/MNIST8M/all.mat"""', '"""r"""'], {}), "('/code/BIDMach/data/MNIST8M/all.mat', 'r')\n", (164, 207), False, 'import h5py\n'), ((213, 224), 'time.time', 'time.time', ([], {}), '()\n', (222, 224), False, 'import time\n'), ((274, 288), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (282, 288), True, 'import numpy as np\n'), ((294, 305), 'time.time', 'time.time', ([], {}), '()\n', (303, 305), False, 'import time\n'), ((405, 567), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(256)', 'init': '"""random"""', 'n_init': '(1)', 'max_iter': '(10)', 'tol': '(0.0001)', 'precompute_distances': '(False)', 'verbose': '(0)', 'random_state': 'None', 'copy_x': '(False)', 'n_jobs': '(1)'}), "(n_clusters=256, init='random', n_init=1, max_iter=10, tol=0.0001,\n precompute_distances=False, verbose=0, random_state=None, copy_x=False,\n n_jobs=1)\n", (411, 567), False, 'from sklearn.cluster import KMeans\n'), ((579, 590), 'time.time', 'time.time', ([], {}), '()\n', (588, 590), False, 'import time\n')]
|
"""Interfacing parameters for the OpenBCI Ganglion Board."""
from ble2lsl.devices.device import BasePacketHandler
from ble2lsl.utils import bad_data_size, dict_partial_from_keys
import struct
from warnings import warn
import numpy as np
from pygatt import BLEAddressType
NAME = "Ganglion"
MANUFACTURER = "OpenBCI"
STREAMS = ["EEG", "accelerometer", "messages"]
"""Data provided by the OpenBCI Ganglion, and available for subscription."""
DEFAULT_SUBSCRIPTIONS = ["EEG", "messages"]
"""Streams to which to subscribe by default."""
# for constructing dicts with STREAMS as keys
streams_dict = dict_partial_from_keys(STREAMS)
PARAMS = dict(
streams=dict(
type=streams_dict(STREAMS), # same as stream names
channel_count=streams_dict([4, 3, 1]),
nominal_srate=streams_dict([200, 10, 0.0]),
channel_format=streams_dict(['float32', 'float32', 'string']),
numpy_dtype=streams_dict(['float32', 'float32', 'object']),
units=streams_dict([('uV',) * 4, ('g\'s',) * 3, ('',)]),
ch_names=streams_dict([('A', 'B', 'C', 'D'), ('x', 'y', 'z'),
('message',)]),
chunk_size=streams_dict([1, 1, 1]),
),
ble=dict(
address_type=BLEAddressType.random,
# service='fe84',
interval_min=6, # OpenBCI suggest 9
interval_max=11, # suggest 10
# receive characteristic UUIDs
EEG=["2d30c082f39f4ce6923f3484ea480596"],
accelerometer='', # placeholder; already subscribed through eeg
messages='', # placeholder; subscription not required
# send characteristic UUID and commands
send="2d30c083f39f4ce6923f3484ea480596",
stream_on=b'b',
stream_off=b's',
accelerometer_on=b'n',
accelerometer_off=b'N',
# impedance_on=b'z',
# impedance_off=b'Z',
# other characteristics
# disconnect="2d30c084f39f4ce6923f3484ea480596",
),
)
"""OpenBCI Ganglion LSL- and BLE-related parameters."""
INT_SIGN_BYTE = (b'\x00', b'\xff')
SCALE_FACTOR = streams_dict([1.2 / (8388608.0 * 1.5 * 51.0),
0.016,
1 # not used (messages)
])
"""Scale factors for conversion of EEG and accelerometer data to mV."""
ID_TURNOVER = streams_dict([201, 10])
"""The number of samples processed before the packet ID cycles back to zero."""
class PacketHandler(BasePacketHandler):
"""Process packets from the OpenBCI Ganglion into chunks."""
def __init__(self, streamer, **kwargs):
super().__init__(PARAMS["streams"], streamer, **kwargs)
self._sample_ids = streams_dict([-1] * len(STREAMS))
if "EEG" in self._streamer.subscriptions:
self._last_eeg_data = np.zeros(self._chunks["EEG"].shape[1])
if "messages" in self._streamer.subscriptions:
self._chunks["messages"][0] = ""
self._chunk_idxs["messages"] = -1
if "accelerometer" in self._streamer.subscriptions:
# queue accelerometer_on command
self._streamer.send_command(PARAMS["ble"]["accelerometer_on"])
# byte ID ranges for parsing function selection
self._byte_id_ranges = {(101, 200): self._parse_compressed_19bit,
(0, 0): self._parse_uncompressed,
(206, 207): self._parse_message,
(1, 100): self._parse_compressed_18bit,
(201, 205): self._parse_impedance,
(208, -1): self._unknown_packet_warning}
def process_packet(self, handle, packet):
"""Process incoming data packet.
Calls the corresponding parsing function depending on packet format.
"""
start_byte = packet[0]
for r in self._byte_id_ranges:
if start_byte >= r[0] and start_byte <= r[1]:
self._byte_id_ranges[r](start_byte, packet[1:])
break
def _update_counts_and_enqueue(self, name, sample_id):
"""Update last packet ID and dropped packets"""
if self._sample_ids[name] == -1:
self._sample_ids[name] = sample_id
self._chunk_idxs[name] = 1
return
# sample IDs loops every 101 packets
self._chunk_idxs[name] += sample_id - self._sample_ids[name]
if sample_id < self._sample_ids[name]:
self._chunk_idxs[name] += ID_TURNOVER[name]
self._sample_ids[name] = sample_id
if name == "EEG":
self._chunks[name][0, :] = np.copy(self._last_eeg_data)
self._chunks[name] *= SCALE_FACTOR[name]
self._enqueue_chunk(name)
def _unknown_packet_warning(self, start_byte, packet):
"""Print if incoming byte ID is unknown."""
warn("Unknown Ganglion packet byte ID: {}".format(start_byte))
def _parse_message(self, start_byte, packet):
"""Parse a partial ASCII message."""
if "messages" in self._streamer.subscriptions:
self._chunks["messages"] += str(packet)
if start_byte == 207:
self._enqueue_chunk("messages")
self._chunks["messages"][0] = ""
def _parse_uncompressed(self, packet_id, packet):
"""Parse a raw uncompressed packet."""
if bad_data_size(packet, 19, "uncompressed data"):
return
# 4 channels of 24bits
self._last_eeg_data[:] = [int_from_24bits(packet[i:i + 3])
for i in range(0, 12, 3)]
# = np.array([chan_data], dtype=np.float32).T
self._update_counts_and_enqueue("EEG", packet_id)
def _update_data_with_deltas(self, packet_id, deltas):
for delta_id in [0, 1]:
# convert from packet to sample ID
sample_id = (packet_id - 1) * 2 + delta_id + 1
# 19bit packets hold deltas between two samples
self._last_eeg_data += np.array(deltas[delta_id])
self._update_counts_and_enqueue("EEG", sample_id)
def _parse_compressed_19bit(self, packet_id, packet):
"""Parse a 19-bit compressed packet without accelerometer data."""
if bad_data_size(packet, 19, "19-bit compressed data"):
return
packet_id -= 100
# should get 2 by 4 arrays of uncompressed data
deltas = decompress_deltas_19bit(packet)
self._update_data_with_deltas(packet_id, deltas)
def _parse_compressed_18bit(self, packet_id, packet):
""" Dealing with "18-bit compression without Accelerometer" """
if bad_data_size(packet, 19, "18-bit compressed data"):
return
# set appropriate accelerometer byte
id_ones = packet_id % 10 - 1
if id_ones in [0, 1, 2]:
value = int8_from_byte(packet[18])
self._chunks["accelerometer"][0, id_ones] = value
if id_ones == 2:
self._update_counts_and_enqueue("accelerometer",
packet_id // 10)
# deltas: should get 2 by 4 arrays of uncompressed data
deltas = decompress_deltas_18bit(packet[:-1])
self._update_data_with_deltas(packet_id, deltas)
def _parse_impedance(self, packet_id, packet):
"""Parse impedance data.
After turning on impedance checking, takes a few seconds to complete.
"""
raise NotImplementedError # until this is sorted out...
if packet[-2:] != 'Z\n':
print("Wrong format for impedance: not ASCII ending with 'Z\\n'")
# convert from ASCII to actual value
imp_value = int(packet[:-2])
# from 201 to 205 codes to the right array size
self.last_impedance[packet_id - 201] = imp_value
self.push_sample(packet_id - 200, self._data,
self.last_accelerometer, self.last_impedance)
def int_from_24bits(unpacked):
"""Convert 24-bit data coded on 3 bytes to a proper integer."""
if bad_data_size(unpacked, 3, "3-byte buffer"):
raise ValueError("Bad input size for byte conversion.")
# FIXME: quick'n dirty, unpack wants strings later on
int_bytes = INT_SIGN_BYTE[unpacked[0] > 127] + struct.pack('3B', *unpacked)
# unpack little endian(>) signed integer(i) (-> platform independent)
int_unpacked = struct.unpack('>i', int_bytes)[0]
return int_unpacked
def int32_from_19bit(three_byte_buffer):
"""Convert 19-bit data coded on 3 bytes to a proper integer."""
if bad_data_size(three_byte_buffer, 3, "3-byte buffer"):
raise ValueError("Bad input size for byte conversion.")
# if LSB is 1, negative number
if three_byte_buffer[2] & 0x01 > 0:
prefix = 0b1111111111111
int32 = ((prefix << 19) | (three_byte_buffer[0] << 16)
| (three_byte_buffer[1] << 8) | three_byte_buffer[2]) \
| ~0xFFFFFFFF
else:
prefix = 0
int32 = (prefix << 19) | (three_byte_buffer[0] << 16) \
| (three_byte_buffer[1] << 8) | three_byte_buffer[2]
return int32
def int32_from_18bit(three_byte_buffer):
"""Convert 18-bit data coded on 3 bytes to a proper integer."""
if bad_data_size(three_byte_buffer, 3, "3-byte buffer"):
raise ValueError("Bad input size for byte conversion.")
# if LSB is 1, negative number, some hasty unsigned to signed conversion to do
if three_byte_buffer[2] & 0x01 > 0:
prefix = 0b11111111111111
int32 = ((prefix << 18) | (three_byte_buffer[0] << 16)
| (three_byte_buffer[1] << 8) | three_byte_buffer[2]) \
| ~0xFFFFFFFF
else:
prefix = 0
int32 = (prefix << 18) | (three_byte_buffer[0] << 16) \
| (three_byte_buffer[1] << 8) | three_byte_buffer[2]
return int32
def int8_from_byte(byte):
"""Convert one byte to signed integer."""
if byte > 127:
return (256 - byte) * (-1)
else:
return byte
def decompress_deltas_19bit(buffer):
"""Parse packet deltas from 19-bit compression format."""
if bad_data_size(buffer, 19, "19-byte compressed packet"):
raise ValueError("Bad input size for byte conversion.")
deltas = np.zeros((2, 4))
# Sample 1 - Channel 1
minibuf = [(buffer[0] >> 5),
((buffer[0] & 0x1F) << 3 & 0xFF) | (buffer[1] >> 5),
((buffer[1] & 0x1F) << 3 & 0xFF) | (buffer[2] >> 5)]
deltas[0][0] = int32_from_19bit(minibuf)
# Sample 1 - Channel 2
minibuf = [(buffer[2] & 0x1F) >> 2,
(buffer[2] << 6 & 0xFF) | (buffer[3] >> 2),
(buffer[3] << 6 & 0xFF) | (buffer[4] >> 2)]
deltas[0][1] = int32_from_19bit(minibuf)
# Sample 1 - Channel 3
minibuf = [((buffer[4] & 0x03) << 1 & 0xFF) | (buffer[5] >> 7),
((buffer[5] & 0x7F) << 1 & 0xFF) | (buffer[6] >> 7),
((buffer[6] & 0x7F) << 1 & 0xFF) | (buffer[7] >> 7)]
deltas[0][2] = int32_from_19bit(minibuf)
# Sample 1 - Channel 4
minibuf = [((buffer[7] & 0x7F) >> 4),
((buffer[7] & 0x0F) << 4 & 0xFF) | (buffer[8] >> 4),
((buffer[8] & 0x0F) << 4 & 0xFF) | (buffer[9] >> 4)]
deltas[0][3] = int32_from_19bit(minibuf)
# Sample 2 - Channel 1
minibuf = [((buffer[9] & 0x0F) >> 1),
(buffer[9] << 7 & 0xFF) | (buffer[10] >> 1),
(buffer[10] << 7 & 0xFF) | (buffer[11] >> 1)]
deltas[1][0] = int32_from_19bit(minibuf)
# Sample 2 - Channel 2
minibuf = [((buffer[11] & 0x01) << 2 & 0xFF) | (buffer[12] >> 6),
(buffer[12] << 2 & 0xFF) | (buffer[13] >> 6),
(buffer[13] << 2 & 0xFF) | (buffer[14] >> 6)]
deltas[1][1] = int32_from_19bit(minibuf)
# Sample 2 - Channel 3
minibuf = [((buffer[14] & 0x38) >> 3),
((buffer[14] & 0x07) << 5 & 0xFF) | ((buffer[15] & 0xF8) >> 3),
((buffer[15] & 0x07) << 5 & 0xFF) | ((buffer[16] & 0xF8) >> 3)]
deltas[1][2] = int32_from_19bit(minibuf)
# Sample 2 - Channel 4
minibuf = [(buffer[16] & 0x07), buffer[17], buffer[18]]
deltas[1][3] = int32_from_19bit(minibuf)
return deltas
def decompress_deltas_18bit(buffer):
"""Parse packet deltas from 18-byte compression format."""
if bad_data_size(buffer, 18, "18-byte compressed packet"):
raise ValueError("Bad input size for byte conversion.")
deltas = np.zeros((2, 4))
# Sample 1 - Channel 1
minibuf = [(buffer[0] >> 6),
((buffer[0] & 0x3F) << 2 & 0xFF) | (buffer[1] >> 6),
((buffer[1] & 0x3F) << 2 & 0xFF) | (buffer[2] >> 6)]
deltas[0][0] = int32_from_18bit(minibuf)
# Sample 1 - Channel 2
minibuf = [(buffer[2] & 0x3F) >> 4,
(buffer[2] << 4 & 0xFF) | (buffer[3] >> 4),
(buffer[3] << 4 & 0xFF) | (buffer[4] >> 4)]
deltas[0][1] = int32_from_18bit(minibuf)
# Sample 1 - Channel 3
minibuf = [(buffer[4] & 0x0F) >> 2,
(buffer[4] << 6 & 0xFF) | (buffer[5] >> 2),
(buffer[5] << 6 & 0xFF) | (buffer[6] >> 2)]
deltas[0][2] = int32_from_18bit(minibuf)
# Sample 1 - Channel 4
minibuf = [(buffer[6] & 0x03), buffer[7], buffer[8]]
deltas[0][3] = int32_from_18bit(minibuf)
# Sample 2 - Channel 1
minibuf = [(buffer[9] >> 6),
((buffer[9] & 0x3F) << 2 & 0xFF) | (buffer[10] >> 6),
((buffer[10] & 0x3F) << 2 & 0xFF) | (buffer[11] >> 6)]
deltas[1][0] = int32_from_18bit(minibuf)
# Sample 2 - Channel 2
minibuf = [(buffer[11] & 0x3F) >> 4,
(buffer[11] << 4 & 0xFF) | (buffer[12] >> 4),
(buffer[12] << 4 & 0xFF) | (buffer[13] >> 4)]
deltas[1][1] = int32_from_18bit(minibuf)
# Sample 2 - Channel 3
minibuf = [(buffer[13] & 0x0F) >> 2,
(buffer[13] << 6 & 0xFF) | (buffer[14] >> 2),
(buffer[14] << 6 & 0xFF) | (buffer[15] >> 2)]
deltas[1][2] = int32_from_18bit(minibuf)
# Sample 2 - Channel 4
minibuf = [(buffer[15] & 0x03), buffer[16], buffer[17]]
deltas[1][3] = int32_from_18bit(minibuf)
return deltas
|
[
"numpy.copy",
"struct.unpack",
"numpy.zeros",
"struct.pack",
"ble2lsl.utils.dict_partial_from_keys",
"ble2lsl.utils.bad_data_size",
"numpy.array"
] |
[((599, 630), 'ble2lsl.utils.dict_partial_from_keys', 'dict_partial_from_keys', (['STREAMS'], {}), '(STREAMS)\n', (621, 630), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((8030, 8073), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['unpacked', '(3)', '"""3-byte buffer"""'], {}), "(unpacked, 3, '3-byte buffer')\n", (8043, 8073), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((8549, 8601), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['three_byte_buffer', '(3)', '"""3-byte buffer"""'], {}), "(three_byte_buffer, 3, '3-byte buffer')\n", (8562, 8601), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((9240, 9292), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['three_byte_buffer', '(3)', '"""3-byte buffer"""'], {}), "(three_byte_buffer, 3, '3-byte buffer')\n", (9253, 9292), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((10128, 10182), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['buffer', '(19)', '"""19-byte compressed packet"""'], {}), "(buffer, 19, '19-byte compressed packet')\n", (10141, 10182), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((10262, 10278), 'numpy.zeros', 'np.zeros', (['(2, 4)'], {}), '((2, 4))\n', (10270, 10278), True, 'import numpy as np\n'), ((12316, 12370), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['buffer', '(18)', '"""18-byte compressed packet"""'], {}), "(buffer, 18, '18-byte compressed packet')\n", (12329, 12370), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((12450, 12466), 'numpy.zeros', 'np.zeros', (['(2, 4)'], {}), '((2, 4))\n', (12458, 12466), True, 'import numpy as np\n'), ((5350, 5396), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['packet', '(19)', '"""uncompressed data"""'], {}), "(packet, 19, 'uncompressed data')\n", (5363, 5396), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((6214, 6265), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['packet', '(19)', '"""19-bit compressed data"""'], {}), "(packet, 19, '19-bit compressed data')\n", (6227, 6265), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((6616, 6667), 'ble2lsl.utils.bad_data_size', 'bad_data_size', (['packet', '(19)', '"""18-bit compressed data"""'], {}), "(packet, 19, '18-bit compressed data')\n", (6629, 6667), False, 'from ble2lsl.utils import bad_data_size, dict_partial_from_keys\n'), ((8249, 8277), 'struct.pack', 'struct.pack', (['"""3B"""', '*unpacked'], {}), "('3B', *unpacked)\n", (8260, 8277), False, 'import struct\n'), ((8372, 8402), 'struct.unpack', 'struct.unpack', (['""">i"""', 'int_bytes'], {}), "('>i', int_bytes)\n", (8385, 8402), False, 'import struct\n'), ((2787, 2825), 'numpy.zeros', 'np.zeros', (["self._chunks['EEG'].shape[1]"], {}), "(self._chunks['EEG'].shape[1])\n", (2795, 2825), True, 'import numpy as np\n'), ((4608, 4636), 'numpy.copy', 'np.copy', (['self._last_eeg_data'], {}), '(self._last_eeg_data)\n', (4615, 4636), True, 'import numpy as np\n'), ((5980, 6006), 'numpy.array', 'np.array', (['deltas[delta_id]'], {}), '(deltas[delta_id])\n', (5988, 6006), True, 'import numpy as np\n')]
|
import cv2
from imutils.video.pivideostream import PiVideoStream
import time
from tf_lite import Model
import numpy as np
import RPi.GPIO as GPIO
from time import sleep
from cv2 import resize
from picamera import PiCamera
import wiringpi as wiringpi
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
class VideoCamera(object):
def __init__(self):
self.cap = PiVideoStream().start()
time.sleep(0.1)
print("Initialising Raspberry Pi...")
GPIO.output(11,1)
print("LED Red Testing")
time.sleep(1.0)
GPIO.output(11,0)
GPIO.output(13,1)
print("LED Green Testing")
time.sleep(1.0)
GPIO.output(13,0)
GPIO.output(15,1)
print("LED Blue Testing")
time.sleep(1.0)
GPIO.output(15,0)
wiringpi.wiringPiSetup()
wiringpi.pinMode(26, 2)
wiringpi.softPwmCreate(26,0,25)
def __del__(self):
self.cap.stop()
def get_frame(self):
frame = self.cap.read()
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
def get_object(self, classifier):
frame = self.cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
objects = classifier.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the objects
for (x, y, w, h) in objects:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 140, 125), 2)
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
def get_mask(self):
frame = self.cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
dutycycle = 0
model = Model()
interpreter = model.load_interpreter()
input_details = model.input_details()
output_details = model.output_details()
input_shape = input_details[0]['shape']
label_dict = {0: 'MASK', 1: "NO MASK"}
eye_img = gray
resized = cv2.resize(eye_img, (100,100))
normalized = resized / 255.0
reshaped = np.reshape(normalized, input_shape)
reshaped = np.float32(reshaped)
interpreter.set_tensor(input_details[0]['index'], reshaped)
interpreter.invoke()
result = interpreter.get_tensor(output_details[0]['index'])
result = 1 - result
label = np.argmax(result, axis=1)[0]
if label==0:
cv2.putText(frame, label_dict[label], (75,150), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (250, 240, 255), 2)
GPIO.output(15,1)
print(label_dict[label])
wiringpi.softPwmWrite(26,25)
time.sleep(0.1)
position = dutycycle
GPIO.output(15,0)
elif label==1:
cv2.putText(frame, label_dict[label], (75,150), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (250, 240, 255), 2)
GPIO.output(13,1)
print(label_dict[label])
wiringpi.softPwmWrite(26,0)
time.sleep(0.1)
position = dutycycle
GPIO.output(13,0)
ret, jpeg = cv2.imencode('.jpg', frame)
return frame
PiCam = VideoCamera()
def rescaleFrame(frame, scale=2.5):
# Images, Videos and Live Video
width = int(frame.shape[1] * scale)
height = int(frame.shape[0] * scale)
dimensions = (width,height)
return cv2.resize(frame, dimensions, interpolation=cv2.INTER_AREA)
while(True):
frame = PiCam.get_mask()
frame_resized = rescaleFrame(frame)
cv2.imshow('FACE MASK DETECTOR',frame_resized)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
|
[
"wiringpi.softPwmCreate",
"numpy.argmax",
"cv2.rectangle",
"cv2.imencode",
"RPi.GPIO.output",
"cv2.imshow",
"RPi.GPIO.setup",
"cv2.cvtColor",
"wiringpi.pinMode",
"imutils.video.pivideostream.PiVideoStream",
"numpy.reshape",
"cv2.destroyAllWindows",
"wiringpi.softPwmWrite",
"tf_lite.Model",
"cv2.resize",
"RPi.GPIO.setmode",
"cv2.waitKey",
"time.sleep",
"cv2.putText",
"numpy.float32",
"wiringpi.wiringPiSetup"
] |
[((250, 274), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BOARD'], {}), '(GPIO.BOARD)\n', (262, 274), True, 'import RPi.GPIO as GPIO\n'), ((275, 299), 'RPi.GPIO.setup', 'GPIO.setup', (['(11)', 'GPIO.OUT'], {}), '(11, GPIO.OUT)\n', (285, 299), True, 'import RPi.GPIO as GPIO\n'), ((300, 324), 'RPi.GPIO.setup', 'GPIO.setup', (['(13)', 'GPIO.OUT'], {}), '(13, GPIO.OUT)\n', (310, 324), True, 'import RPi.GPIO as GPIO\n'), ((325, 349), 'RPi.GPIO.setup', 'GPIO.setup', (['(15)', 'GPIO.OUT'], {}), '(15, GPIO.OUT)\n', (335, 349), True, 'import RPi.GPIO as GPIO\n'), ((3814, 3837), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3835, 3837), False, 'import cv2\n'), ((3506, 3565), 'cv2.resize', 'cv2.resize', (['frame', 'dimensions'], {'interpolation': 'cv2.INTER_AREA'}), '(frame, dimensions, interpolation=cv2.INTER_AREA)\n', (3516, 3565), False, 'import cv2\n'), ((3652, 3699), 'cv2.imshow', 'cv2.imshow', (['"""FACE MASK DETECTOR"""', 'frame_resized'], {}), "('FACE MASK DETECTOR', frame_resized)\n", (3662, 3699), False, 'import cv2\n'), ((457, 472), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (467, 472), False, 'import time\n'), ((527, 545), 'RPi.GPIO.output', 'GPIO.output', (['(11)', '(1)'], {}), '(11, 1)\n', (538, 545), True, 'import RPi.GPIO as GPIO\n'), ((586, 601), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (596, 601), False, 'import time\n'), ((610, 628), 'RPi.GPIO.output', 'GPIO.output', (['(11)', '(0)'], {}), '(11, 0)\n', (621, 628), True, 'import RPi.GPIO as GPIO\n'), ((636, 654), 'RPi.GPIO.output', 'GPIO.output', (['(13)', '(1)'], {}), '(13, 1)\n', (647, 654), True, 'import RPi.GPIO as GPIO\n'), ((697, 712), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (707, 712), False, 'import time\n'), ((721, 739), 'RPi.GPIO.output', 'GPIO.output', (['(13)', '(0)'], {}), '(13, 0)\n', (732, 739), True, 'import RPi.GPIO as GPIO\n'), ((747, 765), 'RPi.GPIO.output', 'GPIO.output', (['(15)', '(1)'], {}), '(15, 1)\n', (758, 765), True, 'import RPi.GPIO as GPIO\n'), ((807, 822), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (817, 822), False, 'import time\n'), ((831, 849), 'RPi.GPIO.output', 'GPIO.output', (['(15)', '(0)'], {}), '(15, 0)\n', (842, 849), True, 'import RPi.GPIO as GPIO\n'), ((857, 881), 'wiringpi.wiringPiSetup', 'wiringpi.wiringPiSetup', ([], {}), '()\n', (879, 881), True, 'import wiringpi as wiringpi\n'), ((890, 913), 'wiringpi.pinMode', 'wiringpi.pinMode', (['(26)', '(2)'], {}), '(26, 2)\n', (906, 913), True, 'import wiringpi as wiringpi\n'), ((922, 955), 'wiringpi.softPwmCreate', 'wiringpi.softPwmCreate', (['(26)', '(0)', '(25)'], {}), '(26, 0, 25)\n', (944, 955), True, 'import wiringpi as wiringpi\n'), ((1082, 1109), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'frame'], {}), "('.jpg', frame)\n", (1094, 1109), False, 'import cv2\n'), ((1226, 1265), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1238, 1265), False, 'import cv2\n'), ((1651, 1678), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'frame'], {}), "('.jpg', frame)\n", (1663, 1678), False, 'import cv2\n'), ((1781, 1820), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1793, 1820), False, 'import cv2\n'), ((1868, 1875), 'tf_lite.Model', 'Model', ([], {}), '()\n', (1873, 1875), False, 'from tf_lite import Model\n'), ((2153, 2184), 'cv2.resize', 'cv2.resize', (['eye_img', '(100, 100)'], {}), '(eye_img, (100, 100))\n', (2163, 2184), False, 'import cv2\n'), ((2240, 2275), 'numpy.reshape', 'np.reshape', (['normalized', 'input_shape'], {}), '(normalized, input_shape)\n', (2250, 2275), True, 'import numpy as np\n'), ((2295, 2315), 'numpy.float32', 'np.float32', (['reshaped'], {}), '(reshaped)\n', (2305, 2315), True, 'import numpy as np\n'), ((3237, 3264), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'frame'], {}), "('.jpg', frame)\n", (3249, 3264), False, 'import cv2\n'), ((1567, 1629), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 140, 125)', '(2)'], {}), '(frame, (x, y), (x + w, y + h), (0, 140, 125), 2)\n', (1580, 1629), False, 'import cv2\n'), ((2525, 2550), 'numpy.argmax', 'np.argmax', (['result'], {'axis': '(1)'}), '(result, axis=1)\n', (2534, 2550), True, 'import numpy as np\n'), ((2587, 2691), 'cv2.putText', 'cv2.putText', (['frame', 'label_dict[label]', '(75, 150)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', '(250, 240, 255)', '(2)'], {}), '(frame, label_dict[label], (75, 150), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, (250, 240, 255), 2)\n', (2598, 2691), False, 'import cv2\n'), ((2698, 2716), 'RPi.GPIO.output', 'GPIO.output', (['(15)', '(1)'], {}), '(15, 1)\n', (2709, 2716), True, 'import RPi.GPIO as GPIO\n'), ((2765, 2794), 'wiringpi.softPwmWrite', 'wiringpi.softPwmWrite', (['(26)', '(25)'], {}), '(26, 25)\n', (2786, 2794), True, 'import wiringpi as wiringpi\n'), ((2806, 2821), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (2816, 2821), False, 'import time\n'), ((2867, 2885), 'RPi.GPIO.output', 'GPIO.output', (['(15)', '(0)'], {}), '(15, 0)\n', (2878, 2885), True, 'import RPi.GPIO as GPIO\n'), ((3706, 3720), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3717, 3720), False, 'import cv2\n'), ((425, 440), 'imutils.video.pivideostream.PiVideoStream', 'PiVideoStream', ([], {}), '()\n', (438, 440), False, 'from imutils.video.pivideostream import PiVideoStream\n'), ((2920, 3024), 'cv2.putText', 'cv2.putText', (['frame', 'label_dict[label]', '(75, 150)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', '(250, 240, 255)', '(2)'], {}), '(frame, label_dict[label], (75, 150), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, (250, 240, 255), 2)\n', (2931, 3024), False, 'import cv2\n'), ((3031, 3049), 'RPi.GPIO.output', 'GPIO.output', (['(13)', '(1)'], {}), '(13, 1)\n', (3042, 3049), True, 'import RPi.GPIO as GPIO\n'), ((3098, 3126), 'wiringpi.softPwmWrite', 'wiringpi.softPwmWrite', (['(26)', '(0)'], {}), '(26, 0)\n', (3119, 3126), True, 'import wiringpi as wiringpi\n'), ((3138, 3153), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (3148, 3153), False, 'import time\n'), ((3199, 3217), 'RPi.GPIO.output', 'GPIO.output', (['(13)', '(0)'], {}), '(13, 0)\n', (3210, 3217), True, 'import RPi.GPIO as GPIO\n')]
|
from config import HNConfig as Config
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib import colors
import os
window_size = 5
dpi = 100
iter_lim = 5000
record_moment = np.arange(0, iter_lim, 10)
record = False
delta_t = 0.01
noise = 0.001
u_0 = 0.02
param_a = 1.0
param_b = 1.0
param_c = 2.0
param_d = 1.0
def sigmoid(inputs):
return 1.0 / (np.ones(inputs.shape) + np.exp(-inputs / u_0))
def dist(p1, p2):
return np.linalg.norm(p1 - p2)
def kronecker_delta(i, j):
if i == j:
return 1.0
return 0.0
def calc_weight_matrix(city_array):
city_num = city_array.shape[0]
n = city_num ** 2
tmp = np.zeros((n, n))
for s0 in range(n):
x = int(s0 / city_num)
i = s0 % city_num
for s1 in range(n):
y = int(s1 / city_num)
j = s1 % city_num
dxy = dist(city_array[x, :], city_array[y, :])
tmp[s0, s1] = -param_a * kronecker_delta(x, y) * (1.0 - kronecker_delta(i, j)) - param_b * kronecker_delta(
i, j) * (1.0 - kronecker_delta(x, y)) - param_c - param_d * dxy * (
kronecker_delta(j, (i - 1) % city_num) + kronecker_delta(j, (i + 1) % city_num))
return tmp
def calc_bias(city_array):
city_num = city_array.shape[0]
n = city_num ** 2
tmp = param_c * n * np.ones(n)
return tmp
def update_inner_vals(nodes_array, inner_vals, weight_matrix, biases):
tau = 1.0
asdf = np.dot(weight_matrix, nodes_array)
delta = (-inner_vals / tau + asdf + biases) * delta_t
return inner_vals + delta
# TODO bad code
def make_directory():
dir_name = './results/'
directory = os.path.dirname(dir_name)
try:
os.stat(directory)
except:
os.mkdir(directory)
dir_name += Config.city_file.replace(
'.csv', '') + '/'
directory = os.path.dirname(dir_name)
try:
os.stat(directory)
except:
os.mkdir(directory)
dir_name += 'hopfield_net/'
directory = os.path.dirname(dir_name)
try:
os.stat(directory)
except:
os.mkdir(directory)
return dir_name
def en_begin(inner_vals_array, nodes_array, weights_matrix, biases_array):
if record:
dir_name = make_directory()
for i in range(iter_lim):
if i in record_moment:
filename = 'iteration-' + str(i) + '.png'
file_path = dir_name + filename
plt.savefig(file_path)
inner_vals_array = update_inner_vals(nodes_array, inner_vals_array, weights_matrix, biases_array)
nodes_array = sigmoid(inner_vals_array)
plt.title("iteration=" + str(i + 1))
mat_visual.set_data(np.reshape(nodes_array, (city_num, city_num)))
plt.pause(.0001)
else:
i = 1
# while plt.get_fignums():
# inner_vals_array = update_inner_vals(nodes_array, inner_vals_array, weights_matrix, biases_array)
# nodes_array = sigmoid(inner_vals_array)
# plt.title("iteration=" + str(i))
# mat_visual.set_data(np.reshape(nodes_array, (city_num, city_num)))
# i += 1
# plt.pause(.01)
while plt.get_fignums():
inner_vals_array = update_inner_vals(nodes_array, inner_vals_array, weights_matrix, biases_array)
nodes_array = sigmoid(inner_vals_array)
plt.title("iteration=" + str(i))
mat_visual.set_data(np.reshape(nodes_array, (city_num, city_num)))
i += 1
plt.pause(.0001)
if __name__ == "__main__":
if (Config.read_file):
np_cities = np.genfromtxt(
Config.file_path + Config.city_file, delimiter=',')
city_num = np_cities.shape[0]
# width_x = (np.max(np_cities[:, 0]) - np.min(np_cities[:, 0]))
# width_y = (np.max(np_cities[:, 1]) - np.min(np_cities[:, 1]))
# width = np.amax([width_x, width_y])
# np_cities[:, 0] -= np.min(np_cities[:, 0])
# np_cities[:, 0] /= width
# np_cities[:, 1] -= np.min(np_cities[:, 1])
# np_cities[:, 1] /= width
# center_x = np.average(np_cities[:, 0])
# center_y = np.average(np_cities[:, 1])
figsize = (window_size, window_size)
else:
city_num = Config.city_num
# “continuous uniform” distribution random
np_cities = np.random.random((city_num, 2))
center_x = 0.5
center_y = 0.5
figsize = (window_size, window_size)
inner_vals = (np.random.random((city_num ** 2)) - 0.5) * noise
nodes = sigmoid(inner_vals)
weights = calc_weight_matrix(np_cities)
biases = calc_bias(np_cities)
fig = plt.figure(figsize=figsize, dpi=dpi)
mat_visual = plt.matshow(np.reshape(nodes, (city_num, city_num)), fignum=0, cmap=cm.Greys, norm=colors.Normalize(vmin=0., vmax=1.))
fig.colorbar(mat_visual)
plt.title("iteration=" + str(0))
plt.pause(.0001)
en_begin(inner_vals, nodes, weights, biases)
|
[
"os.mkdir",
"config.HNConfig.city_file.replace",
"os.stat",
"matplotlib.colors.Normalize",
"os.path.dirname",
"numpy.zeros",
"numpy.ones",
"numpy.genfromtxt",
"matplotlib.pyplot.figure",
"numpy.random.random",
"numpy.linalg.norm",
"numpy.arange",
"numpy.reshape",
"numpy.exp",
"numpy.dot",
"matplotlib.pyplot.get_fignums",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.savefig"
] |
[((219, 245), 'numpy.arange', 'np.arange', (['(0)', 'iter_lim', '(10)'], {}), '(0, iter_lim, 10)\n', (228, 245), True, 'import numpy as np\n'), ((476, 499), 'numpy.linalg.norm', 'np.linalg.norm', (['(p1 - p2)'], {}), '(p1 - p2)\n', (490, 499), True, 'import numpy as np\n'), ((683, 699), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (691, 699), True, 'import numpy as np\n'), ((1502, 1536), 'numpy.dot', 'np.dot', (['weight_matrix', 'nodes_array'], {}), '(weight_matrix, nodes_array)\n', (1508, 1536), True, 'import numpy as np\n'), ((1709, 1734), 'os.path.dirname', 'os.path.dirname', (['dir_name'], {}), '(dir_name)\n', (1724, 1734), False, 'import os\n'), ((1895, 1920), 'os.path.dirname', 'os.path.dirname', (['dir_name'], {}), '(dir_name)\n', (1910, 1920), False, 'import os\n'), ((2045, 2070), 'os.path.dirname', 'os.path.dirname', (['dir_name'], {}), '(dir_name)\n', (2060, 2070), False, 'import os\n'), ((4702, 4738), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize', 'dpi': 'dpi'}), '(figsize=figsize, dpi=dpi)\n', (4712, 4738), True, 'from matplotlib import pyplot as plt\n'), ((4945, 4962), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (4954, 4962), True, 'from matplotlib import pyplot as plt\n'), ((1378, 1388), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (1385, 1388), True, 'import numpy as np\n'), ((1752, 1770), 'os.stat', 'os.stat', (['directory'], {}), '(directory)\n', (1759, 1770), False, 'import os\n'), ((1827, 1863), 'config.HNConfig.city_file.replace', 'Config.city_file.replace', (['""".csv"""', '""""""'], {}), "('.csv', '')\n", (1851, 1863), True, 'from config import HNConfig as Config\n'), ((1938, 1956), 'os.stat', 'os.stat', (['directory'], {}), '(directory)\n', (1945, 1956), False, 'import os\n'), ((2088, 2106), 'os.stat', 'os.stat', (['directory'], {}), '(directory)\n', (2095, 2106), False, 'import os\n'), ((3221, 3238), 'matplotlib.pyplot.get_fignums', 'plt.get_fignums', ([], {}), '()\n', (3236, 3238), True, 'from matplotlib import pyplot as plt\n'), ((3650, 3715), 'numpy.genfromtxt', 'np.genfromtxt', (['(Config.file_path + Config.city_file)'], {'delimiter': '""","""'}), "(Config.file_path + Config.city_file, delimiter=',')\n", (3663, 3715), True, 'import numpy as np\n'), ((4392, 4423), 'numpy.random.random', 'np.random.random', (['(city_num, 2)'], {}), '((city_num, 2))\n', (4408, 4423), True, 'import numpy as np\n'), ((4768, 4807), 'numpy.reshape', 'np.reshape', (['nodes', '(city_num, city_num)'], {}), '(nodes, (city_num, city_num))\n', (4778, 4807), True, 'import numpy as np\n'), ((398, 419), 'numpy.ones', 'np.ones', (['inputs.shape'], {}), '(inputs.shape)\n', (405, 419), True, 'import numpy as np\n'), ((422, 443), 'numpy.exp', 'np.exp', (['(-inputs / u_0)'], {}), '(-inputs / u_0)\n', (428, 443), True, 'import numpy as np\n'), ((1791, 1810), 'os.mkdir', 'os.mkdir', (['directory'], {}), '(directory)\n', (1799, 1810), False, 'import os\n'), ((1977, 1996), 'os.mkdir', 'os.mkdir', (['directory'], {}), '(directory)\n', (1985, 1996), False, 'import os\n'), ((2127, 2146), 'os.mkdir', 'os.mkdir', (['directory'], {}), '(directory)\n', (2135, 2146), False, 'import os\n'), ((2811, 2828), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (2820, 2828), True, 'from matplotlib import pyplot as plt\n'), ((3557, 3574), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (3566, 3574), True, 'from matplotlib import pyplot as plt\n'), ((4533, 4564), 'numpy.random.random', 'np.random.random', (['(city_num ** 2)'], {}), '(city_num ** 2)\n', (4549, 4564), True, 'import numpy as np\n'), ((4839, 4875), 'matplotlib.colors.Normalize', 'colors.Normalize', ([], {'vmin': '(0.0)', 'vmax': '(1.0)'}), '(vmin=0.0, vmax=1.0)\n', (4855, 4875), False, 'from matplotlib import colors\n'), ((2486, 2508), 'matplotlib.pyplot.savefig', 'plt.savefig', (['file_path'], {}), '(file_path)\n', (2497, 2508), True, 'from matplotlib import pyplot as plt\n'), ((2752, 2797), 'numpy.reshape', 'np.reshape', (['nodes_array', '(city_num, city_num)'], {}), '(nodes_array, (city_num, city_num))\n', (2762, 2797), True, 'import numpy as np\n'), ((3479, 3524), 'numpy.reshape', 'np.reshape', (['nodes_array', '(city_num, city_num)'], {}), '(nodes_array, (city_num, city_num))\n', (3489, 3524), True, 'import numpy as np\n')]
|
import copy
import pandas as pd
import numpy as np
import warnings
import logging
from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
from supervised.preprocessing.preprocessing_categorical import PreprocessingCategorical
from supervised.preprocessing.preprocessing_missing import PreprocessingMissingValues
from supervised.preprocessing.scale import Scale
from supervised.preprocessing.label_encoder import LabelEncoder
from supervised.preprocessing.label_binarizer import LabelBinarizer
from supervised.preprocessing.datetime_transformer import DateTimeTransformer
from supervised.preprocessing.text_transformer import TextTransformer
from supervised.preprocessing.goldenfeatures_transformer import (
GoldenFeaturesTransformer,
)
from supervised.preprocessing.kmeans_transformer import KMeansTransformer
from supervised.preprocessing.exclude_missing_target import ExcludeRowsMissingTarget
from supervised.algorithms.registry import (
BINARY_CLASSIFICATION,
MULTICLASS_CLASSIFICATION,
REGRESSION,
)
from supervised.utils.config import LOG_LEVEL
from supervised.exceptions import AutoMLException
logger = logging.getLogger(__name__)
logger.setLevel(LOG_LEVEL)
class Preprocessing(object):
def __init__(
self,
preprocessing_params={"target_preprocessing": [], "columns_preprocessing": {}},
model_name=None,
k_fold=None,
repeat=None,
):
self._params = preprocessing_params
if "target_preprocessing" not in preprocessing_params:
self._params["target_preprocessing"] = []
if "columns_preprocessing" not in preprocessing_params:
self._params["columns_preprocessing"] = {}
# preprocssing step attributes
self._categorical_y = None
self._scale_y = None
self._missing_values = []
self._categorical = []
self._scale = []
self._remove_columns = []
self._datetime_transforms = []
self._text_transforms = []
self._golden_features = None
self._kmeans = None
self._add_random_feature = self._params.get("add_random_feature", False)
self._drop_features = self._params.get("drop_features", [])
self._model_name = model_name
self._k_fold = k_fold
self._repeat = repeat
def _exclude_missing_targets(self, X=None, y=None):
# check if there are missing values in target column
if y is None:
return X, y
y_missing = pd.isnull(y)
if np.sum(np.array(y_missing)) == 0:
return X, y
y = y.drop(y.index[y_missing])
y.index = range(y.shape[0])
if X is not None:
X = X.drop(X.index[y_missing])
X.index = range(X.shape[0])
return X, y
# fit and transform
def fit_and_transform(self, X_train, y_train, sample_weight=None):
logger.debug("Preprocessing.fit_and_transform")
if y_train is not None:
# target preprocessing
# this must be used first, maybe we will drop some rows because of missing target values
target_preprocessing = self._params.get("target_preprocessing")
logger.debug("target_preprocessing params: {}".format(target_preprocessing))
X_train, y_train, sample_weight = ExcludeRowsMissingTarget.transform(
X_train, y_train, sample_weight
)
if PreprocessingCategorical.CONVERT_INTEGER in target_preprocessing:
logger.debug("Convert target to integer")
self._categorical_y = LabelEncoder(try_to_fit_numeric=True)
self._categorical_y.fit(y_train)
y_train = pd.Series(self._categorical_y.transform(y_train))
if PreprocessingCategorical.CONVERT_ONE_HOT in target_preprocessing:
logger.debug("Convert target to one-hot coding")
self._categorical_y = LabelBinarizer()
self._categorical_y.fit(pd.DataFrame({"target": y_train}), "target")
y_train = self._categorical_y.transform(
pd.DataFrame({"target": y_train}), "target"
)
if Scale.SCALE_LOG_AND_NORMAL in target_preprocessing:
logger.debug("Scale log and normal")
self._scale_y = Scale(
["target"], scale_method=Scale.SCALE_LOG_AND_NORMAL
)
y_train = pd.DataFrame({"target": y_train})
self._scale_y.fit(y_train)
y_train = self._scale_y.transform(y_train)
y_train = y_train["target"]
if Scale.SCALE_NORMAL in target_preprocessing:
logger.debug("Scale normal")
self._scale_y = Scale(["target"], scale_method=Scale.SCALE_NORMAL)
y_train = pd.DataFrame({"target": y_train})
self._scale_y.fit(y_train)
y_train = self._scale_y.transform(y_train)
y_train = y_train["target"]
# columns preprocessing
columns_preprocessing = self._params.get("columns_preprocessing")
for column in columns_preprocessing:
transforms = columns_preprocessing[column]
# logger.debug("Preprocess column {} with: {}".format(column, transforms))
# remove empty or constant columns
cols_to_remove = list(
filter(
lambda k: "remove_column" in columns_preprocessing[k],
columns_preprocessing,
)
)
if X_train is not None:
X_train.drop(cols_to_remove, axis=1, inplace=True)
self._remove_columns = cols_to_remove
numeric_cols = [] # get numeric cols before text transformations
# needed for golden features
if X_train is not None and (
"golden_features" in self._params or "kmeans_features" in self._params
):
numeric_cols = X_train.select_dtypes(include="number").columns.tolist()
# there can be missing values in the text data,
# but we don't want to handle it by fill missing methods
# zeros will be imputed by text_transform method
cols_to_process = list(
filter(
lambda k: "text_transform" in columns_preprocessing[k],
columns_preprocessing,
)
)
new_text_columns = []
for col in cols_to_process:
t = TextTransformer()
t.fit(X_train, col)
X_train = t.transform(X_train)
self._text_transforms += [t]
new_text_columns += t._new_columns
# end of text transform
for missing_method in [PreprocessingMissingValues.FILL_NA_MEDIAN]:
cols_to_process = list(
filter(
lambda k: missing_method in columns_preprocessing[k],
columns_preprocessing,
)
)
missing = PreprocessingMissingValues(cols_to_process, missing_method)
missing.fit(X_train)
X_train = missing.transform(X_train)
self._missing_values += [missing]
# golden features
golden_columns = []
if "golden_features" in self._params:
results_path = self._params["golden_features"]["results_path"]
ml_task = self._params["golden_features"]["ml_task"]
features_count = self._params["golden_features"].get("features_count")
self._golden_features = GoldenFeaturesTransformer(
results_path, ml_task, features_count
)
self._golden_features.fit(X_train[numeric_cols], y_train)
X_train = self._golden_features.transform(X_train)
golden_columns = self._golden_features._new_columns
kmeans_columns = []
if "kmeans_features" in self._params:
results_path = self._params["kmeans_features"]["results_path"]
self._kmeans = KMeansTransformer(
results_path, self._model_name, self._k_fold
)
self._kmeans.fit(X_train[numeric_cols], y_train)
X_train = self._kmeans.transform(X_train)
kmeans_columns = self._kmeans._new_features
for convert_method in [
PreprocessingCategorical.CONVERT_INTEGER,
PreprocessingCategorical.CONVERT_ONE_HOT,
PreprocessingCategorical.CONVERT_LOO,
]:
cols_to_process = list(
filter(
lambda k: convert_method in columns_preprocessing[k],
columns_preprocessing,
)
)
convert = PreprocessingCategorical(cols_to_process, convert_method)
convert.fit(X_train, y_train)
X_train = convert.transform(X_train)
self._categorical += [convert]
# datetime transform
cols_to_process = list(
filter(
lambda k: "datetime_transform" in columns_preprocessing[k],
columns_preprocessing,
)
)
new_datetime_columns = []
for col in cols_to_process:
t = DateTimeTransformer()
t.fit(X_train, col)
X_train = t.transform(X_train)
self._datetime_transforms += [t]
new_datetime_columns += t._new_columns
# SCALE
for scale_method in [Scale.SCALE_NORMAL, Scale.SCALE_LOG_AND_NORMAL]:
cols_to_process = list(
filter(
lambda k: scale_method in columns_preprocessing[k],
columns_preprocessing,
)
)
if (
len(cols_to_process)
and len(new_datetime_columns)
and scale_method == Scale.SCALE_NORMAL
):
cols_to_process += new_datetime_columns
if (
len(cols_to_process)
and len(new_text_columns)
and scale_method == Scale.SCALE_NORMAL
):
cols_to_process += new_text_columns
if (
len(cols_to_process)
and len(golden_columns)
and scale_method == Scale.SCALE_NORMAL
):
cols_to_process += golden_columns
if (
len(cols_to_process)
and len(kmeans_columns)
and scale_method == Scale.SCALE_NORMAL
):
cols_to_process += kmeans_columns
if len(cols_to_process):
scale = Scale(cols_to_process)
scale.fit(X_train)
X_train = scale.transform(X_train)
self._scale += [scale]
if self._add_random_feature:
# -1, 1, with 0 mean
X_train["random_feature"] = np.random.rand(X_train.shape[0]) * 2.0 - 1.0
if self._drop_features:
available_cols = X_train.columns.tolist()
drop_cols = [c for c in self._drop_features if c in available_cols]
if len(drop_cols) == X_train.shape[1]:
raise AutoMLException(
"All features are droppped! Your data looks like random data."
)
if drop_cols:
X_train.drop(drop_cols, axis=1, inplace=True)
self._drop_features = drop_cols
if X_train is not None:
# there can be catagorical columns (in CatBoost) which cant be clipped
numeric_cols = X_train.select_dtypes(include="number").columns.tolist()
X_train[numeric_cols] = X_train[numeric_cols].clip(
lower=np.finfo(np.float32).min + 1000,
upper=np.finfo(np.float32).max - 1000,
)
return X_train, y_train, sample_weight
def transform(self, X_validation, y_validation, sample_weight_validation=None):
logger.debug("Preprocessing.transform")
# doing copy to avoid SettingWithCopyWarning
if X_validation is not None:
X_validation = X_validation.copy(deep=False)
if y_validation is not None:
y_validation = y_validation.copy(deep=False)
# target preprocessing
# this must be used first, maybe we will drop some rows because of missing target values
if y_validation is not None:
target_preprocessing = self._params.get("target_preprocessing")
logger.debug("target_preprocessing -> {}".format(target_preprocessing))
(
X_validation,
y_validation,
sample_weight_validation,
) = ExcludeRowsMissingTarget.transform(
X_validation, y_validation, sample_weight_validation
)
if PreprocessingCategorical.CONVERT_INTEGER in target_preprocessing:
if y_validation is not None and self._categorical_y is not None:
y_validation = pd.Series(
self._categorical_y.transform(y_validation)
)
if PreprocessingCategorical.CONVERT_ONE_HOT in target_preprocessing:
if y_validation is not None and self._categorical_y is not None:
y_validation = self._categorical_y.transform(
pd.DataFrame({"target": y_validation}), "target"
)
if Scale.SCALE_LOG_AND_NORMAL in target_preprocessing:
if self._scale_y is not None and y_validation is not None:
logger.debug("Transform log and normalize")
y_validation = pd.DataFrame({"target": y_validation})
y_validation = self._scale_y.transform(y_validation)
y_validation = y_validation["target"]
if Scale.SCALE_NORMAL in target_preprocessing:
if self._scale_y is not None and y_validation is not None:
logger.debug("Transform normalize")
y_validation = pd.DataFrame({"target": y_validation})
y_validation = self._scale_y.transform(y_validation)
y_validation = y_validation["target"]
# columns preprocessing
if len(self._remove_columns) and X_validation is not None:
cols_to_remove = [
col for col in X_validation.columns if col in self._remove_columns
]
X_validation.drop(cols_to_remove, axis=1, inplace=True)
# text transform
for tt in self._text_transforms:
if X_validation is not None and tt is not None:
X_validation = tt.transform(X_validation)
for missing in self._missing_values:
if X_validation is not None and missing is not None:
X_validation = missing.transform(X_validation)
# to be sure that all missing are filled
# in case new data there can be gaps!
if (
X_validation is not None
and np.sum(np.sum(pd.isnull(X_validation))) > 0
and len(self._params["columns_preprocessing"]) > 0
):
# there is something missing, fill it
# we should notice user about it!
# warnings should go to the separate file ...
# warnings.warn(
# "There are columns {} with missing values which didnt have missing values in train dataset.".format(
# list(
# X_validation.columns[np.where(np.sum(pd.isnull(X_validation)))]
# )
# )
# )
missing = PreprocessingMissingValues(
X_validation.columns, PreprocessingMissingValues.FILL_NA_MEDIAN
)
missing.fit(X_validation)
X_validation = missing.transform(X_validation)
# golden features
if self._golden_features is not None:
X_validation = self._golden_features.transform(X_validation)
if self._kmeans is not None:
X_validation = self._kmeans.transform(X_validation)
for convert in self._categorical:
if X_validation is not None and convert is not None:
X_validation = convert.transform(X_validation)
for dtt in self._datetime_transforms:
if X_validation is not None and dtt is not None:
X_validation = dtt.transform(X_validation)
for scale in self._scale:
if X_validation is not None and scale is not None:
X_validation = scale.transform(X_validation)
if self._add_random_feature:
# -1, 1, with 0 mean
X_validation["random_feature"] = (
np.random.rand(X_validation.shape[0]) * 2.0 - 1.0
)
if self._drop_features and X_validation is not None:
X_validation.drop(self._drop_features, axis=1, inplace=True)
if X_validation is not None:
# there can be catagorical columns (in CatBoost) which cant be clipped
numeric_cols = X_validation.select_dtypes(include="number").columns.tolist()
X_validation[numeric_cols] = X_validation[numeric_cols].clip(
lower=np.finfo(np.float32).min + 1000,
upper=np.finfo(np.float32).max - 1000,
)
return X_validation, y_validation, sample_weight_validation
def inverse_scale_target(self, y):
if self._scale_y is not None:
y = pd.DataFrame({"target": y})
y = self._scale_y.inverse_transform(y)
y = y["target"]
return y
def inverse_categorical_target(self, y):
if self._categorical_y is not None:
y = self._categorical_y.inverse_transform(y)
y = y.astype(str)
return y
def get_target_class_names(self):
pos_label, neg_label = "1", "0"
if self._categorical_y is not None:
if self._params["ml_task"] == BINARY_CLASSIFICATION:
# binary classification
for label, value in self._categorical_y.to_json().items():
if value == 1:
pos_label = label
else:
neg_label = label
return [neg_label, pos_label]
else:
# multiclass classification
# logger.debug(self._categorical_y.to_json())
if "unique_values" not in self._categorical_y.to_json():
labels = dict(
(v, k) for k, v in self._categorical_y.to_json().items()
)
else:
labels = {
i: v
for i, v in enumerate(
self._categorical_y.to_json()["unique_values"]
)
}
return list(labels.values())
else: # self._categorical_y is None
if "ml_task" in self._params:
if self._params["ml_task"] == BINARY_CLASSIFICATION:
return ["0", "1"]
return []
def prepare_target_labels(self, y):
pos_label, neg_label = "1", "0"
if self._categorical_y is not None:
if len(y.shape) == 1:
# binary classification
for label, value in self._categorical_y.to_json().items():
if value == 1:
pos_label = label
else:
neg_label = label
# threshold is applied in AutoML class
return pd.DataFrame(
{
"prediction_{}".format(neg_label): 1 - y,
"prediction_{}".format(pos_label): y,
}
)
else:
# multiclass classification
if "unique_values" not in self._categorical_y.to_json():
labels = dict(
(v, k) for k, v in self._categorical_y.to_json().items()
)
else:
labels = {
i: v
for i, v in enumerate(
self._categorical_y.to_json()["unique_values"]
)
}
d = {}
cols = []
for i in range(y.shape[1]):
d["prediction_{}".format(labels[i])] = y[:, i]
cols += ["prediction_{}".format(labels[i])]
df = pd.DataFrame(d)
df["label"] = np.argmax(np.array(df[cols]), axis=1)
df["label"] = df["label"].map(labels)
return df
else: # self._categorical_y is None
if "ml_task" in self._params:
if self._params["ml_task"] == BINARY_CLASSIFICATION:
return pd.DataFrame({"prediction_0": 1 - y, "prediction_1": y})
elif self._params["ml_task"] == MULTICLASS_CLASSIFICATION:
return pd.DataFrame(
data=y,
columns=["prediction_{}".format(i) for i in range(y.shape[1])],
)
return pd.DataFrame({"prediction": y})
def to_json(self):
preprocessing_params = {}
if self._remove_columns:
preprocessing_params["remove_columns"] = self._remove_columns
if self._missing_values is not None and len(self._missing_values):
mvs = [] # refactor
for mv in self._missing_values:
if mv.to_json():
mvs += [mv.to_json()]
if mvs:
preprocessing_params["missing_values"] = mvs
if self._categorical is not None and len(self._categorical):
cats = [] # refactor
for cat in self._categorical:
if cat.to_json():
cats += [cat.to_json()]
if cats:
preprocessing_params["categorical"] = cats
if self._datetime_transforms is not None and len(self._datetime_transforms):
dtts = []
for dtt in self._datetime_transforms:
dtts += [dtt.to_json()]
if dtts:
preprocessing_params["datetime_transforms"] = dtts
if self._text_transforms is not None and len(self._text_transforms):
tts = []
for tt in self._text_transforms:
tts += [tt.to_json()]
if tts:
preprocessing_params["text_transforms"] = tts
if self._golden_features is not None:
preprocessing_params["golden_features"] = self._golden_features.to_json()
if self._kmeans is not None:
preprocessing_params["kmeans"] = self._kmeans.to_json()
if self._scale is not None and len(self._scale):
scs = [sc.to_json() for sc in self._scale if sc.to_json()]
if scs:
preprocessing_params["scale"] = scs
if self._categorical_y is not None:
cat_y = self._categorical_y.to_json()
if cat_y:
preprocessing_params["categorical_y"] = cat_y
if self._scale_y is not None:
preprocessing_params["scale_y"] = self._scale_y.to_json()
if "ml_task" in self._params:
preprocessing_params["ml_task"] = self._params["ml_task"]
if self._add_random_feature:
preprocessing_params["add_random_feature"] = True
if self._drop_features:
preprocessing_params["drop_features"] = self._drop_features
preprocessing_params["params"] = self._params
return preprocessing_params
def from_json(self, data_json, results_path):
self._params = data_json.get("params", self._params)
if "remove_columns" in data_json:
self._remove_columns = data_json.get("remove_columns", [])
if "missing_values" in data_json:
self._missing_values = []
for mv_data in data_json["missing_values"]:
mv = PreprocessingMissingValues()
mv.from_json(mv_data)
self._missing_values += [mv]
if "categorical" in data_json:
self._categorical = []
for cat_data in data_json["categorical"]:
cat = PreprocessingCategorical()
cat.from_json(cat_data)
self._categorical += [cat]
if "datetime_transforms" in data_json:
self._datetime_transforms = []
for dtt_params in data_json["datetime_transforms"]:
dtt = DateTimeTransformer()
dtt.from_json(dtt_params)
self._datetime_transforms += [dtt]
if "text_transforms" in data_json:
self._text_transforms = []
for tt_params in data_json["text_transforms"]:
tt = TextTransformer()
tt.from_json(tt_params)
self._text_transforms += [tt]
if "golden_features" in data_json:
self._golden_features = GoldenFeaturesTransformer()
self._golden_features.from_json(data_json["golden_features"], results_path)
if "kmeans" in data_json:
self._kmeans = KMeansTransformer()
self._kmeans.from_json(data_json["kmeans"], results_path)
if "scale" in data_json:
self._scale = []
for scale_data in data_json["scale"]:
sc = Scale()
sc.from_json(scale_data)
self._scale += [sc]
if "categorical_y" in data_json:
if "new_columns" in data_json["categorical_y"]:
self._categorical_y = LabelBinarizer()
else:
self._categorical_y = LabelEncoder()
self._categorical_y.from_json(data_json["categorical_y"])
if "scale_y" in data_json:
self._scale_y = Scale()
self._scale_y.from_json(data_json["scale_y"])
if "ml_task" in data_json:
self._params["ml_task"] = data_json["ml_task"]
self._add_random_feature = data_json.get("add_random_feature", False)
self._drop_features = data_json.get("drop_features", [])
|
[
"pandas.DataFrame",
"supervised.preprocessing.datetime_transformer.DateTimeTransformer",
"supervised.exceptions.AutoMLException",
"supervised.preprocessing.preprocessing_categorical.PreprocessingCategorical",
"pandas.isnull",
"supervised.preprocessing.goldenfeatures_transformer.GoldenFeaturesTransformer",
"supervised.preprocessing.text_transformer.TextTransformer",
"numpy.finfo",
"numpy.array",
"supervised.preprocessing.label_binarizer.LabelBinarizer",
"supervised.preprocessing.label_encoder.LabelEncoder",
"numpy.random.rand",
"supervised.preprocessing.kmeans_transformer.KMeansTransformer",
"supervised.preprocessing.scale.Scale",
"supervised.preprocessing.exclude_missing_target.ExcludeRowsMissingTarget.transform",
"logging.getLogger",
"supervised.preprocessing.preprocessing_missing.PreprocessingMissingValues"
] |
[((1148, 1175), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1165, 1175), False, 'import logging\n'), ((2507, 2519), 'pandas.isnull', 'pd.isnull', (['y'], {}), '(y)\n', (2516, 2519), True, 'import pandas as pd\n'), ((21376, 21407), 'pandas.DataFrame', 'pd.DataFrame', (["{'prediction': y}"], {}), "({'prediction': y})\n", (21388, 21407), True, 'import pandas as pd\n'), ((3326, 3393), 'supervised.preprocessing.exclude_missing_target.ExcludeRowsMissingTarget.transform', 'ExcludeRowsMissingTarget.transform', (['X_train', 'y_train', 'sample_weight'], {}), '(X_train, y_train, sample_weight)\n', (3360, 3393), False, 'from supervised.preprocessing.exclude_missing_target import ExcludeRowsMissingTarget\n'), ((6484, 6501), 'supervised.preprocessing.text_transformer.TextTransformer', 'TextTransformer', ([], {}), '()\n', (6499, 6501), False, 'from supervised.preprocessing.text_transformer import TextTransformer\n'), ((7004, 7063), 'supervised.preprocessing.preprocessing_missing.PreprocessingMissingValues', 'PreprocessingMissingValues', (['cols_to_process', 'missing_method'], {}), '(cols_to_process, missing_method)\n', (7030, 7063), False, 'from supervised.preprocessing.preprocessing_missing import PreprocessingMissingValues\n'), ((7552, 7616), 'supervised.preprocessing.goldenfeatures_transformer.GoldenFeaturesTransformer', 'GoldenFeaturesTransformer', (['results_path', 'ml_task', 'features_count'], {}), '(results_path, ml_task, features_count)\n', (7577, 7616), False, 'from supervised.preprocessing.goldenfeatures_transformer import GoldenFeaturesTransformer\n'), ((8021, 8084), 'supervised.preprocessing.kmeans_transformer.KMeansTransformer', 'KMeansTransformer', (['results_path', 'self._model_name', 'self._k_fold'], {}), '(results_path, self._model_name, self._k_fold)\n', (8038, 8084), False, 'from supervised.preprocessing.kmeans_transformer import KMeansTransformer\n'), ((8719, 8776), 'supervised.preprocessing.preprocessing_categorical.PreprocessingCategorical', 'PreprocessingCategorical', (['cols_to_process', 'convert_method'], {}), '(cols_to_process, convert_method)\n', (8743, 8776), False, 'from supervised.preprocessing.preprocessing_categorical import PreprocessingCategorical\n'), ((9220, 9241), 'supervised.preprocessing.datetime_transformer.DateTimeTransformer', 'DateTimeTransformer', ([], {}), '()\n', (9239, 9241), False, 'from supervised.preprocessing.datetime_transformer import DateTimeTransformer\n'), ((12715, 12807), 'supervised.preprocessing.exclude_missing_target.ExcludeRowsMissingTarget.transform', 'ExcludeRowsMissingTarget.transform', (['X_validation', 'y_validation', 'sample_weight_validation'], {}), '(X_validation, y_validation,\n sample_weight_validation)\n', (12749, 12807), False, 'from supervised.preprocessing.exclude_missing_target import ExcludeRowsMissingTarget\n'), ((15697, 15793), 'supervised.preprocessing.preprocessing_missing.PreprocessingMissingValues', 'PreprocessingMissingValues', (['X_validation.columns', 'PreprocessingMissingValues.FILL_NA_MEDIAN'], {}), '(X_validation.columns, PreprocessingMissingValues\n .FILL_NA_MEDIAN)\n', (15723, 15793), False, 'from supervised.preprocessing.preprocessing_missing import PreprocessingMissingValues\n'), ((17565, 17592), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y}"], {}), "({'target': y})\n", (17577, 17592), True, 'import pandas as pd\n'), ((25261, 25288), 'supervised.preprocessing.goldenfeatures_transformer.GoldenFeaturesTransformer', 'GoldenFeaturesTransformer', ([], {}), '()\n', (25286, 25288), False, 'from supervised.preprocessing.goldenfeatures_transformer import GoldenFeaturesTransformer\n'), ((25439, 25458), 'supervised.preprocessing.kmeans_transformer.KMeansTransformer', 'KMeansTransformer', ([], {}), '()\n', (25456, 25458), False, 'from supervised.preprocessing.kmeans_transformer import KMeansTransformer\n'), ((26109, 26116), 'supervised.preprocessing.scale.Scale', 'Scale', ([], {}), '()\n', (26114, 26116), False, 'from supervised.preprocessing.scale import Scale\n'), ((2538, 2557), 'numpy.array', 'np.array', (['y_missing'], {}), '(y_missing)\n', (2546, 2557), True, 'import numpy as np\n'), ((3602, 3639), 'supervised.preprocessing.label_encoder.LabelEncoder', 'LabelEncoder', ([], {'try_to_fit_numeric': '(True)'}), '(try_to_fit_numeric=True)\n', (3614, 3639), False, 'from supervised.preprocessing.label_encoder import LabelEncoder\n'), ((3950, 3966), 'supervised.preprocessing.label_binarizer.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (3964, 3966), False, 'from supervised.preprocessing.label_binarizer import LabelBinarizer\n'), ((4345, 4403), 'supervised.preprocessing.scale.Scale', 'Scale', (["['target']"], {'scale_method': 'Scale.SCALE_LOG_AND_NORMAL'}), "(['target'], scale_method=Scale.SCALE_LOG_AND_NORMAL)\n", (4350, 4403), False, 'from supervised.preprocessing.scale import Scale\n'), ((4468, 4501), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y_train}"], {}), "({'target': y_train})\n", (4480, 4501), True, 'import pandas as pd\n'), ((4786, 4836), 'supervised.preprocessing.scale.Scale', 'Scale', (["['target']"], {'scale_method': 'Scale.SCALE_NORMAL'}), "(['target'], scale_method=Scale.SCALE_NORMAL)\n", (4791, 4836), False, 'from supervised.preprocessing.scale import Scale\n'), ((4863, 4896), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y_train}"], {}), "({'target': y_train})\n", (4875, 4896), True, 'import pandas as pd\n'), ((10651, 10673), 'supervised.preprocessing.scale.Scale', 'Scale', (['cols_to_process'], {}), '(cols_to_process)\n', (10656, 10673), False, 'from supervised.preprocessing.scale import Scale\n'), ((11195, 11274), 'supervised.exceptions.AutoMLException', 'AutoMLException', (['"""All features are droppped! Your data looks like random data."""'], {}), "('All features are droppped! Your data looks like random data.')\n", (11210, 11274), False, 'from supervised.exceptions import AutoMLException\n'), ((20696, 20711), 'pandas.DataFrame', 'pd.DataFrame', (['d'], {}), '(d)\n', (20708, 20711), True, 'import pandas as pd\n'), ((24250, 24278), 'supervised.preprocessing.preprocessing_missing.PreprocessingMissingValues', 'PreprocessingMissingValues', ([], {}), '()\n', (24276, 24278), False, 'from supervised.preprocessing.preprocessing_missing import PreprocessingMissingValues\n'), ((24512, 24538), 'supervised.preprocessing.preprocessing_categorical.PreprocessingCategorical', 'PreprocessingCategorical', ([], {}), '()\n', (24536, 24538), False, 'from supervised.preprocessing.preprocessing_categorical import PreprocessingCategorical\n'), ((24799, 24820), 'supervised.preprocessing.datetime_transformer.DateTimeTransformer', 'DateTimeTransformer', ([], {}), '()\n', (24818, 24820), False, 'from supervised.preprocessing.datetime_transformer import DateTimeTransformer\n'), ((25077, 25094), 'supervised.preprocessing.text_transformer.TextTransformer', 'TextTransformer', ([], {}), '()\n', (25092, 25094), False, 'from supervised.preprocessing.text_transformer import TextTransformer\n'), ((25663, 25670), 'supervised.preprocessing.scale.Scale', 'Scale', ([], {}), '()\n', (25668, 25670), False, 'from supervised.preprocessing.scale import Scale\n'), ((25887, 25903), 'supervised.preprocessing.label_binarizer.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (25901, 25903), False, 'from supervised.preprocessing.label_binarizer import LabelBinarizer\n'), ((25960, 25974), 'supervised.preprocessing.label_encoder.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (25972, 25974), False, 'from supervised.preprocessing.label_encoder import LabelEncoder\n'), ((4007, 4040), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y_train}"], {}), "({'target': y_train})\n", (4019, 4040), True, 'import pandas as pd\n'), ((4129, 4162), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y_train}"], {}), "({'target': y_train})\n", (4141, 4162), True, 'import pandas as pd\n'), ((10910, 10942), 'numpy.random.rand', 'np.random.rand', (['X_train.shape[0]'], {}), '(X_train.shape[0])\n', (10924, 10942), True, 'import numpy as np\n'), ((13699, 13737), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y_validation}"], {}), "({'target': y_validation})\n", (13711, 13737), True, 'import pandas as pd\n'), ((14095, 14133), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y_validation}"], {}), "({'target': y_validation})\n", (14107, 14133), True, 'import pandas as pd\n'), ((16795, 16832), 'numpy.random.rand', 'np.random.rand', (['X_validation.shape[0]'], {}), '(X_validation.shape[0])\n', (16809, 16832), True, 'import numpy as np\n'), ((20752, 20770), 'numpy.array', 'np.array', (['df[cols]'], {}), '(df[cols])\n', (20760, 20770), True, 'import numpy as np\n'), ((21045, 21101), 'pandas.DataFrame', 'pd.DataFrame', (["{'prediction_0': 1 - y, 'prediction_1': y}"], {}), "({'prediction_0': 1 - y, 'prediction_1': y})\n", (21057, 21101), True, 'import pandas as pd\n'), ((13386, 13424), 'pandas.DataFrame', 'pd.DataFrame', (["{'target': y_validation}"], {}), "({'target': y_validation})\n", (13398, 13424), True, 'import pandas as pd\n'), ((15096, 15119), 'pandas.isnull', 'pd.isnull', (['X_validation'], {}), '(X_validation)\n', (15105, 15119), True, 'import pandas as pd\n'), ((11731, 11751), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (11739, 11751), True, 'import numpy as np\n'), ((11786, 11806), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (11794, 11806), True, 'import numpy as np\n'), ((17300, 17320), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (17308, 17320), True, 'import numpy as np\n'), ((17355, 17375), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (17363, 17375), True, 'import numpy as np\n')]
|
#!/usr/bin/env ipython
# author: <NAME>
# chunk the merged file and also build the chunkfile
import numpy as np
import pandas as pd
import ipdb
import mimic_paths
n_splits = 50
def build_chunk_file(version='180817'):
base_merged_dir = mimic_paths.merged_dir + version + '/reduced/'
df = pd.read_hdf(base_merged_dir + 'merged_clean.h5', columns=['PatientID'])
pids = sorted(df['PatientID'].unique())
chunks = np.array_split(pids, n_splits)
chunkfile = open(mimic_paths.chunks_file + '.' + version, 'w')
chunkfile.write('PatientID,ChunkfileIndex\n')
for chunk_idx, chunk in enumerate(chunks):
for pid in chunk:
chunkfile.write(str(int(pid)) + ',' + str(chunk_idx) + '\n')
chunkfile.close()
return True
def chunk_up_merged_file(version='180817'):
"""
assumes the chunkfile already exists
"""
base_merged_dir = mimic_paths.merged_dir + version + '/reduced/'
df = pd.read_hdf(base_merged_dir + '/merged_clean.h5')
chunks = pd.read_csv(mimic_paths.chunks_file + '.' + version)
for chunk_idx in chunks['ChunkfileIndex'].unique():
pids = set(chunks.loc[chunks['ChunkfileIndex'] == chunk_idx, 'PatientID'])
idx_start = min(pids)
idx_stop = max(pids)
chunk_name = 'reduced_fmat_' + str(chunk_idx) + '_' + str(idx_start) + '--' + str(idx_stop) + '.h5'
chunk_df = df.loc[df['PatientID'].isin(pids), :]
print(chunk_name, ';', chunk_df.shape)
chunk_df.to_hdf(base_merged_dir + chunk_name, key='merged_clean', append=False, complevel=5, complib='blosc:lz4', data_columns=['PatientID'], format='table')
|
[
"numpy.array_split",
"pandas.read_csv",
"pandas.read_hdf"
] |
[((299, 370), 'pandas.read_hdf', 'pd.read_hdf', (["(base_merged_dir + 'merged_clean.h5')"], {'columns': "['PatientID']"}), "(base_merged_dir + 'merged_clean.h5', columns=['PatientID'])\n", (310, 370), True, 'import pandas as pd\n'), ((428, 458), 'numpy.array_split', 'np.array_split', (['pids', 'n_splits'], {}), '(pids, n_splits)\n', (442, 458), True, 'import numpy as np\n'), ((944, 993), 'pandas.read_hdf', 'pd.read_hdf', (["(base_merged_dir + '/merged_clean.h5')"], {}), "(base_merged_dir + '/merged_clean.h5')\n", (955, 993), True, 'import pandas as pd\n'), ((1007, 1059), 'pandas.read_csv', 'pd.read_csv', (["(mimic_paths.chunks_file + '.' + version)"], {}), "(mimic_paths.chunks_file + '.' + version)\n", (1018, 1059), True, 'import pandas as pd\n')]
|
import matplotlib.pyplot as plt
import numpy as np
def draw_text(ax, x, y):
max_y = np.max(y)
for i, v in enumerate(y):
text = str(y[i])
ax.text(x[i] - 0.045 * len(text), y[i],
r'\textbf{' + text + '}')
def draw_error_bar(ax, x, xticks, y_gpu, e_gpu, title, ylabel):
offset = 0.2
width = offset * 2
bar_gpu = ax.bar(x, y_gpu, width=width, color=(0.86, 0.27, 0.22))
ax.errorbar(x, y_gpu, yerr=e_gpu, fmt='.', color=(0.96, 0.71, 0),capsize=10)
ax.yaxis.grid(True)
ax.set_xticks(x)
ax.set_xticklabels(xticks)
ax.set_title(title)
ax.set_ylabel(ylabel)
if __name__ == '__main__':
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
fig, axs = plt.subplots(figsize=(5, 3))
x = np.array([1, 2, 3, 4, 5])
labels = [r'\textit{fr2\_desktop}', r'\textit{fr3\_household}',
r'\textit{lounge}', r'\textit{copyroom}',
r'\textit{livingroom1}']
# mean = 8.713374, std = 1.637024
y_gpu_mc = np.array([8.71, 11.63, 6.28, 5.18, 4.07])
e_gpu_mc = np.array([1.64, 3.25, 1.98, 1.94, 1.15])
draw_error_bar(axs, x, labels,
y_gpu_mc, e_gpu_mc,
r'\textbf{Marching Cubes for Voxels in Frustum}',
r'\textbf{Average time per frame} (ms)')
fig.tight_layout()
# bar_cpu_odom = plt.bar(x + offset, y_cpu_odom, width=width)
# plt.errorbar(x + offset, y_cpu_odom, yerr=e_cpu_odom, fmt='.g', capsize=20)
# for i, v in enumerate(y_cpu_odom):
# plt.text(x[i] + offset + 0.02, y_cpu_odom[i] + 5, str(y_cpu_odom[i]))
plt.savefig('mc_time.pdf', bbox_inches='tight')
plt.show()
|
[
"matplotlib.pyplot.show",
"numpy.max",
"numpy.array",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] |
[((90, 99), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (96, 99), True, 'import numpy as np\n'), ((663, 690), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (669, 690), True, 'import matplotlib.pyplot as plt\n'), ((695, 725), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""'}), "('font', family='serif')\n", (701, 725), True, 'import matplotlib.pyplot as plt\n'), ((742, 770), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 3)'}), '(figsize=(5, 3))\n', (754, 770), True, 'import matplotlib.pyplot as plt\n'), ((779, 804), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (787, 804), True, 'import numpy as np\n'), ((1018, 1059), 'numpy.array', 'np.array', (['[8.71, 11.63, 6.28, 5.18, 4.07]'], {}), '([8.71, 11.63, 6.28, 5.18, 4.07])\n', (1026, 1059), True, 'import numpy as np\n'), ((1075, 1115), 'numpy.array', 'np.array', (['[1.64, 3.25, 1.98, 1.94, 1.15]'], {}), '([1.64, 3.25, 1.98, 1.94, 1.15])\n', (1083, 1115), True, 'import numpy as np\n'), ((1618, 1665), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""mc_time.pdf"""'], {'bbox_inches': '"""tight"""'}), "('mc_time.pdf', bbox_inches='tight')\n", (1629, 1665), True, 'import matplotlib.pyplot as plt\n'), ((1670, 1680), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1678, 1680), True, 'import matplotlib.pyplot as plt\n')]
|
"""Simulate a trading bot by predicting a series of values using train/test sets."""
from model import Forecast
import numpy as np
import copy
from multiprocessing import Pool
def simulate(p=1, d=0, q=0):
"""
This bot will perform the following steps.
1. Load data, pipeline, and split it into training and test sets.
2. Train an optimized ARIMA model on the training data.
3. Make a series of point forecasts and store the predictions in a list.
Prediction requires exogenous variables, so append the next data point
to both the endogenous and exogenous variables in the Forecast object
before making the next prediction.
"""
# print("Loading data...")
f = Forecast("blockchain.csv")
# Define an index on which to split (like 80% of the way)
ixSplit = int(0.8 * f.endog.shape[0])
# Define training and test sets
train_endog = f.endog[:ixSplit]
train_exog = f.exog[:ixSplit]
test_endog = f.endog[ixSplit:]
test_exog = f.exog[ixSplit:]
# Update the instance
f.endog = train_endog
f.exog = train_exog
# Copy test exogenous variables to compare with the predictions
endog_expected = copy.deepcopy(test_endog)
# Make a series of predictions
# print("Making predictions...")
preds = list()
for i in range(len(test_exog)):
# Make the prediction
pred = f.predictARIMA_R(p, d, q, endog=f.endog, exog=f.exog)
preds.append(pred)
# Append the model's data with the first data in the test arrays
# Note that np.delete is analagous to pop, but -1 indicates the first
# item in the array.
f.exog = np.append(f.exog, [test_exog[0]], axis=0)
test_exog = np.delete(test_exog, 0, axis=0)
f.endog = np.append(f.endog, [test_endog[0]], axis=0)
test_endog = np.delete(test_endog, 0)
return preds, endog_expected
def decisionRule():
"""Decide whether to buy, sell, or hold."""
pass
def score_simulation(preds, endog_expected):
"""Score a simulation based on mean squared error."""
MSE = 0
for i in range(len(preds)):
MSE += (preds[i] - endog_expected[i]) ** 2
return MSE
def test_f(gen):
p = gen[0][0]
d = gen[0][1]
q = gen[0][2]
try:
preds, exog_expected = simulate(p, d, q)
score = score_simulation(preds, exog_expected)
except:
score = 0
return (score, p, d, q)
if __name__ == "__main__":
POOL = Pool(maxtasksperchild=500)
p_range = range(5)
d_range = range(5)
q_range = [0] * 5
gen = list()
for _p in p_range:
for _d in d_range:
gen.append((_p, _d, 0))
_gen = zip(gen)
x = POOL.map(test_f, _gen)
print("Done")
print(x)
# [(0, 0, 0, 0), (0, 0, 1, 0), (0, 0, 2, 0), (0, 0, 3, 0), (0, 0, 4, 0), (29.292981789631671, 1, 0, 0), (0, 1, 1, 0), (0, 1, 2, 0), (0, 1, 3, 0), (0, 1, 4, 0), (0, 2, 0, 0), (0, 2, 1, 0), (0, 2, 2, 0), (0, 2, 3, 0), (0, 2, 4, 0), (0, 3, 0, 0), (0, 3, 1, 0), (54.253053572867898, 3, 2, 0), (0, 3, 3, 0), (0, 3, 4, 0), (0, 4, 0, 0), (0, 4, 1, 0), (0, 4, 2, 0), (0, 4, 3, 0), (250.45917084881501, 4, 4, 0)]
|
[
"copy.deepcopy",
"model.Forecast",
"numpy.append",
"multiprocessing.Pool",
"numpy.delete"
] |
[((717, 743), 'model.Forecast', 'Forecast', (['"""blockchain.csv"""'], {}), "('blockchain.csv')\n", (725, 743), False, 'from model import Forecast\n'), ((1191, 1216), 'copy.deepcopy', 'copy.deepcopy', (['test_endog'], {}), '(test_endog)\n', (1204, 1216), False, 'import copy\n'), ((2482, 2508), 'multiprocessing.Pool', 'Pool', ([], {'maxtasksperchild': '(500)'}), '(maxtasksperchild=500)\n', (2486, 2508), False, 'from multiprocessing import Pool\n'), ((1668, 1709), 'numpy.append', 'np.append', (['f.exog', '[test_exog[0]]'], {'axis': '(0)'}), '(f.exog, [test_exog[0]], axis=0)\n', (1677, 1709), True, 'import numpy as np\n'), ((1730, 1761), 'numpy.delete', 'np.delete', (['test_exog', '(0)'], {'axis': '(0)'}), '(test_exog, 0, axis=0)\n', (1739, 1761), True, 'import numpy as np\n'), ((1780, 1823), 'numpy.append', 'np.append', (['f.endog', '[test_endog[0]]'], {'axis': '(0)'}), '(f.endog, [test_endog[0]], axis=0)\n', (1789, 1823), True, 'import numpy as np\n'), ((1845, 1869), 'numpy.delete', 'np.delete', (['test_endog', '(0)'], {}), '(test_endog, 0)\n', (1854, 1869), True, 'import numpy as np\n')]
|
import matplotlib as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
plt.use('TkAgg')
#Adapted for python3 and contec data graphing from
# https://stackoverflow.com/questions/43114508/can-a-pyqt-embedded-matplotlib-graph-be-interactive
import tkinter as tk
from tkinter import ttk
class My_GUI:
def __init__(self,master):
self.master=master
master.title("Data from Contex")
data = np.loadtxt("contec_data.csv", skiprows = 1, delimiter=',')
time, spo2, pulse = data[:,0], data[:,2], data[:,3]
minutes = time/60.
f = Figure(figsize=(8,5), dpi=100)
ax1 = f.add_subplot(111)
# plot the spO2 values in red
color = 'tab:red'
ax1.set_xlabel('time (minutes)')
ax1.set_ylabel('spO2', color=color)
ax1.plot(minutes,spo2,label='spO2',color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax1.set_ylim(85,100)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
# plot the heart rate values in blue
color = 'tab:blue'
ax2.set_ylabel('Pulse', color=color) # we already handled the x-label with ax1
ax2.plot(minutes, pulse, color=color, label = 'pulse', picker=False)
ax2.tick_params(axis='y', labelcolor=color, color=color)
ax2.set_xlabel('Time (sec)')
ax2.set_ylim(30,120)
canvas1=FigureCanvasTkAgg(f,master)
canvas1.draw()
canvas1.get_tk_widget().pack(side="top",fill='x',expand=True)
f.canvas.mpl_connect('pick_event',self.onpick)
toolbar=NavigationToolbar2Tk(canvas1,master)
toolbar.update()
toolbar.pack(side='top',fill='x')
# Set "picker=True" in call to plot() to enable pick events
def onpick(self,event):
#do stuff
print("My OnPick Event Worked!")
return True
root=tk.Tk()
gui=My_GUI(root)
root.mainloop()
|
[
"matplotlib.backends.backend_tkagg.NavigationToolbar2Tk",
"matplotlib.figure.Figure",
"matplotlib.use",
"numpy.loadtxt",
"tkinter.Tk",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
] |
[((168, 184), 'matplotlib.use', 'plt.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (175, 184), True, 'import matplotlib as plt\n'), ((1973, 1980), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (1978, 1980), True, 'import tkinter as tk\n'), ((514, 570), 'numpy.loadtxt', 'np.loadtxt', (['"""contec_data.csv"""'], {'skiprows': '(1)', 'delimiter': '""","""'}), "('contec_data.csv', skiprows=1, delimiter=',')\n", (524, 570), True, 'import numpy as np\n'), ((672, 703), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(8, 5)', 'dpi': '(100)'}), '(figsize=(8, 5), dpi=100)\n', (678, 703), False, 'from matplotlib.figure import Figure\n'), ((1494, 1522), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['f', 'master'], {}), '(f, master)\n', (1511, 1522), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((1687, 1724), 'matplotlib.backends.backend_tkagg.NavigationToolbar2Tk', 'NavigationToolbar2Tk', (['canvas1', 'master'], {}), '(canvas1, master)\n', (1707, 1724), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n')]
|
"""Class to create batches from a configuration"""
import logging
import math
import random
import numpy as np
from .Batch import Batch
from ..config.ExperimentConfig import ExperimentConfig
from ..constants import DATA_OUT_INDEX, DATA_TYPE_TEST, DATA_TYPE_DEV
from ..constants import DATA_TYPE_TRAIN
class Batches(object):
def __init__(self, config, data_type=DATA_TYPE_TRAIN, no_mini_batches=False):
"""
Initialize the batches by loading the training data from the configuration file.
Populates the `_batches` property with a dict that matches each task to batches.
Each item in a batch is a tuple of list of labels, list of tokens, and list of sample objects.
Args:
config (ExperimentConfig): Configuration object
data_type (str): type of data (train, dev or test)
no_mini_batches (bool): whether to use mini batches or not, i.e. whether to use the batch_size specified
in the configuration file or just build one batch for each sequence length
"""
assert isinstance(config, ExperimentConfig)
assert data_type in [DATA_TYPE_TRAIN, DATA_TYPE_DEV, DATA_TYPE_TEST]
logger = logging.getLogger("shared.Batches.__init__")
self._batches = {}
logger.debug("Building batches for %d tasks", len(config.tasks))
for task in config.tasks:
logger.debug("Task: %s", task.name)
data = task.data_reader.get_data(data_type, DATA_OUT_INDEX, word2idx=config.word2idx)
# Sort by sentence length
data.sort(key=lambda sample: sample.len)
train_ranges = []
old_sent_length = data[0].len
idx_start = 0
# Find start and end of ranges with sentences with same length
for idx in range(len(data)):
sent_length = data[idx].len
if sent_length != old_sent_length:
train_ranges.append((idx_start, idx))
idx_start = idx
old_sent_length = sent_length
# Add last sentence
train_ranges.append((idx_start, len(data)))
logger.debug("%d different sentence lengths", len(train_ranges))
# Break up ranges into smaller mini batch sizes
mini_batch_ranges = []
if no_mini_batches:
logger.debug("`no_mini_batches == True` --> not building any mini batches")
for batch_range in train_ranges:
range_len = batch_range[1] - batch_range[0]
if no_mini_batches:
bins = 1
else:
bins = int(math.ceil(range_len / float(config.batch_size)))
bin_size = int(math.ceil(range_len / float(bins)))
for binNr in range(bins):
start_idx = binNr * bin_size + batch_range[0]
end_idx = min(batch_range[1], (binNr + 1) * bin_size + batch_range[0])
mini_batch_ranges.append((start_idx, end_idx))
logger.debug("%d batches", len(mini_batch_ranges))
self._batches[task.name] = []
# Shuffle training data
# 1. Shuffle sentences that have the same length
for data_range in train_ranges:
for i in reversed(range(data_range[0] + 1, data_range[1])):
# pick an element in x[:i+1] with which to exchange x[i]
j = random.randint(data_range[0], i)
data[i], data[j] = data[j], data[i]
# 2. Shuffle the order of the mini batch ranges
random.shuffle(mini_batch_ranges)
for rng in mini_batch_ranges:
start, end = rng
rng_samples = data[start:end]
labels = np.asarray([sample.labels_as_array for sample in rng_samples])
tokens = np.asarray([sample.tokens_as_array for sample in rng_samples])
characters = None
if config.character_level_information:
max_token_length = max([sample.get_max_token_length() for sample in rng_samples])
characters = np.asarray([
sample.get_tokens_as_char_ids(config.char2idx, max_token_length)
for sample in rng_samples
])
self._batches[task.name].append(Batch(labels, tokens, rng_samples, characters))
def iterate_tasks(self):
"""
Iterate over all batches by task, i.e. first use all batches for one task, then for the next and so on.
Returns:
generator: A generator for batches. The generator always returns a tuple consisting of the task name and
the batch.
"""
return ((task, batch) for task, batches in self._batches.items() for batch in batches)
def find_min_num_batches(self):
"""
Find the minimum number of batches across all tasks.
This number is the number of batches for the iterate_batches method.
Returns:
int: minimum number of batches
"""
logger = logging.getLogger("shared.Batches.find_min_num_batches")
# min([len(batches) for batches in self._batches.values()])
min_num_batches = float("inf")
for task_name, batches in self._batches.items():
num_batches = len(batches)
if num_batches < min_num_batches:
min_num_batches = num_batches
logger.debug("Task %s has %d batches.", task_name, num_batches)
logger.debug("Choosing the minimum for this iteration. Minimum: %d", min_num_batches)
return min_num_batches
def iterate_batches(self):
"""
Iterate over all batches and alternate between tasks, i.e. use a batch of one task, then one of the next, and so
on.
Returns:
generator: A generator for batches. The generator always returns a tuple consisting of the task name and
the batch.
"""
min_num_batches = self.find_min_num_batches()
for idx in range(min_num_batches):
for task in self._batches.keys():
yield task, self._batches[task][idx]
def find_total_num_batches(self):
"""
Find the total number of batches across all tasks.
Returns:
int: total number of batches
"""
return sum([len(batches) for batches in self._batches.values()])
def iterate_batches_randomly(self):
"""
Iterate over all batches and choose a batch from a task at random each time.
Returns:
generator: A generator for batches. The generator always returns a tuple consisting of the task name and
the batch.
"""
logger = logging.getLogger("shared.Batches.iterate_batches_randomly")
tasks = list(self._batches.keys())
num_tasks = len(tasks)
task_indices = {task: 0 for task in tasks}
task_num_batches = {task: len(self._batches[task]) for task in tasks}
num_batches_total = self.find_total_num_batches()
logger.debug("Iterating randomly over batches for %d tasks.", num_tasks)
logger.debug("There are %d batches in total.", num_batches_total)
for task, num_batches in task_num_batches.items():
logger.debug("Task %s has %d batches.", task, num_batches)
def find_task_with_remaining_batches():
task = tasks[np.random.randint(0, num_tasks)]
t_idx = task_indices[task]
t_num_batches = task_num_batches[task]
if t_idx < t_num_batches:
return task
else:
return find_task_with_remaining_batches()
for idx in range(num_batches_total):
current_task = find_task_with_remaining_batches()
logger.debug(
"Current task %s; task index: %d; task batches: %d",
current_task,
task_indices[current_task],
task_num_batches[current_task],
)
yield current_task, self._batches[current_task][task_indices[current_task]]
task_indices[current_task] += 1
|
[
"random.randint",
"random.shuffle",
"numpy.asarray",
"numpy.random.randint",
"logging.getLogger"
] |
[((1208, 1252), 'logging.getLogger', 'logging.getLogger', (['"""shared.Batches.__init__"""'], {}), "('shared.Batches.__init__')\n", (1225, 1252), False, 'import logging\n'), ((5188, 5244), 'logging.getLogger', 'logging.getLogger', (['"""shared.Batches.find_min_num_batches"""'], {}), "('shared.Batches.find_min_num_batches')\n", (5205, 5244), False, 'import logging\n'), ((6876, 6936), 'logging.getLogger', 'logging.getLogger', (['"""shared.Batches.iterate_batches_randomly"""'], {}), "('shared.Batches.iterate_batches_randomly')\n", (6893, 6936), False, 'import logging\n'), ((3660, 3693), 'random.shuffle', 'random.shuffle', (['mini_batch_ranges'], {}), '(mini_batch_ranges)\n', (3674, 3693), False, 'import random\n'), ((3841, 3903), 'numpy.asarray', 'np.asarray', (['[sample.labels_as_array for sample in rng_samples]'], {}), '([sample.labels_as_array for sample in rng_samples])\n', (3851, 3903), True, 'import numpy as np\n'), ((3929, 3991), 'numpy.asarray', 'np.asarray', (['[sample.tokens_as_array for sample in rng_samples]'], {}), '([sample.tokens_as_array for sample in rng_samples])\n', (3939, 3991), True, 'import numpy as np\n'), ((7561, 7592), 'numpy.random.randint', 'np.random.randint', (['(0)', 'num_tasks'], {}), '(0, num_tasks)\n', (7578, 7592), True, 'import numpy as np\n'), ((3498, 3530), 'random.randint', 'random.randint', (['data_range[0]', 'i'], {}), '(data_range[0], i)\n', (3512, 3530), False, 'import random\n')]
|
import cv2
import numpy as np
import pyrealsense2 as rs
import pandas as pd
import os
from cubemos.skeletontracking.core_wrapper import CM_TargetComputeDevice
from cubemos.skeletontracking.native_wrapper import Api
import math
joints = ['Nose','Neck','Right_shoulder','Right_elbow','Right_wrist','Left_shoulder',
'Left_elbow','Left_wrist','Right_hip','Right_knee','Right_ankle','Left_hip',
'Left_knee','Left_ankle','Right_eye','Left_eye','Right_ear','Left_ear']
def default_license_dir():
return os.path.join(os.environ["HOME"], ".cubemos", "skeleton_tracking", "license")
count = 0
api = Api(default_license_dir())
sdk_path = os.environ["CUBEMOS_SKEL_SDK"]
model_path = os.path.join(sdk_path, "models", "skeleton-tracking", "fp32", "skeleton-tracking.cubemos")
api.load_model(CM_TargetComputeDevice.CM_CPU, model_path)
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.color, 848, 480, rs.format.bgr8, 30)
config.enable_stream(rs.stream.depth, 848, 480, rs.format.z16, 30)
profile = pipeline.start(config)
depth_scale = profile.get_device().first_depth_sensor().get_depth_scale()
for x in range(5):
pipeline.wait_for_frames()
spatial = rs.spatial_filter()
spatial.set_option(rs.option.filter_magnitude, 5)
spatial.set_option(rs.option.filter_smooth_alpha, 1)
spatial.set_option(rs.option.filter_smooth_delta, 50)
hole_filling = rs.hole_filling_filter()
decimation = rs.decimation_filter()
decimation.set_option(rs.option.filter_magnitude, 3)
global df
df = pd.DataFrame(columns = ['Nose:X','Nose:Y','Nose:Z','Nose:TrueDistance',
'Neck:X','Neck:Y','Neck:Z','Neck:TrueDistance',
'Right_shoulder:X','Right_shoulder:Y','Right_shoulder:Z','Right_shoulder:TrueDistance',
'Right_elbow:X','Right_elbow:Y','Right_elbow:Z','Right_elbow:TrueDistance',
'Right_wrist:X','Right_wrist:Y','Right_wrist:Z','Right_wrist:TrueDistance',
'Left_shoulder:X','Left_shoulder:Y','Left_shoulder:Z','Left_shoulder:TrueDistance',
'Left_elbow:X','Left_elbow:Y','Left_elbow:Z','Left_elbow:TrueDistance',
'Left_wrist:X','Left_wrist:Y','Left_wrist:Z','Left_wrist:TrueDistance',
'Right_hip:X','Right_hip:Y','Right_hip:Z','Right_hip:TrueDistance',
'Right_knee:X','Right_knee:Y','Right_knee:Z','Right_knee:TrueDistance',
'Right_ankle:X','Right_ankle:Y','Right_ankle:Z','Right_ankle:TrueDistance',
'Left_hip:X','Left_hip:Y','Left_hip:Z','Left_hip:TrueDistance',
'Left_knee:X','Left_knee:Y','Left_knee:Z','Left_knee:TrueDistance',
'Left_ankle:X','Left_ankle:Y','Left_ankle:Z','Left_ankle:TrueDistance'])
df = df.append({'Nose:X':0,'Nose:Y':0,'Nose:Z':0,'Nose:TrueDistance':0,
'Neck:X':0,'Neck:Y':0,'Neck:Z':0,'Neck:TrueDistance':0,
'Right_shoulder:X':0,'Right_shoulder:Y':0,'Right_shoulder:Z':0,'Right_shoulder:TrueDistance':0,
'Right_elbow:X':0,'Right_elbow:Y':0,'Right_elbow:Z':0,'Right_elbow:TrueDistance':0,
'Right_wrist:X':0,'Right_wrist:Y':0,'Right_wrist:Z':0,'Right_wrist:TrueDistance':0,
'Left_shoulder:X':0,'Left_shoulder:Y':0,'Left_shoulder:Z':0,'Left_shoulder:TrueDistance':0,
'Left_elbow:X':0,'Left_elbow:Y':0,'Left_elbow:Z':0,'Left_elbow:TrueDistance':0,
'Left_wrist:X':0,'Left_wrist:Y':0,'Left_wrist:Z':0,'Left_wrist:TrueDistance':0,
'Right_hip:X':0,'Right_hip:Y':0,'Right_hip:Z':0,'Right_hip:TrueDistance':0,
'Right_knee:X':0,'Right_knee:Y':0,'Right_knee:Z':0,'Right_knee:TrueDistance':0,
'Right_ankle:X':0,'Right_ankle:Y':0,'Right_ankle:Z':0,'Right_ankle:TrueDistance':0,
'Left_hip:X':0,'Left_hip:Y':0,'Left_hip:Z':0,'Left_hip:TrueDistance':0,
'Left_knee:X':0,'Left_knee:Y':0,'Left_knee:Z':0,'Left_knee:TrueDistance':0,
'Left_ankle:X':0,'Left_ankle:Y':0,'Left_ankle:Z':0,'Left_ankle:TrueDistance':0}, ignore_index=True)
"""
def detectRect(img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,2)
contours,_ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.imshow('Rectangle',thresh)
for contour in contours:
if(cv2.contourArea(contour)>700):
approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
if(len(approx)==4):
x,y,w,h = cv2.boundingRect(approx)
img = cv2.rectangle(img, (x, y), (x + w, y + h), (36,255,12), 1)
#cv2.imshow('Rectangle', img)
"""
def get_valid_coordinates(skeleton, depth, confidence_threshold):
result_coordinate = {}
result_distance = {}
for i in range (len(skeleton.joints)):
if skeleton.confidences[i] >= confidence_threshold:
if skeleton.joints[i][0] >= 0 and skeleton.joints[i][1] >= 0:
result_coordinate[joints[i]] = tuple(map(int, skeleton.joints[i]))
dist,_,_,_ = cv2.mean((depth[result_coordinate[joints[i]][1]-3:result_coordinate[joints[i]][1]+3,result_coordinate[joints[i]][0]-3:result_coordinate[joints[i]][0]+3].astype(float))*depth_scale)
result_distance[joints[i]] = dist
return result_coordinate,result_distance
def convert_depth_to_phys_coord_using_realsense(intrin,x, y, depth):
#print("x={},y={}".format(x,y))
result = rs.rs2_deproject_pixel_to_point(intrin, [x, y], depth)
#result[0]: right (x), result[1]: down (y), result[2]: forward (z) from camera POV
return result[0], result[1], result[2]
def render_result(skeletons, color_img, depth_img, intr, confidence_threshold):
global df
#depth_frame.__class__ = rs.pyrealsense2.depth_frame
white = np.zeros([640,800,3],dtype=np.uint8)
white.fill(255)
skeleton_color = (0, 140, 255)
#print(f"#Skeletons in frame : {len(skeletons)}")
if len(skeletons) == 1:
for index, skeleton in enumerate(skeletons):
x1,y1,z1,true_dist1 = None,None,None,None
x2,y2,z2,true_dist2 = None,None,None,None
x3,y3,z3,true_dist3 = None,None,None,None
x4,y4,z4,true_dist4 = None,None,None,None
x5,y5,z5,true_dist5 = None,None,None,None
x6,y6,z6,true_dist6 = None,None,None,None
x7,y7,z7,true_dist7 = None,None,None,None
x8,y8,z8,true_dist8 = None,None,None,None
x9,y9,z9,true_dist9 = None,None,None,None
x10,y10,z10,true_dist10 = None,None,None,None
x11,y11,z11,true_dist11 = None,None,None,None
x12,y12,z12,true_dist12 = None,None,None,None
x13,y13,z13,true_dist13 = None,None,None,None
x14,y14,z14,true_dist14 = None,None,None,None
joint_locations,joint_distances = get_valid_coordinates(skeleton, depth_img, confidence_threshold)
for joint,coordinate in joint_locations.items():
if joint == 'Right_ear' or joint == 'Left_ear' or joint == 'Right_eye' or joint == 'Left_eye':
continue
elif(joint == 'Neck'):
cv2.circle(color_img, coordinate, radius=5, color=skeleton_color, thickness=-1)
x1,y1,z1 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist1 = math.sqrt((x1**2)+(y1**2)+(z1**2))
cv2.putText(white,"xyz = {0:.4},{1:.4},{2:.4}".format(x1,y1,z1),(20,30), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,255,0),2,cv2.LINE_AA)
cv2.putText(white,"trueDist = {0:.4}".format(true_dist1),(20,120), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,255,154),2,cv2.LINE_AA)
cv2.putText(white,"Difference = {0:.5}".format((true_dist1-z1)),(20,230), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,255,154),2,cv2.LINE_AA)
elif(joint == 'Nose'):
x2,y2,z2 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist2 = math.sqrt((x2**2)+(y2**2)+(z2**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Right_shoulder'):
x3,y3,z3 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist3 = math.sqrt((x3**2)+(y3**2)+(z3**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Right_elbow'):
x4,y4,z4 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist4 = math.sqrt((x4**2)+(y4**2)+(z4**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Right_wrist'):
x5,y5,z5 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist5 = math.sqrt((x5**2)+(y5**2)+(z5**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Left_shoulder'):
x6,y6,z6 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist6 = math.sqrt((x6**2)+(y6**2)+(z6**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Left_elbow'):
x7,y7,z7 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist7 = math.sqrt((x7**2)+(y7**2)+(z7**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Left_wrist'):
x8,y8,z8 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist8 = math.sqrt((x8**2)+(y8**2)+(z8**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Right_hip'):
x9,y9,z9 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist9 = math.sqrt((x9**2)+(y9**2)+(z9**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Right_knee'):
x10,y10,z10 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist10 = math.sqrt((x10**2)+(y10**2)+(z10**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Right_ankle'):
x11,y11,z11 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist11 = math.sqrt((x11**2)+(y11**2)+(z11**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Left_hip'):
x12,y12,z12 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist12 = math.sqrt((x12**2)+(y12**2)+(z12**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Left_knee'):
x13,y13,z13 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist13 = math.sqrt((x13**2)+(y13**2)+(z13**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
elif(joint == 'Left_ankle'):
x14,y14,z14 = convert_depth_to_phys_coord_using_realsense(intr, coordinate[0], coordinate[1], joint_distances[joint])
true_dist14 = math.sqrt((x14**2)+(y14**2)+(z14**2))
cv2.circle(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)
df = df.append({'Nose:X':x1,'Nose:Y':y1,'Nose:Z':z1,'Nose:TrueDistance':true_dist1,
'Neck:X':x2,'Neck:Y':y2,'Neck:Z':z2,'Neck:TrueDistance':true_dist2,
'Right_shoulder:X':x3,'Right_shoulder:Y':y3,'Right_shoulder:Z':z3,'Right_shoulder:TrueDistance':true_dist3,
'Right_elbow:X':x4,'Right_elbow:Y':y4,'Right_elbow:Z':z4,'Right_elbow:TrueDistance':true_dist4,
'Right_wrist:X':x5,'Right_wrist:Y':y5,'Right_wrist:Z':z5,'Right_wrist:TrueDistance':true_dist5,
'Left_shoulder:X':x6,'Left_shoulder:Y':y6,'Left_shoulder:Z':z6,'Left_shoulder:TrueDistance':true_dist6,
'Left_elbow:X':x7,'Left_elbow:Y':y7,'Left_elbow:Z':z7,'Left_elbow:TrueDistance':true_dist7,
'Left_wrist:X':x8,'Left_wrist:Y':y8,'Left_wrist:Z':z8,'Left_wrist:TrueDistance':true_dist8,
'Right_hip:X':x9,'Right_hip:Y':y9,'Right_hip:Z':z9,'Right_hip:TrueDistance':true_dist9,
'Right_knee:X':x10,'Right_knee:Y':y10,'Right_knee:Z':z10,'Right_knee:TrueDistance':true_dist10,
'Right_ankle:X':x11,'Right_ankle:Y':y11,'Right_ankle:Z':z11,'Right_ankle:TrueDistance':true_dist11,
'Left_hip:X':x12,'Left_hip:Y':y12,'Left_hip:Z':z12,'Left_hip:TrueDistance':true_dist12,
'Left_knee:X':x13,'Left_knee:Y':y13,'Left_knee:Z':z13,'Left_knee:TrueDistance':true_dist13,
'Left_ankle:X':x14,'Left_ankle:Y':y14,'Left_ankle:Z':z14,'Left_ankle:TrueDistance':true_dist14}, ignore_index=True)
#print(message)
cv2.imshow('Skeleton', color_img)
cv2.imshow('Output',white)
#out.write(color_img)
else:
cv2.imshow('Skeleton', color_img)
cv2.imshow('Output',white)
#out.write(color_img)
while True:
count = count+1
frame = pipeline.wait_for_frames()
align = rs.align(rs.stream.color)
aligned_frame = align.process(frame)
depth_frame = aligned_frame.get_depth_frame()
color_frame = aligned_frame.get_color_frame()
spatial_depth = spatial.process(depth_frame)
#decimated_depth = decimation.process(depth_frame)
prof = spatial_depth.get_profile()
video_prof = prof.as_video_stream_profile()
intrinsics = video_prof.get_intrinsics()
#filled_depth = hole_filling.process(filtered_depth)
#depth_image = np.asanyarray(depth_frame.get_data())
depth_image_spatial = np.asanyarray(spatial_depth.get_data())
#depth_image_decimated = np.asanyarray(decimated_depth.get_data())
color_image = np.asanyarray(color_frame.get_data())
#color_image = cv2.resize(color_image, (int(color_image.shape[1]/3), int(color_image.shape[0]/3)), interpolation = cv2.INTER_CUBIC)
skeletons = api.estimate_keypoints(color_image, 256)
#render_result(skeletons, color_image, depth_image, intrinsics, 0.6)
render_result(skeletons, color_image,depth_image_spatial, intrinsics, 0.6)
#detectRect(color_image)
cv2.namedWindow('Skeleton', cv2.WINDOW_AUTOSIZE)
cv2.namedWindow('Output', cv2.WINDOW_AUTOSIZE)
key = cv2.waitKey(1)
# Press esc or 'q' to close the image window
if key & 0xFF == ord('q') or key == 27:
cv2.destroyWindow('Skeleton')
break
pipeline.stop()
df = df.tail(-1)
df.to_csv ('/home/kathir/Desktop/Data/spatial_glare.csv', index = False, header=True)
os.system('cls||clear')
print(count)
|
[
"pandas.DataFrame",
"pyrealsense2.decimation_filter",
"cv2.circle",
"math.sqrt",
"pyrealsense2.pipeline",
"cv2.waitKey",
"pyrealsense2.spatial_filter",
"numpy.zeros",
"os.system",
"pyrealsense2.align",
"pyrealsense2.config",
"pyrealsense2.rs2_deproject_pixel_to_point",
"pyrealsense2.hole_filling_filter",
"cv2.destroyWindow",
"cv2.imshow",
"os.path.join",
"cv2.namedWindow"
] |
[((695, 789), 'os.path.join', 'os.path.join', (['sdk_path', '"""models"""', '"""skeleton-tracking"""', '"""fp32"""', '"""skeleton-tracking.cubemos"""'], {}), "(sdk_path, 'models', 'skeleton-tracking', 'fp32',\n 'skeleton-tracking.cubemos')\n", (707, 789), False, 'import os\n'), ((856, 869), 'pyrealsense2.pipeline', 'rs.pipeline', ([], {}), '()\n', (867, 869), True, 'import pyrealsense2 as rs\n'), ((879, 890), 'pyrealsense2.config', 'rs.config', ([], {}), '()\n', (888, 890), True, 'import pyrealsense2 as rs\n'), ((1194, 1213), 'pyrealsense2.spatial_filter', 'rs.spatial_filter', ([], {}), '()\n', (1211, 1213), True, 'import pyrealsense2 as rs\n'), ((1386, 1410), 'pyrealsense2.hole_filling_filter', 'rs.hole_filling_filter', ([], {}), '()\n', (1408, 1410), True, 'import pyrealsense2 as rs\n'), ((1425, 1447), 'pyrealsense2.decimation_filter', 'rs.decimation_filter', ([], {}), '()\n', (1445, 1447), True, 'import pyrealsense2 as rs\n'), ((1516, 2624), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Nose:X', 'Nose:Y', 'Nose:Z', 'Nose:TrueDistance', 'Neck:X', 'Neck:Y',\n 'Neck:Z', 'Neck:TrueDistance', 'Right_shoulder:X', 'Right_shoulder:Y',\n 'Right_shoulder:Z', 'Right_shoulder:TrueDistance', 'Right_elbow:X',\n 'Right_elbow:Y', 'Right_elbow:Z', 'Right_elbow:TrueDistance',\n 'Right_wrist:X', 'Right_wrist:Y', 'Right_wrist:Z',\n 'Right_wrist:TrueDistance', 'Left_shoulder:X', 'Left_shoulder:Y',\n 'Left_shoulder:Z', 'Left_shoulder:TrueDistance', 'Left_elbow:X',\n 'Left_elbow:Y', 'Left_elbow:Z', 'Left_elbow:TrueDistance',\n 'Left_wrist:X', 'Left_wrist:Y', 'Left_wrist:Z',\n 'Left_wrist:TrueDistance', 'Right_hip:X', 'Right_hip:Y', 'Right_hip:Z',\n 'Right_hip:TrueDistance', 'Right_knee:X', 'Right_knee:Y',\n 'Right_knee:Z', 'Right_knee:TrueDistance', 'Right_ankle:X',\n 'Right_ankle:Y', 'Right_ankle:Z', 'Right_ankle:TrueDistance',\n 'Left_hip:X', 'Left_hip:Y', 'Left_hip:Z', 'Left_hip:TrueDistance',\n 'Left_knee:X', 'Left_knee:Y', 'Left_knee:Z', 'Left_knee:TrueDistance',\n 'Left_ankle:X', 'Left_ankle:Y', 'Left_ankle:Z', 'Left_ankle:TrueDistance']"}), "(columns=['Nose:X', 'Nose:Y', 'Nose:Z', 'Nose:TrueDistance',\n 'Neck:X', 'Neck:Y', 'Neck:Z', 'Neck:TrueDistance', 'Right_shoulder:X',\n 'Right_shoulder:Y', 'Right_shoulder:Z', 'Right_shoulder:TrueDistance',\n 'Right_elbow:X', 'Right_elbow:Y', 'Right_elbow:Z',\n 'Right_elbow:TrueDistance', 'Right_wrist:X', 'Right_wrist:Y',\n 'Right_wrist:Z', 'Right_wrist:TrueDistance', 'Left_shoulder:X',\n 'Left_shoulder:Y', 'Left_shoulder:Z', 'Left_shoulder:TrueDistance',\n 'Left_elbow:X', 'Left_elbow:Y', 'Left_elbow:Z',\n 'Left_elbow:TrueDistance', 'Left_wrist:X', 'Left_wrist:Y',\n 'Left_wrist:Z', 'Left_wrist:TrueDistance', 'Right_hip:X', 'Right_hip:Y',\n 'Right_hip:Z', 'Right_hip:TrueDistance', 'Right_knee:X', 'Right_knee:Y',\n 'Right_knee:Z', 'Right_knee:TrueDistance', 'Right_ankle:X',\n 'Right_ankle:Y', 'Right_ankle:Z', 'Right_ankle:TrueDistance',\n 'Left_hip:X', 'Left_hip:Y', 'Left_hip:Z', 'Left_hip:TrueDistance',\n 'Left_knee:X', 'Left_knee:Y', 'Left_knee:Z', 'Left_knee:TrueDistance',\n 'Left_ankle:X', 'Left_ankle:Y', 'Left_ankle:Z', 'Left_ankle:TrueDistance'])\n", (1528, 2624), True, 'import pandas as pd\n'), ((16095, 16118), 'os.system', 'os.system', (['"""cls||clear"""'], {}), "('cls||clear')\n", (16104, 16118), False, 'import os\n'), ((518, 594), 'os.path.join', 'os.path.join', (["os.environ['HOME']", '""".cubemos"""', '"""skeleton_tracking"""', '"""license"""'], {}), "(os.environ['HOME'], '.cubemos', 'skeleton_tracking', 'license')\n", (530, 594), False, 'import os\n'), ((5701, 5755), 'pyrealsense2.rs2_deproject_pixel_to_point', 'rs.rs2_deproject_pixel_to_point', (['intrin', '[x, y]', 'depth'], {}), '(intrin, [x, y], depth)\n', (5732, 5755), True, 'import pyrealsense2 as rs\n'), ((6052, 6091), 'numpy.zeros', 'np.zeros', (['[640, 800, 3]'], {'dtype': 'np.uint8'}), '([640, 800, 3], dtype=np.uint8)\n', (6060, 6091), True, 'import numpy as np\n'), ((14616, 14641), 'pyrealsense2.align', 'rs.align', (['rs.stream.color'], {}), '(rs.stream.color)\n', (14624, 14641), True, 'import pyrealsense2 as rs\n'), ((15706, 15754), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Skeleton"""', 'cv2.WINDOW_AUTOSIZE'], {}), "('Skeleton', cv2.WINDOW_AUTOSIZE)\n", (15721, 15754), False, 'import cv2\n'), ((15759, 15805), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Output"""', 'cv2.WINDOW_AUTOSIZE'], {}), "('Output', cv2.WINDOW_AUTOSIZE)\n", (15774, 15805), False, 'import cv2\n'), ((15816, 15830), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (15827, 15830), False, 'import cv2\n'), ((14428, 14461), 'cv2.imshow', 'cv2.imshow', (['"""Skeleton"""', 'color_img'], {}), "('Skeleton', color_img)\n", (14438, 14461), False, 'import cv2\n'), ((14472, 14499), 'cv2.imshow', 'cv2.imshow', (['"""Output"""', 'white'], {}), "('Output', white)\n", (14482, 14499), False, 'import cv2\n'), ((15932, 15961), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""Skeleton"""'], {}), "('Skeleton')\n", (15949, 15961), False, 'import cv2\n'), ((14298, 14331), 'cv2.imshow', 'cv2.imshow', (['"""Skeleton"""', 'color_img'], {}), "('Skeleton', color_img)\n", (14308, 14331), False, 'import cv2\n'), ((14348, 14375), 'cv2.imshow', 'cv2.imshow', (['"""Output"""', 'white'], {}), "('Output', white)\n", (14358, 14375), False, 'import cv2\n'), ((7426, 7505), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': 'skeleton_color', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=skeleton_color, thickness=-1)\n', (7436, 7505), False, 'import cv2\n'), ((7674, 7712), 'math.sqrt', 'math.sqrt', (['(x1 ** 2 + y1 ** 2 + z1 ** 2)'], {}), '(x1 ** 2 + y1 ** 2 + z1 ** 2)\n', (7683, 7712), False, 'import math\n'), ((8353, 8391), 'math.sqrt', 'math.sqrt', (['(x2 ** 2 + y2 ** 2 + z2 ** 2)'], {}), '(x2 ** 2 + y2 ** 2 + z2 ** 2)\n', (8362, 8391), False, 'import math\n'), ((8408, 8486), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (8418, 8486), False, 'import cv2\n'), ((8704, 8742), 'math.sqrt', 'math.sqrt', (['(x3 ** 2 + y3 ** 2 + z3 ** 2)'], {}), '(x3 ** 2 + y3 ** 2 + z3 ** 2)\n', (8713, 8742), False, 'import math\n'), ((8759, 8837), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (8769, 8837), False, 'import cv2\n'), ((9052, 9090), 'math.sqrt', 'math.sqrt', (['(x4 ** 2 + y4 ** 2 + z4 ** 2)'], {}), '(x4 ** 2 + y4 ** 2 + z4 ** 2)\n', (9061, 9090), False, 'import math\n'), ((9107, 9185), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (9117, 9185), False, 'import cv2\n'), ((9400, 9438), 'math.sqrt', 'math.sqrt', (['(x5 ** 2 + y5 ** 2 + z5 ** 2)'], {}), '(x5 ** 2 + y5 ** 2 + z5 ** 2)\n', (9409, 9438), False, 'import math\n'), ((9455, 9533), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (9465, 9533), False, 'import cv2\n'), ((9750, 9788), 'math.sqrt', 'math.sqrt', (['(x6 ** 2 + y6 ** 2 + z6 ** 2)'], {}), '(x6 ** 2 + y6 ** 2 + z6 ** 2)\n', (9759, 9788), False, 'import math\n'), ((9805, 9883), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (9815, 9883), False, 'import cv2\n'), ((10097, 10135), 'math.sqrt', 'math.sqrt', (['(x7 ** 2 + y7 ** 2 + z7 ** 2)'], {}), '(x7 ** 2 + y7 ** 2 + z7 ** 2)\n', (10106, 10135), False, 'import math\n'), ((10152, 10230), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (10162, 10230), False, 'import cv2\n'), ((10444, 10482), 'math.sqrt', 'math.sqrt', (['(x8 ** 2 + y8 ** 2 + z8 ** 2)'], {}), '(x8 ** 2 + y8 ** 2 + z8 ** 2)\n', (10453, 10482), False, 'import math\n'), ((10499, 10577), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (10509, 10577), False, 'import cv2\n'), ((10790, 10828), 'math.sqrt', 'math.sqrt', (['(x9 ** 2 + y9 ** 2 + z9 ** 2)'], {}), '(x9 ** 2 + y9 ** 2 + z9 ** 2)\n', (10799, 10828), False, 'import math\n'), ((10845, 10923), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (10855, 10923), False, 'import cv2\n'), ((11141, 11182), 'math.sqrt', 'math.sqrt', (['(x10 ** 2 + y10 ** 2 + z10 ** 2)'], {}), '(x10 ** 2 + y10 ** 2 + z10 ** 2)\n', (11150, 11182), False, 'import math\n'), ((11199, 11277), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (11209, 11277), False, 'import cv2\n'), ((11496, 11537), 'math.sqrt', 'math.sqrt', (['(x11 ** 2 + y11 ** 2 + z11 ** 2)'], {}), '(x11 ** 2 + y11 ** 2 + z11 ** 2)\n', (11505, 11537), False, 'import math\n'), ((11554, 11632), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (11564, 11632), False, 'import cv2\n'), ((11848, 11889), 'math.sqrt', 'math.sqrt', (['(x12 ** 2 + y12 ** 2 + z12 ** 2)'], {}), '(x12 ** 2 + y12 ** 2 + z12 ** 2)\n', (11857, 11889), False, 'import math\n'), ((11906, 11984), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (11916, 11984), False, 'import cv2\n'), ((12201, 12242), 'math.sqrt', 'math.sqrt', (['(x13 ** 2 + y13 ** 2 + z13 ** 2)'], {}), '(x13 ** 2 + y13 ** 2 + z13 ** 2)\n', (12210, 12242), False, 'import math\n'), ((12259, 12337), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (12269, 12337), False, 'import cv2\n'), ((12555, 12596), 'math.sqrt', 'math.sqrt', (['(x14 ** 2 + y14 ** 2 + z14 ** 2)'], {}), '(x14 ** 2 + y14 ** 2 + z14 ** 2)\n', (12564, 12596), False, 'import math\n'), ((12613, 12691), 'cv2.circle', 'cv2.circle', (['color_img', 'coordinate'], {'radius': '(5)', 'color': '(34, 240, 25)', 'thickness': '(-1)'}), '(color_img, coordinate, radius=5, color=(34, 240, 25), thickness=-1)\n', (12623, 12691), False, 'import cv2\n')]
|
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
# factor_graph_input_pipeline.py : Defines the input pipeline for the PDP framework.
import collections
import json
import linecache
import numpy as np
import torch
import torch.utils.data as data
class DynamicBatchDivider(object):
"""Implements the dynamic batching process."""
def __init__(self, limit, hidden_dim):
self.limit = limit
self.hidden_dim = hidden_dim
def divide(self, variable_num, function_num, graph_map, edge_feature, graph_feature, label, misc_data):
batch_size = len(variable_num)
edge_num = [len(n) for n in edge_feature]
graph_map_list = []
edge_feature_list = []
graph_feature_list = []
variable_num_list = []
function_num_list = []
label_list = []
misc_data_list = []
if (self.limit // (max(edge_num) * self.hidden_dim)) >= batch_size:
if graph_feature[0] is None:
graph_feature_list = [[None]]
else:
graph_feature_list = [graph_feature]
graph_map_list = [graph_map]
edge_feature_list = [edge_feature]
variable_num_list = [variable_num]
function_num_list = [function_num]
label_list = [label]
misc_data_list = [misc_data]
else:
indices = sorted(range(len(edge_num)), reverse=True, key=lambda k: edge_num[k])
sorted_edge_num = sorted(edge_num, reverse=True)
i = 0
while i < batch_size:
allowed_batch_size = self.limit // (sorted_edge_num[i] * self.hidden_dim)
ind = indices[i:min(i + allowed_batch_size, batch_size)]
if graph_feature[0] is None:
graph_feature_list += [[None]]
else:
graph_feature_list += [[graph_feature[j] for j in ind]]
edge_feature_list += [[edge_feature[j] for j in ind]]
variable_num_list += [[variable_num[j] for j in ind]]
function_num_list += [[function_num[j] for j in ind]]
graph_map_list += [[graph_map[j] for j in ind]]
label_list += [[label[j] for j in ind]]
misc_data_list += [[misc_data[j] for j in ind]]
i += allowed_batch_size
return variable_num_list, function_num_list, graph_map_list, edge_feature_list, graph_feature_list, label_list, misc_data_list
###############################################################
class FactorGraphDataset(data.Dataset):
"""Implements a PyTorch Dataset class for reading and parsing CNFs in the JSON format from disk."""
def __init__(self, input_file, limit, hidden_dim, max_cache_size=100000, generator=None, epoch_size=0, batch_replication=1):
self._cache = collections.OrderedDict()
self._generator = generator
self._epoch_size = epoch_size
self._input_file = input_file
self._max_cache_size = max_cache_size
if self._generator is None:
with open(self._input_file, 'r') as fh_input:
self._row_num = len(fh_input.readlines())
self.batch_divider = DynamicBatchDivider(limit // batch_replication, hidden_dim)
def __len__(self):
if self._generator is not None:
return self._epoch_size
else:
return self._row_num
def __getitem__(self, idx):
if self._generator is not None:
return self._generator.generate()
else:
if idx in self._cache:
return self._cache[idx]
line = linecache.getline(self._input_file, idx + 1)
result = self._convert_line(line)
if len(self._cache) >= self._max_cache_size:
self._cache.popitem(last=False)
self._cache[idx] = result
return result
def _convert_line(self, json_str):
input_data = json.loads(json_str)
variable_num, function_num = input_data[0]
variable_ind = np.abs(np.array(input_data[1], dtype=np.int32)) - 1
function_ind = np.abs(np.array(input_data[2], dtype=np.int32)) - 1
edge_feature = np.sign(np.array(input_data[1], dtype=np.float32))
graph_map = np.stack((variable_ind, function_ind))
alpha = float(function_num) / variable_num
misc_data = []
if len(input_data) > 4:
misc_data = input_data[4]
return (variable_num, function_num, graph_map, edge_feature, None, float(input_data[3]), misc_data)
def dag_collate_fn(self, input_data):
"""Torch dataset loader collation function for factor graph input."""
vn, fn, gm, ef, gf, l, md = zip(*input_data)
variable_num, function_num, graph_map, edge_feature, graph_feat, label, misc_data = \
self.batch_divider.divide(vn, fn, gm, ef, gf, l, md)
segment_num = len(variable_num)
graph_feat_batch = []
graph_map_batch = []
batch_variable_map_batch = []
batch_function_map_batch = []
edge_feature_batch = []
label_batch = []
for i in range(segment_num):
# Create the graph features batch
graph_feat_batch += [None if graph_feat[i][0] is None else torch.from_numpy(np.stack(graph_feat[i])).float()]
# Create the edge feature batch
edge_feature_batch += [torch.from_numpy(np.expand_dims(np.concatenate(edge_feature[i]), 1)).float()]
# Create the label batch
label_batch += [torch.from_numpy(np.expand_dims(np.array(label[i]), 1)).float()]
# Create the graph map, variable map and function map batches
g_map_b = np.zeros((2, 0), dtype=np.int32)
v_map_b = np.zeros(0, dtype=np.int32)
f_map_b = np.zeros(0, dtype=np.int32)
variable_ind = 0
function_ind = 0
for j in range(len(graph_map[i])):
graph_map[i][j][0, :] += variable_ind
graph_map[i][j][1, :] += function_ind
g_map_b = np.concatenate((g_map_b, graph_map[i][j]), axis=1)
v_map_b = np.concatenate((v_map_b, np.tile(j, variable_num[i][j])))
f_map_b = np.concatenate((f_map_b, np.tile(j, function_num[i][j])))
variable_ind += variable_num[i][j]
function_ind += function_num[i][j]
graph_map_batch += [torch.from_numpy(g_map_b).int()]
batch_variable_map_batch += [torch.from_numpy(v_map_b).int()]
batch_function_map_batch += [torch.from_numpy(f_map_b).int()]
return graph_map_batch, batch_variable_map_batch, batch_function_map_batch, edge_feature_batch, graph_feat_batch, label_batch, misc_data
@staticmethod
def get_loader(input_file, limit, hidden_dim, batch_size, shuffle, num_workers,
max_cache_size=100000, use_cuda=True, generator=None, epoch_size=0, batch_replication=1):
"""Return the torch dataset loader object for the input."""
dataset = FactorGraphDataset(
input_file=input_file,
limit=limit,
hidden_dim=hidden_dim,
max_cache_size=max_cache_size,
generator=generator,
epoch_size=epoch_size,
batch_replication=batch_replication)
data_loader = torch.utils.data.DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_workers,
collate_fn=dataset.dag_collate_fn,
pin_memory=use_cuda)
return data_loader
|
[
"numpy.stack",
"linecache.getline",
"json.loads",
"torch.utils.data.DataLoader",
"numpy.zeros",
"numpy.array",
"numpy.tile",
"collections.OrderedDict",
"numpy.concatenate",
"torch.from_numpy"
] |
[((3044, 3069), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (3067, 3069), False, 'import collections\n'), ((4208, 4228), 'json.loads', 'json.loads', (['json_str'], {}), '(json_str)\n', (4218, 4228), False, 'import json\n'), ((4533, 4571), 'numpy.stack', 'np.stack', (['(variable_ind, function_ind)'], {}), '((variable_ind, function_ind))\n', (4541, 4571), True, 'import numpy as np\n'), ((7717, 7891), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'dataset', 'batch_size': 'batch_size', 'shuffle': 'shuffle', 'num_workers': 'num_workers', 'collate_fn': 'dataset.dag_collate_fn', 'pin_memory': 'use_cuda'}), '(dataset=dataset, batch_size=batch_size, shuffle\n =shuffle, num_workers=num_workers, collate_fn=dataset.dag_collate_fn,\n pin_memory=use_cuda)\n', (7744, 7891), False, 'import torch\n'), ((3873, 3917), 'linecache.getline', 'linecache.getline', (['self._input_file', '(idx + 1)'], {}), '(self._input_file, idx + 1)\n', (3890, 3917), False, 'import linecache\n'), ((4467, 4508), 'numpy.array', 'np.array', (['input_data[1]'], {'dtype': 'np.float32'}), '(input_data[1], dtype=np.float32)\n', (4475, 4508), True, 'import numpy as np\n'), ((6024, 6056), 'numpy.zeros', 'np.zeros', (['(2, 0)'], {'dtype': 'np.int32'}), '((2, 0), dtype=np.int32)\n', (6032, 6056), True, 'import numpy as np\n'), ((6080, 6107), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': 'np.int32'}), '(0, dtype=np.int32)\n', (6088, 6107), True, 'import numpy as np\n'), ((6131, 6158), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': 'np.int32'}), '(0, dtype=np.int32)\n', (6139, 6158), True, 'import numpy as np\n'), ((4314, 4353), 'numpy.array', 'np.array', (['input_data[1]'], {'dtype': 'np.int32'}), '(input_data[1], dtype=np.int32)\n', (4322, 4353), True, 'import numpy as np\n'), ((4390, 4429), 'numpy.array', 'np.array', (['input_data[2]'], {'dtype': 'np.int32'}), '(input_data[2], dtype=np.int32)\n', (4398, 4429), True, 'import numpy as np\n'), ((6406, 6456), 'numpy.concatenate', 'np.concatenate', (['(g_map_b, graph_map[i][j])'], {'axis': '(1)'}), '((g_map_b, graph_map[i][j]), axis=1)\n', (6420, 6456), True, 'import numpy as np\n'), ((6511, 6541), 'numpy.tile', 'np.tile', (['j', 'variable_num[i][j]'], {}), '(j, variable_num[i][j])\n', (6518, 6541), True, 'import numpy as np\n'), ((6596, 6626), 'numpy.tile', 'np.tile', (['j', 'function_num[i][j]'], {}), '(j, function_num[i][j])\n', (6603, 6626), True, 'import numpy as np\n'), ((6770, 6795), 'torch.from_numpy', 'torch.from_numpy', (['g_map_b'], {}), '(g_map_b)\n', (6786, 6795), False, 'import torch\n'), ((6845, 6870), 'torch.from_numpy', 'torch.from_numpy', (['v_map_b'], {}), '(v_map_b)\n', (6861, 6870), False, 'import torch\n'), ((6920, 6945), 'torch.from_numpy', 'torch.from_numpy', (['f_map_b'], {}), '(f_map_b)\n', (6936, 6945), False, 'import torch\n'), ((5595, 5618), 'numpy.stack', 'np.stack', (['graph_feat[i]'], {}), '(graph_feat[i])\n', (5603, 5618), True, 'import numpy as np\n'), ((5744, 5775), 'numpy.concatenate', 'np.concatenate', (['edge_feature[i]'], {}), '(edge_feature[i])\n', (5758, 5775), True, 'import numpy as np\n'), ((5891, 5909), 'numpy.array', 'np.array', (['label[i]'], {}), '(label[i])\n', (5899, 5909), True, 'import numpy as np\n')]
|
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import random
import numpy as np
import pytest
import cirq
def _operations_to_matrix(operations, qubits):
return cirq.Circuit(operations).unitary(
qubit_order=cirq.QubitOrder.explicit(qubits), qubits_that_should_be_present=qubits
)
def _random_single_MS_effect():
t = random.random()
s = np.sin(t)
c = np.cos(t)
return cirq.dot(
cirq.kron(cirq.testing.random_unitary(2), cirq.testing.random_unitary(2)),
np.array([[c, 0, 0, -1j * s], [0, c, -1j * s, 0], [0, -1j * s, c, 0], [-1j * s, 0, 0, c]]),
cirq.kron(cirq.testing.random_unitary(2), cirq.testing.random_unitary(2)),
)
def _random_double_MS_effect():
t1 = random.random()
s1 = np.sin(t1)
c1 = np.cos(t1)
t2 = random.random()
s2 = np.sin(t2)
c2 = np.cos(t2)
return cirq.dot(
cirq.kron(cirq.testing.random_unitary(2), cirq.testing.random_unitary(2)),
np.array(
[[c1, 0, 0, -1j * s1], [0, c1, -1j * s1, 0], [0, -1j * s1, c1, 0], [-1j * s1, 0, 0, c1]]
),
cirq.kron(cirq.testing.random_unitary(2), cirq.testing.random_unitary(2)),
np.array(
[[c2, 0, 0, -1j * s2], [0, c2, -1j * s2, 0], [0, -1j * s2, c2, 0], [-1j * s2, 0, 0, c2]]
),
cirq.kron(cirq.testing.random_unitary(2), cirq.testing.random_unitary(2)),
)
def assert_ops_implement_unitary(q0, q1, operations, intended_effect, atol=0.01):
actual_effect = _operations_to_matrix(operations, (q0, q1))
assert cirq.allclose_up_to_global_phase(actual_effect, intended_effect, atol=atol)
def assert_ms_depth_below(operations, threshold):
total_ms = 0
for op in operations:
assert len(op.qubits) <= 2
if len(op.qubits) == 2:
assert isinstance(op, cirq.GateOperation)
assert isinstance(op.gate, cirq.XXPowGate)
total_ms += abs(op.gate.exponent)
assert total_ms <= threshold
# yapf: disable
@pytest.mark.parametrize('max_ms_depth,effect', [
(0, np.eye(4)),
(0, np.array([
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0],
[1, 0, 0, 0j]
])),
(1, cirq.unitary(cirq.ms(np.pi/4))),
(0, cirq.unitary(cirq.CZ ** 0.00000001)),
(0.5, cirq.unitary(cirq.CZ ** 0.5)),
(1, cirq.unitary(cirq.CZ)),
(1, cirq.unitary(cirq.CNOT)),
(1, np.array([
[1, 0, 0, 1j],
[0, 1, 1j, 0],
[0, 1j, 1, 0],
[1j, 0, 0, 1],
]) * np.sqrt(0.5)),
(1, np.array([
[1, 0, 0, -1j],
[0, 1, -1j, 0],
[0, -1j, 1, 0],
[-1j, 0, 0, 1],
]) * np.sqrt(0.5)),
(1, np.array([
[1, 0, 0, 1j],
[0, 1, -1j, 0],
[0, -1j, 1, 0],
[1j, 0, 0, 1],
]) * np.sqrt(0.5)),
(1.5, cirq.map_eigenvalues(cirq.unitary(cirq.SWAP),
lambda e: e ** 0.5)),
(2, cirq.unitary(cirq.SWAP).dot(cirq.unitary(cirq.CZ))),
(3, cirq.unitary(cirq.SWAP)),
(3, np.array([
[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 0, 1, 0],
[1, 0, 0, 0j],
])),
] + [
(1, _random_single_MS_effect()) for _ in range(10)
] + [
(3, cirq.testing.random_unitary(4)) for _ in range(10)
] + [
(2, _random_double_MS_effect()) for _ in range(10)
])
# yapf: enable
def test_two_to_ops(max_ms_depth: int, effect: np.ndarray):
q0 = cirq.NamedQubit('q0')
q1 = cirq.NamedQubit('q1')
operations = cirq.two_qubit_matrix_to_ion_operations(q0, q1, effect)
assert_ops_implement_unitary(q0, q1, operations, effect)
assert_ms_depth_below(operations, max_ms_depth)
|
[
"cirq.ms",
"cirq.QubitOrder.explicit",
"cirq.testing.random_unitary",
"cirq.unitary",
"cirq.NamedQubit",
"random.random",
"cirq.allclose_up_to_global_phase",
"numpy.sin",
"cirq.two_qubit_matrix_to_ion_operations",
"numpy.array",
"numpy.cos",
"cirq.Circuit",
"numpy.eye",
"numpy.sqrt"
] |
[((879, 894), 'random.random', 'random.random', ([], {}), '()\n', (892, 894), False, 'import random\n'), ((903, 912), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (909, 912), True, 'import numpy as np\n'), ((921, 930), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (927, 930), True, 'import numpy as np\n'), ((1267, 1282), 'random.random', 'random.random', ([], {}), '()\n', (1280, 1282), False, 'import random\n'), ((1292, 1302), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (1298, 1302), True, 'import numpy as np\n'), ((1312, 1322), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (1318, 1322), True, 'import numpy as np\n'), ((1333, 1348), 'random.random', 'random.random', ([], {}), '()\n', (1346, 1348), False, 'import random\n'), ((1358, 1368), 'numpy.sin', 'np.sin', (['t2'], {}), '(t2)\n', (1364, 1368), True, 'import numpy as np\n'), ((1378, 1388), 'numpy.cos', 'np.cos', (['t2'], {}), '(t2)\n', (1384, 1388), True, 'import numpy as np\n'), ((2084, 2159), 'cirq.allclose_up_to_global_phase', 'cirq.allclose_up_to_global_phase', (['actual_effect', 'intended_effect'], {'atol': 'atol'}), '(actual_effect, intended_effect, atol=atol)\n', (2116, 2159), False, 'import cirq\n'), ((3920, 3941), 'cirq.NamedQubit', 'cirq.NamedQubit', (['"""q0"""'], {}), "('q0')\n", (3935, 3941), False, 'import cirq\n'), ((3951, 3972), 'cirq.NamedQubit', 'cirq.NamedQubit', (['"""q1"""'], {}), "('q1')\n", (3966, 3972), False, 'import cirq\n'), ((3991, 4046), 'cirq.two_qubit_matrix_to_ion_operations', 'cirq.two_qubit_matrix_to_ion_operations', (['q0', 'q1', 'effect'], {}), '(q0, q1, effect)\n', (4030, 4046), False, 'import cirq\n'), ((1043, 1145), 'numpy.array', 'np.array', (['[[c, 0, 0, -1.0j * s], [0, c, -1.0j * s, 0], [0, -1.0j * s, c, 0], [-1.0j *\n s, 0, 0, c]]'], {}), '([[c, 0, 0, -1.0j * s], [0, c, -1.0j * s, 0], [0, -1.0j * s, c, 0],\n [-1.0j * s, 0, 0, c]])\n', (1051, 1145), True, 'import numpy as np\n'), ((1501, 1611), 'numpy.array', 'np.array', (['[[c1, 0, 0, -1.0j * s1], [0, c1, -1.0j * s1, 0], [0, -1.0j * s1, c1, 0], [-\n 1.0j * s1, 0, 0, c1]]'], {}), '([[c1, 0, 0, -1.0j * s1], [0, c1, -1.0j * s1, 0], [0, -1.0j * s1,\n c1, 0], [-1.0j * s1, 0, 0, c1]])\n', (1509, 1611), True, 'import numpy as np\n'), ((1714, 1824), 'numpy.array', 'np.array', (['[[c2, 0, 0, -1.0j * s2], [0, c2, -1.0j * s2, 0], [0, -1.0j * s2, c2, 0], [-\n 1.0j * s2, 0, 0, c2]]'], {}), '([[c2, 0, 0, -1.0j * s2], [0, c2, -1.0j * s2, 0], [0, -1.0j * s2,\n c2, 0], [-1.0j * s2, 0, 0, c2]])\n', (1722, 1824), True, 'import numpy as np\n'), ((706, 730), 'cirq.Circuit', 'cirq.Circuit', (['operations'], {}), '(operations)\n', (718, 730), False, 'import cirq\n'), ((760, 792), 'cirq.QubitOrder.explicit', 'cirq.QubitOrder.explicit', (['qubits'], {}), '(qubits)\n', (784, 792), False, 'import cirq\n'), ((970, 1000), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (997, 1000), False, 'import cirq\n'), ((1002, 1032), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1029, 1032), False, 'import cirq\n'), ((1153, 1183), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1180, 1183), False, 'import cirq\n'), ((1185, 1215), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1212, 1215), False, 'import cirq\n'), ((1428, 1458), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1455, 1458), False, 'import cirq\n'), ((1460, 1490), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1487, 1490), False, 'import cirq\n'), ((1641, 1671), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1668, 1671), False, 'import cirq\n'), ((1673, 1703), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1700, 1703), False, 'import cirq\n'), ((1854, 1884), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1881, 1884), False, 'import cirq\n'), ((1886, 1916), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(2)'], {}), '(2)\n', (1913, 1916), False, 'import cirq\n'), ((3721, 3751), 'cirq.testing.random_unitary', 'cirq.testing.random_unitary', (['(4)'], {}), '(4)\n', (3748, 3751), False, 'import cirq\n'), ((2587, 2596), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2593, 2596), True, 'import numpy as np\n'), ((2607, 2676), 'numpy.array', 'np.array', (['[[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0.0j]]'], {}), '([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0.0j]])\n', (2615, 2676), True, 'import numpy as np\n'), ((2765, 2795), 'cirq.unitary', 'cirq.unitary', (['(cirq.CZ ** 1e-08)'], {}), '(cirq.CZ ** 1e-08)\n', (2777, 2795), False, 'import cirq\n'), ((2813, 2841), 'cirq.unitary', 'cirq.unitary', (['(cirq.CZ ** 0.5)'], {}), '(cirq.CZ ** 0.5)\n', (2825, 2841), False, 'import cirq\n'), ((2853, 2874), 'cirq.unitary', 'cirq.unitary', (['cirq.CZ'], {}), '(cirq.CZ)\n', (2865, 2874), False, 'import cirq\n'), ((2885, 2908), 'cirq.unitary', 'cirq.unitary', (['cirq.CNOT'], {}), '(cirq.CNOT)\n', (2897, 2908), False, 'import cirq\n'), ((3503, 3526), 'cirq.unitary', 'cirq.unitary', (['cirq.SWAP'], {}), '(cirq.SWAP)\n', (3515, 3526), False, 'import cirq\n'), ((3537, 3606), 'numpy.array', 'np.array', (['[[0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0.0j]]'], {}), '([[0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0.0j]])\n', (3545, 3606), True, 'import numpy as np\n'), ((2736, 2754), 'cirq.ms', 'cirq.ms', (['(np.pi / 4)'], {}), '(np.pi / 4)\n', (2743, 2754), False, 'import cirq\n'), ((2919, 2997), 'numpy.array', 'np.array', (['[[1, 0, 0, 1.0j], [0, 1, 1.0j, 0], [0, 1.0j, 1, 0], [1.0j, 0, 0, 1]]'], {}), '([[1, 0, 0, 1.0j], [0, 1, 1.0j, 0], [0, 1.0j, 1, 0], [1.0j, 0, 0, 1]])\n', (2927, 2997), True, 'import numpy as np\n'), ((3031, 3043), 'numpy.sqrt', 'np.sqrt', (['(0.5)'], {}), '(0.5)\n', (3038, 3043), True, 'import numpy as np\n'), ((3054, 3141), 'numpy.array', 'np.array', (['[[1, 0, 0, -1.0j], [0, 1, -1.0j, 0], [0, -1.0j, 1, 0], [-1.0j, 0, 0, 1]]'], {}), '([[1, 0, 0, -1.0j], [0, 1, -1.0j, 0], [0, -1.0j, 1, 0], [-1.0j, 0, \n 0, 1]])\n', (3062, 3141), True, 'import numpy as np\n'), ((3170, 3182), 'numpy.sqrt', 'np.sqrt', (['(0.5)'], {}), '(0.5)\n', (3177, 3182), True, 'import numpy as np\n'), ((3193, 3278), 'numpy.array', 'np.array', (['[[1, 0, 0, 1.0j], [0, 1, -1.0j, 0], [0, -1.0j, 1, 0], [1.0j, 0, 0, 1]]'], {}), '([[1, 0, 0, 1.0j], [0, 1, -1.0j, 0], [0, -1.0j, 1, 0], [1.0j, 0, 0, 1]]\n )\n', (3201, 3278), True, 'import numpy as np\n'), ((3307, 3319), 'numpy.sqrt', 'np.sqrt', (['(0.5)'], {}), '(0.5)\n', (3314, 3319), True, 'import numpy as np\n'), ((3354, 3377), 'cirq.unitary', 'cirq.unitary', (['cirq.SWAP'], {}), '(cirq.SWAP)\n', (3366, 3377), False, 'import cirq\n'), ((3469, 3490), 'cirq.unitary', 'cirq.unitary', (['cirq.CZ'], {}), '(cirq.CZ)\n', (3481, 3490), False, 'import cirq\n'), ((3441, 3464), 'cirq.unitary', 'cirq.unitary', (['cirq.SWAP'], {}), '(cirq.SWAP)\n', (3453, 3464), False, 'import cirq\n')]
|
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import numpy as np
def selection_sort(arr):
for i in range(len(arr)):
j = i + np.argmin(arr[i:])
(arr[i],arr[j]) = (arr[j],arr[i])
return arr
if __name__ == "__main__" :
x = [1,3,24,5,6]
x = selection_sort(x)
print(x)
|
[
"numpy.argmin"
] |
[((127, 145), 'numpy.argmin', 'np.argmin', (['arr[i:]'], {}), '(arr[i:])\n', (136, 145), True, 'import numpy as np\n')]
|
'''
Social LSTM model implementation using Tensorflow
Social LSTM Paper: http://vision.stanford.edu/pdf/CVPR16_N_LSTM.pdf
Author : <NAME>
Date: 10th October 2016
'''
import tensorflow as tf
import numpy as np
from tensorflow.python.ops import rnn_cell
import ipdb
# The Vanilla LSTM model
class Model():
def __init__(self, args, infer=False):
'''
Initialisation function for the class Model.
Params:
args: Contains arguments required for the Model creation
'''
# If sampling new trajectories, then infer mode
if infer:
# Infer one position at a time
args.batch_size = 1
args.seq_length = 1
# Store the arguments
self.args = args
# Initialize a BasicLSTMCell recurrent unit
# args.rnn_size contains the dimension of the hidden state of the LSTM
cell = rnn_cell.BasicLSTMCell(args.rnn_size, state_is_tuple=False)
# Multi-layer RNN construction, if more than one layer
cell = rnn_cell.MultiRNNCell([cell] * args.num_layers, state_is_tuple=False)
# TODO: (improve) Dropout layer can be added here
# Store the recurrent unit
self.cell = cell
# TODO: (resolve) Do we need to use a fixed seq_length?
# Input data contains sequence of (x,y) points
self.input_data = tf.placeholder(tf.float32, [None, args.seq_length, 2])
# target data contains sequences of (x,y) points as well
self.target_data = tf.placeholder(tf.float32, [None, args.seq_length, 2])
# Learning rate
self.lr = tf.Variable(args.learning_rate, trainable=False, name="learning_rate")
# Initial cell state of the LSTM (initialised with zeros)
self.initial_state = cell.zero_state(batch_size=args.batch_size, dtype=tf.float32)
# Output size is the set of parameters (mu, sigma, corr)
output_size = 5 # 2 mu, 2 sigma and 1 corr
# Embedding for the spatial coordinates
with tf.variable_scope("coordinate_embedding"):
# The spatial embedding using a ReLU layer
# Embed the 2D coordinates into embedding_size dimensions
# TODO: (improve) For now assume embedding_size = rnn_size
embedding_w = tf.get_variable("embedding_w", [2, args.embedding_size])
embedding_b = tf.get_variable("embedding_b", [args.embedding_size])
# Output linear layer
with tf.variable_scope("rnnlm"):
output_w = tf.get_variable("output_w", [args.rnn_size, output_size], initializer=tf.truncated_normal_initializer(stddev=0.01), trainable=True)
output_b = tf.get_variable("output_b", [output_size], initializer=tf.constant_initializer(0.01), trainable=True)
# Split inputs according to sequences.
inputs = tf.split(1, args.seq_length, self.input_data)
# Get a list of 2D tensors. Each of size numPoints x 2
inputs = [tf.squeeze(input_, [1]) for input_ in inputs]
# Embed the input spatial points into the embedding space
embedded_inputs = []
for x in inputs:
# Each x is a 2D tensor of size numPoints x 2
# Embedding layer
embedded_x = tf.nn.relu(tf.add(tf.matmul(x, embedding_w), embedding_b))
embedded_inputs.append(embedded_x)
# Feed the embedded input data, the initial state of the LSTM cell, the recurrent unit to the seq2seq decoder
outputs, last_state = tf.nn.seq2seq.rnn_decoder(embedded_inputs, self.initial_state, cell, loop_function=None, scope="rnnlm")
# Concatenate the outputs from the RNN decoder and reshape it to ?xargs.rnn_size
output = tf.reshape(tf.concat(1, outputs), [-1, args.rnn_size])
# Apply the output linear layer
output = tf.nn.xw_plus_b(output, output_w, output_b)
# Store the final LSTM cell state after the input data has been feeded
self.final_state = last_state
# reshape target data so that it aligns with predictions
flat_target_data = tf.reshape(self.target_data, [-1, 2])
# Extract the x-coordinates and y-coordinates from the target data
[x_data, y_data] = tf.split(1, 2, flat_target_data)
def tf_2d_normal(x, y, mux, muy, sx, sy, rho):
'''
Function that implements the PDF of a 2D normal distribution
params:
x : input x points
y : input y points
mux : mean of the distribution in x
muy : mean of the distribution in y
sx : std dev of the distribution in x
sy : std dev of the distribution in y
rho : Correlation factor of the distribution
'''
# eq 3 in the paper
# and eq 24 & 25 in Graves (2013)
# Calculate (x - mux) and (y-muy)
normx = tf.sub(x, mux)
normy = tf.sub(y, muy)
# Calculate sx*sy
sxsy = tf.mul(sx, sy)
# Calculate the exponential factor
z = tf.square(tf.div(normx, sx)) + tf.square(tf.div(normy, sy)) - 2*tf.div(tf.mul(rho, tf.mul(normx, normy)), sxsy)
negRho = 1 - tf.square(rho)
# Numerator
result = tf.exp(tf.div(-z, 2*negRho))
# Normalization constant
denom = 2 * np.pi * tf.mul(sxsy, tf.sqrt(negRho))
# Final PDF calculation
result = tf.div(result, denom)
self.result = result
return result
# Important difference between loss func of Social LSTM and Graves (2013)
# is that it is evaluated over all time steps in the latter whereas it is
# done from t_obs+1 to t_pred in the former
def get_lossfunc(z_mux, z_muy, z_sx, z_sy, z_corr, x_data, y_data):
'''
Function to calculate given a 2D distribution over x and y, and target data
of observed x and y points
params:
z_mux : mean of the distribution in x
z_muy : mean of the distribution in y
z_sx : std dev of the distribution in x
z_sy : std dev of the distribution in y
z_rho : Correlation factor of the distribution
x_data : target x points
y_data : target y points
'''
# step = tf.constant(1e-3, dtype=tf.float32, shape=(1, 1))
# Calculate the PDF of the data w.r.t to the distribution
result0 = tf_2d_normal(x_data, y_data, z_mux, z_muy, z_sx, z_sy, z_corr)
# result0_2 = tf_2d_normal(tf.add(x_data, step), y_data, z_mux, z_muy, z_sx, z_sy, z_corr)
# result0_3 = tf_2d_normal(x_data, tf.add(y_data, step), z_mux, z_muy, z_sx, z_sy, z_corr)
# result0_4 = tf_2d_normal(tf.add(x_data, step), tf.add(y_data, step), z_mux, z_muy, z_sx, z_sy, z_corr)
# result0 = tf.div(tf.add(tf.add(tf.add(result0_1, result0_2), result0_3), result0_4), tf.constant(4.0, dtype=tf.float32, shape=(1, 1)))
# result0 = tf.mul(tf.mul(result0, step), step)
# For numerical stability purposes
epsilon = 1e-20
# TODO: (resolve) I don't think we need this as we don't have the inner
# summation
# result1 = tf.reduce_sum(result0, 1, keep_dims=True)
# Apply the log operation
result1 = -tf.log(tf.maximum(result0, epsilon)) # Numerical stability
# TODO: For now, implementing loss func over all time-steps
# Sum up all log probabilities for each data point
return tf.reduce_sum(result1)
def get_coef(output):
# eq 20 -> 22 of Graves (2013)
# TODO : (resolve) Does Social LSTM paper do this as well?
# the paper says otherwise but this is essential as we cannot
# have negative standard deviation and correlation needs to be between
# -1 and 1
z = output
# Split the output into 5 parts corresponding to means, std devs and corr
z_mux, z_muy, z_sx, z_sy, z_corr = tf.split(1, 5, z)
# The output must be exponentiated for the std devs
z_sx = tf.exp(z_sx)
z_sy = tf.exp(z_sy)
# Tanh applied to keep it in the range [-1, 1]
z_corr = tf.tanh(z_corr)
return [z_mux, z_muy, z_sx, z_sy, z_corr]
# Extract the coef from the output of the linear layer
[o_mux, o_muy, o_sx, o_sy, o_corr] = get_coef(output)
# Store the output from the model
self.output = output
# Store the predicted outputs
self.mux = o_mux
self.muy = o_muy
self.sx = o_sx
self.sy = o_sy
self.corr = o_corr
# Compute the loss function
lossfunc = get_lossfunc(o_mux, o_muy, o_sx, o_sy, o_corr, x_data, y_data)
# Compute the cost
self.cost = tf.div(lossfunc, (args.batch_size * args.seq_length))
# Get trainable_variables
tvars = tf.trainable_variables()
# TODO: (resolve) We are clipping the gradients as is usually done in LSTM
# implementations. Social LSTM paper doesn't mention about this at all
# Calculate gradients of the cost w.r.t all the trainable variables
self.gradients = tf.gradients(self.cost, tvars)
# Clip the gradients if they are larger than the value given in args
grads, _ = tf.clip_by_global_norm(self.gradients, args.grad_clip)
# NOTE: Using RMSprop as suggested by Social LSTM instead of Adam as Graves(2013) does
# optimizer = tf.train.AdamOptimizer(self.lr)
# initialize the optimizer with teh given learning rate
optimizer = tf.train.RMSPropOptimizer(self.lr)
# Train operator
self.train_op = optimizer.apply_gradients(zip(grads, tvars))
def sample(self, sess, traj, true_traj, num=10):
'''
Given an initial trajectory (as a list of tuples of points), predict the future trajectory
until a few timesteps
Params:
sess: Current session of Tensorflow
traj: List of past trajectory points
true_traj : List of complete trajectory points
num: Number of time-steps into the future to be predicted
'''
def sample_gaussian_2d(mux, muy, sx, sy, rho):
'''
Function to sample a point from a given 2D normal distribution
params:
mux : mean of the distribution in x
muy : mean of the distribution in y
sx : std dev of the distribution in x
sy : std dev of the distribution in y
rho : Correlation factor of the distribution
'''
# Extract mean
mean = [mux, muy]
# Extract covariance matrix
cov = [[sx*sx, rho*sx*sy], [rho*sx*sy, sy*sy]]
# Sample a point from the multivariate normal distribution
x = np.random.multivariate_normal(mean, cov, 1)
return x[0][0], x[0][1]
# Initial state with zeros
state = sess.run(self.cell.zero_state(1, tf.float32))
# Iterate over all the positions seen in the trajectory
for pos in traj[:-1]:
# Create the input data tensor
data = np.zeros((1, 1, 2), dtype=np.float32)
data[0, 0, 0] = pos[0] # x
data[0, 0, 1] = pos[1] # y
# Create the feed dict
feed = {self.input_data: data, self.initial_state: state}
# Get the final state after processing the current position
[state] = sess.run([self.final_state], feed)
ret = traj
# Last position in the observed trajectory
last_pos = traj[-1]
# Construct the input data tensor for the last point
prev_data = np.zeros((1, 1, 2), dtype=np.float32)
prev_data[0, 0, 0] = last_pos[0] # x
prev_data[0, 0, 1] = last_pos[1] # y
prev_target_data = np.reshape(true_traj[traj.shape[0]], (1, 1, 2))
for t in range(num):
# Create the feed dict
feed = {self.input_data: prev_data, self.initial_state: state, self.target_data: prev_target_data}
# Get the final state and also the coef of the distribution of the next point
[o_mux, o_muy, o_sx, o_sy, o_corr, state, cost] = sess.run([self.mux, self.muy, self.sx, self.sy, self.corr, self.final_state, self.cost], feed)
# print cost
# Sample the next point from the distribution
next_x, next_y = sample_gaussian_2d(o_mux[0][0], o_muy[0][0], o_sx[0][0], o_sy[0][0], o_corr[0][0])
# Append the new point to the trajectory
ret = np.vstack((ret, [next_x, next_y]))
# Set the current sampled position as the last observed position
prev_data[0, 0, 0] = next_x
prev_data[0, 0, 1] = next_y
# ipdb.set_trace()
return ret
|
[
"tensorflow.reduce_sum",
"tensorflow.trainable_variables",
"tensorflow.constant_initializer",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.matmul",
"tensorflow.python.ops.rnn_cell.BasicLSTMCell",
"tensorflow.Variable",
"tensorflow.sqrt",
"tensorflow.split",
"tensorflow.clip_by_global_norm",
"tensorflow.get_variable",
"tensorflow.variable_scope",
"tensorflow.div",
"tensorflow.concat",
"tensorflow.placeholder",
"tensorflow.exp",
"numpy.reshape",
"tensorflow.squeeze",
"tensorflow.gradients",
"tensorflow.truncated_normal_initializer",
"tensorflow.mul",
"tensorflow.python.ops.rnn_cell.MultiRNNCell",
"numpy.vstack",
"numpy.zeros",
"tensorflow.nn.seq2seq.rnn_decoder",
"numpy.random.multivariate_normal",
"tensorflow.nn.xw_plus_b",
"tensorflow.square",
"tensorflow.tanh",
"tensorflow.sub"
] |
[((895, 954), 'tensorflow.python.ops.rnn_cell.BasicLSTMCell', 'rnn_cell.BasicLSTMCell', (['args.rnn_size'], {'state_is_tuple': '(False)'}), '(args.rnn_size, state_is_tuple=False)\n', (917, 954), False, 'from tensorflow.python.ops import rnn_cell\n'), ((1034, 1103), 'tensorflow.python.ops.rnn_cell.MultiRNNCell', 'rnn_cell.MultiRNNCell', (['([cell] * args.num_layers)'], {'state_is_tuple': '(False)'}), '([cell] * args.num_layers, state_is_tuple=False)\n', (1055, 1103), False, 'from tensorflow.python.ops import rnn_cell\n'), ((1369, 1423), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, args.seq_length, 2]'], {}), '(tf.float32, [None, args.seq_length, 2])\n', (1383, 1423), True, 'import tensorflow as tf\n'), ((1516, 1570), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, args.seq_length, 2]'], {}), '(tf.float32, [None, args.seq_length, 2])\n', (1530, 1570), True, 'import tensorflow as tf\n'), ((1614, 1684), 'tensorflow.Variable', 'tf.Variable', (['args.learning_rate'], {'trainable': '(False)', 'name': '"""learning_rate"""'}), "(args.learning_rate, trainable=False, name='learning_rate')\n", (1625, 1684), True, 'import tensorflow as tf\n'), ((2845, 2890), 'tensorflow.split', 'tf.split', (['(1)', 'args.seq_length', 'self.input_data'], {}), '(1, args.seq_length, self.input_data)\n', (2853, 2890), True, 'import tensorflow as tf\n'), ((3507, 3614), 'tensorflow.nn.seq2seq.rnn_decoder', 'tf.nn.seq2seq.rnn_decoder', (['embedded_inputs', 'self.initial_state', 'cell'], {'loop_function': 'None', 'scope': '"""rnnlm"""'}), "(embedded_inputs, self.initial_state, cell,\n loop_function=None, scope='rnnlm')\n", (3532, 3614), True, 'import tensorflow as tf\n'), ((3831, 3874), 'tensorflow.nn.xw_plus_b', 'tf.nn.xw_plus_b', (['output', 'output_w', 'output_b'], {}), '(output, output_w, output_b)\n', (3846, 3874), True, 'import tensorflow as tf\n'), ((4085, 4122), 'tensorflow.reshape', 'tf.reshape', (['self.target_data', '[-1, 2]'], {}), '(self.target_data, [-1, 2])\n', (4095, 4122), True, 'import tensorflow as tf\n'), ((4225, 4257), 'tensorflow.split', 'tf.split', (['(1)', '(2)', 'flat_target_data'], {}), '(1, 2, flat_target_data)\n', (4233, 4257), True, 'import tensorflow as tf\n'), ((8963, 9014), 'tensorflow.div', 'tf.div', (['lossfunc', '(args.batch_size * args.seq_length)'], {}), '(lossfunc, args.batch_size * args.seq_length)\n', (8969, 9014), True, 'import tensorflow as tf\n'), ((9068, 9092), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (9090, 9092), True, 'import tensorflow as tf\n'), ((9357, 9387), 'tensorflow.gradients', 'tf.gradients', (['self.cost', 'tvars'], {}), '(self.cost, tvars)\n', (9369, 9387), True, 'import tensorflow as tf\n'), ((9484, 9538), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['self.gradients', 'args.grad_clip'], {}), '(self.gradients, args.grad_clip)\n', (9506, 9538), True, 'import tensorflow as tf\n'), ((9773, 9807), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', (['self.lr'], {}), '(self.lr)\n', (9798, 9807), True, 'import tensorflow as tf\n'), ((11884, 11921), 'numpy.zeros', 'np.zeros', (['(1, 1, 2)'], {'dtype': 'np.float32'}), '((1, 1, 2), dtype=np.float32)\n', (11892, 11921), True, 'import numpy as np\n'), ((12042, 12089), 'numpy.reshape', 'np.reshape', (['true_traj[traj.shape[0]]', '(1, 1, 2)'], {}), '(true_traj[traj.shape[0]], (1, 1, 2))\n', (12052, 12089), True, 'import numpy as np\n'), ((2023, 2064), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""coordinate_embedding"""'], {}), "('coordinate_embedding')\n", (2040, 2064), True, 'import tensorflow as tf\n'), ((2291, 2347), 'tensorflow.get_variable', 'tf.get_variable', (['"""embedding_w"""', '[2, args.embedding_size]'], {}), "('embedding_w', [2, args.embedding_size])\n", (2306, 2347), True, 'import tensorflow as tf\n'), ((2374, 2427), 'tensorflow.get_variable', 'tf.get_variable', (['"""embedding_b"""', '[args.embedding_size]'], {}), "('embedding_b', [args.embedding_size])\n", (2389, 2427), True, 'import tensorflow as tf\n'), ((2472, 2498), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""rnnlm"""'], {}), "('rnnlm')\n", (2489, 2498), True, 'import tensorflow as tf\n'), ((2972, 2995), 'tensorflow.squeeze', 'tf.squeeze', (['input_', '[1]'], {}), '(input_, [1])\n', (2982, 2995), True, 'import tensorflow as tf\n'), ((3729, 3750), 'tensorflow.concat', 'tf.concat', (['(1)', 'outputs'], {}), '(1, outputs)\n', (3738, 3750), True, 'import tensorflow as tf\n'), ((4898, 4912), 'tensorflow.sub', 'tf.sub', (['x', 'mux'], {}), '(x, mux)\n', (4904, 4912), True, 'import tensorflow as tf\n'), ((4933, 4947), 'tensorflow.sub', 'tf.sub', (['y', 'muy'], {}), '(y, muy)\n', (4939, 4947), True, 'import tensorflow as tf\n'), ((4997, 5011), 'tensorflow.mul', 'tf.mul', (['sx', 'sy'], {}), '(sx, sy)\n', (5003, 5011), True, 'import tensorflow as tf\n'), ((5457, 5478), 'tensorflow.div', 'tf.div', (['result', 'denom'], {}), '(result, denom)\n', (5463, 5478), True, 'import tensorflow as tf\n'), ((7634, 7656), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['result1'], {}), '(result1)\n', (7647, 7656), True, 'import tensorflow as tf\n'), ((8139, 8156), 'tensorflow.split', 'tf.split', (['(1)', '(5)', 'z'], {}), '(1, 5, z)\n', (8147, 8156), True, 'import tensorflow as tf\n'), ((8241, 8253), 'tensorflow.exp', 'tf.exp', (['z_sx'], {}), '(z_sx)\n', (8247, 8253), True, 'import tensorflow as tf\n'), ((8273, 8285), 'tensorflow.exp', 'tf.exp', (['z_sy'], {}), '(z_sy)\n', (8279, 8285), True, 'import tensorflow as tf\n'), ((8366, 8381), 'tensorflow.tanh', 'tf.tanh', (['z_corr'], {}), '(z_corr)\n', (8373, 8381), True, 'import tensorflow as tf\n'), ((11014, 11057), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean', 'cov', '(1)'], {}), '(mean, cov, 1)\n', (11043, 11057), True, 'import numpy as np\n'), ((11349, 11386), 'numpy.zeros', 'np.zeros', (['(1, 1, 2)'], {'dtype': 'np.float32'}), '((1, 1, 2), dtype=np.float32)\n', (11357, 11386), True, 'import numpy as np\n'), ((12780, 12814), 'numpy.vstack', 'np.vstack', (['(ret, [next_x, next_y])'], {}), '((ret, [next_x, next_y]))\n', (12789, 12814), True, 'import numpy as np\n'), ((5212, 5226), 'tensorflow.square', 'tf.square', (['rho'], {}), '(rho)\n', (5221, 5226), True, 'import tensorflow as tf\n'), ((5279, 5301), 'tensorflow.div', 'tf.div', (['(-z)', '(2 * negRho)'], {}), '(-z, 2 * negRho)\n', (5285, 5301), True, 'import tensorflow as tf\n'), ((2593, 2637), 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': '(0.01)'}), '(stddev=0.01)\n', (2624, 2637), True, 'import tensorflow as tf\n'), ((2733, 2762), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.01)'], {}), '(0.01)\n', (2756, 2762), True, 'import tensorflow as tf\n'), ((3270, 3295), 'tensorflow.matmul', 'tf.matmul', (['x', 'embedding_w'], {}), '(x, embedding_w)\n', (3279, 3295), True, 'import tensorflow as tf\n'), ((5383, 5398), 'tensorflow.sqrt', 'tf.sqrt', (['negRho'], {}), '(negRho)\n', (5390, 5398), True, 'import tensorflow as tf\n'), ((7426, 7454), 'tensorflow.maximum', 'tf.maximum', (['result0', 'epsilon'], {}), '(result0, epsilon)\n', (7436, 7454), True, 'import tensorflow as tf\n'), ((5085, 5102), 'tensorflow.div', 'tf.div', (['normx', 'sx'], {}), '(normx, sx)\n', (5091, 5102), True, 'import tensorflow as tf\n'), ((5116, 5133), 'tensorflow.div', 'tf.div', (['normy', 'sy'], {}), '(normy, sy)\n', (5122, 5133), True, 'import tensorflow as tf\n'), ((5158, 5178), 'tensorflow.mul', 'tf.mul', (['normx', 'normy'], {}), '(normx, normy)\n', (5164, 5178), True, 'import tensorflow as tf\n')]
|
"""
Compute distance from an arrays
"""
import tensorflow as tf
import sqlite3
import numpy as np
import time
def get_face_v(database_filename='face.db'):
scope_conn = sqlite3.connect(database_filename)
scope_cursor = scope_conn.cursor()
records = []
sql_statement = 'SELECT vector ' + ' FROM image_face_table'
scope_cursor.execute(sql_statement)
records = scope_cursor.fetchall()
return records
def bad_culute():
with tf.Graph().as_default(), tf.device('/cpu:0'):
with tf.Session() as sess:
data = tf.placeholder(tf.float32, (1248, 128), 'input')
face1 = tf.placeholder(tf.float32, (128,), 'face')
# tf.reduce_sum(data, data)
# data_t = tf.transpose(data,[1,0])
# dis = tf.sqrt(tf.reduce_sum(tf.square(data[i] - data[j]), axis=1))
_distance = tf.sqrt(tf.reduce_sum(tf.square(data - face1), 1))
begin = time.time()
face_v = get_face_v()
facev = []
for face in face_v:
# print(face)
str_list = face[0].split(',')
vector_data = list(map(lambda s: float(s), str_list))
facev.append(vector_data)
facev = np.asarray(facev)
print(facev.shape)
time_load = time.time()
print("load vector %.2f " % (time_load - begin))
init = tf.global_variables_initializer()
distances = []
for face in facev:
distance = sess.run(_distance, feed_dict={data: facev, face1: face})
distances.append(distance)
time_exe = time.time()
print("cult distance vector %.2f " % (time_exe - begin))
print(len(distances))
print(distances)
def cutlt_distance_GPU():
with tf.Graph().as_default(), tf.device('/gpu:0'):
with tf.Session() as sess:
# len = 1248
data = tf.placeholder(tf.float32, (None, 128), 'input')
x1 = tf.expand_dims(data, 0)
print(x1.shape)
len = tf.shape(x1)
print(len)
xo = tf.tile(x1, [len[1], 1, 1])
xt = tf.transpose(xo, [1, 0, 2])
_distance = tf.sqrt(tf.reduce_sum(tf.square(xo-xt), 2))
begin = time.time()
face_v = get_face_v()
facev = []
for face in face_v:
# print(face)
str_list = face[0].split(',')
vector_data = list(map(lambda s: float(s), str_list))
facev.append(vector_data)
facev = np.asarray(facev)
print(facev.shape)
time_load = time.time()
print("load vector %.2f " % (time_load - begin))
init = tf.global_variables_initializer()
distances = sess.run(_distance, feed_dict={data: facev })
time_exe = time.time()
print("cult distance vector %.2f " % (time_exe - begin))
print(distances.shape)
print(distances)
def dist(face1, face2):
distance = np.sqrt(np.sum(np.square(face1 - face2)))
# print(distance)
return distance
def cult_with_cpu():
begin = time.time()
face_v = get_face_v()
facev = []
for face in face_v:
# print(face)
str_list = face[0].split(',')
vector_data = list(map(lambda s: float(s), str_list))
facev.append(vector_data)
facev = np.asarray(facev)
print(facev.shape)
time_load = time.time()
print("load vector %.2f " % (time_load - begin))
distances = np.zeros((len(facev),len(facev)), dtype=np.float32)
print(distances.shape)
for i,face in enumerate(facev):
for k, face2 in enumerate(facev):
# distances[i][k] = dist(face, face2)
if k == i:
pass
elif k<i:
distances[i][k] = distances[k][i]
else:
distances[i][k] = dist(face, face2)
time_exe = time.time()
print("cult distance vector %.2f " % (time_exe - begin))
print(distances.shape)
# print(distances)
def cult_with_np():
begin = time.time()
face_v = get_face_v()
facev = []
for face in face_v:
# print(face)
str_list = face[0].split(',')
vector_data = list(map(lambda s: float(s), str_list))
facev.append(vector_data)
facev = np.asarray(facev)
print(facev.shape)
time_load = time.time()
print("load vector %.2f " % (time_load - begin))
distances = np.zeros((len(facev),len(facev)), dtype=np.float32)
print(distances.shape)
for i,face in enumerate(facev):
distance_l = np.linalg.norm(face - facev, axis=1)
distances[i,:] = distance_l
# for k, face2 in enumerate(facev):
# # distances[i][k] = dist(face, face2)
# if k == i:
# pass
# elif k<i:
# distances[i][k] = distances[k][i]
# else:
# distances[i][k] = dist(face, face2)
time_exe = time.time()
print("cult distance vector %.2f " % (time_exe - begin))
print(distances.shape)
print(distances)
if __name__ == '__main__':
# import timeit
# cult_with_cpu()
cult_with_np()
cutlt_distance_GPU()
|
[
"tensorflow.global_variables_initializer",
"numpy.asarray",
"tensorflow.device",
"tensorflow.Session",
"numpy.square",
"time.time",
"tensorflow.transpose",
"tensorflow.placeholder",
"tensorflow.shape",
"tensorflow.tile",
"numpy.linalg.norm",
"sqlite3.connect",
"tensorflow.Graph",
"tensorflow.square",
"tensorflow.expand_dims"
] |
[((176, 210), 'sqlite3.connect', 'sqlite3.connect', (['database_filename'], {}), '(database_filename)\n', (191, 210), False, 'import sqlite3\n'), ((3218, 3229), 'time.time', 'time.time', ([], {}), '()\n', (3227, 3229), False, 'import time\n'), ((3464, 3481), 'numpy.asarray', 'np.asarray', (['facev'], {}), '(facev)\n', (3474, 3481), True, 'import numpy as np\n'), ((3522, 3533), 'time.time', 'time.time', ([], {}), '()\n', (3531, 3533), False, 'import time\n'), ((4012, 4023), 'time.time', 'time.time', ([], {}), '()\n', (4021, 4023), False, 'import time\n'), ((4168, 4179), 'time.time', 'time.time', ([], {}), '()\n', (4177, 4179), False, 'import time\n'), ((4414, 4431), 'numpy.asarray', 'np.asarray', (['facev'], {}), '(facev)\n', (4424, 4431), True, 'import numpy as np\n'), ((4472, 4483), 'time.time', 'time.time', ([], {}), '()\n', (4481, 4483), False, 'import time\n'), ((5072, 5083), 'time.time', 'time.time', ([], {}), '()\n', (5081, 5083), False, 'import time\n'), ((482, 501), 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), "('/cpu:0')\n", (491, 501), True, 'import tensorflow as tf\n'), ((1859, 1878), 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (1868, 1878), True, 'import tensorflow as tf\n'), ((4689, 4725), 'numpy.linalg.norm', 'np.linalg.norm', (['(face - facev)'], {'axis': '(1)'}), '(face - facev, axis=1)\n', (4703, 4725), True, 'import numpy as np\n'), ((516, 528), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (526, 528), True, 'import tensorflow as tf\n'), ((557, 605), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(1248, 128)', '"""input"""'], {}), "(tf.float32, (1248, 128), 'input')\n", (571, 605), True, 'import tensorflow as tf\n'), ((626, 668), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(128,)', '"""face"""'], {}), "(tf.float32, (128,), 'face')\n", (640, 668), True, 'import tensorflow as tf\n'), ((934, 945), 'time.time', 'time.time', ([], {}), '()\n', (943, 945), False, 'import time\n'), ((1243, 1260), 'numpy.asarray', 'np.asarray', (['facev'], {}), '(facev)\n', (1253, 1260), True, 'import numpy as np\n'), ((1317, 1328), 'time.time', 'time.time', ([], {}), '()\n', (1326, 1328), False, 'import time\n'), ((1409, 1442), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1440, 1442), True, 'import tensorflow as tf\n'), ((1653, 1664), 'time.time', 'time.time', ([], {}), '()\n', (1662, 1664), False, 'import time\n'), ((1893, 1905), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1903, 1905), True, 'import tensorflow as tf\n'), ((1959, 2007), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(None, 128)', '"""input"""'], {}), "(tf.float32, (None, 128), 'input')\n", (1973, 2007), True, 'import tensorflow as tf\n'), ((2025, 2048), 'tensorflow.expand_dims', 'tf.expand_dims', (['data', '(0)'], {}), '(data, 0)\n', (2039, 2048), True, 'import tensorflow as tf\n'), ((2095, 2107), 'tensorflow.shape', 'tf.shape', (['x1'], {}), '(x1)\n', (2103, 2107), True, 'import tensorflow as tf\n'), ((2148, 2175), 'tensorflow.tile', 'tf.tile', (['x1', '[len[1], 1, 1]'], {}), '(x1, [len[1], 1, 1])\n', (2155, 2175), True, 'import tensorflow as tf\n'), ((2193, 2220), 'tensorflow.transpose', 'tf.transpose', (['xo', '[1, 0, 2]'], {}), '(xo, [1, 0, 2])\n', (2205, 2220), True, 'import tensorflow as tf\n'), ((2311, 2322), 'time.time', 'time.time', ([], {}), '()\n', (2320, 2322), False, 'import time\n'), ((2620, 2637), 'numpy.asarray', 'np.asarray', (['facev'], {}), '(facev)\n', (2630, 2637), True, 'import numpy as np\n'), ((2694, 2705), 'time.time', 'time.time', ([], {}), '()\n', (2703, 2705), False, 'import time\n'), ((2786, 2819), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2817, 2819), True, 'import tensorflow as tf\n'), ((2915, 2926), 'time.time', 'time.time', ([], {}), '()\n', (2924, 2926), False, 'import time\n'), ((3115, 3139), 'numpy.square', 'np.square', (['(face1 - face2)'], {}), '(face1 - face2)\n', (3124, 3139), True, 'import numpy as np\n'), ((457, 467), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (465, 467), True, 'import tensorflow as tf\n'), ((1834, 1844), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1842, 1844), True, 'import tensorflow as tf\n'), ((884, 907), 'tensorflow.square', 'tf.square', (['(data - face1)'], {}), '(data - face1)\n', (893, 907), True, 'import tensorflow as tf\n'), ((2268, 2286), 'tensorflow.square', 'tf.square', (['(xo - xt)'], {}), '(xo - xt)\n', (2277, 2286), True, 'import tensorflow as tf\n')]
|
import os, sys
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
import torch
import torchvision
# 1. Architecture
from net_module.net import ConvMultiHypoNet, ConvMixtureDensityNet
# 2. Training manager
from network_manager import NetworkManager
# 3. Data handler
from data_handle import data_handler_zip as dh
from util import utils_test
from util import utils_yaml
from util import zfilter
print("Program: animation\n")
### Config file name
# config_file = 'mdn_20_test.yml'
config_file = 'ewta_20_test.yml'
### Load parameters and define paths
root_dir = Path(__file__).parents[1]
param_path = os.path.join(root_dir, 'Config/', config_file)
param = utils_yaml.from_yaml(param_path)
param['device'] = 'cuda' # cuda or multi
model_path = os.path.join(root_dir, param['model_path'])
zip_path = os.path.join(root_dir, param['zip_path'])
csv_path = os.path.join(param['data_name'], param['label_csv'])
data_dir = param['data_name']
print("Save to", model_path)
### Visualization option
idx_start = 0
idx_end = 786
pause_time = 0.1
### Prepare data
composed = torchvision.transforms.Compose([dh.ToTensor()])
dataset = dh.ImageStackDataset(zip_path, csv_path, data_dir, channel_per_image=param['cpi'], transform=composed, T_channel=param['with_T'])
print("Data prepared. #Samples:{}.".format(len(dataset)))
print('Sample: {\'image\':',dataset[0]['image'].shape,'\'label\':',dataset[0]['label'],'}')
### Initialize the model
net = ConvMultiHypoNet(param['input_channel'], param['dim_out'], param['fc_input'], num_components=param['num_components'])
# net = ConvMixtureDensityNet(param['input_channel'], param['dim_out'], param['fc_input'], num_components=param['num_components'])
myNet = NetworkManager(net, loss_function_dict={}, verbose=False, device=param['device'])
myNet.build_Network()
myNet.model.load_state_dict(torch.load(model_path))
myNet.model.eval() # with BN layer, must run eval first
### Visualize
fig, ax = plt.subplots()
idc = np.linspace(idx_start,idx_end,num=idx_end-idx_start).astype('int')
for idx in idc:
plt.cla()
img = dataset[idx]['image']
traj = np.array(dataset[idx]['traj'])
hyposM = myNet.inference(img) # for WTA
# alpha, mu, sigma = myNet.inference(img, mdn=True) # for MDN
### Kalman filter ###
X0 = np.array([[traj[0,0], traj[0,1], 0, 0]]).transpose()
kf_model = zfilter.model_CV(X0, Ts=1)
P0 = zfilter.fill_diag((1,1,1,1))
Q = zfilter.fill_diag((0.1,0.1,0.1,0.1))
R = zfilter.fill_diag((0.1,0.1))
KF = zfilter.KalmanFilter(kf_model, P0, Q, R)
Y = [np.array(traj[1,:]), np.array(traj[2,:]),
np.array(traj[3,:]), np.array(traj[4,:])]
for kf_i in range(len(Y) + dataset.T):
if kf_i<len(Y):
KF.one_step(np.array([[0]]), np.array(Y[kf_i]).reshape(2,1))
else:
KF.predict(np.array([[0]]), evolve_P=False)
KF.append_state(KF.X)
### ------------- ###
hypos_clusters = utils_test.fit_DBSCAN(hyposM[0], eps=0.5, min_sample=3) # DBSCAN
mu_list, std_list = utils_test.fit_cluster2gaussian(hypos_clusters) # Gaussian fitting
utils_test.plot_Gaussian_ellipses(ax, mu_list, std_list)
# utils_test.plot_parzen_distribution(ax, hyposM[0,:,:])
utils_test.plot_on_simmap(ax, dataset[idx], hyposM[0,:,:])
# utils_test.plot_on_simmap(ax, dataset[idx], None)
# utils_test.plot_mdn_output(ax, alpha, mu, sigma)
for i, hc in enumerate(hypos_clusters):
ax.scatter(hc[:,0], hc[:,1], marker='x', label=f"est{i+1}")
plt.plot(KF.X[0], KF.X[1], 'mo', label='KF')
ax.add_patch(patches.Ellipse(KF.X[:2], 3*KF.P[0,0], 3*KF.P[1,1], fc='g', zorder=0))
plt.xlabel("x [m]", fontsize=14)
plt.ylabel("y [m]", fontsize=14)
plt.legend()
ax.axis('equal')
plt.legend(prop={'size': 14}, loc='upper right')
if idx == idc[-1]:
plt.text(5,5,'Done!',fontsize=20)
if pause_time == 0:
plt.pause(0.1)
input()
else:
plt.pause(pause_time)
plt.show()
|
[
"util.utils_test.fit_DBSCAN",
"pathlib.Path",
"network_manager.NetworkManager",
"os.path.join",
"torch.load",
"data_handle.data_handler_zip.ToTensor",
"matplotlib.pyplot.cla",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"data_handle.data_handler_zip.ImageStackDataset",
"util.utils_test.fit_cluster2gaussian",
"matplotlib.pyplot.text",
"util.utils_test.plot_on_simmap",
"util.zfilter.fill_diag",
"matplotlib.pyplot.ylabel",
"matplotlib.patches.Ellipse",
"net_module.net.ConvMultiHypoNet",
"matplotlib.pyplot.plot",
"util.utils_test.plot_Gaussian_ellipses",
"util.utils_yaml.from_yaml",
"numpy.array",
"util.zfilter.KalmanFilter",
"matplotlib.pyplot.xlabel",
"util.zfilter.model_CV"
] |
[((662, 708), 'os.path.join', 'os.path.join', (['root_dir', '"""Config/"""', 'config_file'], {}), "(root_dir, 'Config/', config_file)\n", (674, 708), False, 'import os, sys\n'), ((717, 749), 'util.utils_yaml.from_yaml', 'utils_yaml.from_yaml', (['param_path'], {}), '(param_path)\n', (737, 749), False, 'from util import utils_yaml\n'), ((805, 848), 'os.path.join', 'os.path.join', (['root_dir', "param['model_path']"], {}), "(root_dir, param['model_path'])\n", (817, 848), False, 'import os, sys\n'), ((862, 903), 'os.path.join', 'os.path.join', (['root_dir', "param['zip_path']"], {}), "(root_dir, param['zip_path'])\n", (874, 903), False, 'import os, sys\n'), ((916, 968), 'os.path.join', 'os.path.join', (["param['data_name']", "param['label_csv']"], {}), "(param['data_name'], param['label_csv'])\n", (928, 968), False, 'import os, sys\n'), ((1187, 1321), 'data_handle.data_handler_zip.ImageStackDataset', 'dh.ImageStackDataset', (['zip_path', 'csv_path', 'data_dir'], {'channel_per_image': "param['cpi']", 'transform': 'composed', 'T_channel': "param['with_T']"}), "(zip_path, csv_path, data_dir, channel_per_image=param[\n 'cpi'], transform=composed, T_channel=param['with_T'])\n", (1207, 1321), True, 'from data_handle import data_handler_zip as dh\n'), ((1499, 1621), 'net_module.net.ConvMultiHypoNet', 'ConvMultiHypoNet', (["param['input_channel']", "param['dim_out']", "param['fc_input']"], {'num_components': "param['num_components']"}), "(param['input_channel'], param['dim_out'], param['fc_input'\n ], num_components=param['num_components'])\n", (1515, 1621), False, 'from net_module.net import ConvMultiHypoNet, ConvMixtureDensityNet\n'), ((1756, 1842), 'network_manager.NetworkManager', 'NetworkManager', (['net'], {'loss_function_dict': '{}', 'verbose': '(False)', 'device': "param['device']"}), "(net, loss_function_dict={}, verbose=False, device=param[\n 'device'])\n", (1770, 1842), False, 'from network_manager import NetworkManager\n'), ((1993, 2007), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2005, 2007), True, 'import matplotlib.pyplot as plt\n'), ((4045, 4055), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4053, 4055), True, 'import matplotlib.pyplot as plt\n'), ((1888, 1910), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (1898, 1910), False, 'import torch\n'), ((2102, 2111), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (2109, 2111), True, 'import matplotlib.pyplot as plt\n'), ((2165, 2195), 'numpy.array', 'np.array', (["dataset[idx]['traj']"], {}), "(dataset[idx]['traj'])\n", (2173, 2195), True, 'import numpy as np\n'), ((2410, 2436), 'util.zfilter.model_CV', 'zfilter.model_CV', (['X0'], {'Ts': '(1)'}), '(X0, Ts=1)\n', (2426, 2436), False, 'from util import zfilter\n'), ((2446, 2477), 'util.zfilter.fill_diag', 'zfilter.fill_diag', (['(1, 1, 1, 1)'], {}), '((1, 1, 1, 1))\n', (2463, 2477), False, 'from util import zfilter\n'), ((2484, 2523), 'util.zfilter.fill_diag', 'zfilter.fill_diag', (['(0.1, 0.1, 0.1, 0.1)'], {}), '((0.1, 0.1, 0.1, 0.1))\n', (2501, 2523), False, 'from util import zfilter\n'), ((2530, 2559), 'util.zfilter.fill_diag', 'zfilter.fill_diag', (['(0.1, 0.1)'], {}), '((0.1, 0.1))\n', (2547, 2559), False, 'from util import zfilter\n'), ((2568, 2608), 'util.zfilter.KalmanFilter', 'zfilter.KalmanFilter', (['kf_model', 'P0', 'Q', 'R'], {}), '(kf_model, P0, Q, R)\n', (2588, 2608), False, 'from util import zfilter\n'), ((3004, 3059), 'util.utils_test.fit_DBSCAN', 'utils_test.fit_DBSCAN', (['hyposM[0]'], {'eps': '(0.5)', 'min_sample': '(3)'}), '(hyposM[0], eps=0.5, min_sample=3)\n', (3025, 3059), False, 'from util import utils_test\n'), ((3093, 3140), 'util.utils_test.fit_cluster2gaussian', 'utils_test.fit_cluster2gaussian', (['hypos_clusters'], {}), '(hypos_clusters)\n', (3124, 3140), False, 'from util import utils_test\n'), ((3165, 3221), 'util.utils_test.plot_Gaussian_ellipses', 'utils_test.plot_Gaussian_ellipses', (['ax', 'mu_list', 'std_list'], {}), '(ax, mu_list, std_list)\n', (3198, 3221), False, 'from util import utils_test\n'), ((3287, 3347), 'util.utils_test.plot_on_simmap', 'utils_test.plot_on_simmap', (['ax', 'dataset[idx]', 'hyposM[0, :, :]'], {}), '(ax, dataset[idx], hyposM[0, :, :])\n', (3312, 3347), False, 'from util import utils_test\n'), ((3576, 3620), 'matplotlib.pyplot.plot', 'plt.plot', (['KF.X[0]', 'KF.X[1]', '"""mo"""'], {'label': '"""KF"""'}), "(KF.X[0], KF.X[1], 'mo', label='KF')\n", (3584, 3620), True, 'import matplotlib.pyplot as plt\n'), ((3714, 3746), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x [m]"""'], {'fontsize': '(14)'}), "('x [m]', fontsize=14)\n", (3724, 3746), True, 'import matplotlib.pyplot as plt\n'), ((3751, 3783), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y [m]"""'], {'fontsize': '(14)'}), "('y [m]', fontsize=14)\n", (3761, 3783), True, 'import matplotlib.pyplot as plt\n'), ((3788, 3800), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3798, 3800), True, 'import matplotlib.pyplot as plt\n'), ((3826, 3874), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'prop': "{'size': 14}", 'loc': '"""upper right"""'}), "(prop={'size': 14}, loc='upper right')\n", (3836, 3874), True, 'import matplotlib.pyplot as plt\n'), ((623, 637), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (627, 637), False, 'from pathlib import Path\n'), ((1161, 1174), 'data_handle.data_handler_zip.ToTensor', 'dh.ToTensor', ([], {}), '()\n', (1172, 1174), True, 'from data_handle import data_handler_zip as dh\n'), ((2014, 2070), 'numpy.linspace', 'np.linspace', (['idx_start', 'idx_end'], {'num': '(idx_end - idx_start)'}), '(idx_start, idx_end, num=idx_end - idx_start)\n', (2025, 2070), True, 'import numpy as np\n'), ((2618, 2638), 'numpy.array', 'np.array', (['traj[1, :]'], {}), '(traj[1, :])\n', (2626, 2638), True, 'import numpy as np\n'), ((2639, 2659), 'numpy.array', 'np.array', (['traj[2, :]'], {}), '(traj[2, :])\n', (2647, 2659), True, 'import numpy as np\n'), ((2670, 2690), 'numpy.array', 'np.array', (['traj[3, :]'], {}), '(traj[3, :])\n', (2678, 2690), True, 'import numpy as np\n'), ((2691, 2711), 'numpy.array', 'np.array', (['traj[4, :]'], {}), '(traj[4, :])\n', (2699, 2711), True, 'import numpy as np\n'), ((3638, 3713), 'matplotlib.patches.Ellipse', 'patches.Ellipse', (['KF.X[:2]', '(3 * KF.P[0, 0])', '(3 * KF.P[1, 1])'], {'fc': '"""g"""', 'zorder': '(0)'}), "(KF.X[:2], 3 * KF.P[0, 0], 3 * KF.P[1, 1], fc='g', zorder=0)\n", (3653, 3713), False, 'from matplotlib import patches\n'), ((3907, 3943), 'matplotlib.pyplot.text', 'plt.text', (['(5)', '(5)', '"""Done!"""'], {'fontsize': '(20)'}), "(5, 5, 'Done!', fontsize=20)\n", (3915, 3943), True, 'import matplotlib.pyplot as plt\n'), ((3973, 3987), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (3982, 3987), True, 'import matplotlib.pyplot as plt\n'), ((4022, 4043), 'matplotlib.pyplot.pause', 'plt.pause', (['pause_time'], {}), '(pause_time)\n', (4031, 4043), True, 'import matplotlib.pyplot as plt\n'), ((2342, 2384), 'numpy.array', 'np.array', (['[[traj[0, 0], traj[0, 1], 0, 0]]'], {}), '([[traj[0, 0], traj[0, 1], 0, 0]])\n', (2350, 2384), True, 'import numpy as np\n'), ((2803, 2818), 'numpy.array', 'np.array', (['[[0]]'], {}), '([[0]])\n', (2811, 2818), True, 'import numpy as np\n'), ((2889, 2904), 'numpy.array', 'np.array', (['[[0]]'], {}), '([[0]])\n', (2897, 2904), True, 'import numpy as np\n'), ((2820, 2837), 'numpy.array', 'np.array', (['Y[kf_i]'], {}), '(Y[kf_i])\n', (2828, 2837), True, 'import numpy as np\n')]
|
import math
import numpy as np
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import shapely
def array_minmax(x):
mn = np.min(x)
mx = np.max(x)
md = (mn + mx)/2.0
(mn,mx) = ((mn-md)*1.2+md, (mx-md)*1.2+md)
return (mn, mx)
def create_samples(count, uv_poly):
print(uv_poly)
#polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
a = [(uv_poly[i,0], uv_poly[i,1]) for i in range(uv_poly.shape[0])]
print(a)
polygon = Polygon(a)
print(polygon)
x0,x1 = array_minmax(uv_poly[:,0])
y0,y1 = array_minmax(uv_poly[:,1])
GRID_FR = 0.1/10
meshgridx, meshgridy = np.meshgrid(
np.arange(x0,x1, (x1-x0)*GRID_FR),
np.arange(y0,y1, (y1-y0)*GRID_FR),
)
print(meshgridx.shape)
print(meshgridy.shape)
grid_xy = np.array([meshgridx.ravel(), meshgridy.ravel()]).T
print(grid_xy.shape)
print(polygon.within(Point(0,0)))
print(polygon.contains(Point(0,0)))
#print(polygon.contains(grid_xy))
#print(polygon.contains([(uv_poly[i,0], uv_poly[i,1]) for i in range(uv_poly.shape[0])]))
# TBC
#Shapely.
#shapely.
points = [Point(grid_xy[i,0], grid_xy[i,1]) for i in range(grid_xy.shape[0])]
#polygon.within(points)
which = [polygon.contains(Point(grid_xy[i,0], grid_xy[i,1])) for i in range(grid_xy.shape[0])]
return grid_xy[which,:]
def create_master_grid(xa, ya):
#GRID_FR = 0.1 * 0.5 # *0.1
meshgridx0, meshgridy0 = np.meshgrid(xa, ya)
grid_xy0 = np.array([meshgridx0.ravel(), meshgridy0.ravel()]).T
return grid_xy0
master_grids = {}
class G:
def __init__(self):
#self.__x = x
pass
def init_grid(key, GRID_FR):
#GRID_FR = 0.1 * 0.5 # *0.1
obj = G() #{}
xa = np.arange(0,1.0, 1.0*GRID_FR)
ya = np.arange(0,1.0, 1.0*GRID_FR)
obj.grid_xy0 = create_master_grid(xa,ya)
master_grids[key] = obj
def create_samples_region(uv, region, grid_xy0):
#return create_samples(count, uv[region,:])
# const
uv_poly = uv[region,:]
a = [(uv_poly[i,0], uv_poly[i,1]) for i in range(uv_poly.shape[0])]
polygon = Polygon(a)
x0,x1 = array_minmax(uv_poly[:,0])
y0,y1 = array_minmax(uv_poly[:,1])
grid_xy = grid_xy0.copy()
grid_xy[:,0] = grid_xy0[:,0]*(x1-x0)+x0
grid_xy[:,1] = grid_xy0[:,1]*(y1-y0)+y0
# meshgridy = meshgridx0*(x1-x0)+x0
which = [polygon.contains(Point(grid_xy[i,0], grid_xy[i,1])) for i in range(grid_xy.shape[0])]
return grid_xy[which,:]
def poly_region_points(uv, regions):
KEY = '0'
grid_xy0 = master_grids[KEY].grid_xy0
l = []
for i in range(len(regions)):
region_xy = create_samples_region(uv, regions[i], grid_xy0)
l.append(region_xy)
gxy = np.concatenate(l, axis=0)
plot_scatter_uv(gxy)
return gxy
def sample_poly_region(uv, regions, texture):
poly_region_points
exit()
def create_samples_region1(uv, region, grid_xy0):
uv_poly = uv[region,:]
a = [(uv_poly[i,0], uv_poly[i,1]) for i in range(uv_poly.shape[0])]
a = filter(lambda t: not math.isnan(t[0]), a)
# What to do if it is partially outside?
polygon = Polygon(a)
x0,x1 = array_minmax(uv_poly[:,0])
y0,y1 = array_minmax(uv_poly[:,1])
grid_xy = grid_xy0.copy()
grid_xy[:,0] = grid_xy0[:,0]*(x1-x0)+x0
grid_xy[:,1] = grid_xy0[:,1]*(y1-y0)+y0
# meshgridy = meshgridx0*(x1-x0)+x0
which = [polygon.contains(Point(grid_xy[i,0], grid_xy[i,1])) for i in range(grid_xy.shape[0])]
return grid_xy[which,:]
import os
def sample_colors_polygons(uv, regions, texture):
xa = np.arange(0, texture.shape[0], 1.0)
ya = np.arange(0, texture.shape[1], 1.0)
grid_xy0 = create_master_grid(xa,ya)
print('len(regions)', len(regions))
l = []
for i in range(len(regions)):
print('i', i, flush=True)
region_xy = create_samples_region1(uv, regions[i], grid_xy0)
print('>>>i', i, flush=True)
print(region_xy)
l.append(region_xy)
plot_scatter_uv(l[-1], False)
plt.show()
dfgdkj
exit()
# poly_region_points(uv, regions)
def plot_scatter_uv(xy, show=True):
import matplotlib.pyplot as plt
plt.plot(xy[:,0], xy[:, 1], '.')
if show:
plt.show()
def run_tests():
GRID_FR = 0.1 * 0.5 # *0.1
init_grid('0', GRID_FR)
KEY = '0'
grid_xy0 = master_grids[KEY].grid_xy0
#import image_loader
#image_loader.load_image_withsize
uv = np.array([[0,1],[0.4,0.8],[0.8, 0.5],[1,0.3],[0,-1],[-1,0],[-0.3,0.3]])
assert uv.shape[1] == 2
xy = create_samples_region(uv, [0,1,2,3,4,5,6], grid_xy0)
plot_scatter_uv(xy)
print(xy)
print(xy.shape) # 34 points
# 3208 / 10000
# test 2
import image_loader
BLUE_FLOWER = "../art/256px-Bachelor's_button,_Basket_flower,_Boutonniere_flower,_Cornflower_-_3.jpeg"
texture1, physical_size1, dpi1 = image_loader.load_image_withsize(BLUE_FLOWER,
sample_px=200, sample_cm=10.0)
uv = np.random.rand(*(100,2))*100
regions = [[0,1,2,3], [3,4,6,7], [5,6,7,8,9]]
test1_points = poly_region_points(uv, regions)
rgba = sample_poly_region(uv, regions, texture1)
print(rgba)
if __name__ == "__main__":
run_tests()
|
[
"shapely.geometry.Point",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"math.isnan",
"matplotlib.pyplot.plot",
"numpy.min",
"numpy.max",
"numpy.arange",
"shapely.geometry.polygon.Polygon",
"numpy.array",
"numpy.random.rand",
"image_loader.load_image_withsize",
"numpy.concatenate"
] |
[((158, 167), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (164, 167), True, 'import numpy as np\n'), ((177, 186), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (183, 186), True, 'import numpy as np\n'), ((489, 499), 'shapely.geometry.polygon.Polygon', 'Polygon', (['a'], {}), '(a)\n', (496, 499), False, 'from shapely.geometry.polygon import Polygon\n'), ((1466, 1485), 'numpy.meshgrid', 'np.meshgrid', (['xa', 'ya'], {}), '(xa, ya)\n', (1477, 1485), True, 'import numpy as np\n'), ((1737, 1769), 'numpy.arange', 'np.arange', (['(0)', '(1.0)', '(1.0 * GRID_FR)'], {}), '(0, 1.0, 1.0 * GRID_FR)\n', (1746, 1769), True, 'import numpy as np\n'), ((1774, 1806), 'numpy.arange', 'np.arange', (['(0)', '(1.0)', '(1.0 * GRID_FR)'], {}), '(0, 1.0, 1.0 * GRID_FR)\n', (1783, 1806), True, 'import numpy as np\n'), ((2096, 2106), 'shapely.geometry.polygon.Polygon', 'Polygon', (['a'], {}), '(a)\n', (2103, 2106), False, 'from shapely.geometry.polygon import Polygon\n'), ((2701, 2726), 'numpy.concatenate', 'np.concatenate', (['l'], {'axis': '(0)'}), '(l, axis=0)\n', (2715, 2726), True, 'import numpy as np\n'), ((3100, 3110), 'shapely.geometry.polygon.Polygon', 'Polygon', (['a'], {}), '(a)\n', (3107, 3110), False, 'from shapely.geometry.polygon import Polygon\n'), ((3546, 3581), 'numpy.arange', 'np.arange', (['(0)', 'texture.shape[0]', '(1.0)'], {}), '(0, texture.shape[0], 1.0)\n', (3555, 3581), True, 'import numpy as np\n'), ((3589, 3624), 'numpy.arange', 'np.arange', (['(0)', 'texture.shape[1]', '(1.0)'], {}), '(0, texture.shape[1], 1.0)\n', (3598, 3624), True, 'import numpy as np\n'), ((3953, 3963), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3961, 3963), True, 'import matplotlib.pyplot as plt\n'), ((4098, 4131), 'matplotlib.pyplot.plot', 'plt.plot', (['xy[:, 0]', 'xy[:, 1]', '"""."""'], {}), "(xy[:, 0], xy[:, 1], '.')\n", (4106, 4131), True, 'import matplotlib.pyplot as plt\n'), ((4350, 4437), 'numpy.array', 'np.array', (['[[0, 1], [0.4, 0.8], [0.8, 0.5], [1, 0.3], [0, -1], [-1, 0], [-0.3, 0.3]]'], {}), '([[0, 1], [0.4, 0.8], [0.8, 0.5], [1, 0.3], [0, -1], [-1, 0], [-0.3,\n 0.3]])\n', (4358, 4437), True, 'import numpy as np\n'), ((4763, 4839), 'image_loader.load_image_withsize', 'image_loader.load_image_withsize', (['BLUE_FLOWER'], {'sample_px': '(200)', 'sample_cm': '(10.0)'}), '(BLUE_FLOWER, sample_px=200, sample_cm=10.0)\n', (4795, 4839), False, 'import image_loader\n'), ((664, 702), 'numpy.arange', 'np.arange', (['x0', 'x1', '((x1 - x0) * GRID_FR)'], {}), '(x0, x1, (x1 - x0) * GRID_FR)\n', (673, 702), True, 'import numpy as np\n'), ((705, 743), 'numpy.arange', 'np.arange', (['y0', 'y1', '((y1 - y0) * GRID_FR)'], {}), '(y0, y1, (y1 - y0) * GRID_FR)\n', (714, 743), True, 'import numpy as np\n'), ((1152, 1187), 'shapely.geometry.Point', 'Point', (['grid_xy[i, 0]', 'grid_xy[i, 1]'], {}), '(grid_xy[i, 0], grid_xy[i, 1])\n', (1157, 1187), False, 'from shapely.geometry import Point\n'), ((4146, 4156), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4154, 4156), True, 'import matplotlib.pyplot as plt\n'), ((4854, 4879), 'numpy.random.rand', 'np.random.rand', (['*(100, 2)'], {}), '(*(100, 2))\n', (4868, 4879), True, 'import numpy as np\n'), ((915, 926), 'shapely.geometry.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (920, 926), False, 'from shapely.geometry import Point\n'), ((955, 966), 'shapely.geometry.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (960, 966), False, 'from shapely.geometry import Point\n'), ((1278, 1313), 'shapely.geometry.Point', 'Point', (['grid_xy[i, 0]', 'grid_xy[i, 1]'], {}), '(grid_xy[i, 0], grid_xy[i, 1])\n', (1283, 1313), False, 'from shapely.geometry import Point\n'), ((2376, 2411), 'shapely.geometry.Point', 'Point', (['grid_xy[i, 0]', 'grid_xy[i, 1]'], {}), '(grid_xy[i, 0], grid_xy[i, 1])\n', (2381, 2411), False, 'from shapely.geometry import Point\n'), ((3380, 3415), 'shapely.geometry.Point', 'Point', (['grid_xy[i, 0]', 'grid_xy[i, 1]'], {}), '(grid_xy[i, 0], grid_xy[i, 1])\n', (3385, 3415), False, 'from shapely.geometry import Point\n'), ((3019, 3035), 'math.isnan', 'math.isnan', (['t[0]'], {}), '(t[0])\n', (3029, 3035), False, 'import math\n')]
|
# coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tf_agents.policies.eager_tf_policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import parameterized
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.agents.ddpg import actor_network
from tf_agents.environments import random_py_environment
from tf_agents.policies import actor_policy
from tf_agents.policies import policy_saver
from tf_agents.policies import py_tf_eager_policy
from tf_agents.policies import random_tf_policy
from tf_agents.specs import array_spec
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.utils import common
from tf_agents.utils import nest_utils
from tf_agents.utils import test_utils
class PyTFEagerPolicyTest(test_utils.TestCase):
def testPyEnvCompatible(self):
if not common.has_eager_been_enabled():
self.skipTest('Only supported in eager.')
observation_spec = array_spec.ArraySpec([2], np.float32)
action_spec = array_spec.BoundedArraySpec([1], np.float32, 2, 3)
observation_tensor_spec = tensor_spec.from_spec(observation_spec)
action_tensor_spec = tensor_spec.from_spec(action_spec)
time_step_tensor_spec = ts.time_step_spec(observation_tensor_spec)
actor_net = actor_network.ActorNetwork(
observation_tensor_spec,
action_tensor_spec,
fc_layer_params=(10,),
)
tf_policy = actor_policy.ActorPolicy(
time_step_tensor_spec, action_tensor_spec, actor_network=actor_net)
py_policy = py_tf_eager_policy.PyTFEagerPolicy(tf_policy)
# Env will validate action types automaticall since we provided the
# action_spec.
env = random_py_environment.RandomPyEnvironment(observation_spec,
action_spec)
time_step = env.reset()
for _ in range(100):
action_step = py_policy.action(time_step)
time_step = env.step(action_step.action)
def testRandomTFPolicyCompatibility(self):
if not common.has_eager_been_enabled():
self.skipTest('Only supported in eager.')
observation_spec = array_spec.ArraySpec([2], np.float32)
action_spec = array_spec.BoundedArraySpec([1], np.float32, 2, 3)
info_spec = {
'a': array_spec.BoundedArraySpec([1], np.float32, 0, 1),
'b': array_spec.BoundedArraySpec([1], np.float32, 100, 101)
}
observation_tensor_spec = tensor_spec.from_spec(observation_spec)
action_tensor_spec = tensor_spec.from_spec(action_spec)
info_tensor_spec = tensor_spec.from_spec(info_spec)
time_step_tensor_spec = ts.time_step_spec(observation_tensor_spec)
tf_policy = random_tf_policy.RandomTFPolicy(
time_step_tensor_spec, action_tensor_spec, info_spec=info_tensor_spec)
py_policy = py_tf_eager_policy.PyTFEagerPolicy(tf_policy)
env = random_py_environment.RandomPyEnvironment(observation_spec,
action_spec)
time_step = env.reset()
def _check_action_step(action_step):
self.assertIsInstance(action_step.action, np.ndarray)
self.assertEqual(action_step.action.shape, (1,))
self.assertBetween(action_step.action[0], 2.0, 3.0)
self.assertIsInstance(action_step.info['a'], np.ndarray)
self.assertEqual(action_step.info['a'].shape, (1,))
self.assertBetween(action_step.info['a'][0], 0.0, 1.0)
self.assertIsInstance(action_step.info['b'], np.ndarray)
self.assertEqual(action_step.info['b'].shape, (1,))
self.assertBetween(action_step.info['b'][0], 100.0, 101.0)
for _ in range(100):
action_step = py_policy.action(time_step)
_check_action_step(action_step)
time_step = env.step(action_step.action)
class SavedModelPYTFEagerPolicyTest(test_utils.TestCase,
parameterized.TestCase):
def setUp(self):
super(SavedModelPYTFEagerPolicyTest, self).setUp()
if not common.has_eager_been_enabled():
self.skipTest('Only supported in eager.')
observation_spec = array_spec.ArraySpec([2], np.float32)
self.action_spec = array_spec.BoundedArraySpec([1], np.float32, 2, 3)
self.time_step_spec = ts.time_step_spec(observation_spec)
observation_tensor_spec = tensor_spec.from_spec(observation_spec)
action_tensor_spec = tensor_spec.from_spec(self.action_spec)
time_step_tensor_spec = tensor_spec.from_spec(self.time_step_spec)
actor_net = actor_network.ActorNetwork(
observation_tensor_spec,
action_tensor_spec,
fc_layer_params=(10,),
)
self.tf_policy = actor_policy.ActorPolicy(
time_step_tensor_spec, action_tensor_spec, actor_network=actor_net)
def testSavedModel(self):
path = os.path.join(self.get_temp_dir(), 'saved_policy')
saver = policy_saver.PolicySaver(self.tf_policy)
saver.save(path)
eager_py_policy = py_tf_eager_policy.SavedModelPyTFEagerPolicy(
path, self.time_step_spec, self.action_spec)
rng = np.random.RandomState()
sample_time_step = array_spec.sample_spec_nest(self.time_step_spec, rng)
batched_sample_time_step = nest_utils.batch_nested_array(sample_time_step)
original_action = self.tf_policy.action(batched_sample_time_step)
unbatched_original_action = nest_utils.unbatch_nested_tensors(
original_action)
original_action_np = tf.nest.map_structure(lambda t: t.numpy(),
unbatched_original_action)
saved_policy_action = eager_py_policy.action(sample_time_step)
tf.nest.assert_same_structure(saved_policy_action.action, self.action_spec)
np.testing.assert_array_almost_equal(original_action_np.action,
saved_policy_action.action)
@parameterized.parameters(None, 0, 100, 200000)
def testGetTrainStep(self, train_step):
path = os.path.join(self.get_temp_dir(), 'saved_policy')
if train_step is None:
# Use the default argument, which should set the train step to be -1.
saver = policy_saver.PolicySaver(self.tf_policy)
expected_train_step = -1
else:
saver = policy_saver.PolicySaver(
self.tf_policy, train_step=tf.constant(train_step))
expected_train_step = train_step
saver.save(path)
eager_py_policy = py_tf_eager_policy.SavedModelPyTFEagerPolicy(
path, self.time_step_spec, self.action_spec)
self.assertEqual(expected_train_step, eager_py_policy.get_train_step())
def testUpdateFromCheckpoint(self):
path = os.path.join(self.get_temp_dir(), 'saved_policy')
saver = policy_saver.PolicySaver(self.tf_policy)
saver.save(path)
self.evaluate(
tf.nest.map_structure(lambda v: v.assign(v * 0 + -1),
self.tf_policy.variables()))
checkpoint_path = os.path.join(self.get_temp_dir(), 'checkpoint')
saver.save_checkpoint(checkpoint_path)
eager_py_policy = py_tf_eager_policy.SavedModelPyTFEagerPolicy(
path, self.time_step_spec, self.action_spec)
# Use evaluate to force a copy.
saved_model_variables = self.evaluate(eager_py_policy.variables())
checkpoint = tf.train.Checkpoint(policy=eager_py_policy._policy)
manager = tf.train.CheckpointManager(
checkpoint, directory=checkpoint_path, max_to_keep=None)
eager_py_policy.update_from_checkpoint(manager.latest_checkpoint)
assert_np_not_equal = lambda a, b: self.assertFalse(np.equal(a, b).all())
tf.nest.map_structure(assert_np_not_equal, saved_model_variables,
self.evaluate(eager_py_policy.variables()))
assert_np_all_equal = lambda a, b: self.assertTrue(np.equal(a, b).all())
tf.nest.map_structure(assert_np_all_equal,
self.evaluate(self.tf_policy.variables()),
self.evaluate(eager_py_policy.variables()))
def testInferenceFromCheckpoint(self):
path = os.path.join(self.get_temp_dir(), 'saved_policy')
saver = policy_saver.PolicySaver(self.tf_policy)
saver.save(path)
rng = np.random.RandomState()
sample_time_step = array_spec.sample_spec_nest(self.time_step_spec, rng)
batched_sample_time_step = nest_utils.batch_nested_array(sample_time_step)
self.evaluate(
tf.nest.map_structure(lambda v: v.assign(v * 0 + -1),
self.tf_policy.variables()))
checkpoint_path = os.path.join(self.get_temp_dir(), 'checkpoint')
saver.save_checkpoint(checkpoint_path)
eager_py_policy = py_tf_eager_policy.SavedModelPyTFEagerPolicy(
path, self.time_step_spec, self.action_spec)
# Use evaluate to force a copy.
saved_model_variables = self.evaluate(eager_py_policy.variables())
checkpoint = tf.train.Checkpoint(policy=eager_py_policy._policy)
manager = tf.train.CheckpointManager(
checkpoint, directory=checkpoint_path, max_to_keep=None)
eager_py_policy.update_from_checkpoint(manager.latest_checkpoint)
assert_np_not_equal = lambda a, b: self.assertFalse(np.equal(a, b).all())
tf.nest.map_structure(assert_np_not_equal, saved_model_variables,
self.evaluate(eager_py_policy.variables()))
assert_np_all_equal = lambda a, b: self.assertTrue(np.equal(a, b).all())
tf.nest.map_structure(assert_np_all_equal,
self.evaluate(self.tf_policy.variables()),
self.evaluate(eager_py_policy.variables()))
# Can't check if the action is different as in some cases depending on
# variable initialization it will be the same. Checking that they are at
# least always the same.
checkpoint_action = eager_py_policy.action(sample_time_step)
current_policy_action = self.tf_policy.action(batched_sample_time_step)
current_policy_action = self.evaluate(
nest_utils.unbatch_nested_tensors(current_policy_action))
tf.nest.map_structure(assert_np_all_equal, current_policy_action,
checkpoint_action)
if __name__ == '__main__':
test_utils.main()
|
[
"tf_agents.specs.array_spec.BoundedArraySpec",
"tf_agents.policies.py_tf_eager_policy.PyTFEagerPolicy",
"tf_agents.policies.py_tf_eager_policy.SavedModelPyTFEagerPolicy",
"tf_agents.agents.ddpg.actor_network.ActorNetwork",
"tf_agents.trajectories.time_step.time_step_spec",
"tensorflow.nest.map_structure",
"tf_agents.specs.array_spec.sample_spec_nest",
"numpy.testing.assert_array_almost_equal",
"tf_agents.utils.nest_utils.unbatch_nested_tensors",
"tensorflow.train.Checkpoint",
"numpy.random.RandomState",
"numpy.equal",
"tf_agents.policies.random_tf_policy.RandomTFPolicy",
"tf_agents.utils.test_utils.main",
"tensorflow.nest.assert_same_structure",
"tf_agents.policies.actor_policy.ActorPolicy",
"tensorflow.constant",
"tf_agents.specs.tensor_spec.from_spec",
"tf_agents.utils.nest_utils.batch_nested_array",
"tf_agents.utils.common.has_eager_been_enabled",
"tf_agents.specs.array_spec.ArraySpec",
"absl.testing.parameterized.parameters",
"tf_agents.environments.random_py_environment.RandomPyEnvironment",
"tf_agents.policies.policy_saver.PolicySaver",
"tensorflow.train.CheckpointManager"
] |
[((6472, 6518), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['None', '(0)', '(100)', '(200000)'], {}), '(None, 0, 100, 200000)\n', (6496, 6518), False, 'from absl.testing import parameterized\n'), ((10732, 10749), 'tf_agents.utils.test_utils.main', 'test_utils.main', ([], {}), '()\n', (10747, 10749), False, 'from tf_agents.utils import test_utils\n'), ((1649, 1686), 'tf_agents.specs.array_spec.ArraySpec', 'array_spec.ArraySpec', (['[2]', 'np.float32'], {}), '([2], np.float32)\n', (1669, 1686), False, 'from tf_agents.specs import array_spec\n'), ((1705, 1755), 'tf_agents.specs.array_spec.BoundedArraySpec', 'array_spec.BoundedArraySpec', (['[1]', 'np.float32', '(2)', '(3)'], {}), '([1], np.float32, 2, 3)\n', (1732, 1755), False, 'from tf_agents.specs import array_spec\n'), ((1787, 1826), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['observation_spec'], {}), '(observation_spec)\n', (1808, 1826), False, 'from tf_agents.specs import tensor_spec\n'), ((1852, 1886), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['action_spec'], {}), '(action_spec)\n', (1873, 1886), False, 'from tf_agents.specs import tensor_spec\n'), ((1915, 1957), 'tf_agents.trajectories.time_step.time_step_spec', 'ts.time_step_spec', (['observation_tensor_spec'], {}), '(observation_tensor_spec)\n', (1932, 1957), True, 'from tf_agents.trajectories import time_step as ts\n'), ((1975, 2073), 'tf_agents.agents.ddpg.actor_network.ActorNetwork', 'actor_network.ActorNetwork', (['observation_tensor_spec', 'action_tensor_spec'], {'fc_layer_params': '(10,)'}), '(observation_tensor_spec, action_tensor_spec,\n fc_layer_params=(10,))\n', (2001, 2073), False, 'from tf_agents.agents.ddpg import actor_network\n'), ((2118, 2214), 'tf_agents.policies.actor_policy.ActorPolicy', 'actor_policy.ActorPolicy', (['time_step_tensor_spec', 'action_tensor_spec'], {'actor_network': 'actor_net'}), '(time_step_tensor_spec, action_tensor_spec,\n actor_network=actor_net)\n', (2142, 2214), False, 'from tf_agents.policies import actor_policy\n'), ((2237, 2282), 'tf_agents.policies.py_tf_eager_policy.PyTFEagerPolicy', 'py_tf_eager_policy.PyTFEagerPolicy', (['tf_policy'], {}), '(tf_policy)\n', (2271, 2282), False, 'from tf_agents.policies import py_tf_eager_policy\n'), ((2384, 2456), 'tf_agents.environments.random_py_environment.RandomPyEnvironment', 'random_py_environment.RandomPyEnvironment', (['observation_spec', 'action_spec'], {}), '(observation_spec, action_spec)\n', (2425, 2456), False, 'from tf_agents.environments import random_py_environment\n'), ((2821, 2858), 'tf_agents.specs.array_spec.ArraySpec', 'array_spec.ArraySpec', (['[2]', 'np.float32'], {}), '([2], np.float32)\n', (2841, 2858), False, 'from tf_agents.specs import array_spec\n'), ((2877, 2927), 'tf_agents.specs.array_spec.BoundedArraySpec', 'array_spec.BoundedArraySpec', (['[1]', 'np.float32', '(2)', '(3)'], {}), '([1], np.float32, 2, 3)\n', (2904, 2927), False, 'from tf_agents.specs import array_spec\n'), ((3116, 3155), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['observation_spec'], {}), '(observation_spec)\n', (3137, 3155), False, 'from tf_agents.specs import tensor_spec\n'), ((3181, 3215), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['action_spec'], {}), '(action_spec)\n', (3202, 3215), False, 'from tf_agents.specs import tensor_spec\n'), ((3239, 3271), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['info_spec'], {}), '(info_spec)\n', (3260, 3271), False, 'from tf_agents.specs import tensor_spec\n'), ((3300, 3342), 'tf_agents.trajectories.time_step.time_step_spec', 'ts.time_step_spec', (['observation_tensor_spec'], {}), '(observation_tensor_spec)\n', (3317, 3342), True, 'from tf_agents.trajectories import time_step as ts\n'), ((3360, 3466), 'tf_agents.policies.random_tf_policy.RandomTFPolicy', 'random_tf_policy.RandomTFPolicy', (['time_step_tensor_spec', 'action_tensor_spec'], {'info_spec': 'info_tensor_spec'}), '(time_step_tensor_spec, action_tensor_spec,\n info_spec=info_tensor_spec)\n', (3391, 3466), False, 'from tf_agents.policies import random_tf_policy\n'), ((3489, 3534), 'tf_agents.policies.py_tf_eager_policy.PyTFEagerPolicy', 'py_tf_eager_policy.PyTFEagerPolicy', (['tf_policy'], {}), '(tf_policy)\n', (3523, 3534), False, 'from tf_agents.policies import py_tf_eager_policy\n'), ((3545, 3617), 'tf_agents.environments.random_py_environment.RandomPyEnvironment', 'random_py_environment.RandomPyEnvironment', (['observation_spec', 'action_spec'], {}), '(observation_spec, action_spec)\n', (3586, 3617), False, 'from tf_agents.environments import random_py_environment\n'), ((4753, 4790), 'tf_agents.specs.array_spec.ArraySpec', 'array_spec.ArraySpec', (['[2]', 'np.float32'], {}), '([2], np.float32)\n', (4773, 4790), False, 'from tf_agents.specs import array_spec\n'), ((4814, 4864), 'tf_agents.specs.array_spec.BoundedArraySpec', 'array_spec.BoundedArraySpec', (['[1]', 'np.float32', '(2)', '(3)'], {}), '([1], np.float32, 2, 3)\n', (4841, 4864), False, 'from tf_agents.specs import array_spec\n'), ((4891, 4926), 'tf_agents.trajectories.time_step.time_step_spec', 'ts.time_step_spec', (['observation_spec'], {}), '(observation_spec)\n', (4908, 4926), True, 'from tf_agents.trajectories import time_step as ts\n'), ((4958, 4997), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['observation_spec'], {}), '(observation_spec)\n', (4979, 4997), False, 'from tf_agents.specs import tensor_spec\n'), ((5023, 5062), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['self.action_spec'], {}), '(self.action_spec)\n', (5044, 5062), False, 'from tf_agents.specs import tensor_spec\n'), ((5091, 5133), 'tf_agents.specs.tensor_spec.from_spec', 'tensor_spec.from_spec', (['self.time_step_spec'], {}), '(self.time_step_spec)\n', (5112, 5133), False, 'from tf_agents.specs import tensor_spec\n'), ((5151, 5249), 'tf_agents.agents.ddpg.actor_network.ActorNetwork', 'actor_network.ActorNetwork', (['observation_tensor_spec', 'action_tensor_spec'], {'fc_layer_params': '(10,)'}), '(observation_tensor_spec, action_tensor_spec,\n fc_layer_params=(10,))\n', (5177, 5249), False, 'from tf_agents.agents.ddpg import actor_network\n'), ((5299, 5395), 'tf_agents.policies.actor_policy.ActorPolicy', 'actor_policy.ActorPolicy', (['time_step_tensor_spec', 'action_tensor_spec'], {'actor_network': 'actor_net'}), '(time_step_tensor_spec, action_tensor_spec,\n actor_network=actor_net)\n', (5323, 5395), False, 'from tf_agents.policies import actor_policy\n'), ((5503, 5543), 'tf_agents.policies.policy_saver.PolicySaver', 'policy_saver.PolicySaver', (['self.tf_policy'], {}), '(self.tf_policy)\n', (5527, 5543), False, 'from tf_agents.policies import policy_saver\n'), ((5588, 5681), 'tf_agents.policies.py_tf_eager_policy.SavedModelPyTFEagerPolicy', 'py_tf_eager_policy.SavedModelPyTFEagerPolicy', (['path', 'self.time_step_spec', 'self.action_spec'], {}), '(path, self.time_step_spec,\n self.action_spec)\n', (5632, 5681), False, 'from tf_agents.policies import py_tf_eager_policy\n'), ((5697, 5720), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (5718, 5720), True, 'import numpy as np\n'), ((5744, 5797), 'tf_agents.specs.array_spec.sample_spec_nest', 'array_spec.sample_spec_nest', (['self.time_step_spec', 'rng'], {}), '(self.time_step_spec, rng)\n', (5771, 5797), False, 'from tf_agents.specs import array_spec\n'), ((5829, 5876), 'tf_agents.utils.nest_utils.batch_nested_array', 'nest_utils.batch_nested_array', (['sample_time_step'], {}), '(sample_time_step)\n', (5858, 5876), False, 'from tf_agents.utils import nest_utils\n'), ((5980, 6030), 'tf_agents.utils.nest_utils.unbatch_nested_tensors', 'nest_utils.unbatch_nested_tensors', (['original_action'], {}), '(original_action)\n', (6013, 6030), False, 'from tf_agents.utils import nest_utils\n'), ((6254, 6329), 'tensorflow.nest.assert_same_structure', 'tf.nest.assert_same_structure', (['saved_policy_action.action', 'self.action_spec'], {}), '(saved_policy_action.action, self.action_spec)\n', (6283, 6329), True, 'import tensorflow as tf\n'), ((6335, 6430), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['original_action_np.action', 'saved_policy_action.action'], {}), '(original_action_np.action,\n saved_policy_action.action)\n', (6371, 6430), True, 'import numpy as np\n'), ((7006, 7099), 'tf_agents.policies.py_tf_eager_policy.SavedModelPyTFEagerPolicy', 'py_tf_eager_policy.SavedModelPyTFEagerPolicy', (['path', 'self.time_step_spec', 'self.action_spec'], {}), '(path, self.time_step_spec,\n self.action_spec)\n', (7050, 7099), False, 'from tf_agents.policies import py_tf_eager_policy\n'), ((7294, 7334), 'tf_agents.policies.policy_saver.PolicySaver', 'policy_saver.PolicySaver', (['self.tf_policy'], {}), '(self.tf_policy)\n', (7318, 7334), False, 'from tf_agents.policies import policy_saver\n'), ((7632, 7725), 'tf_agents.policies.py_tf_eager_policy.SavedModelPyTFEagerPolicy', 'py_tf_eager_policy.SavedModelPyTFEagerPolicy', (['path', 'self.time_step_spec', 'self.action_spec'], {}), '(path, self.time_step_spec,\n self.action_spec)\n', (7676, 7725), False, 'from tf_agents.policies import py_tf_eager_policy\n'), ((7857, 7908), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {'policy': 'eager_py_policy._policy'}), '(policy=eager_py_policy._policy)\n', (7876, 7908), True, 'import tensorflow as tf\n'), ((7923, 8010), 'tensorflow.train.CheckpointManager', 'tf.train.CheckpointManager', (['checkpoint'], {'directory': 'checkpoint_path', 'max_to_keep': 'None'}), '(checkpoint, directory=checkpoint_path,\n max_to_keep=None)\n', (7949, 8010), True, 'import tensorflow as tf\n'), ((8685, 8725), 'tf_agents.policies.policy_saver.PolicySaver', 'policy_saver.PolicySaver', (['self.tf_policy'], {}), '(self.tf_policy)\n', (8709, 8725), False, 'from tf_agents.policies import policy_saver\n'), ((8758, 8781), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (8779, 8781), True, 'import numpy as np\n'), ((8805, 8858), 'tf_agents.specs.array_spec.sample_spec_nest', 'array_spec.sample_spec_nest', (['self.time_step_spec', 'rng'], {}), '(self.time_step_spec, rng)\n', (8832, 8858), False, 'from tf_agents.specs import array_spec\n'), ((8890, 8937), 'tf_agents.utils.nest_utils.batch_nested_array', 'nest_utils.batch_nested_array', (['sample_time_step'], {}), '(sample_time_step)\n', (8919, 8937), False, 'from tf_agents.utils import nest_utils\n'), ((9215, 9308), 'tf_agents.policies.py_tf_eager_policy.SavedModelPyTFEagerPolicy', 'py_tf_eager_policy.SavedModelPyTFEagerPolicy', (['path', 'self.time_step_spec', 'self.action_spec'], {}), '(path, self.time_step_spec,\n self.action_spec)\n', (9259, 9308), False, 'from tf_agents.policies import py_tf_eager_policy\n'), ((9440, 9491), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {'policy': 'eager_py_policy._policy'}), '(policy=eager_py_policy._policy)\n', (9459, 9491), True, 'import tensorflow as tf\n'), ((9506, 9593), 'tensorflow.train.CheckpointManager', 'tf.train.CheckpointManager', (['checkpoint'], {'directory': 'checkpoint_path', 'max_to_keep': 'None'}), '(checkpoint, directory=checkpoint_path,\n max_to_keep=None)\n', (9532, 9593), True, 'import tensorflow as tf\n'), ((10590, 10678), 'tensorflow.nest.map_structure', 'tf.nest.map_structure', (['assert_np_all_equal', 'current_policy_action', 'checkpoint_action'], {}), '(assert_np_all_equal, current_policy_action,\n checkpoint_action)\n', (10611, 10678), True, 'import tensorflow as tf\n'), ((1544, 1575), 'tf_agents.utils.common.has_eager_been_enabled', 'common.has_eager_been_enabled', ([], {}), '()\n', (1573, 1575), False, 'from tf_agents.utils import common\n'), ((2716, 2747), 'tf_agents.utils.common.has_eager_been_enabled', 'common.has_eager_been_enabled', ([], {}), '()\n', (2745, 2747), False, 'from tf_agents.utils import common\n'), ((2959, 3009), 'tf_agents.specs.array_spec.BoundedArraySpec', 'array_spec.BoundedArraySpec', (['[1]', 'np.float32', '(0)', '(1)'], {}), '([1], np.float32, 0, 1)\n', (2986, 3009), False, 'from tf_agents.specs import array_spec\n'), ((3024, 3078), 'tf_agents.specs.array_spec.BoundedArraySpec', 'array_spec.BoundedArraySpec', (['[1]', 'np.float32', '(100)', '(101)'], {}), '([1], np.float32, 100, 101)\n', (3051, 3078), False, 'from tf_agents.specs import array_spec\n'), ((4648, 4679), 'tf_agents.utils.common.has_eager_been_enabled', 'common.has_eager_been_enabled', ([], {}), '()\n', (4677, 4679), False, 'from tf_agents.utils import common\n'), ((6739, 6779), 'tf_agents.policies.policy_saver.PolicySaver', 'policy_saver.PolicySaver', (['self.tf_policy'], {}), '(self.tf_policy)\n', (6763, 6779), False, 'from tf_agents.policies import policy_saver\n'), ((10528, 10584), 'tf_agents.utils.nest_utils.unbatch_nested_tensors', 'nest_utils.unbatch_nested_tensors', (['current_policy_action'], {}), '(current_policy_action)\n', (10561, 10584), False, 'from tf_agents.utils import nest_utils\n'), ((6898, 6921), 'tensorflow.constant', 'tf.constant', (['train_step'], {}), '(train_step)\n', (6909, 6921), True, 'import tensorflow as tf\n'), ((8144, 8158), 'numpy.equal', 'np.equal', (['a', 'b'], {}), '(a, b)\n', (8152, 8158), True, 'import numpy as np\n'), ((8362, 8376), 'numpy.equal', 'np.equal', (['a', 'b'], {}), '(a, b)\n', (8370, 8376), True, 'import numpy as np\n'), ((9727, 9741), 'numpy.equal', 'np.equal', (['a', 'b'], {}), '(a, b)\n', (9735, 9741), True, 'import numpy as np\n'), ((9945, 9959), 'numpy.equal', 'np.equal', (['a', 'b'], {}), '(a, b)\n', (9953, 9959), True, 'import numpy as np\n')]
|
import argparse
import tensorflow as tf
from docqa.model_dir import ModelDir
import numpy as np
def main():
parser = argparse.ArgumentParser(description='')
parser.add_argument("model")
args = parser.parse_args()
model_dir = ModelDir(args.model)
checkpoint = model_dir.get_best_weights()
print(checkpoint)
if checkpoint is None:
print("Show latest checkpoint")
checkpoint = model_dir.get_latest_checkpoint()
else:
print("Show best weights")
reader = tf.train.NewCheckpointReader(checkpoint)
param_map = reader.get_variable_to_shape_map()
total = 0
for k in sorted(param_map):
v = param_map[k]
print('%s: %s' % (k, str(v)))
total += np.prod(v)
print("%d total" % total)
if __name__ == "__main__":
main()
|
[
"tensorflow.train.NewCheckpointReader",
"argparse.ArgumentParser",
"numpy.prod",
"docqa.model_dir.ModelDir"
] |
[((123, 162), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""'}), "(description='')\n", (146, 162), False, 'import argparse\n'), ((244, 264), 'docqa.model_dir.ModelDir', 'ModelDir', (['args.model'], {}), '(args.model)\n', (252, 264), False, 'from docqa.model_dir import ModelDir\n'), ((514, 554), 'tensorflow.train.NewCheckpointReader', 'tf.train.NewCheckpointReader', (['checkpoint'], {}), '(checkpoint)\n', (542, 554), True, 'import tensorflow as tf\n'), ((732, 742), 'numpy.prod', 'np.prod', (['v'], {}), '(v)\n', (739, 742), True, 'import numpy as np\n')]
|
#! /usr/bin/env python
from matplotlib.pyplot import sci
import numpy as np
import math as m
from scipy import linalg
# test pass
def generate_H (traj_constant, timelist):
max_exponent = traj_constant.max_exponent
max_diff = traj_constant.max_diff
trajs_num = timelist.shape[0]-1
H = np.zeros((0,0))
H_seg = np.zeros((max_exponent+1, max_exponent+1), dtype=float)
for time_index in range(1, trajs_num+1):
lower_limit = timelist[time_index-1]
upper_limit = timelist[time_index]
for i in range(max_exponent+1):
for j in range(max_exponent+1):
if (i - max_diff) >= 0 and (j - max_diff) >= 0:
const1 = i + j - 2*max_diff + 1
H_seg[i, j] = m.factorial(i)*m.factorial(j)*(upper_limit**const1-lower_limit**const1)/(m.factorial(i-max_diff)*m.factorial(j-max_diff)*const1)
Hi = linalg.block_diag(H_seg, H_seg, H_seg)
H = linalg.block_diag(H, Hi)
return H
|
[
"scipy.linalg.block_diag",
"numpy.zeros",
"math.factorial"
] |
[((301, 317), 'numpy.zeros', 'np.zeros', (['(0, 0)'], {}), '((0, 0))\n', (309, 317), True, 'import numpy as np\n'), ((330, 389), 'numpy.zeros', 'np.zeros', (['(max_exponent + 1, max_exponent + 1)'], {'dtype': 'float'}), '((max_exponent + 1, max_exponent + 1), dtype=float)\n', (338, 389), True, 'import numpy as np\n'), ((901, 939), 'scipy.linalg.block_diag', 'linalg.block_diag', (['H_seg', 'H_seg', 'H_seg'], {}), '(H_seg, H_seg, H_seg)\n', (918, 939), False, 'from scipy import linalg\n'), ((952, 976), 'scipy.linalg.block_diag', 'linalg.block_diag', (['H', 'Hi'], {}), '(H, Hi)\n', (969, 976), False, 'from scipy import linalg\n'), ((758, 772), 'math.factorial', 'm.factorial', (['i'], {}), '(i)\n', (769, 772), True, 'import math as m\n'), ((773, 787), 'math.factorial', 'm.factorial', (['j'], {}), '(j)\n', (784, 787), True, 'import math as m\n'), ((831, 856), 'math.factorial', 'm.factorial', (['(i - max_diff)'], {}), '(i - max_diff)\n', (842, 856), True, 'import math as m\n'), ((855, 880), 'math.factorial', 'm.factorial', (['(j - max_diff)'], {}), '(j - max_diff)\n', (866, 880), True, 'import math as m\n')]
|
import open3d as o3d
import numpy as np
import python.open3d_tutorial as o3dtut
# http://www.open3d.org/docs/release/tutorial/geometry/mesh_deformation.html
########################################################################################################################
# 1. Mesh deformation
########################################################################################################################
'''
If we want to deform a triangle mesh according to a small number of constraints, we can use mesh deformation algorithms.
Open3D implements the as-rigid-as-possible method by [SorkineAndAlexa2007] that optimizes the following energy function
∑i∑j∈N(i)wij||(p′i−p′j)−Ri(pi−pj)||2,
where Ri are the rotation matrices that we want to optimize for, and pi and p′i are the vertex positions before and
after the optimization, respectively. N(i) is the set of neighbors of vertex i. The weights wij are cotangent weights.
Open3D implements this method in deform_as_rigid_as_possible. The first argument to this method is a set of
constraint_ids that refer to the vertices in the triangle mesh. The second argument constrint_pos defines at which
position those vertices should be after the optimization. The optimization process is an iterative scheme. Hence, we
also can define the number of iterations via max_iter.
'''
mesh = o3dtut.get_armadillo_mesh()
vertices = np.asarray(mesh.vertices)
static_ids = [idx for idx in np.where(vertices[:, 1] < -30)[0]]
static_pos = []
for id in static_ids:
static_pos.append(vertices[id])
handle_ids = [2490]
handle_pos = [vertices[2490] + np.array((-40, -40, -40))]
constraint_ids = o3d.utility.IntVector(static_ids + handle_ids)
constraint_pos = o3d.utility.Vector3dVector(static_pos + handle_pos)
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
mesh_prime = mesh.deform_as_rigid_as_possible(constraint_ids, constraint_pos, max_iter=50)
print('Original Mesh')
R = mesh.get_rotation_matrix_from_xyz((0, np.pi, 0))
o3d.visualization.draw_geometries([mesh.rotate(R, center=mesh.get_center())])
print('Deformed Mesh')
mesh_prime.compute_vertex_normals()
o3d.visualization.draw_geometries([mesh_prime.rotate(R, center=mesh_prime.get_center())], width=800, height=600)
########################################################################################################################
# 2. Smoothed ARAP
########################################################################################################################
'''
Open3D also implements a smoothed version of the ARAP objective defined as
∑i∑j∈N(i)wij||(p′i−p′j)−Ri(pi−pj)||2+αA||Ri−Rj||2,
that penalizes a deviation of neighboring rotation matrices. α is a trade-off parameter for the regularization term and
A is the surface area.
The smoothed objective can be used in deform_as_rigid_as_possible by using the argument energy with the parameter
Smoothed.
'''
|
[
"open3d.utility.VerbosityContextManager",
"numpy.asarray",
"python.open3d_tutorial.get_armadillo_mesh",
"numpy.where",
"numpy.array",
"open3d.utility.Vector3dVector",
"open3d.utility.IntVector"
] |
[((1352, 1379), 'python.open3d_tutorial.get_armadillo_mesh', 'o3dtut.get_armadillo_mesh', ([], {}), '()\n', (1377, 1379), True, 'import python.open3d_tutorial as o3dtut\n'), ((1392, 1417), 'numpy.asarray', 'np.asarray', (['mesh.vertices'], {}), '(mesh.vertices)\n', (1402, 1417), True, 'import numpy as np\n'), ((1651, 1697), 'open3d.utility.IntVector', 'o3d.utility.IntVector', (['(static_ids + handle_ids)'], {}), '(static_ids + handle_ids)\n', (1672, 1697), True, 'import open3d as o3d\n'), ((1715, 1766), 'open3d.utility.Vector3dVector', 'o3d.utility.Vector3dVector', (['(static_pos + handle_pos)'], {}), '(static_pos + handle_pos)\n', (1741, 1766), True, 'import open3d as o3d\n'), ((1773, 1842), 'open3d.utility.VerbosityContextManager', 'o3d.utility.VerbosityContextManager', (['o3d.utility.VerbosityLevel.Debug'], {}), '(o3d.utility.VerbosityLevel.Debug)\n', (1808, 1842), True, 'import open3d as o3d\n'), ((1607, 1632), 'numpy.array', 'np.array', (['(-40, -40, -40)'], {}), '((-40, -40, -40))\n', (1615, 1632), True, 'import numpy as np\n'), ((1447, 1477), 'numpy.where', 'np.where', (['(vertices[:, 1] < -30)'], {}), '(vertices[:, 1] < -30)\n', (1455, 1477), True, 'import numpy as np\n')]
|
"""Functions for rounding numbers."""
import functools
import numpy as np
def np_vectorize(f):
"""Like `np.vectorize`, but with some embellishments.
- Includes `functools.wraps`
- Applies `.item()` to output if input was a scalar.
"""
vectorized = np.vectorize(f)
@functools.wraps(f)
def new(*args, **kwargs):
output = vectorized(*args, **kwargs)
if np.isscalar(args[0]) and not isinstance(args[0], np.ndarray):
output = output.item()
return output
return new
@np_vectorize
def _round2prec(num, prec):
"""Don't use (directly)! Suffers from numerical precision.
This function is left here just for reference. Use `round2` instead.
The issue is that:
>>> _round2prec(0.7,.1)
0.7000000000000001
"""
return prec * round(num / prec)
@np_vectorize
def log10int(x):
"""Compute decimal order, rounded down.
Conversion to `int` means that we cannot return nan's or +/- infinity,
even though this could be meaningful. Instead, we return integers of magnitude
a little less than IEEE floating point max/min-ima instead.
This avoids a lot of clauses in the parent/callers to this function.
Examples
--------
>>> log10int([1e-1, 1e-2, 1, 3, 10, np.inf, -np.inf, np.nan])
array([ -1, -2, 0, 0, 1, 300, -300, -300])
"""
# Extreme cases -- https://stackoverflow.com/q/65248379
if np.isnan(x):
y = -300
elif x < 1e-300:
y = -300
elif x > 1e+300:
y = +300
# Normal case
else:
y = int(np.floor(np.log10(np.abs(x))))
return y
@np_vectorize
def round2(x, prec=1.0):
r"""Round to a nice precision.
Parameters
----------
x : array_like
Value to be rounded.
prec: float
Precision, before prettify, which is given by
$$ \text{prec} = 10^{\text{floor}(-\log_{10}|\text{prec}|)} $$
Returns
-------
Rounded value (always a float).
See Also
--------
round2sigfig
Examples
--------
>>> round2(1.65, 0.543)
1.6
>>> round2(1.66, 0.543)
1.7
>>> round2(1.65, 1.234)
2.0
"""
if np.isnan(prec):
return x
ndecimal = -log10int(prec)
return np.round(x, ndecimal)
@np_vectorize
def round2sigfig(x, sigfig=1):
"""Round to significant figures.
Parameters
----------
x
Value to be rounded.
sigfig
Number of significant figures to include.
Returns
-------
rounded value (always a float).
See Also
--------
np.round : rounds to a given number of *decimals*.
round2 : rounds to a given *precision*.
Examples
--------
>>> round2sigfig(1234.5678, 1)
1000.0
>>> round2sigfig(1234.5678, 4)
1235.0
>>> round2sigfig(1234.5678, 6)
1234.57
"""
ndecimal = sigfig - log10int(x) - 1
return np.round(x, ndecimal)
def is_whole(x, **kwargs):
"""Check if a number is a whole/natural number to precision given by `np.isclose`.
For actual type checking, use `isinstance(x, (int, np.integer))`.
"""
return np.isclose(x, round(x), **kwargs)
|
[
"numpy.vectorize",
"numpy.abs",
"numpy.isscalar",
"numpy.isnan",
"functools.wraps",
"numpy.round"
] |
[((273, 288), 'numpy.vectorize', 'np.vectorize', (['f'], {}), '(f)\n', (285, 288), True, 'import numpy as np\n'), ((295, 313), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (310, 313), False, 'import functools\n'), ((1436, 1447), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (1444, 1447), True, 'import numpy as np\n'), ((2183, 2197), 'numpy.isnan', 'np.isnan', (['prec'], {}), '(prec)\n', (2191, 2197), True, 'import numpy as np\n'), ((2258, 2279), 'numpy.round', 'np.round', (['x', 'ndecimal'], {}), '(x, ndecimal)\n', (2266, 2279), True, 'import numpy as np\n'), ((2903, 2924), 'numpy.round', 'np.round', (['x', 'ndecimal'], {}), '(x, ndecimal)\n', (2911, 2924), True, 'import numpy as np\n'), ((400, 420), 'numpy.isscalar', 'np.isscalar', (['args[0]'], {}), '(args[0])\n', (411, 420), True, 'import numpy as np\n'), ((1604, 1613), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (1610, 1613), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__description__ = """
Img processor for decision if mouth is open or close
"""
import sys
import os
import cv2
import numpy as np
from pprint import pprint
# root of project repository
THE_FILE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.abspath(os.path.join(THE_FILE_DIR, '../../..', '..', '..'))
sys.path.append(PROJECT_ROOT)
from src.img.container.image import Image
from src.img.container.result import ImageProcessorResult
from src.img.processor.processor import ImgProcessor
from src.img.processor.faces.landmarks_detector.result import LandmarksDetectorResult, FaceLandmarsks
from src.img.processor.reformat.squere_crop.result import SquereCropResult
from src.img.container.geometry import Point
from src.img.processor.faces.face_detector.result import FaceDetectorResult
class PointsPairs:
"""
Corresponding points and conection to real values from landmarks
"""
def __init__(self, points_pairs_id: [(int, int)]):
"""
The points_pairs_id is list of pairs of id which are relevnt in the case.
For task as "left eye" us importantn, that one ID can be used more times.
"""
def add_id(d:dict, i:int, id:int):
"""
Crete dictionary: id => list of position in values array.
"""
if not id in d:
d[id] = []
d[id].append(i)
self._id_to_positions1 = {} # id1 => [position] for id1 in [(id1, _)]
self._id_to_positions2 = {} # id2 => [position] for id1 in [(_, id2)]
for i, (id1,id2) in enumerate(points_pairs_id):
add_id(self._id_to_positions1, i, id1)
add_id(self._id_to_positions2, i, id2)
# create placeholder for values of points
self._xy_values_array1 = np.full(shape=(len(points_pairs_id), 2), fill_value=np.nan, dtype=np.float)
self._xy_values_array2 = np.full(shape=(len(points_pairs_id), 2), fill_value=np.nan, dtype=np.float)
def reset_values(self):
self._xy_values_array1[:, :] = np.nan
self._xy_values_array2[:, :] = np.nan
def add(self, point_number, point: Point) -> bool:
"""
Try to add real valuses (from piscture, i.e. point.x() and point.y()) to all corespondet places
Return True just when point_numer/point are used.
"""
def add_value(id: int, index_dict: dict, point: Point, values_array: np.ndarray) -> bool:
if id in index_dict:
for index in index_dict[id]:
values_array[index][0] = point.x()
values_array[index][1] = point.y()
return True
else:
return False
return add_value(point_number, self._id_to_positions1, point, self._xy_values_array1) \
or add_value(point_number, self._id_to_positions2, point, self._xy_values_array2)
def _get_distances(self) -> np.ndarray:
"""
Returns array of distances of two corresponding points.
"""
return np.linalg.norm(self._xy_values_array1 - self._xy_values_array2, axis=1)
def get_mean_distances(self) -> float:
"""
Returns mean of array of distances of two corresponding points
"""
return self._get_distances().mean()
def debug_print(self):
print('id to positions 1', self._id_to_positions1)
print('id to positions 2', self._id_to_positions2)
print('xy_values_array 1', self._xy_values_array1.shape, "\n", self._xy_values_array1)
print()
print('xy_values_array 2', self._xy_values_array2.shape, "\n", self._xy_values_array2)
print()
distances = self._get_distances()
print('distances', distances.shape, distances)
print('metrics', self.get_mean_distances())
class IsOpenManager:
"""
Decide if mouth/eye/... is open or not
"""
FOUND_MAX_RATE = -np.inf
FOUND_MIN_RATE = np.inf
THRESHOLD_PERCENTS = 25.5
def __init__(
self,
name : str,
mouth_like_pairs: PointsPairs,
reference_pairs: PointsPairs,
max_rate: np.float = FOUND_MAX_RATE,
min_rate: np.float = FOUND_MIN_RATE,
threshold_percents: np.float = THRESHOLD_PERCENTS,
calibration_mode: bool = True
):
self.name = name
self._mouth_like_pairs = mouth_like_pairs
self._reference_pairs = reference_pairs
self._threshold_percents = threshold_percents
self._max_rate = max_rate
self._min_rate = min_rate
self._calibration_mode = calibration_mode
def add(self, point_number, point: Point):
"""
Try to add point values (if point_number is acceptable)
"""
self._mouth_like_pairs.add(point_number=point_number, point=point)
self._reference_pairs.add(point_number=point_number, point=point)
def get_rate_rate_percents_is_open(self) -> (float, float, bool):
"""
Compare distances of pairs of points for mouth_like object with same disnces in comparation objects
"""
# if self._reference_pairs.get_mean_distances() is 0, it is a error and raising exception is on the place
rate = self._mouth_like_pairs.get_mean_distances() / self._reference_pairs.get_mean_distances()
if self._calibration_mode:
self._min_rate = min(self._min_rate, rate)
self._max_rate = max(self._max_rate, rate)
percents = 100 * (rate - self._min_rate) / (self._max_rate - self._min_rate)
is_open = percents >= self._threshold_percents
'''
print(f'{self.name}, min:{self._min_rate:2.3f}, max:{self._max_rate:2.3f}')
print(f'{self.name}, rate:{rate:2.3f}, ({percents:2.3f} %), open:{is_open}')
print(f'{self.name}, in:{self._mouth_like_pairs.get_mean_distances():2.3f}, ref:{self._reference_pairs.get_mean_distances():2.3f}')
'''
return rate, percents, is_open
def get_threshold_percents(self):
return self._threshold_percents
# --- specific configurations for mouth --------------------------------------------------------------------------------
class InsightfaceMouthIsOpenManager(IsOpenManager):
def __init__(
self,
calibration_mode: bool = True,
threshold_percents: np.float = 25.0
):
super().__init__(
name = 'insightface.106.mouth',
mouth_like_pairs = PointsPairs([
(60, 71), (62, 53), (63, 56), (67, 59)
]),
reference_pairs = PointsPairs([
(72, 80), (1, 2), (25, 20)
]),
calibration_mode = calibration_mode,
threshold_percents=threshold_percents
)
# --- specific configurations for left eye ----------------------------------------------------------------------------
class InsightfaceLeftEyeIsOpenManager(IsOpenManager):
def __init__(
self,
calibration_mode: bool = True,
threshold_percents: np.float = 50.0
):
center_of_left_eye = 92 # or 88
obj_list = []
for second in [87, 89, 90, 91] + list(range(93, 103)):
obj_list.append((center_of_left_eye, second))
super().__init__(
name = 'insightface.106.left eye',
mouth_like_pairs = PointsPairs(
# [(95, 90), (94, 87), (96, 91)]
# [(94, 87)]
obj_list
),
reference_pairs = PointsPairs([
(72, 80), (1, 2), (25, 20)
]),
calibration_mode = calibration_mode,
threshold_percents = threshold_percents
)
# --- specific configurations for right eye ----------------------------------------------------------------------------
class InsightfaceRightEyeIsOpenManager(IsOpenManager):
def __init__(
self,
calibration_mode: bool = True,
threshold_percents: np.float = 50.0
):
center_of_right_eye = 34 # or 38
obj_list = []
for second in [33, 35, 36, 37] + list(range(39, 52)):
obj_list.append((center_of_right_eye, second))
super().__init__(
name = 'insightface.106.right eye',
mouth_like_pairs = PointsPairs(
# [(41, 36), (40, 33), (42, 37)]
# [(41, 36), (40, 33), (42, 37)]
obj_list
),
reference_pairs = PointsPairs([
(72, 80), (1, 2), (25, 20)
]),
calibration_mode = calibration_mode,
threshold_percents = threshold_percents
)
class IsOpenResult(ImageProcessorResult):
def __init__(
self,
processor: ImgProcessor,
time_ms: int = None,
rate: float = np.nan,
open_percents: float = np.nan,
is_open: bool = False,
face_landmarks: FaceDetectorResult = None,
threshold_percents: int = None
):
super().__init__(processor=processor, time_ms=time_ms)
self.rate = rate
self.open_percents = open_percents
self.is_open = is_open
self.face_landmarks = face_landmarks
self.threshold_percents = threshold_percents
class IsOpenImgProcessor(ImgProcessor):
def __init__(self, is_open_manager: IsOpenManager):
super().__init__(name=is_open_manager.name + '.is_open')
self._is_open_manager = is_open_manager
def _process_image(self, img: Image = None) -> (Image, FaceDetectorResult):
"""
Face coordinates an landmarks was found in orig_img_array.
Use landmarks for desicion if mouth/eye/... is open.
"""
result = ImageProcessorResult(processor=self)
landmark_results = img.get_results().get_results_for_processor_super_class(LandmarksDetectorResult) # [FaceLandmarsks]
for landmark_result in landmark_results: # FaceLandmarsks
for face_landmarks in landmark_result.get_face_landmark_couples():
landmarks = face_landmarks.get_landmarks() # [Point]
# registre landmarks
for point_number, landmark_point in enumerate(landmarks):
self._is_open_manager.add(point_number=point_number, point=landmark_point)
# calculate result
rate, percents, is_open = self._is_open_manager.get_rate_rate_percents_is_open()
result = IsOpenResult(
processor=self,
rate=rate,
open_percents=percents,
is_open=is_open,
face_landmarks=face_landmarks,
threshold_percents = self._is_open_manager.get_threshold_percents()
)
# print('XXX', result.rate, result.open_percents, result.is_open)
return img, result
if __name__ == "__main__":
# for testing
def add_verbose(pp: PointsPairs, point_number: int, point: Point):
success = pp.add(point_number=point_number, point=point)
print(f'add({point_number}, {point}) -> {success}')
coresponding_points_ids = [
(64,55), (66,54), (71, 60)
]
pp = PointsPairs(coresponding_points_ids)
print('list of coresponding ids', coresponding_points_ids)
# will be ignored, point_number=1 is not registred
add_verbose(pp=pp, point_number=1, point=Point(1000, 2000))
# will be added tu up
add_verbose(pp=pp, point_number=64, point=Point(0, 1))
add_verbose(pp=pp, point_number=66, point=Point(2, 2))
add_verbose(pp=pp, point_number=71, point=Point(100, 100))
# will be added to down
add_verbose(pp=pp, point_number=55, point=Point(1, 1))
add_verbose(pp=pp, point_number=54, point=Point(4, 4))
add_verbose(pp=pp, point_number=60, point=Point(100, 105))
pp.debug_print()
|
[
"sys.path.append",
"os.path.abspath",
"src.img.container.geometry.Point",
"numpy.linalg.norm",
"src.img.container.result.ImageProcessorResult",
"os.path.join"
] |
[((436, 465), 'sys.path.append', 'sys.path.append', (['PROJECT_ROOT'], {}), '(PROJECT_ROOT)\n', (451, 465), False, 'import sys\n'), ((384, 434), 'os.path.join', 'os.path.join', (['THE_FILE_DIR', '"""../../.."""', '""".."""', '""".."""'], {}), "(THE_FILE_DIR, '../../..', '..', '..')\n", (396, 434), False, 'import os\n'), ((325, 350), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (340, 350), False, 'import os\n'), ((3159, 3230), 'numpy.linalg.norm', 'np.linalg.norm', (['(self._xy_values_array1 - self._xy_values_array2)'], {'axis': '(1)'}), '(self._xy_values_array1 - self._xy_values_array2, axis=1)\n', (3173, 3230), True, 'import numpy as np\n'), ((9843, 9879), 'src.img.container.result.ImageProcessorResult', 'ImageProcessorResult', ([], {'processor': 'self'}), '(processor=self)\n', (9863, 9879), False, 'from src.img.container.result import ImageProcessorResult\n'), ((11559, 11576), 'src.img.container.geometry.Point', 'Point', (['(1000)', '(2000)'], {}), '(1000, 2000)\n', (11564, 11576), False, 'from src.img.container.geometry import Point\n'), ((11651, 11662), 'src.img.container.geometry.Point', 'Point', (['(0)', '(1)'], {}), '(0, 1)\n', (11656, 11662), False, 'from src.img.container.geometry import Point\n'), ((11710, 11721), 'src.img.container.geometry.Point', 'Point', (['(2)', '(2)'], {}), '(2, 2)\n', (11715, 11721), False, 'from src.img.container.geometry import Point\n'), ((11769, 11784), 'src.img.container.geometry.Point', 'Point', (['(100)', '(100)'], {}), '(100, 100)\n', (11774, 11784), False, 'from src.img.container.geometry import Point\n'), ((11861, 11872), 'src.img.container.geometry.Point', 'Point', (['(1)', '(1)'], {}), '(1, 1)\n', (11866, 11872), False, 'from src.img.container.geometry import Point\n'), ((11920, 11931), 'src.img.container.geometry.Point', 'Point', (['(4)', '(4)'], {}), '(4, 4)\n', (11925, 11931), False, 'from src.img.container.geometry import Point\n'), ((11979, 11994), 'src.img.container.geometry.Point', 'Point', (['(100)', '(105)'], {}), '(100, 105)\n', (11984, 11994), False, 'from src.img.container.geometry import Point\n')]
|
import os
import math
import numpy as np
import pickle
from PIL import Image
import matplotlib.pyplot as plt
import torch
import torchvision
def tensor2im(img, imtype=np.uint8, unnormalize=True, idx=0, nrows=None):
if img.shape[1] == 1:
# img = np.repeat(img, 3, axis=1)
img = torch.cat((img, img, img), dim=1)
# print(img.shape, type(img))
if len(img.shape) == 4:
nrows = nrows if nrows is not None else int(math.sqrt(img.size(0)))
img = img[idx] if idx >= 0 else torchvision.utils.make_grid(img, nrows)
img = img.cpu().float()
if unnormalize:
mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
for i, m, s in zip(img, mean, std):
i.mul_(s).add_(m)
image_numpy = img.numpy()
image_numpy_t = image_numpy
image_numpy_t = image_numpy_t*254.0
return image_numpy_t.astype(imtype)
def tensor2maskim(mask, imtype=np.uint8, idx=0, nrows=None):
im = tensor2im(mask, imtype=imtype, idx=idx, unnormalize=False, nrows=nrows)
return im
def mkdirs(paths):
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths)
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def save_image(image_numpy, image_path):
mkdir(os.path.dirname(image_path))
image_numpy = image_numpy.transpose((1,2,0))
image_pil = Image.fromarray(image_numpy)
image_pil.save(image_path)
def save_str_data(data, path):
mkdir(os.path.dirname(path))
np.savetxt(path, data, delimiter=",", fmt="%s")
def load_pickle(file_path):
f = open(file_path, 'rb')
file_pickle = pickle.load(f)
f.close()
return file_pickle
def list_reader_2(file_list):
img_list = []
label = []
with open(file_list, 'r') as file:
for line in file.readlines():
element = line.split()
img_path = element[0]
if element[16] == '1':
for i in range(15):
label.append(0)
img_list.append(img_path)
else:
label.append(1)
img_list.append(img_path)
return img_list, label
def list_reader_all22(file_list):
img_list = []
with open(file_list, 'r') as file:
for line in file.readlines():
img_path = line
img_list.append(img_path[:-1])
return img_list
def list_reader_all(file_list):
img_list = []
with open(file_list, 'rb') as file:
for line in file.readlines():
img_path = line
img_list.append(img_path.split())
return img_list
def list_reader(file_list):
img_list = []
with open(file_list, 'r') as file:
for line in file.readlines():
img_path = line
img_list.append(img_path.split()[0])
return img_list
def composite_image(top_x, top_y, occ_img, img):
occ = np.zeros((128, 128, 4))
img = np.asarray(img)
if occ_img.shape[2] == 3:
occ_img = np.concatenate((occ_img, 255 * np.ones((occ_img.shape[0], occ_img.shape[1], 1))), axis=2)
occ[top_y : top_y + occ_img.shape[0], top_x : top_x + occ_img.shape[1], :] += occ_img
occ = occ.astype('uint8')
composite_img = np.concatenate((img.astype('uint8'), occ, occ[:, :, 3:4], occ[:, :, 3:4]), axis=2)
final_composite_img = np.multiply((np.ones((128, 128, 3)) * 255 - \
composite_img[:, :, 6:9]).astype('uint8') / 255,
composite_img[:, :, 0:3]).astype('uint8') + \
np.multiply(composite_img[:, :, 6:9].astype('uint8') / 255,
composite_img[:, :, 3:6]).astype('uint8')
final_composite_img = Image.fromarray(final_composite_img)
return final_composite_img
def process_image(img, occ_img, occ_type):
random_ang = (np.random.rand() - 0.5) * 30
occ_img = occ_img.rotate(random_ang, expand = 1)
if occ_type == 'glasses' or occ_type == 'sun_glasses':
occ_img = occ_img.resize((100, int(occ_img.size[1] / (occ_img.size[0] / 100))))
top_x = 14
top_y = int(40 - occ_img.size[1] / 2 + (np.random.rand() - 1) * 10)
top_y = (top_y if(top_y >= 0) else 0)
elif occ_type == 'scarf' or occ_type == 'cup':
if occ_img.size[0] >= occ_img.size[1]:
occ_img = occ_img.resize((64, int(occ_img.size[1] / (occ_img.size[0] / 64))))
else:
occ_img = occ_img.resize(((int(occ_img.size[0] / (occ_img.size[1] / 64))), 64))
top_x = np.random.randint(0, 128 - occ_img.size[0])
top_y = np.random.randint(128 - occ_img.size[1] -20 , 128 - occ_img.size[1])
elif occ_type == 'hand':
if occ_img.size[0] >= occ_img.size[1]:
occ_img = occ_img.resize((120, int(occ_img.size[1] / (occ_img.size[0] / 120))))
else:
occ_img = occ_img.resize(((int(occ_img.size[0] / (occ_img.size[1] / 120))), 120))
top_x = np.random.randint(0, 128 - occ_img.size[0])
top_y = np.random.randint(0, 128 - occ_img.size[1])
elif occ_type == 'phone':
if occ_img.size[0] >= occ_img.size[1]:
occ_img = occ_img.resize((80, int(occ_img.size[1] / (occ_img.size[0] / 80))))
else:
occ_img = occ_img.resize(((int(occ_img.size[0] / (occ_img.size[1] / 80))), 80))
top_x = np.random.randint(0, 128 - occ_img.size[0])
top_y = np.random.randint(0, 128 - occ_img.size[1])
elif occ_type == 'mask':
if occ_img.size[0] >= occ_img.size[1]:
occ_img = occ_img.resize((100, int(occ_img.size[1] / (occ_img.size[0] / 100))))
else:
occ_img = occ_img.resize(((int(occ_img.size[0] / (occ_img.size[1] / 100))), 100))
top_x = np.random.randint(0, 128 - occ_img.size[0])
top_y = np.random.randint(128 - occ_img.size[1] -20 , 128 - occ_img.size[1])
else:
if occ_img.size[0] >= occ_img.size[1]:
occ_img = occ_img.resize((70, int(occ_img.size[1] / (occ_img.size[0] / 70))))
else:
occ_img = occ_img.resize(((int(occ_img.size[0] / (occ_img.size[1] / 70))), 70))
top_x = np.random.randint(0, 128 - occ_img.size[0])
top_y = np.random.randint(0, 128 - occ_img.size[1])
final_composite_img = composite_image(top_x, top_y, np.asarray(occ_img), img)
return final_composite_img
|
[
"os.makedirs",
"numpy.random.rand",
"numpy.asarray",
"numpy.savetxt",
"numpy.zeros",
"torch.cat",
"os.path.exists",
"os.path.dirname",
"torchvision.utils.make_grid",
"numpy.ones",
"pickle.load",
"numpy.random.randint",
"PIL.Image.fromarray"
] |
[((1442, 1470), 'PIL.Image.fromarray', 'Image.fromarray', (['image_numpy'], {}), '(image_numpy)\n', (1457, 1470), False, 'from PIL import Image\n'), ((1573, 1620), 'numpy.savetxt', 'np.savetxt', (['path', 'data'], {'delimiter': '""","""', 'fmt': '"""%s"""'}), "(path, data, delimiter=',', fmt='%s')\n", (1583, 1620), True, 'import numpy as np\n'), ((1699, 1713), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1710, 1713), False, 'import pickle\n'), ((2985, 3008), 'numpy.zeros', 'np.zeros', (['(128, 128, 4)'], {}), '((128, 128, 4))\n', (2993, 3008), True, 'import numpy as np\n'), ((3019, 3034), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (3029, 3034), True, 'import numpy as np\n'), ((3848, 3884), 'PIL.Image.fromarray', 'Image.fromarray', (['final_composite_img'], {}), '(final_composite_img)\n', (3863, 3884), False, 'from PIL import Image\n'), ((300, 333), 'torch.cat', 'torch.cat', (['(img, img, img)'], {'dim': '(1)'}), '((img, img, img), dim=1)\n', (309, 333), False, 'import torch\n'), ((1241, 1261), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1255, 1261), False, 'import os\n'), ((1271, 1288), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (1282, 1288), False, 'import os\n'), ((1342, 1369), 'os.path.dirname', 'os.path.dirname', (['image_path'], {}), '(image_path)\n', (1357, 1369), False, 'import os\n'), ((1546, 1567), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (1561, 1567), False, 'import os\n'), ((6452, 6471), 'numpy.asarray', 'np.asarray', (['occ_img'], {}), '(occ_img)\n', (6462, 6471), True, 'import numpy as np\n'), ((513, 552), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['img', 'nrows'], {}), '(img, nrows)\n', (540, 552), False, 'import torchvision\n'), ((3988, 4004), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (4002, 4004), True, 'import numpy as np\n'), ((4674, 4717), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[0])'], {}), '(0, 128 - occ_img.size[0])\n', (4691, 4717), True, 'import numpy as np\n'), ((4734, 4802), 'numpy.random.randint', 'np.random.randint', (['(128 - occ_img.size[1] - 20)', '(128 - occ_img.size[1])'], {}), '(128 - occ_img.size[1] - 20, 128 - occ_img.size[1])\n', (4751, 4802), True, 'import numpy as np\n'), ((5096, 5139), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[0])'], {}), '(0, 128 - occ_img.size[0])\n', (5113, 5139), True, 'import numpy as np\n'), ((5156, 5199), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[1])'], {}), '(0, 128 - occ_img.size[1])\n', (5173, 5199), True, 'import numpy as np\n'), ((3120, 3168), 'numpy.ones', 'np.ones', (['(occ_img.shape[0], occ_img.shape[1], 1)'], {}), '((occ_img.shape[0], occ_img.shape[1], 1))\n', (3127, 3168), True, 'import numpy as np\n'), ((5490, 5533), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[0])'], {}), '(0, 128 - occ_img.size[0])\n', (5507, 5533), True, 'import numpy as np\n'), ((5550, 5593), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[1])'], {}), '(0, 128 - occ_img.size[1])\n', (5567, 5593), True, 'import numpy as np\n'), ((4287, 4303), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (4301, 4303), True, 'import numpy as np\n'), ((5887, 5930), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[0])'], {}), '(0, 128 - occ_img.size[0])\n', (5904, 5930), True, 'import numpy as np\n'), ((5947, 6015), 'numpy.random.randint', 'np.random.randint', (['(128 - occ_img.size[1] - 20)', '(128 - occ_img.size[1])'], {}), '(128 - occ_img.size[1] - 20, 128 - occ_img.size[1])\n', (5964, 6015), True, 'import numpy as np\n'), ((6290, 6333), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[0])'], {}), '(0, 128 - occ_img.size[0])\n', (6307, 6333), True, 'import numpy as np\n'), ((6350, 6393), 'numpy.random.randint', 'np.random.randint', (['(0)', '(128 - occ_img.size[1])'], {}), '(0, 128 - occ_img.size[1])\n', (6367, 6393), True, 'import numpy as np\n'), ((3443, 3465), 'numpy.ones', 'np.ones', (['(128, 128, 3)'], {}), '((128, 128, 3))\n', (3450, 3465), True, 'import numpy as np\n')]
|
from tempfile import TemporaryDirectory, NamedTemporaryFile
import numpy as np
import pytest
from lhotse import (
ChunkedLilcomHdf5Writer,
LilcomFilesWriter,
LilcomHdf5Writer,
NumpyFilesWriter,
NumpyHdf5Writer,
)
from lhotse.array import Array, TemporalArray
@pytest.mark.parametrize(
"array",
[
np.arange(20),
np.arange(20).reshape(2, 10),
np.arange(20).reshape(2, 5, 2),
np.arange(20).astype(np.float32),
np.arange(20).astype(np.int8),
],
)
@pytest.mark.parametrize(
"writer_class",
[
NumpyFilesWriter,
NumpyHdf5Writer,
pytest.param(
LilcomFilesWriter,
marks=pytest.mark.xfail(reason="Lilcom changes dtype to float32"),
),
pytest.param(
LilcomHdf5Writer,
marks=pytest.mark.xfail(reason="Lilcom changes dtype to float32"),
),
pytest.param(
ChunkedLilcomHdf5Writer,
marks=pytest.mark.xfail(
reason="Lilcom changes dtype to float32 (and Chunked variant works only with shape 2)"
),
),
],
)
def test_write_read_temporal_array_no_lilcom(array, writer_class):
with TemporaryDirectory() as d, writer_class(d) as writer:
manifest = writer.store_array(
key="utt1",
value=array,
temporal_dim=0,
frame_shift=0.4,
start=0.0,
)
restored = manifest.load()
assert array.ndim == manifest.ndim
assert array.shape == restored.shape
assert list(array.shape) == manifest.shape
assert array.dtype == restored.dtype
np.testing.assert_almost_equal(array, restored)
@pytest.mark.parametrize(
"array",
[
np.arange(20).astype(np.float32),
np.arange(20).reshape(2, 10).astype(np.float32),
np.arange(20).reshape(2, 5, 2).astype(np.float32),
],
)
@pytest.mark.parametrize(
"writer_class",
[
LilcomFilesWriter,
LilcomHdf5Writer,
],
)
def test_write_read_temporal_array_lilcom(array, writer_class):
with TemporaryDirectory() as d, writer_class(d) as writer:
manifest = writer.store_array(
key="utt1",
value=array,
temporal_dim=0,
frame_shift=0.4,
start=0.0,
)
restored = manifest.load()
assert array.ndim == manifest.ndim
assert array.shape == restored.shape
assert list(array.shape) == manifest.shape
assert array.dtype == restored.dtype
np.testing.assert_almost_equal(array, restored)
def test_temporal_array_serialization():
# Individual items do not support JSON/etc. serialization;
# instead, the XSet (e.g. CutSet) classes convert them to dicts.
manifest = TemporalArray(
array=Array(
storage_type="lilcom_hdf5",
storage_path="/tmp/data",
storage_key="irrelevant",
shape=[300],
),
temporal_dim=0,
frame_shift=0.3,
start=5.0,
)
serialized = manifest.to_dict()
restored = TemporalArray.from_dict(serialized)
assert manifest == restored
def test_temporal_array_partial_read():
array = np.arange(30).astype(np.int8)
with NamedTemporaryFile(suffix=".h5") as f, NumpyHdf5Writer(f.name) as writer:
manifest = writer.store_array(
key="utt1",
value=array,
temporal_dim=0,
frame_shift=0.5,
start=0.0,
)
# Read all
restored = manifest.load()
np.testing.assert_equal(array, restored)
# Read first 10 frames (0 - 5 seconds)
first_10 = manifest.load(duration=5)
np.testing.assert_equal(array[:10], first_10)
# Read last 10 frames (10 - 15 seconds)
last_10 = manifest.load(start=10)
np.testing.assert_equal(array[-10:], last_10)
last_10 = manifest.load(start=10, duration=5)
np.testing.assert_equal(array[-10:], last_10)
# Read middle 10 frames (5 - 10 seconds)
mid_10 = manifest.load(start=5, duration=5)
np.testing.assert_equal(array[10:20], mid_10)
|
[
"tempfile.NamedTemporaryFile",
"tempfile.TemporaryDirectory",
"lhotse.array.Array",
"numpy.testing.assert_almost_equal",
"lhotse.NumpyHdf5Writer",
"numpy.arange",
"numpy.testing.assert_equal",
"lhotse.array.TemporalArray.from_dict",
"pytest.mark.parametrize",
"pytest.mark.xfail"
] |
[((1939, 2017), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""writer_class"""', '[LilcomFilesWriter, LilcomHdf5Writer]'], {}), "('writer_class', [LilcomFilesWriter, LilcomHdf5Writer])\n", (1962, 2017), False, 'import pytest\n'), ((3135, 3170), 'lhotse.array.TemporalArray.from_dict', 'TemporalArray.from_dict', (['serialized'], {}), '(serialized)\n', (3158, 3170), False, 'from lhotse.array import Array, TemporalArray\n'), ((1217, 1237), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (1235, 1237), False, 'from tempfile import TemporaryDirectory, NamedTemporaryFile\n'), ((1676, 1723), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['array', 'restored'], {}), '(array, restored)\n', (1706, 1723), True, 'import numpy as np\n'), ((336, 349), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (345, 349), True, 'import numpy as np\n'), ((2125, 2145), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (2143, 2145), False, 'from tempfile import TemporaryDirectory, NamedTemporaryFile\n'), ((2584, 2631), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['array', 'restored'], {}), '(array, restored)\n', (2614, 2631), True, 'import numpy as np\n'), ((3297, 3329), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'suffix': '""".h5"""'}), "(suffix='.h5')\n", (3315, 3329), False, 'from tempfile import TemporaryDirectory, NamedTemporaryFile\n'), ((3336, 3359), 'lhotse.NumpyHdf5Writer', 'NumpyHdf5Writer', (['f.name'], {}), '(f.name)\n', (3351, 3359), False, 'from lhotse import ChunkedLilcomHdf5Writer, LilcomFilesWriter, LilcomHdf5Writer, NumpyFilesWriter, NumpyHdf5Writer\n'), ((3612, 3652), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['array', 'restored'], {}), '(array, restored)\n', (3635, 3652), True, 'import numpy as np\n'), ((3754, 3799), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['array[:10]', 'first_10'], {}), '(array[:10], first_10)\n', (3777, 3799), True, 'import numpy as np\n'), ((3899, 3944), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['array[-10:]', 'last_10'], {}), '(array[-10:], last_10)\n', (3922, 3944), True, 'import numpy as np\n'), ((4007, 4052), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['array[-10:]', 'last_10'], {}), '(array[-10:], last_10)\n', (4030, 4052), True, 'import numpy as np\n'), ((4163, 4208), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['array[10:20]', 'mid_10'], {}), '(array[10:20], mid_10)\n', (4186, 4208), True, 'import numpy as np\n'), ((2851, 2954), 'lhotse.array.Array', 'Array', ([], {'storage_type': '"""lilcom_hdf5"""', 'storage_path': '"""/tmp/data"""', 'storage_key': '"""irrelevant"""', 'shape': '[300]'}), "(storage_type='lilcom_hdf5', storage_path='/tmp/data', storage_key=\n 'irrelevant', shape=[300])\n", (2856, 2954), False, 'from lhotse.array import Array, TemporalArray\n'), ((3257, 3270), 'numpy.arange', 'np.arange', (['(30)'], {}), '(30)\n', (3266, 3270), True, 'import numpy as np\n'), ((359, 372), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (368, 372), True, 'import numpy as np\n'), ((397, 410), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (406, 410), True, 'import numpy as np\n'), ((437, 450), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (446, 450), True, 'import numpy as np\n'), ((479, 492), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (488, 492), True, 'import numpy as np\n'), ((693, 752), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""Lilcom changes dtype to float32"""'}), "(reason='Lilcom changes dtype to float32')\n", (710, 752), False, 'import pytest\n'), ((835, 894), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""Lilcom changes dtype to float32"""'}), "(reason='Lilcom changes dtype to float32')\n", (852, 894), False, 'import pytest\n'), ((984, 1099), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""Lilcom changes dtype to float32 (and Chunked variant works only with shape 2)"""'}), "(reason=\n 'Lilcom changes dtype to float32 (and Chunked variant works only with shape 2)'\n )\n", (1001, 1099), False, 'import pytest\n'), ((1779, 1792), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (1788, 1792), True, 'import numpy as np\n'), ((1821, 1834), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (1830, 1834), True, 'import numpy as np\n'), ((1878, 1891), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (1887, 1891), True, 'import numpy as np\n')]
|
"""
Create a uniformly spaced (lon,lat) grid of initial particle locations based on nemo bathymetry
"""
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
from mpl_toolkits.basemap import Basemap
spacing = 0.1 #spacing between particles
plotspacing = 1. #For binning of final plot
outdir = './initial_coordinates/'
name = 'coordinates_ddeg01'
def create_particles():
#Create uniform grid of particles
filename='./nemo_bathymetry/bathy_level.nc'
data = Dataset(filename,'r')
bathy=np.array(data['Bathy_level'][0])
lon=np.array([data['nav_lon']][0])
lat=np.array([data['nav_lat']][0])
print('Data loaded')
grid=np.mgrid[-180:180:spacing,-90:90:spacing]
n=grid[0].size;
lons=np.reshape(grid[0],n)
lats=np.reshape(grid[1],n)
print('Interpolating')
bathy_points = griddata(np.array([lon.flatten(), lat.flatten()]).T, bathy.flatten(), (lons, lats), method='nearest')
lons_new=np.array([lons[i] for i in range(len(lons)) if bathy_points[i]!=0])
lats_new=np.array([lats[i] for i in range(len(lats)) if bathy_points[i]!=0])
lons_new[lons_new<0.] += 360.
np.savez(outdir + str(name), lons = lons_new, lats = lats_new)
#create_particles()
def Plot_particles():
#Plot to check if everything went well
data = np.load(outdir + str(name) + '.npz')
lons = data['lons']
lats = data['lats']
# lons=np.load(outdir + 'Lons_full' + str(name) + '.npy')
# lats=np.load(outdir + 'Lats_full' + str(name) + '.npy')
assert (len(lons)==len(lats))
print('Number of particles: ', len(lons))
fig = plt.figure(figsize=(25, 30))
ax = fig.add_subplot(211)
ax.set_title("Particles")
m = Basemap(projection='robin',lon_0=-180,resolution='c')
m.drawcoastlines()
xs, ys = m(lons, lats)
m.scatter(xs,ys)
ax = fig.add_subplot(212)
ax.set_title("Particles per bin. Should be constant everywhere but on land.")
m = Basemap(projection='robin',lon_0=-180,resolution='c')
m.drawcoastlines()
lon_bin_edges = np.arange(0, 360+spacing, plotspacing)
lat_bins_edges = np.arange(-90, 90+spacing, plotspacing)
density, _, _ = np.histogram2d(lats, lons, [lat_bins_edges, lon_bin_edges])
lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bin_edges, lat_bins_edges)
xs, ys = m(lon_bins_2d, lat_bins_2d)
plt.pcolormesh(xs, ys, density,cmap=plt.cm.RdBu_r)
cbar = plt.colorbar(orientation='vertical', shrink=0.625, aspect=20, fraction=0.2,pad=0.02)
cbar.set_label('Particles per bin',size=8)
#Plot_particles()
def split_grid():
data = np.load(outdir + str(name) + '.npz')
lons = data['lons']
lats = data['lats']
print('Total number of particles: ', len(lons))
N=5 #Number of sub-grids
k = len(lons)//N+1 #Number of particles per file
print(k)
for i in range(0,len(lons)//k+1):
lo = lons[i*k:(i+1)*k]
la = lats[i*k:(i+1)*k]
np.savez(outdir + 'coordinates' + str(i), lons = lo, lats=la)
print('shape: ', lo.shape)
#split_grid()
def plot_grid():
##For testing the distribution
plt.figure(figsize=(15,15))
m = Basemap(projection='mill', llcrnrlat=-89., urcrnrlat=89., llcrnrlon=0., urcrnrlon=360., resolution='l')
m.drawcoastlines()
p_tot=0
for i in range(5):
data = np.load(outdir + 'coordinates' + str(i) + '.npz')
lons = data['lons']
print('min: ', np.min(lons))
print('max: ', np.max(lons))
lats = data['lats']
p_tot+=len(lons)
print(len(lons))
xs, ys = m(lons, lats)
m.scatter(xs,ys)
print('total number of particles: ', p_tot)
plot_grid()
|
[
"netCDF4.Dataset",
"numpy.meshgrid",
"numpy.histogram2d",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"numpy.min",
"numpy.array",
"numpy.reshape",
"numpy.arange",
"matplotlib.pyplot.pcolormesh",
"numpy.max",
"mpl_toolkits.basemap.Basemap"
] |
[((535, 557), 'netCDF4.Dataset', 'Dataset', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (542, 557), False, 'from netCDF4 import Dataset\n'), ((567, 599), 'numpy.array', 'np.array', (["data['Bathy_level'][0]"], {}), "(data['Bathy_level'][0])\n", (575, 599), True, 'import numpy as np\n'), ((608, 638), 'numpy.array', 'np.array', (["[data['nav_lon']][0]"], {}), "([data['nav_lon']][0])\n", (616, 638), True, 'import numpy as np\n'), ((647, 677), 'numpy.array', 'np.array', (["[data['nav_lat']][0]"], {}), "([data['nav_lat']][0])\n", (655, 677), True, 'import numpy as np\n'), ((788, 810), 'numpy.reshape', 'np.reshape', (['grid[0]', 'n'], {}), '(grid[0], n)\n', (798, 810), True, 'import numpy as np\n'), ((819, 841), 'numpy.reshape', 'np.reshape', (['grid[1]', 'n'], {}), '(grid[1], n)\n', (829, 841), True, 'import numpy as np\n'), ((1681, 1709), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 30)'}), '(figsize=(25, 30))\n', (1691, 1709), True, 'import matplotlib.pyplot as plt\n'), ((1783, 1838), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""robin"""', 'lon_0': '(-180)', 'resolution': '"""c"""'}), "(projection='robin', lon_0=-180, resolution='c')\n", (1790, 1838), False, 'from mpl_toolkits.basemap import Basemap\n'), ((2034, 2089), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""robin"""', 'lon_0': '(-180)', 'resolution': '"""c"""'}), "(projection='robin', lon_0=-180, resolution='c')\n", (2041, 2089), False, 'from mpl_toolkits.basemap import Basemap\n'), ((2132, 2172), 'numpy.arange', 'np.arange', (['(0)', '(360 + spacing)', 'plotspacing'], {}), '(0, 360 + spacing, plotspacing)\n', (2141, 2172), True, 'import numpy as np\n'), ((2192, 2233), 'numpy.arange', 'np.arange', (['(-90)', '(90 + spacing)', 'plotspacing'], {}), '(-90, 90 + spacing, plotspacing)\n', (2201, 2233), True, 'import numpy as np\n'), ((2257, 2316), 'numpy.histogram2d', 'np.histogram2d', (['lats', 'lons', '[lat_bins_edges, lon_bin_edges]'], {}), '(lats, lons, [lat_bins_edges, lon_bin_edges])\n', (2271, 2316), True, 'import numpy as np\n'), ((2353, 2395), 'numpy.meshgrid', 'np.meshgrid', (['lon_bin_edges', 'lat_bins_edges'], {}), '(lon_bin_edges, lat_bins_edges)\n', (2364, 2395), True, 'import numpy as np\n'), ((2442, 2493), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['xs', 'ys', 'density'], {'cmap': 'plt.cm.RdBu_r'}), '(xs, ys, density, cmap=plt.cm.RdBu_r)\n', (2456, 2493), True, 'import matplotlib.pyplot as plt\n'), ((2504, 2593), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'orientation': '"""vertical"""', 'shrink': '(0.625)', 'aspect': '(20)', 'fraction': '(0.2)', 'pad': '(0.02)'}), "(orientation='vertical', shrink=0.625, aspect=20, fraction=0.2,\n pad=0.02)\n", (2516, 2593), True, 'import matplotlib.pyplot as plt\n'), ((3228, 3256), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 15)'}), '(figsize=(15, 15))\n', (3238, 3256), True, 'import matplotlib.pyplot as plt\n'), ((3264, 3375), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""mill"""', 'llcrnrlat': '(-89.0)', 'urcrnrlat': '(89.0)', 'llcrnrlon': '(0.0)', 'urcrnrlon': '(360.0)', 'resolution': '"""l"""'}), "(projection='mill', llcrnrlat=-89.0, urcrnrlat=89.0, llcrnrlon=0.0,\n urcrnrlon=360.0, resolution='l')\n", (3271, 3375), False, 'from mpl_toolkits.basemap import Basemap\n'), ((3548, 3560), 'numpy.min', 'np.min', (['lons'], {}), '(lons)\n', (3554, 3560), True, 'import numpy as np\n'), ((3585, 3597), 'numpy.max', 'np.max', (['lons'], {}), '(lons)\n', (3591, 3597), True, 'import numpy as np\n')]
|
import os
import numpy as np
def generate_first_N_primes(N):
ii, jj, flag = 0, 0, 0
primes = []
# Traverse each number from 1 to N
# with the help of for loop
for ii in range(1, N + 1, 1):
if (ii == 1 or ii == 0):
# Skip 0 and 1
continue
# flag variable to tell
# if i is prime or not
flag = 1;
for jj in range(2, ((ii // 2) + 1), 1):
if (ii % jj == 0):
flag = 0;
break;
# flag = 1 means ii is prime
# and flag = 0 means ii is not prime
if (flag == 1):
primes.append(ii)
return primes
def generate_halton_samples(dim, n, sf=[1]):
primeNums = generate_first_N_primes(1000)
if len(sf) is not dim:
sf = np.ones(dim)
samples = np.zeros((dim,n))
for idx, base_val in enumerate(primeNums[:dim]):
if sf[idx] > 0:
samples[idx,:] = sf[idx]*generate_halton_sequence(n, base_val)
else:
samples[idx,:] = -2*sf[idx]*(generate_halton_sequence(n, base_val) - 0.5)
return samples
def generate_halton_sequence(n, base):
halton_sequence = np.zeros(n)
for idx, val in enumerate(range(1, n+1)):
halton_sequence[idx] = local_halton_single_number(val, base)
return halton_sequence
def local_halton_single_number(n, b):
n0 = n
hn = 0
f = 1/float(b)
while n0 > 0:
n1 = np.floor(n0/b)
r = n0 - b*n1
hn = hn + f*r
f = f/float(b)
n0 = n1
return hn
|
[
"numpy.floor",
"numpy.zeros",
"numpy.ones"
] |
[((824, 842), 'numpy.zeros', 'np.zeros', (['(dim, n)'], {}), '((dim, n))\n', (832, 842), True, 'import numpy as np\n'), ((1150, 1161), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1158, 1161), True, 'import numpy as np\n'), ((797, 809), 'numpy.ones', 'np.ones', (['dim'], {}), '(dim)\n', (804, 809), True, 'import numpy as np\n'), ((1399, 1415), 'numpy.floor', 'np.floor', (['(n0 / b)'], {}), '(n0 / b)\n', (1407, 1415), True, 'import numpy as np\n')]
|
# Copyright (c) 2020, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ==============================================================================
"""Drawing an ellipsoid in a scikit-image style.
Reference:
https://github.com/scikit-image/scikit-image/blob/v0.16.2/skimage/draw/draw.py
Copyright (C) 2019, the scikit-image team
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of skimage nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import numpy as np
def ellipsoid(center, radii, rotation, scales=None, shape=None, minarea=0):
"""Generate coordinates of pixels within ellipsoid.
Parameters
----------
center : (3,) ndarray of double
Centre coordinate of ellipsoid.
radii : (3,) ndarray of double
Radii of ellipsoid
rotation : (3, 3) ndarray of double
Rotation matrix of ellipsoid.
scales : (3,) array-like of double
Scales of axes w.r.t. center and radii.
shape : tuple, optional
Image shape which is used to determine the maximum extent of output
pixel coordinates. This is useful for ellipsoids which exceed the
image size.
By default the full extent of the ellipsoid is used.
minarea : int
Minumum area to be drawn.
Ellipsoid will be enlarged inside the calculated bounding box until it
reaches to this value.
This parameter is useful when the user wants to force to draw
ellipsoids even when the calculated area is small.
Returns
-------
dd, rr, cc : ndarray of int
Voxel coordinates of ellipsoid.
May be used to directl index into an array, e.g.
``img[dd, rr, cc] = 1``
"""
assert center.shape == (3,)
assert radii.shape == (3,)
assert 0 < radii.max(), "radii should contain at least one positive value"
assert rotation.shape == (3, 3)
if scales is None:
scales = (1.,) * 3
scales = np.array(scales)
assert scales.shape == (3,)
scaled_center = center / scales
# The upper_left_bottom and lower_right_top corners of the smallest cuboid
# containing the ellipsoid.
factor = np.array([
[i, j, k] for k in (-1, 1) for j in (-1, 1) for i in (-1, 1)]).T
while True:
radii_rot = np.abs(
np.diag(1. / scales).dot(rotation.dot(np.diag(radii).dot(factor)))
).max(axis=1)
# In the original scikit-image code, ceil and floor were replaced.
# https://github.com/scikit-image/scikit-image/blob/master/skimage/draw/draw.py#L127
upper_left_bottom = np.floor(scaled_center - radii_rot).astype(int)
lower_right_top = np.ceil(scaled_center + radii_rot).astype(int)
if shape is not None:
# Constrain upper_left and lower_ight by shape boundary.
upper_left_bottom = np.maximum(
upper_left_bottom, np.array([0, 0, 0]))
lower_right_top = np.minimum(
lower_right_top, np.array(shape[:3]) - 1)
bounding_shape = lower_right_top - upper_left_bottom + 1
d_lim, r_lim, c_lim = np.ogrid[0:float(bounding_shape[0]),
0:float(bounding_shape[1]),
0:float(bounding_shape[2])]
d_org, r_org, c_org = scaled_center - upper_left_bottom
d_rad, r_rad, c_rad = radii
rotation_inv = np.linalg.inv(rotation)
conversion_matrix = rotation_inv.dot(np.diag(scales))
d, r, c = (d_lim - d_org), (r_lim - r_org), (c_lim - c_org)
distances = (
((d * conversion_matrix[0, 0] +
r * conversion_matrix[0, 1] +
c * conversion_matrix[0, 2]) / d_rad) ** 2 +
((d * conversion_matrix[1, 0] +
r * conversion_matrix[1, 1] +
c * conversion_matrix[1, 2]) / r_rad) ** 2 +
((d * conversion_matrix[2, 0] +
r * conversion_matrix[2, 1] +
c * conversion_matrix[2, 2]) / c_rad) ** 2
)
if distances.size < minarea:
old_radii = radii.copy()
radii *= 1.1
print('Increase radii from ({}) to ({})'.format(old_radii, radii))
else:
break
distance_thresh = 1
while True:
dd, rr, cc = np.nonzero(distances < distance_thresh)
if len(dd) < minarea:
distance_thresh *= 1.1
else:
break
dd.flags.writeable = True
rr.flags.writeable = True
cc.flags.writeable = True
dd += upper_left_bottom[0]
rr += upper_left_bottom[1]
cc += upper_left_bottom[2]
return dd, rr, cc
|
[
"numpy.ceil",
"numpy.floor",
"numpy.nonzero",
"numpy.linalg.inv",
"numpy.array",
"numpy.diag"
] |
[((4541, 4557), 'numpy.array', 'np.array', (['scales'], {}), '(scales)\n', (4549, 4557), True, 'import numpy as np\n'), ((4752, 4824), 'numpy.array', 'np.array', (['[[i, j, k] for k in (-1, 1) for j in (-1, 1) for i in (-1, 1)]'], {}), '([[i, j, k] for k in (-1, 1) for j in (-1, 1) for i in (-1, 1)])\n', (4760, 4824), True, 'import numpy as np\n'), ((5989, 6012), 'numpy.linalg.inv', 'np.linalg.inv', (['rotation'], {}), '(rotation)\n', (6002, 6012), True, 'import numpy as np\n'), ((6885, 6924), 'numpy.nonzero', 'np.nonzero', (['(distances < distance_thresh)'], {}), '(distances < distance_thresh)\n', (6895, 6924), True, 'import numpy as np\n'), ((6058, 6073), 'numpy.diag', 'np.diag', (['scales'], {}), '(scales)\n', (6065, 6073), True, 'import numpy as np\n'), ((5177, 5212), 'numpy.floor', 'np.floor', (['(scaled_center - radii_rot)'], {}), '(scaled_center - radii_rot)\n', (5185, 5212), True, 'import numpy as np\n'), ((5251, 5285), 'numpy.ceil', 'np.ceil', (['(scaled_center + radii_rot)'], {}), '(scaled_center + radii_rot)\n', (5258, 5285), True, 'import numpy as np\n'), ((5477, 5496), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (5485, 5496), True, 'import numpy as np\n'), ((5573, 5592), 'numpy.array', 'np.array', (['shape[:3]'], {}), '(shape[:3])\n', (5581, 5592), True, 'import numpy as np\n'), ((4892, 4913), 'numpy.diag', 'np.diag', (['(1.0 / scales)'], {}), '(1.0 / scales)\n', (4899, 4913), True, 'import numpy as np\n'), ((4930, 4944), 'numpy.diag', 'np.diag', (['radii'], {}), '(radii)\n', (4937, 4944), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests
import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance
from sklearn import svm, metrics, calibration
from PIL import Image, ExifTags
random.seed(0)
################################
# ImageInfo class and helpers
################################
class ImageInfo(object):
allFeatures = []
def __init__(self, fname, subdir, parent = None):
self.fname = fname
self.subdir = subdir
self.children = []
self.parent = parent
if parent:
self.parent = self.shallowCopy(parent)
def getFeat(self):
if self.allFeatures == []:
raise Exception("Need to set/load DNN features first using e.g. this line 'ImageInfo.allFeatures = loadFromPickle(featuresPath)'")
key = self.subdir + "/" + self.fname
feat = np.array(self.allFeatures[key], np.float32)
assert (len(feat) == 4096 or len(feat) == 2048 or len(feat) == 512 or len(feat) == 25088)
return feat
def getImg(self, rootDir):
imgPath = self.getImgPath(rootDir)
return imread(imgPath)
def getImgPath(self, rootDir):
return rootDir + self.subdir + "/" + self.fname
def addChild(self, node):
node.parent = self
self.children.append(node)
def isSameClassAsParent(self):
return self.subdir == self.parent.subdir
def shallowCopy(self, node):
return ImageInfo(node.fname, node.subdir, node.parent)
def display(self):
print("Parent: " + self.node2Str(self))
for childIndex,child in enumerate(self.children):
print(" Child {:4} : {}".format(childIndex, self.node2Str(child)))
def node2Str(self, node):
return("fname = {}, subdir={}".format(node.fname, node.subdir)) #, node.parent)
def getImgPaths(imgInfos, rootDir=""):
paths = set()
for imgInfo in imgInfos:
paths.add(rootDir + "/" + imgInfo.subdir + "/" + imgInfo.fname)
for child in imgInfo.children:
paths.add(rootDir + "/" + child.subdir + "/" + child.fname)
return paths
def getRandomImgInfo(imgFilenames, subdirToExclude = None):
subdirs = list(imgFilenames.keys())
subdir = getRandomListElement(subdirs)
while subdir == subdirToExclude:
subdir = getRandomListElement(subdirs)
imgFilename = getRandomListElement(imgFilenames[subdir])
return ImageInfo(imgFilename, subdir)
################################
# helper functions - svm
################################
def getImgPairsFeatures(imgInfos, metric, boL2Normalize):
feats = []
labels = []
for queryImgIndex, queryImgInfo in enumerate(imgInfos):
queryFeat = queryImgInfo.getFeat()
if boL2Normalize:
queryFeat /= np.linalg.norm(queryFeat, 2)
for refImgInfo in queryImgInfo.children:
refFeat = refImgInfo.getFeat()
if boL2Normalize:
refFeat /= np.linalg.norm(refFeat, 2)
# Evaluate difference between the two images
featDiff = queryFeat - refFeat
if metric.lower() == 'diff':
feat = featDiff
elif metric.lower() == 'l1':
feat = abs(featDiff)
elif metric.lower() == 'l2':
feat = featDiff ** 2
else:
raise Exception("Unknown metric: " + metric)
feats.append(np.float32(feat))
labels.append(int(refImgInfo.isSameClassAsParent()))
return feats, labels
def mineHardNegatives(learner, imgFilenames, nrAddPerIter, featureDifferenceMetric, boL2Normalize,
maxNrRounds, initialThreshold = 1):
hardNegatives = []
roundCounterHardNegFound = 0
hardNegThreshold = initialThreshold
# Hard negative mining by repeatedly selecting a pair of images and adding to the
# training set if they are misclassified by at least a certain threshold.
for roundCounter in range(maxNrRounds):
roundCounterHardNegFound += 1
if len(hardNegatives) >= nrAddPerIter:
break
# Reduce threshold if no hard negative found after 1000 rounds
if roundCounterHardNegFound > 1000:
hardNegThreshold /= 2.0
roundCounterHardNegFound = 0
print(" Hard negative mining sampling round {:6d}: found {:4d} number of hard negatives; reducing hard negative threshold to {:3.3f}.".format(
roundCounter, len(hardNegatives), hardNegThreshold))
# Sample two images from different ground truth class
ImageInfo1 = getRandomImgInfo(imgFilenames)
ImageInfo2 = getRandomImgInfo(imgFilenames, ImageInfo1.subdir)
ImageInfo1.addChild(ImageInfo2)
# Evaluate svm
featCandidate, labelCandidate = getImgPairsFeatures([ImageInfo1], featureDifferenceMetric, boL2Normalize)
assert (len(labelCandidate) == 1 and labelCandidate[0] == 0 and ImageInfo1.subdir != ImageInfo2.subdir)
score = learner.decision_function(featCandidate)
# If confidence is sufficiently high then add to list of hard negatives
if score > hardNegThreshold:
hardNegatives.append(featCandidate[0])
roundCounterHardNegFound = 0
print(" Hard negatives found: {}, after {} sampling rounds".format(len(hardNegatives), roundCounter+1))
return hardNegatives
def getSampleWeights(labels, negPosRatio = 1):
indsNegatives = np.where(np.array(labels) == 0)[0]
indsPositives = np.where(np.array(labels) != 0)[0]
negWeight = float(negPosRatio) * len(indsPositives) / len(indsNegatives)
weights = np.array([1.0] * len(labels))
weights[indsNegatives] = negWeight
assert (abs(sum(weights[indsNegatives]) - negPosRatio * sum(weights[indsPositives])) < 10 ** -3)
return weights
def plotScoreVsProbability(learner, feats_train, feats_test):
probsTest = learner.predict_proba(feats_test)[:, 1]
probsTrain = learner.predict_proba(feats_train)[:, 1]
scoresTest = learner.base_estimator.decision_function(feats_test)
scoresTrain = learner.base_estimator.decision_function(feats_train)
plt.scatter(scoresTrain, probsTrain, c='r', label = 'train')
plt.scatter(scoresTest, probsTest, c='b', label = 'test')
plt.ylim([-0.02, 1.02])
plt.xlabel('SVM score')
plt.ylabel('Probability')
plt.title('Calibrated SVM - training set (red), test set (blue)')
return plt
################################
# helper functions - general
################################
def getImagePairs(imgFilenames, maxQueryImgsPerSubdir, maxNegImgsPerQueryImg):
# Get sub-directories with at least two images in them
querySubdirs = [s for s in imgFilenames.keys() if len(imgFilenames[s]) > 1]
# Generate pos and neg pairs for each subdir
imgInfos = []
for querySubdir in querySubdirs:
queryFilenames = randomizeList(imgFilenames[querySubdir])
# Pick at most 'maxQueryImgsPerSubdir' query images at random
for queryFilename in queryFilenames[:maxQueryImgsPerSubdir]:
queryInfo = ImageInfo(queryFilename, querySubdir)
# Add one positive example at random
refFilename = getRandomListElement(list(set(queryFilenames) - set([queryFilename])))
queryInfo.children.append(ImageInfo(refFilename, querySubdir, queryInfo))
assert(refFilename != queryFilename)
# Add multiple negative examples at random
for _ in range(maxNegImgsPerQueryImg):
refSubdir = getRandomListElement(list(set(querySubdirs) - set([querySubdir])))
refFilename = getRandomListElement(imgFilenames[refSubdir])
queryInfo.children.append(ImageInfo(refFilename, refSubdir, queryInfo))
assert(refSubdir != querySubdir)
# Store
queryInfo.children = randomizeList(queryInfo.children)
imgInfos.append(queryInfo)
print("Generated image pairs for {} query images, each with 1 positive image pair and {} negative image pairs.".format(len(imgInfos), maxNegImgsPerQueryImg))
return imgInfos
def getImgLabelMap(imgFilenames, imgDir, lut = None):
table = []
for label in imgFilenames.keys():
for imgFilename in imgFilenames[label]:
imgPath = imgDir + "/" + str(label) + "/" + imgFilename
if lut != None:
table.append((imgPath, lut[label]))
else:
table.append((imgPath, label))
return table
def balanceDatasetUsingDuplicates(data):
duplicates = []
counts = collections.Counter(getColumn(data,1))
print("Before balancing of training set:")
for item in counts.items():
print(" Class {:3}: {:5} exmples".format(*item))
# Get duplicates to balance dataset
targetCount = max(getColumn(counts.items(), 1))
while min(getColumn(counts.items(),1)) < targetCount:
for imgPath, label in data:
if counts[label] < targetCount:
duplicates.append((imgPath, label))
counts[label] += 1
# Add duplicates to original dataset
print("After balancing: all classes now have {} images; added {} duplicates to the {} original images.".format(targetCount, len(duplicates), len(data)))
data += duplicates
counts = collections.Counter(getColumn(data,1))
assert(min(counts.values()) == max(counts.values()) == targetCount)
return data
def printFeatLabelInfo(title, feats, labels, preString = " "):
print(title)
print(preString + "Number of examples: {}".format(len(feats)))
print(preString + "Number of positive examples: {}".format(sum(np.array(labels) == 1)))
print(preString + "Number of negative examples: {}".format(sum(np.array(labels) == 0)))
print(preString + "Dimension of each example: {}".format(len(feats[0])))
def sklearnAccuracy(learner, feats, gtLabels):
estimatedLabels = learner.predict(feats)
confusionMatrix = metrics.confusion_matrix(gtLabels, estimatedLabels)
return accsConfusionMatrix(confusionMatrix)
####################################
# Subset of helper library
# used in image similarity tutorial
####################################
# Typical meaning of variable names -- Computer Vision:
# pt = 2D point (column,row)
# img = image
# width,height (or w/h) = image dimensions
# bbox = bbox object (stores: left, top,right,bottom co-ordinates)
# rect = rectangle (order: left, top, right, bottom)
# angle = rotation angle in degree
# scale = image up/downscaling factor
# Typical meaning of variable names -- general:
# lines,strings = list of strings
# line,string = single string
# xmlString = string with xml tags
# table = 2D row/column matrix implemented using a list of lists
# row,list1D = single row in a table, i.e. single 1D-list
# rowItem = single item in a row
# list1D = list of items, not necessarily strings
# item = single item of a list1D
# slotValue = e.g. "terminator" in: play <movie> terminator </movie>
# slotTag = e.g. "<movie>" or "</movie>" in: play <movie> terminator </movie>
# slotName = e.g. "movie" in: play <movie> terminator </movie>
# slot = e.g. "<movie> terminator </movie>" in: play <movie> terminator </movie>
def readFile(inputFile):
# Reading as binary, to avoid problems with end-of-text characters.
# Note that readlines() does not remove the line ending characters
with open(inputFile,'rb') as f:
lines = f.readlines()
for i,s in enumerate(lines):
removeLineEndCharacters(s.decode('utf8'))
return [removeLineEndCharacters(s.decode('utf8')) for s in lines];
def writeFile(outputFile, lines, header=None):
with open(outputFile,'w') as f:
if header != None:
f.write("%s\n" % header)
for line in lines:
f.write("%s\n" % line)
def writeBinaryFile(outputFile, data):
with open(outputFile,'wb') as f:
bytes = f.write(data)
return bytes
def readTable(inputFile, delimiter='\t'):
lines = readFile(inputFile);
return splitStrings(lines, delimiter)
def writeTable(outputFile, table, header=None):
lines = tableToList1D(table)
writeFile(outputFile, lines, header)
def loadFromPickle(inputFile):
with open(inputFile, 'rb') as filePointer:
data = pickle.load(filePointer)
return data
def saveToPickle(outputFile, data):
p = pickle.Pickler(open(outputFile,"wb"))
p.fast = True
p.dump(data)
def makeDirectory(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def getFilesInDirectory(directory, postfix=""):
if not os.path.exists(directory):
return []
fileNames = [s for s in os.listdir(directory) if not os.path.isdir(directory + "/" + s)]
if not postfix or postfix == "":
return fileNames
else:
return [s for s in fileNames if s.lower().endswith(postfix)]
def getDirectoriesInDirectory(directory):
return [s for s in os.listdir(directory) if os.path.isdir(directory + "/" + s)]
def downloadFromUrl(url, boVerbose = True):
data = []
url = url.strip()
try:
r = requests.get(url, timeout = 1)
data = r.content
except:
if boVerbose:
print('Error downloading url {0}'.format(url))
if boVerbose and data == []: # and r.status_code != 200:
print('Error {} downloading url {}'.format(r.status_code, url))
return data
def removeLineEndCharacters(line):
if line.endswith('\r\n'):
return line[:-2]
elif line.endswith('\n'):
return line[:-1]
else:
return line
def splitString(string, delimiter='\t', columnsToKeepIndices=None):
if string == None:
return None
items = string.split(delimiter)
if columnsToKeepIndices != None:
items = getColumns([items], columnsToKeepIndices)
items = items[0]
return items
def splitStrings(strings, delimiter, columnsToKeepIndices=None):
table = [splitString(string, delimiter, columnsToKeepIndices) for string in strings]
return table
def getColumn(table, columnIndex):
column = []
for row in table:
column.append(row[columnIndex])
return column
def tableToList1D(table, delimiter='\t'):
return [delimiter.join([str(s) for s in row]) for row in table]
def ToIntegers(list1D):
return [int(float(x)) for x in list1D]
def mergeDictionaries(dict1, dict2):
tmp = dict1.copy()
tmp.update(dict2)
return tmp
def getRandomNumber(low, high):
randomNumber = random.randint(low,high)
return randomNumber
def randomizeList(listND, containsHeader=False):
if containsHeader:
header = listND[0]
listND = listND[1:]
random.shuffle(listND)
if containsHeader:
listND.insert(0, header)
return listND
def getRandomListElement(listND, containsHeader=False):
if containsHeader:
index = getRandomNumber(1, len(listND) - 1)
else:
index = getRandomNumber(0, len(listND) - 1)
return listND[index]
def accsConfusionMatrix(confMatrix):
perClassAccs = [(1.0 * row[rowIndex] / sum(row)) for rowIndex,row in enumerate(confMatrix)]
return perClassAccs
def computeVectorDistance(vec1, vec2, method, boL2Normalize, weights = [], bias = [], learner = []):
# Pre-processing
if boL2Normalize:
vec1 = vec1 / np.linalg.norm(vec1, 2)
vec2 = vec2 / np.linalg.norm(vec2, 2)
assert (len(vec1) == len(vec2))
# Distance computation
vecDiff = vec1 - vec2
method = method.lower()
if method == 'random':
dist = random.random()
elif method == 'l1':
dist = sum(abs(vecDiff))
elif method == 'l2':
dist = np.linalg.norm(vecDiff, 2)
elif method == 'normalizedl2':
a = vec1 / np.linalg.norm(vec1, 2)
b = vec2 / np.linalg.norm(vec2, 2)
dist = np.linalg.norm(a - b, 2)
elif method == "cosine":
dist = scipy.spatial.distance.cosine(vec1, vec2)
elif method == "correlation":
dist = scipy.spatial.distance.correlation(vec1, vec2)
elif method == "chisquared":
dist = chiSquared(vec1, vec2)
elif method == "normalizedchisquared":
a = vec1 / sum(vec1)
b = vec2 / sum(vec2)
dist = chiSquared(a, b)
elif method == "hamming":
dist = scipy.spatial.distance.hamming(vec1 > 0, vec2 > 0)
elif method == "mahalanobis":
#assumes covariance matric is provided, e..g. using: sampleCovMat = np.cov(np.transpose(np.array(feats)))
dist = scipy.spatial.distance.mahalanobis(vec1, vec2, sampleCovMat)
elif method == 'weightedl1':
feat = np.float32(abs(vecDiff))
dist = np.dot(weights, feat) + bias
dist = -float(dist)
# assert(abs(dist - learnerL1.decision_function([feat])) < 0.000001)
elif method == 'weightedl2':
feat = (vecDiff) ** 2
dist = np.dot(weights, feat) + bias
dist = -float(dist)
elif method == 'weightedl2prob':
feat = (vecDiff) ** 2
dist = learner.predict_proba([feat])[0][1]
dist = float(dist)
# elif method == 'learnerscore':
# feat = (vecDiff) ** 2
# dist = learner.base_estimator.decision_function([feat])[0]
# dist = -float(dist)
else:
raise Exception("Distance method unknown: " + method)
assert (not np.isnan(dist))
return dist
def rotationFromExifTag(imgPath):
TAGSinverted = {v: k for k, v in list(ExifTags.TAGS.items())}
orientationExifId = TAGSinverted['Orientation']
try:
imageExifTags = Image.open(imgPath)._getexif()
except:
imageExifTags = None
#rotate the image if orientation exif tag is present
rotation = 0
if imageExifTags != None and orientationExifId != None and orientationExifId in imageExifTags:
orientation = imageExifTags[orientationExifId]
if orientation == 1 or orientation == 0:
rotation = 0 #no need to do anything
elif orientation == 6:
rotation = -90
elif orientation == 8:
rotation = 90
else:
raise Exception("ERROR: orientation = " + str(orientation) + " not_supported!")
return rotation
def imread(imgPath, boThrowErrorIfExifRotationTagSet = True):
if not os.path.exists(imgPath):
raise Exception("ERROR: image path does not exist.")
rotation = rotationFromExifTag(imgPath)
if boThrowErrorIfExifRotationTagSet and rotation != 0:
print("Error: exif roation tag set, image needs to be rotated by %d degrees." % rotation)
img = cv2.imread(imgPath)
if img is None:
raise Exception("ERROR: cannot load image " + imgPath)
if rotation != 0:
img = imrotate(img, -90).copy() # To avoid occassional error: "TypeError: Layout of the output array img is incompatible with cv::Mat"
return img
def imWidth(input):
return imWidthHeight(input)[0]
def imHeight(input):
return imWidthHeight(input)[1]
def imWidthHeight(input):
if type(input) is str: #or type(input) is unicode:
width, height = Image.open(input).size # This does not load the full image
else:
width = input.shape[1]
height = input.shape[0]
return width,height
def imconvertCv2Numpy(img):
(b,g,r) = cv2.split(img)
return cv2.merge([r,g,b])
def imconvertCv2Pil(img):
cv2_im = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
pil_im = Image.fromarray(cv2_im)
return pil_im
def imconvertPil2Cv(pilImg):
return imconvertPil2Numpy(pilImg)[:, :, ::-1]
def imconvertPil2Numpy(pilImg):
rgb = pilImg.convert('RGB')
return np.array(rgb).copy()
def imresize(img, scale, interpolation = cv2.INTER_LINEAR):
return cv2.resize(img, (0,0), fx=scale, fy=scale, interpolation=interpolation)
def imresizeMaxDim(img, maxDim, boUpscale = False, interpolation = cv2.INTER_LINEAR):
scale = 1.0 * maxDim / max(img.shape[:2])
if scale < 1 or boUpscale:
img = imresize(img, scale, interpolation)
else:
scale = 1.0
return img, scale
def imresizeAndPad(img, width, height, padColor):
# resize image
imgWidth, imgHeight = imWidthHeight(img)
scale = min(float(width) / float(imgWidth), float(height) / float(imgHeight))
imgResized = imresize(img, scale) #, interpolation=cv2.INTER_NEAREST)
resizedWidth, resizedHeight = imWidthHeight(imgResized)
# pad image
top = int(max(0, np.round((height - resizedHeight) / 2)))
left = int(max(0, np.round((width - resizedWidth) / 2)))
bottom = height - top - resizedHeight
right = width - left - resizedWidth
return cv2.copyMakeBorder(imgResized, top, bottom, left, right,
cv2.BORDER_CONSTANT, value=padColor)
def imrotate(img, angle):
imgPil = imconvertCv2Pil(img)
imgPil = imgPil.rotate(angle, expand=True)
return imconvertPil2Cv(imgPil)
def imshow(img, waitDuration=0, maxDim = None, windowName = 'img'):
if isinstance(img, str): # Test if 'img' is a string
img = cv2.imread(img)
if maxDim is not None:
scaleVal = 1.0 * maxDim / max(img.shape[:2])
if scaleVal < 1:
img = imresize(img, scaleVal)
cv2.imshow(windowName, img)
cv2.waitKey(waitDuration)
|
[
"matplotlib.pyplot.title",
"random.shuffle",
"numpy.isnan",
"pickle.load",
"numpy.linalg.norm",
"cv2.imshow",
"numpy.round",
"random.randint",
"cv2.cvtColor",
"cv2.copyMakeBorder",
"os.path.exists",
"cv2.split",
"random.seed",
"requests.get",
"cv2.resize",
"matplotlib.pyplot.ylim",
"cv2.waitKey",
"random.random",
"matplotlib.pyplot.ylabel",
"cv2.merge",
"numpy.dot",
"os.listdir",
"os.makedirs",
"os.path.isdir",
"matplotlib.pyplot.scatter",
"numpy.float32",
"PIL.Image.open",
"cv2.imread",
"numpy.array",
"PIL.ExifTags.TAGS.items",
"PIL.Image.fromarray",
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.xlabel"
] |
[((257, 271), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (268, 271), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((6221, 6279), 'matplotlib.pyplot.scatter', 'plt.scatter', (['scoresTrain', 'probsTrain'], {'c': '"""r"""', 'label': '"""train"""'}), "(scoresTrain, probsTrain, c='r', label='train')\n", (6232, 6279), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((6286, 6341), 'matplotlib.pyplot.scatter', 'plt.scatter', (['scoresTest', 'probsTest'], {'c': '"""b"""', 'label': '"""test"""'}), "(scoresTest, probsTest, c='b', label='test')\n", (6297, 6341), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((6350, 6373), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-0.02, 1.02]'], {}), '([-0.02, 1.02])\n', (6358, 6373), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((6378, 6401), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""SVM score"""'], {}), "('SVM score')\n", (6388, 6401), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((6406, 6431), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Probability"""'], {}), "('Probability')\n", (6416, 6431), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((6436, 6501), 'matplotlib.pyplot.title', 'plt.title', (['"""Calibrated SVM - training set (red), test set (blue)"""'], {}), "('Calibrated SVM - training set (red), test set (blue)')\n", (6445, 6501), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((10062, 10113), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['gtLabels', 'estimatedLabels'], {}), '(gtLabels, estimatedLabels)\n', (10086, 10113), False, 'from sklearn import svm, metrics, calibration\n'), ((14823, 14848), 'random.randint', 'random.randint', (['low', 'high'], {}), '(low, high)\n', (14837, 14848), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((15004, 15026), 'random.shuffle', 'random.shuffle', (['listND'], {}), '(listND)\n', (15018, 15026), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((18871, 18890), 'cv2.imread', 'cv2.imread', (['imgPath'], {}), '(imgPath)\n', (18881, 18890), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((19574, 19588), 'cv2.split', 'cv2.split', (['img'], {}), '(img)\n', (19583, 19588), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((19600, 19620), 'cv2.merge', 'cv2.merge', (['[r, g, b]'], {}), '([r, g, b])\n', (19609, 19620), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((19659, 19695), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (19671, 19695), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((19708, 19731), 'PIL.Image.fromarray', 'Image.fromarray', (['cv2_im'], {}), '(cv2_im)\n', (19723, 19731), False, 'from PIL import Image, ExifTags\n'), ((19999, 20071), 'cv2.resize', 'cv2.resize', (['img', '(0, 0)'], {'fx': 'scale', 'fy': 'scale', 'interpolation': 'interpolation'}), '(img, (0, 0), fx=scale, fy=scale, interpolation=interpolation)\n', (20009, 20071), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((20904, 21002), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['imgResized', 'top', 'bottom', 'left', 'right', 'cv2.BORDER_CONSTANT'], {'value': 'padColor'}), '(imgResized, top, bottom, left, right, cv2.\n BORDER_CONSTANT, value=padColor)\n', (20922, 21002), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((21478, 21505), 'cv2.imshow', 'cv2.imshow', (['windowName', 'img'], {}), '(windowName, img)\n', (21488, 21505), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((21510, 21535), 'cv2.waitKey', 'cv2.waitKey', (['waitDuration'], {}), '(waitDuration)\n', (21521, 21535), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((917, 960), 'numpy.array', 'np.array', (['self.allFeatures[key]', 'np.float32'], {}), '(self.allFeatures[key], np.float32)\n', (925, 960), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((12604, 12628), 'pickle.load', 'pickle.load', (['filePointer'], {}), '(filePointer)\n', (12615, 12628), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((12805, 12830), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (12819, 12830), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((12840, 12862), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (12851, 12862), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((12923, 12948), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (12937, 12948), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((13431, 13459), 'requests.get', 'requests.get', (['url'], {'timeout': '(1)'}), '(url, timeout=1)\n', (13443, 13459), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((15875, 15890), 'random.random', 'random.random', ([], {}), '()\n', (15888, 15890), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((17642, 17656), 'numpy.isnan', 'np.isnan', (['dist'], {}), '(dist)\n', (17650, 17656), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((18574, 18597), 'os.path.exists', 'os.path.exists', (['imgPath'], {}), '(imgPath)\n', (18588, 18597), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((21311, 21326), 'cv2.imread', 'cv2.imread', (['img'], {}), '(img)\n', (21321, 21326), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((2840, 2868), 'numpy.linalg.norm', 'np.linalg.norm', (['queryFeat', '(2)'], {}), '(queryFeat, 2)\n', (2854, 2868), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((12996, 13017), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (13006, 13017), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((13268, 13289), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (13278, 13289), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((13293, 13327), 'os.path.isdir', 'os.path.isdir', (["(directory + '/' + s)"], {}), "(directory + '/' + s)\n", (13306, 13327), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((15645, 15668), 'numpy.linalg.norm', 'np.linalg.norm', (['vec1', '(2)'], {}), '(vec1, 2)\n', (15659, 15668), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((15691, 15714), 'numpy.linalg.norm', 'np.linalg.norm', (['vec2', '(2)'], {}), '(vec2, 2)\n', (15705, 15714), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((19374, 19391), 'PIL.Image.open', 'Image.open', (['input'], {}), '(input)\n', (19384, 19391), False, 'from PIL import Image, ExifTags\n'), ((19906, 19919), 'numpy.array', 'np.array', (['rgb'], {}), '(rgb)\n', (19914, 19919), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((20708, 20746), 'numpy.round', 'np.round', (['((height - resizedHeight) / 2)'], {}), '((height - resizedHeight) / 2)\n', (20716, 20746), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((20771, 20807), 'numpy.round', 'np.round', (['((width - resizedWidth) / 2)'], {}), '((width - resizedWidth) / 2)\n', (20779, 20807), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((3019, 3045), 'numpy.linalg.norm', 'np.linalg.norm', (['refFeat', '(2)'], {}), '(refFeat, 2)\n', (3033, 3045), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((3480, 3496), 'numpy.float32', 'np.float32', (['feat'], {}), '(feat)\n', (3490, 3496), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((5532, 5548), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (5540, 5548), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((5587, 5603), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (5595, 5603), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((13025, 13059), 'os.path.isdir', 'os.path.isdir', (["(directory + '/' + s)"], {}), "(directory + '/' + s)\n", (13038, 13059), False, 'import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests\n'), ((15989, 16015), 'numpy.linalg.norm', 'np.linalg.norm', (['vecDiff', '(2)'], {}), '(vecDiff, 2)\n', (16003, 16015), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((17751, 17772), 'PIL.ExifTags.TAGS.items', 'ExifTags.TAGS.items', ([], {}), '()\n', (17770, 17772), False, 'from PIL import Image, ExifTags\n'), ((17860, 17879), 'PIL.Image.open', 'Image.open', (['imgPath'], {}), '(imgPath)\n', (17870, 17879), False, 'from PIL import Image, ExifTags\n'), ((16152, 16176), 'numpy.linalg.norm', 'np.linalg.norm', (['(a - b)', '(2)'], {}), '(a - b, 2)\n', (16166, 16176), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((9752, 9768), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (9760, 9768), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((9844, 9860), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (9852, 9860), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((16070, 16093), 'numpy.linalg.norm', 'np.linalg.norm', (['vec1', '(2)'], {}), '(vec1, 2)\n', (16084, 16093), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((16113, 16136), 'numpy.linalg.norm', 'np.linalg.norm', (['vec2', '(2)'], {}), '(vec2, 2)\n', (16127, 16136), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((16971, 16992), 'numpy.dot', 'np.dot', (['weights', 'feat'], {}), '(weights, feat)\n', (16977, 16992), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n'), ((17183, 17204), 'numpy.dot', 'np.dot', (['weights', 'feat'], {}), '(weights, feat)\n', (17189, 17204), True, 'import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance\n')]
|
import numpy as np
array = np.array([
[[+0, +1, +2], [+3, +4, +5], [+6, +7, +8], [+9, 10, 11], [12, 13, 14]],
[[15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]],
[[30, 31, 32], [33, 34, 35], [36, 37, 38], [39, 40, 41], [42, 43, 44]],
[[45, 46, 47], [48, 49, 50], [51, 52, 53], [54, 55, 56], [57, 58, 59]],
])
array_flat = array.flatten(order='F')
tmp = np.array(array.T)
for i in np.nditer(array):
print(i)
print('==========')
for i in np.nditer(tmp):
print(i)
print('==========')
for i in np.nditer(array, order='F'):
print(i)
# %%
print('Array in F style flattened:\n', array.flatten(order='F'))
print('Array in F style recovered:\n', array.flatten(order='F').reshape(*array.shape, order='F'))
|
[
"numpy.nditer",
"numpy.array"
] |
[((28, 342), 'numpy.array', 'np.array', (['[[[+0, +1, +2], [+3, +4, +5], [+6, +7, +8], [+9, 10, 11], [12, 13, 14]], [[\n 15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]], [\n [30, 31, 32], [33, 34, 35], [36, 37, 38], [39, 40, 41], [42, 43, 44]],\n [[45, 46, 47], [48, 49, 50], [51, 52, 53], [54, 55, 56], [57, 58, 59]]]'], {}), '([[[+0, +1, +2], [+3, +4, +5], [+6, +7, +8], [+9, 10, 11], [12, 13,\n 14]], [[15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28,\n 29]], [[30, 31, 32], [33, 34, 35], [36, 37, 38], [39, 40, 41], [42, 43,\n 44]], [[45, 46, 47], [48, 49, 50], [51, 52, 53], [54, 55, 56], [57, 58,\n 59]]])\n', (36, 342), True, 'import numpy as np\n'), ((392, 409), 'numpy.array', 'np.array', (['array.T'], {}), '(array.T)\n', (400, 409), True, 'import numpy as np\n'), ((420, 436), 'numpy.nditer', 'np.nditer', (['array'], {}), '(array)\n', (429, 436), True, 'import numpy as np\n'), ((480, 494), 'numpy.nditer', 'np.nditer', (['tmp'], {}), '(tmp)\n', (489, 494), True, 'import numpy as np\n'), ((539, 566), 'numpy.nditer', 'np.nditer', (['array'], {'order': '"""F"""'}), "(array, order='F')\n", (548, 566), True, 'import numpy as np\n')]
|
import numpy as np
import cvxpy as cvx
class BlackLittermanPortfolio():
def __init__(self, exp_returns, sigma, market_cap, prior, delta, tau, min_returns, omega):
if len(prior) == 0:
self.prior = self.calculate_prior(sigma, market_cap, delta, tau)
else:
self.prior = prior
self.likelihood = self.calculate_likelihood(exp_returns, sigma, tau)
self.posterior = self.master_formula(self.prior, self.likelihood)
self.optimal_weights = self.optimize_problem(self.posterior, omega, min_returns)
def calculate_prior(self, sigma, market_cap, delta, tau):
market_cap = (np.array(market_cap)).reshape((-1,1))
equilibrium_returns = delta * (sigma @ market_cap)
return [equilibrium_returns, tau * sigma]
def calculate_likelihood(self, expected_returns, sigma, tau):
views_vector = (np.array(expected_returns)).reshape((-1,1))
absolute_pick_matrix = np.identity(views_vector.shape[0])
omega = np.diag(np.diag(tau * absolute_pick_matrix @ sigma @ absolute_pick_matrix))
return [views_vector, omega]
def master_formula(self, prior, likelihood):
mu_prior, sigma_prior = prior[0], prior[1]
mu_likelihood, sigma_likelihood = likelihood[0], likelihood[1]
mu_bl = np.linalg.inv(np.linalg.inv(sigma_prior) + np.linalg.inv(sigma_likelihood)) @\
(np.linalg.inv(sigma_prior)@ mu_prior + np.linalg.inv(sigma_likelihood) @ mu_likelihood)
sigma_bl = np.linalg.inv(np.linalg.inv(sigma_prior) + np.linalg.inv(sigma_likelihood))
return [mu_bl, sigma_bl]
def optimize_problem(self, posterior, omega, min_returns):
mu, sigma = posterior[0], posterior[1]
dim = mu.shape[0]
w = cvx.Variable(dim)
obj = cvx.Minimize(cvx.quad_form(w, sigma))
mu_t = np.reshape(mu, (1, -1))
constr_1 = mu_t @ w
constr_2 = sum(w)
problem = cvx.Problem(obj, [constr_1 >= min_returns, constr_2 == 1])
problem.solve()
return w.value
def get_weights(self):
return self.optimal_weights
def get_posterior(self):
return self.posterior
'''
import pandas as pd
df_dataprojets = pd.read_excel('portfolio_optimization/DataProjets.xls', sheet_name=0)
df_marketcap = pd.read_excel('portfolio_optimization/DataProjets.xls', sheet_name=1, index_col=0)
df_sector = pd.read_excel('portfolio_optimization/DataProjets.xls', sheet_name=2)
df_bechmark =pd.read_excel('portfolio_optimization/DataProjets.xls', sheet_name=3, index_col = 0)
tickers = list(df_dataprojets['Tickers'].values)
df_marketcap.index = pd.to_datetime(df_marketcap.index)
df_marketcap_month = df_marketcap.resample('1D')
df_marketcap_month = df_marketcap_month.mean()
df_marketcap_month.fillna(method = 'ffill', inplace = True)
correspondences = df_dataprojets[['Sedol', 'Tickers']]
correspondences.set_index('Sedol', drop = True, inplace = True)
correspondences_dict = correspondences.to_dict()['Tickers']
df_marketcap_month.rename(columns = correspondences_dict, inplace = True)
tickers = ['AAPL', 'IBM', 'BLK', 'AMZN', 'XOM', 'NKE']
tickers_marketcap = df_marketcap_month[tickers]
from mu import *
from sigma import *
from dataloader import *
from markowitz import *
from robust_optimiser import *
from mean_variance_portfolio import *
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
period = '12mo'
rebalancing_freq = 5*20
data = Dataloader(period, tickers, rebalancing_freq)
dates, tickers_close_info = data.get_close()
close_returns = pd.DataFrame()
i = 0
prior = []
for close_df in tickers_close_info:
tickers_close_returns = (close_df/close_df.shift(1)).dropna() - 1
exp_returns = mu(tickers_close_returns, tickers, rebalancing_freq).get_mu()
# exp_returns = (tickers_close_returns.iloc[-1].values)
sigma = Sigma(tickers_close_returns, rebalancing_freq).get_sigma()
# sigma = tickers_close_returns.cov().to_numpy()
omega=np.diag(np.diag(sigma))
if i > 0:
markowitz_df = (tickers_close_returns.multiply(markowitz_weights)).sum(axis = 1)
mvo_df = (tickers_close_returns.multiply(mvo_weights)).sum(axis = 1)
tickers_close_returns['Portfolio Black-Litterman'] = markowitz_df
tickers_close_returns['Portfolio Robust'] = mvo_df
tickers_close_returns.dropna(axis = 0, inplace = True)
close_returns = close_returns.append(tickers_close_returns)
else:
i = 1
end_date = list(tickers_close_returns.index)[-1]
marketcap = tickers_marketcap.loc[end_date].values
markowitz = BlackLittermanPortfolio(exp_returns, sigma, marketcap, prior, 0.1, 0.75, 0.2, omega)
mvo = RobustOptimiser(exp_returns, sigma, omega, 5,8)
markowitz_weights = markowitz.get_weights()
mvo_weights = mvo.get_w_robust()
markowitz_weights = markowitz_weights/sum(abs(markowitz_weights))
mvo_weights = mvo_weights/sum(abs(mvo_weights))
prior = markowitz.get_posterior()
close_returns = (close_returns + 1).cumprod(axis = 0)
close_returns[['Portfolio Black-Litterman', 'Portfolio Robust']].plot()
plt.show()
'''
|
[
"numpy.identity",
"numpy.array",
"cvxpy.Problem",
"numpy.reshape",
"cvxpy.Variable",
"numpy.linalg.inv",
"numpy.diag",
"cvxpy.quad_form"
] |
[((960, 994), 'numpy.identity', 'np.identity', (['views_vector.shape[0]'], {}), '(views_vector.shape[0])\n', (971, 994), True, 'import numpy as np\n'), ((1780, 1797), 'cvxpy.Variable', 'cvx.Variable', (['dim'], {}), '(dim)\n', (1792, 1797), True, 'import cvxpy as cvx\n'), ((1865, 1888), 'numpy.reshape', 'np.reshape', (['mu', '(1, -1)'], {}), '(mu, (1, -1))\n', (1875, 1888), True, 'import numpy as np\n'), ((1962, 2020), 'cvxpy.Problem', 'cvx.Problem', (['obj', '[constr_1 >= min_returns, constr_2 == 1]'], {}), '(obj, [constr_1 >= min_returns, constr_2 == 1])\n', (1973, 2020), True, 'import cvxpy as cvx\n'), ((1019, 1085), 'numpy.diag', 'np.diag', (['(tau * absolute_pick_matrix @ sigma @ absolute_pick_matrix)'], {}), '(tau * absolute_pick_matrix @ sigma @ absolute_pick_matrix)\n', (1026, 1085), True, 'import numpy as np\n'), ((1825, 1848), 'cvxpy.quad_form', 'cvx.quad_form', (['w', 'sigma'], {}), '(w, sigma)\n', (1838, 1848), True, 'import cvxpy as cvx\n'), ((643, 663), 'numpy.array', 'np.array', (['market_cap'], {}), '(market_cap)\n', (651, 663), True, 'import numpy as np\n'), ((885, 911), 'numpy.array', 'np.array', (['expected_returns'], {}), '(expected_returns)\n', (893, 911), True, 'import numpy as np\n'), ((1526, 1552), 'numpy.linalg.inv', 'np.linalg.inv', (['sigma_prior'], {}), '(sigma_prior)\n', (1539, 1552), True, 'import numpy as np\n'), ((1555, 1586), 'numpy.linalg.inv', 'np.linalg.inv', (['sigma_likelihood'], {}), '(sigma_likelihood)\n', (1568, 1586), True, 'import numpy as np\n'), ((1327, 1353), 'numpy.linalg.inv', 'np.linalg.inv', (['sigma_prior'], {}), '(sigma_prior)\n', (1340, 1353), True, 'import numpy as np\n'), ((1356, 1387), 'numpy.linalg.inv', 'np.linalg.inv', (['sigma_likelihood'], {}), '(sigma_likelihood)\n', (1369, 1387), True, 'import numpy as np\n'), ((1405, 1431), 'numpy.linalg.inv', 'np.linalg.inv', (['sigma_prior'], {}), '(sigma_prior)\n', (1418, 1431), True, 'import numpy as np\n'), ((1444, 1475), 'numpy.linalg.inv', 'np.linalg.inv', (['sigma_likelihood'], {}), '(sigma_likelihood)\n', (1457, 1475), True, 'import numpy as np\n')]
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides WCS helper tools.
"""
from astropy import units as u
from astropy.coordinates import UnitSphericalRepresentation
from astropy.wcs import WCS
from astropy.wcs.utils import pixel_to_skycoord, skycoord_to_pixel
import numpy as np
def _pixel_to_world(xpos, ypos, wcs):
"""
Calculate the sky coordinates at the input pixel positions.
Parameters
----------
xpos, ypos : float or array-like
The x and y pixel position(s).
wcs : WCS object or `None`
A world coordinate system (WCS) transformation that
supports the `astropy shared interface for WCS
<https://docs.astropy.org/en/stable/wcs/wcsapi.html>`_ (e.g.,
`astropy.wcs.WCS`, `gwcs.wcs.WCS`).
Returns
-------
skycoord : `~astropy.coordinates.SkyCoord`
The sky coordinate(s) at the input position(s).
"""
if wcs is None:
return None
# NOTE: unitless gwcs objects fail with Quantity inputs
if isinstance(xpos, u.Quantity) or isinstance(ypos, u.Quantity):
raise TypeError('xpos and ypos must not be Quantity objects')
try:
return wcs.pixel_to_world(xpos, ypos)
except AttributeError:
if isinstance(wcs, WCS):
# for Astropy < 3.1 WCS support
return pixel_to_skycoord(xpos, ypos, wcs, origin=0)
else:
raise ValueError('Input wcs does not support the shared WCS '
'interface.')
def _world_to_pixel(skycoord, wcs):
"""
Calculate the sky coordinates at the input pixel positions.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
The sky coordinate(s).
wcs : WCS object or `None`
A world coordinate system (WCS) transformation that
supports the `astropy shared interface for WCS
<https://docs.astropy.org/en/stable/wcs/wcsapi.html>`_ (e.g.,
`astropy.wcs.WCS`, `gwcs.wcs.WCS`).
Returns
-------
xpos, ypos : float or array-like
The x and y pixel position(s) at the input sky coordinate(s).
"""
if wcs is None:
return None
try:
return wcs.world_to_pixel(skycoord)
except AttributeError:
if isinstance(wcs, WCS):
# for Astropy < 3.1 WCS support
return skycoord_to_pixel(skycoord, wcs, origin=0)
else:
raise ValueError('Input wcs does not support the shared WCS '
'interface.')
def _pixel_scale_angle_at_skycoord(skycoord, wcs, offset=1.0*u.arcsec):
"""
Calculate the pixel scale and WCS rotation angle at the position of
a SkyCoord coordinate.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
The SkyCoord coordinate.
wcs : WCS object
A world coordinate system (WCS) transformation that
supports the `astropy shared interface for WCS
<https://docs.astropy.org/en/stable/wcs/wcsapi.html>`_ (e.g.,
`astropy.wcs.WCS`, `gwcs.wcs.WCS`).
offset : `~astropy.units.Quantity`
A small angular offset to use to compute the pixel scale and
position angle.
Returns
-------
scale : `~astropy.units.Quantity`
The pixel scale in arcsec/pixel.
angle : `~astropy.units.Quantity`
The angle (in degrees) measured counterclockwise from the
positive x axis to the "North" axis of the celestial coordinate
system.
Notes
-----
If distortions are present in the image, the x and y pixel scales
likely differ. This function computes a single pixel scale along
the North/South axis.
"""
try:
x, y = wcs.world_to_pixel(skycoord)
# We take a point directly North (i.e., latitude offset) the
# input sky coordinate and convert it to pixel coordinates,
# then we use the pixel deltas between the input and offset sky
# coordinate to calculate the pixel scale and angle.
skycoord_offset = skycoord.directional_offset_by(0.0, offset)
x_offset, y_offset = wcs.world_to_pixel(skycoord_offset)
except AttributeError:
# for Astropy < 3.1 WCS support
x, y = skycoord_to_pixel(skycoord, wcs)
coord = skycoord.represent_as('unitspherical')
coord_new = UnitSphericalRepresentation(coord.lon, coord.lat + offset)
coord_offset = skycoord.realize_frame(coord_new)
x_offset, y_offset = skycoord_to_pixel(coord_offset, wcs)
dx = x_offset - x
dy = y_offset - y
scale = offset.to(u.arcsec) / (np.hypot(dx, dy) * u.pixel)
angle = (np.arctan2(dy, dx) * u.radian).to(u.deg)
return scale, angle
|
[
"numpy.arctan2",
"astropy.wcs.utils.skycoord_to_pixel",
"numpy.hypot",
"astropy.coordinates.UnitSphericalRepresentation",
"astropy.wcs.utils.pixel_to_skycoord"
] |
[((4251, 4283), 'astropy.wcs.utils.skycoord_to_pixel', 'skycoord_to_pixel', (['skycoord', 'wcs'], {}), '(skycoord, wcs)\n', (4268, 4283), False, 'from astropy.wcs.utils import pixel_to_skycoord, skycoord_to_pixel\n'), ((4359, 4417), 'astropy.coordinates.UnitSphericalRepresentation', 'UnitSphericalRepresentation', (['coord.lon', '(coord.lat + offset)'], {}), '(coord.lon, coord.lat + offset)\n', (4386, 4417), False, 'from astropy.coordinates import UnitSphericalRepresentation\n'), ((4504, 4540), 'astropy.wcs.utils.skycoord_to_pixel', 'skycoord_to_pixel', (['coord_offset', 'wcs'], {}), '(coord_offset, wcs)\n', (4521, 4540), False, 'from astropy.wcs.utils import pixel_to_skycoord, skycoord_to_pixel\n'), ((4621, 4637), 'numpy.hypot', 'np.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (4629, 4637), True, 'import numpy as np\n'), ((1353, 1397), 'astropy.wcs.utils.pixel_to_skycoord', 'pixel_to_skycoord', (['xpos', 'ypos', 'wcs'], {'origin': '(0)'}), '(xpos, ypos, wcs, origin=0)\n', (1370, 1397), False, 'from astropy.wcs.utils import pixel_to_skycoord, skycoord_to_pixel\n'), ((2367, 2409), 'astropy.wcs.utils.skycoord_to_pixel', 'skycoord_to_pixel', (['skycoord', 'wcs'], {'origin': '(0)'}), '(skycoord, wcs, origin=0)\n', (2384, 2409), False, 'from astropy.wcs.utils import pixel_to_skycoord, skycoord_to_pixel\n'), ((4662, 4680), 'numpy.arctan2', 'np.arctan2', (['dy', 'dx'], {}), '(dy, dx)\n', (4672, 4680), True, 'import numpy as np\n')]
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import contextlib
import copy
import io
import itertools
import json
import logging
import numpy as np
import os
import pickle
from collections import OrderedDict
import pynlostools.mask as mask_util
import torch
from fvcore.common.file_io import PathManager
from pynlostools.nlos import NLOS
from pynlostools.nloseval import NLOSeval
from tabulate import tabulate
import detectron2.utils.comm as comm
from detectron2.data import MetadataCatalog
from adet.data.datasets.nlos import convert_to_nlos_json
#from detectron2.evaluation.fast_eval_api import NLOSeval_opt
from detectron2.structures import Boxes, BoxMode, pairwise_iou
from detectron2.utils.logger import create_small_table
from detectron2.evaluation.evaluator import DatasetEvaluator
class NLOSEvaluator(DatasetEvaluator):
"""
Evaluate AR for object proposals, AP for instance detection/segmentation, AP
for keypoint detection outputs using NLOS's metrics.
See http://nlosdataset.org/#detection-eval and
http://nlosdataset.org/#keypoints-eval to understand its metrics.
In addition to NLOS, this evaluator is able to support any bounding box detection,
instance segmentation, or keypoint detection dataset.
"""
def __init__(self, dataset_name, cfg, distributed, output_dir=None, *, use_fast_impl=True):
"""
Args:
dataset_name (str): name of the dataset to be evaluated.
It must have either the following corresponding metadata:
"json_file": the path to the NLOS format annotation
Or it must be in detectron2's standard dataset format
so it can be converted to NLOS format automatically.
cfg (CfgNode): config instance
distributed (True): if True, will collect results from all ranks and run evaluation
in the main process.
Otherwise, will evaluate the results in the current process.
output_dir (str): optional, an output directory to dump all
results predicted on the dataset. The dump contains two files:
1. "instance_predictions.pth" a file in torch serialization
format that contains all the raw original predictions.
2. "nlos_instances_results.json" a json file in NLOS's result
format.
use_fast_impl (bool): use a fast but **unofficial** implementation to compute AP.
Although the results should be very close to the official implementation in NLOS
API, it is still recommended to compute results with the official API for use in
papers.
"""
self._tasks = self._tasks_from_config(cfg)
self._distributed = distributed
self._output_dir = output_dir
self._use_fast_impl = use_fast_impl
self._cpu_device = torch.device("cpu")
self._logger = logging.getLogger(__name__)
self._metadata = MetadataCatalog.get(dataset_name)
if not hasattr(self._metadata, "json_file"):
self._logger.info(
f"'{dataset_name}' is not registered by `register_nlos_instances`."
" Therefore trying to convert it to NLOS format ..."
)
cache_path = os.path.join(output_dir, f"{dataset_name}_nlos_format.json")
self._metadata.json_file = cache_path
convert_to_nlos_json(dataset_name, cache_path)
json_file = PathManager.get_local_path(self._metadata.json_file)
with contextlib.redirect_stdout(io.StringIO()):
self._nlos_api = NLOS(json_file)
self._kpt_oks_sigmas = cfg.TEST.KEYPOINT_OKS_SIGMAS
# Test set json files do not contain annotations (evaluation must be
# performed using the NLOS evaluation server).
self._do_evaluation = "annotations" in self._nlos_api.dataset
def reset(self):
self._predictions = []
def _tasks_from_config(self, cfg):
"""
Returns:
tuple[str]: tasks that can be evaluated under the given configuration.
"""
tasks = ("bbox",)
if cfg.MODEL.MASK_ON:
tasks = tasks + ("segm",)
if cfg.MODEL.KEYPOINT_ON:
tasks = tasks + ("keypoints",)
return tasks
def process(self, inputs, outputs):
"""
Args:
inputs: the inputs to a NLOS model (e.g., GeneralizedRCNN).
It is a list of dict. Each dict corresponds to an image and
contains keys like "height", "width", "file_name", "image_id".
outputs: the outputs of a NLOS model. It is a list of dicts with key
"instances" that contains :class:`Instances`.
"""
for input, output in zip(inputs, outputs):
prediction = {"image_id": input["image_id"]}
# TODO this is ugly
if "instances" in output:
instances = output["instances"].to(self._cpu_device)
prediction["instances"] = instances_to_nlos_json(instances, input["image_id"])
if "proposals" in output:
prediction["proposals"] = output["proposals"].to(self._cpu_device)
if "classification" in output:
prediction['classification'] = [{ok : ov.to(self._cpu_device) for ok , ov in out.items()} for out in output['classification']]
self._predictions.append(prediction)
def evaluate(self):
if self._distributed:
comm.synchronize()
predictions = comm.gather(self._predictions, dst=0)
predictions = list(itertools.chain(*predictions))
if not comm.is_main_process():
return {}
else:
predictions = self._predictions
if len(predictions) == 0:
self._logger.warning("[NLOSEvaluator] Did not receive valid predictions.")
return {}
if self._output_dir:
PathManager.mkdirs(self._output_dir)
file_path = os.path.join(self._output_dir, "instances_predictions.pth")
with PathManager.open(file_path, "wb") as f:
torch.save(predictions, f)
self._results = OrderedDict()
if "proposals" in predictions[0]:
self._eval_box_proposals(predictions)
if "instances" in predictions[0]:
self._eval_predictions(set(self._tasks), predictions)
if "classification" in predictions[0]:
self._eval_classification(predictions)
# Copy so the caller can do whatever with results
return copy.deepcopy(self._results)
def _eval_classification(self, predictions):
self._logger.info("Preparing results for NLOS format ...")
#nlos_results = list(itertools.chain(*[x["classification"] for x in predictions]))
nlos_results = [x["classification"] for x in predictions]
# unmap the category ids for NLOS
if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"):
reverse_id_mapping = {
v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items()
}
for result in nlos_results:
for inst in result:
category_id = inst["category_id"].item()
assert (
category_id in reverse_id_mapping
), "A prediction has category_id={}, which is not available in the dataset.".format(
category_id
)
inst["category_id"] = reverse_id_mapping[category_id]
if self._output_dir:
file_path = os.path.join(self._output_dir, "nlos_instances_results.json")
self._logger.info("Saving results to {}".format(file_path))
with PathManager.open(file_path, "w") as f:
f.write(json.dumps(nlos_results))
f.flush()
if not self._do_evaluation:
self._logger.info("Annotations are not available for evaluation.")
return
self._logger.info(
"Evaluating predictions with {} NLOS API...".format(
"unofficial" if self._use_fast_impl else "official"
)
)
"""
nlos_eval = (
_evaluate_predictions_on_nlos(
self._nlos_api,
nlos_results,
task,
kpt_oks_sigmas=self._kpt_oks_sigmas,
use_fast_impl=self._use_fast_impl,
)
if len(nlos_results) > 0
else None # nlosapi does not handle empty results very well
)
res = self._derive_nlos_results(
nlos_eval, task, class_names=self._metadata.get("thing_classes")
)
self._results[task] = res
"""
def _eval_predictions(self, tasks, predictions):
"""
Evaluate predictions on the given tasks.
Fill self._results with the metrics of the tasks.
"""
self._logger.info("Preparing results for NLOS format ...")
nlos_results = list(itertools.chain(*[x["instances"] for x in predictions]))
# unmap the category ids for NLOS
if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"):
reverse_id_mapping = {
v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items()
}
for result in nlos_results:
category_id = result["category_id"]
assert (
category_id in reverse_id_mapping
), "A prediction has category_id={}, which is not available in the dataset.".format(
category_id
)
result["category_id"] = reverse_id_mapping[category_id]
if self._output_dir:
file_path = os.path.join(self._output_dir, "nlos_instances_results.json")
self._logger.info("Saving results to {}".format(file_path))
with PathManager.open(file_path, "w") as f:
f.write(json.dumps(nlos_results))
f.flush()
if not self._do_evaluation:
self._logger.info("Annotations are not available for evaluation.")
return
self._logger.info(
"Evaluating predictions with {} NLOS API...".format(
"unofficial" if self._use_fast_impl else "official"
)
)
for task in sorted(tasks):
nlos_eval = (
_evaluate_predictions_on_nlos(
self._nlos_api,
nlos_results,
task,
kpt_oks_sigmas=self._kpt_oks_sigmas,
use_fast_impl=self._use_fast_impl,
)
if len(nlos_results) > 0
else None # nlosapi does not handle empty results very well
)
res = self._derive_nlos_results(
nlos_eval, task, class_names=self._metadata.get("thing_classes")
)
self._results[task] = res
def _eval_box_proposals(self, predictions):
"""
Evaluate the box proposals in predictions.
Fill self._results with the metrics for "box_proposals" task.
"""
if self._output_dir:
# Saving generated box proposals to file.
# Predicted box_proposals are in XYXY_ABS mode.
bbox_mode = BoxMode.XYXY_ABS.value
ids, boxes, objectness_logits = [], [], []
for prediction in predictions:
ids.append(prediction["image_id"])
boxes.append(prediction["proposals"].proposal_boxes.tensor.numpy())
objectness_logits.append(prediction["proposals"].objectness_logits.numpy())
proposal_data = {
"boxes": boxes,
"objectness_logits": objectness_logits,
"ids": ids,
"bbox_mode": bbox_mode,
}
with PathManager.open(os.path.join(self._output_dir, "box_proposals.pkl"), "wb") as f:
pickle.dump(proposal_data, f)
if not self._do_evaluation:
self._logger.info("Annotations are not available for evaluation.")
return
self._logger.info("Evaluating bbox proposals ...")
res = {}
areas = {"all": "", "small": "s", "medium": "m", "large": "l"}
for limit in [100, 1000]:
for area, suffix in areas.items():
stats = _evaluate_box_proposals(predictions, self._nlos_api, area=area, limit=limit)
key = "AR{}@{:d}".format(suffix, limit)
res[key] = float(stats["ar"].item() * 100)
self._logger.info("Proposal metrics: \n" + create_small_table(res))
self._results["box_proposals"] = res
def _derive_nlos_results(self, nlos_eval, iou_type, class_names=None):
"""
Derive the desired score numbers from summarized NLOSeval.
Args:
nlos_eval (None or NLOSEval): None represents no predictions from model.
iou_type (str):
class_names (None or list[str]): if provided, will use it to predict
per-category AP.
Returns:
a dict of {metric name: score}
"""
metrics = {
"bbox": ["AP", "AP50", "AP75", "APs", "APm", "APl"],
"segm": ["AP", "AP50", "AP75", "APs", "APm", "APl"],
"keypoints": ["AP", "AP50", "AP75", "APm", "APl"],
}[iou_type]
#arng_names = ["all","small","medium","large"]
ithr_names = ["50:95", "50", "75"]
if nlos_eval is None:
self._logger.warn("No predictions from the model!")
return {metric: float("nan") for metric in metrics}
# the standard metrics
results = {
metric: float(nlos_eval.stats[idx] * 100 if nlos_eval.stats[idx] >= 0 else "nan")
for idx, metric in enumerate(metrics)
}
self._logger.info(
"Evaluation results for {}: \n".format(iou_type) + create_small_table(results)
)
if not np.isfinite(sum(results.values())):
self._logger.info("Some metrics cannot be computed and is shown as NaN.")
if class_names is None or len(class_names) <= 1:
return results
# Compute per-category AP
# from https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L222-L252 # noqa
precisions = nlos_eval.eval["precision"]
# precision has dims (iou, recall, cls, area range, max dets)
assert len(class_names) == precisions.shape[2]
results_per_category = []
for idx, name in enumerate(class_names):
# area range index 0: all area ranges
# max dets index -1: typically 100 per image
"""
for arng_idx, rng_name in enumerate(arng_names):
precision = precisions[:, :, idx, arng_idx, -1]
precision = precision[precision > -1]
ap = np.mean(precision) if precision.size else float("nan")
results_per_category.append(("{}, {}".format(name,rng_name), float(ap * 100)))
"""
for ithr_idx, ithr_name in enumerate(ithr_names):
if ithr_idx == 0:
precision = precisions[:, :, idx, :, -1]
else:
precision = precisions[(int(ithr_name) - 50) // 5, :, idx, :, -1]
precision = precision[precision > -1]
ap = np.mean(precision) if precision.size else float("nan")
results_per_category.append(("{}, {}".format(name,ithr_name), float(ap * 100)))
# tabulate it
N_COLS = min(6, len(results_per_category) * 2)
results_flatten = list(itertools.chain(*results_per_category))
result_dict = {}
for i in range(len(results_flatten)//2):
result_dict[results_flatten[2*i]] = results_flatten[2*i+1]
with open('result_dict.json','w') as fp:
json.dump(result_dict, fp)
results_2d = itertools.zip_longest(*[results_flatten[i::N_COLS] for i in range(N_COLS)])
table = tabulate(
results_2d,
tablefmt="pipe",
floatfmt=".3f",
headers=["category", "AP"] * (N_COLS // 2),
numalign="left",
)
self._logger.info("Per-category {} AP: \n".format(iou_type) + table)
results.update({"AP-" + name: ap for name, ap in results_per_category})
return results
def instances_to_nlos_json(instances, img_id):
"""
Dump an "Instances" object to a NLOS-format json that's used for evaluation.
Args:
instances (Instances):
img_id (int): the image id
Returns:
list[dict]: list of json annotations in NLOS format.
"""
num_instance = len(instances)
if num_instance == 0:
return []
boxes = instances.pred_boxes.tensor.numpy()
boxes = BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
boxes = boxes.tolist()
scores = instances.scores.tolist()
classes = instances.pred_classes.tolist()
#level = instances.level.tolist()
has_mask = instances.has("pred_masks")
if has_mask:
# use RLE to encode the masks, because they are too large and takes memory
# since this evaluator stores outputs of the entire dataset
rles = [
mask_util.encode(np.array(mask[:, :, None], order="F", dtype="uint8"))[0]
for mask in instances.pred_masks
]
for rle in rles:
# "counts" is an array encoded by mask_util as a byte-stream. Python3's
# json writer which always produces strings cannot serialize a bytestream
# unless you decode it. Thankfully, utf-8 works out (which is also what
# the pynlostools/_mask.pyx does).
rle["counts"] = rle["counts"].decode("utf-8")
has_keypoints = instances.has("pred_keypoints")
if has_keypoints:
keypoints = instances.pred_keypoints
results = []
for k in range(num_instance):
result = {
"image_group_id": img_id,
"category_id": classes[k],
"bbox": boxes[k],
"score": scores[k],
#"level": level[k]
}
if has_mask:
result["segmentation"] = rles[k]
if has_keypoints:
# In NLOS annotations,
# keypoints coordinates are pixel indices.
# However our predictions are floating point coordinates.
# Therefore we subtract 0.5 to be consistent with the annotation format.
# This is the inverse of data loading logic in `datasets/nlos.py`.
keypoints[k][:, :2] -= 0.5
result["keypoints"] = keypoints[k].flatten().tolist()
results.append(result)
return results
# inspired from Detectron:
# https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L255 # noqa
def _evaluate_box_proposals(dataset_predictions, nlos_api, thresholds=None, area="all", limit=None):
"""
Evaluate detection proposal recall metrics. This function is a much
faster alternative to the official NLOS API recall evaluation code. However,
it produces slightly different results.
"""
# Record max overlap value for each gt box
# Return vector of overlap values
areas = {
"all": 0,
"small": 1,
"medium": 2,
"large": 3,
"96-128": 4,
"128-256": 5,
"256-512": 6,
"512-inf": 7,
}
area_ranges = [
[0 ** 2, 1e5 ** 2], # all
[0 ** 2, 32 ** 2], # small
[32 ** 2, 96 ** 2], # medium
[96 ** 2, 1e5 ** 2], # large
[96 ** 2, 128 ** 2], # 96-128
[128 ** 2, 256 ** 2], # 128-256
[256 ** 2, 512 ** 2], # 256-512
[512 ** 2, 1e5 ** 2],
] # 512-inf
assert area in areas, "Unknown area range: {}".format(area)
area_range = area_ranges[areas[area]]
gt_overlaps = []
num_pos = 0
for prediction_dict in dataset_predictions:
predictions = prediction_dict["proposals"]
# sort predictions in descending order
# TODO maybe remove this and make it explicit in the documentation
inds = predictions.objectness_logits.sort(descending=True)[1]
predictions = predictions[inds]
ann_ids = nlos_api.getAnnIds(imgIds=prediction_dict["image_id"])
anno = nlos_api.loadAnns(ann_ids)
gt_boxes = [
BoxMode.convert(obj["bbox"], BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)
for obj in anno
if obj["iscrowd"] == 0
]
gt_boxes = torch.as_tensor(gt_boxes).reshape(-1, 4) # guard against no boxes
gt_boxes = Boxes(gt_boxes)
gt_areas = torch.as_tensor([obj["area"] for obj in anno if obj["iscrowd"] == 0])
if len(gt_boxes) == 0 or len(predictions) == 0:
continue
valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1])
gt_boxes = gt_boxes[valid_gt_inds]
num_pos += len(gt_boxes)
if len(gt_boxes) == 0:
continue
if limit is not None and len(predictions) > limit:
predictions = predictions[:limit]
overlaps = pairwise_iou(predictions.proposal_boxes, gt_boxes)
_gt_overlaps = torch.zeros(len(gt_boxes))
for j in range(min(len(predictions), len(gt_boxes))):
# find which proposal box maximally covers each gt box
# and get the iou amount of coverage for each gt box
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
# find which gt box is 'best' covered (i.e. 'best' = most iou)
gt_ovr, gt_ind = max_overlaps.max(dim=0)
assert gt_ovr >= 0
# find the proposal box that covers the best covered gt box
box_ind = argmax_overlaps[gt_ind]
# record the iou coverage of this gt box
_gt_overlaps[j] = overlaps[box_ind, gt_ind]
assert _gt_overlaps[j] == gt_ovr
# mark the proposal box and the gt box as used
overlaps[box_ind, :] = -1
overlaps[:, gt_ind] = -1
# append recorded iou coverage level
gt_overlaps.append(_gt_overlaps)
gt_overlaps = (
torch.cat(gt_overlaps, dim=0) if len(gt_overlaps) else torch.zeros(0, dtype=torch.float32)
)
gt_overlaps, _ = torch.sort(gt_overlaps)
if thresholds is None:
step = 0.05
thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32)
recalls = torch.zeros_like(thresholds)
# compute recall for each iou threshold
for i, t in enumerate(thresholds):
recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos)
# ar = 2 * np.trapz(recalls, thresholds)
ar = recalls.mean()
return {
"ar": ar,
"recalls": recalls,
"thresholds": thresholds,
"gt_overlaps": gt_overlaps,
"num_pos": num_pos,
}
def _evaluate_predictions_on_nlos(
nlos_gt, nlos_results, iou_type, kpt_oks_sigmas=None, use_fast_impl=True
):
"""
Evaluate the nlos results using NLOSEval API.
"""
assert len(nlos_results) > 0
if iou_type == "segm":
nlos_results = copy.deepcopy(nlos_results)
# When evaluating mask AP, if the results contain bbox, nlosapi will
# use the box area as the area of the instance, instead of the mask area.
# This leads to a different definition of small/medium/large.
# We remove the bbox field to let mask AP use mask area.
for c in nlos_results:
c.pop("bbox", None)
if iou_type == "classification":
pass
nlos_dt = nlos_gt.loadRes(nlos_results)
use_fast_impl = False
#nlos_eval = (NLOSeval_opt if use_fast_impl else NLOSeval)(nlos_gt, nlos_dt, iou_type)
nlos_eval = NLOSeval(nlos_gt, nlos_dt, iou_type)
if iou_type == "keypoints":
# Use the NLOS default keypoint OKS sigmas unless overrides are specified
if kpt_oks_sigmas:
assert hasattr(nlos_eval.params, "kpt_oks_sigmas"), "pynlostools is too old!"
nlos_eval.params.kpt_oks_sigmas = np.array(kpt_oks_sigmas)
# NLOSAPI requires every detection and every gt to have keypoints, so
# we just take the first entry from both
num_keypoints_dt = len(nlos_results[0]["keypoints"]) // 3
num_keypoints_gt = len(next(iter(nlos_gt.anns.values()))["keypoints"]) // 3
num_keypoints_oks = len(nlos_eval.params.kpt_oks_sigmas)
assert num_keypoints_oks == num_keypoints_dt == num_keypoints_gt, (
f"[NLOSEvaluator] Prediction contain {num_keypoints_dt} keypoints. "
f"Ground truth contains {num_keypoints_gt} keypoints. "
f"The length of cfg.TEST.KEYPOINT_OKS_SIGMAS is {num_keypoints_oks}. "
"They have to agree with each other. For meaning of OKS, please refer to "
"http://nlosdataset.org/#keypoints-eval."
)
nlos_eval.evaluate()
nlos_eval.accumulate()
nlos_eval.summarize()
return nlos_eval
|
[
"pickle.dump",
"torch.cat",
"pynlostools.nlos.NLOS",
"json.dumps",
"numpy.mean",
"detectron2.utils.logger.create_small_table",
"torch.arange",
"torch.device",
"pynlostools.nloseval.NLOSeval",
"detectron2.data.MetadataCatalog.get",
"os.path.join",
"detectron2.structures.pairwise_iou",
"fvcore.common.file_io.PathManager.open",
"fvcore.common.file_io.PathManager.get_local_path",
"adet.data.datasets.nlos.convert_to_nlos_json",
"torch.zeros",
"detectron2.utils.comm.synchronize",
"detectron2.utils.comm.is_main_process",
"itertools.chain",
"json.dump",
"copy.deepcopy",
"io.StringIO",
"torch.zeros_like",
"detectron2.utils.comm.gather",
"detectron2.structures.Boxes",
"fvcore.common.file_io.PathManager.mkdirs",
"torch.sort",
"torch.save",
"tabulate.tabulate",
"numpy.array",
"collections.OrderedDict",
"torch.as_tensor",
"detectron2.structures.BoxMode.convert",
"logging.getLogger"
] |
[((17202, 17260), 'detectron2.structures.BoxMode.convert', 'BoxMode.convert', (['boxes', 'BoxMode.XYXY_ABS', 'BoxMode.XYWH_ABS'], {}), '(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)\n', (17217, 17260), False, 'from detectron2.structures import Boxes, BoxMode, pairwise_iou\n'), ((22757, 22780), 'torch.sort', 'torch.sort', (['gt_overlaps'], {}), '(gt_overlaps)\n', (22767, 22780), False, 'import torch\n'), ((22922, 22950), 'torch.zeros_like', 'torch.zeros_like', (['thresholds'], {}), '(thresholds)\n', (22938, 22950), False, 'import torch\n'), ((24218, 24254), 'pynlostools.nloseval.NLOSeval', 'NLOSeval', (['nlos_gt', 'nlos_dt', 'iou_type'], {}), '(nlos_gt, nlos_dt, iou_type)\n', (24226, 24254), False, 'from pynlostools.nloseval import NLOSeval\n'), ((2942, 2961), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2954, 2961), False, 'import torch\n'), ((2985, 3012), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (3002, 3012), False, 'import logging\n'), ((3039, 3072), 'detectron2.data.MetadataCatalog.get', 'MetadataCatalog.get', (['dataset_name'], {}), '(dataset_name)\n', (3058, 3072), False, 'from detectron2.data import MetadataCatalog\n'), ((3541, 3593), 'fvcore.common.file_io.PathManager.get_local_path', 'PathManager.get_local_path', (['self._metadata.json_file'], {}), '(self._metadata.json_file)\n', (3567, 3593), False, 'from fvcore.common.file_io import PathManager\n'), ((6287, 6300), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (6298, 6300), False, 'from collections import OrderedDict\n'), ((6672, 6700), 'copy.deepcopy', 'copy.deepcopy', (['self._results'], {}), '(self._results)\n', (6685, 6700), False, 'import copy\n'), ((16398, 16516), 'tabulate.tabulate', 'tabulate', (['results_2d'], {'tablefmt': '"""pipe"""', 'floatfmt': '""".3f"""', 'headers': "(['category', 'AP'] * (N_COLS // 2))", 'numalign': '"""left"""'}), "(results_2d, tablefmt='pipe', floatfmt='.3f', headers=['category',\n 'AP'] * (N_COLS // 2), numalign='left')\n", (16406, 16516), False, 'from tabulate import tabulate\n'), ((21076, 21091), 'detectron2.structures.Boxes', 'Boxes', (['gt_boxes'], {}), '(gt_boxes)\n', (21081, 21091), False, 'from detectron2.structures import Boxes, BoxMode, pairwise_iou\n'), ((21111, 21180), 'torch.as_tensor', 'torch.as_tensor', (["[obj['area'] for obj in anno if obj['iscrowd'] == 0]"], {}), "([obj['area'] for obj in anno if obj['iscrowd'] == 0])\n", (21126, 21180), False, 'import torch\n'), ((21598, 21648), 'detectron2.structures.pairwise_iou', 'pairwise_iou', (['predictions.proposal_boxes', 'gt_boxes'], {}), '(predictions.proposal_boxes, gt_boxes)\n', (21610, 21648), False, 'from detectron2.structures import Boxes, BoxMode, pairwise_iou\n'), ((22639, 22668), 'torch.cat', 'torch.cat', (['gt_overlaps'], {'dim': '(0)'}), '(gt_overlaps, dim=0)\n', (22648, 22668), False, 'import torch\n'), ((22694, 22729), 'torch.zeros', 'torch.zeros', (['(0)'], {'dtype': 'torch.float32'}), '(0, dtype=torch.float32)\n', (22705, 22729), False, 'import torch\n'), ((22850, 22908), 'torch.arange', 'torch.arange', (['(0.5)', '(0.95 + 1e-05)', 'step'], {'dtype': 'torch.float32'}), '(0.5, 0.95 + 1e-05, step, dtype=torch.float32)\n', (22862, 22908), False, 'import torch\n'), ((23604, 23631), 'copy.deepcopy', 'copy.deepcopy', (['nlos_results'], {}), '(nlos_results)\n', (23617, 23631), False, 'import copy\n'), ((3350, 3410), 'os.path.join', 'os.path.join', (['output_dir', 'f"""{dataset_name}_nlos_format.json"""'], {}), "(output_dir, f'{dataset_name}_nlos_format.json')\n", (3362, 3410), False, 'import os\n'), ((3473, 3519), 'adet.data.datasets.nlos.convert_to_nlos_json', 'convert_to_nlos_json', (['dataset_name', 'cache_path'], {}), '(dataset_name, cache_path)\n', (3493, 3519), False, 'from adet.data.datasets.nlos import convert_to_nlos_json\n'), ((3679, 3694), 'pynlostools.nlos.NLOS', 'NLOS', (['json_file'], {}), '(json_file)\n', (3683, 3694), False, 'from pynlostools.nlos import NLOS\n'), ((5582, 5600), 'detectron2.utils.comm.synchronize', 'comm.synchronize', ([], {}), '()\n', (5598, 5600), True, 'import detectron2.utils.comm as comm\n'), ((5627, 5664), 'detectron2.utils.comm.gather', 'comm.gather', (['self._predictions'], {'dst': '(0)'}), '(self._predictions, dst=0)\n', (5638, 5664), True, 'import detectron2.utils.comm as comm\n'), ((6041, 6077), 'fvcore.common.file_io.PathManager.mkdirs', 'PathManager.mkdirs', (['self._output_dir'], {}), '(self._output_dir)\n', (6059, 6077), False, 'from fvcore.common.file_io import PathManager\n'), ((6102, 6161), 'os.path.join', 'os.path.join', (['self._output_dir', '"""instances_predictions.pth"""'], {}), "(self._output_dir, 'instances_predictions.pth')\n", (6114, 6161), False, 'import os\n'), ((7749, 7810), 'os.path.join', 'os.path.join', (['self._output_dir', '"""nlos_instances_results.json"""'], {}), "(self._output_dir, 'nlos_instances_results.json')\n", (7761, 7810), False, 'import os\n'), ((9191, 9246), 'itertools.chain', 'itertools.chain', (["*[x['instances'] for x in predictions]"], {}), "(*[x['instances'] for x in predictions])\n", (9206, 9246), False, 'import itertools\n'), ((9951, 10012), 'os.path.join', 'os.path.join', (['self._output_dir', '"""nlos_instances_results.json"""'], {}), "(self._output_dir, 'nlos_instances_results.json')\n", (9963, 10012), False, 'import os\n'), ((16008, 16046), 'itertools.chain', 'itertools.chain', (['*results_per_category'], {}), '(*results_per_category)\n', (16023, 16046), False, 'import itertools\n'), ((16257, 16283), 'json.dump', 'json.dump', (['result_dict', 'fp'], {}), '(result_dict, fp)\n', (16266, 16283), False, 'import json\n'), ((20833, 20897), 'detectron2.structures.BoxMode.convert', 'BoxMode.convert', (["obj['bbox']", 'BoxMode.XYWH_ABS', 'BoxMode.XYXY_ABS'], {}), "(obj['bbox'], BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)\n", (20848, 20897), False, 'from detectron2.structures import Boxes, BoxMode, pairwise_iou\n'), ((24533, 24557), 'numpy.array', 'np.array', (['kpt_oks_sigmas'], {}), '(kpt_oks_sigmas)\n', (24541, 24557), True, 'import numpy as np\n'), ((3634, 3647), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (3645, 3647), False, 'import io\n'), ((5696, 5725), 'itertools.chain', 'itertools.chain', (['*predictions'], {}), '(*predictions)\n', (5711, 5725), False, 'import itertools\n'), ((5747, 5769), 'detectron2.utils.comm.is_main_process', 'comm.is_main_process', ([], {}), '()\n', (5767, 5769), True, 'import detectron2.utils.comm as comm\n'), ((6179, 6212), 'fvcore.common.file_io.PathManager.open', 'PathManager.open', (['file_path', '"""wb"""'], {}), "(file_path, 'wb')\n", (6195, 6212), False, 'from fvcore.common.file_io import PathManager\n'), ((6235, 6261), 'torch.save', 'torch.save', (['predictions', 'f'], {}), '(predictions, f)\n', (6245, 6261), False, 'import torch\n'), ((7900, 7932), 'fvcore.common.file_io.PathManager.open', 'PathManager.open', (['file_path', '"""w"""'], {}), "(file_path, 'w')\n", (7916, 7932), False, 'from fvcore.common.file_io import PathManager\n'), ((10102, 10134), 'fvcore.common.file_io.PathManager.open', 'PathManager.open', (['file_path', '"""w"""'], {}), "(file_path, 'w')\n", (10118, 10134), False, 'from fvcore.common.file_io import PathManager\n'), ((12207, 12236), 'pickle.dump', 'pickle.dump', (['proposal_data', 'f'], {}), '(proposal_data, f)\n', (12218, 12236), False, 'import pickle\n'), ((12868, 12891), 'detectron2.utils.logger.create_small_table', 'create_small_table', (['res'], {}), '(res)\n', (12886, 12891), False, 'from detectron2.utils.logger import create_small_table\n'), ((14196, 14223), 'detectron2.utils.logger.create_small_table', 'create_small_table', (['results'], {}), '(results)\n', (14214, 14223), False, 'from detectron2.utils.logger import create_small_table\n'), ((20990, 21015), 'torch.as_tensor', 'torch.as_tensor', (['gt_boxes'], {}), '(gt_boxes)\n', (21005, 21015), False, 'import torch\n'), ((7963, 7987), 'json.dumps', 'json.dumps', (['nlos_results'], {}), '(nlos_results)\n', (7973, 7987), False, 'import json\n'), ((10165, 10189), 'json.dumps', 'json.dumps', (['nlos_results'], {}), '(nlos_results)\n', (10175, 10189), False, 'import json\n'), ((12126, 12177), 'os.path.join', 'os.path.join', (['self._output_dir', '"""box_proposals.pkl"""'], {}), "(self._output_dir, 'box_proposals.pkl')\n", (12138, 12177), False, 'import os\n'), ((15746, 15764), 'numpy.mean', 'np.mean', (['precision'], {}), '(precision)\n', (15753, 15764), True, 'import numpy as np\n'), ((17669, 17721), 'numpy.array', 'np.array', (['mask[:, :, None]'], {'order': '"""F"""', 'dtype': '"""uint8"""'}), "(mask[:, :, None], order='F', dtype='uint8')\n", (17677, 17721), True, 'import numpy as np\n')]
|
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
import unittest
from scipy.constants import mu_0
from SimPEG.electromagnetics import natural_source as nsem
from SimPEG import maps
TOL = 1e-4
FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order
CONDUCTIVITY = 1e1
MU = mu_0
def JvecAdjointTest(sigmaHalf, formulation="PrimSec"):
forType = "PrimSec" not in formulation
survey, sigma, sigBG, m1d = nsem.utils.test_utils.setup1DSurvey(
sigmaHalf, tD=forType, structure=False
)
print("Adjoint test of e formulation for {:s} comp \n".format(formulation))
if "PrimSec" in formulation:
problem = nsem.Simulation1DPrimarySecondary(
m1d, survey=survey, sigmaPrimary=sigBG, sigmaMap=maps.IdentityMap(m1d)
)
else:
raise NotImplementedError(
"Only {} formulations are implemented.".format(formulation)
)
m = sigma
u = problem.fields(m)
np.random.seed(1983)
v = np.random.rand(survey.nD,)
# print problem.PropMap.PropModel.nP
w = np.random.rand(problem.mesh.nC,)
vJw = v.ravel().dot(problem.Jvec(m, w, u))
wJtv = w.ravel().dot(problem.Jtvec(m, v, u))
tol = np.max([TOL * (10 ** int(np.log10(np.abs(vJw)))), FLR])
print(" vJw wJtv vJw - wJtv tol abs(vJw - wJtv) < tol")
print(vJw, wJtv, vJw - wJtv, tol, np.abs(vJw - wJtv) < tol)
return np.abs(vJw - wJtv) < tol
class NSEM_1D_AdjointTests(unittest.TestCase):
def setUp(self):
pass
# Test the adjoint of Jvec and Jtvec
# def test_JvecAdjoint_zxxr(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zxxr',.1))
# def test_JvecAdjoint_zxxi(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zxxi',.1))
# def test_JvecAdjoint_zxyr(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zxyr',.1))
# def test_JvecAdjoint_zxyi(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zxyi',.1))
# def test_JvecAdjoint_zyxr(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zyxr',.1))
# def test_JvecAdjoint_zyxi(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zyxi',.1))
# def test_JvecAdjoint_zyyr(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zyyr',.1))
# def test_JvecAdjoint_zyyi(self):self.assertTrue(JvecAdjointTest(random(1e-2),'zyyi',.1))
def test_JvecAdjoint_All(self):
self.assertTrue(JvecAdjointTest(1e-2))
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"SimPEG.electromagnetics.natural_source.utils.test_utils.setup1DSurvey",
"numpy.random.seed",
"numpy.abs",
"SimPEG.maps.IdentityMap",
"numpy.random.rand"
] |
[((514, 589), 'SimPEG.electromagnetics.natural_source.utils.test_utils.setup1DSurvey', 'nsem.utils.test_utils.setup1DSurvey', (['sigmaHalf'], {'tD': 'forType', 'structure': '(False)'}), '(sigmaHalf, tD=forType, structure=False)\n', (549, 589), True, 'from SimPEG.electromagnetics import natural_source as nsem\n'), ((1036, 1056), 'numpy.random.seed', 'np.random.seed', (['(1983)'], {}), '(1983)\n', (1050, 1056), True, 'import numpy as np\n'), ((1065, 1090), 'numpy.random.rand', 'np.random.rand', (['survey.nD'], {}), '(survey.nD)\n', (1079, 1090), True, 'import numpy as np\n'), ((1141, 1172), 'numpy.random.rand', 'np.random.rand', (['problem.mesh.nC'], {}), '(problem.mesh.nC)\n', (1155, 1172), True, 'import numpy as np\n'), ((2508, 2523), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2521, 2523), False, 'import unittest\n'), ((1482, 1500), 'numpy.abs', 'np.abs', (['(vJw - wJtv)'], {}), '(vJw - wJtv)\n', (1488, 1500), True, 'import numpy as np\n'), ((1445, 1463), 'numpy.abs', 'np.abs', (['(vJw - wJtv)'], {}), '(vJw - wJtv)\n', (1451, 1463), True, 'import numpy as np\n'), ((832, 853), 'SimPEG.maps.IdentityMap', 'maps.IdentityMap', (['m1d'], {}), '(m1d)\n', (848, 853), False, 'from SimPEG import maps\n'), ((1315, 1326), 'numpy.abs', 'np.abs', (['vJw'], {}), '(vJw)\n', (1321, 1326), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
from __future__ import print_function
import logging
import os
import sys
import keras
import numpy as np
import pandas as pd
from tqdm import tqdm
import c_lm
import preprocess
# logging
logging.basicConfig(format='%(asctime)s %(process)s %(levelname)-8s %(message)s', stream=sys.stdout)
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def main(data_dir: str, lm_dir: str, output_file: str):
vectors = _vectorise_files(data_dir, lm_dir)
vectors.to_pickle(output_file)
def _vectorise_files(data_dir: str, lm_dir: str):
log.info("loading vocabulary...")
vocabulary = c_lm.read_vocabulary(os.path.join(lm_dir, 'vocabulary.txt'))
log.info("loading model...")
full_model = keras.models.load_model(os.path.join(lm_dir, 'model.hdf5'))
# we do not need the top, classification layer -- we will only be using the final activations of the top LSTM layer
language_model = keras.models.Sequential(full_model.layers[:-1])
content_dir = os.path.join(data_dir, 'content')
vectors = [(file_name, mean_vector, sd_vector)
for file_name in tqdm(sorted(os.listdir(content_dir)), desc="vectorising")
for mean_vector, sd_vector in [_vectorise_file(os.path.join(content_dir, file_name), vocabulary, language_model)]]
return pd.DataFrame(vectors, columns=('file', 'mean_vector', 'sd_vector'))
def _vectorise_file(c_file: str, vocabulary: dict, language_model):
with open(c_file) as f:
denoised_content = preprocess.denoise_c(f.read())
lm_input = c_lm.vectorise(denoised_content, vocabulary)
x = _make_batch(lm_input, language_model.inputs[0].shape)
activations = language_model.predict(x, batch_size=x.shape[0])
mean_vector = np.mean(activations, axis=(0, 1))
sd_vector = np.sqrt(np.mean((activations - mean_vector) ** 2, axis=(0, 1)))
return mean_vector, sd_vector
def _make_batch(token_vectors: list, input_shape):
batch_length = int(input_shape[1])
batch_size = max(int(np.ceil(len(token_vectors) / batch_length)), 1)
pad_size = batch_size * batch_length - len(token_vectors)
padded = np.zeros(batch_size * batch_length)
padded[pad_size:] = token_vectors
return padded.reshape((batch_size, batch_length))
if __name__ == '__main__':
main(*sys.argv[1:])
|
[
"pandas.DataFrame",
"logging.basicConfig",
"c_lm.vectorise",
"numpy.zeros",
"numpy.mean",
"keras.models.Sequential",
"os.path.join",
"os.listdir",
"logging.getLogger"
] |
[((215, 320), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(process)s %(levelname)-8s %(message)s"""', 'stream': 'sys.stdout'}), "(format=\n '%(asctime)s %(process)s %(levelname)-8s %(message)s', stream=sys.stdout)\n", (234, 320), False, 'import logging\n'), ((322, 349), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (339, 349), False, 'import logging\n'), ((938, 985), 'keras.models.Sequential', 'keras.models.Sequential', (['full_model.layers[:-1]'], {}), '(full_model.layers[:-1])\n', (961, 985), False, 'import keras\n'), ((1004, 1037), 'os.path.join', 'os.path.join', (['data_dir', '"""content"""'], {}), "(data_dir, 'content')\n", (1016, 1037), False, 'import os\n'), ((1320, 1387), 'pandas.DataFrame', 'pd.DataFrame', (['vectors'], {'columns': "('file', 'mean_vector', 'sd_vector')"}), "(vectors, columns=('file', 'mean_vector', 'sd_vector'))\n", (1332, 1387), True, 'import pandas as pd\n'), ((1559, 1603), 'c_lm.vectorise', 'c_lm.vectorise', (['denoised_content', 'vocabulary'], {}), '(denoised_content, vocabulary)\n', (1573, 1603), False, 'import c_lm\n'), ((1751, 1784), 'numpy.mean', 'np.mean', (['activations'], {'axis': '(0, 1)'}), '(activations, axis=(0, 1))\n', (1758, 1784), True, 'import numpy as np\n'), ((2139, 2174), 'numpy.zeros', 'np.zeros', (['(batch_size * batch_length)'], {}), '(batch_size * batch_length)\n', (2147, 2174), True, 'import numpy as np\n'), ((647, 685), 'os.path.join', 'os.path.join', (['lm_dir', '"""vocabulary.txt"""'], {}), "(lm_dir, 'vocabulary.txt')\n", (659, 685), False, 'import os\n'), ((761, 795), 'os.path.join', 'os.path.join', (['lm_dir', '"""model.hdf5"""'], {}), "(lm_dir, 'model.hdf5')\n", (773, 795), False, 'import os\n'), ((1809, 1863), 'numpy.mean', 'np.mean', (['((activations - mean_vector) ** 2)'], {'axis': '(0, 1)'}), '((activations - mean_vector) ** 2, axis=(0, 1))\n', (1816, 1863), True, 'import numpy as np\n'), ((1133, 1156), 'os.listdir', 'os.listdir', (['content_dir'], {}), '(content_dir)\n', (1143, 1156), False, 'import os\n'), ((1241, 1277), 'os.path.join', 'os.path.join', (['content_dir', 'file_name'], {}), '(content_dir, file_name)\n', (1253, 1277), False, 'import os\n')]
|
# -*- coding: utf-8 -*-
from typing import Dict, List, NamedTuple, Optional, Tuple, Union
import numpy as np
import pandas as pd
import pymatgen as pmg
import spyns
Neighbor = Tuple[pmg.PeriodicSite, float, int]
SiteNeighbors = List[Optional[Neighbor]]
AllNeighborDistances = List[SiteNeighbors]
NeighborDistances = Dict[str, Union[List[str], List[float], List[int]]]
class NeighborsDataFrames(NamedTuple):
neighbor_count: pd.DataFrame
sublattice_pairs: pd.DataFrame
def build_neighbors_data_frames(
structure: pmg.Structure, r: float
) -> NeighborsDataFrames:
"""Find neighbor and sublattice pairs in a structure within a cutoff distance.
:param structure: A pymatgen ``Structure`` object.
:param r: Cutoff radius for finding neighbors in sphere.
:return: A ``NeighborsDataFrames`` named tuple with two field names:
``neighbor_count``
A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs
and separation distances.
``sublattice_pairs``
A pandas ``DataFrame`` of neighbor distances mapped to unique bin
intervals.
"""
cell_structure = spyns.lattice.generate.add_subspecie_labels_if_missing(
cell_structure=structure
)
neighbor_distances_df: pd.DataFrame = get_neighbor_distances_data_frame(
cell_structure=cell_structure, r=r
)
distance_bins_df: pd.DataFrame = neighbor_distances_df.pipe(
define_bins_to_group_and_sort_by_distance
)
neighbor_count_df: pd.DataFrame = neighbor_distances_df.pipe(
group_site_index_pairs_by_distance, distance_bins_df=distance_bins_df
).pipe(count_neighbors_within_distance_groups).pipe(sort_neighbors_by_site_index_i)
sublattice_pairs_df: pd.DataFrame = neighbor_count_df.pipe(
sort_and_rank_unique_sublattice_pairs
)
return NeighborsDataFrames(
neighbor_count=neighbor_count_df, sublattice_pairs=sublattice_pairs_df
)
def sort_and_rank_unique_sublattice_pairs(data_frame: pd.DataFrame) -> pd.DataFrame:
"""Group, sort, and rank unique subspecies_ij and distance_bin columns.
:param neighbor_distances_df: A pandas ``DataFrame`` of pairwise neighbor
distances.
:return: A pandas ``DataFrame`` of unique sublattice pairs.
"""
subspecies_columns = ["subspecies_i", "subspecies_j"]
sublattice_columns = subspecies_columns + ["distance_bin"]
return (
data_frame.loc[:, sublattice_columns]
.drop_duplicates(subset=sublattice_columns)
.sort_values(sublattice_columns)
.assign(
subspecies_ij_distance_rank=lambda x: x.groupby(
subspecies_columns
).cumcount()
)
.reset_index(drop=True)
)
def sort_neighbors_by_site_index_i(neighbor_count_df: pd.DataFrame) -> pd.DataFrame:
"""Sort by site index i, then neighbor distances, then neighbor index j.
:param neighbor_count_df: A data frame of neighbor counts aggregated over
site-index pairs and separation distances.
:return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index
pairs and separation distances sorted by site index i, then neighbor
distances, then neighbor index j.
"""
return neighbor_count_df.sort_values(by=["i", "distance_bin", "j"]).reset_index(
drop=True
)
def count_neighbors_within_distance_groups(
grouped_distances: pd.core.groupby.DataFrameGroupBy,
) -> pd.DataFrame:
"""Count number of neighbors within each group of same-distance site-index pairs.
:param grouped_distances: A data frame grouped over site-index pairs, subspecies
pairs, and bin intervals.
:return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs
and separation distances.
"""
return (
grouped_distances.apply(
lambda x: pd.to_numeric(arg=x["distance_ij"].count(), downcast="integer")
)
.rename("n")
.reset_index()
)
def group_site_index_pairs_by_distance(
neighbor_distances_df: pd.DataFrame, distance_bins_df: pd.DataFrame
) -> pd.core.groupby.DataFrameGroupBy:
"""Iterate over all sites, grouping by site-index pairs, subspecies pairs, and
bin intervals.
:param neighbor_distances_df: A pandas ``DataFrame`` containing all pairwise
neighbor distances.
:param distance_bins_df: A pandas ``DataFrame`` of neighbor distances mapped to
unique bin intervals.
:return: A data frame grouped over site-index pairs, subspecies pairs, and
bin intervals.
"""
binned_distances: pd.Series = pd.cut(
x=neighbor_distances_df["distance_ij"], bins=distance_bins_df.index
).rename("distance_bin")
return neighbor_distances_df.groupby(
["i", "j", "subspecies_i", "subspecies_j", binned_distances]
)
def define_bins_to_group_and_sort_by_distance(
neighbor_distances_df: pd.DataFrame,
) -> pd.DataFrame:
"""Defines bin intervals to group and sort neighbor pairs by distance.
:param neighbor_distances_df: A pandas ``DataFrame`` of pairwise neighbor
distances.
:return: A pandas ``DataFrame`` of neighbor distances mapped to unique bin
intervals.
"""
unique_distances: np.ndarray = find_unique_distances(
distance_ij=neighbor_distances_df["distance_ij"]
)
bin_intervals: pd.IntervalIndex = define_bin_intervals(
unique_distances=unique_distances
)
return pd.DataFrame(
data={
"distance_bin": pd.Categorical(values=bin_intervals, ordered=True),
"distance_ij": pd.Categorical(values=unique_distances, ordered=True),
},
index=bin_intervals,
)
def find_unique_distances(distance_ij: pd.Series) -> np.ndarray:
"""Finds the unique distances that define the neighbor groups.
:param distance_ij: A pandas ``Series`` of pairwise neighbor distances.
:return: An array of unique neighbor distances.
"""
unique_floats: np.ndarray = np.sort(distance_ij.unique())
next_distance_not_close: np.ndarray = np.logical_not(
np.isclose(unique_floats[1:], unique_floats[:-1])
)
return np.concatenate(
(unique_floats[:1], unique_floats[1:][next_distance_not_close])
)
def define_bin_intervals(unique_distances: np.ndarray) -> pd.IntervalIndex:
"""Constructs bin intervals used to group over neighbor distances.
This binning procedure provides a robust method for grouping data based on a
variable with a float data type.
:param unique_distances: An array of neighbor distances returned by asking
pandas to return the unique distances.
:return: A pandas ``IntervalIndex`` defining bin intervals can be used to sort
and group neighbor distances.
"""
bin_centers: np.ndarray = np.concatenate(([0], unique_distances))
bin_edges: np.ndarray = np.concatenate(
[
bin_centers[:-1] + (bin_centers[1:] - bin_centers[:-1]) / 2,
bin_centers[-1:] + (bin_centers[-1:] - bin_centers[-2:-1]) / 2,
]
)
return pd.IntervalIndex.from_breaks(breaks=bin_edges)
def get_neighbor_distances_data_frame(
cell_structure: pmg.Structure, r: float
) -> pd.DataFrame:
"""Get data frame of pairwise neighbor distances for each atom in the unit cell,
out to a distance ``r``.
:param cell_structure: A pymatgen ``Structure`` object.
:param r: Cut-off distance to use when detecting site neighbors.
:return: A pandas ``DataFrame`` of pairwise neighbor distances.
"""
all_neighbors: AllNeighborDistances = cell_structure.get_all_neighbors(
r=r, include_index=True
)
neighbor_distances: NeighborDistances = extract_neighbor_distance_data(
cell_structure=cell_structure, all_neighbors=all_neighbors
)
return pd.DataFrame(data=neighbor_distances)
def extract_neighbor_distance_data(
cell_structure: pmg.Structure, all_neighbors: AllNeighborDistances
) -> NeighborDistances:
"""Extracts the site indices, site species, and neighbor distances for each pair
and stores it in a dictionary.
:param cell_structure: A pymatgen ``Structure`` object.
:param all_neighbors: A list of lists containing the neighbors for each site in
the structure.
:return: A dictionary of site indices, site species, and neighbor distances for
each pair.
"""
neighbor_distances: NeighborDistances = {
"i": [],
"j": [],
"subspecies_i": [],
"subspecies_j": [],
"distance_ij": [],
}
site_i_index: int
site_i_neighbors: SiteNeighbors
for site_i_index, site_i_neighbors in enumerate(all_neighbors):
append_site_i_neighbor_distance_data(
site_i_index=site_i_index,
site_i_neighbors=site_i_neighbors,
cell_structure=cell_structure,
neighbor_distances=neighbor_distances,
)
return neighbor_distances
def append_site_i_neighbor_distance_data(
site_i_index: int,
site_i_neighbors: SiteNeighbors,
cell_structure: pmg.Structure,
neighbor_distances: NeighborDistances,
) -> None:
"""Helper function to append indices, species, and distances in the
``neighbor_distances`` dictionary.
:param site_i_index: Site index of first site in neighbor pair.
:param site_i_neighbors: A list of site i's neighbors.
:param cell_structure: The pymatgen ``Structure`` object that defines the crystal
structure.
:param neighbor_distances: A dictionary of site indices, site species, and neighbor
distances for each pair.
"""
site_j: Neighbor
for site_j in site_i_neighbors:
subspecies_pair: List[str] = [
cell_structure[site_i_index].properties["subspecie"],
cell_structure[site_j[2]].properties["subspecie"],
]
index_pair: List[str] = [site_i_index, site_j[2]]
neighbor_distances["i"].append(index_pair[0])
neighbor_distances["j"].append(index_pair[1])
neighbor_distances["subspecies_i"].append(subspecies_pair[0])
neighbor_distances["subspecies_j"].append(subspecies_pair[1])
neighbor_distances["distance_ij"].append(site_j[1])
|
[
"pandas.DataFrame",
"pandas.IntervalIndex.from_breaks",
"pandas.cut",
"numpy.isclose",
"pandas.Categorical",
"spyns.lattice.generate.add_subspecie_labels_if_missing",
"numpy.concatenate"
] |
[((1167, 1252), 'spyns.lattice.generate.add_subspecie_labels_if_missing', 'spyns.lattice.generate.add_subspecie_labels_if_missing', ([], {'cell_structure': 'structure'}), '(cell_structure=structure\n )\n', (1221, 1252), False, 'import spyns\n'), ((6223, 6302), 'numpy.concatenate', 'np.concatenate', (['(unique_floats[:1], unique_floats[1:][next_distance_not_close])'], {}), '((unique_floats[:1], unique_floats[1:][next_distance_not_close]))\n', (6237, 6302), True, 'import numpy as np\n'), ((6871, 6910), 'numpy.concatenate', 'np.concatenate', (['([0], unique_distances)'], {}), '(([0], unique_distances))\n', (6885, 6910), True, 'import numpy as np\n'), ((6940, 7085), 'numpy.concatenate', 'np.concatenate', (['[bin_centers[:-1] + (bin_centers[1:] - bin_centers[:-1]) / 2, bin_centers[-\n 1:] + (bin_centers[-1:] - bin_centers[-2:-1]) / 2]'], {}), '([bin_centers[:-1] + (bin_centers[1:] - bin_centers[:-1]) / 2,\n bin_centers[-1:] + (bin_centers[-1:] - bin_centers[-2:-1]) / 2])\n', (6954, 7085), True, 'import numpy as np\n'), ((7143, 7189), 'pandas.IntervalIndex.from_breaks', 'pd.IntervalIndex.from_breaks', ([], {'breaks': 'bin_edges'}), '(breaks=bin_edges)\n', (7171, 7189), True, 'import pandas as pd\n'), ((7890, 7927), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'neighbor_distances'}), '(data=neighbor_distances)\n', (7902, 7927), True, 'import pandas as pd\n'), ((6155, 6204), 'numpy.isclose', 'np.isclose', (['unique_floats[1:]', 'unique_floats[:-1]'], {}), '(unique_floats[1:], unique_floats[:-1])\n', (6165, 6204), True, 'import numpy as np\n'), ((4657, 4732), 'pandas.cut', 'pd.cut', ([], {'x': "neighbor_distances_df['distance_ij']", 'bins': 'distance_bins_df.index'}), "(x=neighbor_distances_df['distance_ij'], bins=distance_bins_df.index)\n", (4663, 4732), True, 'import pandas as pd\n'), ((5575, 5625), 'pandas.Categorical', 'pd.Categorical', ([], {'values': 'bin_intervals', 'ordered': '(True)'}), '(values=bin_intervals, ordered=True)\n', (5589, 5625), True, 'import pandas as pd\n'), ((5654, 5707), 'pandas.Categorical', 'pd.Categorical', ([], {'values': 'unique_distances', 'ordered': '(True)'}), '(values=unique_distances, ordered=True)\n', (5668, 5707), True, 'import pandas as pd\n')]
|
# Standard Library
import os
import time
from datetime import datetime
# Third Party
import numpy as np
import pytest
import xgboost
from tests.core.utils import check_tf_events, delete_local_trials, verify_files
# First Party
from smdebug.core.modes import ModeKeys
from smdebug.core.save_config import SaveConfig, SaveConfigMode
from smdebug.xgboost import Hook as XG_Hook
SMDEBUG_XG_HOOK_TESTS_DIR = "/tmp/test_output/smdebug_xg/tests/"
def simple_xg_model(hook, num_round=10, seed=42, with_timestamp=False):
np.random.seed(seed)
train_data = np.random.rand(5, 10)
train_label = np.random.randint(2, size=5)
dtrain = xgboost.DMatrix(train_data, label=train_label)
test_data = np.random.rand(5, 10)
test_label = np.random.randint(2, size=5)
dtest = xgboost.DMatrix(test_data, label=test_label)
params = {}
scalars_to_be_saved = dict()
ts = time.time()
hook.save_scalar(
"xg_num_steps", num_round, sm_metric=True, timestamp=ts if with_timestamp else None
)
scalars_to_be_saved["scalar/xg_num_steps"] = (ts, num_round)
ts = time.time()
hook.save_scalar(
"xg_before_train", 1, sm_metric=False, timestamp=ts if with_timestamp else None
)
scalars_to_be_saved["scalar/xg_before_train"] = (ts, 1)
hook.set_mode(ModeKeys.TRAIN)
xgboost.train(
params,
dtrain,
evals=[(dtrain, "train"), (dtest, "test")],
num_boost_round=num_round,
callbacks=[hook],
)
ts = time.time()
hook.save_scalar("xg_after_train", 1, sm_metric=False, timestamp=ts if with_timestamp else None)
scalars_to_be_saved["scalar/xg_after_train"] = (ts, 1)
return scalars_to_be_saved
def helper_xgboost_tests(collection, save_config, with_timestamp):
coll_name, coll_regex = collection
run_id = "trial_" + coll_name + "-" + datetime.now().strftime("%Y%m%d-%H%M%S%f")
trial_dir = os.path.join(SMDEBUG_XG_HOOK_TESTS_DIR, run_id)
hook = XG_Hook(
out_dir=trial_dir,
include_collections=[coll_name],
save_config=save_config,
export_tensorboard=True,
)
saved_scalars = simple_xg_model(hook, with_timestamp=with_timestamp)
hook.close()
verify_files(trial_dir, save_config, saved_scalars)
if with_timestamp:
check_tf_events(trial_dir, saved_scalars)
@pytest.mark.parametrize("collection", [("all", ".*"), ("scalars", "^scalar")])
@pytest.mark.parametrize(
"save_config",
[
SaveConfig(save_steps=[0, 2, 4, 6, 8]),
SaveConfig(
{
ModeKeys.TRAIN: SaveConfigMode(save_interval=2),
ModeKeys.GLOBAL: SaveConfigMode(save_interval=3),
ModeKeys.EVAL: SaveConfigMode(save_interval=1),
}
),
],
)
@pytest.mark.parametrize("with_timestamp", [True, False])
def test_xgboost_save_scalar(collection, save_config, with_timestamp):
helper_xgboost_tests(collection, save_config, with_timestamp)
delete_local_trials([SMDEBUG_XG_HOOK_TESTS_DIR])
|
[
"tests.core.utils.delete_local_trials",
"numpy.random.seed",
"xgboost.train",
"datetime.datetime.now",
"time.time",
"smdebug.core.save_config.SaveConfigMode",
"smdebug.core.save_config.SaveConfig",
"tests.core.utils.check_tf_events",
"numpy.random.randint",
"tests.core.utils.verify_files",
"numpy.random.rand",
"pytest.mark.parametrize",
"os.path.join",
"xgboost.DMatrix",
"smdebug.xgboost.Hook"
] |
[((2346, 2424), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""collection"""', "[('all', '.*'), ('scalars', '^scalar')]"], {}), "('collection', [('all', '.*'), ('scalars', '^scalar')])\n", (2369, 2424), False, 'import pytest\n'), ((2788, 2844), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""with_timestamp"""', '[True, False]'], {}), "('with_timestamp', [True, False])\n", (2811, 2844), False, 'import pytest\n'), ((522, 542), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (536, 542), True, 'import numpy as np\n'), ((561, 582), 'numpy.random.rand', 'np.random.rand', (['(5)', '(10)'], {}), '(5, 10)\n', (575, 582), True, 'import numpy as np\n'), ((601, 629), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(5)'}), '(2, size=5)\n', (618, 629), True, 'import numpy as np\n'), ((643, 689), 'xgboost.DMatrix', 'xgboost.DMatrix', (['train_data'], {'label': 'train_label'}), '(train_data, label=train_label)\n', (658, 689), False, 'import xgboost\n'), ((707, 728), 'numpy.random.rand', 'np.random.rand', (['(5)', '(10)'], {}), '(5, 10)\n', (721, 728), True, 'import numpy as np\n'), ((746, 774), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(5)'}), '(2, size=5)\n', (763, 774), True, 'import numpy as np\n'), ((787, 831), 'xgboost.DMatrix', 'xgboost.DMatrix', (['test_data'], {'label': 'test_label'}), '(test_data, label=test_label)\n', (802, 831), False, 'import xgboost\n'), ((892, 903), 'time.time', 'time.time', ([], {}), '()\n', (901, 903), False, 'import time\n'), ((1099, 1110), 'time.time', 'time.time', ([], {}), '()\n', (1108, 1110), False, 'import time\n'), ((1326, 1448), 'xgboost.train', 'xgboost.train', (['params', 'dtrain'], {'evals': "[(dtrain, 'train'), (dtest, 'test')]", 'num_boost_round': 'num_round', 'callbacks': '[hook]'}), "(params, dtrain, evals=[(dtrain, 'train'), (dtest, 'test')],\n num_boost_round=num_round, callbacks=[hook])\n", (1339, 1448), False, 'import xgboost\n'), ((1501, 1512), 'time.time', 'time.time', ([], {}), '()\n', (1510, 1512), False, 'import time\n'), ((1914, 1961), 'os.path.join', 'os.path.join', (['SMDEBUG_XG_HOOK_TESTS_DIR', 'run_id'], {}), '(SMDEBUG_XG_HOOK_TESTS_DIR, run_id)\n', (1926, 1961), False, 'import os\n'), ((1974, 2088), 'smdebug.xgboost.Hook', 'XG_Hook', ([], {'out_dir': 'trial_dir', 'include_collections': '[coll_name]', 'save_config': 'save_config', 'export_tensorboard': '(True)'}), '(out_dir=trial_dir, include_collections=[coll_name], save_config=\n save_config, export_tensorboard=True)\n', (1981, 2088), True, 'from smdebug.xgboost import Hook as XG_Hook\n'), ((2218, 2269), 'tests.core.utils.verify_files', 'verify_files', (['trial_dir', 'save_config', 'saved_scalars'], {}), '(trial_dir, save_config, saved_scalars)\n', (2230, 2269), False, 'from tests.core.utils import check_tf_events, delete_local_trials, verify_files\n'), ((2986, 3034), 'tests.core.utils.delete_local_trials', 'delete_local_trials', (['[SMDEBUG_XG_HOOK_TESTS_DIR]'], {}), '([SMDEBUG_XG_HOOK_TESTS_DIR])\n', (3005, 3034), False, 'from tests.core.utils import check_tf_events, delete_local_trials, verify_files\n'), ((2301, 2342), 'tests.core.utils.check_tf_events', 'check_tf_events', (['trial_dir', 'saved_scalars'], {}), '(trial_dir, saved_scalars)\n', (2316, 2342), False, 'from tests.core.utils import check_tf_events, delete_local_trials, verify_files\n'), ((2484, 2522), 'smdebug.core.save_config.SaveConfig', 'SaveConfig', ([], {'save_steps': '[0, 2, 4, 6, 8]'}), '(save_steps=[0, 2, 4, 6, 8])\n', (2494, 2522), False, 'from smdebug.core.save_config import SaveConfig, SaveConfigMode\n'), ((1855, 1869), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1867, 1869), False, 'from datetime import datetime\n'), ((2590, 2621), 'smdebug.core.save_config.SaveConfigMode', 'SaveConfigMode', ([], {'save_interval': '(2)'}), '(save_interval=2)\n', (2604, 2621), False, 'from smdebug.core.save_config import SaveConfig, SaveConfigMode\n'), ((2656, 2687), 'smdebug.core.save_config.SaveConfigMode', 'SaveConfigMode', ([], {'save_interval': '(3)'}), '(save_interval=3)\n', (2670, 2687), False, 'from smdebug.core.save_config import SaveConfig, SaveConfigMode\n'), ((2720, 2751), 'smdebug.core.save_config.SaveConfigMode', 'SaveConfigMode', ([], {'save_interval': '(1)'}), '(save_interval=1)\n', (2734, 2751), False, 'from smdebug.core.save_config import SaveConfig, SaveConfigMode\n')]
|
import cv2
import numpy as np
cap = cv2.VideoCapture('./video/Teletubbies_Trim.mp4')
while True:
ret, frame = cap.read()
if not ret:
cap = cv2.VideoCapture('./video/Teletubbies_Trim.mp4')
ret, frame = cap.read()
# break
cv2.imshow('frame', frame)
# color filtering
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# hsv hue sat value
lower_purple = np.array([50, 0, 40])
upper_purple = np.array([170, 80, 120])
mask = cv2.inRange(frame, lower_purple, upper_purple)
res = cv2.bitwise_and(frame, frame, mask=mask)
# cv2.imshow('mask', mask)
cv2.imshow('res', res)
kernel = np.ones((10, 10), np.uint8)
erosion = cv2.erode(mask, kernel, iterations=1)
dilation = cv2.dilate(mask, kernel, iterations=1)
cv2.imshow('erosion', erosion)
cv2.imshow('dilation', dilation)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
cv2.imshow('opening', opening)
cv2.imshow('closing', closing)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
if k == 32:
cv2.waitKey(-1)
cap.release()
cv2.destroyAllWindows()
|
[
"cv2.bitwise_and",
"cv2.dilate",
"cv2.cvtColor",
"cv2.morphologyEx",
"cv2.waitKey",
"cv2.imshow",
"numpy.ones",
"cv2.VideoCapture",
"numpy.array",
"cv2.erode",
"cv2.destroyAllWindows",
"cv2.inRange"
] |
[((37, 85), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""./video/Teletubbies_Trim.mp4"""'], {}), "('./video/Teletubbies_Trim.mp4')\n", (53, 85), False, 'import cv2\n'), ((1165, 1188), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1186, 1188), False, 'import cv2\n'), ((258, 284), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (268, 284), False, 'import cv2\n'), ((318, 356), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HSV'], {}), '(frame, cv2.COLOR_BGR2HSV)\n', (330, 356), False, 'import cv2\n'), ((401, 422), 'numpy.array', 'np.array', (['[50, 0, 40]'], {}), '([50, 0, 40])\n', (409, 422), True, 'import numpy as np\n'), ((442, 466), 'numpy.array', 'np.array', (['[170, 80, 120]'], {}), '([170, 80, 120])\n', (450, 466), True, 'import numpy as np\n'), ((479, 525), 'cv2.inRange', 'cv2.inRange', (['frame', 'lower_purple', 'upper_purple'], {}), '(frame, lower_purple, upper_purple)\n', (490, 525), False, 'import cv2\n'), ((536, 576), 'cv2.bitwise_and', 'cv2.bitwise_and', (['frame', 'frame'], {'mask': 'mask'}), '(frame, frame, mask=mask)\n', (551, 576), False, 'import cv2\n'), ((612, 634), 'cv2.imshow', 'cv2.imshow', (['"""res"""', 'res'], {}), "('res', res)\n", (622, 634), False, 'import cv2\n'), ((649, 676), 'numpy.ones', 'np.ones', (['(10, 10)', 'np.uint8'], {}), '((10, 10), np.uint8)\n', (656, 676), True, 'import numpy as np\n'), ((691, 728), 'cv2.erode', 'cv2.erode', (['mask', 'kernel'], {'iterations': '(1)'}), '(mask, kernel, iterations=1)\n', (700, 728), False, 'import cv2\n'), ((744, 782), 'cv2.dilate', 'cv2.dilate', (['mask', 'kernel'], {'iterations': '(1)'}), '(mask, kernel, iterations=1)\n', (754, 782), False, 'import cv2\n'), ((787, 817), 'cv2.imshow', 'cv2.imshow', (['"""erosion"""', 'erosion'], {}), "('erosion', erosion)\n", (797, 817), False, 'import cv2\n'), ((822, 854), 'cv2.imshow', 'cv2.imshow', (['"""dilation"""', 'dilation'], {}), "('dilation', dilation)\n", (832, 854), False, 'import cv2\n'), ((870, 916), 'cv2.morphologyEx', 'cv2.morphologyEx', (['mask', 'cv2.MORPH_OPEN', 'kernel'], {}), '(mask, cv2.MORPH_OPEN, kernel)\n', (886, 916), False, 'import cv2\n'), ((931, 978), 'cv2.morphologyEx', 'cv2.morphologyEx', (['mask', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(mask, cv2.MORPH_CLOSE, kernel)\n', (947, 978), False, 'import cv2\n'), ((983, 1013), 'cv2.imshow', 'cv2.imshow', (['"""opening"""', 'opening'], {}), "('opening', opening)\n", (993, 1013), False, 'import cv2\n'), ((1018, 1048), 'cv2.imshow', 'cv2.imshow', (['"""closing"""', 'closing'], {}), "('closing', closing)\n", (1028, 1048), False, 'import cv2\n'), ((157, 205), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""./video/Teletubbies_Trim.mp4"""'], {}), "('./video/Teletubbies_Trim.mp4')\n", (173, 205), False, 'import cv2\n'), ((1058, 1072), 'cv2.waitKey', 'cv2.waitKey', (['(5)'], {}), '(5)\n', (1069, 1072), False, 'import cv2\n'), ((1134, 1149), 'cv2.waitKey', 'cv2.waitKey', (['(-1)'], {}), '(-1)\n', (1145, 1149), False, 'import cv2\n')]
|
from skimage import io
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
if __name__ == "__main__":
from libExtractTile import getNotEmptyTiles
import npImageNormalizations as npImNorm
else:
from .libExtractTile import getNotEmptyTiles
#import .npImageNormalizations as npImNorm
import unittest
import math
class TestExtractTile(unittest.TestCase):
def setUp(self):
datasetPath = "data\\kaggleOfficial"
citoImagesPath = os.path.join(datasetPath,"train_images")
#self.toOpen = os.path.join(citoImagesPath,"00a7fb880dc12c5de82df39b30533da9.tiff")
#self.toOpen = r"M:\Panda\officialData\train_images\00a76bfbec239fd9f465d6581806ff42.tiff"
self.toOpen = r"//10.0.4.13/Machine_Learning/Panda/officialData/train_images/00a7fb880dc12c5de82df39b30533da9.tiff"
#self.toOpen = r"C:\ML\PANDA-Challenge\data\kaggleOfficial\train_images\00a76bfbec239fd9f465d6581806ff42.tiff"
print("file exists {0}".format(os.path.exists(self.toOpen)))
open(self.toOpen,"r")
print("opened")
#print("Attempting to open {0}".format(self.toOpen))
self.im = io.imread(self.toOpen,plugin="tifffile")
self.shape = self.im.shape
#print("Read. shape {0}".format(self.im.shape))
def test_idx_list_of_tiles_returned(self):
h,w,_ = self.shape
tileSize = 1024
idxList,_ = getNotEmptyTiles(self.im,tileSize)
possibleTiles = math.ceil(h/tileSize) * math.ceil(w/tileSize)
self.assertLess(len(idxList),possibleTiles)
def test_all_tiles_have_same_size(self):
tileSize = 1024
_,tiles = getNotEmptyTiles(self.im,tileSize)
for tile in tiles:
th,tw,tc = tile.shape
self.assertEqual(th,tileSize,"height not equal to requested size")
self.assertEqual(tw,tileSize,"width not equal to requested size")
self.assertEqual(tc,3, "number of color channels not equal to requested size")
def test_precomputed_tile_indices_return_the_same(self):
tileSize = 1024
precomputed,tiles = getNotEmptyTiles(self.im,tileSize)
_,tiles2 = getNotEmptyTiles(self.im,tileSize, precomputedTileIndices=precomputed)
self.assertEqual(len(tiles),len(tiles2))
for i in range(0,len(tiles)):
t1,t2 = tiles[i],tiles2[i]
self.assertTrue(np.nansum(abs(t1-t2)) == 0) # exact match
if __name__ == "__main__":
print("test app")
testCase = TestExtractTile()
testCase.setUp()
tileSize = 1024
plt.figure()
plt.imshow(testCase.im)
#plt.show() # display it
#normalized = npImNorm.GCNtoRGB_uint8(npImNorm.GCN(testCase.im, lambdaTerm=10.0))
#plt.figure()
#plt.imshow(normalized)
#input("Press Enter to continue...")
tileIdx,tiles = getNotEmptyTiles(testCase.im,tileSize)
# playing with contrasts
contrasts = []
means = []
for tile in tiles:
contrasts.append(npImNorm.getImageContrast_withoutPureWhite(tile))
means.append(npImNorm.getImageMean_withoutPureWhite(tile))
meanContrast = np.mean(np.array(contrasts))
meanMean = np.mean(means)
for i in range(0,len(tiles)):
tiles[i] = npImNorm.GCNtoRGB_uint8(npImNorm.GCN(tiles[i], lambdaTerm=0.0, precomputedContrast=meanContrast, precomputedMean=meanMean), cutoffSigmasRange=1.0)
h,w,_ = testCase.im.shape
possibleTiles = math.ceil(h/tileSize) * math.ceil(w/tileSize)
print("Got {0} non empty tiles out of {1} possible.".format(len(tileIdx),possibleTiles))
N = len(tileIdx)
cols = round(math.sqrt(N))
rows = math.ceil(N/cols)
plt.figure()
r,c = tileIdx[N-1]
plt.title("tile [{0},{1}]".format(r,c))
plt.imshow(tiles[N-1])
fig, ax = plt.subplots(rows,cols)
fig.set_facecolor((0.3,0.3,0.3))
idx = 1
for row in range(0,rows):
for col in range(0,cols):
row = (idx - 1) // cols
col = (idx -1) % cols
#ax[row,col].set_title("tile [{0},{1}]".format(tile_r,tile_c))
ax[row,col].axis('off')
if idx-1 < N:
ax[row,col].imshow(tiles[idx-1])
idx = idx + 1
plt.show() # display it
#im.show()
|
[
"npImageNormalizations.getImageContrast_withoutPureWhite",
"matplotlib.pyplot.show",
"os.path.join",
"math.sqrt",
"math.ceil",
"npImageNormalizations.getImageMean_withoutPureWhite",
"matplotlib.pyplot.imshow",
"os.path.exists",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"npImageNormalizations.GCN",
"matplotlib.pyplot.subplots",
"libExtractTile.getNotEmptyTiles",
"skimage.io.imread"
] |
[((2594, 2606), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2604, 2606), True, 'import matplotlib.pyplot as plt\n'), ((2611, 2634), 'matplotlib.pyplot.imshow', 'plt.imshow', (['testCase.im'], {}), '(testCase.im)\n', (2621, 2634), True, 'import matplotlib.pyplot as plt\n'), ((2868, 2907), 'libExtractTile.getNotEmptyTiles', 'getNotEmptyTiles', (['testCase.im', 'tileSize'], {}), '(testCase.im, tileSize)\n', (2884, 2907), False, 'from libExtractTile import getNotEmptyTiles\n'), ((3216, 3230), 'numpy.mean', 'np.mean', (['means'], {}), '(means)\n', (3223, 3230), True, 'import numpy as np\n'), ((3687, 3706), 'math.ceil', 'math.ceil', (['(N / cols)'], {}), '(N / cols)\n', (3696, 3706), False, 'import math\n'), ((3716, 3728), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3726, 3728), True, 'import matplotlib.pyplot as plt\n'), ((3804, 3828), 'matplotlib.pyplot.imshow', 'plt.imshow', (['tiles[N - 1]'], {}), '(tiles[N - 1])\n', (3814, 3828), True, 'import matplotlib.pyplot as plt\n'), ((3842, 3866), 'matplotlib.pyplot.subplots', 'plt.subplots', (['rows', 'cols'], {}), '(rows, cols)\n', (3854, 3866), True, 'import matplotlib.pyplot as plt\n'), ((4300, 4310), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4308, 4310), True, 'import matplotlib.pyplot as plt\n'), ((480, 521), 'os.path.join', 'os.path.join', (['datasetPath', '"""train_images"""'], {}), "(datasetPath, 'train_images')\n", (492, 521), False, 'import os\n'), ((1175, 1216), 'skimage.io.imread', 'io.imread', (['self.toOpen'], {'plugin': '"""tifffile"""'}), "(self.toOpen, plugin='tifffile')\n", (1184, 1216), False, 'from skimage import io\n'), ((1426, 1461), 'libExtractTile.getNotEmptyTiles', 'getNotEmptyTiles', (['self.im', 'tileSize'], {}), '(self.im, tileSize)\n', (1442, 1461), False, 'from libExtractTile import getNotEmptyTiles\n'), ((1679, 1714), 'libExtractTile.getNotEmptyTiles', 'getNotEmptyTiles', (['self.im', 'tileSize'], {}), '(self.im, tileSize)\n', (1695, 1714), False, 'from libExtractTile import getNotEmptyTiles\n'), ((2137, 2172), 'libExtractTile.getNotEmptyTiles', 'getNotEmptyTiles', (['self.im', 'tileSize'], {}), '(self.im, tileSize)\n', (2153, 2172), False, 'from libExtractTile import getNotEmptyTiles\n'), ((2191, 2262), 'libExtractTile.getNotEmptyTiles', 'getNotEmptyTiles', (['self.im', 'tileSize'], {'precomputedTileIndices': 'precomputed'}), '(self.im, tileSize, precomputedTileIndices=precomputed)\n', (2207, 2262), False, 'from libExtractTile import getNotEmptyTiles\n'), ((3176, 3195), 'numpy.array', 'np.array', (['contrasts'], {}), '(contrasts)\n', (3184, 3195), True, 'import numpy as np\n'), ((3483, 3506), 'math.ceil', 'math.ceil', (['(h / tileSize)'], {}), '(h / tileSize)\n', (3492, 3506), False, 'import math\n'), ((3507, 3530), 'math.ceil', 'math.ceil', (['(w / tileSize)'], {}), '(w / tileSize)\n', (3516, 3530), False, 'import math\n'), ((3662, 3674), 'math.sqrt', 'math.sqrt', (['N'], {}), '(N)\n', (3671, 3674), False, 'import math\n'), ((1485, 1508), 'math.ceil', 'math.ceil', (['(h / tileSize)'], {}), '(h / tileSize)\n', (1494, 1508), False, 'import math\n'), ((1509, 1532), 'math.ceil', 'math.ceil', (['(w / tileSize)'], {}), '(w / tileSize)\n', (1518, 1532), False, 'import math\n'), ((3032, 3080), 'npImageNormalizations.getImageContrast_withoutPureWhite', 'npImNorm.getImageContrast_withoutPureWhite', (['tile'], {}), '(tile)\n', (3074, 3080), True, 'import npImageNormalizations as npImNorm\n'), ((3103, 3147), 'npImageNormalizations.getImageMean_withoutPureWhite', 'npImNorm.getImageMean_withoutPureWhite', (['tile'], {}), '(tile)\n', (3141, 3147), True, 'import npImageNormalizations as npImNorm\n'), ((3308, 3410), 'npImageNormalizations.GCN', 'npImNorm.GCN', (['tiles[i]'], {'lambdaTerm': '(0.0)', 'precomputedContrast': 'meanContrast', 'precomputedMean': 'meanMean'}), '(tiles[i], lambdaTerm=0.0, precomputedContrast=meanContrast,\n precomputedMean=meanMean)\n', (3320, 3410), True, 'import npImageNormalizations as npImNorm\n'), ((1011, 1038), 'os.path.exists', 'os.path.exists', (['self.toOpen'], {}), '(self.toOpen)\n', (1025, 1038), False, 'import os\n')]
|
import glob
import skimage.io as io
import skimage.transform as trans
import numpy as np
import pylab as plt
def square_image(img, random = None):
""" Square Image
Function that takes an image (ndarray),
gets its maximum dimension,
creates a black square canvas of max dimension
and puts the original image into the
black canvas's center
If random [0, 2] is specified, the original image is placed
in the new image depending on the coefficient,
where 0 - constrained to the left/up anchor,
2 - constrained to the right/bottom anchor
"""
size = max(img.shape[0], img.shape[1])
new_img = np.zeros((size, size),np.float32)
ax, ay = (size - img.shape[1])//2, (size - img.shape[0])//2
if random and not ax == 0:
ax = int(ax * random)
elif random and not ay == 0:
ay = int(ay * random)
new_img[ay:img.shape[0] + ay, ax:ax+img.shape[1]] = img
return new_img
def reshape_image(img, target_size):
""" Reshape Image
Function that takes an image
and rescales it to target_size
"""
img = trans.resize(img,target_size)
img = np.reshape(img,img.shape+(1,))
img = np.reshape(img,(1,)+img.shape)
return img
def normalize_mask(mask):
""" Mask Normalization
Function that returns normalized mask
Each pixel is either 0 or 1
"""
mask[mask > 0.5] = 1
mask[mask <= 0.5] = 0
return mask
def show_image(img):
plt.imshow(img, cmap=plt.cm.gray)
plt.show()
|
[
"pylab.show",
"numpy.zeros",
"pylab.imshow",
"skimage.transform.resize",
"numpy.reshape"
] |
[((640, 674), 'numpy.zeros', 'np.zeros', (['(size, size)', 'np.float32'], {}), '((size, size), np.float32)\n', (648, 674), True, 'import numpy as np\n'), ((1090, 1120), 'skimage.transform.resize', 'trans.resize', (['img', 'target_size'], {}), '(img, target_size)\n', (1102, 1120), True, 'import skimage.transform as trans\n'), ((1130, 1163), 'numpy.reshape', 'np.reshape', (['img', '(img.shape + (1,))'], {}), '(img, img.shape + (1,))\n', (1140, 1163), True, 'import numpy as np\n'), ((1171, 1204), 'numpy.reshape', 'np.reshape', (['img', '((1,) + img.shape)'], {}), '(img, (1,) + img.shape)\n', (1181, 1204), True, 'import numpy as np\n'), ((1446, 1479), 'pylab.imshow', 'plt.imshow', (['img'], {'cmap': 'plt.cm.gray'}), '(img, cmap=plt.cm.gray)\n', (1456, 1479), True, 'import pylab as plt\n'), ((1484, 1494), 'pylab.show', 'plt.show', ([], {}), '()\n', (1492, 1494), True, 'import pylab as plt\n')]
|
"""
Copyright (c) 2018-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
from extensions.middle.ConvertLayoutDependentOperations import ConvertLayoutDependentOperations
from mo.graph.graph import Node, Graph
from mo.middle.passes.eliminate import merge_data_nodes, graph_clean_up_tf
from mo.middle.passes.fusing.helpers import get_next_operation
from mo.middle.replacement import MiddleReplacementPattern
from mo.utils.error import Error
class FusePermutesSequence(MiddleReplacementPattern):
"""
This pass finds sequence of Permute operations and merge them to single Permute operation
In case if resulting Permutation do nothing, we just remove it
"""
enabled = True
graph_condition = [lambda graph: graph.graph['fw'] != 'caffe']
def run_after(self):
return [ConvertLayoutDependentOperations]
def find_and_replace_pattern(self, graph: Graph):
for node in list(graph.nodes()):
if node not in graph.nodes():
continue
permute_node = Node(graph, node)
if permute_node.has_valid('type') and permute_node.type == 'Permute':
list_of_permutes = [permute_node]
# Get sequence of permutations
node = permute_node
while True:
next_ops = get_next_operation(node)
if len(next_ops) != 1:
break
next_op = next_ops[0]
if next_op.has_valid('type') and next_op.type == 'Permute':
list_of_permutes.append(next_op)
node = next_op
else:
break
final_permutation = np.array([x for x in range(len(list_of_permutes[0].order))], dtype=np.int64)
for permute in list_of_permutes:
if not permute.has_valid('order'):
raise Error("Permute node {} has wrong attribute order = None".format(permute.name))
final_permutation = final_permutation[np.array(permute.order, dtype=np.int64)]
if np.array_equal(final_permutation, [x for x in range(len(list_of_permutes[0].order))]):
first_data_node, last_data_node = list_of_permutes[0].in_node(), list_of_permutes[-1].out_node()
graph.remove_edge(first_data_node.id, list_of_permutes[0].id)
else:
if len(list_of_permutes) < 2:
continue
first_data_node, last_data_node = list_of_permutes[0].out_node(), list_of_permutes[-1].out_node()
list_of_permutes[0].order = final_permutation
graph.remove_edge(first_data_node.id, first_data_node.out_node().id)
graph.remove_edge(last_data_node.in_node().id, last_data_node.id)
merge_data_nodes(graph, first_data_node, last_data_node)
graph.remove_node(last_data_node.id)
graph_clean_up_tf(graph)
|
[
"mo.graph.graph.Node",
"numpy.array",
"mo.middle.passes.fusing.helpers.get_next_operation",
"mo.middle.passes.eliminate.graph_clean_up_tf",
"mo.middle.passes.eliminate.merge_data_nodes"
] |
[((1567, 1584), 'mo.graph.graph.Node', 'Node', (['graph', 'node'], {}), '(graph, node)\n', (1571, 1584), False, 'from mo.graph.graph import Node, Graph\n'), ((3442, 3498), 'mo.middle.passes.eliminate.merge_data_nodes', 'merge_data_nodes', (['graph', 'first_data_node', 'last_data_node'], {}), '(graph, first_data_node, last_data_node)\n', (3458, 3498), False, 'from mo.middle.passes.eliminate import merge_data_nodes, graph_clean_up_tf\n'), ((3568, 3592), 'mo.middle.passes.eliminate.graph_clean_up_tf', 'graph_clean_up_tf', (['graph'], {}), '(graph)\n', (3585, 3592), False, 'from mo.middle.passes.eliminate import merge_data_nodes, graph_clean_up_tf\n'), ((1859, 1883), 'mo.middle.passes.fusing.helpers.get_next_operation', 'get_next_operation', (['node'], {}), '(node)\n', (1877, 1883), False, 'from mo.middle.passes.fusing.helpers import get_next_operation\n'), ((2617, 2656), 'numpy.array', 'np.array', (['permute.order'], {'dtype': 'np.int64'}), '(permute.order, dtype=np.int64)\n', (2625, 2656), True, 'import numpy as np\n')]
|
"""Wrapped xgboost for tabular datasets."""
from time import perf_counter
import logging
from copy import copy
from copy import deepcopy
from typing import Optional
from typing import Callable
from typing import Tuple
from typing import Dict
import xgboost as xgb
from xgboost import dask as dxgb
import numpy as np
import pandas as pd
import cupy as cp
from lightautoml.dataset.gpu.gpu_dataset import DaskCudfDataset
from lightautoml.dataset.gpu.gpu_dataset import CudfDataset
from .base_gpu import TabularMLAlgo_gpu
from .base_gpu import TabularDatasetGpu
from lightautoml.pipelines.selection.base import ImportanceEstimator
from lightautoml.validation.base import TrainValidIterator
from lightautoml.ml_algo.tuning.base import Distribution
from lightautoml.ml_algo.tuning.base import SearchSpace
logger = logging.getLogger(__name__)
class BoostXGB(TabularMLAlgo_gpu, ImportanceEstimator):
"""Gradient boosting on decision trees from LightGBM library.
default_params: All available parameters listed in lightgbm documentation:
- https://lightgbm.readthedocs.io/en/latest/Parameters.html
freeze_defaults:
- ``True`` : params may be rewritten depending on dataset.
- ``False``: params may be changed only manually or with tuning.
timer: :class:`~lightautoml.utils.timer.Timer` instance or ``None``.
"""
_name: str = 'XGB'
_default_params = {
'tree_method':'gpu_hist',
'predictor':'gpu_predictor',
'task': 'train',
"learning_rate": 0.05,
"max_leaves": 128,
"max_depth": 0,
"verbosity": 0,
"reg_alpha": 1,
"reg_lambda": 0.0,
"gamma": 0.0,
'max_bin': 255,
'n_estimators': 3000,
'early_stopping_rounds': 100,
'random_state': 42
}
def _infer_params(self) -> Tuple[dict, int, int, int, Optional[Callable], Optional[Callable]]:
"""Infer all parameters in lightgbm format.
Returns:
Tuple (params, num_trees, early_stopping_rounds, verbose_eval, fobj, feval).
About parameters: https://lightgbm.readthedocs.io/en/latest/_modules/lightgbm/engine.html
"""
params = copy(self.params)
early_stopping_rounds = params.pop('early_stopping_rounds')
num_trees = params.pop('n_estimators')
root_logger = logging.getLogger()
level = root_logger.getEffectiveLevel()
if level in (logging.CRITICAL, logging.ERROR, logging.WARNING):
verbose_eval = False
elif level == logging.INFO:
verbose_eval = 100
else:
verbose_eval = 10
# get objective params
loss = self.task.losses['xgb']
params['objective'] = loss.fobj_name
fobj = loss.fobj
# get metric params
params['metric'] = loss.metric_name
feval = loss.feval
params['num_class'] = self.n_classes
# add loss and tasks params if defined
params = {**params, **loss.fobj_params, **loss.metric_params}
return params, num_trees, early_stopping_rounds, verbose_eval, fobj, feval
def init_params_on_input(self, train_valid_iterator: TrainValidIterator) -> dict:
"""Get model parameters depending on dataset parameters.
Args:
train_valid_iterator: Classic cv-iterator.
Returns:
Parameters of model.
"""
rows_num = len(train_valid_iterator.train)
task = train_valid_iterator.train.task.name
suggested_params = copy(self.default_params)
if self.freeze_defaults:
# if user change defaults manually - keep it
return suggested_params
if task == 'reg':
suggested_params = {
"learning_rate": 0.05,
"max_leaves": 32
}
if rows_num <= 10000:
init_lr = 0.01
ntrees = 3000
es = 200
elif rows_num <= 20000:
init_lr = 0.02
ntrees = 3000
es = 200
elif rows_num <= 100000:
init_lr = 0.03
ntrees = 1200
es = 200
elif rows_num <= 300000:
init_lr = 0.04
ntrees = 2000
es = 100
else:
init_lr = 0.05
ntrees = 2000
es = 100
if rows_num > 300000:
suggested_params['max_leaves'] = 128 if task == 'reg' else 244
elif rows_num > 100000:
suggested_params['max_leaves'] = 64 if task == 'reg' else 128
elif rows_num > 50000:
suggested_params['max_leaves'] = 32 if task == 'reg' else 64
# params['reg_alpha'] = 1 if task == 'reg' else 0.5
elif rows_num > 20000:
suggested_params['max_leaves'] = 32 if task == 'reg' else 32
suggested_params['reg_alpha'] = 0.5 if task == 'reg' else 0.0
elif rows_num > 10000:
suggested_params['max_leaves'] = 32 if task == 'reg' else 64
suggested_params['reg_alpha'] = 0.5 if task == 'reg' else 0.2
elif rows_num > 5000:
suggested_params['max_leaves'] = 24 if task == 'reg' else 32
suggested_params['reg_alpha'] = 0.5 if task == 'reg' else 0.5
else:
suggested_params['max_leaves'] = 16 if task == 'reg' else 16
suggested_params['reg_alpha'] = 1 if task == 'reg' else 1
suggested_params['learning_rate'] = init_lr
suggested_params['n_estimators'] = ntrees
suggested_params['early_stopping_rounds'] = es
return suggested_params
def _get_default_search_spaces(self, suggested_params: Dict, estimated_n_trials: int) -> Dict:
"""Sample hyperparameters from suggested.
Args:
suggested_params: Dict with parameters.
estimated_n_trials: Maximum number of hyperparameter estimations.
Returns:
dict with sampled hyperparameters.
"""
optimization_search_space = {}
optimization_search_space['max_depth'] = SearchSpace(
Distribution.INTUNIFORM,
low=3,
high=7
)
optimization_search_space['max_leaves'] = SearchSpace(
Distribution.INTUNIFORM,
low=16,
high=255,
)
if estimated_n_trials > 30:
optimization_search_space['min_child_weight'] = SearchSpace(
Distribution.LOGUNIFORM,
low=1e-3,
high=10.0,
)
if estimated_n_trials > 100:
optimization_search_space['reg_alpha'] = SearchSpace(
Distribution.LOGUNIFORM,
low=1e-8,
high=10.0,
)
optimization_search_space['reg_lambda'] = SearchSpace(
Distribution.LOGUNIFORM,
low=1e-8,
high=10.0,
)
return optimization_search_space
def fit_predict_single_fold(self, train: TabularDatasetGpu, valid: TabularDatasetGpu, dev_id: int = 0) -> Tuple[xgb.Booster, np.ndarray]:
"""Implements training and prediction on single fold.
Args:
train: Train Dataset.
valid: Validation Dataset.
Returns:
Tuple (model, predicted_values)
"""
st = perf_counter()
train_target = train.target
train_weights = train.weights
valid_target = valid.target
valid_weights = valid.weights
train_data = train.data
valid_data = valid.data
with cp.cuda.Device(dev_id):
if type(train) == DaskCudfDataset:
train_target = train_target.compute()
if train_weights is not None:
train_weights = train_weights.compute()
valid_target = valid_target.compute()
if valid_weights is not None:
valid_weights = valid_weights.compute()
train_data = train_data.compute()
valid_data = valid_data.compute()
elif type(train) == CudfDataset:
train_target = train_target.copy()
if train_weights is not None:
train_weights = train_weights.copy()
valid_target = valid_target.copy()
if valid_weights is not None:
valid_weights = valid_weights.copy()
train_data = train_data.copy()
valid_data = valid_data.copy()
elif type(train_target) == cp.ndarray:
train_target = cp.copy(train_target)
if train_weights is not None:
train_weights = cp.copy(train_weights)
valid_target = cp.copy(valid_target)
if valid_weights is not None:
valid_weights = cp.copy(valid_weights)
train_data = cp.copy(train_data)
valid_data = cp.copy(valid_data)
else:
raise NotImplementedError("given type of input is not implemented:" + str(type(train_target)) + "class:" + str(self._name))
params, num_trees, early_stopping_rounds, verbose_eval, fobj, feval = self._infer_params()
train_target, train_weight = self.task.losses['xgb'].fw_func(train_target, train_weights)
valid_target, valid_weight = self.task.losses['xgb'].fw_func(valid_target, valid_weights)
xgb_train = xgb.DMatrix(train_data, label=train_target, weight=train_weight)
xgb_valid = xgb.DMatrix(valid_data, label=valid_target, weight=valid_weight)
params['gpu_id'] = dev_id
model = xgb.train(params, xgb_train, num_boost_round=num_trees, evals=[(xgb_train, 'train'), (xgb_valid, 'valid')],
obj=fobj, feval=feval, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval
)
val_pred = model.inplace_predict(valid_data)
val_pred = self.task.losses['xgb'].bw_func(val_pred)
print(perf_counter() - st, "xgb single fold time")
with cp.cuda.Device(0):
val_pred = cp.copy(val_pred)
return model, val_pred
def predict_single_fold(self, model: xgb.Booster, dataset: TabularDatasetGpu) -> np.ndarray:
"""Predict target values for dataset.
Args:
model: Lightgbm object.
dataset: Test Dataset.
Return:
Predicted target values.
"""
dataset_data = dataset.data
if type(dataset) == DaskCudfDataset:
dataset_data = dataset_data.compute()
pred = self.task.losses['xgb'].bw_func(model.inplace_predict(dataset_data))
return pred
def get_features_score(self) -> pd.Series:
"""Computes feature importance as mean values of feature importance provided by lightgbm per all models.
Returns:
Series with feature importances.
"""
#FIRST SORT TO FEATURES AND THEN SORT BACK TO IMPORTANCES - BAD
imp = 0
for model in self.models:
val = model.get_score(importance_type='gain')
sorted_list = [0.0 if val.get(i) is None else val.get(i) for i in self.features]
scores = np.array(sorted_list)
imp = imp + scores
imp = imp / len(self.models)
return pd.Series(imp, index=self.features).sort_values(ascending=False)
def fit(self, train_valid: TrainValidIterator):
"""Just to be compatible with :class:`~lightautoml.pipelines.selection.base.ImportanceEstimator`.
Args:
train_valid: Classic cv-iterator.
"""
self.fit_predict(train_valid)
class BoostXGB_dask(BoostXGB):
def __init__(self, client, *args, **kwargs):
self.client = client
super().__init__(*args, **kwargs)
def __deepcopy__(self, memo):
new_inst = type(self).__new__(self.__class__)
new_inst.client = self.client
for k,v in super().__dict__.items():
if k != 'client':
setattr(new_inst, k, deepcopy(v, memo))
return new_inst
def fit_predict_single_fold(self, train: DaskCudfDataset, valid: DaskCudfDataset, dev_id: int = 0) -> Tuple[dxgb.Booster, np.ndarray]:
"""Implements training and prediction on single fold.
Args:
train: Train Dataset.
valid: Validation Dataset.
Returns:
Tuple (model, predicted_values)
"""
params, num_trees, early_stopping_rounds, verbose_eval, fobj, feval = self._infer_params()
train_target, train_weight = self.task.losses['xgb'].fw_func(train.target, train.weights)
valid_target, valid_weight = self.task.losses['xgb'].fw_func(valid.target, valid.weights)
xgb_train = dxgb.DaskDeviceQuantileDMatrix(self.client, train.data, label=train_target, weight=train_weight)
xgb_valid = dxgb.DaskDeviceQuantileDMatrix(self.client, valid.data, label=valid_target, weight=valid_weight)
model = dxgb.train(self.client, params, xgb_train, num_boost_round=num_trees, evals=[(xgb_train, 'train'), (xgb_valid, 'valid')],
obj=fobj, feval=feval, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval
)
val_pred = dxgb.inplace_predict(self.client, model, valid.data)
val_pred = self.task.losses['xgb'].bw_func(val_pred)
return model, val_pred
def predict_single_fold(self, model: dxgb.Booster, dataset: TabularDatasetGpu) -> np.ndarray:
"""Predict target values for dataset.
Args:
model: Lightgbm object.
dataset: Test Dataset.
Return:
Predicted target values.
"""
pred = self.task.losses['xgb'].bw_func(dxgb.inplace_predict(self.client, model, dataset.data))
return pred
def get_features_score(self) -> pd.Series:
"""Computes feature importance as mean values of feature importance provided by lightgbm per all models.
Returns:
Series with feature importances.
"""
#FIRST SORT TO FEATURES AND THEN SORT BACK TO IMPORTANCES - BAD
imp = 0
for model in self.models:
val = model['booster'].get_score(importance_type='gain')
sorted_list = [0.0 if val.get(i) is None else val.get(i) for i in self.features]
scores = np.array(sorted_list)
imp = imp + scores
imp = imp / len(self.models)
return pd.Series(imp, index=self.features).sort_values(ascending=False)
|
[
"copy.deepcopy",
"xgboost.train",
"lightautoml.ml_algo.tuning.base.SearchSpace",
"copy.copy",
"time.perf_counter",
"xgboost.dask.train",
"xgboost.dask.inplace_predict",
"xgboost.dask.DaskDeviceQuantileDMatrix",
"numpy.array",
"pandas.Series",
"cupy.cuda.Device",
"cupy.copy",
"xgboost.DMatrix",
"logging.getLogger"
] |
[((814, 841), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (831, 841), False, 'import logging\n'), ((2201, 2218), 'copy.copy', 'copy', (['self.params'], {}), '(self.params)\n', (2205, 2218), False, 'from copy import copy\n'), ((2357, 2376), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (2374, 2376), False, 'import logging\n'), ((3549, 3574), 'copy.copy', 'copy', (['self.default_params'], {}), '(self.default_params)\n', (3553, 3574), False, 'from copy import copy\n'), ((6087, 6138), 'lightautoml.ml_algo.tuning.base.SearchSpace', 'SearchSpace', (['Distribution.INTUNIFORM'], {'low': '(3)', 'high': '(7)'}), '(Distribution.INTUNIFORM, low=3, high=7)\n', (6098, 6138), False, 'from lightautoml.ml_algo.tuning.base import SearchSpace\n'), ((6236, 6290), 'lightautoml.ml_algo.tuning.base.SearchSpace', 'SearchSpace', (['Distribution.INTUNIFORM'], {'low': '(16)', 'high': '(255)'}), '(Distribution.INTUNIFORM, low=16, high=255)\n', (6247, 6290), False, 'from lightautoml.ml_algo.tuning.base import SearchSpace\n'), ((7366, 7380), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (7378, 7380), False, 'from time import perf_counter\n'), ((9484, 9548), 'xgboost.DMatrix', 'xgb.DMatrix', (['train_data'], {'label': 'train_target', 'weight': 'train_weight'}), '(train_data, label=train_target, weight=train_weight)\n', (9495, 9548), True, 'import xgboost as xgb\n'), ((9569, 9633), 'xgboost.DMatrix', 'xgb.DMatrix', (['valid_data'], {'label': 'valid_target', 'weight': 'valid_weight'}), '(valid_data, label=valid_target, weight=valid_weight)\n', (9580, 9633), True, 'import xgboost as xgb\n'), ((9684, 9894), 'xgboost.train', 'xgb.train', (['params', 'xgb_train'], {'num_boost_round': 'num_trees', 'evals': "[(xgb_train, 'train'), (xgb_valid, 'valid')]", 'obj': 'fobj', 'feval': 'feval', 'early_stopping_rounds': 'early_stopping_rounds', 'verbose_eval': 'verbose_eval'}), "(params, xgb_train, num_boost_round=num_trees, evals=[(xgb_train,\n 'train'), (xgb_valid, 'valid')], obj=fobj, feval=feval,\n early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval)\n", (9693, 9894), True, 'import xgboost as xgb\n'), ((12888, 12988), 'xgboost.dask.DaskDeviceQuantileDMatrix', 'dxgb.DaskDeviceQuantileDMatrix', (['self.client', 'train.data'], {'label': 'train_target', 'weight': 'train_weight'}), '(self.client, train.data, label=train_target,\n weight=train_weight)\n', (12918, 12988), True, 'from xgboost import dask as dxgb\n'), ((13005, 13105), 'xgboost.dask.DaskDeviceQuantileDMatrix', 'dxgb.DaskDeviceQuantileDMatrix', (['self.client', 'valid.data'], {'label': 'valid_target', 'weight': 'valid_weight'}), '(self.client, valid.data, label=valid_target,\n weight=valid_weight)\n', (13035, 13105), True, 'from xgboost import dask as dxgb\n'), ((13118, 13343), 'xgboost.dask.train', 'dxgb.train', (['self.client', 'params', 'xgb_train'], {'num_boost_round': 'num_trees', 'evals': "[(xgb_train, 'train'), (xgb_valid, 'valid')]", 'obj': 'fobj', 'feval': 'feval', 'early_stopping_rounds': 'early_stopping_rounds', 'verbose_eval': 'verbose_eval'}), "(self.client, params, xgb_train, num_boost_round=num_trees, evals\n =[(xgb_train, 'train'), (xgb_valid, 'valid')], obj=fobj, feval=feval,\n early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval)\n", (13128, 13343), True, 'from xgboost import dask as dxgb\n'), ((13408, 13460), 'xgboost.dask.inplace_predict', 'dxgb.inplace_predict', (['self.client', 'model', 'valid.data'], {}), '(self.client, model, valid.data)\n', (13428, 13460), True, 'from xgboost import dask as dxgb\n'), ((6435, 6493), 'lightautoml.ml_algo.tuning.base.SearchSpace', 'SearchSpace', (['Distribution.LOGUNIFORM'], {'low': '(0.001)', 'high': '(10.0)'}), '(Distribution.LOGUNIFORM, low=0.001, high=10.0)\n', (6446, 6493), False, 'from lightautoml.ml_algo.tuning.base import SearchSpace\n'), ((6647, 6705), 'lightautoml.ml_algo.tuning.base.SearchSpace', 'SearchSpace', (['Distribution.LOGUNIFORM'], {'low': '(1e-08)', 'high': '(10.0)'}), '(Distribution.LOGUNIFORM, low=1e-08, high=10.0)\n', (6658, 6705), False, 'from lightautoml.ml_algo.tuning.base import SearchSpace\n'), ((6822, 6880), 'lightautoml.ml_algo.tuning.base.SearchSpace', 'SearchSpace', (['Distribution.LOGUNIFORM'], {'low': '(1e-08)', 'high': '(10.0)'}), '(Distribution.LOGUNIFORM, low=1e-08, high=10.0)\n', (6833, 6880), False, 'from lightautoml.ml_algo.tuning.base import SearchSpace\n'), ((7606, 7628), 'cupy.cuda.Device', 'cp.cuda.Device', (['dev_id'], {}), '(dev_id)\n', (7620, 7628), True, 'import cupy as cp\n'), ((10127, 10144), 'cupy.cuda.Device', 'cp.cuda.Device', (['(0)'], {}), '(0)\n', (10141, 10144), True, 'import cupy as cp\n'), ((10169, 10186), 'cupy.copy', 'cp.copy', (['val_pred'], {}), '(val_pred)\n', (10176, 10186), True, 'import cupy as cp\n'), ((11284, 11305), 'numpy.array', 'np.array', (['sorted_list'], {}), '(sorted_list)\n', (11292, 11305), True, 'import numpy as np\n'), ((13899, 13953), 'xgboost.dask.inplace_predict', 'dxgb.inplace_predict', (['self.client', 'model', 'dataset.data'], {}), '(self.client, model, dataset.data)\n', (13919, 13953), True, 'from xgboost import dask as dxgb\n'), ((14519, 14540), 'numpy.array', 'np.array', (['sorted_list'], {}), '(sorted_list)\n', (14527, 14540), True, 'import numpy as np\n'), ((10069, 10083), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (10081, 10083), False, 'from time import perf_counter\n'), ((11399, 11434), 'pandas.Series', 'pd.Series', (['imp'], {'index': 'self.features'}), '(imp, index=self.features)\n', (11408, 11434), True, 'import pandas as pd\n'), ((14634, 14669), 'pandas.Series', 'pd.Series', (['imp'], {'index': 'self.features'}), '(imp, index=self.features)\n', (14643, 14669), True, 'import pandas as pd\n'), ((12154, 12171), 'copy.deepcopy', 'deepcopy', (['v', 'memo'], {}), '(v, memo)\n', (12162, 12171), False, 'from copy import deepcopy\n'), ((8626, 8647), 'cupy.copy', 'cp.copy', (['train_target'], {}), '(train_target)\n', (8633, 8647), True, 'import cupy as cp\n'), ((8784, 8805), 'cupy.copy', 'cp.copy', (['valid_target'], {}), '(valid_target)\n', (8791, 8805), True, 'import cupy as cp\n'), ((8940, 8959), 'cupy.copy', 'cp.copy', (['train_data'], {}), '(train_data)\n', (8947, 8959), True, 'import cupy as cp\n'), ((8989, 9008), 'cupy.copy', 'cp.copy', (['valid_data'], {}), '(valid_data)\n', (8996, 9008), True, 'import cupy as cp\n'), ((8730, 8752), 'cupy.copy', 'cp.copy', (['train_weights'], {}), '(train_weights)\n', (8737, 8752), True, 'import cupy as cp\n'), ((8888, 8910), 'cupy.copy', 'cp.copy', (['valid_weights'], {}), '(valid_weights)\n', (8895, 8910), True, 'import cupy as cp\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.