code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
"""
mathEX.py
@author: <NAME>
@email: <EMAIL>
Math-related functions, extensions.
"""
import numpy as np
from ml.utils.logger import get_logger
LOGGER = get_logger(__name__)
def change_to_multi_class(y):
"""
change the input prediction y to array-wise multi_class classifiers.
@param y:input prediction y, numpy arrays
@return: array-wise multi_class classifiers
"""
if not isinstance(y, np.ndarray) or y.ndim <= 1:
LOGGER.info('Input is not an np.ndarray, adding default value...')
y = np.array([[0]])
m = y.shape[1]
num_of_fields = int(y.max()) + 1
multi_class_y = np.zeros([num_of_fields, m])
for i in range(m):
label = y[0, i]
# print(type(label))
if isinstance(label, np.int64) and label >= 0:
multi_class_y[label, i] = 1
else:
multi_class_y[0, i] = 1
return multi_class_y
def compute_cost(al, y):
"""
compute costs between output results and actual results y. NEEDS TO BE MODIFIED.
@param al: output results, numpy arrays
@param y: actual result, numpy arrays
@return: cost, floats
"""
if isinstance(al, np.float) or isinstance(al, float) or isinstance(al, int):
al = np.array([[al]])
if isinstance(y, np.float) or isinstance(y, float) or isinstance(y, int):
y = np.array([[y]])
if not isinstance(al, np.ndarray) or not isinstance(y, np.ndarray) or not al.ndim > 1 or not y.ndim > 1:
LOGGER.info('Input is not an np.ndarray, adding default value...')
al = np.array([[0.5]])
y = np.array([[0.6]])
m = y.shape[1]
# Compute loss from aL and y.
cost = sum(sum((1. / m) * (-np.dot(y, np.log(al).T) - np.dot(1 - y, np.log(1 - al).T))))
cost = np.squeeze(cost)
assert (cost.shape == ())
return cost
def compute_cost_with_l2_regularization(al, y, parameters, lambd):
"""
compute costs with L2 regularization, uses the original cost function.
@param al: results AL, numpy arrays
@param y: actual results y, numpy arrays
@param parameters: parameters got from forward propagation, dictionaries
@param lambd: lambda for regularization, floats
@return: cost, floats
"""
if isinstance(al, np.float) or isinstance(al, float) or isinstance(al, int):
al = np.array([[al]])
if isinstance(y, np.float) or isinstance(y, float) or isinstance(y, int):
y = np.array([[y]])
if not isinstance(al, np.ndarray) or not isinstance(y, np.ndarray) or not al.ndim > 1 or not y.ndim > 1:
LOGGER.info('Input is not an np.ndarray, adding default value...')
al = np.array([[0.5]])
y = np.array([[0.6]])
m = y.shape[1]
num_of_parameters = len(parameters) // 2
w_square_sum = 0
# adding up Ws
for i in range(num_of_parameters):
try:
w_square_sum += np.sum(np.square(parameters['W'+str(i+1)]))
except KeyError as ex:
LOGGER.info('Invalid parameter set')
raise ex
# compute regular costs
cross_entropy_cost = compute_cost(al, y)
# combine regular costs and regularization term
l2_regularization_cost = (lambd / (2 * m)) * w_square_sum
cost = cross_entropy_cost + l2_regularization_cost
return cost
"""
def initialize_parameters_deep_he(layer_dims):
initialization for deep learning with HE random algorithm to prevent fading & exploding gradients.
@param layer_dims: dimensions of layers, lists
@return: initialized parameters
np.random.seed(1)
parameters = {}
L = len(layer_dims) # number of layers in the network
for l in range(1, L):
# initialized W with random and HE term
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) * np.sqrt(2 / layer_dims[l - 1])
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
assert (parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1]))
assert (parameters['b' + str(l)].shape == (layer_dims[l], 1))
return parameters
"""
"""
def initialize_parameters_deep(layer_dims):
np.random.seed(1)
parameters = {}
L = len(layer_dims) # number of layers in the network
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1])
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
assert (parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1]))
assert (parameters['b' + str(l)].shape == (layer_dims[l], 1))
return parameters
"""
def l_model_forward(x, parameters):
"""
Forward propagation of deep learning.
@param x: input x, numpy arrays
@param parameters:
@return: output aL and caches for following calculations, numpy arrays and indexes
"""
caches = []
a = x
l_total = len(parameters) // 2 # number of layers in the neural network
# Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
for l in range(1, l_total):
a_prev = a
# use relu or leaky relu in hidden layers
# print(l)
# print(parameters['W' + str(l)])
a, cache = linear_activation_forward(
a_prev, parameters['W' + str(l)], parameters['b' + str(l)],
activation="leaky_relu") # was relu
caches.append(cache)
# Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
# output layer with sigmoid activation
al, cache = linear_activation_forward(
a, parameters['W' + str(l_total)], parameters['b' + str(l_total)], activation="sigmoid")
caches.append(cache)
# assert (aL.shape == (10, x.shape[1])) # shape[0] should be same with shape[0] of output layer
return al, caches
def l_model_backward_with_l2(al, y, caches, lambd):
"""
Backward propagation for deep learning with L2 regularization.
@param al: output AL, numpy arrays
@param y: actual answers y, numpy arrays
@param caches: caches from forward propagation, dictionaries
@param lambd: regularization parameter lambda, floats
@return: gradients for gradient decent, dictionaries
"""
grads = {}
l = len(caches) # the number of layers
y = y.reshape(al.shape) # after this line, Y is the same shape as AL
# Initializing the back propagation
dal = - (np.divide(y, al) - np.divide(1 - y, 1 - al))
# Lth layer Inputs: "AL, Y, caches". Outputs: "grads["dAL"], grads["dWL"], grads["dbL"]
current_cache = caches[l - 1]
grads["dA" + str(l - 1)], grads["dW" + str(l)], grads["db" + str(l)] = \
linear_activation_backward_with_l2(
dal, current_cache, lambd, activation="sigmoid")
for l in reversed(range(l - 1)):
# lth layer: (RELU -> LINEAR) gradients.
current_cache = caches[l]
# use relu or leaky relu for hidden layers
da_prev_temp, dw_temp, db_temp = \
linear_activation_backward_with_l2(
grads["dA" + str(l + 1)], current_cache, lambd, activation="leaky_relu")
grads["dA" + str(l)] = da_prev_temp
grads["dW" + str(l + 1)] = dw_temp
grads["db" + str(l + 1)] = db_temp
return grads
def linear_activation_backward_with_l2(da, cache, lambd, activation):
"""
activation step for backward propagation with multiple choices of activation function.
@param da: dA from last step of backward propagation, numpy arrays
@param cache: caches in deep learning, dictionaries
@param lambd: regularization parameter lambda, floats
@param activation: choice of activation, strings
@return: last dA, dW, db, numpy arrays
"""
linear_cache, activation_cache = cache
# if activation == "relu":
# dZ = relu_backward(da, activation_cache)
# dA_prev, dW, db = linear_backward_with_l2(dZ, linear_cache, lambd)
if activation == "sigmoid":
dZ = sigmoid_backward(da, activation_cache)
dA_prev, dW, db = linear_backward_with_l2(dZ, linear_cache, lambd)
elif activation == "leaky_relu":
dZ = leaky_relu_backward(da, activation_cache)
dA_prev, dW, db = linear_backward_with_l2(dZ, linear_cache, lambd)
return dA_prev, dW, db
def linear_activation_forward(a_prev, w, b, activation):
"""
activation step for forward propagation with multiple choices of activation function.
@param a_prev: previous A from last step of forward propagation, numpy arrays
@param w: parameter W in current layer, numpy arrays
@param b: parameter b in current layer, numpy arrays
@param activation: choice of activation, strings
@return: current A and cache for following calculation
"""
if activation == "sigmoid":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
z, linear_cache = linear_forward(a_prev, w, b)
a, activation_cache = sigmoid(z)
# elif activation == "relu":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
# z, linear_cache = linear_forward(a_prev, w, b)
# a, activation_cache = relu(z)
elif activation == "leaky_relu":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
z, linear_cache = linear_forward(a_prev, w, b)
a, activation_cache = leaky_relu(z)
assert (a.shape == (w.shape[0], a_prev.shape[1]))
cache = (linear_cache, activation_cache)
return a, cache
def linear_backward_with_l2(dz, cache, lambd):
"""
linear step in backward propagation.
@param dz: current dZ, numpy arrays
@param cache: caches from previous calculation, dictionaries
@param lambd: regularization parameter lambda, floats
@return: previous dA, current dW, db, numpy arrays
"""
a_prev, w, b = cache
m = a_prev.shape[1]
dW = 1. / m * np.dot(dz, a_prev.T) + (lambd / m) * w
db = 1. / m * np.sum(dz, axis=1, keepdims=True)
dA_prev = np.dot(w.T, dz)
# dA_prev = dropouts_backward(dA_prev, D, keep_prob)
assert (dA_prev.shape == a_prev.shape)
assert (dW.shape == w.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
def linear_forward(a, w, b):
"""
linear step for forward propagation
@param a: current A, numpy arrays
@param w: current parameter W, numpy arrays
@param b: current parameter b, numpy arrays
@return: current z, and caches for following calculations, numpy arrays and dictionaries
"""
# print(a.shape, w.shape, b.shape)
z = w.dot(a) + b
assert (z.shape == (w.shape[0], a.shape[1]))
cache = (a, w, b)
return z, cache
def one_vs_all_prediction(prob_matrix):
"""
Compare every probability, get the maximum and output the index.
@param prob_matrix: probability matrix, numpy arrays
@return: prediction generated from probability matrix, numpy arrays
"""
m = prob_matrix.shape[1]
prediction = np.argmax(prob_matrix, axis=0)
prediction = np.array([prediction]) # keep dimensions
assert (prediction.shape == (1, m))
return prediction
def relu(z):
"""
relu function
@param z: input A, numpy arrays or numbers
@return: output A, numpy arrays or numbers
"""
if isinstance(z, np.float) or isinstance(z, np.int64) or isinstance(z, float) or isinstance(z, int):
z = np.array([[z]])
a = np.maximum(0, z)
assert (a.shape == z.shape)
cache = z
return a, cache
def relu_backward(da, cache):
"""
compute gradient of relu function.
@param da: input dA, numpy arrays or numbers
@param cache: caches with Z, dictionaries
@return: result dZ, numpy arrays or numbers
"""
z = cache
dz = np.array(da, copy=True) # just converting dz to a correct object.
# When z <= 0s you should set dz to 0 as well.
dz[z <= 0] = 0
assert (dz.shape == z.shape)
return dz
def leaky_relu(z):
"""
leaky relu function
@param z: input Z, numpy arrays or numbers
@return: result A and caches for following calculation
"""
if isinstance(z, np.float) or isinstance(z, np.int64) or isinstance(z, float) or isinstance(z, int):
z = np.array([[z]])
a = np.maximum(0.01 * z, z)
assert (a.shape == z.shape)
cache = z
return a, cache
def leaky_relu_backward(da, cache):
"""
compute gradients of leaky relu function.
@param da: input dA, numpy arrays or numbers
@param cache: cache with Z, dictionaries
@return: result dZ, numpy arrays or numbers
"""
z = cache
dz = np.array(da, copy=True) # just converting dz to a correct object.
# When z < 0, you should set dz to 0.01 as well.
# temp = np.ones(Z.shape)
# temp[Z <= 0] = 0.01
# dZ = dZ*temp
# Z[Z > 0] = 1
# Z[Z != 1] = 0.01
# dZ = dZ*Z
temp = np.ones_like(z)
temp[z <= 0] = 0.01
dz = dz*temp
assert (dz.shape == z.shape)
return dz
def sigmoid(z):
"""
sigmoid function.
@param z: input Z, numpy arrays or numbers
@return: result A, caches for following calculations, numpy arrays or numbers, dictionaries
"""
a = 1 / (1 + np.exp(-z))
cache = z
return a, cache
def sigmoid_backward(da, cache):
"""
compute gradients of sigmoid function.
@param da: input dA, numpy arrays or numbers
@param cache: caches with Z, dictionaries
@return: result dZ, numpy arrays or numbers
"""
if isinstance(da, np.float) or isinstance(da, np.int64) or isinstance(da, float) or isinstance(da, int):
da = np.array([[da]])
if isinstance(cache, np.float) or isinstance(cache, np.int64) or isinstance(cache, float) or isinstance(cache, int):
cache = np.array([[cache]])
z = cache
s = 1 / (1 + np.exp(-z))
dz = da * s * (1 - s)
assert (dz.shape == z.shape)
return dz
"""
unused dropout functions
def dropouts_forward(A, activation_cache, keep_prob):
D = np.random.rand(A.shape[0], A.shape[1])
D = D < keep_prob
A = A * D
A = A / keep_prob
cache = (activation_cache, D)
return A, cache
def dropouts_backward(dA, D, keep_prob):
dA = dA*D
dA = dA/keep_prob
return dA
"""
"""
def update_parameters(parameters, grads, learning_rate):
#add """"""
update parameters with gradients.
@param parameters: input parameters, dictionaries
@param grads: gradients, dictionaries
@param learning_rate: hyper-parameter alpha for deep learning, floats
@return: updated parameters, dictionaries
L = len(parameters) // 2 # number of layers in the neural network
# Update rule for each parameter. Use a for loop.
for l in range(L):
parameters["W" + str(l + 1)] = parameters["W" + str(l + 1)] - learning_rate * grads["dW" + str(l + 1)]
parameters["b" + str(l + 1)] = parameters["b" + str(l + 1)] - learning_rate * grads["db" + str(l + 1)]
return parameters
"""
| [
"numpy.ones_like",
"numpy.log",
"numpy.argmax",
"numpy.squeeze",
"numpy.exp",
"numpy.array",
"numpy.dot",
"numpy.zeros",
"numpy.sum",
"ml.utils.logger.get_logger",
"numpy.maximum",
"numpy.divide"
] | [((155, 175), 'ml.utils.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (165, 175), False, 'from ml.utils.logger import get_logger\n'), ((625, 653), 'numpy.zeros', 'np.zeros', (['[num_of_fields, m]'], {}), '([num_of_fields, m])\n', (633, 653), True, 'import numpy as np\n'), ((1765, 1781), 'numpy.squeeze', 'np.squeeze', (['cost'], {}), '(cost)\n', (1775, 1781), True, 'import numpy as np\n'), ((9908, 9923), 'numpy.dot', 'np.dot', (['w.T', 'dz'], {}), '(w.T, dz)\n', (9914, 9923), True, 'import numpy as np\n'), ((10892, 10922), 'numpy.argmax', 'np.argmax', (['prob_matrix'], {'axis': '(0)'}), '(prob_matrix, axis=0)\n', (10901, 10922), True, 'import numpy as np\n'), ((10940, 10962), 'numpy.array', 'np.array', (['[prediction]'], {}), '([prediction])\n', (10948, 10962), True, 'import numpy as np\n'), ((11332, 11348), 'numpy.maximum', 'np.maximum', (['(0)', 'z'], {}), '(0, z)\n', (11342, 11348), True, 'import numpy as np\n'), ((11672, 11695), 'numpy.array', 'np.array', (['da'], {'copy': '(True)'}), '(da, copy=True)\n', (11680, 11695), True, 'import numpy as np\n'), ((12170, 12193), 'numpy.maximum', 'np.maximum', (['(0.01 * z)', 'z'], {}), '(0.01 * z, z)\n', (12180, 12193), True, 'import numpy as np\n'), ((12528, 12551), 'numpy.array', 'np.array', (['da'], {'copy': '(True)'}), '(da, copy=True)\n', (12536, 12551), True, 'import numpy as np\n'), ((12795, 12810), 'numpy.ones_like', 'np.ones_like', (['z'], {}), '(z)\n', (12807, 12810), True, 'import numpy as np\n'), ((532, 547), 'numpy.array', 'np.array', (['[[0]]'], {}), '([[0]])\n', (540, 547), True, 'import numpy as np\n'), ((1237, 1253), 'numpy.array', 'np.array', (['[[al]]'], {}), '([[al]])\n', (1245, 1253), True, 'import numpy as np\n'), ((1344, 1359), 'numpy.array', 'np.array', (['[[y]]'], {}), '([[y]])\n', (1352, 1359), True, 'import numpy as np\n'), ((1557, 1574), 'numpy.array', 'np.array', (['[[0.5]]'], {}), '([[0.5]])\n', (1565, 1574), True, 'import numpy as np\n'), ((1587, 1604), 'numpy.array', 'np.array', (['[[0.6]]'], {}), '([[0.6]])\n', (1595, 1604), True, 'import numpy as np\n'), ((2325, 2341), 'numpy.array', 'np.array', (['[[al]]'], {}), '([[al]])\n', (2333, 2341), True, 'import numpy as np\n'), ((2432, 2447), 'numpy.array', 'np.array', (['[[y]]'], {}), '([[y]])\n', (2440, 2447), True, 'import numpy as np\n'), ((2645, 2662), 'numpy.array', 'np.array', (['[[0.5]]'], {}), '([[0.5]])\n', (2653, 2662), True, 'import numpy as np\n'), ((2675, 2692), 'numpy.array', 'np.array', (['[[0.6]]'], {}), '([[0.6]])\n', (2683, 2692), True, 'import numpy as np\n'), ((9860, 9893), 'numpy.sum', 'np.sum', (['dz'], {'axis': '(1)', 'keepdims': '(True)'}), '(dz, axis=1, keepdims=True)\n', (9866, 9893), True, 'import numpy as np\n'), ((11307, 11322), 'numpy.array', 'np.array', (['[[z]]'], {}), '([[z]])\n', (11315, 11322), True, 'import numpy as np\n'), ((12145, 12160), 'numpy.array', 'np.array', (['[[z]]'], {}), '([[z]])\n', (12153, 12160), True, 'import numpy as np\n'), ((13526, 13542), 'numpy.array', 'np.array', (['[[da]]'], {}), '([[da]])\n', (13534, 13542), True, 'import numpy as np\n'), ((13681, 13700), 'numpy.array', 'np.array', (['[[cache]]'], {}), '([[cache]])\n', (13689, 13700), True, 'import numpy as np\n'), ((6361, 6377), 'numpy.divide', 'np.divide', (['y', 'al'], {}), '(y, al)\n', (6370, 6377), True, 'import numpy as np\n'), ((6380, 6404), 'numpy.divide', 'np.divide', (['(1 - y)', '(1 - al)'], {}), '(1 - y, 1 - al)\n', (6389, 6404), True, 'import numpy as np\n'), ((9803, 9823), 'numpy.dot', 'np.dot', (['dz', 'a_prev.T'], {}), '(dz, a_prev.T)\n', (9809, 9823), True, 'import numpy as np\n'), ((13119, 13129), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (13125, 13129), True, 'import numpy as np\n'), ((13734, 13744), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (13740, 13744), True, 'import numpy as np\n'), ((1732, 1746), 'numpy.log', 'np.log', (['(1 - al)'], {}), '(1 - al)\n', (1738, 1746), True, 'import numpy as np\n'), ((1702, 1712), 'numpy.log', 'np.log', (['al'], {}), '(al)\n', (1708, 1712), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
def print_matrix(matrix):
pd.set_option('display.max_rows', len(matrix))
print()
print(matrix)
def normalize(matrix):
return matrix.div(matrix.sum(axis=1), axis=0)
def generate_matrix(data):
key_set = set(data.keys())
for edges in data.values():
keys = edges.keys()
key_set.update(keys)
all_keys = sorted(list(key_set))
for key in all_keys:
if key not in data:
data[key] = {key: 1}
matrix_list = []
for key in all_keys:
edges = data[key]
row = []
# sum_of_row = sum(edges.values())
for key2 in all_keys:
# value = Fraction(edges.get(key2, 0), sum_of_row)
value = edges.get(key2, 0)
row.append(value)
matrix_list.append(row)
matrix = pd.DataFrame(
data=matrix_list,
index=all_keys,
columns=all_keys,
)
result = normalize(matrix).astype('float')
return result
def find_absorbing_rows(matrix):
result = []
for index, row in enumerate(matrix.iterrows()):
values = row[1].values
if values[index] == 1:
result.append(row[0])
return result
def sort_states(matrix):
all_states = list(matrix.index.values)
absorbing = find_absorbing_rows(matrix)
transition = [name for name in all_states if name not in absorbing]
return transition, absorbing
def sort_matrix(matrix):
# sort the matrix
transition, absorbing = sort_states(matrix)
sorted_states = transition + absorbing
sorted_matrix = matrix.reindex(index=sorted_states, columns=sorted_states)
return sorted_matrix
def decompose(matrix):
# sort the matrix
transition, absorbing = sort_states(matrix)
sorted_states = transition + absorbing
sorted_matrix = matrix.reindex(index=sorted_states, columns=sorted_states)
matrix_size = len(matrix)
t_size = len(transition)
q_matrix = sorted_matrix.iloc[0:t_size, 0:t_size]
r_matrix = sorted_matrix.iloc[0:t_size, t_size:matrix_size]
return q_matrix, r_matrix
# result = calculate_b(drunk_walk_example)
def get_steady_state(matrix):
q, r = decompose(matrix)
i = np.identity(len(q))
q = q.mul(-1)
q = q.add(i)
v = np.linalg.inv(q)
result = np.matmul(v, r)
return result
| [
"pandas.DataFrame",
"numpy.linalg.inv",
"numpy.matmul"
] | [((837, 901), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'matrix_list', 'index': 'all_keys', 'columns': 'all_keys'}), '(data=matrix_list, index=all_keys, columns=all_keys)\n', (849, 901), True, 'import pandas as pd\n'), ((2279, 2295), 'numpy.linalg.inv', 'np.linalg.inv', (['q'], {}), '(q)\n', (2292, 2295), True, 'import numpy as np\n'), ((2309, 2324), 'numpy.matmul', 'np.matmul', (['v', 'r'], {}), '(v, r)\n', (2318, 2324), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import itertools
import copy
import joblib
import numpy
import scipy.sparse
import segment
import collections
import skimage.io
import features
import color_space
def _calc_adjacency_matrix(label_img, n_region):
r = numpy.vstack([label_img[:, :-1].ravel(), label_img[:, 1:].ravel()])
b = numpy.vstack([label_img[:-1, :].ravel(), label_img[1:, :].ravel()])
t = numpy.hstack([r, b])
A = scipy.sparse.coo_matrix((numpy.ones(t.shape[1]), (t[0], t[1])), shape=(n_region, n_region), dtype=bool).todense().getA()
A = A | A.transpose()
for i in range(n_region):
A[i, i] = True
dic = {i : {i} ^ set(numpy.flatnonzero(A[i])) for i in range(n_region)}
Adjacency = collections.namedtuple('Adjacency', ['matrix', 'dictionary'])
return Adjacency(matrix = A, dictionary = dic)
def _new_adjacency_dict(A, i, j, t):
Ak = copy.deepcopy(A)
Ak[t] = (Ak[i] | Ak[j]) - {i, j}
del Ak[i], Ak[j]
for (p, Q) in Ak.items():
if i in Q or j in Q:
Q -= {i, j}
Q.add(t)
return Ak
def _new_label_image(F, i, j, t):
Fk = numpy.copy(F)
Fk[Fk == i] = Fk[Fk == j] = t
return Fk
def _build_initial_similarity_set(A0, feature_extractor):
S = list()
for (i, J) in A0.items():
S += [(feature_extractor.similarity(i, j), (i, j)) for j in J if i < j]
return sorted(S)
def _merge_similarity_set(feature_extractor, Ak, S, i, j, t):
# remove entries which have i or j
S = list(filter(lambda x: not(i in x[1] or j in x[1]), S))
# calculate similarity between region t and its adjacencies
St = [(feature_extractor.similarity(t, x), (t, x)) for x in Ak[t] if t < x] +\
[(feature_extractor.similarity(x, t), (x, t)) for x in Ak[t] if x < t]
return sorted(S + St)
def hierarchical_segmentation(I, k = 100, feature_mask = features.SimilarityMask(1, 1, 1, 1)):
F0, n_region = segment.segment_label(I, 0.8, k, 100)
adj_mat, A0 = _calc_adjacency_matrix(F0, n_region)
feature_extractor = features.Features(I, F0, n_region)
# stores list of regions sorted by their similarity
S = _build_initial_similarity_set(A0, feature_extractor)
# stores region label and its parent (empty if initial).
R = {i : () for i in range(n_region)}
A = [A0] # stores adjacency relation for each step
F = [F0] # stores label image for each step
# greedy hierarchical grouping loop
while len(S):
(s, (i, j)) = S.pop()
t = feature_extractor.merge(i, j)
# record merged region (larger region should come first)
R[t] = (i, j) if feature_extractor.size[j] < feature_extractor.size[i] else (j, i)
Ak = _new_adjacency_dict(A[-1], i, j, t)
A.append(Ak)
S = _merge_similarity_set(feature_extractor, Ak, S, i, j, t)
F.append(_new_label_image(F[-1], i, j, t))
# bounding boxes for each hierarchy
L = feature_extractor.bbox
return (R, F, L)
def _generate_regions(R, L):
n_ini = sum(not parent for parent in R.values())
n_all = len(R)
regions = list()
for label in R.keys():
i = min(n_all - n_ini + 1, n_all - label)
vi = numpy.random.rand() * i
regions.append((vi, L[i]))
return sorted(regions)
def _selective_search_one(I, color, k, mask):
I_color = color_space.convert_color(I, color)
(R, F, L) = hierarchical_segmentation(I_color, k, mask)
return _generate_regions(R, L)
def selective_search(I, color_spaces = ['rgb'], ks = [100], feature_masks = [features.SimilarityMask(1, 1, 1, 1)], n_jobs = -1):
parameters = itertools.product(color_spaces, ks, feature_masks)
region_set = joblib.Parallel(n_jobs = n_jobs)(joblib.delayed(_selective_search_one)(I, color, k, mask) for (color, k, mask) in parameters)
#flatten list of list of tuple to list of tuple
regions = sum(region_set, [])
return sorted(regions)
| [
"numpy.copy",
"collections.namedtuple",
"numpy.random.rand",
"numpy.ones",
"numpy.hstack",
"segment.segment_label",
"itertools.product",
"numpy.flatnonzero",
"features.SimilarityMask",
"joblib.Parallel",
"copy.deepcopy",
"joblib.delayed",
"features.Features",
"color_space.convert_color"
] | [((436, 456), 'numpy.hstack', 'numpy.hstack', (['[r, b]'], {}), '([r, b])\n', (448, 456), False, 'import numpy\n'), ((760, 821), 'collections.namedtuple', 'collections.namedtuple', (['"""Adjacency"""', "['matrix', 'dictionary']"], {}), "('Adjacency', ['matrix', 'dictionary'])\n", (782, 821), False, 'import collections\n'), ((920, 936), 'copy.deepcopy', 'copy.deepcopy', (['A'], {}), '(A)\n', (933, 936), False, 'import copy\n'), ((1158, 1171), 'numpy.copy', 'numpy.copy', (['F'], {}), '(F)\n', (1168, 1171), False, 'import numpy\n'), ((1904, 1939), 'features.SimilarityMask', 'features.SimilarityMask', (['(1)', '(1)', '(1)', '(1)'], {}), '(1, 1, 1, 1)\n', (1927, 1939), False, 'import features\n'), ((1961, 1998), 'segment.segment_label', 'segment.segment_label', (['I', '(0.8)', 'k', '(100)'], {}), '(I, 0.8, k, 100)\n', (1982, 1998), False, 'import segment\n'), ((2078, 2112), 'features.Features', 'features.Features', (['I', 'F0', 'n_region'], {}), '(I, F0, n_region)\n', (2095, 2112), False, 'import features\n'), ((3382, 3417), 'color_space.convert_color', 'color_space.convert_color', (['I', 'color'], {}), '(I, color)\n', (3407, 3417), False, 'import color_space\n'), ((3660, 3710), 'itertools.product', 'itertools.product', (['color_spaces', 'ks', 'feature_masks'], {}), '(color_spaces, ks, feature_masks)\n', (3677, 3710), False, 'import itertools\n'), ((3591, 3626), 'features.SimilarityMask', 'features.SimilarityMask', (['(1)', '(1)', '(1)', '(1)'], {}), '(1, 1, 1, 1)\n', (3614, 3626), False, 'import features\n'), ((3728, 3758), 'joblib.Parallel', 'joblib.Parallel', ([], {'n_jobs': 'n_jobs'}), '(n_jobs=n_jobs)\n', (3743, 3758), False, 'import joblib\n'), ((3234, 3253), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (3251, 3253), False, 'import numpy\n'), ((692, 715), 'numpy.flatnonzero', 'numpy.flatnonzero', (['A[i]'], {}), '(A[i])\n', (709, 715), False, 'import numpy\n'), ((3761, 3798), 'joblib.delayed', 'joblib.delayed', (['_selective_search_one'], {}), '(_selective_search_one)\n', (3775, 3798), False, 'import joblib\n'), ((490, 512), 'numpy.ones', 'numpy.ones', (['t.shape[1]'], {}), '(t.shape[1])\n', (500, 512), False, 'import numpy\n')] |
from keras.layers import Dense
from keras.layers import Reshape, Conv2D, MaxPooling2D, UpSampling2D, Flatten
from keras.models import Sequential
from keras.datasets import mnist
import numpy as np
from dehydrated_vae import build_vae
#preprocess mnist dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
#create encoder and decoder
#NOTE: the encoder does not contain the latent mean/stddev layers
latent_size = 2
acti = "tanh"
encoder = Sequential([
Dense(256, input_shape=[28 * 28], activation=acti),
Dense(128, activation=acti)
])
decoder = Sequential([
Dense(256, input_shape=[latent_size]),
Dense(128, activation=acti),
Dense(28 * 28, activation="sigmoid")
])
#create the VAE
#the encoder will be wrapped in a new model containing the latent mean layer
vae, encoder, decoder, loss = \
build_vae(encoder, decoder, latent_size, kl_scale=1/np.prod(x_train.shape[1:]))
vae.compile(optimizer="adam", loss=loss)
vae.summary()
vae.fit(x_train, x_train, epochs=10)
#####
import matplotlib.pyplot as plt
n = 20
digit_size = 28
figure = np.zeros((digit_size * n, digit_size * n))
xyrange = 1
grid_x = np.linspace(-xyrange, xyrange, n)
grid_y = np.linspace(-xyrange, xyrange, n)
for i, yi in enumerate(grid_x):
for j, xi in enumerate(grid_y):
z_sample = np.array([[xi, yi]])
x_decoded = decoder.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size)
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size] = digit
plt.figure(figsize=(10, 10))
plt.imshow(figure)
plt.show()
#####
y_map = encoder.predict(x_test)
plt.figure(figsize=(10, 10))
plt.scatter(y_map[:, 0], y_map[:, 1], c=y_test, cmap="jet", edgecolors="k")
plt.colorbar()
plt.show()
| [
"matplotlib.pyplot.imshow",
"numpy.prod",
"keras.datasets.mnist.load_data",
"matplotlib.pyplot.colorbar",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.scatter",
"keras.layers.Dense",
"matplotlib.pyplot.show"
] | [((301, 318), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (316, 318), False, 'from keras.datasets import mnist\n'), ((1288, 1330), 'numpy.zeros', 'np.zeros', (['(digit_size * n, digit_size * n)'], {}), '((digit_size * n, digit_size * n))\n', (1296, 1330), True, 'import numpy as np\n'), ((1352, 1385), 'numpy.linspace', 'np.linspace', (['(-xyrange)', 'xyrange', 'n'], {}), '(-xyrange, xyrange, n)\n', (1363, 1385), True, 'import numpy as np\n'), ((1395, 1428), 'numpy.linspace', 'np.linspace', (['(-xyrange)', 'xyrange', 'n'], {}), '(-xyrange, xyrange, n)\n', (1406, 1428), True, 'import numpy as np\n'), ((1760, 1788), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (1770, 1788), True, 'import matplotlib.pyplot as plt\n'), ((1789, 1807), 'matplotlib.pyplot.imshow', 'plt.imshow', (['figure'], {}), '(figure)\n', (1799, 1807), True, 'import matplotlib.pyplot as plt\n'), ((1808, 1818), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1816, 1818), True, 'import matplotlib.pyplot as plt\n'), ((1859, 1887), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (1869, 1887), True, 'import matplotlib.pyplot as plt\n'), ((1888, 1963), 'matplotlib.pyplot.scatter', 'plt.scatter', (['y_map[:, 0]', 'y_map[:, 1]'], {'c': 'y_test', 'cmap': '"""jet"""', 'edgecolors': '"""k"""'}), "(y_map[:, 0], y_map[:, 1], c=y_test, cmap='jet', edgecolors='k')\n", (1899, 1963), True, 'import matplotlib.pyplot as plt\n'), ((1964, 1978), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1976, 1978), True, 'import matplotlib.pyplot as plt\n'), ((1979, 1989), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1987, 1989), True, 'import matplotlib.pyplot as plt\n'), ((444, 470), 'numpy.prod', 'np.prod', (['x_train.shape[1:]'], {}), '(x_train.shape[1:])\n', (451, 470), True, 'import numpy as np\n'), ((511, 536), 'numpy.prod', 'np.prod', (['x_test.shape[1:]'], {}), '(x_test.shape[1:])\n', (518, 536), True, 'import numpy as np\n'), ((689, 739), 'keras.layers.Dense', 'Dense', (['(256)'], {'input_shape': '[28 * 28]', 'activation': 'acti'}), '(256, input_shape=[28 * 28], activation=acti)\n', (694, 739), False, 'from keras.layers import Dense\n'), ((743, 770), 'keras.layers.Dense', 'Dense', (['(128)'], {'activation': 'acti'}), '(128, activation=acti)\n', (748, 770), False, 'from keras.layers import Dense\n'), ((800, 837), 'keras.layers.Dense', 'Dense', (['(256)'], {'input_shape': '[latent_size]'}), '(256, input_shape=[latent_size])\n', (805, 837), False, 'from keras.layers import Dense\n'), ((841, 868), 'keras.layers.Dense', 'Dense', (['(128)'], {'activation': 'acti'}), '(128, activation=acti)\n', (846, 868), False, 'from keras.layers import Dense\n'), ((872, 908), 'keras.layers.Dense', 'Dense', (['(28 * 28)'], {'activation': '"""sigmoid"""'}), "(28 * 28, activation='sigmoid')\n", (877, 908), False, 'from keras.layers import Dense\n'), ((1517, 1537), 'numpy.array', 'np.array', (['[[xi, yi]]'], {}), '([[xi, yi]])\n', (1525, 1537), True, 'import numpy as np\n'), ((1092, 1118), 'numpy.prod', 'np.prod', (['x_train.shape[1:]'], {}), '(x_train.shape[1:])\n', (1099, 1118), True, 'import numpy as np\n')] |
"""
Cat isolater
Uses Mask R-CNN to isolate (perform image segmentation) on images to identify cats present in the image
Note: This turns out to be rather slow, like 5 seconds per frame on my (admittedly older) MacBook Pro.
Usage:
from cat_isolator import CatIsolater
cat_isolator = CatIsolater(model_path="mask-rcnn-coco", confidence=0.75, threshold=0.3)
image = cv2.imread("your_picture.jpg")
cats = cat_isolator.look_for_cat(image, debug=True)
if len(cats) > 0:
print("Found {} cats".format(len(cats)))
for cat in cats:
# show the cats
cv2.imshow("Extracted_Region", cat.extracted_region)
cv2.waitKey(0)
"""
import cv2
import numpy as np
import os
import time
class CatIsolater:
def __init__(self, model_path="coco", confidence=0.75, threshold=0.3):
# derive the paths to the Mask R-CNN weights and model configuration
weightsPath = os.path.join(model_path, "frozen_inference_graph.pb")
configPath = os.path.join(model_path, "mask_rcnn_inception_v2_coco_2018_01_28.pbtxt")
labelsPath = os.path.join(model_path, "object_detection_classes_coco.txt")
self.net = cv2.dnn.readNetFromTensorflow(weightsPath, configPath)
self.confidence = confidence
self.threshold = threshold
self.labels = open(labelsPath).read().strip().split("\n")
def look_for_cat(self, image, debug=False):
H, W = image.shape[:2]
blob = cv2.dnn.blobFromImage(image, swapRB=True, crop=False)
self.net.setInput(blob)
start = time.time()
boxes, masks = self.net.forward(["detection_out_final", "detection_masks"])
end = time.time()
if debug:
# print timing information and volume information on Mask R-CNN
print("[INFO] Mask R-CNN took {:.6f} seconds".format(end - start))
print("[INFO] boxes shape: {}".format(boxes.shape))
print("[INFO] masks shape: {}".format(masks.shape))
# loop over the number of detected objects
cats = []
for i in range(0, boxes.shape[2]):
# extract the class ID of the detection along with the confidence
# (i.e., probability) associated with the prediction
classID = int(boxes[0, 0, i, 1])
confidence = boxes[0, 0, i, 2]
text = "{}: {:.4f}".format(self.labels[classID], confidence)
if debug:
print(text)
if self.labels[classID] != "cat" or confidence < self.confidence:
# we care only about cats, so skip anything else
continue
# scale the bounding box coordinates back relative to the
# size of the image and then compute the width and the height
# of the bounding box
box = boxes[0, 0, i, 3:7] * np.array([W, H, W, H])
(startX, startY, endX, endY) = box.astype("int")
boxW = endX - startX
boxH = endY - startY
# extract the pixel-wise segmentation for the object, resize
# the mask such that it's the same dimensions of the bounding
# box, and then finally threshold to create a *binary* mask
mask = masks[i, classID]
mask = cv2.resize(mask, (boxW, boxH),
interpolation=cv2.INTER_NEAREST)
mask = (mask > self.threshold)
roi = image[startY:endY, startX:endX]
visMask = (mask * 255).astype("uint8")
extracted_region = cv2.bitwise_and(roi, roi, mask=visMask)
detection_response = DetectionResponse(text=text,
confidence=confidence,
extracted_region=extracted_region)
cats.append(detection_response)
return cats
class DetectionResponse:
"""
Simple object representing a detected object
"""
def __init__(self, text="", confidence=0.0, extracted_region=None):
self.text = text
self.confidence = confidence
self.extracted_region = extracted_region
| [
"cv2.dnn.blobFromImage",
"cv2.dnn.readNetFromTensorflow",
"os.path.join",
"cv2.bitwise_and",
"numpy.array",
"cv2.resize",
"time.time"
] | [((894, 947), 'os.path.join', 'os.path.join', (['model_path', '"""frozen_inference_graph.pb"""'], {}), "(model_path, 'frozen_inference_graph.pb')\n", (906, 947), False, 'import os\n'), ((969, 1041), 'os.path.join', 'os.path.join', (['model_path', '"""mask_rcnn_inception_v2_coco_2018_01_28.pbtxt"""'], {}), "(model_path, 'mask_rcnn_inception_v2_coco_2018_01_28.pbtxt')\n", (981, 1041), False, 'import os\n'), ((1063, 1124), 'os.path.join', 'os.path.join', (['model_path', '"""object_detection_classes_coco.txt"""'], {}), "(model_path, 'object_detection_classes_coco.txt')\n", (1075, 1124), False, 'import os\n'), ((1144, 1198), 'cv2.dnn.readNetFromTensorflow', 'cv2.dnn.readNetFromTensorflow', (['weightsPath', 'configPath'], {}), '(weightsPath, configPath)\n', (1173, 1198), False, 'import cv2\n'), ((1432, 1485), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['image'], {'swapRB': '(True)', 'crop': '(False)'}), '(image, swapRB=True, crop=False)\n', (1453, 1485), False, 'import cv2\n'), ((1534, 1545), 'time.time', 'time.time', ([], {}), '()\n', (1543, 1545), False, 'import time\n'), ((1644, 1655), 'time.time', 'time.time', ([], {}), '()\n', (1653, 1655), False, 'import time\n'), ((3239, 3302), 'cv2.resize', 'cv2.resize', (['mask', '(boxW, boxH)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(mask, (boxW, boxH), interpolation=cv2.INTER_NEAREST)\n', (3249, 3302), False, 'import cv2\n'), ((3508, 3547), 'cv2.bitwise_and', 'cv2.bitwise_and', (['roi', 'roi'], {'mask': 'visMask'}), '(roi, roi, mask=visMask)\n', (3523, 3547), False, 'import cv2\n'), ((2813, 2835), 'numpy.array', 'np.array', (['[W, H, W, H]'], {}), '([W, H, W, H])\n', (2821, 2835), True, 'import numpy as np\n')] |
from numpy import divide
import numpy as np
def compare_resolution(image_a, image_b):
""" This is a check that can be used to prevent errors (image similarity algorithms require that
the input size is equal and also to maybe give information if the resolution is smaller or greater than expected
:returns a tuple of factors for the difference between width, height and the bands"""
# We need to pad the shape if the image has a different amount of bands
max_length = max(len(image_a.shape), len(image_b.shape))
min_length = min(len(image_a.shape), len(image_b.shape))
pad_length = max_length - min_length
# only pad the shorter one
if image_a.shape < image_b.shape:
image_a_shape = np.pad(image_a.shape, (0, pad_length), mode='constant')
image_b_shape = image_b.shape
else:
image_a_shape = image_a.shape
image_b_shape = np.pad(image_b.shape, (0, pad_length), mode='constant')
try:
factors = divide(image_a_shape, image_b_shape)
factors_list = [factor for factor in factors]
except ValueError:
factors_list = None
return {'resolution_factors': factors_list,
'desription': 'Image a is X times smaller/greater than image b'}
| [
"numpy.pad",
"numpy.divide"
] | [((729, 784), 'numpy.pad', 'np.pad', (['image_a.shape', '(0, pad_length)'], {'mode': '"""constant"""'}), "(image_a.shape, (0, pad_length), mode='constant')\n", (735, 784), True, 'import numpy as np\n'), ((895, 950), 'numpy.pad', 'np.pad', (['image_b.shape', '(0, pad_length)'], {'mode': '"""constant"""'}), "(image_b.shape, (0, pad_length), mode='constant')\n", (901, 950), True, 'import numpy as np\n'), ((979, 1015), 'numpy.divide', 'divide', (['image_a_shape', 'image_b_shape'], {}), '(image_a_shape, image_b_shape)\n', (985, 1015), False, 'from numpy import divide\n')] |
"""VARLiNGAM algorithm.
Author: <NAME>
.. MIT License
..
.. Copyright (c) 2019 <NAME>
..
.. Permission is hereby granted, free of charge, to any person obtaining a copy
.. of this software and associated documentation files (the "Software"), to deal
.. in the Software without restriction, including without limitation the rights
.. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
.. copies of the Software, and to permit persons to whom the Software is
.. furnished to do so, subject to the following conditions:
..
.. The above copyright notice and this permission notice shall be included in all
.. copies or substantial portions of the Software.
..
.. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
.. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
.. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
.. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
.. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
.. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
.. SOFTWARE.
"""
import numpy as np
import pandas as pd
import networkx as nx
from statsmodels.tsa.vector_ar.var_model import VAR
from ...causality.graph import LiNGAM
from ...causality.graph.model import GraphModel
from ...utils.Settings import SETTINGS
class VarLiNGAM(GraphModel):
""" Estimate a VAR-LiNGAM
Random generate matrix ids to set zeros.
Args:
lag (float): order to estimate the vector autoregressive model
verbose (bool): Verbosity of the class. Defaults to SETTINGS.verbose
.. note::
Ref: - <NAME>, <NAME>, <NAME> ((ICML-2008). Causal modelling
combining instantaneous and lagged effects: an identifiable model based
on non-Gaussianity;
- <NAME>, <NAME>, <NAME>, <NAME> (JMLR-2010). Estimation of
a Structural Vector Autoregression Model Using Non-Gaussianity;
"""
def __init__(self, lag=1, verbose=None):
self.lag = lag
self.verbose = SETTINGS.get_default(verbose=verbose)
def orient_undirected_graph(self, data, graph):
"""Run varLiNGAM on an undirected graph."""
# Building setup w/ arguments.
raise ValueError("VarLiNGAM cannot (yet) be ran with a skeleton/directed graph.")
def orient_directed_graph(self, data, graph):
"""Run varLiNGAM on a directed_graph."""
raise ValueError("VarLiNGAM cannot (yet) be ran with a skeleton/directed graph.")
def create_graph_from_data(self, data):
""" Run the VarLiNGAM algorithm on data.
Args:
data (pandas.DataFrame): time series data
Returns:
tuple :(networkx.Digraph, networkx.Digraph) Predictions given by
the varLiNGAM algorithm: Instantaneous and Lagged causal Graphs
"""
inst, lagged = self._run_varLiNGAM(data.values, verbose=self.verbose)
return (nx.relabel_nodes(nx.DiGraph(inst),
{idx: i for idx, i in enumerate(data.columns)}),
nx.relabel_nodes(nx.DiGraph(lagged),
{idx: i for idx, i in enumerate(data.columns)}),
)
def _run_varLiNGAM(self, xt, verbose=False):
""" Run the VarLiNGAM algorithm on data.
Args:
xt : time series matrix with size n*m (length*num_variables)
Returns:
Tuple: (Bo, Bhat) Instantaneous and lagged causal coefficients
"""
Ident = np.identity(xt.shape[1])
# Step 1: VAR estimation
model = VAR(xt)
results = model.fit(self.lag)
Mt_ = results.params[1:, :]
# Step 2: LiNGAM on Residuals
resid_VAR = results.resid
model = LiNGAM(verbose=verbose)
data = pd.DataFrame(resid_VAR)
Bo_ = model._run_LiNGAM(data)
# Step 3: Get instantaneous matrix Bo from LiNGAM
# Bo_ = pd.read_csv("results.csv").values
# Step 4: Calculation of lagged Bhat
Bhat_ = np.dot((Ident - Bo_), Mt_)
return (Bo_, Bhat_)
| [
"numpy.identity",
"networkx.DiGraph",
"numpy.dot",
"pandas.DataFrame",
"statsmodels.tsa.vector_ar.var_model.VAR"
] | [((3673, 3697), 'numpy.identity', 'np.identity', (['xt.shape[1]'], {}), '(xt.shape[1])\n', (3684, 3697), True, 'import numpy as np\n'), ((3751, 3758), 'statsmodels.tsa.vector_ar.var_model.VAR', 'VAR', (['xt'], {}), '(xt)\n', (3754, 3758), False, 'from statsmodels.tsa.vector_ar.var_model import VAR\n'), ((3968, 3991), 'pandas.DataFrame', 'pd.DataFrame', (['resid_VAR'], {}), '(resid_VAR)\n', (3980, 3991), True, 'import pandas as pd\n'), ((4208, 4232), 'numpy.dot', 'np.dot', (['(Ident - Bo_)', 'Mt_'], {}), '(Ident - Bo_, Mt_)\n', (4214, 4232), True, 'import numpy as np\n'), ((3095, 3111), 'networkx.DiGraph', 'nx.DiGraph', (['inst'], {}), '(inst)\n', (3105, 3111), True, 'import networkx as nx\n'), ((3230, 3248), 'networkx.DiGraph', 'nx.DiGraph', (['lagged'], {}), '(lagged)\n', (3240, 3248), True, 'import networkx as nx\n')] |
from math import floor
import numpy as np
import matplotlib.pyplot as plt
class BatchVisualization:
"""
Visualization methods for Sweep object.
"""
@staticmethod
def ordinal(n):
""" Returns ordinal representation of <n>. """
return "%d%s" % (n,"tsnrhtdd"[(floor(n/10)%10!=1)*(n%10<4)*n%10::4])
def plot_culture_grid(self, size=1, title=False, square=True, **kwargs):
"""
Plots grid of cell cultures.
Args:
size (int) - figure panel size
title (bool) - if True, add title
square (bool) - if True, truncate replicates to make a square grid
Returns:
fig (matplotlib.figures.Figure)
"""
# determine figure shape
ncols = int(np.floor(np.sqrt(self.size)))
if square:
nrows = ncols
else:
nrows = self.size // ncols
if self.size % ncols != 0:
nrows += 1
npanels = nrows*ncols
# create figure
figsize = (ncols*size, nrows*size)
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
# plot replicates
for replicate_id in range(self.size):
if replicate_id >= npanels:
break
ax = axes.ravel()[replicate_id]
# load simulation
sim = self[replicate_id]
# plot culture
sim.plot(ax=ax, **kwargs)
# format axis
if title:
title = '{:s} replicate'.format(self.ordinal(replicate_id))
ax.set_title(title, fontsize=8)
for ax in axes.ravel():
ax.axis('off')
return fig
| [
"numpy.sqrt",
"matplotlib.pyplot.subplots",
"math.floor"
] | [((1088, 1143), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': 'nrows', 'ncols': 'ncols', 'figsize': 'figsize'}), '(nrows=nrows, ncols=ncols, figsize=figsize)\n', (1100, 1143), True, 'import matplotlib.pyplot as plt\n'), ((785, 803), 'numpy.sqrt', 'np.sqrt', (['self.size'], {}), '(self.size)\n', (792, 803), True, 'import numpy as np\n'), ((295, 308), 'math.floor', 'floor', (['(n / 10)'], {}), '(n / 10)\n', (300, 308), False, 'from math import floor\n')] |
#! /usr/bin/env python
#
# compare rotation curves; this assumes a directory populated by "mkgalmod"
#
import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
#
do_barolo = True
# # pick a table from what mkgalmod has made
table0 = 'run.rotmod'
table1 = 'run.rcmod'
table2 = 'run.rotcurtab'
table3 = 'run.rcslit'
table4 = 'run.rcring'
table5 = 'barolo_2dfit/_2dtrm.txt'
table6 = 'barolo_3dfit/ringlog1.txt'
table7 = 'run.rcshape'
(r0, v0) = np.loadtxt(table0).T
(rmod, vmod, zmod) = np.loadtxt(table1).T
(r1,vsys1,dvsys1,vrot1,dvrot1,pa1,dpa1,inc1,dinc1,xpos1,dxpos1,ypos1,dypos1,npt1,sigma1) = np.loadtxt(table2).T
(rslit,vslit,eslit) = np.loadtxt(table3).T
(rring,vring,ering) = np.loadtxt(table4).T
if do_barolo:
(r2p,r2,vsys2,vrot2,vexp2,pa2,inc2,xpos2,ypos2) = np.loadtxt(table5).T
(r3p,r3,vrot3,disp3,inc3,pa3,z03p,z03,e3,xpos3,ypos3,vsys3,vrad3) = np.loadtxt(table6).T
(rshape,vshape) = np.loadtxt(table7).T
fmod = interp1d(r0, v0, kind = 'cubic')
#plt.figure(1,figsize=(11, 8.5)) # landscape
plt.figure(1,figsize=(8.5,11)) # portrait
plt.subplot(2,1,1)
plt.plot(r0,v0, '-', c='black',label='model')
plt.plot(rshape,vshape,'--',c='black',label='shape')
plt.plot(rring,vring, '-o',c='red', label='rotcur')
plt.plot(rslit,vslit, '-o',c='green',label='slit')
if do_barolo:
plt.plot(r2,vrot2, '-o',c='blue',label='barolo_2dfit')
plt.plot(r3,vrot3, '-o',c='magenta',label='barolo_3dfit')
plt.xlim(0,800)
#plt.xlabel('Radius')
plt.ylabel('Velocity')
plt.grid()
plt.legend(loc='lower right',fontsize = 'small')
vmax = 10
plt.subplot(4,1,3)
plt.plot(rmod,vmod-fmod(rmod), '-', c='black',label='model')
plt.plot(rshape,vshape-fmod(rshape),'--',c='black',label='shape')
plt.plot(rring,vring-fmod(rring), '-o',c='red', label='rotcur')
plt.plot(rslit,vslit-fmod(rslit), '-o',c='green',label='slit')
if do_barolo:
plt.plot(r2,vrot2-fmod(r2), '-o',c='blue', label='barolo_2dfit')
plt.plot(r3,vrot3-fmod(r3), '-o',c='magenta',label='barolo_3dfit')
plt.xlim(0,800)
plt.ylim(-vmax,vmax)
#plt.xlabel('Radius')
plt.ylabel('Velocity difference')
plt.grid()
#plt.legend(fontsize = 'x-small')
vmax = 1
plt.subplot(4,1,4)
plt.plot(rmod,vmod-fmod(rmod), '-', c='black',label='model')
plt.plot(rshape,vshape-fmod(rshape),'--',c='black',label='shape')
plt.plot(rring,vring-fmod(rring), '-o',c='red', label='rotcur')
plt.plot(rslit,vslit-fmod(rslit), '-o',c='green',label='slit')
if do_barolo:
plt.plot(r2,vrot2-fmod(r2), '-o',c='blue', label='barolo_2dfit')
plt.plot(r3,vrot3-fmod(r3), '-o',c='magenta',label='barolo_3dfit')
plt.xlim(0,800)
plt.ylim(-vmax,vmax)
plt.xlabel('Radius')
plt.ylabel('Velocity difference')
plt.grid()
#plt.legend(fontsize = 'x-small')
#plt.tight_layout(h_pad=0, w_pad=0, pad=0)
plt.savefig('rotcmp1.pdf')
plt.show()
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"scipy.interpolate.interp1d",
"matplotlib.pyplot.figure",
"numpy.loadtxt",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.subplot",
"... | [((1001, 1031), 'scipy.interpolate.interp1d', 'interp1d', (['r0', 'v0'], {'kind': '"""cubic"""'}), "(r0, v0, kind='cubic')\n", (1009, 1031), False, 'from scipy.interpolate import interp1d\n'), ((1083, 1115), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(8.5, 11)'}), '(1, figsize=(8.5, 11))\n', (1093, 1115), True, 'import matplotlib.pyplot as plt\n'), ((1131, 1151), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (1142, 1151), True, 'import matplotlib.pyplot as plt\n'), ((1150, 1197), 'matplotlib.pyplot.plot', 'plt.plot', (['r0', 'v0', '"""-"""'], {'c': '"""black"""', 'label': '"""model"""'}), "(r0, v0, '-', c='black', label='model')\n", (1158, 1197), True, 'import matplotlib.pyplot as plt\n'), ((1203, 1259), 'matplotlib.pyplot.plot', 'plt.plot', (['rshape', 'vshape', '"""--"""'], {'c': '"""black"""', 'label': '"""shape"""'}), "(rshape, vshape, '--', c='black', label='shape')\n", (1211, 1259), True, 'import matplotlib.pyplot as plt\n'), ((1256, 1309), 'matplotlib.pyplot.plot', 'plt.plot', (['rring', 'vring', '"""-o"""'], {'c': '"""red"""', 'label': '"""rotcur"""'}), "(rring, vring, '-o', c='red', label='rotcur')\n", (1264, 1309), True, 'import matplotlib.pyplot as plt\n'), ((1310, 1363), 'matplotlib.pyplot.plot', 'plt.plot', (['rslit', 'vslit', '"""-o"""'], {'c': '"""green"""', 'label': '"""slit"""'}), "(rslit, vslit, '-o', c='green', label='slit')\n", (1318, 1363), True, 'import matplotlib.pyplot as plt\n'), ((1501, 1517), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(800)'], {}), '(0, 800)\n', (1509, 1517), True, 'import matplotlib.pyplot as plt\n'), ((1543, 1565), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Velocity"""'], {}), "('Velocity')\n", (1553, 1565), True, 'import matplotlib.pyplot as plt\n'), ((1566, 1576), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (1574, 1576), True, 'import matplotlib.pyplot as plt\n'), ((1577, 1624), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""', 'fontsize': '"""small"""'}), "(loc='lower right', fontsize='small')\n", (1587, 1624), True, 'import matplotlib.pyplot as plt\n'), ((1638, 1658), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(4)', '(1)', '(3)'], {}), '(4, 1, 3)\n', (1649, 1658), True, 'import matplotlib.pyplot as plt\n'), ((2085, 2101), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(800)'], {}), '(0, 800)\n', (2093, 2101), True, 'import matplotlib.pyplot as plt\n'), ((2101, 2122), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-vmax)', 'vmax'], {}), '(-vmax, vmax)\n', (2109, 2122), True, 'import matplotlib.pyplot as plt\n'), ((2144, 2177), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Velocity difference"""'], {}), "('Velocity difference')\n", (2154, 2177), True, 'import matplotlib.pyplot as plt\n'), ((2178, 2188), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2186, 2188), True, 'import matplotlib.pyplot as plt\n'), ((2234, 2254), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(4)', '(1)', '(4)'], {}), '(4, 1, 4)\n', (2245, 2254), True, 'import matplotlib.pyplot as plt\n'), ((2681, 2697), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(800)'], {}), '(0, 800)\n', (2689, 2697), True, 'import matplotlib.pyplot as plt\n'), ((2697, 2718), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-vmax)', 'vmax'], {}), '(-vmax, vmax)\n', (2705, 2718), True, 'import matplotlib.pyplot as plt\n'), ((2718, 2738), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Radius"""'], {}), "('Radius')\n", (2728, 2738), True, 'import matplotlib.pyplot as plt\n'), ((2739, 2772), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Velocity difference"""'], {}), "('Velocity difference')\n", (2749, 2772), True, 'import matplotlib.pyplot as plt\n'), ((2773, 2783), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2781, 2783), True, 'import matplotlib.pyplot as plt\n'), ((2865, 2891), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""rotcmp1.pdf"""'], {}), "('rotcmp1.pdf')\n", (2876, 2891), True, 'import matplotlib.pyplot as plt\n'), ((2892, 2902), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2900, 2902), True, 'import matplotlib.pyplot as plt\n'), ((511, 529), 'numpy.loadtxt', 'np.loadtxt', (['table0'], {}), '(table0)\n', (521, 529), True, 'import numpy as np\n'), ((553, 571), 'numpy.loadtxt', 'np.loadtxt', (['table1'], {}), '(table1)\n', (563, 571), True, 'import numpy as np\n'), ((665, 683), 'numpy.loadtxt', 'np.loadtxt', (['table2'], {}), '(table2)\n', (675, 683), True, 'import numpy as np\n'), ((708, 726), 'numpy.loadtxt', 'np.loadtxt', (['table3'], {}), '(table3)\n', (718, 726), True, 'import numpy as np\n'), ((751, 769), 'numpy.loadtxt', 'np.loadtxt', (['table4'], {}), '(table4)\n', (761, 769), True, 'import numpy as np\n'), ((972, 990), 'numpy.loadtxt', 'np.loadtxt', (['table7'], {}), '(table7)\n', (982, 990), True, 'import numpy as np\n'), ((1380, 1437), 'matplotlib.pyplot.plot', 'plt.plot', (['r2', 'vrot2', '"""-o"""'], {'c': '"""blue"""', 'label': '"""barolo_2dfit"""'}), "(r2, vrot2, '-o', c='blue', label='barolo_2dfit')\n", (1388, 1437), True, 'import matplotlib.pyplot as plt\n'), ((1441, 1501), 'matplotlib.pyplot.plot', 'plt.plot', (['r3', 'vrot3', '"""-o"""'], {'c': '"""magenta"""', 'label': '"""barolo_3dfit"""'}), "(r3, vrot3, '-o', c='magenta', label='barolo_3dfit')\n", (1449, 1501), True, 'import matplotlib.pyplot as plt\n'), ((840, 858), 'numpy.loadtxt', 'np.loadtxt', (['table5'], {}), '(table5)\n', (850, 858), True, 'import numpy as np\n'), ((933, 951), 'numpy.loadtxt', 'np.loadtxt', (['table6'], {}), '(table6)\n', (943, 951), True, 'import numpy as np\n')] |
import pandas as pd
import numpy as np
def cr_uplift(control, variant, round=None):
"""
Compute uplift
Parameters
----------
control : float
Proportion in control group
variant : float
Proportion in variant group
round
If int rounds the results to this number of decimals. Otherwise,
no rounding
Returns
-------
dict
holding `diff` for the signed difference between the proportions and
`upli` for the uplift in percentage
"""
abs_change = variant - control
pct_chnage = 100 * abs_change / control
if type(round) is int:
return {
"diff": np.round(abs_change, decimals=round),
'upli': np.round(pct_chnage, decimals=round)
}
else:
return {
"diff": abs_change,
"upli": pct_chnage
}
def generate_experiment(seed=42, N=10000, control_cr=None, variant_cr=None):
"""
Generate a single experiment
Parameters
----------
seed : int
Seed for random numbers generator
N : int
Number of observations in the experiment
control_cr : float
Probability of success for the control group in (0,1) interval
variant_cr : float
Probability of success for the control group in (0,1) interval
Returns
-------
pd.DataFrame
For example:
Converted Visited CR_pct
Control 594 2000 29.7
Variant 612 2000 30.6
"""
np.random.seed(seed)
control = np.random.choice([0, 1], p=[1-control_cr, control_cr], size=N)
variant = np.random.choice([0, 1], p=[1-variant_cr, variant_cr], size=N)
res = pd.DataFrame(
{
"Converted": [control.sum(), variant.sum()],
"Visited": [N, N]
}, index=['Control', 'Variant'])
res['CR_pct'] = 100 * res.Converted / res.Visited
return res
def manual_z_score(data):
p_c, p_v = data.Converted / data.Visited
c_t, v_t = data.Visited
p = (c_t * p_c + v_t * p_v) / (c_t + v_t)
z = (p_c - p_v) / np.sqrt((p * (1 - p)) / c_t + ((p * (1 - p)) / v_t))
return z
| [
"numpy.random.choice",
"numpy.sqrt",
"numpy.random.seed",
"numpy.round"
] | [((1537, 1557), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1551, 1557), True, 'import numpy as np\n'), ((1572, 1636), 'numpy.random.choice', 'np.random.choice', (['[0, 1]'], {'p': '[1 - control_cr, control_cr]', 'size': 'N'}), '([0, 1], p=[1 - control_cr, control_cr], size=N)\n', (1588, 1636), True, 'import numpy as np\n'), ((1649, 1713), 'numpy.random.choice', 'np.random.choice', (['[0, 1]'], {'p': '[1 - variant_cr, variant_cr]', 'size': 'N'}), '([0, 1], p=[1 - variant_cr, variant_cr], size=N)\n', (1665, 1713), True, 'import numpy as np\n'), ((2112, 2158), 'numpy.sqrt', 'np.sqrt', (['(p * (1 - p) / c_t + p * (1 - p) / v_t)'], {}), '(p * (1 - p) / c_t + p * (1 - p) / v_t)\n', (2119, 2158), True, 'import numpy as np\n'), ((667, 703), 'numpy.round', 'np.round', (['abs_change'], {'decimals': 'round'}), '(abs_change, decimals=round)\n', (675, 703), True, 'import numpy as np\n'), ((725, 761), 'numpy.round', 'np.round', (['pct_chnage'], {'decimals': 'round'}), '(pct_chnage, decimals=round)\n', (733, 761), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import numpy as np
import subprocess as sp
import argparse
def run_example(_exec):
"""
run_example
Args:
_exec - string, example executable (including relative path)
Returns:
bytestring, stdout from running provided example
"""
p = sp.Popen(_exec, stdout=sp.PIPE, stderr=sp.STDOUT)
return p.stdout.readlines()
if __name__ == "__main__":
"""
run example_robot1 and, if optional command line flag \"makeplot\" is set, plot the cartesian position
and it's error for the three filter strategies used in the example: Predict, EKF, UKF
"""
parser = argparse.ArgumentParser()
parser.add_argument("--makeplot", help="Set to visualize output.", action="store_true")
parser.add_argument("--path_to_exec", help="Path to executable, relative or absolute", default="../../build")
args = parser.parse_args()
# raise a generic RunTimeError if executable fails for any reason
try:
lines = run_example(args.path_to_exec + "/example_robot1")
except:
raise RuntimeError("Failed to run example_robot1")
# compile output into numpy array
data = None
for line in lines:
# convert to string
line_string = str(line.splitlines()[0], "utf-8")
line_data = np.array([float(s) for s in line_string.split(",")]).reshape((12, 1))
if data is None:
data = line_data
else:
data = np.hstack((data, line_data))
# plot the data only if flag is set
if args.makeplot:
errors = np.empty((3, data.shape[1]))
errors[0, :] = np.linalg.norm(data[:2, :] - data[3:5, :], axis=0)
errors[1, :] = np.linalg.norm(data[:2, :] - data[6:8, :], axis=0)
errors[2, :] = np.linalg.norm(data[:2, :] - data[9:11, :], axis=0)
f, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data[0, :], data[1, :], color="r", label="ground-truth")
ax1.plot(data[3, :], data[4, :], color="g", label="predict-only")
ax1.plot(data[6, :], data[7, :], color="b", label="ekf")
ax1.plot(data[9, :], data[10, :], color="k", label="ukf")
ax1.legend()
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax1.set_title("Cartesian Position")
ax2.plot(errors[0, :], color="g")
ax2.plot(errors[1, :], color="b")
ax2.plot(errors[2, :], color="k")
ax2.set_xlabel("Timestep")
ax2.set_ylabel("RMS Error")
ax2.set_title("RMS Error of Cartesian Position")
plt.gcf().canvas.set_window_title("Comparison of Different Filters")
plt.show()
| [
"argparse.ArgumentParser",
"numpy.hstack",
"subprocess.Popen",
"matplotlib.pyplot.gcf",
"numpy.empty",
"numpy.linalg.norm",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((322, 371), 'subprocess.Popen', 'sp.Popen', (['_exec'], {'stdout': 'sp.PIPE', 'stderr': 'sp.STDOUT'}), '(_exec, stdout=sp.PIPE, stderr=sp.STDOUT)\n', (330, 371), True, 'import subprocess as sp\n'), ((660, 685), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (683, 685), False, 'import argparse\n'), ((1594, 1622), 'numpy.empty', 'np.empty', (['(3, data.shape[1])'], {}), '((3, data.shape[1]))\n', (1602, 1622), True, 'import numpy as np\n'), ((1646, 1696), 'numpy.linalg.norm', 'np.linalg.norm', (['(data[:2, :] - data[3:5, :])'], {'axis': '(0)'}), '(data[:2, :] - data[3:5, :], axis=0)\n', (1660, 1696), True, 'import numpy as np\n'), ((1720, 1770), 'numpy.linalg.norm', 'np.linalg.norm', (['(data[:2, :] - data[6:8, :])'], {'axis': '(0)'}), '(data[:2, :] - data[6:8, :], axis=0)\n', (1734, 1770), True, 'import numpy as np\n'), ((1794, 1845), 'numpy.linalg.norm', 'np.linalg.norm', (['(data[:2, :] - data[9:11, :])'], {'axis': '(0)'}), '(data[:2, :] - data[9:11, :], axis=0)\n', (1808, 1845), True, 'import numpy as np\n'), ((1870, 1888), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {}), '(1, 2)\n', (1882, 1888), True, 'import matplotlib.pyplot as plt\n'), ((2628, 2638), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2636, 2638), True, 'import matplotlib.pyplot as plt\n'), ((1485, 1513), 'numpy.hstack', 'np.hstack', (['(data, line_data)'], {}), '((data, line_data))\n', (1494, 1513), True, 'import numpy as np\n'), ((2551, 2560), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (2558, 2560), True, 'import matplotlib.pyplot as plt\n')] |
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import collections
import numpy as np
class word2vec(torch.nn.Module):
def __init__(self, vocab_size, embedding_dim, negative_samples, ns, model_type):
super(word2vec, self).__init__()
self.ns = ns
self.negative_samples = negative_samples
self.row_idx = 0
self.col_idx = 0
self.batch_end = 0
self.embedding_dim = embedding_dim
self.vocab_size = vocab_size + 1
self.model_type = model_type
self.u_embeddings = torch.nn.Embedding(self.vocab_size, self.embedding_dim, sparse = True)
self.v_embeddings = torch.nn.Embedding(self.vocab_size, self.embedding_dim, sparse = True)
if torch.cuda.is_available():
self.u_embeddings = self.u_embeddings.cuda()
self.v_embeddings = self.v_embeddings.cuda()
#embedding init
initrange = 0.5 / self.embedding_dim
self.u_embeddings.weight.data.uniform_(-initrange, initrange)
self.v_embeddings.weight.data.uniform_(-0, 0)
def generate_batch(self, corpus, window_size):
row_idx = self.row_idx
col_idx = self.col_idx
context = collections.deque()
target = collections.deque()
i = 0
while row_idx < len(corpus.data):
data = corpus.data[row_idx]
target_ = data[col_idx]
sentence_length = len(data)
start_idx = col_idx - window_size
start_idx = 0 if start_idx < 0 else start_idx
end_idx = col_idx + 1 + window_size
end_idx = end_idx if end_idx < (sentence_length ) else sentence_length
if self.model_type == "skip-gram":
for t in range(start_idx, end_idx):
if t > sentence_length - 1:break
if t == col_idx:continue
context.append(data[t])
target.append(target_)
i += 1
else:
c = [data[x] for i, x in enumerate(range(start_idx, end_idx)) if x != col_idx]
if len(c) == (window_size * 2):
context.append(c)
target.append(target_)
i += 1
col_idx = (col_idx + 1)
if col_idx == len(data):
col_idx = 0
row_idx = row_idx + 1
if self.model_type == "skip-gram":
x = np.array(target)
y = np.array(context)
elif self.model_type == "cbow":
x = np.array(context)
y = np.array(target)
return x, y
def negative_sampling(self, corpus):
negative_samples = np.random.randint(low = 1, high = self.vocab_size, size = self.negative_samples)
#negative_samples = np.random.choice(corpus.negaive_sample_table_w, p = corpus.negaive_sample_table_p, size = self.negative_samples)
return negative_samples
def forward(self, batch, corpus = None):
if self.model_type == "skip-gram":
if self.ns == 0:
u_emb = self.u_embeddings(batch[0])
v_emb = self.v_embeddings(torch.LongTensor(range(self.vocab_size)))
z = torch.matmul(u_emb, torch.t(v_emb))
log_softmax = F.log_softmax(z, dim = 1)
loss = F.nll_loss(log_softmax, batch[1])
else:
#positive
u_emb = self.u_embeddings(batch[0])
v_emb = self.v_embeddings(batch[1])
score = torch.sum(torch.mul(u_emb, v_emb), dim = 1)#inner product
log_target = F.logsigmoid(score)
#negative
v_emb_negative = self.v_embeddings(batch[2])
neg_score = -1 * torch.sum(torch.mul(u_emb.view(batch[0].shape[0], 1, self.embedding_dim), v_emb_negative.view(batch[0].shape[0], batch[2].shape[1], self.embedding_dim)), dim = 2)
log_neg_sample = F.logsigmoid(neg_score)
loss = -1 * (log_target.sum() + log_neg_sample.sum())
elif self.model_type == "cbow":
if self.ns == 0:
u_emb = torch.mean(self.u_embeddings(batch[0]), dim = 1)
v_emb = self.v_embeddings(torch.LongTensor(range(self.vocab_size)))
z = torch.matmul(u_emb, torch.t(v_emb))
log_softmax = F.log_softmax(z, dim = 1)
loss = F.nll_loss(log_softmax, batch[1])
else:
#positive
u_emb = torch.mean(self.u_embeddings(batch[0]), dim = 1)
v_emb = self.v_embeddings(batch[1])
score = torch.sum(torch.mul(u_emb, v_emb), dim = 1)#inner product
log_target = F.logsigmoid(score)
#negative
v_emb_negative = self.v_embeddings(batch[2])
neg_score = -1 * torch.sum(torch.mul(u_emb.view(batch[0].shape[0], 1, self.embedding_dim), v_emb_negative.view(batch[0].shape[0], batch[2].shape[1], self.embedding_dim)), dim = 2)
log_neg_sample = F.logsigmoid(neg_score)
loss = -1 * (log_target.sum() + log_neg_sample.sum())
return loss
| [
"torch.mul",
"collections.deque",
"torch.nn.functional.nll_loss",
"numpy.array",
"numpy.random.randint",
"torch.cuda.is_available",
"torch.nn.functional.log_softmax",
"torch.nn.functional.logsigmoid",
"torch.t",
"torch.nn.Embedding"
] | [((584, 652), 'torch.nn.Embedding', 'torch.nn.Embedding', (['self.vocab_size', 'self.embedding_dim'], {'sparse': '(True)'}), '(self.vocab_size, self.embedding_dim, sparse=True)\n', (602, 652), False, 'import torch\n'), ((683, 751), 'torch.nn.Embedding', 'torch.nn.Embedding', (['self.vocab_size', 'self.embedding_dim'], {'sparse': '(True)'}), '(self.vocab_size, self.embedding_dim, sparse=True)\n', (701, 751), False, 'import torch\n'), ((765, 790), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (788, 790), False, 'import torch\n'), ((1232, 1251), 'collections.deque', 'collections.deque', ([], {}), '()\n', (1249, 1251), False, 'import collections\n'), ((1270, 1289), 'collections.deque', 'collections.deque', ([], {}), '()\n', (1287, 1289), False, 'import collections\n'), ((2761, 2835), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': 'self.vocab_size', 'size': 'self.negative_samples'}), '(low=1, high=self.vocab_size, size=self.negative_samples)\n', (2778, 2835), True, 'import numpy as np\n'), ((2514, 2530), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (2522, 2530), True, 'import numpy as np\n'), ((2547, 2564), 'numpy.array', 'np.array', (['context'], {}), '(context)\n', (2555, 2564), True, 'import numpy as np\n'), ((2621, 2638), 'numpy.array', 'np.array', (['context'], {}), '(context)\n', (2629, 2638), True, 'import numpy as np\n'), ((2655, 2671), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (2663, 2671), True, 'import numpy as np\n'), ((3379, 3402), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['z'], {'dim': '(1)'}), '(z, dim=1)\n', (3392, 3402), True, 'import torch.nn.functional as F\n'), ((3428, 3461), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['log_softmax', 'batch[1]'], {}), '(log_softmax, batch[1])\n', (3438, 3461), True, 'import torch.nn.functional as F\n'), ((3721, 3740), 'torch.nn.functional.logsigmoid', 'F.logsigmoid', (['score'], {}), '(score)\n', (3733, 3740), True, 'import torch.nn.functional as F\n'), ((4058, 4081), 'torch.nn.functional.logsigmoid', 'F.logsigmoid', (['neg_score'], {}), '(neg_score)\n', (4070, 4081), True, 'import torch.nn.functional as F\n'), ((3333, 3347), 'torch.t', 'torch.t', (['v_emb'], {}), '(v_emb)\n', (3340, 3347), False, 'import torch\n'), ((3644, 3667), 'torch.mul', 'torch.mul', (['u_emb', 'v_emb'], {}), '(u_emb, v_emb)\n', (3653, 3667), False, 'import torch\n'), ((4466, 4489), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['z'], {'dim': '(1)'}), '(z, dim=1)\n', (4479, 4489), True, 'import torch.nn.functional as F\n'), ((4515, 4548), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['log_softmax', 'batch[1]'], {}), '(log_softmax, batch[1])\n', (4525, 4548), True, 'import torch.nn.functional as F\n'), ((4830, 4849), 'torch.nn.functional.logsigmoid', 'F.logsigmoid', (['score'], {}), '(score)\n', (4842, 4849), True, 'import torch.nn.functional as F\n'), ((5167, 5190), 'torch.nn.functional.logsigmoid', 'F.logsigmoid', (['neg_score'], {}), '(neg_score)\n', (5179, 5190), True, 'import torch.nn.functional as F\n'), ((4419, 4433), 'torch.t', 'torch.t', (['v_emb'], {}), '(v_emb)\n', (4426, 4433), False, 'import torch\n'), ((4753, 4776), 'torch.mul', 'torch.mul', (['u_emb', 'v_emb'], {}), '(u_emb, v_emb)\n', (4762, 4776), False, 'import torch\n')] |
from fairnr.modules.brdf import Microfacet
import torch
import numpy as np
brdf = Microfacet()
N = 4
L = 1
np.random.seed(125)
pts2l = torch.Tensor(np.random.random((N, L, 3)))
pts2c = torch.Tensor(np.random.random((N, 3)))
normal = torch.Tensor(np.random.random((N, 3)))
albedo = torch.Tensor(np.random.random((N, 3)))
rough = torch.Tensor(np.random.random((N, 1)))
res = brdf(pts2l, pts2c, normal, albedo, rough)
print(res) | [
"numpy.random.random",
"fairnr.modules.brdf.Microfacet",
"numpy.random.seed"
] | [((83, 95), 'fairnr.modules.brdf.Microfacet', 'Microfacet', ([], {}), '()\n', (93, 95), False, 'from fairnr.modules.brdf import Microfacet\n'), ((110, 129), 'numpy.random.seed', 'np.random.seed', (['(125)'], {}), '(125)\n', (124, 129), True, 'import numpy as np\n'), ((152, 179), 'numpy.random.random', 'np.random.random', (['(N, L, 3)'], {}), '((N, L, 3))\n', (168, 179), True, 'import numpy as np\n'), ((202, 226), 'numpy.random.random', 'np.random.random', (['(N, 3)'], {}), '((N, 3))\n', (218, 226), True, 'import numpy as np\n'), ((250, 274), 'numpy.random.random', 'np.random.random', (['(N, 3)'], {}), '((N, 3))\n', (266, 274), True, 'import numpy as np\n'), ((298, 322), 'numpy.random.random', 'np.random.random', (['(N, 3)'], {}), '((N, 3))\n', (314, 322), True, 'import numpy as np\n'), ((345, 369), 'numpy.random.random', 'np.random.random', (['(N, 1)'], {}), '((N, 1))\n', (361, 369), True, 'import numpy as np\n')] |
# Copyright 2021 The Private Cardinality Estimation Framework 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.
"""Grid test point generator.
Generates an evenly spaced grid of test points.
"""
import itertools
import numpy as np
from typing import Iterable
from typing import List
from wfa_planning_evaluation_framework.data_generators.data_set import DataSet
from wfa_planning_evaluation_framework.driver.test_point_generator import (
TestPointGenerator,
)
class GridTestPointGenerator(TestPointGenerator):
"""Generates a collection of evenly spaced test points."""
def __init__(self, dataset: DataSet, rng: np.random.Generator, grid_size: int):
"""Returns a GridTestPointGenerator.
Args:
dataset: The DataSet for which test points are to be generated.
rng: A numpy Generator object that is used to seed the generation
of random test points.
grid_size: The number of points that should be generated along the
grid for each dimension. Thus, if grid_size is 5 and there are
three publishers, the total number of test points is 5**3 = 125.
"""
super().__init__(dataset)
self._rng = rng
self._grid_size = grid_size
def test_points(self) -> Iterable[List[float]]:
"""Returns a generator for generating a list of test points.
Returns:
An iterable of spend vectors representing locations where
the true reach surface is to be compared to the modeled reach
surface.
"""
points_per_dimension = []
for i in range(self._npublishers):
points_per_dimension.append(
list(
self._max_spends[i]
* np.arange(1, self._grid_size + 1)
/ (self._grid_size + 1)
)
)
for point in itertools.product(*points_per_dimension):
yield point
| [
"itertools.product",
"numpy.arange"
] | [((2397, 2437), 'itertools.product', 'itertools.product', (['*points_per_dimension'], {}), '(*points_per_dimension)\n', (2414, 2437), False, 'import itertools\n'), ((2266, 2299), 'numpy.arange', 'np.arange', (['(1)', '(self._grid_size + 1)'], {}), '(1, self._grid_size + 1)\n', (2275, 2299), True, 'import numpy as np\n')] |
from typing import List, Optional
from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException
from fastapi.security.api_key import APIKeyQuery, APIKey
from pydantic import BaseModel
from starlette.status import HTTP_403_FORBIDDEN
from skimage.metrics import structural_similarity as ssim
import cv2
import numpy as np
import requests as re
API_KEY = "6e8e8295-cfa1-4bb7-9ea6-c15df77e11e2"
API_KEY_NAME = 'access_token'
api_key_query = APIKeyQuery(name=API_KEY_NAME)
app = FastAPI()
# define function for retrieving API key from query parameter
async def get_api_key(api_key_query: str = Security(api_key_query)):
if api_key_query == API_KEY:
return api_key_query
else:
raise HTTPException(
status_cod=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
)
# pydantic offers BaseModel class for request body declaration/validation
class Urls(BaseModel):
img_url_1: Optional[str] = None
img_url_2: Optional[str] = None
@app.post("/image/files") # create route for receiving image files
async def image( # set params of UploadFile and APIKey for security
images: Optional[List[UploadFile]] = File(None),
api_key: APIKey = Depends(get_api_key)
):
if images:
img1, img2 = images # unpack both images
img1, img2 = await img1.read(), await img2.read() # read both images
img1_np, img2_np = convert_image(img1), convert_image(img2) # convert images in np arrays and grey images
similarity_percent = round(ssim(img1_np, img2_np) * 100) # calculate structural similarity index
else:
return { 'message': 'No images were received' }
return { 'similarity_percent': similarity_percent }
@app.post("/image/urls") # create route for receiving string urls
async def image_urls( # set params of Urls instance and APIKey for security
urls: Urls,
api_key: APIKey = Depends(get_api_key)
):
if urls.img_url_1 and urls.img_url_2:
img1, img2 = re.get(urls.img_url_1).content, re.get(urls.img_url_2).content # get request images from urls
img1_np, img2_np = convert_image(img1), convert_image(img2) # convert images in np arrays and grey images
similarity_percent = round(ssim(img1_np, img2_np) * 100) # calculate structural similarity index
else:
return { 'message': 'No images were received' }
return { 'similarity_percent': similarity_percent }
# This function is converting the bytes of our image
# into a workable numpy array as well as greying out the image
def convert_image(image):
nparr = np.frombuffer(image, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
return img_np
| [
"fastapi.Security",
"fastapi.FastAPI",
"skimage.metrics.structural_similarity",
"fastapi.HTTPException",
"requests.get",
"cv2.imdecode",
"fastapi.security.api_key.APIKeyQuery",
"numpy.frombuffer",
"fastapi.File",
"fastapi.Depends"
] | [((480, 510), 'fastapi.security.api_key.APIKeyQuery', 'APIKeyQuery', ([], {'name': 'API_KEY_NAME'}), '(name=API_KEY_NAME)\n', (491, 510), False, 'from fastapi.security.api_key import APIKeyQuery, APIKey\n'), ((520, 529), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (527, 529), False, 'from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException\n'), ((639, 662), 'fastapi.Security', 'Security', (['api_key_query'], {}), '(api_key_query)\n', (647, 662), False, 'from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException\n'), ((1183, 1193), 'fastapi.File', 'File', (['None'], {}), '(None)\n', (1187, 1193), False, 'from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException\n'), ((1216, 1236), 'fastapi.Depends', 'Depends', (['get_api_key'], {}), '(get_api_key)\n', (1223, 1236), False, 'from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException\n'), ((1873, 1893), 'fastapi.Depends', 'Depends', (['get_api_key'], {}), '(get_api_key)\n', (1880, 1893), False, 'from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException\n'), ((2527, 2557), 'numpy.frombuffer', 'np.frombuffer', (['image', 'np.uint8'], {}), '(image, np.uint8)\n', (2540, 2557), True, 'import numpy as np\n'), ((2569, 2610), 'cv2.imdecode', 'cv2.imdecode', (['nparr', 'cv2.IMREAD_GRAYSCALE'], {}), '(nparr, cv2.IMREAD_GRAYSCALE)\n', (2581, 2610), False, 'import cv2\n'), ((737, 827), 'fastapi.HTTPException', 'HTTPException', ([], {'status_cod': 'HTTP_403_FORBIDDEN', 'detail': '"""Could not validate credentials"""'}), "(status_cod=HTTP_403_FORBIDDEN, detail=\n 'Could not validate credentials')\n", (750, 827), False, 'from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException\n'), ((1510, 1532), 'skimage.metrics.structural_similarity', 'ssim', (['img1_np', 'img2_np'], {}), '(img1_np, img2_np)\n', (1514, 1532), True, 'from skimage.metrics import structural_similarity as ssim\n'), ((1954, 1976), 'requests.get', 're.get', (['urls.img_url_1'], {}), '(urls.img_url_1)\n', (1960, 1976), True, 'import requests as re\n'), ((1986, 2008), 'requests.get', 're.get', (['urls.img_url_2'], {}), '(urls.img_url_2)\n', (1992, 2008), True, 'import requests as re\n'), ((2187, 2209), 'skimage.metrics.structural_similarity', 'ssim', (['img1_np', 'img2_np'], {}), '(img1_np, img2_np)\n', (2191, 2209), True, 'from skimage.metrics import structural_similarity as ssim\n')] |
# For image output to bmp file
import numpy as np
import imageio
# For image operation
from library.image_tool_box import *
# For math/statistic operation
from library.math_tool_box import StatMaker
import math
### 1. Downlaod and unpack those 4 test data from MNIST database.
# train-images-idx3-ubyte.gz: training set images (9912422 bytes)
# train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
# t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
# t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
# MNIST database
# http://yann.lecun.com/exdb/mnist/
# This is is completed, and they're saved in sub-directory "./data_of_mAiLab003"
file_name_of_MNIST_image = 'train-images.idx3-ubyte'
file_name_of_MNIST_label = 'train-labels.idx1-ubyte'
data_directory_path = 'data_of_mAiLab003/'
path_of_MNIST_image = data_directory_path + file_name_of_MNIST_image
path_of_MNIST_label = data_directory_path + file_name_of_MNIST_label
with open(path_of_MNIST_image, 'rb') as file_handle:
# Read header of MNIST image file
header_return = get_MNIST_image_header(file_handle)
if -1 == header_return:
# Handle End-of-File, or exception
pass
else:
(img_height, img_width) = header_return
image_container = []
for index in range(10):
image_return = read_one_MNIST_image(file_handle, img_height, img_width)
if -2 == image_return:
# Handle exception
print("Error occurs in index {:0>2d}".format( index ) )
break
else:
image_matrix = image_return
# Push image_matrix into container
image_container.append(image_matrix)
average_image_of_first_ten = gen_average_image( image_container )
### 2. Output first image from test file, "train-images.idx3-ubyte", with image size 28 x 28.
# print_first image
print("First image array:")
print_image_array( image_container[0] )
### 3. Output the average image (with rounding down to nearest integer) of the first ten from test file
# , "train-images.idx3-ubyte", with image size 28 x 28.
# print average image of first ten
print("Average image array of first ten:")
print_image_array( average_image_of_first_ten )
### 4. Output the average label value (with rounding down to hundredths) of the first ten from test file
# , "train-labels.idx1-ubyte".
with open(path_of_MNIST_label, 'rb') as file_handle:
# Read header of MNIST label file
header_return = get_MNIST_label_header(file_handle)
if -1 == header_return:
# Handle End-of-File, or exception
pass
else:
number_of_items = header_return
# Read first 10 labels, then save them into label_series
label_series = list( file_handle.read(10) )
label_stat = StatMaker( label_series )
avg = label_stat.get_avg()
# rounding down to hundredths
avg = math.floor( (avg * 100) / 100 )
print("The average value of first ten labels in '{:<20}' is {:+02.2f}\n".format( str(file_name_of_MNIST_label), avg ) )
### 5. Extend and output first image to 32x32 from test file, with zero padding on boundary area.
new_side_length = 32
original_side_length = img_width
padding_size = (new_side_length - original_side_length)//2
print("First image array extneds to 32x32 with zero padding over boundary:")
print_image_array_with_padding( image_container[0], padding_size )
### 6. Output and save first image as BitMap(.bmp) file.
print("First image is saved into 'first_image.bmp'.")
# Convert python 2D array(list) to numpy array on datatype uint8.
# data type: np.uint8 = Unsigned 8 bit integer, from 0 to 255
first_image = np.array( object=image_container[0], dtype=np.uint8 )
# Save it from numpy array to bmp file
imageio.imwrite('first_image.bmp', first_image)
'''
Example output:
### 1. Downlaod and unpack those 4 test data from MNIST database.
# This is is completed, and they're saved in sub-directory "./data_of_mAiLab003"
### 2. Output first image from test file, "train-images.idx3-ubyte", with image size 28 x 28.
First image array:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 03 12 12 12 7E 88 AF 1A A6 FF F7 7F 00 00 00 00
00 00 00 00 00 00 00 00 1E 24 5E 9A AA FD FD FD FD FD E1 AC FD F2 C3 40 00 00 00 00
00 00 00 00 00 00 00 31 EE FD FD FD FD FD FD FD FD FB 5D 52 52 38 27 00 00 00 00 00
00 00 00 00 00 00 00 12 DB FD FD FD FD FD C6 B6 F7 F1 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 50 9C 6B FD FD CD 0B 00 2B 9A 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 0E 01 9A FD 5A 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 8B FD BE 02 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 0B BE FD 46 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 23 F1 E1 A0 6C 01 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 51 F0 FD FD 77 19 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 2D BA FD FD 96 1B 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 5D FC FD BB 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F9 FD F9 40 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 2E 82 B7 FD FD CF 02 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 27 94 E5 FD FD FD FA B6 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 18 72 DD FD FD FD FD C9 4E 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 17 42 D5 FD FD FD FD C6 51 02 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 12 AB DB FD FD FD FD C3 50 09 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 37 AC E2 FD FD FD FD F4 85 0B 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 88 FD FD FD D4 87 84 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
### 3. Output the average image (with rounding down to nearest integer) of the first ten from test file
# , "train-images.idx3-ubyte", with image size 28 x 28.
Average image array of first ten:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 0E 19 15 08 0F 19 0F 05 00 00 12 13 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 07 1C 2B 4D 3B 41 4A 5C 4D 42 45 35 1C 00 00 00 00
00 00 00 00 06 08 00 00 03 07 17 26 3B 6D 88 6A 64 6D 78 6B 6B 59 31 0F 00 00 00 00
00 00 00 00 0C 10 00 04 17 2B 32 37 5D A2 AC 8A 7B 73 65 79 80 5F 20 00 00 00 00 00
00 00 00 00 16 10 00 01 15 25 41 65 95 B7 A1 6D 5E 78 6E 7F 7D 50 0A 00 00 00 00 00
00 00 00 00 16 10 00 00 08 1A 31 68 95 A6 68 26 38 56 66 84 77 36 00 00 00 00 00 00
00 00 00 04 18 10 00 00 00 21 4A 5B 7D 78 3D 3B 39 44 62 74 6D 35 05 00 00 00 00 00
00 00 00 0C 19 10 00 00 11 2C 3F 46 4C 61 36 40 42 4E 65 6A 65 1E 10 00 00 00 00 00
00 00 00 0F 19 0C 00 0D 2B 31 2C 20 2D 50 58 5D 55 5E 68 62 49 1B 13 00 00 00 00 00
00 00 00 0F 19 06 01 1C 32 32 28 2C 25 6F 9B 90 7A 6A 64 41 25 19 13 00 00 00 00 00
00 00 00 0F 19 08 02 2D 40 4A 3A 4F 69 B1 C8 BC 9D 71 52 1C 1D 19 13 00 00 00 00 00
00 00 00 0F 19 17 1D 4D 65 72 7B 7D 95 B8 B3 BE 89 63 56 2E 19 19 0E 00 00 00 00 00
00 00 00 00 0B 11 22 4A 60 60 4B 39 3A 5D 7E 82 69 6E 7C 5A 22 13 01 00 00 00 00 00
00 00 00 00 00 00 1C 3C 39 19 16 17 1D 56 8A 7D 5A 6E 7A 60 36 19 06 04 04 00 00 00
00 00 00 00 00 00 21 35 26 0A 19 19 24 5D 84 76 49 66 67 3A 10 18 19 19 16 00 00 00
00 00 00 00 00 0A 22 39 20 01 20 2B 44 55 81 7D 73 6B 5B 1F 00 08 12 12 03 00 00 00
00 00 00 00 00 1D 34 4A 30 34 39 4C 6A 5A 79 95 65 68 42 0F 00 00 00 00 00 00 00 00
00 00 00 00 00 29 3A 4B 48 5D 67 76 6A 5F 85 8B 49 3D 25 09 00 00 00 00 00 00 00 00
00 00 00 00 00 16 27 4C 5A 67 7B 7A 5B 48 5F 63 32 2B 1C 0F 00 00 00 00 00 00 00 00
00 00 00 00 05 16 26 35 45 64 71 7A 39 19 3E 4B 22 2A 1D 0F 00 00 00 00 00 00 00 00
00 00 00 00 0D 19 1A 23 2F 3A 37 21 02 00 1A 2E 16 0D 19 0F 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 12 19 11 01 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 0E 19 04 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
### 4. Output the average label value (with rounding down to hundredths) of the first ten from test file
# , "train-labels.idx1-ubyte".
The average value of first ten labels in 'train-labels.idx1-ubyte' is +3.00
### 5. Extend and output first image to 32x32 from test file, with zero padding on boundary area.
First image array extneds to 32x32 with zero padding over boundary:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 12 12 12 7E 88 AF 1A A6 FF F7 7F 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 1E 24 5E 9A AA FD FD FD FD FD E1 AC FD F2 C3 40 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 31 EE FD FD FD FD FD FD FD FD FB 5D 52 52 38 27 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 12 DB FD FD FD FD FD C6 B6 F7 F1 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 50 9C 6B FD FD CD 0B 00 2B 9A 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 0E 01 9A FD 5A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 8B FD BE 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 0B BE FD 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 23 F1 E1 A0 6C 01 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 51 F0 FD FD 77 19 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2D BA FD FD 96 1B 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 5D FC FD BB 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F9 FD F9 40 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2E 82 B7 FD FD CF 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 94 E5 FD FD FD FA B6 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 18 72 DD FD FD FD FD C9 4E 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 17 42 D5 FD FD FD FD C6 51 02 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 12 AB DB FD FD FD FD C3 50 09 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 37 AC E2 FD FD FD FD F4 85 0B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 88 FD FD FD D4 87 84 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
### 6. Output and save first image as BitMap(.bmp) file.
First image is saved into 'first_image.bmp'.
''' | [
"math.floor",
"numpy.array",
"library.math_tool_box.StatMaker",
"imageio.imwrite"
] | [((3794, 3845), 'numpy.array', 'np.array', ([], {'object': 'image_container[0]', 'dtype': 'np.uint8'}), '(object=image_container[0], dtype=np.uint8)\n', (3802, 3845), True, 'import numpy as np\n'), ((3888, 3935), 'imageio.imwrite', 'imageio.imwrite', (['"""first_image.bmp"""', 'first_image'], {}), "('first_image.bmp', first_image)\n", (3903, 3935), False, 'import imageio\n'), ((2894, 2917), 'library.math_tool_box.StatMaker', 'StatMaker', (['label_series'], {}), '(label_series)\n', (2903, 2917), False, 'from library.math_tool_box import StatMaker\n'), ((3008, 3035), 'math.floor', 'math.floor', (['(avg * 100 / 100)'], {}), '(avg * 100 / 100)\n', (3018, 3035), False, 'import math\n')] |
import numpy as np
def l96StepRK2(u,Sim):
utmp = u.copy()
source = u[Sim['im'],:] * (u[Sim['ip'],:] - u[Sim['im2'],:]) + Sim['R'] - u
k1 = utmp + Sim['Timestep'] * 0.5 * source
source = k1[Sim['im'],:] * (k1[Sim['ip'],:] - k1[Sim['im2'],:]) + Sim['R'] - k1
u = utmp + Sim['Timestep'] * source
return u
def l96StepBackRK2(u,Sim):
utmp = u.copy()
source = -u[Sim['im'],:] * (u[Sim['ip'],:] - u[Sim['im2'],:]) - Sim['R'] + u
k1 = utmp + Sim['Timestep'] * 0.5 * source
source = -k1[Sim['im'],:] * (k1[Sim['ip'],:] - k1[Sim['im2'],:]) - Sim['R'] + k1
u = utmp + Sim['Timestep'] * source
return u
def l96qoi(u):
return np.sum(u**2)/(2*len(u))
def ksStepETDRK4(u,Sim):
g = Sim['g']
E = Sim['E']
E_2 = Sim['E_2']
Q = Sim['Q']
f1 = Sim['f1']
f2 = Sim['f2']
f3 = Sim['f3']
v = np.fft.fft(u,axis=0)
Nv = g*np.fft.fft(np.real(np.fft.ifft(v,axis=0))**2,axis=0)
a = E_2*v + Q*Nv
Na = g*np.fft.fft(np.real(np.fft.ifft(a,axis=0))**2,axis=0)
b = E_2*v + Q*Na
Nb = g*np.fft.fft(np.real(np.fft.ifft(b,axis=0))**2,axis=0)
c = E_2*a + Q*(2*Nb-Nv)
Nc = g*np.fft.fft(np.real(np.fft.ifft(c,axis=0))**2,axis=0)
v = E*v + Nv*f1 + 2*(Na+Nb)*f2 + Nc*f3
u = np.real(np.fft.ifft(v,axis=0))
return u
def ksStepRK2(u,Sim):
g = Sim['g']
E = Sim['E']
E_2 = Sim['E_2']
Q = Sim['Q']
f1 = Sim['f1']
f2 = Sim['f2']
f3 = Sim['f3']
k = Sim['k']
h = Sim['Timestep']
indexAlias = Sim['indexAlias']
v = np.fft.fft(u,axis=0)
vcopy = v.copy()
v[indexAlias]=0
source = (k**2-k**4)*v - 0.5j*k*np.fft.fft(np.fft.ifft(v,axis=0)**2,axis=0)
k1 = vcopy + h * 0.5 * source
k1[indexAlias]=0
source = (k**2-k**4)*k1 - 0.5j*k*np.fft.fft(np.fft.ifft(k1,axis=0)**2,axis=0)
v = vcopy + h * source
u = np.real(np.fft.ifft(v,axis=0))
return u
def ksStepBackRegularizedETDRK4(u,Sim):
beta = Sim['beta']
k = Sim['k']
h = Sim['Timestep']
Ndof = Sim['Ndof']
g = Sim['g']
E = Sim['Eback']
E_2 = Sim['E_2back']
Q = Sim['Qback']
f1 = Sim['f1back']
f2 = Sim['f2back']
f3 = Sim['f3back']
indexAlias = Sim['indexAlias']
dealias = False
v = np.fft.fft(u,axis=0)
if dealias:
vtmp = v.copy()
vtmp[indexAlias] = 0
Nv = g*np.fft.fft(np.real(np.fft.ifft(vtmp,axis=0))**2,axis=0)
a = E_2*v + Q*Nv
atmp = a.copy()
atmp[indexAlias] = 0
Na = g*np.fft.fft(np.real(np.fft.ifft(atmp,axis=0))**2,axis=0)
b = E_2*v + Q*Na
btmp = b.copy()
btmp[indexAlias] = 0
Nb = g*np.fft.fft(np.real(np.fft.ifft(btmp,axis=0))**2,axis=0)
c = E_2*a + Q*(2*Nb-Nv)
ctmp = c.copy()
ctmp[indexAlias] = 0
Nc = g*np.fft.fft(np.real(np.fft.ifft(c,axis=0))**2,axis=0)
else:
Nv = g*np.fft.fft(np.real(np.fft.ifft(v,axis=0))**2,axis=0)
a = E_2*v + Q*Nv
Na = g*np.fft.fft(np.real(np.fft.ifft(a,axis=0))**2,axis=0)
b = E_2*v + Q*Na
Nb = g*np.fft.fft(np.real(np.fft.ifft(b,axis=0))**2,axis=0)
c = E_2*a + Q*(2*Nb-Nv)
Nc = g*np.fft.fft(np.real(np.fft.ifft(c,axis=0))**2,axis=0)
v = E*v + Nv*f1 + 2*(Na+Nb)*f2 + Nc*f3
u = np.real(np.fft.ifft(v,axis=0))
return u
def ksStepBackRegularizedRK2(u,Sim):
beta = Sim['beta']
k = Sim['k']
h = Sim['Timestep']
Ndof = Sim['Ndof']
indexAlias = Sim['indexAlias']
v = np.fft.fft(u,axis=0)
vcopy = v.copy()
v[indexAlias]=0
source = -(k**2-k**4)*v/(1+beta*(k**4)) + 0.5j*k*np.fft.fft(np.fft.ifft(v,axis=0)**2,axis=0)/(1+beta*(k**4))
k1 = vcopy + h * 0.5 * source
k1[indexAlias]=0
source = -(k**2-k**4)*k1/(1+beta*(k**4)) + 0.5j*k*np.fft.fft(np.fft.ifft(k1,axis=0)**2,axis=0)/(1+beta*(k**4))
v = vcopy + h * source
u = np.real(np.fft.ifft(v,axis=0))
return u
| [
"numpy.sum",
"numpy.fft.fft",
"numpy.fft.ifft"
] | [((874, 895), 'numpy.fft.fft', 'np.fft.fft', (['u'], {'axis': '(0)'}), '(u, axis=0)\n', (884, 895), True, 'import numpy as np\n'), ((1557, 1578), 'numpy.fft.fft', 'np.fft.fft', (['u'], {'axis': '(0)'}), '(u, axis=0)\n', (1567, 1578), True, 'import numpy as np\n'), ((2271, 2292), 'numpy.fft.fft', 'np.fft.fft', (['u'], {'axis': '(0)'}), '(u, axis=0)\n', (2281, 2292), True, 'import numpy as np\n'), ((3530, 3551), 'numpy.fft.fft', 'np.fft.fft', (['u'], {'axis': '(0)'}), '(u, axis=0)\n', (3540, 3551), True, 'import numpy as np\n'), ((684, 698), 'numpy.sum', 'np.sum', (['(u ** 2)'], {}), '(u ** 2)\n', (690, 698), True, 'import numpy as np\n'), ((1282, 1304), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (1293, 1304), True, 'import numpy as np\n'), ((1888, 1910), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (1899, 1910), True, 'import numpy as np\n'), ((3317, 3339), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (3328, 3339), True, 'import numpy as np\n'), ((3926, 3948), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (3937, 3948), True, 'import numpy as np\n'), ((926, 948), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (937, 948), True, 'import numpy as np\n'), ((1011, 1033), 'numpy.fft.ifft', 'np.fft.ifft', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (1022, 1033), True, 'import numpy as np\n'), ((1096, 1118), 'numpy.fft.ifft', 'np.fft.ifft', (['b'], {'axis': '(0)'}), '(b, axis=0)\n', (1107, 1118), True, 'import numpy as np\n'), ((1188, 1210), 'numpy.fft.ifft', 'np.fft.ifft', (['c'], {'axis': '(0)'}), '(c, axis=0)\n', (1199, 1210), True, 'import numpy as np\n'), ((1668, 1690), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (1679, 1690), True, 'import numpy as np\n'), ((1805, 1828), 'numpy.fft.ifft', 'np.fft.ifft', (['k1'], {'axis': '(0)'}), '(k1, axis=0)\n', (1816, 1828), True, 'import numpy as np\n'), ((2401, 2426), 'numpy.fft.ifft', 'np.fft.ifft', (['vtmp'], {'axis': '(0)'}), '(vtmp, axis=0)\n', (2412, 2426), True, 'import numpy as np\n'), ((2550, 2575), 'numpy.fft.ifft', 'np.fft.ifft', (['atmp'], {'axis': '(0)'}), '(atmp, axis=0)\n', (2561, 2575), True, 'import numpy as np\n'), ((2699, 2724), 'numpy.fft.ifft', 'np.fft.ifft', (['btmp'], {'axis': '(0)'}), '(btmp, axis=0)\n', (2710, 2724), True, 'import numpy as np\n'), ((2855, 2877), 'numpy.fft.ifft', 'np.fft.ifft', (['c'], {'axis': '(0)'}), '(c, axis=0)\n', (2866, 2877), True, 'import numpy as np\n'), ((2933, 2955), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (2944, 2955), True, 'import numpy as np\n'), ((3026, 3048), 'numpy.fft.ifft', 'np.fft.ifft', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (3037, 3048), True, 'import numpy as np\n'), ((3119, 3141), 'numpy.fft.ifft', 'np.fft.ifft', (['b'], {'axis': '(0)'}), '(b, axis=0)\n', (3130, 3141), True, 'import numpy as np\n'), ((3219, 3241), 'numpy.fft.ifft', 'np.fft.ifft', (['c'], {'axis': '(0)'}), '(c, axis=0)\n', (3230, 3241), True, 'import numpy as np\n'), ((3657, 3679), 'numpy.fft.ifft', 'np.fft.ifft', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (3668, 3679), True, 'import numpy as np\n'), ((3827, 3850), 'numpy.fft.ifft', 'np.fft.ifft', (['k1'], {'axis': '(0)'}), '(k1, axis=0)\n', (3838, 3850), True, 'import numpy as np\n')] |
"""Tests for rxn_rate_coefficients module"""
import numpy
import pytest
import os, sys
#sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import warnings
warnings.simplefilter("error")
from pychemkin.rxn_rate_coefficients.rxn_rate_coefficients import *
# ===== Tests for forward reaction rate coefficients ===== #
def test_unhandled_rxn_rate_coeff_type():
"""Test invalid/unhandled rxn rate coefficient type."""
rate_coeffs_type = "madeup type"
with pytest.raises(KeyError):
test = determine_rxn_rate_coeff_type(rate_coeffs_type)
def test_invalid_components():
"""Test reaction rate coefficients when
invalid/unhandled component in dictionary."""
# constant
k_parameters = {'sdfs': 10}
with pytest.raises(ValueError):
k_test = ConstantFwdCoeff(k_parameters)
# Arrhenius
k_parameters = {'sdfdds': 10, 'E': 10**3}
T = 10
with pytest.raises(ValueError):
k_test = ArrheniusFwdCoeff(k_parameters, T)
# modified Arrhenius
k_parameters = {'sdfdds': 10, 'E': 10**3, 'b': 10}
T = 10
with pytest.raises(ValueError):
k_test = ArrheniusFwdCoeff(k_parameters, T)
def test_invalid_or_extra_components():
"""Test reaction rate coefficients when
extra component in dictionary."""
# constant
k_parameters = {'k': 10, 'q':8}
with pytest.warns(UserWarning):
k_test = ConstantFwdCoeff(k_parameters).k
# Arrhenius
k_parameters = {'A': 10**7, 'E':10**3, 'R': 8.3144598, 'madeup':120}
T = 10
with pytest.warns(UserWarning):
k_test = ArrheniusFwdCoeff(k_parameters, T).k
k_parameters = {'A': 10**7, 'E':10**3, 'madeup':120}
T = 10
with pytest.warns(UserWarning):
k_test = ArrheniusFwdCoeff(k_parameters, T).k
# modified Arrhenius
k_parameters = {'A': 10**7, 'E':10**3, 'b':0.5, 'madeup':120, 'R': 8.3144598}
T = 10
with pytest.warns(UserWarning):
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
k_parameters = {'A': 10**7, 'E':10**3, 'b':0.5, 'madeup':120}
T = 10
with pytest.warns(UserWarning):
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
def test_constant_rxn_rate_coefficient():
"""Tests for constant reaction rate coefficient."""
# Test when invalid constant (non-positive k)
k_parameters = {'k': -10}
with pytest.raises(ValueError):
k_test = ConstantFwdCoeff(k_parameters).k
# Compute with valid input
k_parameters = {'k': 10}
k_test = ConstantFwdCoeff(k_parameters).k
assert k_test == 10
# Test when T entered (no effect)
k_parameters = {'k': 10}
T = 10
k_test = ConstantFwdCoeff(k_parameters, T).k
assert k_test == 10
def test_arrhenius_rxn_rate_coefficient():
"""Tests for Arrhenius reaction rate coefficient."""
# Test when missing argument T
k_parameters = {'A': 10, 'E':100, 'R':8.3144598}
with pytest.raises(TypeError):
k_test = ArrheniusFwdCoeff(k_parameters).k
# Compute with valid inputs
k_parameters = {'A': 10**7, 'E': 10**3, 'R': 8.3144598}
T = 10**2
k_test = ArrheniusFwdCoeff(k_parameters, T).k
assert numpy.isclose(k_test, 3003748.8791204286, atol=1e-16)
# Test when invalid value for T (non-positive temperature)
k_parameters = {'A': 10, 'E': 100, 'R': 8.3144598}
T = -10
with pytest.raises(ValueError):
k_test = ArrheniusFwdCoeff(k_parameters, T).k
# Test when invalid value for A (non-positive prefactor)
k_parameters = {'A': 0, 'E': 100, 'R': 8.3144598}
T = 10
with pytest.raises(ValueError):
k_test = ArrheniusFwdCoeff(k_parameters, T).k
# Test when invalid value for R (non-positive gas constant)
k_parameters = {'A': 10, 'E': 100, 'R': -100}
T = 10
with pytest.raises(ValueError):
k_test = ArrheniusFwdCoeff(k_parameters, T).k
# Test when changing value of R
k_parameters = {'A': 10, 'E': 100, 'R': 10.453}
T = 10
with pytest.warns(UserWarning):
k_test = ArrheniusFwdCoeff(k_parameters, T).k
def test_modified_arrhenius_rxn_rate_coefficient():
"""Tests for Modified Arrhenius reaction rate coefficient."""
# Test when missing argument T
k_parameters = {'A': 10, 'E':100, 'b':0.5, 'R':8.3144598}
with pytest.raises(TypeError):
k_test = ModifiedArrheniusFwdCoeff(k_parameters).k
# Compute with valid inputs
k_parameters = {'A': 10**7, 'E':10**3, 'b':0.5, 'R':8.3144598}
T = 10**2
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
assert numpy.isclose(k_test, 30037488.791204285, atol=1e-16)
# Test when invalid value for A (non-positive prefactor)
k_parameters = {'A': -10, 'E':100, 'b':0.5, 'R':8.3144598}
T = 10
with pytest.raises(ValueError):
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
# Test when invalid value for b (non-real constant)
k_parameters = {'A': 10, 'E':100, 'b':0.5j, 'R':8.3144598}
T = 10
with pytest.raises(TypeError):
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
# Test when invalid value for T (non-positive temperature)
k_parameters = {'A': 10, 'E':100, 'b':0.5, 'R':8.3144598}
T = -10
with pytest.raises(ValueError):
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
# Test when invalid value for R (non-positive gas constant)
k_parameters = {'A': 10, 'E':100, 'R':-100, 'b':0.5}
T = 10
with pytest.raises(ValueError):
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
# Test when changing value of R
k_parameters = {'A': 10, 'E':100, 'R':10.453, 'b':0.5}
T = 10
with pytest.warns(UserWarning):
k_test = ModifiedArrheniusFwdCoeff(k_parameters, T).k
# ===== Tests for backward reaction rate coefficients ===== #
def test_backward_coefficient_base_class():
"""Test BackwardReactionCoeff class"""
bkwd_coeff = BackwardReactionCoeff()
with pytest.raises(NotImplementedError):
bkwd_coeff.compute_bkwd_coefficient()
@pytest.fixture
def NASA7_backward_coeff_setup():
"""Returns a working (but artificial) example of
backward reaction rate coefficient using NASA
7 polynomial coefficients."""
expected_nasa = numpy.array([[1,0,0,0,0,0,0],
[1,0,0,0,0,0,0],
[1,0,0,0,0,0,0]])
k_f = 100
nu_i = numpy.array([-2, -1, 2])
bkwd_coeff = NASA7BackwardCoeff(nu_i, expected_nasa,
p0=1e5, R=8.3144598)
return bkwd_coeff
def test_NASA7_backward_coeff(NASA7_backward_coeff_setup):
"""Test backward rxn rate coefficient using NASA
7 polynomial coefficients."""
# Test when changing value of R
expected_nasa = numpy.array([[1,0,0,0,0,0,0],
[1,0,0,0,0,0,0],
[1,0,0,0,0,0,0]])
k_f = 100
nu_i = numpy.array([-2, -1, 2])
with pytest.warns(UserWarning):
kwd_coeff = NASA7BackwardCoeff(nu_i, expected_nasa,
p0=1e5, R=43.3423)
# Test value of gamma
assert NASA7_backward_coeff_setup.gamma == -1
# Test computation of H/RT
T = 100
expected_H_over_RT = numpy.array([1, 1, 1])
assert numpy.isclose(NASA7_backward_coeff_setup._H_over_RT(T),
expected_H_over_RT, atol=1e-16).all()
# Test computation of H/RT with invalid T (non-positive temperature)
T = -100
with pytest.raises(ValueError):
NASA7_backward_coeff_setup._H_over_RT(T)
# Test computation of S/R
T = 100
expected_S_over_R = numpy.array([4.60517, 4.60517, 4.60517])
assert numpy.isclose(NASA7_backward_coeff_setup._S_over_R(T),
expected_S_over_R, atol=1e-16).all()
# Test computation of S/R with invalid T (non-positive temperature)
T = -100
with pytest.raises(ValueError):
NASA7_backward_coeff_setup._S_over_R(T)
# Test computation of backward rxn rate coefficient k_b
T = 100
k_f = 100
expected_delta_S_over_R = -4.60517
expected_delta_H_over_RT = -1
fact = NASA7_backward_coeff_setup.p0 / NASA7_backward_coeff_setup.R / T
expected_gamma = -1
expected_ke = (fact ** expected_gamma) * (numpy.exp(expected_delta_S_over_R -
expected_delta_H_over_RT))
expected_kb_val = 442457 # 100 / 2.260104919e-6
assert numpy.isclose(NASA7_backward_coeff_setup.compute_bkwd_coefficient(k_f, T),
expected_kb_val, atol=1e-16)
# Test computation of k_b with invalid T (non-positive temperature)
T = -100
k_f = 100
with pytest.raises(ValueError):
NASA7_backward_coeff_setup.compute_bkwd_coefficient(k_f, T)
| [
"numpy.isclose",
"numpy.exp",
"numpy.array",
"pytest.raises",
"warnings.simplefilter",
"pytest.warns"
] | [((183, 213), 'warnings.simplefilter', 'warnings.simplefilter', (['"""error"""'], {}), "('error')\n", (204, 213), False, 'import warnings\n'), ((3180, 3233), 'numpy.isclose', 'numpy.isclose', (['k_test', '(3003748.8791204286)'], {'atol': '(1e-16)'}), '(k_test, 3003748.8791204286, atol=1e-16)\n', (3193, 3233), False, 'import numpy\n'), ((4572, 4625), 'numpy.isclose', 'numpy.isclose', (['k_test', '(30037488.791204285)'], {'atol': '(1e-16)'}), '(k_test, 30037488.791204285, atol=1e-16)\n', (4585, 4625), False, 'import numpy\n'), ((6252, 6339), 'numpy.array', 'numpy.array', (['[[1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0]]'], {}), '([[1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, \n 0, 0]])\n', (6263, 6339), False, 'import numpy\n'), ((6406, 6430), 'numpy.array', 'numpy.array', (['[-2, -1, 2]'], {}), '([-2, -1, 2])\n', (6417, 6430), False, 'import numpy\n'), ((6772, 6859), 'numpy.array', 'numpy.array', (['[[1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0]]'], {}), '([[1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, \n 0, 0]])\n', (6783, 6859), False, 'import numpy\n'), ((6926, 6950), 'numpy.array', 'numpy.array', (['[-2, -1, 2]'], {}), '([-2, -1, 2])\n', (6937, 6950), False, 'import numpy\n'), ((7252, 7274), 'numpy.array', 'numpy.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (7263, 7274), False, 'import numpy\n'), ((7644, 7684), 'numpy.array', 'numpy.array', (['[4.60517, 4.60517, 4.60517]'], {}), '([4.60517, 4.60517, 4.60517])\n', (7655, 7684), False, 'import numpy\n'), ((495, 518), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (508, 518), False, 'import pytest\n'), ((766, 791), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (779, 791), False, 'import pytest\n'), ((924, 949), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (937, 949), False, 'import pytest\n'), ((1104, 1129), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1117, 1129), False, 'import pytest\n'), ((1367, 1392), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (1379, 1392), False, 'import pytest\n'), ((1554, 1579), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (1566, 1579), False, 'import pytest\n'), ((1713, 1738), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (1725, 1738), False, 'import pytest\n'), ((1922, 1947), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (1934, 1947), False, 'import pytest\n'), ((2098, 2123), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (2110, 2123), False, 'import pytest\n'), ((2376, 2401), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2389, 2401), False, 'import pytest\n'), ((2935, 2959), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2948, 2959), False, 'import pytest\n'), ((3374, 3399), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3387, 3399), False, 'import pytest\n'), ((3591, 3616), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3604, 3616), False, 'import pytest\n'), ((3807, 3832), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3820, 3832), False, 'import pytest\n'), ((3997, 4022), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (4009, 4022), False, 'import pytest\n'), ((4304, 4328), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (4317, 4328), False, 'import pytest\n'), ((4771, 4796), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4784, 4796), False, 'import pytest\n'), ((5000, 5024), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (5013, 5024), False, 'import pytest\n'), ((5235, 5260), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5248, 5260), False, 'import pytest\n'), ((5466, 5491), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5479, 5491), False, 'import pytest\n'), ((5671, 5696), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (5683, 5696), False, 'import pytest\n'), ((5962, 5996), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (5975, 5996), False, 'import pytest\n'), ((6960, 6985), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (6972, 6985), False, 'import pytest\n'), ((7501, 7526), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7514, 7526), False, 'import pytest\n'), ((7908, 7933), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7921, 7933), False, 'import pytest\n'), ((8291, 8352), 'numpy.exp', 'numpy.exp', (['(expected_delta_S_over_R - expected_delta_H_over_RT)'], {}), '(expected_delta_S_over_R - expected_delta_H_over_RT)\n', (8300, 8352), False, 'import numpy\n'), ((8713, 8738), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8726, 8738), False, 'import pytest\n')] |
"""Tools for generating randomized datasets."""
import os
import numpy as np
from scipy.ndimage import gaussian_filter
from ..field import Field, Rock, States, Wells
from .utils import get_config, STATES_KEYWORD
def _apply_uncorrelated_noise(arr, std):
noise = np.random.randn(*arr.shape) * std
return arr + noise
def _apply_correlated_noise(arr, std, freq):
seeds = np.random.choice(
[0, 1], size=arr.shape,
p=[1 - freq, freq]
)
std = std / freq * seeds
noise = np.random.randn(*arr.shape) * std
noise = gaussian_filter(noise, 1 / freq)
return arr + noise
def _get_uniform_samples(*args):
if len(args) > 1:
return tuple(np.random.rand() * (arg[1] - arg[0]) + arg[0] for arg in args)
return np.random.rand() * (args[0][1] - args[0][0]) + args[0][0]
def _noise_component(size, r):
out = np.random.rand(size) * (r[1] - r[0]) + r[0]
return out
def _const_component(size, b):
b = _get_uniform_samples(b)
out = np.zeros(size) + b
return out
def _exp_component(size, a, v):
a, v = _get_uniform_samples(a, v)
l = np.exp(v)
t = np.arange(size)
out = a * np.exp(-t * l)
return out
def _sin_component(size, scale, phi, minima):
scale, phi, minima = _get_uniform_samples(scale, phi, minima)
t = np.arange(size)
out = np.sin(scale * t + phi)
out = (1 + out) * (1 - minima) / 2 + minima
return out
class AttrRandomizer:
"""Baseclass for attribute randomization."""
def __init__(self, associated_class, **kwargs):
for key, arg in kwargs.items():
setattr(self, key, arg)
self.associated_class = associated_class
def __call__(self, attr, **kwargs):
"""Get randomized version of attr."""
if attr.__class__ != self.associated_class:
raise ValueError('Can randomize instances of %s class. Found: %s' % (self.associated_class, attr.__class__))
return self._randomize_attr(attr, **kwargs)
def _randomize_attr(self, *args, **kwargs):
raise NotImplementedError('Abstract method.')
class ControlRandomizer(AttrRandomizer):
"""Randomizer for control attributes (works inplace!)."""
def __init__(self, attr_to_vary='BHPT', equality_condition=None, exp_amp=(70, 250), exp_log_curv=(-6, -4),
const=(1, 10), sin_scale=(0.001, 0.02), sin_phi=(0, 2 * np.pi), sin_minima=(0.6, 0.8),
noise_range=(0, 0)):
"""
Parameters
----------
attr_to_vary: str
Attribute name to vary (should be represented in well's events)
"""
kwargs = dict(attr_to_vary=attr_to_vary, equality_condition=equality_condition, exp_amp=exp_amp,
exp_log_curv=exp_log_curv, const=const, sin_scale=sin_scale, sin_phi=sin_phi,
sin_minima=sin_minima, noise_range=noise_range)
super().__init__(associated_class=Wells, **kwargs)
def _randomize_attr(self, wells, **kwargs):
"""
Parameters
----------
wells: deepfield.field.Wells
Returns
-------
out: deepfield.field.Wells
Wells with randomized events.
"""
_ = kwargs
attr = self.attr_to_vary
exp_amp, exp_curv = self.exp_amp, self.exp_log_curv
const = self.const
sin_scale, sin_phi, sin_minima = self.sin_scale, self.sin_phi, self.sin_minima
noise_range = self.noise_range
def sampler(size):
e = _exp_component(size, exp_amp, exp_curv)
c = _const_component(size, const)
s = _sin_component(size, sin_scale, sin_phi, sin_minima)
eps = _noise_component(size, noise_range)
out = e * s + c + eps
return out
clip_min = 0
clip_max = None
kwargs = {'additive': False, 'clip': (clip_min, clip_max),
'equality_condition': self.equality_condition, attr: sampler}
wells.randomize_events(**kwargs)
return wells
class StatesRandomizer(AttrRandomizer):
"""Randomizer for states attributes"""
def __init__(self, std_reference_func=np.max, std_amplitude=0.01, uncorrelated_noise=False,
correlated_noise_freq=0.1, inplace=False):
"""
Parameters
----------
std_reference_func: callable
Reference function used to calculate standard deviation of randomization
Output of this function will be multiplied by std_amplitude and this value will be used as std.
std_amplitude: float
Multiplier for output of std_reference_func.
The result of multiplication will be used as std of randomization.
uncorrelated_noise: bool
If False, correlated noise will be applied.
inplace: bool
"""
kwargs = dict(std_reference_func=std_reference_func, std_amplitude=std_amplitude,
uncorrelated_noise=uncorrelated_noise, inplace=inplace,
correlated_noise_freq=correlated_noise_freq, sat_attrs=('SOIL', 'SWAT', 'SGAS'))
super().__init__(associated_class=States, **kwargs)
def _randomize_attr(self, states, **kwargs):
"""
Parameters
----------
states: deepfield.field.States
Returns
-------
out: deepfield.field.States
Randomized states.
"""
actnum = kwargs['actnum']
noisy_states = self._apply_noise(states, actnum)
if not self.inplace:
states = States()
for attr, arr in noisy_states.items():
setattr(states, attr, arr)
return states
def _apply_noise(self, states, actnum):
noisy_states = {}
for attr in states.attributes:
arr = getattr(states, attr)
std = self.std_reference_func(arr) * self.std_amplitude
if self.uncorrelated_noise:
arr = _apply_uncorrelated_noise(arr, std)
else:
arr = _apply_correlated_noise(arr, std, self.correlated_noise_freq)
clip_min = 1 if attr == 'PRESSURE' else 0
clip_max = 1 if attr in self.sat_attrs else None
arr = np.clip(arr, a_min=clip_min, a_max=clip_max)
arr *= actnum
noisy_states[attr] = arr
noisy_states = self._normalize_saturations(noisy_states)
return noisy_states
def _normalize_saturations(self, states):
sat_attrs = [attr for attr in self.sat_attrs if attr in states]
if len(sat_attrs) > 1:
sat_denominator = np.sum(
[states[attr] for attr in sat_attrs],
axis=0
)
for attr in sat_attrs:
states[attr] = np.divide(states[attr], sat_denominator, out=np.zeros_like(states[attr]),
where=sat_denominator != 0)
return states
class RockRandomizer(AttrRandomizer):
"""Randomizer for rock attributes."""
def __init__(self, std_reference_func=np.max, std_amplitude=0.01, uncorrelated_noise=False,
correlated_noise_freq=0.1, inplace=False):
"""
Parameters
----------
std_reference_func: callable
Reference function used to calculate standard deviation of randomization
Output of this function will be multiplied by std_amplitude and this value will be used as std.
std_amplitude: float
Multiplier for output of std_reference_func.
The result of multiplication will be used as std of randomization.
uncorrelated_noise: bool
If False, correlated noise will be applied.
inplace: bool
"""
kwargs = dict(std_reference_func=std_reference_func, std_amplitude=std_amplitude,
uncorrelated_noise=uncorrelated_noise, inplace=inplace,
correlated_noise_freq=correlated_noise_freq)
super().__init__(associated_class=Rock, **kwargs)
def _randomize_attr(self, rock, **kwargs):
"""
Parameters
----------
rock: deepfield.field.Rock
Returns
-------
out: deepfield.field.Rock
Randomized rock.
"""
actnum = kwargs['actnum']
noisy_rock = self._apply_noise(rock, actnum)
if not self.inplace:
rock = Rock()
for attr, arr in noisy_rock.items():
setattr(rock, attr, arr)
return rock
def _apply_noise(self, rock, actnum):
perm_attrs = [attr for attr in ('PERMX', 'PERMY', 'PERMZ') if hasattr(rock, attr)]
if perm_attrs:
perm = getattr(rock, perm_attrs[0])
perm[perm == 0] = 1
relative_perm = {attr: getattr(rock, attr) / perm for attr in perm_attrs[1:]}
else:
perm, relative_perm = {}, {}
noisy_rock = {}
for attr in rock.attributes:
if attr in relative_perm:
continue
arr = getattr(rock, attr)
std = self.std_reference_func(arr) * self.std_amplitude
if self.uncorrelated_noise:
arr = _apply_uncorrelated_noise(arr, std)
else:
arr = _apply_correlated_noise(arr, std, self.correlated_noise_freq)
clip_min = 0
clip_max = 1 if attr == 'PORO' else None
arr = np.clip(arr, a_min=clip_min, a_max=clip_max)
arr *= actnum
noisy_rock[attr] = arr
for attr, arr in relative_perm.items():
noisy_rock[attr] = arr * noisy_rock[perm_attrs[0]]
return noisy_rock
class FieldRandomizer:
"""Randomization of Fields, based on some base model."""
default_states_rand = StatesRandomizer(std_reference_func=np.max, std_amplitude=0.01,
uncorrelated_noise=True, inplace=True)
default_rock_rand = RockRandomizer(std_reference_func=np.max, std_amplitude=0.01,
uncorrelated_noise=True, inplace=True)
default_control_rand = ControlRandomizer()
default_randomizer = {
'states': default_states_rand,
'rock': default_rock_rand,
'control': default_control_rand,
}
def __init__(self, path_to_base_field, randomizer=None):
"""
Parameters
----------
path_to_base_field: std
Path to the base-field used to randomize around.
randomizer: dict
Dict with instances of randomizers for states, rock and control (wells)
Should have keys the following form:
randomizer = {
'states': states_rand,
'rock': rock_rand,
'wells': control_rand,
}
"""
self.config = get_config()
self.config[STATES_KEYWORD] = {'attrs': self.config[STATES_KEYWORD]['attrs'], 'subset': [0]}
self.base_path = path_to_base_field
if randomizer is not None:
self.randomizer = {}
for key, def_r in self.default_randomizer.items():
if key not in randomizer.keys() or randomizer[key] is None:
self.randomizer[key] = def_r
else:
self.randomizer[key] = randomizer[key]
else:
self.randomizer = self.default_randomizer
def _load_model(self, path):
"""Load and unravel field model."""
model = Field(path=path, config=self.config, encoding='auto:10000', loglevel='ERROR')
model.load(raise_errors=False)
model.to_spatial()
if 'wells' in map(lambda s: s.lower(), self.config.keys()):
model.wells.drop_incomplete()
model.wells.get_wellblocks(grid=model.grid)
model.wells.apply_perforations()
model.wells.add_null_results_column(column='WWIR')
model.wells.results_to_events(grid=model.grid)
return model
def get_randomized_field(self):
"""Get randomized field.
Returns
-------
out: deepfield.field.Field
Field with randomized initial state, rock and control.
"""
field = self._load_model(self.base_path)
kwargs = {'actnum': field.grid.actnum.astype(np.float)}
for key, rnd in self.randomizer.items():
attr = key if key != 'control' else 'wells'
if hasattr(field, attr):
value = getattr(field, attr)
randomizers = rnd if isinstance(rnd, tuple) else (rnd, )
for randomizer in randomizers:
value = randomizer(value, **kwargs)
setattr(field, attr, value)
return field
def generate_randomized_dataset(self, root_dir, n_samples, fmt=None, title=None):
"""Generate dataset consisting of randomized fields.
Parameters
----------
root_dir: str
Path to the directory to create the dataset
n_samples: int
An amount of fields to generate
fmt: str, optional
Format in which fields will be dumped (with field.dump(fmt=fmt))
If None, fields will be dumped in tNavigator format.
title: str
"""
if not os.path.exists(root_dir):
os.mkdir(root_dir)
fmt = ('.' + fmt) if fmt is not None else ''
title = (title + '_') if title is not None else ''
for i in range(n_samples):
field = self.get_randomized_field()
filename = title + str(i) + fmt
path = os.path.join(root_dir, filename)
if fmt == '':
os.mkdir(path)
field.dump(path=path, config=self.config, mode='w')
| [
"numpy.clip",
"os.path.exists",
"numpy.random.rand",
"numpy.random.choice",
"os.path.join",
"numpy.zeros_like",
"numpy.exp",
"numpy.sum",
"numpy.zeros",
"os.mkdir",
"scipy.ndimage.gaussian_filter",
"numpy.sin",
"numpy.random.randn",
"numpy.arange"
] | [((385, 445), 'numpy.random.choice', 'np.random.choice', (['[0, 1]'], {'size': 'arr.shape', 'p': '[1 - freq, freq]'}), '([0, 1], size=arr.shape, p=[1 - freq, freq])\n', (401, 445), True, 'import numpy as np\n'), ((556, 588), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['noise', '(1 / freq)'], {}), '(noise, 1 / freq)\n', (571, 588), False, 'from scipy.ndimage import gaussian_filter\n'), ((1113, 1122), 'numpy.exp', 'np.exp', (['v'], {}), '(v)\n', (1119, 1122), True, 'import numpy as np\n'), ((1131, 1146), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (1140, 1146), True, 'import numpy as np\n'), ((1313, 1328), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (1322, 1328), True, 'import numpy as np\n'), ((1339, 1362), 'numpy.sin', 'np.sin', (['(scale * t + phi)'], {}), '(scale * t + phi)\n', (1345, 1362), True, 'import numpy as np\n'), ((269, 296), 'numpy.random.randn', 'np.random.randn', (['*arr.shape'], {}), '(*arr.shape)\n', (284, 296), True, 'import numpy as np\n'), ((510, 537), 'numpy.random.randn', 'np.random.randn', (['*arr.shape'], {}), '(*arr.shape)\n', (525, 537), True, 'import numpy as np\n'), ((999, 1013), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (1007, 1013), True, 'import numpy as np\n'), ((1161, 1175), 'numpy.exp', 'np.exp', (['(-t * l)'], {}), '(-t * l)\n', (1167, 1175), True, 'import numpy as np\n'), ((764, 780), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (778, 780), True, 'import numpy as np\n'), ((865, 885), 'numpy.random.rand', 'np.random.rand', (['size'], {}), '(size)\n', (879, 885), True, 'import numpy as np\n'), ((6240, 6284), 'numpy.clip', 'np.clip', (['arr'], {'a_min': 'clip_min', 'a_max': 'clip_max'}), '(arr, a_min=clip_min, a_max=clip_max)\n', (6247, 6284), True, 'import numpy as np\n'), ((6621, 6673), 'numpy.sum', 'np.sum', (['[states[attr] for attr in sat_attrs]'], {'axis': '(0)'}), '([states[attr] for attr in sat_attrs], axis=0)\n', (6627, 6673), True, 'import numpy as np\n'), ((9447, 9491), 'numpy.clip', 'np.clip', (['arr'], {'a_min': 'clip_min', 'a_max': 'clip_max'}), '(arr, a_min=clip_min, a_max=clip_max)\n', (9454, 9491), True, 'import numpy as np\n'), ((13341, 13365), 'os.path.exists', 'os.path.exists', (['root_dir'], {}), '(root_dir)\n', (13355, 13365), False, 'import os\n'), ((13379, 13397), 'os.mkdir', 'os.mkdir', (['root_dir'], {}), '(root_dir)\n', (13387, 13397), False, 'import os\n'), ((13656, 13688), 'os.path.join', 'os.path.join', (['root_dir', 'filename'], {}), '(root_dir, filename)\n', (13668, 13688), False, 'import os\n'), ((13731, 13745), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (13739, 13745), False, 'import os\n'), ((690, 706), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (704, 706), True, 'import numpy as np\n'), ((6831, 6858), 'numpy.zeros_like', 'np.zeros_like', (['states[attr]'], {}), '(states[attr])\n', (6844, 6858), True, 'import numpy as np\n')] |
import logging
import os
import shutil
import time
import json
import random
import linecache
import gc
import numpy as np
import torch
from src.bayesian_summarization.bayesian import BayesianSummarizer
from src.common.loaders import load_model, create_loader
from src.bayesian_summarization.bleu import analyze_generation_bleuvar
from src.summarization.sum_base import TrainerSummarizer
logger = logging.getLogger(__name__)
def write_metrics(out_path, metrics, filename):
with open(os.path.join(out_path, f"{filename}.json"), "a+") as hist:
json.dump(metrics, hist)
hist.write("\n")
class ActiveSum:
"""
Base class for active summarization training.
Implements the basic training step and can be extended
with other active learning strategies.
"""
def __init__(self, data_sampler, device, **kwargs):
self.data_sampler = data_sampler
self.device = device
self.metric = None
self.save_limit = None
self.save_step = None
self.beams = None
self.source_len = None
self.target_len = None
self.val_samples = None
self.test_samples = None
self.lr = None
self.batch_size = None
self.seed = None
self.sum_col = None
self.doc_col = None
self.init_model = None
self.py_module = None
self.best_score = 0.
self.__dict__.update(kwargs)
def train(
self,
labeled_path,
model_path,
eval_path,
epochs,
):
"""
Wraps the call to the summarization trainer with the required arguments
"""
train_path = os.path.join(labeled_path, "train.json")
sum_trainer = TrainerSummarizer(
model_name_or_path=self.init_model,
tokenizer_name=self.init_model,
train_file=train_path,
validation_file=eval_path,
text_column=self.doc_col,
summary_column=self.sum_col,
output_dir=model_path,
logging_dir=f"{model_path}/logs",
seed=self.seed,
per_device_train_batch_size=self.batch_size,
per_device_eval_batch_size=self.batch_size,
overwrite_output_dir=True,
max_val_samples=self.val_samples,
max_test_samples=self.test_samples,
learning_rate=self.lr,
adafactor=True,
max_source_length=self.source_len,
max_target_length=self.target_len,
val_max_target_length=self.target_len,
pad_to_max_length=True,
num_beams=self.beams,
num_train_epochs=epochs,
save_steps=self.save_step,
save_total_limit=self.save_limit,
load_best_model_at_end=True,
evaluation_strategy="epoch",
metric_for_best_model=self.metric,
greater_is_better=True,
do_train=True,
do_eval=True,
predict_with_generate=True,
do_predict=False,
)
sum_trainer.init_sum()
train_metrics = sum_trainer.train()
eval_metrics = sum_trainer.evaluate()
del sum_trainer
gc.collect()
torch.cuda.empty_cache()
return train_metrics, eval_metrics
def train_step(self, labeled_path, model_path, eval_path, epochs):
"""Runs the basic training step and evaluates metrics.
Also, keeps track of the best model based on the primary metric
and does checkpointing and metrics logging.
"""
train_metrics, eval_metrics = self.train(
labeled_path=labeled_path,
model_path=model_path,
eval_path=eval_path,
epochs=epochs,)
write_metrics(model_path, train_metrics, filename="train_metrics_hist")
write_metrics(model_path, eval_metrics, filename="eval_metrics_hist")
if eval_metrics[f"eval_{self.metric}"] > self.best_score:
best_checkpoint_path = os.path.join(model_path, "best_checkpoint")
if not os.path.exists(best_checkpoint_path):
os.mkdir(best_checkpoint_path)
shutil.copy(os.path.join(model_path, "pytorch_model.bin"), best_checkpoint_path)
self.best_score = eval_metrics[f"eval_{self.metric}"]
logger.info(f"Best model with {self.metric} score {self.best_score} saved to {best_checkpoint_path}")
linecache.clearcache()
def predict(self):
pass
def obtain_targets(self):
pass
def write_samples(self, sample, selected_samples, sample_idxs, out_path, scores=None):
"""Writes a dataset sample to be used for training.
Three files are written:
1) train.json: with the training (input, target) pairs, one per line
2) metadata.json: full sample metadata including ranking score
3) all_scores.json: all ranking scores computed in the step (includes examples that weren't selected)
"""
metadata_output = os.path.join(out_path, "metadata.json")
train_output = os.path.join(out_path, "train.json")
score_stats = os.path.join(out_path, "all_scores.json")
mdf = open(metadata_output, "a+")
outf = open(train_output, "a+")
entf = open(score_stats, "a+")
for di, (data_s, data_idx, si) in enumerate(zip(sample, sample_idxs, selected_samples)):
out_json = {"sample_id": data_idx, "score": scores[si] if scores is not None else None, "sample": data_s}
json.dump(out_json, mdf)
mdf.write("\n")
train_sample_json = {
"document": data_s[self.doc_col].replace('\n', ' '),
"summary": data_s[self.sum_col].replace('\n', ' '),
"id": data_idx}
json.dump(train_sample_json, outf)
outf.write("\n")
json.dump({"all_scores": scores}, entf)
entf.write("\n")
mdf.close()
outf.close()
entf.close()
def init_learner(self, init_labeled, model_path, labeled_path, eval_path, epochs):
"""Initialize the active learner.
The initial model is created and trained on an pool of randomly selected examples.
"""
sample, sample_idxs = self.data_sampler.sample_data(k=init_labeled)
self.data_sampler.remove_samples(sample_idxs)
self.write_samples(sample, sample_idxs, sample_idxs, labeled_path)
train_metrics, eval_metrics = self.train(
labeled_path=labeled_path,
model_path=model_path,
eval_path=eval_path,
epochs=epochs,)
logger.info("Finished initial training")
self.best_score = eval_metrics[f"eval_{self.metric}"]
write_metrics(model_path, eval_metrics, filename="eval_metrics_hist")
linecache.clearcache()
def resume_learner(self, labeled_path):
"""
"""
# load previously selected samples
metadata_output = os.path.join(labeled_path, "metadata.json")
selected_idxs = []
with open(metadata_output) as mf:
for s in mf:
selected_idxs.append(json.loads(s.strip())["sample_id"])
# remove samples from data_sampler
self.data_sampler.remove_samples(selected_idxs)
logger.info(f"{len(selected_idxs)} have been removed from the pool")
class BAS(ActiveSum):
"""
Bayesian active summarization module.
At each learning step we sample summaries with MC dropout for a pool
of unlabelled examples. Then we used the BLEUVar metric computed based
on the sampled summaries to select a subset to be labelled.
The labelled set L is extended with the selected subset at each step
and a new model is trained on the extended labelled set.
Example:
```
active_learner = BAS(
train_sampler,
device='gpu',
doc_col='document',
sum_col='summary,
seed=100,
py_module='as_learn.py',
init_model='google/pegasus-large',
source_len=128,
target_len=16,
val_samples=100,
batch_size=6,
beams=4,
lr=1e-4,
save_step=100,
save_limit=1,
metric='rouge_1',
)
active_learner.init_learner(
init_labeled=20,
model_path='path_to_model/model',
labeled_path='path_to_data',
eval_path='path_to_data/validation.json',
epochs=10)
active_learner.learn(
steps=10,
model_path='path_to_model/model',
labeled_path='path_to_data',
k=100, s=10, n=10,
eval_path='path_to_data/validation.json',
epochs=10)
```
"""
def __init__(self, data_sampler, device, **kwargs):
super(BAS, self).__init__(data_sampler, device, **kwargs)
def learn(self, steps, model_path, labeled_path, k, s, n, eval_path, epochs):
"""Learning strategy for Bayesian summarization"""
for i in range(steps):
self.learning_step(model_path, labeled_path, k, s, n, eval_path=eval_path, epochs=epochs, step=i)
def mc_sample(self, sample_idxs, model_path, n):
"""Sample summaries with MC dropout
Summaries are sampled for a list of document ids (sample_idxs) from self.data_sampler.
For each input we run N stochastic forward passes with dropout enabled in order to get
n different summaries.
"""
dataloader = create_loader(self.data_sampler.dataset, batch_size=self.batch_size, sample=sample_idxs)
bayesian_summarizer = BayesianSummarizer(
model_name_or_path=model_path,
tokenizer_name=self.init_model,
text_column=self.doc_col,
seed=self.seed,
max_source_length=self.source_len,
num_beams=self.beams,
)
bayesian_summarizer.init_sum()
generated_sums = bayesian_summarizer.generate_mc_summaries(
dataloader,
n=n)
del bayesian_summarizer
gc.collect()
torch.cuda.empty_cache()
return generated_sums
def rank_data(self, mc_generations, n):
"""Compute the BLEUVar scores for summaries generated with MC dropout"""
bleuvars = []
for gen_list in mc_generations:
bleuvar, _, _, _ = analyze_generation_bleuvar(gen_list, n)
bleuvars.append(bleuvar)
return bleuvars
def select_data(self, scores, s, threshold=0.96):
"""Select the examples with the S highest BLEUVar scores"""
scores = np.array(scores)
top_s = scores.argsort()
top_s = [idx for idx in top_s if scores[idx] < threshold][-s:][::-1]
np.random.shuffle(top_s)
top_s_scores = [scores[i] for i in top_s]
return top_s, top_s_scores
def learning_step(self, model_path, labeled_path, k, s, n, eval_path, epochs, step=0):
"""A single learning step for Bayesian active summarization
1) select a pool of unlabeled examples
2) sample N summaries with MC dropout for the examples in the selected pool
3) compute BLEUVar scores for the selected pool
4) add the S examples with the highest BLEUVar to the labelled set
5) train on the extended labelled set
"""
logger.info(f"Learning step {step}")
si_time = time.time()
sample, sample_idxs = self.data_sampler.sample_data(k=k)
mc_gens = self.mc_sample(sample_idxs, model_path, n)
unc_scores = self.rank_data(mc_gens, n)
selected_samples, selected_scores = self.select_data(unc_scores, s)
selected_idxs = [sample_idxs[i] for i in selected_samples]
self.data_sampler.remove_samples(selected_idxs)
self.write_samples(
sample.select(selected_samples),
selected_samples,
selected_idxs,
labeled_path,
scores=unc_scores)
self.train_step(labeled_path, model_path, eval_path, epochs)
ei_time = time.time()
logger.info(f"Finished learning step {step}: {ei_time - si_time} sec.")
class RandomActiveSum(ActiveSum):
"""
Random active summarization module.
At each learning step we randomly select a subset to be labelled.
The labelled set L is extended with the selected subset at each step
and a new model is trained on the extended labelled set.
Example:
```
active_learner = RandomActiveSum(
train_sampler,
device='gpu',
doc_col='document',
sum_col='summary,
seed=100,
py_module='as_learn.py',
init_model='google/pegasus-large',
source_len=128,
target_len=16,
val_samples=100,
batch_size=6,
beams=4,
lr=1e-4,
save_step=100,
save_limit=1,
metric='rouge_1',
)
active_learner.init_learner(
init_labeled=20,
model_path='path_to_model/model',
labeled_path='path_to_data',
eval_path='path_to_data/validation.json',
epochs=10)
active_learner.learn(
steps=10,
model_path='path_to_model/model',
labeled_path='path_to_data',
k=100, s=10,
eval_path='path_to_data/validation.json',
epochs=10)
```
"""
def __init__(self, data_sampler, device, **kwargs):
super(RandomActiveSum, self).__init__(data_sampler, device, **kwargs)
def learn(self, steps, model_path, labeled_path, k, s, eval_path, epochs):
"""Learning strategy"""
for i in range(steps):
self.learning_step(model_path, labeled_path, k, s, eval_path=eval_path, epochs=epochs, step=i)
def learning_step(self, model_path, labeled_path, k, s, eval_path, epochs, step=0):
"""A single learning step for active summarization
1) select a pool of unlabeled examples
2) randomly add S examples from the unlabelled pool to the labelled set
5) train on the extended labelled set"""
logger.info(f"Learning step {step}")
si_time = time.time()
sample, sample_idxs = self.data_sampler.sample_data(k=k)
selected_idxs = sample_idxs[:s]
selected_samples = list(range(s))
self.data_sampler.remove_samples(selected_idxs)
self.write_samples(sample.select(selected_samples), selected_samples, selected_idxs, labeled_path)
self.train_step(labeled_path, model_path, eval_path, epochs)
ei_time = time.time()
logger.info(f"Finished learning step {step}: {ei_time - si_time} sec.")
class DataSampler:
"""Implements random sampling with and without replacement on a dataset
Example:
```
train_sampler = DataSampler(dataset, split="train")
sample, sample_idxs = train_sampler.sample_data(k=100)
selected_idxs = sample_idxs[:10]
train_sampler.remove_samples(selected_idxs)
remaining_sample_idxs = train_sampler.get_available_samples
new_sample, new_sample_idxs = train_sampler.sample_data(k=100) # removed samples cannot be resampled
```
"""
def __init__(
self,
dataset,
split,
):
self.split = split
self.dataset = dataset
self.num_samples = self.dataset.info.splits[split].num_examples
self.removed = []
def sample_data(self, k):
"""Randomly select K samples from the remaining dataset"""
available_samples = self.get_available_samples()
random.shuffle(available_samples)
sampled_idxs = available_samples[:k]
sample_data = self.dataset.select(sampled_idxs)
return sample_data, sampled_idxs
def remove_samples(self, samples):
"""Remove a subset of samples (the removed can no longer be sampled)"""
self.removed += samples
def get_available_samples(self):
"""Get the available samples excluding samples that have been removed"""
return [si for si in range(0, self.num_samples - 1) if si not in self.removed] | [
"logging.getLogger",
"linecache.clearcache",
"os.path.exists",
"random.shuffle",
"src.common.loaders.create_loader",
"src.bayesian_summarization.bleu.analyze_generation_bleuvar",
"os.path.join",
"src.bayesian_summarization.bayesian.BayesianSummarizer",
"numpy.array",
"os.mkdir",
"gc.collect",
... | [((402, 429), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (419, 429), False, 'import logging\n'), ((561, 585), 'json.dump', 'json.dump', (['metrics', 'hist'], {}), '(metrics, hist)\n', (570, 585), False, 'import json\n'), ((1686, 1726), 'os.path.join', 'os.path.join', (['labeled_path', '"""train.json"""'], {}), "(labeled_path, 'train.json')\n", (1698, 1726), False, 'import os\n'), ((1749, 2728), 'src.summarization.sum_base.TrainerSummarizer', 'TrainerSummarizer', ([], {'model_name_or_path': 'self.init_model', 'tokenizer_name': 'self.init_model', 'train_file': 'train_path', 'validation_file': 'eval_path', 'text_column': 'self.doc_col', 'summary_column': 'self.sum_col', 'output_dir': 'model_path', 'logging_dir': 'f"""{model_path}/logs"""', 'seed': 'self.seed', 'per_device_train_batch_size': 'self.batch_size', 'per_device_eval_batch_size': 'self.batch_size', 'overwrite_output_dir': '(True)', 'max_val_samples': 'self.val_samples', 'max_test_samples': 'self.test_samples', 'learning_rate': 'self.lr', 'adafactor': '(True)', 'max_source_length': 'self.source_len', 'max_target_length': 'self.target_len', 'val_max_target_length': 'self.target_len', 'pad_to_max_length': '(True)', 'num_beams': 'self.beams', 'num_train_epochs': 'epochs', 'save_steps': 'self.save_step', 'save_total_limit': 'self.save_limit', 'load_best_model_at_end': '(True)', 'evaluation_strategy': '"""epoch"""', 'metric_for_best_model': 'self.metric', 'greater_is_better': '(True)', 'do_train': '(True)', 'do_eval': '(True)', 'predict_with_generate': '(True)', 'do_predict': '(False)'}), "(model_name_or_path=self.init_model, tokenizer_name=self.\n init_model, train_file=train_path, validation_file=eval_path,\n text_column=self.doc_col, summary_column=self.sum_col, output_dir=\n model_path, logging_dir=f'{model_path}/logs', seed=self.seed,\n per_device_train_batch_size=self.batch_size, per_device_eval_batch_size\n =self.batch_size, overwrite_output_dir=True, max_val_samples=self.\n val_samples, max_test_samples=self.test_samples, learning_rate=self.lr,\n adafactor=True, max_source_length=self.source_len, max_target_length=\n self.target_len, val_max_target_length=self.target_len,\n pad_to_max_length=True, num_beams=self.beams, num_train_epochs=epochs,\n save_steps=self.save_step, save_total_limit=self.save_limit,\n load_best_model_at_end=True, evaluation_strategy='epoch',\n metric_for_best_model=self.metric, greater_is_better=True, do_train=\n True, do_eval=True, predict_with_generate=True, do_predict=False)\n", (1766, 2728), False, 'from src.summarization.sum_base import TrainerSummarizer\n'), ((3220, 3232), 'gc.collect', 'gc.collect', ([], {}), '()\n', (3230, 3232), False, 'import gc\n'), ((3241, 3265), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (3263, 3265), False, 'import torch\n'), ((4460, 4482), 'linecache.clearcache', 'linecache.clearcache', ([], {}), '()\n', (4480, 4482), False, 'import linecache\n'), ((5046, 5085), 'os.path.join', 'os.path.join', (['out_path', '"""metadata.json"""'], {}), "(out_path, 'metadata.json')\n", (5058, 5085), False, 'import os\n'), ((5109, 5145), 'os.path.join', 'os.path.join', (['out_path', '"""train.json"""'], {}), "(out_path, 'train.json')\n", (5121, 5145), False, 'import os\n'), ((5168, 5209), 'os.path.join', 'os.path.join', (['out_path', '"""all_scores.json"""'], {}), "(out_path, 'all_scores.json')\n", (5180, 5209), False, 'import os\n'), ((5900, 5939), 'json.dump', 'json.dump', (["{'all_scores': scores}", 'entf'], {}), "({'all_scores': scores}, entf)\n", (5909, 5939), False, 'import json\n'), ((6853, 6875), 'linecache.clearcache', 'linecache.clearcache', ([], {}), '()\n', (6873, 6875), False, 'import linecache\n'), ((7014, 7057), 'os.path.join', 'os.path.join', (['labeled_path', '"""metadata.json"""'], {}), "(labeled_path, 'metadata.json')\n", (7026, 7057), False, 'import os\n'), ((9471, 9564), 'src.common.loaders.create_loader', 'create_loader', (['self.data_sampler.dataset'], {'batch_size': 'self.batch_size', 'sample': 'sample_idxs'}), '(self.data_sampler.dataset, batch_size=self.batch_size, sample\n =sample_idxs)\n', (9484, 9564), False, 'from src.common.loaders import load_model, create_loader\n'), ((9590, 9780), 'src.bayesian_summarization.bayesian.BayesianSummarizer', 'BayesianSummarizer', ([], {'model_name_or_path': 'model_path', 'tokenizer_name': 'self.init_model', 'text_column': 'self.doc_col', 'seed': 'self.seed', 'max_source_length': 'self.source_len', 'num_beams': 'self.beams'}), '(model_name_or_path=model_path, tokenizer_name=self.\n init_model, text_column=self.doc_col, seed=self.seed, max_source_length\n =self.source_len, num_beams=self.beams)\n', (9608, 9780), False, 'from src.bayesian_summarization.bayesian import BayesianSummarizer\n'), ((10044, 10056), 'gc.collect', 'gc.collect', ([], {}), '()\n', (10054, 10056), False, 'import gc\n'), ((10065, 10089), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (10087, 10089), False, 'import torch\n'), ((10582, 10598), 'numpy.array', 'np.array', (['scores'], {}), '(scores)\n', (10590, 10598), True, 'import numpy as np\n'), ((10718, 10742), 'numpy.random.shuffle', 'np.random.shuffle', (['top_s'], {}), '(top_s)\n', (10735, 10742), True, 'import numpy as np\n'), ((11373, 11384), 'time.time', 'time.time', ([], {}), '()\n', (11382, 11384), False, 'import time\n'), ((12034, 12045), 'time.time', 'time.time', ([], {}), '()\n', (12043, 12045), False, 'import time\n'), ((14083, 14094), 'time.time', 'time.time', ([], {}), '()\n', (14092, 14094), False, 'import time\n'), ((14495, 14506), 'time.time', 'time.time', ([], {}), '()\n', (14504, 14506), False, 'import time\n'), ((15496, 15529), 'random.shuffle', 'random.shuffle', (['available_samples'], {}), '(available_samples)\n', (15510, 15529), False, 'import random\n'), ((494, 536), 'os.path.join', 'os.path.join', (['out_path', 'f"""{filename}.json"""'], {}), "(out_path, f'{filename}.json')\n", (506, 536), False, 'import os\n'), ((4028, 4071), 'os.path.join', 'os.path.join', (['model_path', '"""best_checkpoint"""'], {}), "(model_path, 'best_checkpoint')\n", (4040, 4071), False, 'import os\n'), ((5558, 5582), 'json.dump', 'json.dump', (['out_json', 'mdf'], {}), '(out_json, mdf)\n', (5567, 5582), False, 'import json\n'), ((5827, 5861), 'json.dump', 'json.dump', (['train_sample_json', 'outf'], {}), '(train_sample_json, outf)\n', (5836, 5861), False, 'import json\n'), ((10340, 10379), 'src.bayesian_summarization.bleu.analyze_generation_bleuvar', 'analyze_generation_bleuvar', (['gen_list', 'n'], {}), '(gen_list, n)\n', (10366, 10379), False, 'from src.bayesian_summarization.bleu import analyze_generation_bleuvar\n'), ((4091, 4127), 'os.path.exists', 'os.path.exists', (['best_checkpoint_path'], {}), '(best_checkpoint_path)\n', (4105, 4127), False, 'import os\n'), ((4145, 4175), 'os.mkdir', 'os.mkdir', (['best_checkpoint_path'], {}), '(best_checkpoint_path)\n', (4153, 4175), False, 'import os\n'), ((4201, 4246), 'os.path.join', 'os.path.join', (['model_path', '"""pytorch_model.bin"""'], {}), "(model_path, 'pytorch_model.bin')\n", (4213, 4246), False, 'import os\n')] |
import cv2
from GazeTracking.gaze_tracking import GazeTracking
import dlib
import os
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import os
import time
c = 0
class VideoDetector():
def __init__(self, detection_model_path, emotion_model_path, img_dir=None):
self.gaze = GazeTracking()
self.face_detection = cv2.CascadeClassifier(detection_model_path)
self.emotion_classifier = load_model(emotion_model_path, compile=False)
self.emotions = ("angry" ,"disgust", "scared", "happy", "sad", "surprised", "neutral")
self.img_dir = img_dir
def extract_images(self, video_path, freq=5):
vidcap = cv2.VideoCapture(video_path)
success, image = vidcap.read()
count = 0
video_length = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
print(video_length)
while count < video_length:
success, image = vidcap.read()
print (count, success)
if success and count % freq == 0:
cv2.imwrite(self.img_dir + "\\frame%d.jpg" % count, image)
count += 1
return True
def _make_img(self, f):
global c
self.gaze.refresh(f)
new_frame = self.gaze.annotated_frame()
text, coord_left, coord_right = self._detect_gaze()
emo_texts, max_ind = self._detect_emotions(f)
cv2.putText(new_frame, text, (60, 60), cv2.FONT_HERSHEY_DUPLEX, 0.7, (0, 0, 255), 2)
for line, y in zip((coord_left, coord_right), (100, 130)):
print(line)
cv2.putText(new_frame, line, (60, y), cv2.FONT_HERSHEY_DUPLEX, 0.8, (0, 0, 0), 2)
for i in range(len(emo_texts)):
color = (0,0,0)
if i == max_ind:
color = (0,0,255)
cv2.putText(new_frame, emo_texts[i], (60, 170+30*i), cv2.FONT_HERSHEY_DUPLEX, 0.65, color, 2)
print(emo_texts[i])
cv2.imshow("annotated", new_frame)
def annotate_imgs(self):
if self.img_dir:
for f in os.listdir(self.img_dir):
print(f)
im = os.path.join(self.img_dir, frame)
f = cv2.imread(im)
self._make_img(f)
if cv2.waitKey(1) == 27:
break
else:
#cv2.namedWindow("online")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
self._make_img(frame)
rval, frame = vc.read()
#time.sleep(1)
if cv2.waitKey(1) == 27:
break
vc.release()
cv2.destroyAllWindows()
def _detect_gaze(self):
text = ""
if self.gaze.is_right():
text = "Looking right"
elif self.gaze.is_left():
text = "Looking left"
elif self.gaze.is_center():
text = "Looking center"
coord_left = f'left eye: {self.gaze.pupil_left_coords()}'
coord_right = f'right eye: {self.gaze.pupil_right_coords()}'
#ratio_ver = f'vertical ratio: {round(float(self.gaze.vertical_ratio()),3)}'
#ratio_hor = f'horizontal ratio: {round(float(self.gaze.horizontal_ratio()),3)}'
return (text, coord_left, coord_right)
def _detect_emotions(self, frame):
emo_frame = imutils.resize(frame, width=300)
gray = cv2.cvtColor(emo_frame, cv2.COLOR_BGR2GRAY)
faces = self.face_detection.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,minSize=(30,30),flags=cv2.CASCADE_SCALE_IMAGE)
emo_texts = []
if len(faces) > 0:
faces = sorted(faces, reverse=True, key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
roi = gray[fY:fY + fH, fX:fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype("float") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis=0)
preds = self.emotion_classifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = self.emotions[preds.argmax()]
max_ind = np.argmax(preds)
for (i, (emotion, prob)) in enumerate(zip(self.emotions, preds)):
text = f'{emotion}, {round(prob*100,3)}'
emo_texts.append(text)
else:
emo_texts = [f'{emotion} ???' for emotion in self.emotions]
max_ind = None
return (emo_texts, max_ind)
| [
"keras.preprocessing.image.img_to_array",
"cv2.imshow",
"cv2.destroyAllWindows",
"cv2.CascadeClassifier",
"os.listdir",
"GazeTracking.gaze_tracking.GazeTracking",
"numpy.max",
"cv2.waitKey",
"numpy.argmax",
"cv2.putText",
"cv2.cvtColor",
"cv2.resize",
"cv2.imread",
"cv2.imwrite",
"keras.... | [((375, 389), 'GazeTracking.gaze_tracking.GazeTracking', 'GazeTracking', ([], {}), '()\n', (387, 389), False, 'from GazeTracking.gaze_tracking import GazeTracking\n'), ((420, 463), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['detection_model_path'], {}), '(detection_model_path)\n', (441, 463), False, 'import cv2\n'), ((498, 543), 'keras.models.load_model', 'load_model', (['emotion_model_path'], {'compile': '(False)'}), '(emotion_model_path, compile=False)\n', (508, 543), False, 'from keras.models import load_model\n'), ((738, 766), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_path'], {}), '(video_path)\n', (754, 766), False, 'import cv2\n'), ((1510, 1598), 'cv2.putText', 'cv2.putText', (['new_frame', 'text', '(60, 60)', 'cv2.FONT_HERSHEY_DUPLEX', '(0.7)', '(0, 0, 255)', '(2)'], {}), '(new_frame, text, (60, 60), cv2.FONT_HERSHEY_DUPLEX, 0.7, (0, 0,\n 255), 2)\n', (1521, 1598), False, 'import cv2\n'), ((2108, 2142), 'cv2.imshow', 'cv2.imshow', (['"""annotated"""', 'new_frame'], {}), "('annotated', new_frame)\n", (2118, 2142), False, 'import cv2\n'), ((2961, 2984), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2982, 2984), False, 'import cv2\n'), ((3675, 3707), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(300)'}), '(frame, width=300)\n', (3689, 3707), False, 'import imutils\n'), ((3723, 3766), 'cv2.cvtColor', 'cv2.cvtColor', (['emo_frame', 'cv2.COLOR_BGR2GRAY'], {}), '(emo_frame, cv2.COLOR_BGR2GRAY)\n', (3735, 3766), False, 'import cv2\n'), ((1698, 1784), 'cv2.putText', 'cv2.putText', (['new_frame', 'line', '(60, y)', 'cv2.FONT_HERSHEY_DUPLEX', '(0.8)', '(0, 0, 0)', '(2)'], {}), '(new_frame, line, (60, y), cv2.FONT_HERSHEY_DUPLEX, 0.8, (0, 0, \n 0), 2)\n', (1709, 1784), False, 'import cv2\n'), ((1961, 2063), 'cv2.putText', 'cv2.putText', (['new_frame', 'emo_texts[i]', '(60, 170 + 30 * i)', 'cv2.FONT_HERSHEY_DUPLEX', '(0.65)', 'color', '(2)'], {}), '(new_frame, emo_texts[i], (60, 170 + 30 * i), cv2.\n FONT_HERSHEY_DUPLEX, 0.65, color, 2)\n', (1972, 2063), False, 'import cv2\n'), ((2227, 2251), 'os.listdir', 'os.listdir', (['self.img_dir'], {}), '(self.img_dir)\n', (2237, 2251), False, 'import os\n'), ((2539, 2558), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (2555, 2558), False, 'import cv2\n'), ((4154, 4179), 'cv2.resize', 'cv2.resize', (['roi', '(64, 64)'], {}), '(roi, (64, 64))\n', (4164, 4179), False, 'import cv2\n'), ((4244, 4261), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['roi'], {}), '(roi)\n', (4256, 4261), False, 'from keras.preprocessing.image import img_to_array\n'), ((4280, 4307), 'numpy.expand_dims', 'np.expand_dims', (['roi'], {'axis': '(0)'}), '(roi, axis=0)\n', (4294, 4307), True, 'import numpy as np\n'), ((4403, 4416), 'numpy.max', 'np.max', (['preds'], {}), '(preds)\n', (4409, 4416), True, 'import numpy as np\n'), ((4490, 4506), 'numpy.argmax', 'np.argmax', (['preds'], {}), '(preds)\n', (4499, 4506), True, 'import numpy as np\n'), ((1115, 1173), 'cv2.imwrite', 'cv2.imwrite', (["(self.img_dir + '\\\\frame%d.jpg' % count)", 'image'], {}), "(self.img_dir + '\\\\frame%d.jpg' % count, image)\n", (1126, 1173), False, 'import cv2\n'), ((2299, 2332), 'os.path.join', 'os.path.join', (['self.img_dir', 'frame'], {}), '(self.img_dir, frame)\n', (2311, 2332), False, 'import os\n'), ((2353, 2367), 'cv2.imread', 'cv2.imread', (['im'], {}), '(im)\n', (2363, 2367), False, 'import cv2\n'), ((2421, 2435), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2432, 2435), False, 'import cv2\n'), ((2878, 2892), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2889, 2892), False, 'import cv2\n')] |
from aiida.orm.data.structure import StructureData
from aiida.orm.data.parameter import ParameterData
from aiida.orm.data.base import Int, Float, Str, Bool
from aiida.orm.data.singlefile import SinglefileData
from aiida.orm.code import Code
from aiida.work.workchain import WorkChain, ToContext, Calc, while_
from aiida.work.run import submit
from aiida_cp2k.calculations import Cp2kCalculation
import tempfile
import shutil
import itertools
import numpy as np
class SlabGeoOptWorkChain(WorkChain):
@classmethod
def define(cls, spec):
super(SlabGeoOptWorkChain, cls).define(spec)
spec.input("cp2k_code", valid_type=Code)
spec.input("structure", valid_type=StructureData)
spec.input("max_force", valid_type=Float, default=Float(0.001))
spec.input("calc_type", valid_type=Str, default=Str('Mixed DFTB'))
spec.input("vdw_switch", valid_type=Bool, default=Bool(False))
spec.input("mgrid_cutoff", valid_type=Int, default=Int(600))
spec.input("fixed_atoms", valid_type=Str, default=Str(''))
spec.input("center_switch", valid_type=Bool, default=Bool(False))
spec.input("num_machines", valid_type=Int, default=Int(1))
spec.outline(
cls.run_geopt,
while_(cls.not_converged)(
cls.run_geopt_again
),
)
spec.dynamic_output()
# ==========================================================================
def not_converged(self):
return self.ctx.geo_opt.res.exceeded_walltime
# ==========================================================================
def run_geopt(self):
self.report("Running CP2K geometry optimization")
inputs = self.build_calc_inputs(self.inputs.structure,
self.inputs.cp2k_code,
self.inputs.max_force,
self.inputs.calc_type,
self.inputs.mgrid_cutoff,
self.inputs.vdw_switch,
self.inputs.fixed_atoms,
self.inputs.center_switch,
self.inputs.num_machines,
None)
self.report("inputs: "+str(inputs))
future = submit(Cp2kCalculation.process(), **inputs)
return ToContext(geo_opt=Calc(future))
# ==========================================================================
def run_geopt_again(self):
# TODO: make this nicer.
inputs_new = self.build_calc_inputs(self.inputs.structure,
self.inputs.cp2k_code,
self.inputs.max_force,
self.inputs.calc_type,
self.inputs.mgrid_cutoff,
self.inputs.vdw_switch,
self.inputs.fixed_atoms,
self.inputs.center_switch,
self.inputs.num_machines,
self.ctx.geo_opt.out.remote_folder)
self.report("inputs (restart): "+str(inputs_new))
future_new = submit(Cp2kCalculation.process(), **inputs_new)
return ToContext(geo_opt=Calc(future_new))
# ==========================================================================
@classmethod
def build_calc_inputs(cls, structure, code, max_force, calc_type,
mgrid_cutoff, vdw_switch, fixed_atoms, center_switch,
num_machines, remote_calc_folder):
inputs = {}
inputs['_label'] = "slab_geo_opt"
inputs['code'] = code
inputs['file'] = {}
# make sure we're dealing with a metal slab
# and figure out which one
atoms = structure.get_ase() # slow
found_metal = False
for el in [29, 47, 79]:
if len(np.argwhere(atoms.numbers == el)) == 0:
continue
first_slab_atom = np.argwhere(atoms.numbers == el)[0, 0] + 1
is_H = atoms.numbers[first_slab_atom-1:] == 1
is_Metal = atoms.numbers[first_slab_atom-1:] == el
if np.all(np.logical_or(is_H, is_Metal)):
found_metal = el
break
if not found_metal:
raise Exception("Structure is not a proper slab.")
if found_metal == 79:
metal_atom = 'Au'
elif found_metal == 47:
metal_atom = 'Ag'
elif found_metal == 29:
metal_atom = 'Cu'
# structure
molslab_f, mol_f = cls.mk_coord_files(atoms, first_slab_atom)
inputs['file']['molslab_coords'] = molslab_f
inputs['file']['mol_coords'] = mol_f
# Au potential
pot_f = SinglefileData(file='/project/apps/surfaces/slab/Au.pot')
inputs['file']['au_pot'] = pot_f
# parameters
cell_abc = "%f %f %f" % (atoms.cell[0, 0],
atoms.cell[1, 1],
atoms.cell[2, 2])
remote_computer = code.get_remote_computer()
machine_cores = remote_computer.get_default_mpiprocs_per_machine()
if calc_type == 'Mixed DFTB':
walltime = 18000
else:
walltime = 86000
inp = cls.get_cp2k_input(cell_abc,
first_slab_atom,
len(atoms),
max_force,
calc_type,
mgrid_cutoff,
vdw_switch,
machine_cores*num_machines,
fixed_atoms,
walltime*0.97,
center_switch,
metal_atom)
if remote_calc_folder is not None:
inp['EXT_RESTART'] = {
'RESTART_FILE_NAME': './parent_calc/aiida-1.restart'
}
inputs['parent_folder'] = remote_calc_folder
inputs['parameters'] = ParameterData(dict=inp)
# settings
settings = ParameterData(dict={'additional_retrieve_list': ['*.pdb']})
inputs['settings'] = settings
# resources
inputs['_options'] = {
"resources": {"num_machines": num_machines},
"max_wallclock_seconds": walltime,
}
return inputs
# ==========================================================================
@classmethod
def mk_coord_files(cls, atoms, first_slab_atom):
mol = atoms[:first_slab_atom-1]
tmpdir = tempfile.mkdtemp()
molslab_fn = tmpdir + '/mol_on_slab.xyz'
mol_fn = tmpdir + '/mol.xyz'
atoms.write(molslab_fn)
mol.write(mol_fn)
molslab_f = SinglefileData(file=molslab_fn)
mol_f = SinglefileData(file=mol_fn)
shutil.rmtree(tmpdir)
return molslab_f, mol_f
# ==========================================================================
@classmethod
def get_cp2k_input(cls, cell_abc, first_slab_atom, last_slab_atom,
max_force, calc_type, mgrid_cutoff, vdw_switch,
machine_cores, fixed_atoms, walltime, center_switch,
metal_atom):
inp = {
'GLOBAL': {
'RUN_TYPE': 'GEO_OPT',
'WALLTIME': '%d' % walltime,
'PRINT_LEVEL': 'LOW',
'EXTENDED_FFT_LENGTHS': ''
},
'MOTION': cls.get_motion(first_slab_atom, last_slab_atom,
max_force, fixed_atoms),
'FORCE_EVAL': [],
}
if calc_type == 'Mixed DFTB':
inp['FORCE_EVAL'] = [cls.force_eval_mixed(cell_abc,
first_slab_atom,
last_slab_atom,
machine_cores),
cls.force_eval_fist(cell_abc, metal_atom),
cls.get_force_eval_qs_dftb(cell_abc,
vdw_switch)]
inp['MULTIPLE_FORCE_EVALS'] = {
'FORCE_EVAL_ORDER': '2 3',
'MULTIPLE_SUBSYS': 'T'
}
elif calc_type == 'Mixed DFT':
inp['FORCE_EVAL'] = [cls.force_eval_mixed(cell_abc,
first_slab_atom,
last_slab_atom,
machine_cores),
cls.force_eval_fist(cell_abc, metal_atom),
cls.get_force_eval_qs_dft(cell_abc,
mgrid_cutoff,
vdw_switch,
center_switch,
metal_atom)]
inp['MULTIPLE_FORCE_EVALS'] = {
'FORCE_EVAL_ORDER': '2 3',
'MULTIPLE_SUBSYS': 'T'
}
elif calc_type == 'Full DFT':
inp['FORCE_EVAL'] = [cls.get_force_eval_qs_dft(
cell_abc,
mgrid_cutoff,
vdw_switch,
center_switch,
metal_atom,
topology='mol_on_slab.xyz'
)]
return inp
# ==========================================================================
@classmethod
def get_motion(cls, first_slab_atom, last_slab_atom,
max_force, fixed_atoms):
motion = {
'CONSTRAINT': {
'FIXED_ATOMS': {
'LIST': '%s' % (fixed_atoms),
}
},
'GEO_OPT': {
'MAX_FORCE': '%f' % (max_force),
'MAX_ITER': '5000'
},
}
return motion
# ==========================================================================
@classmethod
def force_eval_mixed(cls, cell_abc, first_slab_atom, last_slab_atom,
machine_cores):
first_mol_atom = 1
last_mol_atom = first_slab_atom - 1
mol_delim = (first_mol_atom, last_mol_atom)
slab_delim = (first_slab_atom, last_slab_atom)
force_eval = {
'METHOD': 'MIXED',
'MIXED': {
'MIXING_TYPE': 'GENMIX',
'GROUP_PARTITION': '2 %d' % (machine_cores-2),
'GENERIC': {
'ERROR_LIMIT': '1.0E-10',
'MIXING_FUNCTION': 'E1+E2',
'VARIABLES': 'E1 E2'
},
'MAPPING': {
'FORCE_EVAL_MIXED': {
'FRAGMENT':
[{'_': '1', ' ': '%d %d' % mol_delim},
{'_': '2', ' ': '%d %d' % slab_delim}],
},
'FORCE_EVAL': [{'_': '1', 'DEFINE_FRAGMENTS': '1 2'},
{'_': '2', 'DEFINE_FRAGMENTS': '1'}],
}
},
'SUBSYS': {
'CELL': {'ABC': cell_abc},
'TOPOLOGY': {
'COORD_FILE_NAME': 'mol_on_slab.xyz',
'COORDINATE': 'XYZ',
'CONNECTIVITY': 'OFF',
}
}
}
return force_eval
# ==========================================================================
@classmethod
def force_eval_fist(cls, cell_abc, metal_atom):
ff = {
'SPLINE': {
'EPS_SPLINE': '1.30E-5',
'EMAX_SPLINE': '0.8',
},
'CHARGE': [],
'NONBONDED': {
'GENPOT': [],
'LENNARD-JONES': [],
'EAM': {
'ATOMS': 'Au Au',
'PARM_FILE_NAME': 'Au.pot',
},
},
}
element_list = ['H', 'C', 'O', 'N', 'S']
for x in element_list + [metal_atom]:
ff['CHARGE'].append({'ATOM': x, 'CHARGE': 0.0})
genpot_fun = 'A*exp(-av*r)+B*exp(-ac*r)-C/(r^6)/( 1+exp(-20*(r/R-1)) )'
genpot_val = {
'H': '0.878363 1.33747 24.594164 2.206825 32.23516124268186181470 5.84114',
'else': '4.13643 1.33747 115.82004 2.206825 113.96850410723008483218 5.84114'
}
for x in element_list:
ff['NONBONDED']['GENPOT'].append(
{'ATOMS': metal_atom+' ' + x,
'FUNCTION': genpot_fun,
'VARIABLES': 'r',
'PARAMETERS': 'A av B ac C R',
'VALUES': genpot_val[x] if x in genpot_val else genpot_val['else'],
'RCUT': '15'}
)
for x in itertools.combinations_with_replacement(element_list, 2):
ff['NONBONDED']['LENNARD-JONES'].append(
{'ATOMS': " ".join(x),
'EPSILON': '0.0',
'SIGMA': '3.166',
'RCUT': '15'}
)
force_eval = {
'METHOD': 'FIST',
'MM': {
'FORCEFIELD': ff,
'POISSON': {
'EWALD': {
'EWALD_TYPE': 'none',
},
},
},
'SUBSYS': {
'CELL': {
'ABC': cell_abc,
},
'TOPOLOGY': {
'COORD_FILE_NAME': 'mol_on_slab.xyz',
'COORDINATE': 'XYZ',
'CONNECTIVITY': 'OFF',
},
},
}
return force_eval
# ==========================================================================
@classmethod
def get_force_eval_qs_dftb(cls, cell_abc, vdw_switch):
force_eval = {
'METHOD': 'Quickstep',
'DFT': {
'QS': {
'METHOD': 'DFTB',
'EXTRAPOLATION': 'ASPC',
'EXTRAPOLATION_ORDER': '3',
'DFTB': {
'SELF_CONSISTENT': 'T',
'DISPERSION': '%s' % (str(vdw_switch)[0]),
'ORTHOGONAL_BASIS': 'F',
'DO_EWALD': 'F',
'PARAMETER': {
'PARAM_FILE_PATH': 'DFTB/scc',
'PARAM_FILE_NAME': 'scc_parameter',
'UFF_FORCE_FIELD': '../uff_table',
},
},
},
'SCF': {
'MAX_SCF': '30',
'SCF_GUESS': 'RESTART',
'EPS_SCF': '1.0E-6',
'OT': {
'PRECONDITIONER': 'FULL_SINGLE_INVERSE',
'MINIMIZER': 'CG',
},
'OUTER_SCF': {
'MAX_SCF': '20',
'EPS_SCF': '1.0E-6',
},
'PRINT': {
'RESTART': {
'EACH': {
'QS_SCF': '0',
'GEO_OPT': '1',
},
'ADD_LAST': 'NUMERIC',
'FILENAME': 'RESTART'
},
'RESTART_HISTORY': {'_': 'OFF'}
}
}
},
'SUBSYS': {
'CELL': {'ABC': cell_abc},
'TOPOLOGY': {
'COORD_FILE_NAME': 'mol.xyz',
'COORDINATE': 'xyz'
}
}
}
return force_eval
# ==========================================================================
@classmethod
def get_force_eval_qs_dft(cls, cell_abc, mgrid_cutoff, vdw_switch, center_switch,
metal_atom, topology='mol.xyz'):
force_eval = {
'METHOD': 'Quickstep',
'DFT': {
'BASIS_SET_FILE_NAME': 'BASIS_MOLOPT',
'POTENTIAL_FILE_NAME': 'POTENTIAL',
'RESTART_FILE_NAME': './parent_calc/aiida-RESTART.wfn',
'QS': {
'METHOD': 'GPW',
'EXTRAPOLATION': 'ASPC',
'EXTRAPOLATION_ORDER': '3',
'EPS_DEFAULT': '1.0E-14',
},
'MGRID': {
'CUTOFF': '%d' % (mgrid_cutoff),
'NGRIDS': '5',
},
'SCF': {
'MAX_SCF': '20',
'SCF_GUESS': 'RESTART',
'EPS_SCF': '1.0E-7',
'OT': {
'PRECONDITIONER': 'FULL_SINGLE_INVERSE',
'MINIMIZER': 'CG',
},
'OUTER_SCF': {
'MAX_SCF': '15',
'EPS_SCF': '1.0E-7',
},
'PRINT': {
'RESTART': {
'EACH': {
'QS_SCF': '0',
'GEO_OPT': '1',
},
'ADD_LAST': 'NUMERIC',
'FILENAME': 'RESTART'
},
'RESTART_HISTORY': {'_': 'OFF'}
}
},
'XC': {
'XC_FUNCTIONAL': {'_': 'PBE'},
},
},
'SUBSYS': {
'CELL': {'ABC': cell_abc},
'TOPOLOGY': {
'COORD_FILE_NAME': topology,
'COORDINATE': 'xyz',
},
'KIND': [],
}
}
if vdw_switch:
force_eval['DFT']['XC']['VDW_POTENTIAL'] = {
'DISPERSION_FUNCTIONAL': 'PAIR_POTENTIAL',
'PAIR_POTENTIAL': {
'TYPE': 'DFTD3',
'CALCULATE_C9_TERM': '.TRUE.',
'PARAMETER_FILE_NAME': 'dftd3.dat',
'REFERENCE_FUNCTIONAL': 'PBE',
'R_CUTOFF': '15',
}
}
if center_switch:
force_eval['SUBSYS']['TOPOLOGY']['CENTER_COORDINATES'] = {'_': ''},
force_eval['SUBSYS']['KIND'].append({
'_': metal_atom,
'BASIS_SET': 'DZVP-MOLOPT-SR-GTH',
'POTENTIAL': 'GTH-PBE-q11'
})
force_eval['SUBSYS']['KIND'].append({
'_': 'C',
'BASIS_SET': 'TZV2P-MOLOPT-GTH',
'POTENTIAL': 'GTH-PBE-q4'
})
force_eval['SUBSYS']['KIND'].append({
'_': 'Br',
'BASIS_SET': 'DZVP-MOLOPT-SR-GTH',
'POTENTIAL': 'GTH-PBE-q7'
})
force_eval['SUBSYS']['KIND'].append({
'_': 'B',
'BASIS_SET': 'DZVP-MOLOPT-SR-GTH',
'POTENTIAL': 'GTH-PBE-q3'
})
force_eval['SUBSYS']['KIND'].append({
'_': 'O',
'BASIS_SET': 'TZV2P-MOLOPT-GTH',
'POTENTIAL': 'GTH-PBE-q6'
})
force_eval['SUBSYS']['KIND'].append({
'_': 'S',
'BASIS_SET': 'TZV2P-MOLOPT-GTH',
'POTENTIAL': 'GTH-PBE-q6'
})
force_eval['SUBSYS']['KIND'].append({
'_': 'N',
'BASIS_SET': 'TZV2P-MOLOPT-GTH',
'POTENTIAL': 'GTH-PBE-q5'
})
force_eval['SUBSYS']['KIND'].append({
'_': 'H',
'BASIS_SET': 'TZV2P-MOLOPT-GTH',
'POTENTIAL': 'GTH-PBE-q1'
})
return force_eval
# ==========================================================================
def _check_prev_calc(self, prev_calc):
error = None
if prev_calc.get_state() != 'FINISHED':
error = "Previous calculation in state: "+prev_calc.get_state()
elif "aiida.out" not in prev_calc.out.retrieved.get_folder_list():
error = "Previous calculation did not retrive aiida.out"
else:
fn = prev_calc.out.retrieved.get_abs_path("aiida.out")
content = open(fn).read()
if "exceeded requested execution time" in content:
error = "Previous calculation's aiida.out exceeded walltime"
if error:
self.report("ERROR: "+error)
self.abort(msg=error)
raise Exception(error)
# EOF
| [
"aiida_cp2k.calculations.Cp2kCalculation.process",
"aiida.orm.data.base.Bool",
"aiida.work.workchain.Calc",
"aiida.orm.data.parameter.ParameterData",
"aiida.orm.data.base.Int",
"numpy.logical_or",
"aiida.orm.data.singlefile.SinglefileData",
"numpy.argwhere",
"tempfile.mkdtemp",
"shutil.rmtree",
... | [((5048, 5105), 'aiida.orm.data.singlefile.SinglefileData', 'SinglefileData', ([], {'file': '"""/project/apps/surfaces/slab/Au.pot"""'}), "(file='/project/apps/surfaces/slab/Au.pot')\n", (5062, 5105), False, 'from aiida.orm.data.singlefile import SinglefileData\n'), ((6385, 6408), 'aiida.orm.data.parameter.ParameterData', 'ParameterData', ([], {'dict': 'inp'}), '(dict=inp)\n', (6398, 6408), False, 'from aiida.orm.data.parameter import ParameterData\n'), ((6448, 6507), 'aiida.orm.data.parameter.ParameterData', 'ParameterData', ([], {'dict': "{'additional_retrieve_list': ['*.pdb']}"}), "(dict={'additional_retrieve_list': ['*.pdb']})\n", (6461, 6507), False, 'from aiida.orm.data.parameter import ParameterData\n'), ((6945, 6963), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (6961, 6963), False, 'import tempfile\n'), ((7130, 7161), 'aiida.orm.data.singlefile.SinglefileData', 'SinglefileData', ([], {'file': 'molslab_fn'}), '(file=molslab_fn)\n', (7144, 7161), False, 'from aiida.orm.data.singlefile import SinglefileData\n'), ((7178, 7205), 'aiida.orm.data.singlefile.SinglefileData', 'SinglefileData', ([], {'file': 'mol_fn'}), '(file=mol_fn)\n', (7192, 7205), False, 'from aiida.orm.data.singlefile import SinglefileData\n'), ((7215, 7236), 'shutil.rmtree', 'shutil.rmtree', (['tmpdir'], {}), '(tmpdir)\n', (7228, 7236), False, 'import shutil\n'), ((13495, 13551), 'itertools.combinations_with_replacement', 'itertools.combinations_with_replacement', (['element_list', '(2)'], {}), '(element_list, 2)\n', (13534, 13551), False, 'import itertools\n'), ((2410, 2435), 'aiida_cp2k.calculations.Cp2kCalculation.process', 'Cp2kCalculation.process', ([], {}), '()\n', (2433, 2435), False, 'from aiida_cp2k.calculations import Cp2kCalculation\n'), ((3432, 3457), 'aiida_cp2k.calculations.Cp2kCalculation.process', 'Cp2kCalculation.process', ([], {}), '()\n', (3455, 3457), False, 'from aiida_cp2k.calculations import Cp2kCalculation\n'), ((767, 779), 'aiida.orm.data.base.Float', 'Float', (['(0.001)'], {}), '(0.001)\n', (772, 779), False, 'from aiida.orm.data.base import Int, Float, Str, Bool\n'), ((837, 854), 'aiida.orm.data.base.Str', 'Str', (['"""Mixed DFTB"""'], {}), "('Mixed DFTB')\n", (840, 854), False, 'from aiida.orm.data.base import Int, Float, Str, Bool\n'), ((914, 925), 'aiida.orm.data.base.Bool', 'Bool', (['(False)'], {}), '(False)\n', (918, 925), False, 'from aiida.orm.data.base import Int, Float, Str, Bool\n'), ((986, 994), 'aiida.orm.data.base.Int', 'Int', (['(600)'], {}), '(600)\n', (989, 994), False, 'from aiida.orm.data.base import Int, Float, Str, Bool\n'), ((1054, 1061), 'aiida.orm.data.base.Str', 'Str', (['""""""'], {}), "('')\n", (1057, 1061), False, 'from aiida.orm.data.base import Int, Float, Str, Bool\n'), ((1124, 1135), 'aiida.orm.data.base.Bool', 'Bool', (['(False)'], {}), '(False)\n', (1128, 1135), False, 'from aiida.orm.data.base import Int, Float, Str, Bool\n'), ((1196, 1202), 'aiida.orm.data.base.Int', 'Int', (['(1)'], {}), '(1)\n', (1199, 1202), False, 'from aiida.orm.data.base import Int, Float, Str, Bool\n'), ((1266, 1291), 'aiida.work.workchain.while_', 'while_', (['cls.not_converged'], {}), '(cls.not_converged)\n', (1272, 1291), False, 'from aiida.work.workchain import WorkChain, ToContext, Calc, while_\n'), ((2480, 2492), 'aiida.work.workchain.Calc', 'Calc', (['future'], {}), '(future)\n', (2484, 2492), False, 'from aiida.work.workchain import WorkChain, ToContext, Calc, while_\n'), ((3506, 3522), 'aiida.work.workchain.Calc', 'Calc', (['future_new'], {}), '(future_new)\n', (3510, 3522), False, 'from aiida.work.workchain import WorkChain, ToContext, Calc, while_\n'), ((4447, 4476), 'numpy.logical_or', 'np.logical_or', (['is_H', 'is_Metal'], {}), '(is_H, is_Metal)\n', (4460, 4476), True, 'import numpy as np\n'), ((4166, 4198), 'numpy.argwhere', 'np.argwhere', (['(atoms.numbers == el)'], {}), '(atoms.numbers == el)\n', (4177, 4198), True, 'import numpy as np\n'), ((4261, 4293), 'numpy.argwhere', 'np.argwhere', (['(atoms.numbers == el)'], {}), '(atoms.numbers == el)\n', (4272, 4293), True, 'import numpy as np\n')] |
from __future__ import annotations
import os
import random
from matplotlib import pyplot as plt
import pandas as pd
from torchvision.utils import draw_bounding_boxes, draw_segmentation_masks
import src.data.utils.utils as utils
from os.path import join
import src.data.constants as c
from numpy.typing import ArrayLike
import torch
import cv2
import numpy as np
def output_sample(save: str, t: int, timepoint_raw, pred,
size: int = 512, device='cpu'):
utils.make_dir(save)
# TODO: merge this function with output_pred
# just by indexing on timepoint_raw
# Randomly sample 2 slices to debug (per timepoint)
Z = timepoint_raw.shape[0]
# debug_idx = np.random.randint(0, Z, 2)
debug_idx = [Z - int(Z / 2), Z - int(Z / 3), Z - int(Z / 4)]
debug_idx = range(Z)
iterable = zip(debug_idx, timepoint_raw[debug_idx])
for i, (idx, z_slice) in enumerate(iterable):
z_slice = np.int16(z_slice)
boxes = pred[i]['boxes']
masks = pred[i]['masks'] # [mask > 0.5 for mask in pred[i]['masks']]
if len(masks) == 0:
figure = plt.figure()
plt.imshow(z_slice)
plt.title(f'Number of detections: {len(boxes)}')
utils.imsave(join(save,
f't-{t}_{idx}.jpg'), figure, size)
continue
# masks = torch.stack(masks)
# masks = masks.squeeze(1).to(device)
# consolidate masks into one array
mask = utils.get_mask(masks).unsqueeze(0)
# overlay masks onto slice
# z_slice = torch.tensor(z_slice, device=device).repeat(3, 1, 1)
z_slice = utils.normalize(z_slice, 0, 1, cv2.CV_32FC1, device)
# temporarily
z_slice = torch.tensor(z_slice, device=mask.device,
dtype=mask.dtype)
zero = torch.tensor(0, device=mask.device, dtype=mask.dtype)
assert z_slice.shape == mask.shape, \
'Shapes of slice and mask must match'
assert z_slice.dtype == mask.dtype, \
'Dtypes of slice and mask must match'
masked_img = torch.where(mask > zero, mask, z_slice.unsqueeze(0))
bboxed_img = draw_bounding_boxes(masked_img.cpu(), boxes.cpu())[0]
assert bboxed_img.shape == z_slice.shape, \
'Bounding box image and slice image shapes must match'
# plt.subplot(121)
# plt.imshow(bboxed_img[0])
# plt.title(f'Number of detections: {len(boxes)}')
# plt.subplot(122)
# plt.imshow(z_slice)
# plt.title('Ground Truth')
# utils.imsave(join(save,
# f't-{t}_{idx}.jpg'), figure, 512)
images = (bboxed_img, z_slice.squeeze().cpu())
titles = ('Prediction', 'Ground Truth')
grid = (1, 2)
draw_output(images, titles, grid, save, compare=True)
def prepare_draw(image: torch.Tensor, pred: torch.Tensor):
'''
Prepares data for being drawn via the draw_bounding_boxes
and draw_segmentation_masks functions from PyTorch.
'''
# convert grayscale to RGB
# image = image.repeat(3, 1, 1)
# image = image.unsqueeze(0)
boxes = pred['boxes']
# masks = [mask > 0.5 for mask in pred['masks']]
masks = pred['masks']
if len(masks) != 0:
masks = masks.squeeze(1)
else:
masks = torch.empty(0)
image = utils.normalize(image, 0, 255, cv2.CV_8UC1)
return image, boxes, masks
def get_colors(
max_item: ArrayLike,
colormap: str):
'''
Returns color value for integer p.
If max_array contains floating values, make
Inputs:
p: unique cell identifier.
Outputs:
color
'''
random.seed(42)
# find ceiling of color scale
if type(max_item) == int:
# max_item is requested number of colors
scale_max = max_item
elif isinstance(max_item.dtype, np.dtype('float64')):
scale_max = len(max_item)
cmap = plt.get_cmap(colormap)
colors = [cmap(i) for i in np.linspace(0, 1, scale_max)]
# shuffle so that
random.shuffle(colors)
return colors
def output_pred(mode: str, i: int, inputs: tuple, titles: tuple[str],
grid: tuple[int], save=None, compare: bool = False,
dpi: int = None):
'''
Outputs images, and their predictions and labels. First two items of `inputs`
are assumed to be the image array and prediction dictionary, respectively.
'''
image, pred = inputs[:2]
image, bboxes, masks = prepare_draw(image, pred)
if len(bboxes) != 0:
bboxed_img = draw_bounding_boxes(image.cpu(), bboxes)
else:
bboxed_img = image.squeeze()
if len(masks) != 0:
masked_img = utils.get_mask(masks).cpu()
scalar = torch.tensor(255, dtype=torch.uint8)
# Threshold 50 comes from function "performance_mask" where threshold
# is defined as 50 pixels out of 255
pred_img = torch.where(masked_img > 50, scalar,
bboxed_img[0])
else:
pred_img = bboxed_img.squeeze()
if not save:
save = join(c.PROJECT_DATA_DIR, c.PRED_DIR,
'eval', mode)
# draw_output(image[0].cpu(), pred_img.cpu().squeeze(), save, compare, dpi)
images = (image.squeeze(), pred_img)
if len(inputs) > 2:
rest = inputs[2:]
rest = (item.cpu() for item in rest)
images = (*images, *rest)
draw_output(images, titles, grid, save, i, compare, dpi)
def draw_output(images: tuple[torch.Tensor], titles: tuple[str],
grid: tuple[int], save: str, idx: int = None, compare: bool = False,
dpi: int = None):
utils.make_dir(save)
if compare:
len_arr = len(titles)
fig_size = (8 + len_arr * 2, 5 + len_arr)
if dpi:
figure = plt.figure(dpi=dpi, figsize=fig_size)
else:
figure = plt.figure(figsize=fig_size)
x_dim, y_dim = 'X dimension', 'Y dimension'
iterable = enumerate(zip(images, titles))
for i, (image, title) in iterable:
plt.subplot(*grid, i + 1)
plt.imshow(image.squeeze())
plt.title(title)
plt.xlabel(x_dim)
plt.ylabel(y_dim)
plt.suptitle(
f'Prediction for image {idx if idx else None}', fontsize=25)
plt.tight_layout()
utils.imsave(save, figure)
plt.close()
else:
utils.imsave(save, images[1], False)
| [
"matplotlib.pyplot.ylabel",
"src.data.utils.utils.get_mask",
"src.data.utils.utils.imsave",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.close",
"numpy.linspace",
"src.data.utils.utils.make_dir",
"numpy.dtype",
"random.shuffle",
"numpy.int16",
"matplotlib.pyplot.t... | [((476, 496), 'src.data.utils.utils.make_dir', 'utils.make_dir', (['save'], {}), '(save)\n', (490, 496), True, 'import src.data.utils.utils as utils\n'), ((3376, 3419), 'src.data.utils.utils.normalize', 'utils.normalize', (['image', '(0)', '(255)', 'cv2.CV_8UC1'], {}), '(image, 0, 255, cv2.CV_8UC1)\n', (3391, 3419), True, 'import src.data.utils.utils as utils\n'), ((3710, 3725), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (3721, 3725), False, 'import random\n'), ((3973, 3995), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['colormap'], {}), '(colormap)\n', (3985, 3995), True, 'from matplotlib import pyplot as plt\n'), ((4084, 4106), 'random.shuffle', 'random.shuffle', (['colors'], {}), '(colors)\n', (4098, 4106), False, 'import random\n'), ((5702, 5722), 'src.data.utils.utils.make_dir', 'utils.make_dir', (['save'], {}), '(save)\n', (5716, 5722), True, 'import src.data.utils.utils as utils\n'), ((934, 951), 'numpy.int16', 'np.int16', (['z_slice'], {}), '(z_slice)\n', (942, 951), True, 'import numpy as np\n'), ((1646, 1698), 'src.data.utils.utils.normalize', 'utils.normalize', (['z_slice', '(0)', '(1)', 'cv2.CV_32FC1', 'device'], {}), '(z_slice, 0, 1, cv2.CV_32FC1, device)\n', (1661, 1698), True, 'import src.data.utils.utils as utils\n'), ((1739, 1798), 'torch.tensor', 'torch.tensor', (['z_slice'], {'device': 'mask.device', 'dtype': 'mask.dtype'}), '(z_slice, device=mask.device, dtype=mask.dtype)\n', (1751, 1798), False, 'import torch\n'), ((1845, 1898), 'torch.tensor', 'torch.tensor', (['(0)'], {'device': 'mask.device', 'dtype': 'mask.dtype'}), '(0, device=mask.device, dtype=mask.dtype)\n', (1857, 1898), False, 'import torch\n'), ((3348, 3362), 'torch.empty', 'torch.empty', (['(0)'], {}), '(0)\n', (3359, 3362), False, 'import torch\n'), ((4784, 4820), 'torch.tensor', 'torch.tensor', (['(255)'], {'dtype': 'torch.uint8'}), '(255, dtype=torch.uint8)\n', (4796, 4820), False, 'import torch\n'), ((4963, 5014), 'torch.where', 'torch.where', (['(masked_img > 50)', 'scalar', 'bboxed_img[0]'], {}), '(masked_img > 50, scalar, bboxed_img[0])\n', (4974, 5014), False, 'import torch\n'), ((5129, 5179), 'os.path.join', 'join', (['c.PROJECT_DATA_DIR', 'c.PRED_DIR', '"""eval"""', 'mode'], {}), "(c.PROJECT_DATA_DIR, c.PRED_DIR, 'eval', mode)\n", (5133, 5179), False, 'from os.path import join\n'), ((6281, 6354), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['f"""Prediction for image {idx if idx else None}"""'], {'fontsize': '(25)'}), "(f'Prediction for image {idx if idx else None}', fontsize=25)\n", (6293, 6354), True, 'from matplotlib import pyplot as plt\n'), ((6376, 6394), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6392, 6394), True, 'from matplotlib import pyplot as plt\n'), ((6403, 6429), 'src.data.utils.utils.imsave', 'utils.imsave', (['save', 'figure'], {}), '(save, figure)\n', (6415, 6429), True, 'import src.data.utils.utils as utils\n'), ((6438, 6449), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6447, 6449), True, 'from matplotlib import pyplot as plt\n'), ((6469, 6505), 'src.data.utils.utils.imsave', 'utils.imsave', (['save', 'images[1]', '(False)'], {}), '(save, images[1], False)\n', (6481, 6505), True, 'import src.data.utils.utils as utils\n'), ((1114, 1126), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1124, 1126), True, 'from matplotlib import pyplot as plt\n'), ((1139, 1158), 'matplotlib.pyplot.imshow', 'plt.imshow', (['z_slice'], {}), '(z_slice)\n', (1149, 1158), True, 'from matplotlib import pyplot as plt\n'), ((3905, 3924), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (3913, 3924), True, 'import numpy as np\n'), ((4027, 4055), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'scale_max'], {}), '(0, 1, scale_max)\n', (4038, 4055), True, 'import numpy as np\n'), ((5857, 5894), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': 'dpi', 'figsize': 'fig_size'}), '(dpi=dpi, figsize=fig_size)\n', (5867, 5894), True, 'from matplotlib import pyplot as plt\n'), ((5930, 5958), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'fig_size'}), '(figsize=fig_size)\n', (5940, 5958), True, 'from matplotlib import pyplot as plt\n'), ((6117, 6142), 'matplotlib.pyplot.subplot', 'plt.subplot', (['*grid', '(i + 1)'], {}), '(*grid, i + 1)\n', (6128, 6142), True, 'from matplotlib import pyplot as plt\n'), ((6195, 6211), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (6204, 6211), True, 'from matplotlib import pyplot as plt\n'), ((6224, 6241), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_dim'], {}), '(x_dim)\n', (6234, 6241), True, 'from matplotlib import pyplot as plt\n'), ((6254, 6271), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_dim'], {}), '(y_dim)\n', (6264, 6271), True, 'from matplotlib import pyplot as plt\n'), ((1245, 1275), 'os.path.join', 'join', (['save', 'f"""t-{t}_{idx}.jpg"""'], {}), "(save, f't-{t}_{idx}.jpg')\n", (1249, 1275), False, 'from os.path import join\n'), ((1484, 1505), 'src.data.utils.utils.get_mask', 'utils.get_mask', (['masks'], {}), '(masks)\n', (1498, 1505), True, 'import src.data.utils.utils as utils\n'), ((4739, 4760), 'src.data.utils.utils.get_mask', 'utils.get_mask', (['masks'], {}), '(masks)\n', (4753, 4760), True, 'import src.data.utils.utils as utils\n')] |
# import metrics_md
from utils import accuracy
import numpy as np
import torch
import torch.nn.functional as F
# history update
def history_update(loader, model, history, epoch):
with torch.no_grad():
for i, (input, target, idx) in enumerate(loader):
# set input ,target
input, target = input.cuda(), target.cuda()
# compute output
output = model(input)
prec, correct = accuracy(output, target)
#history_update
history.update(idx, correct, output)
history.correctness_counting(epoch)
# rank target entropy. -
def rank_target_entropy(data, normalize=False, max_value=None):
softmax = F.softmax(data, dim=1)
log_softmax = F.log_softmax(data, dim=1)
entropy = softmax * log_softmax
entropy = -1.0 * entropy.sum(dim=1)
# normalize [0 ~ 1]
if normalize:
normalized_entropy = entropy / max_value
return -normalized_entropy
return -entropy
# collect correctness
class History(object):
def __init__(self, n_data):
self.correctness = np.zeros((n_data))
self.correctness_eaurc = np.zeros((n_data))
self.confidence = np.zeros((n_data))
self.correctness_count = 1
def update(self, data_idx, correctness, output):
probs = torch.nn.functional.softmax(output, dim=1)
confidence, _ = probs.max(dim=1)
data_idx = data_idx.cpu().numpy()
self.correctness[data_idx] += correctness.cpu().numpy()
self.confidence[data_idx] = confidence.cpu().detach().numpy()
self.correctness_eaurc[data_idx] = correctness.cpu().numpy()
# counting correctness
def correctness_counting(self, epoch):
if epoch > 1:
self.correctness_count += 1
# sum correctness
def get_sum_correctness(self):
sum_correctness = self.correctness[:]
return sum_correctness
# correctness normalize (0 ~ 1) range
def correctness_normalize(self, data, total_epochs):
data_min = self.correctness.min()
data_max = float(self.correctness_count)
#return (data - data_min) / (data_max - data_min)
return data / total_epochs
# return data
def rank_target(self, data_idx, data_idx2, kappa_i, kappa_j, total_epochs):
data_idx = data_idx.cpu().numpy()
cum_correctness = self.correctness[data_idx]
cum_correctness2 = self.correctness[data_idx2]
# normalize correctness values
cum_correctness = self.correctness_normalize(cum_correctness, total_epochs)
cum_correctness2 = self.correctness_normalize(cum_correctness2, total_epochs)
# make target pair
n_pair = len(data_idx)
correct_i = cum_correctness[:n_pair]
correct_j = cum_correctness2[:n_pair]
# calc target
target = np.ones(n_pair)
# detach kappa
kappa_i = kappa_i.cpu().detach().numpy()
kappa_j = kappa_j.cpu().detach().numpy()
# if c_i == c_j and k_i > k_j
res_bool = np.array((correct_i == correct_j) & (kappa_i > kappa_j))
target[np.where(res_bool == True)] = -1
# if c_i < c_j and k_i > k_j
res_bool = np.array((correct_i < correct_j) & (kappa_i > kappa_j))
target[np.where(res_bool == True)] = -1
# if c_i < c_j and k_i < k_j
res_bool = np.array((correct_i < correct_j) & (kappa_i < kappa_j))
target[np.where(res_bool == True)] = -1
target = torch.from_numpy(target).float().cuda()
# calc margin
margin = abs(correct_i - correct_j)
# e^margin
# margin = np.exp(margin)-1
margin = torch.from_numpy(margin).float().cuda()
return target, margin
# calc eaurc
# def EAURC(self):
# conf_correct = sorted(zip(self.confidence[:], self.correctness_eaurc[:]),
# key=lambda x:x[0], reverse=True)
# sorted_conf, sorted_correct = zip(*conf_correct)
# aurc, eaurc = metrics_md.aurc_eaurc(sorted_conf, sorted_correct)
#
# return aurc, eaurc
| [
"numpy.ones",
"utils.accuracy",
"numpy.where",
"torch.from_numpy",
"numpy.array",
"numpy.zeros",
"torch.nn.functional.log_softmax",
"torch.no_grad",
"torch.nn.functional.softmax"
] | [((695, 717), 'torch.nn.functional.softmax', 'F.softmax', (['data'], {'dim': '(1)'}), '(data, dim=1)\n', (704, 717), True, 'import torch.nn.functional as F\n'), ((737, 763), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['data'], {'dim': '(1)'}), '(data, dim=1)\n', (750, 763), True, 'import torch.nn.functional as F\n'), ((190, 205), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (203, 205), False, 'import torch\n'), ((1092, 1108), 'numpy.zeros', 'np.zeros', (['n_data'], {}), '(n_data)\n', (1100, 1108), True, 'import numpy as np\n'), ((1144, 1160), 'numpy.zeros', 'np.zeros', (['n_data'], {}), '(n_data)\n', (1152, 1160), True, 'import numpy as np\n'), ((1189, 1205), 'numpy.zeros', 'np.zeros', (['n_data'], {}), '(n_data)\n', (1197, 1205), True, 'import numpy as np\n'), ((1313, 1355), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['output'], {'dim': '(1)'}), '(output, dim=1)\n', (1340, 1355), False, 'import torch\n'), ((2847, 2862), 'numpy.ones', 'np.ones', (['n_pair'], {}), '(n_pair)\n', (2854, 2862), True, 'import numpy as np\n'), ((3043, 3099), 'numpy.array', 'np.array', (['((correct_i == correct_j) & (kappa_i > kappa_j))'], {}), '((correct_i == correct_j) & (kappa_i > kappa_j))\n', (3051, 3099), True, 'import numpy as np\n'), ((3205, 3260), 'numpy.array', 'np.array', (['((correct_i < correct_j) & (kappa_i > kappa_j))'], {}), '((correct_i < correct_j) & (kappa_i > kappa_j))\n', (3213, 3260), True, 'import numpy as np\n'), ((3366, 3421), 'numpy.array', 'np.array', (['((correct_i < correct_j) & (kappa_i < kappa_j))'], {}), '((correct_i < correct_j) & (kappa_i < kappa_j))\n', (3374, 3421), True, 'import numpy as np\n'), ((444, 468), 'utils.accuracy', 'accuracy', (['output', 'target'], {}), '(output, target)\n', (452, 468), False, 'from utils import accuracy\n'), ((3115, 3141), 'numpy.where', 'np.where', (['(res_bool == True)'], {}), '(res_bool == True)\n', (3123, 3141), True, 'import numpy as np\n'), ((3276, 3302), 'numpy.where', 'np.where', (['(res_bool == True)'], {}), '(res_bool == True)\n', (3284, 3302), True, 'import numpy as np\n'), ((3437, 3463), 'numpy.where', 'np.where', (['(res_bool == True)'], {}), '(res_bool == True)\n', (3445, 3463), True, 'import numpy as np\n'), ((3488, 3512), 'torch.from_numpy', 'torch.from_numpy', (['target'], {}), '(target)\n', (3504, 3512), False, 'import torch\n'), ((3666, 3690), 'torch.from_numpy', 'torch.from_numpy', (['margin'], {}), '(margin)\n', (3682, 3690), False, 'import torch\n')] |
from abc import ABC, abstractmethod
from itertools import chain, product
from collections import deque
import numpy as np
class SynapsesBuilder(object):
"""
Builder devoted to construct the ANN graph arch. from a config. dict.
"""
def __init__(self, topology):
self.topology = topology
self.stimuli = topology['stimuli']
for k in self.stimuli.keys():
if 'encoding' in topology.keys():
if 'n_neurons' in topology['encoding'][k]['receptive_field']['params']:
self.stimuli[k]['n'] *= topology['encoding'][k]['receptive_field']['params']['n_neurons']
# self.stimuli[k]['n'] = topology['encoding'][k]['receptive_field']['n_neurons']
self.synapses = topology['synapses']
self.ensembles = topology['ensembles']
self.n_inputs = sum([stim['n'] for stim in self.stimuli.values()])
self.n_neurons = sum([ens['n'] for ens in self.ensembles.values()])
self.overall_topology = {name : v for name, v in chain(self.stimuli.items(), self.ensembles.items())}
self.ensemble_pointers = {name: v for name, v in zip(self.overall_topology.keys(), \
np.cumsum([v['n'] for v in self.overall_topology.values()]))}
self.connection_dict = {}
def _build(self, build_func, *args, **kwargs):
matrix = np.zeros([self.n_neurons, self.n_inputs + self.n_neurons])
conn_dict_filled = bool(len(self.connection_dict))
for name, synapse in self.synapses.items():
pre_lst = synapse['pre']
post_lst = synapse['post']
if not isinstance(pre_lst, list): pre_lst = [pre_lst]
if not isinstance(post_lst, list): post_lst = [post_lst]
for (pre, post) in tuple(product(pre_lst, post_lst)):
post_range = (self.ensemble_pointers[post] - self.overall_topology[post]['n']\
- self.n_inputs, self.ensemble_pointers[post] - self.n_inputs)
pre_range = (self.ensemble_pointers[pre] - self.overall_topology[pre]['n'], self.ensemble_pointers[pre])
matrix[post_range[0]:post_range[1], pre_range[0]:pre_range[1]] = build_func(\
pre_range, post_range, synapse_params=synapse, *args, **kwargs)
if not conn_dict_filled:
self.update_connection_dict(name, post_range, pre_range)
return matrix
def build_connections(self):
def _build_connections(node_pre_indices, node_post_indices, synapse_params=None):
conn_submask = np.random.choice(2, p=[1 - synapse_params['p'], synapse_params['p']],\
size=(len(range(*node_post_indices)), len(range(*node_pre_indices)))).astype(bool)
return conn_submask.astype(int)
return self._build(_build_connections)
def build_neurotransmitters(self, mask):
def _build_neurotransmitter(node_pre_indices, node_post_indices, synapse_params=None, neurotransmitter='AMPA', mask=None):
submask = mask[range(*node_post_indices), :][:, range(*node_pre_indices)]
if 'ntx_fixed' in synapse_params.keys() and synapse_params['ntx_fixed']:
if neurotransmitter in synapse_params['neuroTX'].split('+'):
return submask.copy()
else:
return np.zeros_like(submask).astype(bool)
ampa_mask = self._build(_build_neurotransmitter, neurotransmitter='AMPA', mask=mask)
gaba_mask = self._build(_build_neurotransmitter, neurotransmitter='GABA', mask=mask)
ndma_mask = self._build(_build_neurotransmitter, neurotransmitter='NDMA', mask=mask)
return {'AMPA' : ampa_mask, 'GABA' : gaba_mask, 'NDMA' : ndma_mask}
def build_trainable_mask(self, mask, weights):
def _build_trainable_mask(node_pre_indices, node_post_indices, synapse_params=None, mask=None):
submask = mask[range(*node_post_indices), :][:, range(*node_pre_indices)]
if 'trainable' in synapse_params.keys():
return submask if synapse_params['trainable'] else np.zeros_like(submask).astype(bool)
else:
return np.zeros_like(submask).astype(bool)
trainable_mask = self._build(_build_trainable_mask, mask=mask).astype(bool)
weights[~trainable_mask&mask]=(np.random.random(size=np.sum(~trainable_mask&mask))) *.6
return trainable_mask, weights
def build_delays(self, min_delay=1, max_delay=10):
delays = np.random.choice(range(min_delay, max_delay), size=self.n_inputs+self.n_neurons)
spike_buffer = [deque([False for _ in range(int(d))]) for d in delays]
for d in delays:
spike_buffer.append(deque([False for _ in range(int(d))]))
return delays, spike_buffer
def update_connection_dict(self, conn_name, post_range, pre_range):
if conn_name in self.connection_dict:
self.connection_dict[conn_name]['post'].append(post_range)
self.connection_dict[conn_name]['pre'].append(pre_range)
else:
self.connection_dict.update({conn_name : {'post' : [post_range], 'pre' : [pre_range]}})
def build_synapse_params(self):
pass
def build_shared_connections(self):
raise NotImplementedError
| [
"numpy.sum",
"numpy.zeros",
"itertools.product",
"numpy.zeros_like"
] | [((1411, 1469), 'numpy.zeros', 'np.zeros', (['[self.n_neurons, self.n_inputs + self.n_neurons]'], {}), '([self.n_neurons, self.n_inputs + self.n_neurons])\n', (1419, 1469), True, 'import numpy as np\n'), ((1836, 1862), 'itertools.product', 'product', (['pre_lst', 'post_lst'], {}), '(pre_lst, post_lst)\n', (1843, 1862), False, 'from itertools import chain, product\n'), ((4474, 4504), 'numpy.sum', 'np.sum', (['(~trainable_mask & mask)'], {}), '(~trainable_mask & mask)\n', (4480, 4504), True, 'import numpy as np\n'), ((4291, 4313), 'numpy.zeros_like', 'np.zeros_like', (['submask'], {}), '(submask)\n', (4304, 4313), True, 'import numpy as np\n'), ((3449, 3471), 'numpy.zeros_like', 'np.zeros_like', (['submask'], {}), '(submask)\n', (3462, 3471), True, 'import numpy as np\n'), ((4212, 4234), 'numpy.zeros_like', 'np.zeros_like', (['submask'], {}), '(submask)\n', (4225, 4234), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 9 17:41:09 2018
@author: admin
"""
import cv2
import numpy as np
# read and scale down image
# wget https://bigsnarf.files.wordpress.com/2017/05/hammer.png
img = cv2.pyrDown(cv2.imread('b1.jpg', cv2.IMREAD_UNCHANGED))
# threshold image
ret, threshed_img = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),
127, 255, cv2.THRESH_BINARY)
# find contours and get the external one
image, contours, hier = cv2.findContours(threshed_img, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# with each contour, draw boundingRect in green
# a minAreaRect in red and
# a minEnclosingCircle in blue
for c in contours:
# get the bounding rect
x, y, w, h = cv2.boundingRect(c)
# draw a green rectangle to visualize the bounding rect
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# get the min area rect
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
# convert all coordinates floating point values to int
box = np.int0(box)
# draw a red 'nghien' rectangle
cv2.drawContours(img, [box], 0, (0, 0, 255))
# finally, get the min enclosing circle
(x, y), radius = cv2.minEnclosingCircle(c)
# convert all values to int
center = (int(x), int(y))
radius = int(radius)
# and draw the circle in blue
img = cv2.circle(img, center, radius, (255, 0, 0), 2)
print(len(contours))
cv2.drawContours(img, contours, -1, (255, 255, 0), 1)
cv2.imshow("contours", img)
ESC = 27
while True:
if cv2.waitKey(0) & 0xFF == ord('q'):
break
cv2.destroyAllWindows() | [
"cv2.rectangle",
"cv2.drawContours",
"cv2.boxPoints",
"cv2.minEnclosingCircle",
"numpy.int0",
"cv2.imshow",
"cv2.minAreaRect",
"cv2.circle",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.cvtColor",
"cv2.findContours",
"cv2.imread",
"cv2.boundingRect"
] | [((492, 562), 'cv2.findContours', 'cv2.findContours', (['threshed_img', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(threshed_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (508, 562), False, 'import cv2\n'), ((1471, 1524), 'cv2.drawContours', 'cv2.drawContours', (['img', 'contours', '(-1)', '(255, 255, 0)', '(1)'], {}), '(img, contours, -1, (255, 255, 0), 1)\n', (1487, 1524), False, 'import cv2\n'), ((1529, 1556), 'cv2.imshow', 'cv2.imshow', (['"""contours"""', 'img'], {}), "('contours', img)\n", (1539, 1556), False, 'import cv2\n'), ((1652, 1675), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1673, 1675), False, 'import cv2\n'), ((239, 281), 'cv2.imread', 'cv2.imread', (['"""b1.jpg"""', 'cv2.IMREAD_UNCHANGED'], {}), "('b1.jpg', cv2.IMREAD_UNCHANGED)\n", (249, 281), False, 'import cv2\n'), ((340, 377), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (352, 377), False, 'import cv2\n'), ((759, 778), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (775, 778), False, 'import cv2\n'), ((845, 903), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(2)'], {}), '(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n', (858, 903), False, 'import cv2\n'), ((944, 962), 'cv2.minAreaRect', 'cv2.minAreaRect', (['c'], {}), '(c)\n', (959, 962), False, 'import cv2\n'), ((974, 993), 'cv2.boxPoints', 'cv2.boxPoints', (['rect'], {}), '(rect)\n', (987, 993), False, 'import cv2\n'), ((1065, 1077), 'numpy.int0', 'np.int0', (['box'], {}), '(box)\n', (1072, 1077), True, 'import numpy as np\n'), ((1120, 1164), 'cv2.drawContours', 'cv2.drawContours', (['img', '[box]', '(0)', '(0, 0, 255)'], {}), '(img, [box], 0, (0, 0, 255))\n', (1136, 1164), False, 'import cv2\n'), ((1235, 1260), 'cv2.minEnclosingCircle', 'cv2.minEnclosingCircle', (['c'], {}), '(c)\n', (1257, 1260), False, 'import cv2\n'), ((1397, 1444), 'cv2.circle', 'cv2.circle', (['img', 'center', 'radius', '(255, 0, 0)', '(2)'], {}), '(img, center, radius, (255, 0, 0), 2)\n', (1407, 1444), False, 'import cv2\n'), ((1591, 1605), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1602, 1605), False, 'import cv2\n')] |
"""
Copyright: <NAME>, 2013
Code adapted from the Mark Paskin Matlab version
from http://openslam.informatik.uni-freiburg.de/data/svn/tjtf/trunk/matlab/ralign.m
modified by <NAME>
"""
import numpy as np
def estimate_SIM3_umeyama(X,Y):
"""[summary]
estimates rigid transform from X(source) to Y(target)
Args:
X ([type]): Nx3 array
Y ([type]): Nx3 array
Returns:
[type]: [description]
"""
n= X.shape[0]
m = 3
mx = X.mean(0, keepdims=True)
my = Y.mean(0, keepdims=True)
Xc = X - mx#np.tile(mx, (n, 1)).T
Yc = Y - my#np.tile(my, (n, 1)).T
sx = np.mean(np.sum(Xc*Xc, axis=1))
sy = np.mean(np.sum(Yc*Yc, axis=1))
Sxy = (Xc.T @ Yc) / n
U,D,VT = np.linalg.svd(Sxy,full_matrices=True,compute_uv=True)
r = Sxy.ndim #np.rank(Sxy)
d = np.linalg.det(Sxy)
S = np.eye(m)
if r > (m - 1):
if ( np.det(Sxy) < 0 ):
S[m, m] = -1
elif (r == m - 1):
if (np.det(U) * np.det(V) < 0):
S[m, m] = -1
else:
R = np.eye(2)
c = 1
t = np.zeros(2)
return R,c,t
print(U.shape, S.shape, VT.shape)
R = ((U @ S) @ VT).T
c = np.trace(np.diag(D) @ S) / sx
#t = my - c * mx @ R
t = my.reshape(-1,1) - c *(R @ mx.reshape(-1,1))
print('t: ', t)
# create a 4x4 transform matrix
T = np.eye(4)
# c = 1.0
T[:3,:3] = c*R
print(my.shape, R.shape, mx.shape)
T[:3,3] = t.reshape(-1,)
return T | [
"numpy.eye",
"numpy.det",
"numpy.linalg.det",
"numpy.diag",
"numpy.sum",
"numpy.zeros",
"numpy.linalg.svd"
] | [((734, 789), 'numpy.linalg.svd', 'np.linalg.svd', (['Sxy'], {'full_matrices': '(True)', 'compute_uv': '(True)'}), '(Sxy, full_matrices=True, compute_uv=True)\n', (747, 789), True, 'import numpy as np\n'), ((827, 845), 'numpy.linalg.det', 'np.linalg.det', (['Sxy'], {}), '(Sxy)\n', (840, 845), True, 'import numpy as np\n'), ((854, 863), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (860, 863), True, 'import numpy as np\n'), ((1398, 1407), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (1404, 1407), True, 'import numpy as np\n'), ((630, 653), 'numpy.sum', 'np.sum', (['(Xc * Xc)'], {'axis': '(1)'}), '(Xc * Xc, axis=1)\n', (636, 653), True, 'import numpy as np\n'), ((670, 693), 'numpy.sum', 'np.sum', (['(Yc * Yc)'], {'axis': '(1)'}), '(Yc * Yc, axis=1)\n', (676, 693), True, 'import numpy as np\n'), ((897, 908), 'numpy.det', 'np.det', (['Sxy'], {}), '(Sxy)\n', (903, 908), True, 'import numpy as np\n'), ((1073, 1082), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (1079, 1082), True, 'import numpy as np\n'), ((1117, 1128), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (1125, 1128), True, 'import numpy as np\n'), ((1234, 1244), 'numpy.diag', 'np.diag', (['D'], {}), '(D)\n', (1241, 1244), True, 'import numpy as np\n'), ((984, 993), 'numpy.det', 'np.det', (['U'], {}), '(U)\n', (990, 993), True, 'import numpy as np\n'), ((996, 1005), 'numpy.det', 'np.det', (['V'], {}), '(V)\n', (1002, 1005), True, 'import numpy as np\n')] |
import os
import re
import librosa
import noisereduce as nr
import numpy as np
def getX_a(audio_file, sample_rate, audio_start, depth_start, depth_end):
# load audio data
initial_difference = (depth_start - audio_start).total_seconds()
duration = (depth_end - depth_start).total_seconds()
segment_start = int(initial_difference * sample_rate)
segment_end = int(min((initial_difference + duration) * sample_rate, len(audio_file) - 1))
segment = audio_file[segment_start:segment_end]
stft = np.abs(librosa.stft(segment, n_fft=512, hop_length=256, win_length=512))
return np.mean(stft, axis=1)
def process_audio_data(audio_file, datetime_audio):
raw_audio, sample_rate = librosa.load(audio_file)
noisy_part = raw_audio[0:25000]
nr_audio = nr.reduce_noise(audio_clip=raw_audio, noise_clip=noisy_part, verbose=False)
return nr_audio, sample_rate, datetime_audio
| [
"librosa.stft",
"numpy.mean",
"noisereduce.reduce_noise",
"librosa.load"
] | [((603, 624), 'numpy.mean', 'np.mean', (['stft'], {'axis': '(1)'}), '(stft, axis=1)\n', (610, 624), True, 'import numpy as np\n'), ((708, 732), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (720, 732), False, 'import librosa\n'), ((784, 859), 'noisereduce.reduce_noise', 'nr.reduce_noise', ([], {'audio_clip': 'raw_audio', 'noise_clip': 'noisy_part', 'verbose': '(False)'}), '(audio_clip=raw_audio, noise_clip=noisy_part, verbose=False)\n', (799, 859), True, 'import noisereduce as nr\n'), ((526, 590), 'librosa.stft', 'librosa.stft', (['segment'], {'n_fft': '(512)', 'hop_length': '(256)', 'win_length': '(512)'}), '(segment, n_fft=512, hop_length=256, win_length=512)\n', (538, 590), False, 'import librosa\n')] |
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
"""
Observation
===========
In our code so far, there is a problem that it is possible for certain related
values to get out of sync with one another. For example, if we change the
filename after we have read the image into memory, then the data in memory
still refers to the old image. It would be nice if we could automatically
re-load the image if the filename changes. Traits allows you to do this.
The Observe Decorator
---------------------
We want to have the `read_image` method run whenever the ``filename`` trait
changes. We can do this by adding an ``observe`` decorator to the method::
class Image(HasTraits):
...
@observe('filename')
def read_image(self, event):
...
The observer passes an event object to the function which contains information
about what changed, such as the old value of the trait, but we don't need that
information to react to the change, so it is ignored in the body of the
function.
For most traits, the observer will run only when the trait's value *actually*
changes, not just when the value is set. So if you do::
>>> image.filename = "sample_0001.png"
>>> image.filename = "sample_0001.png"
then the observer will only be run once.
Observing Multiple Traits
-------------------------
If you look at the computation of ``pixel_area`` in the original code, it
looks like this::
self.pixel_area = self.scan_height * self.scan_width / self.image.size
It depends on the ``scan_width``, ``scan_height`` and the ``image``, so we
would like to listen to changes to *all* of these. We could write three
``@observe`` functions, one for each trait, but the content would be the
same for each. A better way to do this is to have the observer listen to
all the traits at once::
class Image(HasTraits):
...
@observe('scan_width, scan_height, image')
def update_pixel_area(self, event):
if self.image.size > 0:
self.pixel_area = (
self.scan_height * self.scan_width / self.image.size
)
else:
self.pixel_area = 0
Dynamic Observers
-----------------
Sometimes you want to be able to observe changes to traits from a different
object or piece of code. The ``observe`` method on a ``HasTraits`` subclass
allows you to dynamically specify a function to be called if the value of a
trait changes::
image = Image(
filename="sample_0001.png",
sample_id="0001",
)
def print_filename_changed(event):
print("Filename changed")
image.observe(print_filename_changed, 'filename')
# will print "Filename changed" to the screen
image.filename="sample_0002.png"
Dynamic observers can also be disconnected using the same method, by adding
the argument ``remove=True``::
image.observe(print_filename_changed, 'filename', remove=True)
# nothing will print
image.filename="sample_0003.png"
Exercise
--------
Currently ``scan_height`` and ``scan_width`` are set from the parts of the
``scan_size`` trait as part of the ``traits_init`` method. Remove the
``traits_init`` method and have ``scan_height`` and ``scan_width`` methods
update whenever ``scan_size`` changes.
"""
import os
import datetime
from PIL import Image as PILImage
import numpy as np
from traits.api import (
Array, Date, File, Float, HasTraits, Str, Tuple, observe
)
class Image(HasTraits):
""" An SEM image stored in a file. """
filename = File(exists=True)
sample_id = Str()
operator = Str("N/A")
date_acquired = Date()
scan_size = Tuple(Float, Float)
scan_width = Float
scan_height = Float
image = Array(shape=(None, None), dtype='uint8')
pixel_area = Float()
def traits_init(self):
# useful secondary attributes
self.scan_width, self.scan_height = self.scan_size
# Trait observers
@observe('filename')
def read_image(self, event):
pil_image = PILImage.open(self.filename).convert("L")
self.image = np.array(pil_image)
@observe('scan_width, scan_height, image')
def update_pixel_area(self, event):
if self.image.size > 0:
self.pixel_area = (
self.scan_height * self.scan_width / self.image.size
)
else:
self.pixel_area = 0
# Trait default methods
def _date_acquired_default(self):
return datetime.date.today()
def _scan_size_default(self):
return (1e-5, 1e-5)
# ---------------------------------------------------------------------------
# Demo code
# ---------------------------------------------------------------------------
this_dir = os.path.dirname(__file__)
image_dir = os.path.join(this_dir, "images")
filename = os.path.join(image_dir, "sample_0001.png")
# load the image
image = Image(
filename=filename,
operator="Hannes",
sample_id="0001",
)
# perform some sample computations
print("Scan size:", image.scan_size)
print("Change scan width to 1e-4")
image.scan_width = 1e-4
print("Scan size:", image.scan_size)
for filename in os.listdir(image_dir):
if os.path.splitext(filename)[1] == '.png':
print()
print("Changing filename to {}".format(filename))
image.filename = os.path.join(image_dir, filename)
print(
"The pixel size of {} is {:0.3f} nm²".format(
filename,
image.pixel_area * 1e18,
)
)
| [
"os.listdir",
"traits.api.File",
"traits.api.Str",
"PIL.Image.open",
"traits.api.observe",
"os.path.join",
"traits.api.Array",
"os.path.splitext",
"os.path.dirname",
"traits.api.Tuple",
"numpy.array",
"datetime.date.today",
"traits.api.Date",
"traits.api.Float"
] | [((5107, 5132), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5122, 5132), False, 'import os\n'), ((5145, 5177), 'os.path.join', 'os.path.join', (['this_dir', '"""images"""'], {}), "(this_dir, 'images')\n", (5157, 5177), False, 'import os\n'), ((5189, 5231), 'os.path.join', 'os.path.join', (['image_dir', '"""sample_0001.png"""'], {}), "(image_dir, 'sample_0001.png')\n", (5201, 5231), False, 'import os\n'), ((5523, 5544), 'os.listdir', 'os.listdir', (['image_dir'], {}), '(image_dir)\n', (5533, 5544), False, 'import os\n'), ((3909, 3926), 'traits.api.File', 'File', ([], {'exists': '(True)'}), '(exists=True)\n', (3913, 3926), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((3943, 3948), 'traits.api.Str', 'Str', ([], {}), '()\n', (3946, 3948), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((3964, 3974), 'traits.api.Str', 'Str', (['"""N/A"""'], {}), "('N/A')\n", (3967, 3974), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((3995, 4001), 'traits.api.Date', 'Date', ([], {}), '()\n', (3999, 4001), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((4018, 4037), 'traits.api.Tuple', 'Tuple', (['Float', 'Float'], {}), '(Float, Float)\n', (4023, 4037), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((4099, 4139), 'traits.api.Array', 'Array', ([], {'shape': '(None, None)', 'dtype': '"""uint8"""'}), "(shape=(None, None), dtype='uint8')\n", (4104, 4139), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((4158, 4165), 'traits.api.Float', 'Float', ([], {}), '()\n', (4163, 4165), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((4320, 4339), 'traits.api.observe', 'observe', (['"""filename"""'], {}), "('filename')\n", (4327, 4339), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((4482, 4523), 'traits.api.observe', 'observe', (['"""scan_width, scan_height, image"""'], {}), "('scan_width, scan_height, image')\n", (4489, 4523), False, 'from traits.api import Array, Date, File, Float, HasTraits, Str, Tuple, observe\n'), ((4456, 4475), 'numpy.array', 'np.array', (['pil_image'], {}), '(pil_image)\n', (4464, 4475), True, 'import numpy as np\n'), ((4840, 4861), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (4859, 4861), False, 'import datetime\n'), ((5693, 5726), 'os.path.join', 'os.path.join', (['image_dir', 'filename'], {}), '(image_dir, filename)\n', (5705, 5726), False, 'import os\n'), ((5553, 5579), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (5569, 5579), False, 'import os\n'), ((4393, 4421), 'PIL.Image.open', 'PILImage.open', (['self.filename'], {}), '(self.filename)\n', (4406, 4421), True, 'from PIL import Image as PILImage\n')] |
# modules we'll use
import pandas as pd
import numpy as np
# helpful character encoding module
import chardet
# set seed for reproducibility
np.random.seed(0)
#%%
# start with a string
before = "This is the euro symbol: €"
# check to see what datatype it is
type(before)
#%%
# encode it to a different encoding, replacing characters that raise errors
after = before.encode("utf-8", errors = "replace")
# check the type
type(after)
#%%
# convert it back to utf-8
print(after.decode("utf-8"))
#%%
# try to decode our bytes with the ascii encoding
print(after.decode("ascii"))
#%%
# start with a string
before = "This is the euro symbol: €"
# encode it to a different encoding, replacing characters that raise errors
after = before.encode("ascii", errors = "replace")
# convert it back to utf-8
print(after.decode("ascii"))
# We've lost the original underlying byte string! It's been
# replaced with the underlying byte string for the unknown character :(
#%%
# try to read in a file not in UTF-8
kickstarter_2016 = pd.read_csv("../input/kickstarter-projects/ks-projects-201612.csv")
#%%
# look at the first ten thousand bytes to guess the character encoding
with open("../input/kickstarter-projects/ks-projects-201801.csv", 'rb') as rawdata:
result = chardet.detect(rawdata.read(10000))
# check what the character encoding might be
print(result)
#%%
# read in the file with the encoding detected by chardet
kickstarter_2016 = pd.read_csv("../input/kickstarter-projects/ks-projects-201612.csv", encoding='Windows-1252')
# look at the first few lines
kickstarter_2016.head()
#%%
# save our file (will be saved as UTF-8 by default!)
kickstarter_2016.to_csv("ks-projects-201801-utf8.csv")
| [
"numpy.random.seed",
"pandas.read_csv"
] | [((151, 168), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (165, 168), True, 'import numpy as np\n'), ((1070, 1137), 'pandas.read_csv', 'pd.read_csv', (['"""../input/kickstarter-projects/ks-projects-201612.csv"""'], {}), "('../input/kickstarter-projects/ks-projects-201612.csv')\n", (1081, 1137), True, 'import pandas as pd\n'), ((1500, 1596), 'pandas.read_csv', 'pd.read_csv', (['"""../input/kickstarter-projects/ks-projects-201612.csv"""'], {'encoding': '"""Windows-1252"""'}), "('../input/kickstarter-projects/ks-projects-201612.csv',\n encoding='Windows-1252')\n", (1511, 1596), True, 'import pandas as pd\n')] |
# License: BSD 3 clause
import unittest
import numpy as np
from scipy.sparse import csr_matrix
from tick.robust import ModelModifiedHuber
from tick.base_model.tests.generalized_linear_model import TestGLM
from tick.linear_model import SimuLogReg
class Test(TestGLM):
def test_ModelModifiedHuber(self):
"""...Numerical consistency check of loss and gradient for
Modified Huber model
"""
np.random.seed(12)
n_samples, n_features = 5000, 10
w0 = np.random.randn(n_features)
c0 = np.random.randn()
# First check with intercept
X, y = SimuLogReg(w0, c0, n_samples=n_samples,
verbose=False).simulate()
X_spars = csr_matrix(X)
model = ModelModifiedHuber(fit_intercept=True).fit(X, y)
model_spars = ModelModifiedHuber(fit_intercept=True).fit(X_spars, y)
self.run_test_for_glm(model, model_spars)
self._test_glm_intercept_vs_hardcoded_intercept(model)
# Then check without intercept
X, y = SimuLogReg(w0, None, n_samples=n_samples, verbose=False,
seed=2038).simulate()
X_spars = csr_matrix(X)
model = ModelModifiedHuber(fit_intercept=False).fit(X, y)
model_spars = ModelModifiedHuber(fit_intercept=False).fit(X_spars, y)
self.run_test_for_glm(model, model_spars)
# Test for the Lipschitz constants without intercept
self.assertAlmostEqual(model.get_lip_best(), 2 * 2.6873683857125981)
self.assertAlmostEqual(model.get_lip_mean(), 2 * 9.95845726788432)
self.assertAlmostEqual(model.get_lip_max(), 2 * 54.82616964855237)
self.assertAlmostEqual(model_spars.get_lip_mean(),
model.get_lip_mean())
self.assertAlmostEqual(model_spars.get_lip_max(), model.get_lip_max())
# Test for the Lipschitz constants with intercept
model = ModelModifiedHuber(fit_intercept=True).fit(X, y)
model_spars = ModelModifiedHuber(fit_intercept=True).fit(X_spars, y)
self.assertAlmostEqual(model.get_lip_best(), 2 * 2.687568385712598)
self.assertAlmostEqual(model.get_lip_mean(), 2 * 10.958457267884327)
self.assertAlmostEqual(model.get_lip_max(), 2 * 55.82616964855237)
self.assertAlmostEqual(model_spars.get_lip_mean(),
model.get_lip_mean())
self.assertAlmostEqual(model_spars.get_lip_max(), model.get_lip_max())
if __name__ == '__main__':
unittest.main()
| [
"tick.robust.ModelModifiedHuber",
"tick.linear_model.SimuLogReg",
"numpy.random.seed",
"unittest.main",
"scipy.sparse.csr_matrix",
"numpy.random.randn"
] | [((2511, 2526), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2524, 2526), False, 'import unittest\n'), ((427, 445), 'numpy.random.seed', 'np.random.seed', (['(12)'], {}), '(12)\n', (441, 445), True, 'import numpy as np\n'), ((500, 527), 'numpy.random.randn', 'np.random.randn', (['n_features'], {}), '(n_features)\n', (515, 527), True, 'import numpy as np\n'), ((541, 558), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (556, 558), True, 'import numpy as np\n'), ((722, 735), 'scipy.sparse.csr_matrix', 'csr_matrix', (['X'], {}), '(X)\n', (732, 735), False, 'from scipy.sparse import csr_matrix\n'), ((1169, 1182), 'scipy.sparse.csr_matrix', 'csr_matrix', (['X'], {}), '(X)\n', (1179, 1182), False, 'from scipy.sparse import csr_matrix\n'), ((612, 666), 'tick.linear_model.SimuLogReg', 'SimuLogReg', (['w0', 'c0'], {'n_samples': 'n_samples', 'verbose': '(False)'}), '(w0, c0, n_samples=n_samples, verbose=False)\n', (622, 666), False, 'from tick.linear_model import SimuLogReg\n'), ((752, 790), 'tick.robust.ModelModifiedHuber', 'ModelModifiedHuber', ([], {'fit_intercept': '(True)'}), '(fit_intercept=True)\n', (770, 790), False, 'from tick.robust import ModelModifiedHuber\n'), ((823, 861), 'tick.robust.ModelModifiedHuber', 'ModelModifiedHuber', ([], {'fit_intercept': '(True)'}), '(fit_intercept=True)\n', (841, 861), False, 'from tick.robust import ModelModifiedHuber\n'), ((1046, 1113), 'tick.linear_model.SimuLogReg', 'SimuLogReg', (['w0', 'None'], {'n_samples': 'n_samples', 'verbose': '(False)', 'seed': '(2038)'}), '(w0, None, n_samples=n_samples, verbose=False, seed=2038)\n', (1056, 1113), False, 'from tick.linear_model import SimuLogReg\n'), ((1199, 1238), 'tick.robust.ModelModifiedHuber', 'ModelModifiedHuber', ([], {'fit_intercept': '(False)'}), '(fit_intercept=False)\n', (1217, 1238), False, 'from tick.robust import ModelModifiedHuber\n'), ((1272, 1311), 'tick.robust.ModelModifiedHuber', 'ModelModifiedHuber', ([], {'fit_intercept': '(False)'}), '(fit_intercept=False)\n', (1290, 1311), False, 'from tick.robust import ModelModifiedHuber\n'), ((1933, 1971), 'tick.robust.ModelModifiedHuber', 'ModelModifiedHuber', ([], {'fit_intercept': '(True)'}), '(fit_intercept=True)\n', (1951, 1971), False, 'from tick.robust import ModelModifiedHuber\n'), ((2004, 2042), 'tick.robust.ModelModifiedHuber', 'ModelModifiedHuber', ([], {'fit_intercept': '(True)'}), '(fit_intercept=True)\n', (2022, 2042), False, 'from tick.robust import ModelModifiedHuber\n')] |
import numpy as np
from rl_base.agent.video_game_agent import VideoGameAgent
from rl_base.ml.neural_network import NeuralNetwork
from rl_base.ml.tools.functions import Tanh, Linear, Relu, SoftMax, LinearRelu, Sigmoid
def normalize(x):
return max(min(1, x), -1)
class SnakeAgent(VideoGameAgent):
def __init__(self):
super().__init__(NeuralNetwork((7, 64, 64, 3), (Relu, Relu, Linear), alpha=0.01,
n_min=-0.1, n_max=0.1,
gradient_method=np.vectorize(normalize)),
flat_action_space=3,
max_memory_size=500,
normalize_reward=False,
gamma=0.9,
epsilon_decay=0.999,
min_epsilon=0.01)
| [
"numpy.vectorize"
] | [((534, 557), 'numpy.vectorize', 'np.vectorize', (['normalize'], {}), '(normalize)\n', (546, 557), True, 'import numpy as np\n')] |
from typing import Tuple, List, Union
import numpy as np
from common.exceptionmanager import catch_error_exception
from common.functionutil import ImagesUtil
from dataloaders.batchdatagenerator import BatchDataGenerator
from models.pytorch.networks import UNet
from models.networkchecker import NetworkCheckerBase
class NetworkChecker(NetworkCheckerBase):
def __init__(self,
size_image: Union[Tuple[int, int, int], Tuple[int, int]],
network: UNet
) -> None:
super(NetworkChecker, self).__init__(size_image)
self._network = network
def _is_exist_name_layer_model(self, in_layer_name: str) -> bool:
for ikey_layer_name, _ in self._network._modules.items():
if ikey_layer_name == in_layer_name:
return True
return False
def get_network_layers_names_all(self) -> List[str]:
return [ikey_layer_name for ikey_layer_name, _ in self._network._modules.items()]
def _compute_feature_maps(self, image_data_loader: BatchDataGenerator,
in_layer_name: str,
index_first_featmap: int = None,
max_num_featmaps: int = None
) -> np.ndarray:
# check that "name_layer" exists in model
if not self._is_exist_name_layer_model(in_layer_name):
message = 'Layer \'%s\' does not exist in model...' % (in_layer_name)
catch_error_exception(message)
num_featmaps = 8
# define hook to retrieve feature maps of the desired model layer
def hook(model, input, output):
global out_featmaps_patch
out_featmaps_patch = output.detach().cpu()
# this should be eventually inside Networks.forward()
out_featmaps_patch = out_featmaps_patch.view(-1, num_featmaps, self._size_image[0],
self._size_image[1], self._size_image[2])
return None
# attach hook to the corresponding module layer
self._network._modules[in_layer_name].register_forward_hook(hook)
num_patches = len(image_data_loader)
out_shape_featmaps = [num_patches, num_featmaps] + list(self._size_image)
out_featmaps = np.zeros(out_shape_featmaps, dtype=np.float32)
self._network = self._network.eval() # switch to evaluate mode
for i_img, x_image in enumerate(image_data_loader):
x_image.cuda()
self._network(x_image)
out_featmaps[i_img] = out_featmaps_patch # 'out_featmaps_patch' store inside the function 'hook' above
return ImagesUtil.reshape_channels_last(out_featmaps) # output format "channels_last"
| [
"common.functionutil.ImagesUtil.reshape_channels_last",
"numpy.zeros",
"common.exceptionmanager.catch_error_exception"
] | [((2324, 2370), 'numpy.zeros', 'np.zeros', (['out_shape_featmaps'], {'dtype': 'np.float32'}), '(out_shape_featmaps, dtype=np.float32)\n', (2332, 2370), True, 'import numpy as np\n'), ((2701, 2747), 'common.functionutil.ImagesUtil.reshape_channels_last', 'ImagesUtil.reshape_channels_last', (['out_featmaps'], {}), '(out_featmaps)\n', (2733, 2747), False, 'from common.functionutil import ImagesUtil\n'), ((1492, 1522), 'common.exceptionmanager.catch_error_exception', 'catch_error_exception', (['message'], {}), '(message)\n', (1513, 1522), False, 'from common.exceptionmanager import catch_error_exception\n')] |
import sys
import numpy
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL import GLX
import pyopencl as cl
class raycl(object):
def __init__(self, texture, tex_dim, world):
self.tex_dim = tex_dim
self.world = world
self.clinit()
self.loadProgram("raytrace.cl")
world.init_cldata(self.ctx)
self.tex = cl.GLTexture(
self.ctx, cl.mem_flags.READ_WRITE,
GL_TEXTURE_2D, 0,
texture, 2)
self.gl_objects = [self.tex]
def clinit(self):
plats = cl.get_platforms()
ctx_props = cl.context_properties
props = [(ctx_props.PLATFORM, plats[0]),
(ctx_props.GL_CONTEXT_KHR, platform.GetCurrentContext())]
import sys
if sys.platform == "linux2":
props.append((ctx_props.GLX_DISPLAY_KHR,
GLX.glXGetCurrentDisplay()))
elif sys.platform == "win32":
props.append((ctx_props.WGL_HDC_KHR,
WGL.wglGetCurrentDC()))
self.ctx = cl.Context(properties=props)
self.queue = cl.CommandQueue(self.ctx)
def loadProgram(self, fname):
f = open(fname, "r")
code = "".join(f.readlines())
self.program = cl.Program(self.ctx, code).build()
def execute(self):
glFinish()
cl.enqueue_acquire_gl_objects(self.queue, self.gl_objects)
global_size = self.tex_dim
local_size = None
world = self.world
kernelargs = (self.tex,
numpy.float32(world.camera.rot_x),
numpy.float32(world.camera.rot_y),
numpy.float32(world.camera.x),
numpy.float32(world.camera.y),
numpy.float32(world.camera.z),
numpy.float32(world.camera.fov_x()),
numpy.float32(world.camera.fov_y()),
world.mapdat_clbuf)
self.program.raytrace(self.queue, global_size, local_size,
*kernelargs)
cl.enqueue_release_gl_objects(self.queue, self.gl_objects)
self.queue.flush()
self.queue.finish()
| [
"pyopencl.Program",
"pyopencl.GLTexture",
"pyopencl.get_platforms",
"pyopencl.enqueue_release_gl_objects",
"numpy.float32",
"pyopencl.CommandQueue",
"OpenGL.GLX.glXGetCurrentDisplay",
"pyopencl.enqueue_acquire_gl_objects",
"pyopencl.Context"
] | [((368, 445), 'pyopencl.GLTexture', 'cl.GLTexture', (['self.ctx', 'cl.mem_flags.READ_WRITE', 'GL_TEXTURE_2D', '(0)', 'texture', '(2)'], {}), '(self.ctx, cl.mem_flags.READ_WRITE, GL_TEXTURE_2D, 0, texture, 2)\n', (380, 445), True, 'import pyopencl as cl\n'), ((560, 578), 'pyopencl.get_platforms', 'cl.get_platforms', ([], {}), '()\n', (576, 578), True, 'import pyopencl as cl\n'), ((1051, 1079), 'pyopencl.Context', 'cl.Context', ([], {'properties': 'props'}), '(properties=props)\n', (1061, 1079), True, 'import pyopencl as cl\n'), ((1101, 1126), 'pyopencl.CommandQueue', 'cl.CommandQueue', (['self.ctx'], {}), '(self.ctx)\n', (1116, 1126), True, 'import pyopencl as cl\n'), ((1338, 1396), 'pyopencl.enqueue_acquire_gl_objects', 'cl.enqueue_acquire_gl_objects', (['self.queue', 'self.gl_objects'], {}), '(self.queue, self.gl_objects)\n', (1367, 1396), True, 'import pyopencl as cl\n'), ((2054, 2112), 'pyopencl.enqueue_release_gl_objects', 'cl.enqueue_release_gl_objects', (['self.queue', 'self.gl_objects'], {}), '(self.queue, self.gl_objects)\n', (2083, 2112), True, 'import pyopencl as cl\n'), ((1541, 1574), 'numpy.float32', 'numpy.float32', (['world.camera.rot_x'], {}), '(world.camera.rot_x)\n', (1554, 1574), False, 'import numpy\n'), ((1598, 1631), 'numpy.float32', 'numpy.float32', (['world.camera.rot_y'], {}), '(world.camera.rot_y)\n', (1611, 1631), False, 'import numpy\n'), ((1655, 1684), 'numpy.float32', 'numpy.float32', (['world.camera.x'], {}), '(world.camera.x)\n', (1668, 1684), False, 'import numpy\n'), ((1708, 1737), 'numpy.float32', 'numpy.float32', (['world.camera.y'], {}), '(world.camera.y)\n', (1721, 1737), False, 'import numpy\n'), ((1761, 1790), 'numpy.float32', 'numpy.float32', (['world.camera.z'], {}), '(world.camera.z)\n', (1774, 1790), False, 'import numpy\n'), ((1252, 1278), 'pyopencl.Program', 'cl.Program', (['self.ctx', 'code'], {}), '(self.ctx, code)\n', (1262, 1278), True, 'import pyopencl as cl\n'), ((867, 893), 'OpenGL.GLX.glXGetCurrentDisplay', 'GLX.glXGetCurrentDisplay', ([], {}), '()\n', (891, 893), False, 'from OpenGL import GLX\n')] |
import logging
import os
from sys import platform
import numpy as np
import yaml
import igibson
from igibson.envs.igibson_env import iGibsonEnv
from igibson.objects.articulated_object import URDFObject
from igibson.objects.ycb_object import YCBObject
from igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRendererSettings
from igibson.render.profiler import Profiler
from igibson.robots.turtlebot import Turtlebot
from igibson.scenes.empty_scene import EmptyScene
from igibson.scenes.gibson_indoor_scene import StaticIndoorScene
from igibson.simulator import Simulator
from igibson.utils.assets_utils import get_ig_avg_category_specs, get_ig_category_path, get_ig_model_path
from igibson.utils.utils import let_user_pick, parse_config
def main():
"""
This demo shows how to load scaled objects from the iG object model dataset and
additional objects from the YCB dataset in predefined locations
Loads a concrete object model of a table, and a random one of the same category, and 10 cracker boxes
The objects can be loaded into an empty scene, an interactive scene (iG) or a static scene (Gibson)
The example also shows how to use the Environment API or directly the Simulator API, loading objects and robots
and executing actions
"""
logging.info("*" * 80 + "\nDescription:" + main.__doc__ + "*" * 80)
scene_options = ["Empty scene", "Interactive scene (iG)", "Static scene (Gibson)"]
type_of_scene = let_user_pick(scene_options) - 1
if type_of_scene == 0: # Empty
config = parse_config(os.path.join(igibson.example_config_path, "turtlebot_static_nav.yaml"))
settings = MeshRendererSettings(enable_shadow=False, msaa=False, texture_scale=0.5)
s = Simulator(mode="gui_interactive", image_width=512, image_height=512, rendering_settings=settings)
scene = EmptyScene(render_floor_plane=True, floor_plane_rgba=[0.6, 0.6, 0.6, 1])
# scene.load_object_categories(benchmark_names)
s.import_scene(scene)
robot_config = config["robot"]
robot_config.pop("name")
turtlebot = Turtlebot(**robot_config)
s.import_robot(turtlebot)
elif type_of_scene == 1: # iG
config_filename = os.path.join(igibson.example_config_path, "turtlebot_nav.yaml")
config_data = yaml.load(open(config_filename, "r"), Loader=yaml.FullLoader)
config_data["load_object_categories"] = [] # Uncomment this line to accelerate loading with only the building
config_data["visible_target"] = False
config_data["visible_path"] = False
# Reduce texture scale for Mac.
if platform == "darwin":
config_data["texture_scale"] = 0.5
env = iGibsonEnv(config_file=config_data, mode="gui_interactive")
s = env.simulator
elif type_of_scene == 2: # Gibson
config = parse_config(os.path.join(igibson.example_config_path, "turtlebot_static_nav.yaml"))
settings = MeshRendererSettings(enable_shadow=False, msaa=False)
# Reduce texture scale for Mac.
if platform == "darwin":
settings.texture_scale = 0.5
s = Simulator(mode="gui_interactive", image_width=512, image_height=512, rendering_settings=settings)
scene = StaticIndoorScene("Rs", build_graph=True, pybullet_load_texture=False)
s.import_scene(scene)
robot_config = config["robot"]
robot_config.pop("name")
turtlebot = Turtlebot(**robot_config)
s.import_robot(turtlebot)
# Set a better viewing direction
s.viewer.initial_pos = [-2, 1.4, 1.2]
s.viewer.initial_view_direction = [0.6, -0.8, 0.1]
s.viewer.reset_viewer()
# Objects to load: two tables, the first one is predefined model, the second, random for the same category
table_objects_to_load = {
"table_1": {
"category": "breakfast_table",
"model": "1b4e6f9dd22a8c628ef9d976af675b86",
"pos": (0.0, -0.2, 1.01),
"orn": (0, 0, 90),
},
"table_2": {
"category": "breakfast_table",
"pos": (0.5, -2.0, 1.01),
"orn": (0, 0, 45),
},
}
# Load the specs of the object categories, e.g., common scaling factor
avg_category_spec = get_ig_avg_category_specs()
scene_objects = {}
try:
for obj in table_objects_to_load.values():
category = obj["category"]
if category in scene_objects:
scene_objects[category] += 1
else:
scene_objects[category] = 1
# Get the path for all models of this category
category_path = get_ig_category_path(category)
# If the specific model is given, we use it. If not, we select one randomly
if "model" in obj:
model = obj["model"]
else:
model = np.random.choice(os.listdir(category_path))
# Create the full path combining the path for all models and the name of the model
model_path = get_ig_model_path(category, model)
filename = os.path.join(model_path, model + ".urdf")
# Create a unique name for the object instance
obj_name = "{}_{}".format(category, scene_objects[category])
# Create and import the object
simulator_obj = URDFObject(
filename,
name=obj_name,
category=category,
model_path=model_path,
avg_obj_dims=avg_category_spec.get(category),
fit_avg_dim_volume=True,
texture_randomization=False,
overwrite_inertial=True,
initial_pos=obj["pos"],
initial_orn=obj["orn"],
)
s.import_object(simulator_obj)
for _ in range(10):
obj = YCBObject("003_cracker_box")
s.import_object(obj)
obj.set_position_orientation(np.append(np.random.uniform(low=0, high=2, size=2), [1.8]), [0, 0, 0, 1])
if type_of_scene == 1:
for j in range(10):
logging.info("Resetting environment")
env.reset()
for i in range(100):
with Profiler("Environment action step"):
# action = env.action_space.sample()
state, reward, done, info = env.step([0.1, 0.1])
if done:
logging.info("Episode finished after {} timesteps".format(i + 1))
break
else:
for i in range(10000):
with Profiler("Simulator step"):
turtlebot.apply_action([0.1, 0.1])
s.step()
rgb = s.renderer.render_robot_cameras(modes=("rgb"))
finally:
if type_of_scene == 1:
env.close()
else:
s.disconnect()
if __name__ == "__main__":
main()
| [
"igibson.render.profiler.Profiler",
"os.listdir",
"igibson.render.mesh_renderer.mesh_renderer_cpu.MeshRendererSettings",
"igibson.utils.assets_utils.get_ig_category_path",
"igibson.scenes.empty_scene.EmptyScene",
"os.path.join",
"igibson.scenes.gibson_indoor_scene.StaticIndoorScene",
"igibson.utils.ut... | [((1284, 1351), 'logging.info', 'logging.info', (["('*' * 80 + '\\nDescription:' + main.__doc__ + '*' * 80)"], {}), "('*' * 80 + '\\nDescription:' + main.__doc__ + '*' * 80)\n", (1296, 1351), False, 'import logging\n'), ((4264, 4291), 'igibson.utils.assets_utils.get_ig_avg_category_specs', 'get_ig_avg_category_specs', ([], {}), '()\n', (4289, 4291), False, 'from igibson.utils.assets_utils import get_ig_avg_category_specs, get_ig_category_path, get_ig_model_path\n'), ((1459, 1487), 'igibson.utils.utils.let_user_pick', 'let_user_pick', (['scene_options'], {}), '(scene_options)\n', (1472, 1487), False, 'from igibson.utils.utils import let_user_pick, parse_config\n'), ((1650, 1722), 'igibson.render.mesh_renderer.mesh_renderer_cpu.MeshRendererSettings', 'MeshRendererSettings', ([], {'enable_shadow': '(False)', 'msaa': '(False)', 'texture_scale': '(0.5)'}), '(enable_shadow=False, msaa=False, texture_scale=0.5)\n', (1670, 1722), False, 'from igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRendererSettings\n'), ((1735, 1836), 'igibson.simulator.Simulator', 'Simulator', ([], {'mode': '"""gui_interactive"""', 'image_width': '(512)', 'image_height': '(512)', 'rendering_settings': 'settings'}), "(mode='gui_interactive', image_width=512, image_height=512,\n rendering_settings=settings)\n", (1744, 1836), False, 'from igibson.simulator import Simulator\n'), ((1849, 1921), 'igibson.scenes.empty_scene.EmptyScene', 'EmptyScene', ([], {'render_floor_plane': '(True)', 'floor_plane_rgba': '[0.6, 0.6, 0.6, 1]'}), '(render_floor_plane=True, floor_plane_rgba=[0.6, 0.6, 0.6, 1])\n', (1859, 1921), False, 'from igibson.scenes.empty_scene import EmptyScene\n'), ((2100, 2125), 'igibson.robots.turtlebot.Turtlebot', 'Turtlebot', ([], {}), '(**robot_config)\n', (2109, 2125), False, 'from igibson.robots.turtlebot import Turtlebot\n'), ((1559, 1629), 'os.path.join', 'os.path.join', (['igibson.example_config_path', '"""turtlebot_static_nav.yaml"""'], {}), "(igibson.example_config_path, 'turtlebot_static_nav.yaml')\n", (1571, 1629), False, 'import os\n'), ((2222, 2285), 'os.path.join', 'os.path.join', (['igibson.example_config_path', '"""turtlebot_nav.yaml"""'], {}), "(igibson.example_config_path, 'turtlebot_nav.yaml')\n", (2234, 2285), False, 'import os\n'), ((2713, 2772), 'igibson.envs.igibson_env.iGibsonEnv', 'iGibsonEnv', ([], {'config_file': 'config_data', 'mode': '"""gui_interactive"""'}), "(config_file=config_data, mode='gui_interactive')\n", (2723, 2772), False, 'from igibson.envs.igibson_env import iGibsonEnv\n'), ((4652, 4682), 'igibson.utils.assets_utils.get_ig_category_path', 'get_ig_category_path', (['category'], {}), '(category)\n', (4672, 4682), False, 'from igibson.utils.assets_utils import get_ig_avg_category_specs, get_ig_category_path, get_ig_model_path\n'), ((5047, 5081), 'igibson.utils.assets_utils.get_ig_model_path', 'get_ig_model_path', (['category', 'model'], {}), '(category, model)\n', (5064, 5081), False, 'from igibson.utils.assets_utils import get_ig_avg_category_specs, get_ig_category_path, get_ig_model_path\n'), ((5105, 5146), 'os.path.join', 'os.path.join', (['model_path', "(model + '.urdf')"], {}), "(model_path, model + '.urdf')\n", (5117, 5146), False, 'import os\n'), ((5868, 5896), 'igibson.objects.ycb_object.YCBObject', 'YCBObject', (['"""003_cracker_box"""'], {}), "('003_cracker_box')\n", (5877, 5896), False, 'from igibson.objects.ycb_object import YCBObject\n'), ((2960, 3013), 'igibson.render.mesh_renderer.mesh_renderer_cpu.MeshRendererSettings', 'MeshRendererSettings', ([], {'enable_shadow': '(False)', 'msaa': '(False)'}), '(enable_shadow=False, msaa=False)\n', (2980, 3013), False, 'from igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRendererSettings\n'), ((3140, 3241), 'igibson.simulator.Simulator', 'Simulator', ([], {'mode': '"""gui_interactive"""', 'image_width': '(512)', 'image_height': '(512)', 'rendering_settings': 'settings'}), "(mode='gui_interactive', image_width=512, image_height=512,\n rendering_settings=settings)\n", (3149, 3241), False, 'from igibson.simulator import Simulator\n'), ((3255, 3325), 'igibson.scenes.gibson_indoor_scene.StaticIndoorScene', 'StaticIndoorScene', (['"""Rs"""'], {'build_graph': '(True)', 'pybullet_load_texture': '(False)'}), "('Rs', build_graph=True, pybullet_load_texture=False)\n", (3272, 3325), False, 'from igibson.scenes.gibson_indoor_scene import StaticIndoorScene\n'), ((3448, 3473), 'igibson.robots.turtlebot.Turtlebot', 'Turtlebot', ([], {}), '(**robot_config)\n', (3457, 3473), False, 'from igibson.robots.turtlebot import Turtlebot\n'), ((6125, 6162), 'logging.info', 'logging.info', (['"""Resetting environment"""'], {}), "('Resetting environment')\n", (6137, 6162), False, 'import logging\n'), ((2869, 2939), 'os.path.join', 'os.path.join', (['igibson.example_config_path', '"""turtlebot_static_nav.yaml"""'], {}), "(igibson.example_config_path, 'turtlebot_static_nav.yaml')\n", (2881, 2939), False, 'import os\n'), ((4899, 4924), 'os.listdir', 'os.listdir', (['category_path'], {}), '(category_path)\n', (4909, 4924), False, 'import os\n'), ((5981, 6021), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0)', 'high': '(2)', 'size': '(2)'}), '(low=0, high=2, size=2)\n', (5998, 6021), True, 'import numpy as np\n'), ((6655, 6681), 'igibson.render.profiler.Profiler', 'Profiler', (['"""Simulator step"""'], {}), "('Simulator step')\n", (6663, 6681), False, 'from igibson.render.profiler import Profiler\n'), ((6253, 6288), 'igibson.render.profiler.Profiler', 'Profiler', (['"""Environment action step"""'], {}), "('Environment action step')\n", (6261, 6288), False, 'from igibson.render.profiler import Profiler\n')] |
# coding=utf-8
from contracts import contract
from geometry.spheres import normalize_pi
import numpy as np
from .differentiable_manifold import DifferentiableManifold
__all__ = ['Torus', 'T', 'T1', 'T2', 'T3']
class Torus(DifferentiableManifold):
def __init__(self, n):
DifferentiableManifold.__init__(self, dimension=n)
self.n = n
def belongs(self, a):
ok = np.logical_and(a >= -np.pi, a < np.pi)
if not np.all(ok):
raise ValueError("Not all are ok in %s" % a)
def distance(self, a, b):
b = self.normalize(b - a)
return np.linalg.norm(b)
def logmap(self, base, p):
vel = self.normalize(p - base)
return base, vel
def expmap(self, bv):
a, vel = bv
b = self.normalize(a + vel)
return b
def project_ts(self, bv):
return bv # XXX: more checks
@contract(returns='belongs')
def sample_uniform(self):
return np.random.rand(self.n) * 2 * np.pi - np.pi
def normalize(self, a):
return normalize_pi(a)
def friendly(self, a):
return 'point(%s)' % a
@contract(returns='list(belongs)')
def interesting_points(self):
interesting = []
interesting.append(np.zeros(self.n))
for _ in range(2):
interesting.append(self.sample_uniform())
return interesting
def __repr__(self):
return 'T%s' % self.n
T1 = Torus(1)
T2 = Torus(2)
T3 = Torus(3)
T = {1: T1, 2: T2, 3: T3}
| [
"numpy.random.rand",
"numpy.logical_and",
"numpy.zeros",
"geometry.spheres.normalize_pi",
"numpy.linalg.norm",
"numpy.all",
"contracts.contract"
] | [((890, 917), 'contracts.contract', 'contract', ([], {'returns': '"""belongs"""'}), "(returns='belongs')\n", (898, 917), False, 'from contracts import contract\n'), ((1131, 1164), 'contracts.contract', 'contract', ([], {'returns': '"""list(belongs)"""'}), "(returns='list(belongs)')\n", (1139, 1164), False, 'from contracts import contract\n'), ((398, 436), 'numpy.logical_and', 'np.logical_and', (['(a >= -np.pi)', '(a < np.pi)'], {}), '(a >= -np.pi, a < np.pi)\n', (412, 436), True, 'import numpy as np\n'), ((601, 618), 'numpy.linalg.norm', 'np.linalg.norm', (['b'], {}), '(b)\n', (615, 618), True, 'import numpy as np\n'), ((1050, 1065), 'geometry.spheres.normalize_pi', 'normalize_pi', (['a'], {}), '(a)\n', (1062, 1065), False, 'from geometry.spheres import normalize_pi\n'), ((452, 462), 'numpy.all', 'np.all', (['ok'], {}), '(ok)\n', (458, 462), True, 'import numpy as np\n'), ((1251, 1267), 'numpy.zeros', 'np.zeros', (['self.n'], {}), '(self.n)\n', (1259, 1267), True, 'import numpy as np\n'), ((963, 985), 'numpy.random.rand', 'np.random.rand', (['self.n'], {}), '(self.n)\n', (977, 985), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 23:19:16 2020
@author: alex
------------------------------------
Fichier d'amorce pour les livrables de la problématique GRO640'
"""
import numpy as np
from pyro.control.robotcontrollers import EndEffectorPD
from pyro.control.robotcontrollers import EndEffectorKinematicController
###################
# Part 1
###################
def dh2T( r , d , theta, alpha ):
"""
Parameters
----------
r : float 1x1
d : float 1x1
theta : float 1x1
alpha : float 1x1
4 paramètres de DH
Returns
-------
T : float 4x4 (numpy array)
Matrice de transformation
"""
T = np.zeros((4,4))
###################
# Votre code ici
###################
return T
def dhs2T( r , d , theta, alpha ):
"""
Parameters
----------
r : float nx1
d : float nx1
theta : float nx1
alpha : float nx1
Colonnes de paramètre de DH
Returns
-------
WTT : float 4x4 (numpy array)
Matrice de transformation totale de l'outil
"""
WTT = np.zeros((4,4))
###################
# Votre code ici
###################
return WTT
def f(q):
"""
Parameters
----------
q : float 6x1
Joint space coordinates
Returns
-------
r : float 3x1
Effector (x,y,z) position
"""
r = np.zeros((3,1))
###################
# Votre code ici
###################
return r
###################
# Part 2
###################
class CustomPositionController( EndEffectorKinematicController ) :
############################
def __init__(self, manipulator ):
""" """
EndEffectorKinematicController.__init__( self, manipulator, 1)
###################################################
# Vos paramètres de loi de commande ici !!
###################################################
#############################
def c( self , y , r , t = 0 ):
"""
Feedback law: u = c(y,r,t)
INPUTS
y = q : sensor signal vector = joint angular positions dof x 1
r = r_d : reference signal vector = desired effector position e x 1
t : time 1 x 1
OUPUTS
u = dq : control inputs vector = joint velocities dof x 1
"""
# Feedback from sensors
q = y
# Jacobian computation
J = self.J( q )
# Ref
r_desired = r
r_actual = self.fwd_kin( q )
# Error
e = r_desired - r_actual
################
dq = np.zeros( self.m ) # place-holder de bonne dimension
##################################
# Votre loi de commande ici !!!
##################################
return dq
###################
# Part 3
###################
class CustomDrillingController( EndEffectorPD ) :
"""
"""
############################
def __init__(self, robot_model ):
""" """
EndEffectorPD.__init__( self , robot_model )
# Label
self.name = 'Custom Drilling Controller'
###################################################
# Vos paramètres de loi de commande ici !!
###################################################
# Target effector force
self.rbar = np.array([0,0,0])
#############################
def c( self , y , r , t = 0 ):
"""
Feedback static computation u = c(y,r,t)
INPUTS
y : sensor signal vector p x 1
r : reference signal vector k x 1
t : time 1 x 1
OUPUTS
u : control inputs vector m x 1
"""
# Ref
f_e = r
# Feedback from sensors
x = y
[ q , dq ] = self.x2q( x )
##################################
# Votre loi de commande ici !!!
##################################
tau = np.zeros(self.m) # place-holder de bonne dimension
return tau
###################
# Part 4
###################
def goal2r( r_0 , r_f , t_f ):
"""
Parameters
----------
r_0 : numpy array float 3 x 1
effector initial position
r_f : numpy array float 3 x 1
effector final position
t_f : float
time
Returns
-------
r : numpy array float 3 x l
dr : numpy array float 3 x l
ddr : numpy array float 3 x l
"""
# Time discretization
l = 1000 # nb of time steps
# Number of DoF for the effector only
m = 3
r = np.zeros((m,l))
dr = np.zeros((m,l))
ddr = np.zeros((m,l))
#################################
# Votre code ici !!!
##################################
return r, dr, ddr
def r2q( r, dr, ddr , manipulator ):
"""
Parameters
----------
r : numpy array float 3 x l
dr : numpy array float 3 x l
ddr : numpy array float 3 x l
manipulator : pyro object
Returns
-------
q : numpy array float 3 x l
dq : numpy array float 3 x l
ddq : numpy array float 3 x l
"""
# Time discretization
l = r.shape[1]
# Number of DoF
n = 3
# Output dimensions
q = np.zeros((n,l))
dq = np.zeros((n,l))
ddq = np.zeros((n,l))
#################################
# Votre code ici !!!
##################################
return q, dq, ddq
def q2torque( q, dq, ddq , manipulator ):
"""
Parameters
----------
q : numpy array float 3 x l
dq : numpy array float 3 x l
ddq : numpy array float 3 x l
manipulator : pyro object
Returns
-------
tau : numpy array float 3 x l
"""
# Time discretization
l = q.shape[1]
# Number of DoF
n = 3
# Output dimensions
tau = np.zeros((n,l))
#################################
# Votre code ici !!!
##################################
return tau | [
"numpy.array",
"pyro.control.robotcontrollers.EndEffectorPD.__init__",
"numpy.zeros",
"pyro.control.robotcontrollers.EndEffectorKinematicController.__init__"
] | [((723, 739), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {}), '((4, 4))\n', (731, 739), True, 'import numpy as np\n'), ((1178, 1194), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {}), '((4, 4))\n', (1186, 1194), True, 'import numpy as np\n'), ((1489, 1505), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (1497, 1505), True, 'import numpy as np\n'), ((5097, 5113), 'numpy.zeros', 'np.zeros', (['(m, l)'], {}), '((m, l))\n', (5105, 5113), True, 'import numpy as np\n'), ((5122, 5138), 'numpy.zeros', 'np.zeros', (['(m, l)'], {}), '((m, l))\n', (5130, 5138), True, 'import numpy as np\n'), ((5148, 5164), 'numpy.zeros', 'np.zeros', (['(m, l)'], {}), '((m, l))\n', (5156, 5164), True, 'import numpy as np\n'), ((5772, 5788), 'numpy.zeros', 'np.zeros', (['(n, l)'], {}), '((n, l))\n', (5780, 5788), True, 'import numpy as np\n'), ((5797, 5813), 'numpy.zeros', 'np.zeros', (['(n, l)'], {}), '((n, l))\n', (5805, 5813), True, 'import numpy as np\n'), ((5823, 5839), 'numpy.zeros', 'np.zeros', (['(n, l)'], {}), '((n, l))\n', (5831, 5839), True, 'import numpy as np\n'), ((6389, 6405), 'numpy.zeros', 'np.zeros', (['(n, l)'], {}), '((n, l))\n', (6397, 6405), True, 'import numpy as np\n'), ((1829, 1890), 'pyro.control.robotcontrollers.EndEffectorKinematicController.__init__', 'EndEffectorKinematicController.__init__', (['self', 'manipulator', '(1)'], {}), '(self, manipulator, 1)\n', (1868, 1890), False, 'from pyro.control.robotcontrollers import EndEffectorKinematicController\n'), ((2901, 2917), 'numpy.zeros', 'np.zeros', (['self.m'], {}), '(self.m)\n', (2909, 2917), True, 'import numpy as np\n'), ((3373, 3414), 'pyro.control.robotcontrollers.EndEffectorPD.__init__', 'EndEffectorPD.__init__', (['self', 'robot_model'], {}), '(self, robot_model)\n', (3395, 3414), False, 'from pyro.control.robotcontrollers import EndEffectorPD\n'), ((3733, 3752), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (3741, 3752), True, 'import numpy as np\n'), ((4438, 4454), 'numpy.zeros', 'np.zeros', (['self.m'], {}), '(self.m)\n', (4446, 4454), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
""" Tools for annotating an input image """
from collections import OrderedDict
import logging
import cv2
import numpy as np
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class Annotate():
""" Annotate an input image """
def __init__(self, image, alignments, original_roi=None):
logger.debug("Initializing %s: (alignments: %s, original_roi: %s)",
self.__class__.__name__, alignments, original_roi)
self.image = image
self.alignments = alignments
self.roi = original_roi
self.colors = {1: (255, 0, 0),
2: (0, 255, 0),
3: (0, 0, 255),
4: (255, 255, 0),
5: (255, 0, 255),
6: (0, 255, 255)}
logger.debug("Initialized %s", self.__class__.__name__)
def draw_black_image(self):
""" Change image to black at correct dimensions """
logger.trace("Drawing black image")
height, width = self.image.shape[:2]
self.image = np.zeros((height, width, 3), dtype="uint8")
def draw_bounding_box(self, color_id=1, thickness=1):
""" Draw the bounding box around faces """
color = self.colors[color_id]
for alignment in self.alignments:
top_left = (alignment["x"], alignment["y"])
bottom_right = (alignment["x"] + alignment["w"], alignment["y"] + alignment["h"])
logger.trace("Drawing bounding box: (top_left: %s, bottom_right: %s, color: %s, "
"thickness: %s)", top_left, bottom_right, color, thickness)
cv2.rectangle(self.image, top_left, bottom_right, color, thickness)
def draw_extract_box(self, color_id=2, thickness=1):
""" Draw the extracted face box """
if not self.roi:
return
color = self.colors[color_id]
for idx, roi in enumerate(self.roi):
logger.trace("Drawing Extract Box: (idx: %s, roi: %s)", idx, roi)
top_left = [point for point in roi.squeeze()[0]]
top_left = (top_left[0], top_left[1] - 10)
cv2.putText(self.image,
str(idx),
top_left,
cv2.FONT_HERSHEY_DUPLEX,
1.0,
color,
thickness)
cv2.polylines(self.image, [roi], True, color, thickness)
def draw_landmarks(self, color_id=3, radius=1):
""" Draw the facial landmarks """
color = self.colors[color_id]
for alignment in self.alignments:
landmarks = alignment["landmarks_xy"].astype("int32")
logger.trace("Drawing Landmarks: (landmarks: %s, color: %s, radius: %s)",
landmarks, color, radius)
for (pos_x, pos_y) in landmarks:
cv2.circle(self.image, (pos_x, pos_y), radius, color, -1)
def draw_landmarks_mesh(self, color_id=4, thickness=1):
""" Draw the facial landmarks """
color = self.colors[color_id]
facial_landmarks_idxs = OrderedDict([("mouth", (48, 68)),
("right_eyebrow", (17, 22)),
("left_eyebrow", (22, 27)),
("right_eye", (36, 42)),
("left_eye", (42, 48)),
("nose", (27, 36)),
("jaw", (0, 17)),
("chin", (8, 11))])
for alignment in self.alignments:
landmarks = alignment["landmarks_xy"]
logger.trace("Drawing Landmarks Mesh: (landmarks: %s, color: %s, thickness: %s)",
landmarks, color, thickness)
for key, val in facial_landmarks_idxs.items():
points = np.array([landmarks[val[0]:val[1]]], np.int32)
fill_poly = bool(key in ("right_eye", "left_eye", "mouth"))
cv2.polylines(self.image, points, fill_poly, color, thickness)
def draw_grey_out_faces(self, live_face):
""" Grey out all faces except target """
if not self.roi:
return
alpha = 0.6
overlay = self.image.copy()
for idx, roi in enumerate(self.roi):
if idx != int(live_face):
logger.trace("Greying out face: (idx: %s, roi: %s)", idx, roi)
cv2.fillPoly(overlay, roi, (0, 0, 0))
cv2.addWeighted(overlay, alpha, self.image, 1. - alpha, 0., self.image)
| [
"logging.getLogger",
"cv2.rectangle",
"collections.OrderedDict",
"cv2.fillPoly",
"cv2.polylines",
"cv2.addWeighted",
"numpy.zeros",
"cv2.circle",
"numpy.array"
] | [((161, 188), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (178, 188), False, 'import logging\n'), ((1091, 1134), 'numpy.zeros', 'np.zeros', (['(height, width, 3)'], {'dtype': '"""uint8"""'}), "((height, width, 3), dtype='uint8')\n", (1099, 1134), True, 'import numpy as np\n'), ((3144, 3351), 'collections.OrderedDict', 'OrderedDict', (["[('mouth', (48, 68)), ('right_eyebrow', (17, 22)), ('left_eyebrow', (22, 27\n )), ('right_eye', (36, 42)), ('left_eye', (42, 48)), ('nose', (27, 36)),\n ('jaw', (0, 17)), ('chin', (8, 11))]"], {}), "([('mouth', (48, 68)), ('right_eyebrow', (17, 22)), (\n 'left_eyebrow', (22, 27)), ('right_eye', (36, 42)), ('left_eye', (42, \n 48)), ('nose', (27, 36)), ('jaw', (0, 17)), ('chin', (8, 11))])\n", (3155, 3351), False, 'from collections import OrderedDict\n'), ((4604, 4677), 'cv2.addWeighted', 'cv2.addWeighted', (['overlay', 'alpha', 'self.image', '(1.0 - alpha)', '(0.0)', 'self.image'], {}), '(overlay, alpha, self.image, 1.0 - alpha, 0.0, self.image)\n', (4619, 4677), False, 'import cv2\n'), ((1666, 1733), 'cv2.rectangle', 'cv2.rectangle', (['self.image', 'top_left', 'bottom_right', 'color', 'thickness'], {}), '(self.image, top_left, bottom_right, color, thickness)\n', (1679, 1733), False, 'import cv2\n'), ((2417, 2473), 'cv2.polylines', 'cv2.polylines', (['self.image', '[roi]', '(True)', 'color', 'thickness'], {}), '(self.image, [roi], True, color, thickness)\n', (2430, 2473), False, 'import cv2\n'), ((2913, 2970), 'cv2.circle', 'cv2.circle', (['self.image', '(pos_x, pos_y)', 'radius', 'color', '(-1)'], {}), '(self.image, (pos_x, pos_y), radius, color, -1)\n', (2923, 2970), False, 'import cv2\n'), ((3981, 4027), 'numpy.array', 'np.array', (['[landmarks[val[0]:val[1]]]', 'np.int32'], {}), '([landmarks[val[0]:val[1]]], np.int32)\n', (3989, 4027), True, 'import numpy as np\n'), ((4120, 4182), 'cv2.polylines', 'cv2.polylines', (['self.image', 'points', 'fill_poly', 'color', 'thickness'], {}), '(self.image, points, fill_poly, color, thickness)\n', (4133, 4182), False, 'import cv2\n'), ((4557, 4594), 'cv2.fillPoly', 'cv2.fillPoly', (['overlay', 'roi', '(0, 0, 0)'], {}), '(overlay, roi, (0, 0, 0))\n', (4569, 4594), False, 'import cv2\n')] |
# -*- coding: utf-8 -*-
#@Author: <NAME>
#@Date: 2019-11-25 19:24:06
#@Last Modified by: <NAME>
#@Last Modified time: 2019-11-25 19:24:06
from mmdet.apis import init_detector, inference_detector, show_result,inference_trackor
import mmcv
import os
import time
import ffmpeg
import json
import numpy as np
import cv2
import argparse
import os
import os.path as osp
import shutil
import tempfile
import mmcv
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, load_checkpoint
from mmdet.apis import init_dist
from mmdet.core import coco_eval, results2json, wrap_fp16_model
from mmdet.datasets import build_dataloader, build_dataset
from mmdet.models import build_detector
from mmdet.core import eval_map
import os
def kitti_eval(det_results, dataset, iou_thr=0.5):
gt_bboxes = []
gt_labels = []
gt_ignore = []
for i in range(len(dataset)):
ann = dataset.get_ann_info(i)
bboxes = ann['bboxes']
labels = ann['labels']
gt_bboxes.append(bboxes)
gt_labels.append(labels)
# if i>10:
# break
if not gt_ignore:
gt_ignore = None
dataset_name = 'kitti'
eval_map(
det_results,
gt_bboxes,
gt_labels,
gt_ignore=gt_ignore,
scale_ranges=None,
iou_thr=iou_thr,
dataset=dataset_name,
print_summary=True)
config_file ='/home/ld/RepPoints/configs/reppoints_moment_r101_dcn_fpn_kitti_agg_fuse_st.py'
checkpoint_file='/home/ld/RepPoints/final/fuse/epoch_13.pth'
cfg = mmcv.Config.fromfile(config_file)
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
cfg.model.pretrained = None
cfg.data.test.test_mode = True
dataset = build_dataset(cfg.data.test)
data_path='/backdata01/KITTI/kitti/tracking'
jsonfile_name='kitti_val_3class.json'
# test a video and show the results
with open(os.path.join(data_path,jsonfile_name),'r',encoding='utf-8') as f:
data=json.load(f)
compute_time=0
out_name=['refer','agg']
for i in range(10):
out_name.append('frame_'+str(i+1))
out_path='/home/ld/RepPoints/final/epoch13 thres0.1'
if not os.path.exists(out_path):
os.mkdir(out_path)
for i in range(12):
os.mkdir(os.path.join(out_path,out_name[i]))
results=[]
video_length=0
video_name_check=None
result_record=[]
for i in range(12):
result_record.append([])
eval_data=[]
for i in range(12):
eval_data.append([])
loc_data=[]
for i in range(12):
loc_data.append([])
scale=[8,16,32,64,128]
scale={'8':0,'16':1,'32':2,'64':3,'128':4}
offset_data=[]
for i in range(10):
offset_data.append([])
mask_data=[]
for i in range(10):
mask_data.append([])
#load and test
outputs=mmcv.load('/home/ld/RepPoints/final/epoch13 thres0.1/fuse_result.pkl')
kitti_eval(outputs, dataset)
exit()
# for i in range(12):
# result_record[i]=mmcv.load(os.path.join(out_path,out_name[i],'det_result.pkl'))
# for i in range(12):
# print('evaluating result of ', out_name[i])
# kitti_eval(result_record[i], dataset)
# exit()
# build the model from a config file and a checkpoint file
model = init_detector(config_file, checkpoint_file, device='cuda:0')
model.CLASSES = dataset.CLASSES
for i,(frame) in enumerate(data):
print(i,'in',len(data))
video_name=frame['video_id']
if video_name_check is None:
video_name_check=video_name
else:
if video_name_check==video_name:
video_length+=1
else:
video_name_check=video_name
video_length=0
print('video_name',video_name,'image_name',frame['filename'],'video_length',video_length)
img_name=frame['filename']
# img = mmcv.imread(os.path.join(data_path,img_name))
img=os.path.join(data_path,img_name)
img_list=[img]
if video_length <11:
for j in range(1,11,1):
img_list.append(os.path.join(data_path,data[i+j]['filename']))
else:
for j in range(-1,-11,-1):
img_list.append(os.path.join(data_path,data[i+j]['filename']))
# img1=os.path.join(data_path,data[i+10]['filename'])
result = inference_trackor(model, img_list)
for j in range(12):
bbox_result=result[j][0]
loc_result=result[j][1].long()
result_record[j].append(bbox_result)
loc_data[j].append(loc_result)
#four value and one score
bboxes = np.vstack(bbox_result)
scores = bboxes[:, -1]
inds = scores > 0
scores=bboxes[inds, :][:,4:]
bboxes = bboxes[inds, :][:,:4]
offset_loc=[]
mask_loc=[]
if j>1:
offset=model.agg.offset[j-2]
mask=model.agg.mask[j-2]
for m in range(len(loc_result)):
# print(offset[scale[str(loc_result[m,2].item())]].shape)
# print(loc_result[m,2])
# print(loc_result[m,0]//loc_result[m,2])
offset_loc.append(offset[scale[str(loc_result[m,2].item())]][0,:,loc_result[m,1]//loc_result[m,2],loc_result[m,0]//loc_result[m,2]].data.cpu())
mask_loc.append(mask[scale[str(loc_result[m,2].item())]][0,:,loc_result[m,1]//loc_result[m,2],loc_result[m,0]//loc_result[m,2]].data.cpu())
# print(j-2)
# print(len(offset_loc),offset_loc[0].shape)
offset_data[j-2].append(offset_loc)
mask_data[j-2].append(mask_loc)
# show_result(img, result, model.CLASSES, show=False,out_file=os.path.join(out_path,video_name,img_name))
labels = [
np.full(bbox.shape[0], i, dtype=np.int32)
for i, bbox in enumerate(bbox_result)
]
labels = np.concatenate(labels)
labels = labels[inds]
frame_data={"video_id":frame['video_id'],"filename":os.path.join(frame['filename']), \
"ann":{"bboxes":bboxes.tolist(),"labels":labels.tolist(), \
"track_id":labels.tolist(),'score':scores.tolist()}}
eval_data[j].append(frame_data)
# if i >10:
# break
for i in range(12):
mmcv.dump(result_record[i], os.path.join(out_path,out_name[i],'det_result.pkl'))
mmcv.dump(loc_data[i], os.path.join(out_path,out_name[i],'loc_result.pkl'))
mmcv.dump(eval_data[i], os.path.join(out_path,out_name[i],'track.pkl'))
if i>1:
mmcv.dump(offset_data[i-2], os.path.join(out_path,out_name[i],'offset.pkl'))
mmcv.dump(mask_data[i-2], os.path.join(out_path,out_name[i],'mask.pkl'))
# for i in range(12):
# result_record[i]=mmcv.load(os.path.join(out_path,out_name[i],'det_result.pkl'))
for i in range(12):
print('evaluating result of ', out_name[i])
kitti_eval(result_record[i], dataset)
# with open(os.path.join('./result/','retina_'+jsonfile_name),'w+',encoding='utf-8') as f:
# data=json.dump(eval_data,f)
# mmcv.dump(outputs, args.out) | [
"mmdet.datasets.build_dataset",
"os.path.exists",
"mmdet.apis.inference_trackor",
"mmdet.apis.init_detector",
"os.path.join",
"json.load",
"mmdet.core.eval_map",
"os.mkdir",
"numpy.vstack",
"numpy.concatenate",
"mmcv.Config.fromfile",
"numpy.full",
"mmcv.load"
] | [((1499, 1532), 'mmcv.Config.fromfile', 'mmcv.Config.fromfile', (['config_file'], {}), '(config_file)\n', (1519, 1532), False, 'import mmcv\n'), ((1701, 1729), 'mmdet.datasets.build_dataset', 'build_dataset', (['cfg.data.test'], {}), '(cfg.data.test)\n', (1714, 1729), False, 'from mmdet.datasets import build_dataloader, build_dataset\n'), ((2638, 2708), 'mmcv.load', 'mmcv.load', (['"""/home/ld/RepPoints/final/epoch13 thres0.1/fuse_result.pkl"""'], {}), "('/home/ld/RepPoints/final/epoch13 thres0.1/fuse_result.pkl')\n", (2647, 2708), False, 'import mmcv\n'), ((3040, 3100), 'mmdet.apis.init_detector', 'init_detector', (['config_file', 'checkpoint_file'], {'device': '"""cuda:0"""'}), "(config_file, checkpoint_file, device='cuda:0')\n", (3053, 3100), False, 'from mmdet.apis import init_detector, inference_detector, show_result, inference_trackor\n'), ((1179, 1330), 'mmdet.core.eval_map', 'eval_map', (['det_results', 'gt_bboxes', 'gt_labels'], {'gt_ignore': 'gt_ignore', 'scale_ranges': 'None', 'iou_thr': 'iou_thr', 'dataset': 'dataset_name', 'print_summary': '(True)'}), '(det_results, gt_bboxes, gt_labels, gt_ignore=gt_ignore,\n scale_ranges=None, iou_thr=iou_thr, dataset=dataset_name, print_summary\n =True)\n', (1187, 1330), False, 'from mmdet.core import eval_map\n'), ((1931, 1943), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1940, 1943), False, 'import json\n'), ((2101, 2125), 'os.path.exists', 'os.path.exists', (['out_path'], {}), '(out_path)\n', (2115, 2125), False, 'import os\n'), ((2128, 2146), 'os.mkdir', 'os.mkdir', (['out_path'], {}), '(out_path)\n', (2136, 2146), False, 'import os\n'), ((3581, 3614), 'os.path.join', 'os.path.join', (['data_path', 'img_name'], {}), '(data_path, img_name)\n', (3593, 3614), False, 'import os\n'), ((3914, 3948), 'mmdet.apis.inference_trackor', 'inference_trackor', (['model', 'img_list'], {}), '(model, img_list)\n', (3931, 3948), False, 'from mmdet.apis import init_detector, inference_detector, show_result, inference_trackor\n'), ((1859, 1897), 'os.path.join', 'os.path.join', (['data_path', 'jsonfile_name'], {}), '(data_path, jsonfile_name)\n', (1871, 1897), False, 'import os\n'), ((4142, 4164), 'numpy.vstack', 'np.vstack', (['bbox_result'], {}), '(bbox_result)\n', (4151, 4164), True, 'import numpy as np\n'), ((5200, 5222), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (5214, 5222), True, 'import numpy as np\n'), ((5562, 5615), 'os.path.join', 'os.path.join', (['out_path', 'out_name[i]', '"""det_result.pkl"""'], {}), "(out_path, out_name[i], 'det_result.pkl')\n", (5574, 5615), False, 'import os\n'), ((5639, 5692), 'os.path.join', 'os.path.join', (['out_path', 'out_name[i]', '"""loc_result.pkl"""'], {}), "(out_path, out_name[i], 'loc_result.pkl')\n", (5651, 5692), False, 'import os\n'), ((5717, 5765), 'os.path.join', 'os.path.join', (['out_path', 'out_name[i]', '"""track.pkl"""'], {}), "(out_path, out_name[i], 'track.pkl')\n", (5729, 5765), False, 'import os\n'), ((2179, 2214), 'os.path.join', 'os.path.join', (['out_path', 'out_name[i]'], {}), '(out_path, out_name[i])\n', (2191, 2214), False, 'import os\n'), ((5102, 5143), 'numpy.full', 'np.full', (['bbox.shape[0]', 'i'], {'dtype': 'np.int32'}), '(bbox.shape[0], i, dtype=np.int32)\n', (5109, 5143), True, 'import numpy as np\n'), ((5301, 5332), 'os.path.join', 'os.path.join', (["frame['filename']"], {}), "(frame['filename'])\n", (5313, 5332), False, 'import os\n'), ((5804, 5853), 'os.path.join', 'os.path.join', (['out_path', 'out_name[i]', '"""offset.pkl"""'], {}), "(out_path, out_name[i], 'offset.pkl')\n", (5816, 5853), False, 'import os\n'), ((5881, 5928), 'os.path.join', 'os.path.join', (['out_path', 'out_name[i]', '"""mask.pkl"""'], {}), "(out_path, out_name[i], 'mask.pkl')\n", (5893, 5928), False, 'import os\n'), ((3697, 3745), 'os.path.join', 'os.path.join', (['data_path', "data[i + j]['filename']"], {}), "(data_path, data[i + j]['filename'])\n", (3709, 3745), False, 'import os\n'), ((3802, 3850), 'os.path.join', 'os.path.join', (['data_path', "data[i + j]['filename']"], {}), "(data_path, data[i + j]['filename'])\n", (3814, 3850), False, 'import os\n')] |
# source: https://github.com/adambielski/siamese-triplet/blob/master/losses.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class ContrastiveLoss(nn.Module):
"""
Contrastive loss
Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise
"""
def __init__(self, margin):
super(ContrastiveLoss, self).__init__()
self.margin = margin
def forward(self, output1, output2, target, size_average=True):
distances = (output2 - output1).pow(2).sum(1) # squared distances
losses = 0.5 * (target.float() * distances +
(1 + -1 * target).float() * F.relu(self.margin - distances.sqrt()).pow(2))
return losses.mean() if size_average else losses.sum()
class TripletLoss(nn.Module):
"""
Triplet loss
Takes embeddings of an anchor sample, a positive sample and a negative sample
"""
def __init__(self, margin):
super(TripletLoss, self).__init__()
self.margin = margin
def forward(self, anchor, positive, negative, size_average=True):
distance_positive = (anchor - positive).pow(2).sum(1) # .pow(.5)
distance_negative = (anchor - negative).pow(2).sum(1) # .pow(.5)
losses = F.relu(distance_positive - distance_negative + self.margin)
return losses.mean() if size_average else losses.sum()
class OnlineContrastiveLoss(nn.Module):
"""
Online Contrastive loss
Takes a batch of embeddings and corresponding labels.
Pairs are generated using pair_selector object that take embeddings and targets and return indices of positive
and negative pairs
"""
def __init__(self, margin, pair_selector):
super(OnlineContrastiveLoss, self).__init__()
self.margin = margin
self.pair_selector = pair_selector
def forward(self, embeddings, target):
# print('embeddings losses', embeddings)
# print('target losses', target)
positive_pairs, negative_pairs = self.pair_selector.get_pairs(embeddings, target)
# print('pos pairs',positive_pairs)
# print('neg pairs', negative_pairs)
try:
num = len(negative_pairs)*2
except:
num = 1
#positive_pairs = torch.from_numpy(positive_pairs).cuda() #torch.tensor(positive_pairs)
negative_pairs = torch.from_numpy(np.array(negative_pairs, dtype='float32')) #torch.tensor(negative_pairs)
#print('pos pairs',positive_pairs)
#print('neg pairs', negative_pairs)
hinge_neg_dist = torch.clamp(self.margin - negative_pairs, min=0.0)
loss_imposter = torch.pow(hinge_neg_dist, 2)
loss_genuine = torch.pow(positive_pairs, 2)
loss2x = loss_genuine + loss_imposter
#ave_loss = loss2x.mean()
ave_loss = torch.sum(loss2x) / 2.0 / num
loss = ave_loss
return loss
class OnlineTripletLoss(nn.Module):
"""
Online Triplets loss
Takes a batch of embeddings and corresponding labels.
Triplets are generated using triplet_selector object that take embeddings and targets and return indices of
triplets
"""
def __init__(self, margin, triplet_selector):
super(OnlineTripletLoss, self).__init__()
self.margin = margin
self.triplet_selector = triplet_selector
def forward(self, embeddings, target):
triplets = self.triplet_selector.get_triplets(embeddings, target)
if embeddings.is_cuda:
triplets = triplets.cuda()
ap_distances = (embeddings[triplets[:, 0]] - embeddings[triplets[:, 1]]).pow(2).sum(1) # .pow(.5)
an_distances = (embeddings[triplets[:, 0]] - embeddings[triplets[:, 2]]).pow(2).sum(1) # .pow(.5)
losses = F.relu(ap_distances - an_distances + self.margin)
return losses.mean(), len(triplets)
| [
"torch.pow",
"numpy.array",
"torch.sum",
"torch.nn.functional.relu",
"torch.clamp"
] | [((1316, 1375), 'torch.nn.functional.relu', 'F.relu', (['(distance_positive - distance_negative + self.margin)'], {}), '(distance_positive - distance_negative + self.margin)\n', (1322, 1375), True, 'import torch.nn.functional as F\n'), ((2625, 2675), 'torch.clamp', 'torch.clamp', (['(self.margin - negative_pairs)'], {'min': '(0.0)'}), '(self.margin - negative_pairs, min=0.0)\n', (2636, 2675), False, 'import torch\n'), ((2700, 2728), 'torch.pow', 'torch.pow', (['hinge_neg_dist', '(2)'], {}), '(hinge_neg_dist, 2)\n', (2709, 2728), False, 'import torch\n'), ((2752, 2780), 'torch.pow', 'torch.pow', (['positive_pairs', '(2)'], {}), '(positive_pairs, 2)\n', (2761, 2780), False, 'import torch\n'), ((3816, 3865), 'torch.nn.functional.relu', 'F.relu', (['(ap_distances - an_distances + self.margin)'], {}), '(ap_distances - an_distances + self.margin)\n', (3822, 3865), True, 'import torch.nn.functional as F\n'), ((2440, 2481), 'numpy.array', 'np.array', (['negative_pairs'], {'dtype': '"""float32"""'}), "(negative_pairs, dtype='float32')\n", (2448, 2481), True, 'import numpy as np\n'), ((2880, 2897), 'torch.sum', 'torch.sum', (['loss2x'], {}), '(loss2x)\n', (2889, 2897), False, 'import torch\n')] |
import os
import numpy as np
import time
from gym import utils
from gym.envs.robotics import hand_env
from gym.envs.robotics.utils import robot_get_obs
from gym import spaces
FINGERTIP_SITE_NAMES = [
'robot0:S_fftip',
'robot0:S_mftip',
'robot0:S_rftip',
'robot0:S_lftip',
'robot0:S_thtip',
]
DEFAULT_INITIAL_QPOS = {
'robot0:WRJ1': -0.16514339750464327,
'robot0:WRJ0': -0.31973286565062153,
'robot0:FFJ3': 0.14340512546557435,
'robot0:FFJ2': 0.32028208333591573,
'robot0:FFJ1': 0.7126053607727917,
'robot0:FFJ0': 0.6705281001412586,
'robot0:MFJ3': 0.000246444303701037,
'robot0:MFJ2': 0.3152655251085491,
'robot0:MFJ1': 0.7659800313729842,
'robot0:MFJ0': 0.7323156897425923,
'robot0:RFJ3': 0.00038520700007378114,
'robot0:RFJ2': 0.36743546201985233,
'robot0:RFJ1': 0.7119514095008576,
'robot0:RFJ0': 0.6699446327514138,
'robot0:LFJ4': 0.0525442258033891,
'robot0:LFJ3': -0.13615534724474673,
'robot0:LFJ2': 0.39872030433433003,
'robot0:LFJ1': 0.7415570009679252,
'robot0:LFJ0': 0.704096378652974,
'robot0:THJ4': 0.003673823825070126,
'robot0:THJ3': 0.5506291436028695,
'robot0:THJ2': -0.014515151997119306,
'robot0:THJ1': -0.0015229223564485414,
'robot0:THJ0': -0.7894883021600622,
}
MASK = np.zeros((20,))
MASK[:5] = 1.0
# wrist x2
# first finger x4
# middle finger x4
# ring finger x4
# littlefigner x5
# thumb x5
# Ensure we get the path separator correct on windows
MODEL_XML_PATH = os.path.join('hand', 'reach.xml')
def goal_distance(goal_a, goal_b):
assert goal_a.shape == goal_b.shape
return np.linalg.norm(goal_a - goal_b, axis=-1)
class HandReachEnv(hand_env.HandEnv, utils.EzPickle):
def __init__(
self, distance_threshold=0.01, n_substeps=20, relative_control=False,
initial_qpos=DEFAULT_INITIAL_QPOS, reward_type='sparse',
):
utils.EzPickle.__init__(**locals())
self.distance_threshold = distance_threshold
self.reward_type = reward_type
hand_env.HandEnv.__init__(
self, MODEL_XML_PATH, n_substeps=n_substeps, initial_qpos=initial_qpos,
relative_control=relative_control)
obs = self._get_obs()['observation']
self.observation_space = spaces.Box(-np.inf, np.inf, shape=obs.shape, dtype='float32')
def _get_achieved_goal(self):
goal = [self.sim.data.get_site_xpos(name) for name in FINGERTIP_SITE_NAMES]
return np.array(goal).flatten()
# GoalEnv methods
# ----------------------------
def compute_reward(self, achieved_goal, goal, info):
d = goal_distance(achieved_goal, goal)
if self.reward_type == 'sparse':
return -(d > self.distance_threshold).astype(np.float32)
else:
return -d
def step(self, action):
action = np.clip(action, self.action_space.low, self.action_space.high)
self._set_action(action)
self.sim.step()
self._step_callback()
obs = self._get_obs()
done = False
info = {
'end_effector_loc': obs['achieved_goal'],
'reward_energy': np.linalg.norm(action) * -0.1
}
reward = 0 # self.compute_reward(obs['achieved_goal'], self.goal, info)
return obs['observation'], reward, done, info
def reset(self): #todo: need to change this for self.goal
# Attempt to reset the simulator. Since we randomize initial conditions, it
# is possible to get into a state with numerical issues (e.g. due to penetration or
# Gimbel lock) or we may not achieve an initial condition (e.g. an object is within the hand).
# In this case, we just keep randomizing until we eventually achieve a valid initial
# configuration.
did_reset_sim = False
while not did_reset_sim:
did_reset_sim = self._reset_sim()
self.goal = self._sample_goal().copy()
obs = self._get_obs()['observation']
return obs
# RobotEnv methods
# ----------------------------
def _env_setup(self, initial_qpos):
for name, value in initial_qpos.items():
self.sim.data.set_joint_qpos(name, value)
self.sim.forward()
self.initial_goal = self._get_achieved_goal().copy()
self.palm_xpos = self.sim.data.body_xpos[self.sim.model.body_name2id('robot0:palm')].copy()
def _get_obs(self):
robot_qpos, robot_qvel = robot_get_obs(self.sim)
achieved_goal = self._get_achieved_goal().ravel()
observation = np.concatenate([robot_qpos, robot_qvel, achieved_goal])
return {
'observation': observation.copy(),
'achieved_goal': achieved_goal.copy(),
'desired_goal': self.goal.copy(),
}
def _sample_goal(self):
thumb_name = 'robot0:S_thtip'
finger_names = [name for name in FINGERTIP_SITE_NAMES if name != thumb_name]
finger_name = self.np_random.choice(finger_names)
thumb_idx = FINGERTIP_SITE_NAMES.index(thumb_name)
finger_idx = FINGERTIP_SITE_NAMES.index(finger_name)
assert thumb_idx != finger_idx
# Pick a meeting point above the hand.
meeting_pos = self.palm_xpos + np.array([0.0, -0.09, 0.05])
meeting_pos += self.np_random.normal(scale=0.005, size=meeting_pos.shape)
# Slightly move meeting goal towards the respective finger to avoid that they
# overlap.
goal = self.initial_goal.copy().reshape(-1, 3)
for idx in [thumb_idx, finger_idx]:
offset_direction = (meeting_pos - goal[idx])
offset_direction /= np.linalg.norm(offset_direction)
goal[idx] = meeting_pos - 0.005 * offset_direction
if self.np_random.uniform() < 0.1:
# With some probability, ask all fingers to move back to the origin.
# This avoids that the thumb constantly stays near the goal position already.
goal = self.initial_goal.copy()
return goal.flatten()
def _is_success(self, achieved_goal, desired_goal):
d = goal_distance(achieved_goal, desired_goal)
return (d < self.distance_threshold).astype(np.float32)
def _render_callback(self):
# Visualize targets.
sites_offset = (self.sim.data.site_xpos - self.sim.model.site_pos).copy()
goal = self.goal.reshape(5, 3)
for finger_idx in range(5):
site_name = 'target{}'.format(finger_idx)
site_id = self.sim.model.site_name2id(site_name)
self.sim.model.site_pos[site_id] = goal[finger_idx] - sites_offset[site_id]
# Visualize finger positions.
achieved_goal = self._get_achieved_goal().reshape(5, 3)
for finger_idx in range(5):
site_name = 'finger{}'.format(finger_idx)
site_id = self.sim.model.site_name2id(site_name)
self.sim.model.site_pos[site_id] = achieved_goal[finger_idx] - sites_offset[site_id]
self.sim.forward()
class FingerReachEnv(HandReachEnv):
# only lets the index finger and wrist joint move
def reset(self, goal_pos=None):
# Attempt to reset the simulator. Since we randomize initial conditions, it
# is possible to get into a state with numerical issues (e.g. due to penetration or
# Gimbel lock) or we may not achieve an initial condition (e.g. an object is within the hand).
# In this case, we just keep randomizing until we eventually achieve a valid initial
# configuration.
did_reset_sim = False
while not did_reset_sim:
did_reset_sim = self._reset_sim()
if goal_pos is None:
self.goal = self._sample_goal().copy()
else:
goal = self.initial_goal.copy()
goal[:3] = goal_pos
self.goal = goal
obs = self._get_obs()['observation']
return obs
def step(self, action):
masked_action = action * MASK
return super().step(masked_action)
def _sample_goal(self):
finger_name = 'robot0:S_fftip'
finger_idx = FINGERTIP_SITE_NAMES.index(finger_name)
# Pick a meeting point above the hand.
meeting_pos = self.palm_xpos + np.array([0.0, -0.09, 0.05])
meeting_pos += self.np_random.normal(scale=0.005, size=meeting_pos.shape)
# Slightly move meeting goal towards the respective finger to avoid that they
# overlap.
goal = self.initial_goal.copy().reshape(-1, 3)
idx = finger_idx
offset_direction = (meeting_pos - goal[idx])
# want anywhere between the default qpos and the meeting place
goal[idx] = meeting_pos - np.random.random() * offset_direction
if self.np_random.uniform() < 0.1:
# With some probability, ask all fingers to move back to the origin.
# This avoids that the thumb constantly stays near the goal position already.
goal = self.initial_goal.copy().reshape(-1, 3)
return goal[finger_idx].flatten()
def _render_callback(self):
# Visualize targets.
sites_offset = (self.sim.data.site_xpos - self.sim.model.site_pos).copy()
goal = self.goal.reshape(5, 3)
for finger_idx in range(5):
site_name = 'target{}'.format(finger_idx)
site_id = self.sim.model.site_name2id(site_name)
self.sim.model.site_pos[site_id] = goal[finger_idx] - sites_offset[site_id]
# Visualize finger positions.
achieved_goal = self._get_achieved_goal().reshape(5, 3)
for finger_idx in range(5):
site_name = 'finger{}'.format(finger_idx)
site_id = self.sim.model.site_name2id(site_name)
self.sim.model.site_pos[site_id] = achieved_goal[finger_idx] - sites_offset[site_id]
self.sim.forward()
if __name__ == '__main__':
# env = HandReachEnv()
env = FingerReachEnv()
state = env.reset()
env.render()
import ipdb; ipdb.set_trace()
for index in range(20):
if index < 2:
continue
print(index)
time.sleep(1)
for _ in range(50):
action = np.zeros((20,))
action[index] = 0.5
env.step(action)
env.render()
for _ in range(50):
action = np.zeros((20,))
action[index] = -0.5
env.step(action)
env.render()
| [
"numpy.clip",
"gym.envs.robotics.hand_env.HandEnv.__init__",
"ipdb.set_trace",
"numpy.random.random",
"os.path.join",
"time.sleep",
"gym.spaces.Box",
"numpy.array",
"numpy.zeros",
"numpy.concatenate",
"numpy.linalg.norm",
"gym.envs.robotics.utils.robot_get_obs"
] | [((1313, 1328), 'numpy.zeros', 'np.zeros', (['(20,)'], {}), '((20,))\n', (1321, 1328), True, 'import numpy as np\n'), ((1514, 1547), 'os.path.join', 'os.path.join', (['"""hand"""', '"""reach.xml"""'], {}), "('hand', 'reach.xml')\n", (1526, 1547), False, 'import os\n'), ((1636, 1676), 'numpy.linalg.norm', 'np.linalg.norm', (['(goal_a - goal_b)'], {'axis': '(-1)'}), '(goal_a - goal_b, axis=-1)\n', (1650, 1676), True, 'import numpy as np\n'), ((9995, 10011), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (10009, 10011), False, 'import ipdb\n'), ((2046, 2182), 'gym.envs.robotics.hand_env.HandEnv.__init__', 'hand_env.HandEnv.__init__', (['self', 'MODEL_XML_PATH'], {'n_substeps': 'n_substeps', 'initial_qpos': 'initial_qpos', 'relative_control': 'relative_control'}), '(self, MODEL_XML_PATH, n_substeps=n_substeps,\n initial_qpos=initial_qpos, relative_control=relative_control)\n', (2071, 2182), False, 'from gym.envs.robotics import hand_env\n'), ((2282, 2343), 'gym.spaces.Box', 'spaces.Box', (['(-np.inf)', 'np.inf'], {'shape': 'obs.shape', 'dtype': '"""float32"""'}), "(-np.inf, np.inf, shape=obs.shape, dtype='float32')\n", (2292, 2343), False, 'from gym import spaces\n'), ((2858, 2920), 'numpy.clip', 'np.clip', (['action', 'self.action_space.low', 'self.action_space.high'], {}), '(action, self.action_space.low, self.action_space.high)\n', (2865, 2920), True, 'import numpy as np\n'), ((4465, 4488), 'gym.envs.robotics.utils.robot_get_obs', 'robot_get_obs', (['self.sim'], {}), '(self.sim)\n', (4478, 4488), False, 'from gym.envs.robotics.utils import robot_get_obs\n'), ((4569, 4624), 'numpy.concatenate', 'np.concatenate', (['[robot_qpos, robot_qvel, achieved_goal]'], {}), '([robot_qpos, robot_qvel, achieved_goal])\n', (4583, 4624), True, 'import numpy as np\n'), ((10113, 10126), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (10123, 10126), False, 'import time\n'), ((5252, 5280), 'numpy.array', 'np.array', (['[0.0, -0.09, 0.05]'], {}), '([0.0, -0.09, 0.05])\n', (5260, 5280), True, 'import numpy as np\n'), ((5657, 5689), 'numpy.linalg.norm', 'np.linalg.norm', (['offset_direction'], {}), '(offset_direction)\n', (5671, 5689), True, 'import numpy as np\n'), ((8244, 8272), 'numpy.array', 'np.array', (['[0.0, -0.09, 0.05]'], {}), '([0.0, -0.09, 0.05])\n', (8252, 8272), True, 'import numpy as np\n'), ((10176, 10191), 'numpy.zeros', 'np.zeros', (['(20,)'], {}), '((20,))\n', (10184, 10191), True, 'import numpy as np\n'), ((10327, 10342), 'numpy.zeros', 'np.zeros', (['(20,)'], {}), '((20,))\n', (10335, 10342), True, 'import numpy as np\n'), ((2478, 2492), 'numpy.array', 'np.array', (['goal'], {}), '(goal)\n', (2486, 2492), True, 'import numpy as np\n'), ((3160, 3182), 'numpy.linalg.norm', 'np.linalg.norm', (['action'], {}), '(action)\n', (3174, 3182), True, 'import numpy as np\n'), ((8699, 8717), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (8715, 8717), True, 'import numpy as np\n')] |
"""
Author: <NAME>
Copyright: (C) 2019-2020 <http://www.dei.unipd.it/
Department of Information Engineering> (DEI), <http://www.unipd.it/ University of Padua>, Italy
License: <http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0>
"""
import multiprocessing
import os
from fastText import load_model
from gensim.models import KeyedVectors
from tqdm import tqdm
import data_utils as du
import util
import numpy as np
from model import Model
import tensorflow as tf
import evaluation as ev
import gensim
import lexical_models as lm
from nltk.corpus import wordnet
from itertools import product
#####################################################################################################################
# INPUT DATA PARSING
#####################################################################################################################
def read_collection(coll_main_folder, output_model_path, stemming, stoplist=None):
if not os.path.isfile(output_model_path):
if stoplist is None:
stoplist = util.load_indri_stopwords()
text_by_name = {}
print('reading files in folder')
pool = multiprocessing.Pool(8)
fnames_list = os.listdir(coll_main_folder)
doc_paths_list = [os.path.join(coll_main_folder, filename) for filename in fnames_list]
print('processing collection')
tokenized_docs = pool.starmap(util.tokenize,
[(' '.join(open(fp, 'r').readlines()), stemming, stoplist) for fp in
doc_paths_list])
for i in range(len(fnames_list)):
text_by_name[fnames_list[i].split(r'.')[0]] = tokenized_docs[i]
print('saving model')
util.save_model(text_by_name, output_model_path)
else:
print('loading model: %s' % output_model_path)
text_by_name = util.load_model(output_model_path)
return text_by_name
def compute_input_data(text_by_name, ftext_model_path, encoded_out_folder_docs):
print('loading fasttext model')
f = load_model(ftext_model_path)
encoded_docs_by_name = {}
wi = {}
print('encoding collection')
we_matrix = []
for dn, dt in tqdm(text_by_name.items()):
encoded_d = []
for tok in dt:
if tok not in wi.keys():
wv = f.get_word_vector(tok)
wi[tok] = len(wi)
we_matrix.append(wv)
encoded_d.append(wi[tok])
encoded_docs_by_name[dn] = encoded_d
util.save_model(encoded_d, os.path.join(encoded_out_folder_docs, dn))
return encoded_docs_by_name, wi, np.array(we_matrix)
def encode_queries(queries_main_folder, wi, stemming):
sw = util.load_indri_stopwords()
encoded_qbn = {}
for filename in tqdm(os.listdir(queries_main_folder)):
fp = os.path.join(queries_main_folder, filename)
if os.path.isfile(fp):
tokenized_query = util.tokenize(' '.join(open(fp, 'r').readlines()), stemming=stemming, stoplist=sw)
qn = filename.split(r'.')[0]
encoded_qbn[qn] = [wi[w] for w in tokenized_query if w in wi.keys()]
return encoded_qbn
def compute_inverted_index(coll_folder, stemming, output_file_path_ii):
if not os.path.isfile(output_file_path_ii):
print('computing inverted index')
inverted_idx = {}
sw = util.load_indri_stopwords()
doc_n = 0
for filename in tqdm(os.listdir(coll_folder)):
fp = os.path.join(coll_folder, filename)
doc_id = filename.split(r'.')[0]
if os.path.isfile(fp):
doc_n += 1
d = util.tokenize(' '.join(open(fp, 'r').readlines()), stemming, stoplist=sw)
set_w_in_doc = set(d)
for w in set_w_in_doc:
if w in inverted_idx.keys():
inverted_idx[w].append((doc_id, d.count(w)))
else:
inverted_idx[w] = [(doc_id, d.count(w))]
util.save_model(inverted_idx, output_file_path_ii)
else:
inverted_idx = util.load_model(output_file_path_ii)
return inverted_idx
def compute_data():
ftext_model_path = '../data/fasttext_models/wiki.en.bin'
output_path_wi_model = '../data/fasttext_models/wi_robust'
output_path_ii_model = '../data/fasttext_models/ii_robust'
output_path_idf_model = '../data/fasttext_models/idf_robust'
output_path_encoded_d_model = '../data/fasttext_models/encoded_dbn'
output_path_encoded_q_model = '../data/fasttext_models/encoded_qbn'
output_path_we_matrix_model = '../data/fasttext_models/word_embeddings_matrix_robust'
coll_path = '/Users/albertopurpura/ExperimentalCollections/Robust04/processed/corpus'
queries_main_folder = '/Users/albertopurpura/ExperimentalCollections/Robust04/processed/topics'
output_model_path = 'data/robust/stemmed_coll_model'
encoded_out_folder_docs = 'data/robust/stemmed_encoded_docs_ft'
stemming = True
if not os.path.isfile(output_path_ii_model):
print('computing inverted index')
ii = compute_inverted_index(coll_path, stemming, output_path_ii_model)
util.save_model(ii, output_path_ii_model)
else:
print('loading inverted index')
ii = util.load_model(output_path_ii_model)
if not os.path.isfile(output_path_encoded_d_model):
text_dbn = read_collection(coll_path, output_model_path, stemming=stemming,
stoplist=util.load_indri_stopwords())
encoded_dbn, wi, we_matrix = compute_input_data(text_dbn, ftext_model_path, encoded_out_folder_docs)
util.save_model(encoded_dbn, output_path_encoded_d_model)
util.save_model(wi, output_path_wi_model)
util.save_model(we_matrix, output_path_we_matrix_model)
else:
encoded_dbn = util.load_model(output_path_encoded_d_model)
wi = util.load_model(output_path_wi_model)
we_matrix = util.load_model(output_path_we_matrix_model)
if not os.path.isfile(output_path_encoded_q_model):
encoded_qbn = encode_queries(queries_main_folder, wi, stemming)
util.save_model(encoded_qbn, output_path_encoded_q_model)
else:
encoded_qbn = util.load_model(output_path_encoded_q_model)
idf_scores = du.compute_idf(coll_path, stemming, output_path_ii_model, output_path_idf_model)
return encoded_dbn, encoded_qbn, we_matrix, wi, ii, idf_scores
#####################################################################################################################
#####################################################################################################################
#####################################################################################################################
# TRAINING
#####################################################################################################################
def pad(to_pad, padding_value, max_len):
retval = np.ones(max_len) * padding_value
for i in range(len(to_pad)):
retval[i] = to_pad[i]
return retval
def compute_training_pairs_w_queries_variations(fold_idx, coll, n_iter_per_query, gt_file, dbn, qbn, ftt_model, iwi,
wi):
model_name = 'qn_rd_nrd_pairs_w2v_gk_' + str(fold_idx) + '_' + str(coll) + '_' + str(n_iter_per_query)
if not os.path.isfile(model_name):
rd_b_qry = {}
nrd_by_qry = {}
for line in open(gt_file):
data = line.split()
qname = data[0].strip()
dname = data[2].strip()
if dname not in dbn.keys():
continue
rj = int(data[3].strip())
if qname not in rd_b_qry.keys():
rd_b_qry[qname] = []
nrd_by_qry[qname] = []
if rj > 0:
rd_b_qry[qname].append(dname)
else:
nrd_by_qry[qname].append(dname)
test_q_names = list(qbn.keys())
np.random.shuffle(test_q_names)
qn_rd_nrd_pairs = []
for qn in test_q_names:
if qn not in rd_b_qry.keys():
continue
# add training examples with original query:
encoded_q = qbn[qn]
tmp_rdocs = np.random.choice(rd_b_qry[qn], n_iter_per_query, replace=True)
tmp_nrdocs = np.random.choice(nrd_by_qry[qn], n_iter_per_query, replace=True)
for i in range(n_iter_per_query):
qn_rd_nrd_pairs.append((encoded_q, dbn[tmp_rdocs[i]], dbn[tmp_nrdocs[i]]))
print('original query: ' + ' '.join([iwi[w] for w in encoded_q]))
# add extra training examples
for i in range(len(encoded_q)):
encoded_q_variation = encoded_q
curr_q_word = iwi[encoded_q[i]]
similar_words = get_synonyms(curr_q_word, ftt_model)
for sw in similar_words:
sw = util.stem(sw)
if sw in wi.keys() and curr_q_word != sw:
print('word = ' + curr_q_word + ', substitute = ' + sw)
encoded_q_variation[i] = wi[sw]
print('alternative query: ' + ' '.join([iwi[w] for w in encoded_q_variation]))
tmp_rdocs = np.random.choice(rd_b_qry[qn], n_iter_per_query, replace=True)
tmp_nrdocs = np.random.choice(nrd_by_qry[qn], n_iter_per_query, replace=True)
for j in range(n_iter_per_query):
qn_rd_nrd_pairs.append((encoded_q_variation, dbn[tmp_rdocs[j]], dbn[tmp_nrdocs[j]]))
np.random.shuffle(qn_rd_nrd_pairs)
util.save_model(qn_rd_nrd_pairs, model_name)
else:
qn_rd_nrd_pairs = util.load_model(model_name)
return qn_rd_nrd_pairs
def get_synonyms(source, ft_model):
# a good replacement for a query term should have a similar semantic meaning and a similar usage context
# the first aspect is satisfied by wordnet, the second aspect is checked with the fastText model.
synonyms = []
for syn in wordnet.synsets(source):
for lm in syn.lemmas():
if lm.name() in ft_model.wv.vocab:
rcsim = ft_model.relative_cosine_similarity(source, lm.name(), topn=10)
if rcsim > 0.10:
synonyms.append(lm.name())
# print(set(synonyms))
return set(synonyms)
def compute_training_pairs(fold_idx, coll, n_iter_per_query, gt_file, dbn, qbn):
if not os.path.isfile('qn_rd_nrd_pairs_wn2v' + str(fold_idx) + '_' + str(coll) + '_' + str(n_iter_per_query)):
rd_b_qry = {}
nrd_by_qry = {}
for line in open(gt_file):
data = line.split()
qname = data[0].strip()
dname = data[2].strip()
if dname not in dbn.keys():
continue
rj = int(data[3].strip())
if qname not in rd_b_qry.keys():
rd_b_qry[qname] = []
nrd_by_qry[qname] = []
if rj > 0:
rd_b_qry[qname].append(dname)
else:
nrd_by_qry[qname].append(dname)
test_q_names = list(qbn.keys())
np.random.shuffle(test_q_names)
qn_rd_nrd_pairs = []
for qn in test_q_names:
if qn not in rd_b_qry.keys():
continue
tmp_rdocs = np.random.choice(rd_b_qry[qn], n_iter_per_query, replace=True)
tmp_nrdocs = np.random.choice(nrd_by_qry[qn], n_iter_per_query, replace=True)
for i in range(n_iter_per_query):
qn_rd_nrd_pairs.append((qbn[qn], dbn[tmp_rdocs[i]], dbn[tmp_nrdocs[i]]))
np.random.shuffle(qn_rd_nrd_pairs)
util.save_model(qn_rd_nrd_pairs, 'qn_rd_nrd_pairs_w2v_gk' + str(fold_idx) + '_' + str(coll))
else:
qn_rd_nrd_pairs = util.load_model('qn_rd_nrd_pairs_w2v_gk' + str(fold_idx) + '_' + str(coll))
return qn_rd_nrd_pairs
def compute_wn_sim(qw, dw, i, j, k):
allsyns1 = wordnet.synsets(qw)
allsyns2 = wordnet.synsets(dw)
if len(allsyns2) == 0 or len(allsyns1) == 0:
return 0, i, j, k
best = max((wordnet.wup_similarity(s1, s2) or 0, s1, s2) for s1, s2 in product(allsyns1, allsyns2))[0]
return best, i, j, k
"""
def compute_addit_info_sm_parallel(encoded_q, encoded_d, mql, mdl, iwi):
pool = multiprocessing.Pool(100)
args_to_pass = []
for i in range(len(encoded_q)):
qw = iwi[encoded_q[i]]
for j in range(len(encoded_d)):
dw = iwi[encoded_d[j]]
args_to_pass.append((qw, dw, i, j))
print('computing data in parallel')
results = pool.starmap(compute_wn_wup_sim, args_to_pass)
pool.close()
coeff = np.ones((mql, mdl))
for item in results:
val = item[0]
i = item[1]
j = item[2]
coeff[i, j] = val
return coeff
"""
def compute_addit_info_sm_parallel(encoded_queries, encoded_docs, mql, mdl, iwi, wn2v_model):
# print('computing input data for parallel computation')
coeffs = []
for k in range(len(encoded_queries)):
coeffs.append(np.ones((mql, mdl))) # to use for multipl
# coeffs.append(np.zeros((mql, mdl)))
encoded_q = encoded_queries[k]
encoded_d = encoded_docs[k]
for i in range(len(encoded_q)):
qw = iwi[encoded_q[i]]
for j in range(len(encoded_d)):
dw = iwi[encoded_d[j]]
if qw in wn2v_model.wv.vocab and dw in wn2v_model.wv.vocab:
qwe = wn2v_model[qw] / np.linalg.norm(wn2v_model[qw])
dwe = wn2v_model[dw] / np.linalg.norm(wn2v_model[dw])
cos_sim = np.dot(qwe, dwe)
coeffs[k][i, j] = cos_sim
return coeffs
def compute_addit_info_sm(encoded_q, encoded_d, mql, mdl, iwi):
# http://www.nltk.org/howto/wordnet.html
# https://stackoverflow.com/questions/30829382/check-the-similarity-between-two-words-with-nltk-with-python
coeff = np.ones((mql, mdl))
for i in range(len(encoded_q)):
qw = iwi[encoded_q[i]]
allsyns1 = wordnet.synsets(qw) # set(ss for word in list1 for ss in wordnet.synsets(word))
for j in range(len(encoded_d)):
dw = iwi[encoded_d[j]]
allsyns2 = wordnet.synsets(dw) # set(ss for word in list2 for ss in wordnet.synsets(word))
if len(allsyns2) == 0 or len(allsyns1) == 0:
coeff[i, j] = 0
else:
best = max((wordnet.wup_similarity(s1, s2) or 0, s1, s2) for s1, s2 in product(allsyns1, allsyns2))
coeff[i, j] = best[0]
return coeff
def compute_training_batches(gt_file, dbn, qbn, batch_size, padding_value, fold_idx, ftt_model, iwi, wi,
n_iter_per_query=200, max_q_len=4, max_d_len=500, coll='robust'):
qn_rd_nrd_pairs = compute_training_pairs(fold_idx, coll, n_iter_per_query, gt_file, dbn, qbn)
queries_batch = []
rel_docs_batch = []
nrel_docs_batch = []
batch_pd_lengths = []
batch_nd_lengths = []
batch_q_lengths = []
print('# iterations per epoch: ' + str(int(len(qn_rd_nrd_pairs) / batch_size)))
for encoded_q, encoded_rd, encoded_nrd in qn_rd_nrd_pairs:
batch_pd_lengths.append(len(encoded_rd))
batch_nd_lengths.append(len(encoded_nrd))
batch_q_lengths.append(len(encoded_q))
queries_batch.append(encoded_q)
rel_docs_batch.append(encoded_rd)
nrel_docs_batch.append(encoded_nrd)
if len(queries_batch) == batch_size:
data1 = []
data2 = []
y = []
data1_len = []
data2_len = []
for i in range(len(queries_batch)):
data1.append(pad(queries_batch[i], padding_value, max_q_len))
data1.append(pad(queries_batch[i], padding_value, max_q_len))
y.append(1)
y.append(0)
data2.append(pad(rel_docs_batch[i], padding_value, max_d_len))
data2.append(pad(nrel_docs_batch[i], padding_value, max_d_len))
data1_len.append(batch_q_lengths[i])
data1_len.append(batch_q_lengths[i])
data2_len.append(batch_pd_lengths[i])
data2_len.append(batch_nd_lengths[i])
yield max_q_len, max_d_len, data1, data2, y, data1_len, data2_len
queries_batch = []
rel_docs_batch = []
nrel_docs_batch = []
batch_pd_lengths = []
batch_nd_lengths = []
batch_q_lengths = []
def compute_idf_scaling_coeffs(encoded_q, iwi, idf_scores, mql, mdl):
coeffs = np.ones((mql, mdl))
for i in range(len(encoded_q)):
if int(encoded_q[i]) in iwi.keys():
w = iwi[int(encoded_q[i])]
coeffs[i] = np.ones(mdl) * idf_scores[w]
return coeffs
def compute_training_batches_w_coeffs(gt_file, dbn, qbn, batch_size, padding_value, fold_idx, ftt_model, iwi, wi,
wn2v_model, n_iter_per_query=200, max_q_len=4, max_d_len=500, coll='robust'):
qn_rd_nrd_pairs = compute_training_pairs(fold_idx, coll, n_iter_per_query, gt_file, dbn, qbn)
queries_batch = []
rel_docs_batch = []
nrel_docs_batch = []
batch_pd_lengths = []
batch_nd_lengths = []
batch_q_lengths = []
coeffs = []
print('# iterations per epoch: ' + str(len(qn_rd_nrd_pairs)))
for encoded_q, encoded_rd, encoded_nrd in qn_rd_nrd_pairs:
batch_pd_lengths.append(len(encoded_rd))
batch_nd_lengths.append(len(encoded_nrd))
batch_q_lengths.append(len(encoded_q))
queries_batch.append(encoded_q)
rel_docs_batch.append(encoded_rd)
nrel_docs_batch.append(encoded_nrd)
if len(queries_batch) == batch_size:
data1 = []
data2 = []
y = []
data1_len = []
data2_len = []
coeffs_p = compute_addit_info_sm_parallel(queries_batch, rel_docs_batch, max_q_len, max_d_len, iwi,
wn2v_model)
coeffs_n = compute_addit_info_sm_parallel(queries_batch, nrel_docs_batch, max_q_len, max_d_len, iwi,
wn2v_model)
coeffs = []
for i in range(len(queries_batch)):
data1.append(pad(queries_batch[i], padding_value, max_q_len))
data1.append(pad(queries_batch[i], padding_value, max_q_len))
y.append(1)
y.append(0)
coeffs.append(coeffs_p[i])
coeffs.append(coeffs_n[i])
data2.append(pad(rel_docs_batch[i], padding_value, max_d_len))
data2.append(pad(nrel_docs_batch[i], padding_value, max_d_len))
data1_len.append(batch_q_lengths[i])
data1_len.append(batch_q_lengths[i])
data2_len.append(batch_pd_lengths[i])
data2_len.append(batch_nd_lengths[i])
yield max_q_len, max_d_len, data1, data2, y, data1_len, data2_len, coeffs
queries_batch = []
rel_docs_batch = []
nrel_docs_batch = []
batch_pd_lengths = []
batch_nd_lengths = []
batch_q_lengths = []
coeffs = []
#####################################################################################################################
#####################################################################################################################
#####################################################################################################################
# RANKING
#####################################################################################################################
def get_relevance_scores_by_qry(run_to_rerank):
retval = {}
for line in open(run_to_rerank):
data = line.split()
qname = data[0]
rel_score = float(data[4])
dname = data[2]
if qname not in retval.keys():
retval[qname] = {}
retval[qname][dname] = rel_score
return retval
def compute_docs_to_rerank_by_query(queries_names, qbn, dbn, iwi, ii, fasttext_vec_model):
docs_to_rerank_by_qry = {}
for qn in tqdm(queries_names):
q = qbn[qn]
for qw in q:
query_word = iwi[qw]
if query_word not in fasttext_vec_model.wv.vocab:
continue
# here I try to find the most similar terms to the stemmed word
similar_words = [w[0] for w in fasttext_vec_model.most_similar(positive=[query_word], topn=10)]
for w in similar_words:
# stem the most similar words found in the model
w = util.stem(w)
if w in ii.keys():
if qn not in docs_to_rerank_by_qry.keys():
docs_to_rerank_by_qry[qn] = []
docs_to_rerank_by_qry[qn].extend([pl[0] for pl in ii[w]])
return docs_to_rerank_by_qry
def compute_docs_to_rerank_by_query_lexical(run_to_rerank, test_query_names):
docs_to_rerank_by_query = {}
for line in open(run_to_rerank, 'r'):
data = line.split()
qname = data[0]
dname = data[2]
if qname in test_query_names:
if qname in docs_to_rerank_by_query.keys():
docs_to_rerank_by_query[qname].append(dname)
else:
docs_to_rerank_by_query[qname] = [dname]
return docs_to_rerank_by_query
def compute_docs_to_rerank_by_query_lexical_bm25(query, dbn, ii, iwi, n_docs_to_keep=2000):
docs_with_scores = lm.rank_docs_w_bm25(query, dbn, ii, iwi)
dnames = docs_with_scores.keys()
scores = np.array([docs_with_scores[dn] for dn in dnames])
return (np.array(list(dnames))[np.argsort(-scores)])[0:n_docs_to_keep]
def compute_test_fd_w2v(qbn, dbn, fasttext_vec_model, iwi, ii_dict, max_q_len, max_d_len, padding_value, run_to_rerank):
d_names_bqn = compute_docs_to_rerank_by_query_lexical(run_to_rerank, qbn.keys())
for q_name in qbn.keys():
# d_names = compute_docs_to_rerank_by_query_lexical_bm25(qbn[q_name], dbn, ii_dict, iwi)
d_names = d_names_bqn[q_name]
docs = [dbn[dn] for dn in d_names if dn in dbn.keys()]
d_lengths = [len(d) for d in docs]
padded_d = [pad(d, padding_value, max_d_len) for d in docs]
q = pad(qbn[q_name], padding_value, max_q_len)
doc_batch = []
d_lengths_batch = []
d_names_batch = []
for i in range(len(padded_d)):
doc_batch.append(padded_d[i])
d_lengths_batch.append(d_lengths[i])
d_names_batch.append(d_names[i])
if len(doc_batch) == 5000:
yield [q] * len(doc_batch), doc_batch, [len(qbn[q_name])] * len(doc_batch), d_lengths_batch, \
d_names_batch, q_name
doc_batch = []
d_lengths_batch = []
d_names_batch = []
if len(doc_batch) > 0:
yield [q] * len(doc_batch), doc_batch, [len(qbn[q_name])] * len(doc_batch), d_lengths_batch, \
d_names_batch, q_name
# yield [q] * len(padded_d), padded_d, [len(qbn[q_name])] * len(padded_d), d_lengths, d_names, q_name
def compute_test_fd_w_coeffs(qbn, dbn, fasttext_vec_model, iwi, ii_dict, max_q_len, max_d_len, padding_value,
run_to_rerank, wn2v_model, idf_scores):
d_names_bqn = compute_docs_to_rerank_by_query_lexical(run_to_rerank, qbn.keys())
for q_name in qbn.keys():
# d_names = compute_docs_to_rerank_by_query_lexical_bm25(qbn[q_name], dbn, ii_dict, iwi)
d_names = d_names_bqn[q_name]
docs = [dbn[dn] for dn in d_names if dn in dbn.keys()]
d_lengths = [len(d) for d in docs]
padded_d = [pad(d, padding_value, max_d_len) for d in docs]
q = pad(qbn[q_name], padding_value, max_q_len)
# print('computing coefficients')
coeffs = compute_addit_info_sm_parallel([q] * len(docs), docs, max_q_len, max_d_len, iwi, wn2v_model)
# idf_coeffs = [compute_idf_scaling_coeffs(q, iwi, idf_scores, max_q_len, max_d_len)] * len(padded_d)
yield [q] * len(padded_d), padded_d, [len(qbn[q_name])] * len(padded_d), d_lengths, d_names, q_name, coeffs
def true_rerank(sess, model, test_q_b_name, dbn, run_to_rerank, mql, mdl, padding_value, fold_index, test_qrels_file,
epoch, run_name, fasttext_vec_model, iwi, ii_dict, wn2v_model, idf_scores, output_f='../results'):
rel_docs_by_qry = {}
sim_scores_by_qry = {}
all_preds = {}
dnames_to_rerank_by_qry = {}
for i, (data1_test, data2_test, data1_len_test, data2_len_test, d_names, q_name, coeffs) in tqdm(enumerate(
compute_test_fd_w_coeffs(test_q_b_name, dbn, fasttext_vec_model, iwi, ii_dict, mql, mdl, padding_value,
run_to_rerank, wn2v_model, idf_scores))):
if len(test_q_b_name[q_name]) == 0:
continue
feed_dict = {model.X1: data1_test, model.X1_len: data1_len_test, model.X2: data2_test,
model.X2_len: data2_len_test, model.training: False, model.coeffs: coeffs}
# print('computing prediction %d of %d' % (i, len(test_q_b_name)))
pred = model.test_step(sess, feed_dict)
pred = np.array([p[0] for p in pred])
if q_name not in dnames_to_rerank_by_qry.keys():
dnames_to_rerank_by_qry[q_name] = []
all_preds[q_name] = []
dnames_to_rerank_by_qry[q_name].extend(d_names)
all_preds[q_name].extend(pred / np.max(pred))
for q_name in test_q_b_name.keys():
if q_name not in all_preds.keys():
continue
pred = np.array(all_preds[q_name])
rel_docs_by_qry[q_name] = (np.array(dnames_to_rerank_by_qry[q_name])[np.argsort(-pred)])[0:1000]
sim_scores_by_qry[q_name] = pred[np.argsort(-pred)][0:1000]
map_v = util.create_evaluate_ranking(str(fold_index) + '_' + str(epoch) + '_pure_neural', rel_docs_by_qry,
sim_scores_by_qry, test_qrels_file, run_name, output_folder=output_f)
print('map of pure neural model=%2.5f' % map_v)
return map_v
#####################################################################################################################
#####################################################################################################################
#####################################################################################################################
# MAIN:
#####################################################################################################################
def run():
# map intorno al 17-18%
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
gt_path = '../data/robust/qrels.robust2004.txt'
run_to_rerank = '../data/robust/robust.terrier.krovetz.qld.2k.run'
run_name = 'wordnet_embs_MP_evaluated_at_each_epoch'
batch_size = 64
n_epochs = 20
n_folds = 5
max_patience = 10
encoded_dbn, encoded_qbn, we_matrix, wi, ii, idf_scores = compute_data()
print('loading fasttext model with gensim')
fasttext_vec_model = gensim.models.KeyedVectors.load_word2vec_format(
'../data/fasttext_models/wiki-news-300d-1M.vec') # non viene usato piu perche non uso wordnet direttamente ma uso degli embeddings
wn2vec_model = gensim.models.KeyedVectors.load_word2vec_format('../data/wn_embeddings/wn2vec.txt')
print('inverting word index')
iwi = util.invert_wi(wi)
print('turning inverted index to a dict of dicts')
ii_dict = {w: {p[0]: p[1] for p in pl} for w, pl in ii.items()}
print('reducing document lengths')
dbn = {dn: dc[0: min(len(dc), 500)] for dn, dc in encoded_dbn.items()}
mql = max([len(q) for q in encoded_qbn.values()])
mdl = max([len(d) for d in dbn.values()])
print('max query length; %d' % mql)
print('max doc length; %d' % mdl)
padding_value = we_matrix.shape[0] - 1
config = {'embed_size': 50, 'data1_psize': 3, 'data2_psize': 10, 'embedding': we_matrix, 'feat_size': 0,
'fill_word': padding_value, 'data1_maxlen': mql, 'data2_maxlen': mdl}
folds = du.compute_kfolds_train_test(n_folds, list(encoded_qbn.keys()), coll='robust')
print('starting training')
for fold_index in range(len(folds)):
print('Fold: %d' % fold_index)
tf.reset_default_graph()
sess_config = tf.ConfigProto()
sess_config.gpu_options.allow_growth = True
tf.set_random_seed(0)
with tf.Session(config=sess_config) as sess:
tf.set_random_seed(0)
model = Model(config)
model.init_step(sess)
training_q_names, test_q_names = folds[fold_index]
test_q_b_name = {test_q_names[i]: encoded_qbn[test_q_names[i]] for i in range(len(test_q_names))}
test_qrels_file = 'test_qrels_file_' + str(fold_index)
du.compute_test_gt_file(gt_path, list(dbn.keys()), test_q_names, test_qrels_file)
validation_q_names = np.random.choice(training_q_names, int(len(training_q_names) * 0.20), replace=False)
validation_q_b_name = {validation_q_names[i]: encoded_qbn[validation_q_names[i]] for i in
range(len(validation_q_names))}
validation_qrels_file = 'validation_qrels_file_' + str(fold_index)
du.compute_test_gt_file(gt_path, list(dbn.keys()), validation_q_names, validation_qrels_file)
training_q_names = [n for n in training_q_names if n not in validation_q_names]
training_q_b_name = {training_q_names[i]: encoded_qbn[training_q_names[i]] for i in
range(len(training_q_names))}
max_map = 0.0
best_epoch = -1
best_iter = -1
patience = 0
done = False
for epoch in range(n_epochs):
if done:
print('early stopping')
break
print('epoch=%d' % epoch)
losses = []
for i, (data1_max_len, data2_max_len, data1, data2, y, data1_len, data2_len, coeffs) in \
tqdm(enumerate(compute_training_batches_w_coeffs(gt_path, dbn, training_q_b_name, batch_size,
padding_value=len(we_matrix) - 1,
fold_idx=fold_index, n_iter_per_query=1000,
max_q_len=mql, max_d_len=mdl,
ftt_model=fasttext_vec_model,
wn2v_model=wn2vec_model,
iwi=iwi, wi=wi))):
feed_dict = {model.X1: data1, model.X1_len: data1_len, model.X2: data2,
model.X2_len: data2_len, model.Y: y, model.training: True, model.coeffs: coeffs}
loss = model.train_step(sess, feed_dict)
losses.append(loss)
#if i % 1000 == 0 and i != 0:
print('evaluating at epch %d' % epoch)
map_v = true_rerank(sess, model, validation_q_b_name, dbn, run_to_rerank, mql, mdl,
padding_value, fold_index, validation_qrels_file, epoch, run_name,
fasttext_vec_model, iwi, ii_dict, wn2vec_model, idf_scores,
output_f='../results')
print('Fold=%d, Epoch=%d, Iter=%d, Validation Map=%2.5f, Loss=%2.4f' % (
fold_index, epoch, i, map_v, loss))
if map_v > max_map:
best_epoch = epoch
best_iter = i
patience = 0
map_v_test = true_rerank(sess, model, test_q_b_name, dbn, run_to_rerank, mql, mdl,
padding_value,
fold_index, test_qrels_file, epoch, run_name + '_TEST_set',
wn2vec_model, iwi,
ii_dict, wn2vec_model, idf_scores, output_f='../results')
else:
patience += 1
if patience == max_patience:
print('Early stopping at epoch=%d, iter=%d (patience=%d)!' % (epoch, i, max_patience))
done = True
break
print('Fold %d, (presumed) BEST TEST map=%2.5f' % (fold_index, map_v_test))
print('BEST valid map in fold=%2.4f, at epoch=%d, iter=%d' % (map_v_test, best_epoch, best_iter))
if __name__ == '__main__':
run()
| [
"util.save_model",
"lexical_models.name",
"model.Model",
"numpy.argsort",
"numpy.array",
"numpy.linalg.norm",
"tensorflow.set_random_seed",
"nltk.corpus.wordnet.wup_similarity",
"util.stem",
"os.listdir",
"lexical_models.rank_docs_w_bm25",
"tensorflow.Session",
"itertools.product",
"numpy.... | [((2085, 2113), 'fastText.load_model', 'load_model', (['ftext_model_path'], {}), '(ftext_model_path)\n', (2095, 2113), False, 'from fastText import load_model\n'), ((2736, 2763), 'util.load_indri_stopwords', 'util.load_indri_stopwords', ([], {}), '()\n', (2761, 2763), False, 'import util\n'), ((6342, 6427), 'data_utils.compute_idf', 'du.compute_idf', (['coll_path', 'stemming', 'output_path_ii_model', 'output_path_idf_model'], {}), '(coll_path, stemming, output_path_ii_model, output_path_idf_model\n )\n', (6356, 6427), True, 'import data_utils as du\n'), ((10174, 10197), 'nltk.corpus.wordnet.synsets', 'wordnet.synsets', (['source'], {}), '(source)\n', (10189, 10197), False, 'from nltk.corpus import wordnet\n'), ((12100, 12119), 'nltk.corpus.wordnet.synsets', 'wordnet.synsets', (['qw'], {}), '(qw)\n', (12115, 12119), False, 'from nltk.corpus import wordnet\n'), ((12135, 12154), 'nltk.corpus.wordnet.synsets', 'wordnet.synsets', (['dw'], {}), '(dw)\n', (12150, 12154), False, 'from nltk.corpus import wordnet\n'), ((14107, 14126), 'numpy.ones', 'np.ones', (['(mql, mdl)'], {}), '((mql, mdl))\n', (14114, 14126), True, 'import numpy as np\n'), ((16779, 16798), 'numpy.ones', 'np.ones', (['(mql, mdl)'], {}), '((mql, mdl))\n', (16786, 16798), True, 'import numpy as np\n'), ((20428, 20447), 'tqdm.tqdm', 'tqdm', (['queries_names'], {}), '(queries_names)\n', (20432, 20447), False, 'from tqdm import tqdm\n'), ((21806, 21846), 'lexical_models.rank_docs_w_bm25', 'lm.rank_docs_w_bm25', (['query', 'dbn', 'ii', 'iwi'], {}), '(query, dbn, ii, iwi)\n', (21825, 21846), True, 'import lexical_models as lm\n'), ((21897, 21946), 'numpy.array', 'np.array', (['[docs_with_scores[dn] for dn in dnames]'], {}), '([docs_with_scores[dn] for dn in dnames])\n', (21905, 21946), True, 'import numpy as np\n'), ((27415, 27516), 'gensim.models.KeyedVectors.load_word2vec_format', 'gensim.models.KeyedVectors.load_word2vec_format', (['"""../data/fasttext_models/wiki-news-300d-1M.vec"""'], {}), "(\n '../data/fasttext_models/wiki-news-300d-1M.vec')\n", (27462, 27516), False, 'import gensim\n'), ((27623, 27711), 'gensim.models.KeyedVectors.load_word2vec_format', 'gensim.models.KeyedVectors.load_word2vec_format', (['"""../data/wn_embeddings/wn2vec.txt"""'], {}), "(\n '../data/wn_embeddings/wn2vec.txt')\n", (27670, 27711), False, 'import gensim\n'), ((27751, 27769), 'util.invert_wi', 'util.invert_wi', (['wi'], {}), '(wi)\n', (27765, 27769), False, 'import util\n'), ((981, 1014), 'os.path.isfile', 'os.path.isfile', (['output_model_path'], {}), '(output_model_path)\n', (995, 1014), False, 'import os\n'), ((1178, 1201), 'multiprocessing.Pool', 'multiprocessing.Pool', (['(8)'], {}), '(8)\n', (1198, 1201), False, 'import multiprocessing\n'), ((1224, 1252), 'os.listdir', 'os.listdir', (['coll_main_folder'], {}), '(coll_main_folder)\n', (1234, 1252), False, 'import os\n'), ((1762, 1810), 'util.save_model', 'util.save_model', (['text_by_name', 'output_model_path'], {}), '(text_by_name, output_model_path)\n', (1777, 1810), False, 'import util\n'), ((1899, 1933), 'util.load_model', 'util.load_model', (['output_model_path'], {}), '(output_model_path)\n', (1914, 1933), False, 'import util\n'), ((2650, 2669), 'numpy.array', 'np.array', (['we_matrix'], {}), '(we_matrix)\n', (2658, 2669), True, 'import numpy as np\n'), ((2810, 2841), 'os.listdir', 'os.listdir', (['queries_main_folder'], {}), '(queries_main_folder)\n', (2820, 2841), False, 'import os\n'), ((2857, 2900), 'os.path.join', 'os.path.join', (['queries_main_folder', 'filename'], {}), '(queries_main_folder, filename)\n', (2869, 2900), False, 'import os\n'), ((2912, 2930), 'os.path.isfile', 'os.path.isfile', (['fp'], {}), '(fp)\n', (2926, 2930), False, 'import os\n'), ((3275, 3310), 'os.path.isfile', 'os.path.isfile', (['output_file_path_ii'], {}), '(output_file_path_ii)\n', (3289, 3310), False, 'import os\n'), ((3393, 3420), 'util.load_indri_stopwords', 'util.load_indri_stopwords', ([], {}), '()\n', (3418, 3420), False, 'import util\n'), ((4043, 4093), 'util.save_model', 'util.save_model', (['inverted_idx', 'output_file_path_ii'], {}), '(inverted_idx, output_file_path_ii)\n', (4058, 4093), False, 'import util\n'), ((4127, 4163), 'util.load_model', 'util.load_model', (['output_file_path_ii'], {}), '(output_file_path_ii)\n', (4142, 4163), False, 'import util\n'), ((5044, 5080), 'os.path.isfile', 'os.path.isfile', (['output_path_ii_model'], {}), '(output_path_ii_model)\n', (5058, 5080), False, 'import os\n'), ((5211, 5252), 'util.save_model', 'util.save_model', (['ii', 'output_path_ii_model'], {}), '(ii, output_path_ii_model)\n', (5226, 5252), False, 'import util\n'), ((5316, 5353), 'util.load_model', 'util.load_model', (['output_path_ii_model'], {}), '(output_path_ii_model)\n', (5331, 5353), False, 'import util\n'), ((5366, 5409), 'os.path.isfile', 'os.path.isfile', (['output_path_encoded_d_model'], {}), '(output_path_encoded_d_model)\n', (5380, 5409), False, 'import os\n'), ((5687, 5744), 'util.save_model', 'util.save_model', (['encoded_dbn', 'output_path_encoded_d_model'], {}), '(encoded_dbn, output_path_encoded_d_model)\n', (5702, 5744), False, 'import util\n'), ((5753, 5794), 'util.save_model', 'util.save_model', (['wi', 'output_path_wi_model'], {}), '(wi, output_path_wi_model)\n', (5768, 5794), False, 'import util\n'), ((5803, 5858), 'util.save_model', 'util.save_model', (['we_matrix', 'output_path_we_matrix_model'], {}), '(we_matrix, output_path_we_matrix_model)\n', (5818, 5858), False, 'import util\n'), ((5891, 5935), 'util.load_model', 'util.load_model', (['output_path_encoded_d_model'], {}), '(output_path_encoded_d_model)\n', (5906, 5935), False, 'import util\n'), ((5949, 5986), 'util.load_model', 'util.load_model', (['output_path_wi_model'], {}), '(output_path_wi_model)\n', (5964, 5986), False, 'import util\n'), ((6007, 6051), 'util.load_model', 'util.load_model', (['output_path_we_matrix_model'], {}), '(output_path_we_matrix_model)\n', (6022, 6051), False, 'import util\n'), ((6064, 6107), 'os.path.isfile', 'os.path.isfile', (['output_path_encoded_q_model'], {}), '(output_path_encoded_q_model)\n', (6078, 6107), False, 'import os\n'), ((6189, 6246), 'util.save_model', 'util.save_model', (['encoded_qbn', 'output_path_encoded_q_model'], {}), '(encoded_qbn, output_path_encoded_q_model)\n', (6204, 6246), False, 'import util\n'), ((6279, 6323), 'util.load_model', 'util.load_model', (['output_path_encoded_q_model'], {}), '(output_path_encoded_q_model)\n', (6294, 6323), False, 'import util\n'), ((7032, 7048), 'numpy.ones', 'np.ones', (['max_len'], {}), '(max_len)\n', (7039, 7048), True, 'import numpy as np\n'), ((7436, 7462), 'os.path.isfile', 'os.path.isfile', (['model_name'], {}), '(model_name)\n', (7450, 7462), False, 'import os\n'), ((8057, 8088), 'numpy.random.shuffle', 'np.random.shuffle', (['test_q_names'], {}), '(test_q_names)\n', (8074, 8088), True, 'import numpy as np\n'), ((9713, 9747), 'numpy.random.shuffle', 'np.random.shuffle', (['qn_rd_nrd_pairs'], {}), '(qn_rd_nrd_pairs)\n', (9730, 9747), True, 'import numpy as np\n'), ((9756, 9800), 'util.save_model', 'util.save_model', (['qn_rd_nrd_pairs', 'model_name'], {}), '(qn_rd_nrd_pairs, model_name)\n', (9771, 9800), False, 'import util\n'), ((9837, 9864), 'util.load_model', 'util.load_model', (['model_name'], {}), '(model_name)\n', (9852, 9864), False, 'import util\n'), ((11289, 11320), 'numpy.random.shuffle', 'np.random.shuffle', (['test_q_names'], {}), '(test_q_names)\n', (11306, 11320), True, 'import numpy as np\n'), ((11771, 11805), 'numpy.random.shuffle', 'np.random.shuffle', (['qn_rd_nrd_pairs'], {}), '(qn_rd_nrd_pairs)\n', (11788, 11805), True, 'import numpy as np\n'), ((14213, 14232), 'nltk.corpus.wordnet.synsets', 'wordnet.synsets', (['qw'], {}), '(qw)\n', (14228, 14232), False, 'from nltk.corpus import wordnet\n'), ((25544, 25574), 'numpy.array', 'np.array', (['[p[0] for p in pred]'], {}), '([p[0] for p in pred])\n', (25552, 25574), True, 'import numpy as np\n'), ((25946, 25973), 'numpy.array', 'np.array', (['all_preds[q_name]'], {}), '(all_preds[q_name])\n', (25954, 25973), True, 'import numpy as np\n'), ((28635, 28659), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (28657, 28659), True, 'import tensorflow as tf\n'), ((28682, 28698), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (28696, 28698), True, 'import tensorflow as tf\n'), ((28759, 28780), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(0)'], {}), '(0)\n', (28777, 28780), True, 'import tensorflow as tf\n'), ((1068, 1095), 'util.load_indri_stopwords', 'util.load_indri_stopwords', ([], {}), '()\n', (1093, 1095), False, 'import util\n'), ((1279, 1319), 'os.path.join', 'os.path.join', (['coll_main_folder', 'filename'], {}), '(coll_main_folder, filename)\n', (1291, 1319), False, 'import os\n'), ((2570, 2611), 'os.path.join', 'os.path.join', (['encoded_out_folder_docs', 'dn'], {}), '(encoded_out_folder_docs, dn)\n', (2582, 2611), False, 'import os\n'), ((3468, 3491), 'os.listdir', 'os.listdir', (['coll_folder'], {}), '(coll_folder)\n', (3478, 3491), False, 'import os\n'), ((3511, 3546), 'os.path.join', 'os.path.join', (['coll_folder', 'filename'], {}), '(coll_folder, filename)\n', (3523, 3546), False, 'import os\n'), ((3607, 3625), 'os.path.isfile', 'os.path.isfile', (['fp'], {}), '(fp)\n', (3621, 3625), False, 'import os\n'), ((8332, 8394), 'numpy.random.choice', 'np.random.choice', (['rd_b_qry[qn]', 'n_iter_per_query'], {'replace': '(True)'}), '(rd_b_qry[qn], n_iter_per_query, replace=True)\n', (8348, 8394), True, 'import numpy as np\n'), ((8420, 8484), 'numpy.random.choice', 'np.random.choice', (['nrd_by_qry[qn]', 'n_iter_per_query'], {'replace': '(True)'}), '(nrd_by_qry[qn], n_iter_per_query, replace=True)\n', (8436, 8484), True, 'import numpy as np\n'), ((11474, 11536), 'numpy.random.choice', 'np.random.choice', (['rd_b_qry[qn]', 'n_iter_per_query'], {'replace': '(True)'}), '(rd_b_qry[qn], n_iter_per_query, replace=True)\n', (11490, 11536), True, 'import numpy as np\n'), ((11562, 11626), 'numpy.random.choice', 'np.random.choice', (['nrd_by_qry[qn]', 'n_iter_per_query'], {'replace': '(True)'}), '(nrd_by_qry[qn], n_iter_per_query, replace=True)\n', (11578, 11626), True, 'import numpy as np\n'), ((13214, 13233), 'numpy.ones', 'np.ones', (['(mql, mdl)'], {}), '((mql, mdl))\n', (13221, 13233), True, 'import numpy as np\n'), ((14392, 14411), 'nltk.corpus.wordnet.synsets', 'wordnet.synsets', (['dw'], {}), '(dw)\n', (14407, 14411), False, 'from nltk.corpus import wordnet\n'), ((21982, 22001), 'numpy.argsort', 'np.argsort', (['(-scores)'], {}), '(-scores)\n', (21992, 22001), True, 'import numpy as np\n'), ((28794, 28824), 'tensorflow.Session', 'tf.Session', ([], {'config': 'sess_config'}), '(config=sess_config)\n', (28804, 28824), True, 'import tensorflow as tf\n'), ((28846, 28867), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(0)'], {}), '(0)\n', (28864, 28867), True, 'import tensorflow as tf\n'), ((28888, 28901), 'model.Model', 'Model', (['config'], {}), '(config)\n', (28893, 28901), False, 'from model import Model\n'), ((5539, 5566), 'util.load_indri_stopwords', 'util.load_indri_stopwords', ([], {}), '()\n', (5564, 5566), False, 'import util\n'), ((10246, 10255), 'lexical_models.name', 'lm.name', ([], {}), '()\n', (10253, 10255), True, 'import lexical_models as lm\n'), ((16942, 16954), 'numpy.ones', 'np.ones', (['mdl'], {}), '(mdl)\n', (16949, 16954), True, 'import numpy as np\n'), ((20915, 20927), 'util.stem', 'util.stem', (['w'], {}), '(w)\n', (20924, 20927), False, 'import util\n'), ((25812, 25824), 'numpy.max', 'np.max', (['pred'], {}), '(pred)\n', (25818, 25824), True, 'import numpy as np\n'), ((26009, 26050), 'numpy.array', 'np.array', (['dnames_to_rerank_by_qry[q_name]'], {}), '(dnames_to_rerank_by_qry[q_name])\n', (26017, 26050), True, 'import numpy as np\n'), ((26051, 26068), 'numpy.argsort', 'np.argsort', (['(-pred)'], {}), '(-pred)\n', (26061, 26068), True, 'import numpy as np\n'), ((26120, 26137), 'numpy.argsort', 'np.argsort', (['(-pred)'], {}), '(-pred)\n', (26130, 26137), True, 'import numpy as np\n'), ((9017, 9030), 'util.stem', 'util.stem', (['sw'], {}), '(sw)\n', (9026, 9030), False, 'import util\n'), ((10346, 10355), 'lexical_models.name', 'lm.name', ([], {}), '()\n', (10353, 10355), True, 'import lexical_models as lm\n'), ((12305, 12332), 'itertools.product', 'product', (['allsyns1', 'allsyns2'], {}), '(allsyns1, allsyns2)\n', (12312, 12332), False, 'from itertools import product\n'), ((13790, 13806), 'numpy.dot', 'np.dot', (['qwe', 'dwe'], {}), '(qwe, dwe)\n', (13796, 13806), True, 'import numpy as np\n'), ((9368, 9430), 'numpy.random.choice', 'np.random.choice', (['rd_b_qry[qn]', 'n_iter_per_query'], {'replace': '(True)'}), '(rd_b_qry[qn], n_iter_per_query, replace=True)\n', (9384, 9430), True, 'import numpy as np\n'), ((9468, 9532), 'numpy.random.choice', 'np.random.choice', (['nrd_by_qry[qn]', 'n_iter_per_query'], {'replace': '(True)'}), '(nrd_by_qry[qn], n_iter_per_query, replace=True)\n', (9484, 9532), True, 'import numpy as np\n'), ((10435, 10444), 'lexical_models.name', 'lm.name', ([], {}), '()\n', (10442, 10444), True, 'import lexical_models as lm\n'), ((12246, 12276), 'nltk.corpus.wordnet.wup_similarity', 'wordnet.wup_similarity', (['s1', 's2'], {}), '(s1, s2)\n', (12268, 12276), False, 'from nltk.corpus import wordnet\n'), ((13655, 13685), 'numpy.linalg.norm', 'np.linalg.norm', (['wn2v_model[qw]'], {}), '(wn2v_model[qw])\n', (13669, 13685), True, 'import numpy as np\n'), ((13729, 13759), 'numpy.linalg.norm', 'np.linalg.norm', (['wn2v_model[dw]'], {}), '(wn2v_model[dw])\n', (13743, 13759), True, 'import numpy as np\n'), ((14667, 14694), 'itertools.product', 'product', (['allsyns1', 'allsyns2'], {}), '(allsyns1, allsyns2)\n', (14674, 14694), False, 'from itertools import product\n'), ((14608, 14638), 'nltk.corpus.wordnet.wup_similarity', 'wordnet.wup_similarity', (['s1', 's2'], {}), '(s1, s2)\n', (14630, 14638), False, 'from nltk.corpus import wordnet\n')] |
from numpy import mean, zeros
from copy import deepcopy
class Ensemble(object):
"""
Class represents ensemble learning technique. In short, ensemble techniques predict output over a meta learner
that it self is supplied with output of a number of base learners.
Attributes:
base_learner: Base learner algorithms that supplies meta learner.
number_learners: Number of base learners.
meta_learner: Meta learner that predicts output, based on base learner predictions.
learners: List, containing the trained base learners.
Notes:
base_learner needs to support fit() and predict() function.
meta_learner function needs to support numpy ndarray as input.
"""
def __init__(self, base_learner, number_learners, meta_learner=mean):
self.base_learner = base_learner
self.number_learners = number_learners
self.meta_learner = meta_learner
self.learners = list()
def fit(self, input_matrix, target_vector, metric, verbose=False):
"""Trains learner to approach target vector, given an input matrix, based on a defined metric."""
for i in range(self.number_learners):
if verbose: print(i)
# Creates deepcopy of base learner.
learner = deepcopy(self.base_learner)
# Trains base learner.
learner.fit(input_matrix, target_vector, metric)
# Adds base learner to list.
self.learners.append(learner)
def predict(self, input_matrix):
"""Predicts target vector, given input_matrix, based on trained ensemble."""
# Creates prediction matrix.
predictions = zeros([input_matrix.shape[0], self.number_learners])
# Supplies prediction matrix with predictions of base learners.
for learner, i in zip(self.learners, range(len(self.learners))):
predictions[:, i] = learner.predict(input_matrix)
# Applies meta learner to prediction matrix.
return self.meta_learner(predictions, axis=1)
| [
"numpy.zeros",
"copy.deepcopy"
] | [((1682, 1734), 'numpy.zeros', 'zeros', (['[input_matrix.shape[0], self.number_learners]'], {}), '([input_matrix.shape[0], self.number_learners])\n', (1687, 1734), False, 'from numpy import mean, zeros\n'), ((1292, 1319), 'copy.deepcopy', 'deepcopy', (['self.base_learner'], {}), '(self.base_learner)\n', (1300, 1319), False, 'from copy import deepcopy\n')] |
import numpy as np
from numpy.linalg import norm
from numpy.fft import fft, ifft
from sklearn.metrics import silhouette_score as _silhouette_score
def sbd(x, y):
ncc = _ncc_c(x, y)
idx = ncc.argmax()
dist = 1 - ncc[idx]
if dist < 0:
return 0
else:
return dist
def _ncc_c(x, y):
den = np.array(norm(x) * norm(y))
den[den == 0] = np.Inf
x_len = len(x)
fft_size = 1<<(2*x_len-1).bit_length()
cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size)))
cc = np.concatenate((cc[-(x_len-1):], cc[:x_len]))
return np.real(cc) / den
def silhouette_score(data, labels):
distances = np.zeros((data.shape[0], data.shape[0]))
for idx_a, data_a in enumerate(data):
for idx_b, data_b in enumerate(data):
if idx_a == idx_b:
distances[idx_a, idx_b] = 0
continue
distances[idx_a, idx_b] = sbd(data_a, data_b)
return _silhouette_score(distances, labels, metric='precomputed')
| [
"numpy.fft.fft",
"numpy.real",
"numpy.zeros",
"numpy.concatenate",
"numpy.linalg.norm",
"sklearn.metrics.silhouette_score"
] | [((512, 559), 'numpy.concatenate', 'np.concatenate', (['(cc[-(x_len - 1):], cc[:x_len])'], {}), '((cc[-(x_len - 1):], cc[:x_len]))\n', (526, 559), True, 'import numpy as np\n'), ((640, 680), 'numpy.zeros', 'np.zeros', (['(data.shape[0], data.shape[0])'], {}), '((data.shape[0], data.shape[0]))\n', (648, 680), True, 'import numpy as np\n'), ((938, 996), 'sklearn.metrics.silhouette_score', '_silhouette_score', (['distances', 'labels'], {'metric': '"""precomputed"""'}), "(distances, labels, metric='precomputed')\n", (955, 996), True, 'from sklearn.metrics import silhouette_score as _silhouette_score\n'), ((569, 580), 'numpy.real', 'np.real', (['cc'], {}), '(cc)\n', (576, 580), True, 'import numpy as np\n'), ((335, 342), 'numpy.linalg.norm', 'norm', (['x'], {}), '(x)\n', (339, 342), False, 'from numpy.linalg import norm\n'), ((345, 352), 'numpy.linalg.norm', 'norm', (['y'], {}), '(y)\n', (349, 352), False, 'from numpy.linalg import norm\n'), ((457, 473), 'numpy.fft.fft', 'fft', (['x', 'fft_size'], {}), '(x, fft_size)\n', (460, 473), False, 'from numpy.fft import fft, ifft\n'), ((484, 500), 'numpy.fft.fft', 'fft', (['y', 'fft_size'], {}), '(y, fft_size)\n', (487, 500), False, 'from numpy.fft import fft, ifft\n')] |
import numpy as np
import matplotlib.pyplot as plt
import json
from pylab import *
with open('intermediateOutput.json') as f:
allOps = json.load(f)
with open('intermediateOutput_2.json') as f:
allStageOps = json.load(f)
ops = {'init':0, 'build':0, 'report':0, 'test':0, 'deploy':0, 'checkout':0,'check':0, 'release':0, 'delete':0,'cleanup':0}
cmdDict = {}
for ao in list(allStageOps.keys()):
if 'sonar' in ao:
newKey = ao.replace("sonar","report ")
allStageOps[newKey] = allStageOps.pop(ao);
allOps[newKey] = allOps.pop(ao);
#update ops while iterating through allOps
for ao in allOps.items():
key = ao[0]
val = ao[1]
#print("\n",key,val)
keyExists = False
#if key exists in dictionary ops, then increment
for o in ops.keys():
if o in key:
ops[o] = ops[o] + 1
keyExists = True
break
#else add new item to ops dictionary
if not keyExists:
ops[key] = 1
# Remove stages whose count is <=1
for o in list(ops.keys()):
if ops[o]<=1:
del ops[o]
#for o in ops.items():
# print(o)
myKeys = list(ops.keys())
counts = list(ops.values())
length = len(myKeys)
fig = plt.figure(clear=True,figsize=(length*1.5,max(counts)/1.5))
plt.bar(np.arange(length),counts)
plt.xticks(np.arange(length),myKeys)
plt.xlabel('Stage operations')
plt.ylabel('Frequency')
#plt.autoscale_view()
fig.savefig('freq_ops.jpg',bbox_inches="tight")
for aso in allStageOps.keys():
for o in ops.keys():
if o in aso:
stageCmdList = allStageOps[aso]
if o not in cmdDict:
cmdDict[o] = {}
for s in stageCmdList:
cmdDict[o][s] = cmdDict[o].get(s, 0) + 1
#cmdDict[o][s] = cmdDict[o][s] + 1
break
#for o in cmdDict.items():
# print(o)
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True, figsize=(15,20))
subPlotCount = len(ops)
keyList = list(cmdDict.keys())
tmpArr = []
for i,v in enumerate(range(subPlotCount)):
tmpArr.extend(list(cmdDict[keyList[v]].values()))
maxLim = max(tmpArr)
for i,v in enumerate(range(subPlotCount)):
myDict = cmdDict[keyList[v]]
myKeys = list(myDict.keys())
#print(myKeys)
length = len(myKeys)
counts = list(myDict.values())
v = v+1
ax1 = subplot(subPlotCount,1,v)
ax1.barh(range(length),counts,0.9)
ax1.set_xlim(0,maxLim+1)
ax1.set_yticks(range(length))
ax1.set_yticklabels(myKeys)
ax1.set_ylabel(keyList[v-1])
ax1.yaxis.set_label_position("right")
f.savefig('bigPlot.jpg',bbox_inches="tight") | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"json.load",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((1238, 1268), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Stage operations"""'], {}), "('Stage operations')\n", (1248, 1268), True, 'import matplotlib.pyplot as plt\n'), ((1269, 1292), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frequency"""'], {}), "('Frequency')\n", (1279, 1292), True, 'import matplotlib.pyplot as plt\n'), ((1696, 1755), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)'], {'sharex': '(True)', 'sharey': '(True)', 'figsize': '(15, 20)'}), '(3, sharex=True, sharey=True, figsize=(15, 20))\n', (1708, 1755), True, 'import matplotlib.pyplot as plt\n'), ((140, 152), 'json.load', 'json.load', (['f'], {}), '(f)\n', (149, 152), False, 'import json\n'), ((218, 230), 'json.load', 'json.load', (['f'], {}), '(f)\n', (227, 230), False, 'import json\n'), ((1175, 1192), 'numpy.arange', 'np.arange', (['length'], {}), '(length)\n', (1184, 1192), True, 'import numpy as np\n'), ((1212, 1229), 'numpy.arange', 'np.arange', (['length'], {}), '(length)\n', (1221, 1229), True, 'import numpy as np\n')] |
import numpy as np
from gym import Wrapper
from gym.wrappers.time_limit import TimeLimit
from rlpyt.envs.base import EnvSpaces, EnvStep
from rlpyt.spaces.gym_wrapper import GymSpaceWrapper
import random
import numpy as np
def obs_action_translator(action,power_vec,dim_obs):
trans_action = np.zeros(dim_obs)
for i in range(len(power_vec)):
if action >= power_vec[i]:
trans_action[i] = 1
action -= power_vec[i]
return trans_action
def reward_shaping_ph(reward,obs_act):
return reward, 0
class CWTO_EnvWrapper(Wrapper):
def __init__(self,work_env,env_name,obs_spaces,action_spaces,serial,force_float32=True,act_null_value=[0,0],obs_null_value=[0,0],player_reward_shaping=None,observer_reward_shaping=None,fully_obs=False,rand_obs=False,inc_player_last_act=False,max_episode_length=np.inf,cont_act=False):
env = work_env(env_name)
super().__init__(env)
o = self.env.reset()
self.inc_player_last_act = inc_player_last_act
self.max_episode_length = max_episode_length
self.curr_episode_length = 0
o, r, d, info = self.env.step(self.env.action_space.sample())
env_ = self.env
time_limit = isinstance(self.env, TimeLimit)
while not time_limit and hasattr(env_, "env"):
env_ = env_.env
time_limit = isinstance(env_, TimeLimit)
if time_limit:
info["timeout"] = False # gym's TimeLimit.truncated invalid name.
self.time_limit = time_limit
self._action_space = GymSpaceWrapper(
space=self.env.action_space,
name="act",
null_value=act_null_value,
force_float32=force_float32,
)
self.cont_act = cont_act
self._observation_space = GymSpaceWrapper(
space=self.env.observation_space,
name="obs",
null_value=obs_null_value,
force_float32=force_float32,
)
del self.action_space
del self.observation_space
self.fully_obs = fully_obs
self.rand_obs = rand_obs
self.player_turn = False
self.serial = serial
self.last_done = False
self.last_reward = 0
self.last_info = {}
# self.obs_action_translator = obs_action_translator
if player_reward_shaping is None:
self.player_reward_shaping = reward_shaping_ph
else:
self.player_reward_shaping = player_reward_shaping
if observer_reward_shaping is None:
self.observer_reward_shaping = reward_shaping_ph
else:
self.observer_reward_shaping = observer_reward_shaping
dd = self.env.observation_space.shape
obs_size = 1
for d in dd:
obs_size *= d
self.obs_size = obs_size
if serial:
self.ser_cum_act = np.zeros(self.env.observation_space.shape)
self.ser_counter = 0
else:
self.power_vec = 2 ** np.arange(self.obs_size)[::-1]
self.obs_action_translator = obs_action_translator
if len(obs_spaces) > 1:
player_obs_space = obs_spaces[0]
observer_obs_space = obs_spaces[1]
else:
player_obs_space = obs_spaces[0]
observer_obs_space = obs_spaces[0]
if len(action_spaces) > 1:
player_act_space = action_spaces[0]
observer_act_space = action_spaces[1]
else:
player_act_space = action_spaces[0]
observer_act_space = action_spaces[0]
self.player_action_space = GymSpaceWrapper(space=player_act_space,name="act",null_value=act_null_value[0],force_float32=force_float32)
self.observer_action_space = GymSpaceWrapper(space=observer_act_space,name="act",null_value=act_null_value[1],force_float32=force_float32)
self.player_observation_space = GymSpaceWrapper(space=player_obs_space,name="obs",null_value=obs_null_value[0],force_float32=force_float32)
self.observer_observation_space = GymSpaceWrapper(space=observer_obs_space,name="obs",null_value=obs_null_value[1],force_float32=force_float32)
def step(self,action):
if self.player_turn:
self.player_turn = False
a = self.player_action_space.revert(action)
if a.size <= 1:
a = a.item()
o, r, d, info = self.env.step(a)
self.last_obs = o
self.last_action = a
if self.serial:
obs = np.concatenate([np.zeros(self.last_obs_act.shape), self.last_masked_obs])
else:
obs = np.concatenate([self.last_obs_act, self.last_masked_obs])
if self.inc_player_last_act:
obs = np.append(obs,a)
obs = self.observer_observation_space.convert(obs)
if self.time_limit:
if "TimeLimit.truncated" in info:
info["timeout"] = info.pop("TimeLimit.truncated")
else:
info["timeout"] = False
self.last_info = (info["timeout"])
info = (False)
if isinstance(r, float):
r = np.dtype("float32").type(r) # Scalar float32.
self.last_reward = r
# if (not d) and (self.observer_reward_shaping is not None):
# r = self.observer_reward_shaping(r,self.last_obs_act)
self.curr_episode_length += 1
if self.curr_episode_length >= self.max_episode_length:
d = True
self.last_done = d
return EnvStep(obs, r, d, info)
else:
if not np.array_equal(action,action.astype(bool)):
action = np.random.binomial(1,action)
r_action = self.observer_action_space.revert(action)
if self.serial:
if self.fully_obs:
r_action = 1
elif self.rand_obs:
r_action = random.randint(0,1)
self.ser_cum_act[self.ser_counter] = r_action
self.ser_counter += 1
if self.ser_counter == self.obs_size:
self.player_turn = True
self.ser_counter = 0
masked_obs = np.multiply(np.reshape(self.ser_cum_act, self.last_obs.shape), self.last_obs)
self.last_masked_obs = masked_obs
self.last_obs_act = self.ser_cum_act.copy()
self.ser_cum_act = np.zeros(self.env.env.observation_space.shape)
r = self.last_reward
# if self.player_reward_shaping is not None:
# r = self.player_reward_shaping(r, self.last_obs_act)
d = self.last_done
info = self.last_info
obs = np.concatenate([np.reshape(self.last_obs_act,masked_obs.shape),masked_obs])
obs = self.player_observation_space.convert(obs)
else:
r = 0
info = (False)
obs = np.concatenate([np.reshape(self.ser_cum_act, self.last_masked_obs.shape),self.last_masked_obs])
if self.inc_player_last_act:
obs = np.append(obs, self.last_action)
obs = self.observer_observation_space.convert(obs)
d = False
else:
if not self.cont_act:
r_action = self.obs_action_translator(r_action, self.power_vec, self.obs_size)
if self.fully_obs:
r_action = np.ones(r_action.shape)
elif self.rand_obs:
r_action = np.random.randint(0,2,r_action.shape)
self.player_turn = True
self.last_obs_act = r_action
masked_obs = np.multiply(np.reshape(r_action, self.last_obs.shape), self.last_obs)
self.last_masked_obs = masked_obs
info = self.last_info
r = self.last_reward
# if self.player_reward_shaping is not None:
# r = self.player_reward_shaping(r, r_action)
d = self.last_done
obs = np.concatenate([np.reshape(r_action, masked_obs.shape), masked_obs])
obs = self.player_observation_space.convert(obs)
return EnvStep(obs,r,d,info)
def reset(self):
self.curr_episode_length = 0
self.last_done = False
self.last_reward = 0
self.last_action = self.player_action_space.revert(self.player_action_space.null_value())
if self.serial:
self.ser_cum_act = np.zeros(self.env.observation_space.shape)
self.ser_counter = 0
self.player_turn = False
o = self.env.reset()
self.last_obs = o
obs = np.concatenate([np.zeros(o.shape),np.zeros(o.shape)])
if self.inc_player_last_act:
obs = np.append(obs,self.last_action)
self.last_obs_act = np.zeros(o.shape)
self.last_masked_obs = np.zeros(o.shape)
obs = self.observer_observation_space.convert(obs)
return obs
def spaces(self):
comb_spaces = [EnvSpaces(observation=self.player_observation_space,action=self.player_action_space), EnvSpaces(observation=self.observer_observation_space, action=self.observer_action_space)]
return comb_spaces
def action_space(self):
if self.player_turn:
return self.player_action_space
else:
return self.observer_action_space
def observation_space(self):
if self.player_turn:
return self.player_observation_space
else:
return self.observer_observation_space
def set_fully_observable(self):
self.fully_obs = True
def set_random_observation(self):
self.rand_obs = True
| [
"rlpyt.spaces.gym_wrapper.GymSpaceWrapper",
"numpy.reshape",
"numpy.ones",
"numpy.arange",
"rlpyt.envs.base.EnvSpaces",
"numpy.append",
"numpy.zeros",
"rlpyt.envs.base.EnvStep",
"numpy.random.randint",
"numpy.concatenate",
"numpy.dtype",
"random.randint",
"numpy.random.binomial"
] | [((306, 323), 'numpy.zeros', 'np.zeros', (['dim_obs'], {}), '(dim_obs)\n', (314, 323), True, 'import numpy as np\n'), ((1586, 1703), 'rlpyt.spaces.gym_wrapper.GymSpaceWrapper', 'GymSpaceWrapper', ([], {'space': 'self.env.action_space', 'name': '"""act"""', 'null_value': 'act_null_value', 'force_float32': 'force_float32'}), "(space=self.env.action_space, name='act', null_value=\n act_null_value, force_float32=force_float32)\n", (1601, 1703), False, 'from rlpyt.spaces.gym_wrapper import GymSpaceWrapper\n'), ((1832, 1954), 'rlpyt.spaces.gym_wrapper.GymSpaceWrapper', 'GymSpaceWrapper', ([], {'space': 'self.env.observation_space', 'name': '"""obs"""', 'null_value': 'obs_null_value', 'force_float32': 'force_float32'}), "(space=self.env.observation_space, name='obs', null_value=\n obs_null_value, force_float32=force_float32)\n", (1847, 1954), False, 'from rlpyt.spaces.gym_wrapper import GymSpaceWrapper\n'), ((3693, 3808), 'rlpyt.spaces.gym_wrapper.GymSpaceWrapper', 'GymSpaceWrapper', ([], {'space': 'player_act_space', 'name': '"""act"""', 'null_value': 'act_null_value[0]', 'force_float32': 'force_float32'}), "(space=player_act_space, name='act', null_value=\n act_null_value[0], force_float32=force_float32)\n", (3708, 3808), False, 'from rlpyt.spaces.gym_wrapper import GymSpaceWrapper\n'), ((3839, 3956), 'rlpyt.spaces.gym_wrapper.GymSpaceWrapper', 'GymSpaceWrapper', ([], {'space': 'observer_act_space', 'name': '"""act"""', 'null_value': 'act_null_value[1]', 'force_float32': 'force_float32'}), "(space=observer_act_space, name='act', null_value=\n act_null_value[1], force_float32=force_float32)\n", (3854, 3956), False, 'from rlpyt.spaces.gym_wrapper import GymSpaceWrapper\n'), ((3990, 4105), 'rlpyt.spaces.gym_wrapper.GymSpaceWrapper', 'GymSpaceWrapper', ([], {'space': 'player_obs_space', 'name': '"""obs"""', 'null_value': 'obs_null_value[0]', 'force_float32': 'force_float32'}), "(space=player_obs_space, name='obs', null_value=\n obs_null_value[0], force_float32=force_float32)\n", (4005, 4105), False, 'from rlpyt.spaces.gym_wrapper import GymSpaceWrapper\n'), ((4141, 4258), 'rlpyt.spaces.gym_wrapper.GymSpaceWrapper', 'GymSpaceWrapper', ([], {'space': 'observer_obs_space', 'name': '"""obs"""', 'null_value': 'obs_null_value[1]', 'force_float32': 'force_float32'}), "(space=observer_obs_space, name='obs', null_value=\n obs_null_value[1], force_float32=force_float32)\n", (4156, 4258), False, 'from rlpyt.spaces.gym_wrapper import GymSpaceWrapper\n'), ((9255, 9272), 'numpy.zeros', 'np.zeros', (['o.shape'], {}), '(o.shape)\n', (9263, 9272), True, 'import numpy as np\n'), ((9305, 9322), 'numpy.zeros', 'np.zeros', (['o.shape'], {}), '(o.shape)\n', (9313, 9322), True, 'import numpy as np\n'), ((2944, 2986), 'numpy.zeros', 'np.zeros', (['self.env.observation_space.shape'], {}), '(self.env.observation_space.shape)\n', (2952, 2986), True, 'import numpy as np\n'), ((5726, 5750), 'rlpyt.envs.base.EnvStep', 'EnvStep', (['obs', 'r', 'd', 'info'], {}), '(obs, r, d, info)\n', (5733, 5750), False, 'from rlpyt.envs.base import EnvSpaces, EnvStep\n'), ((8595, 8619), 'rlpyt.envs.base.EnvStep', 'EnvStep', (['obs', 'r', 'd', 'info'], {}), '(obs, r, d, info)\n', (8602, 8619), False, 'from rlpyt.envs.base import EnvSpaces, EnvStep\n'), ((8899, 8941), 'numpy.zeros', 'np.zeros', (['self.env.observation_space.shape'], {}), '(self.env.observation_space.shape)\n', (8907, 8941), True, 'import numpy as np\n'), ((9193, 9225), 'numpy.append', 'np.append', (['obs', 'self.last_action'], {}), '(obs, self.last_action)\n', (9202, 9225), True, 'import numpy as np\n'), ((9452, 9542), 'rlpyt.envs.base.EnvSpaces', 'EnvSpaces', ([], {'observation': 'self.player_observation_space', 'action': 'self.player_action_space'}), '(observation=self.player_observation_space, action=self.\n player_action_space)\n', (9461, 9542), False, 'from rlpyt.envs.base import EnvSpaces, EnvStep\n'), ((9538, 9632), 'rlpyt.envs.base.EnvSpaces', 'EnvSpaces', ([], {'observation': 'self.observer_observation_space', 'action': 'self.observer_action_space'}), '(observation=self.observer_observation_space, action=self.\n observer_action_space)\n', (9547, 9632), False, 'from rlpyt.envs.base import EnvSpaces, EnvStep\n'), ((4744, 4801), 'numpy.concatenate', 'np.concatenate', (['[self.last_obs_act, self.last_masked_obs]'], {}), '([self.last_obs_act, self.last_masked_obs])\n', (4758, 4801), True, 'import numpy as np\n'), ((4867, 4884), 'numpy.append', 'np.append', (['obs', 'a'], {}), '(obs, a)\n', (4876, 4884), True, 'import numpy as np\n'), ((5858, 5887), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'action'], {}), '(1, action)\n', (5876, 5887), True, 'import numpy as np\n'), ((9098, 9115), 'numpy.zeros', 'np.zeros', (['o.shape'], {}), '(o.shape)\n', (9106, 9115), True, 'import numpy as np\n'), ((9116, 9133), 'numpy.zeros', 'np.zeros', (['o.shape'], {}), '(o.shape)\n', (9124, 9133), True, 'import numpy as np\n'), ((3071, 3095), 'numpy.arange', 'np.arange', (['self.obs_size'], {}), '(self.obs_size)\n', (3080, 3095), True, 'import numpy as np\n'), ((6657, 6703), 'numpy.zeros', 'np.zeros', (['self.env.env.observation_space.shape'], {}), '(self.env.env.observation_space.shape)\n', (6665, 6703), True, 'import numpy as np\n'), ((7804, 7827), 'numpy.ones', 'np.ones', (['r_action.shape'], {}), '(r_action.shape)\n', (7811, 7827), True, 'import numpy as np\n'), ((8064, 8105), 'numpy.reshape', 'np.reshape', (['r_action', 'self.last_obs.shape'], {}), '(r_action, self.last_obs.shape)\n', (8074, 8105), True, 'import numpy as np\n'), ((4644, 4677), 'numpy.zeros', 'np.zeros', (['self.last_obs_act.shape'], {}), '(self.last_obs_act.shape)\n', (4652, 4677), True, 'import numpy as np\n'), ((5308, 5327), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (5316, 5327), True, 'import numpy as np\n'), ((6121, 6141), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (6135, 6141), False, 'import random\n'), ((6431, 6480), 'numpy.reshape', 'np.reshape', (['self.ser_cum_act', 'self.last_obs.shape'], {}), '(self.ser_cum_act, self.last_obs.shape)\n', (6441, 6480), True, 'import numpy as np\n'), ((7438, 7470), 'numpy.append', 'np.append', (['obs', 'self.last_action'], {}), '(obs, self.last_action)\n', (7447, 7470), True, 'import numpy as np\n'), ((7897, 7936), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', 'r_action.shape'], {}), '(0, 2, r_action.shape)\n', (7914, 7936), True, 'import numpy as np\n'), ((8454, 8492), 'numpy.reshape', 'np.reshape', (['r_action', 'masked_obs.shape'], {}), '(r_action, masked_obs.shape)\n', (8464, 8492), True, 'import numpy as np\n'), ((7018, 7065), 'numpy.reshape', 'np.reshape', (['self.last_obs_act', 'masked_obs.shape'], {}), '(self.last_obs_act, masked_obs.shape)\n', (7028, 7065), True, 'import numpy as np\n'), ((7277, 7333), 'numpy.reshape', 'np.reshape', (['self.ser_cum_act', 'self.last_masked_obs.shape'], {}), '(self.ser_cum_act, self.last_masked_obs.shape)\n', (7287, 7333), True, 'import numpy as np\n')] |
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class TrfJitter(BaseEstimator, TransformerMixin):
def __init__(self, snrdb, p=1, verbose=0):
self.snrdb = snrdb
self.snr = 10 ** (self.snrdb/10)
self.p = p
self.verbose = verbose
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
output = np.copy(X)
q = np.random.rand(X.shape[0]) < self.p
if self.verbose:
print('Jitter: ', q)
for i in range(X.shape[0]):
if q[i]:
output[i] = self.jitter(X[i])
if y is not None:
return output, y
else:
return output
def jitter(self, x):
Xp = np.sum(x**2, axis=0, keepdims=True) / x.shape[0]
Np = Xp / self.snr
n = np.random.normal(size=x.shape, scale=np.sqrt(Np), loc=0.0)
return x + n
class TrfMagWarp(BaseEstimator, TransformerMixin):
def __init__(self, sigma, p=1, verbose=0):
self.sigma = sigma
self.p = p
self.verbose = verbose
self.knot = 4
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
output = np.copy(X)
q = np.random.rand(X.shape[0]) < self.p
if self.verbose:
print('Warp: ', q)
for i in range(X.shape[0]):
if q[i]:
output[i] = self.mag_warp(X[i])
if y is not None:
return output, y
else:
return output
def mag_warp(self, x):
def _generate_random_curve(x, sigma=0.2, knot=4):
# knot = max(0, min(knot, x.shape[0]-2))
xx = np.arange(0, x.shape[0], (x.shape[0]-1)//(knot+1)).transpose()
yy = np.random.normal(loc=1.0, scale=sigma, size=(knot+2,))
x_range = np.arange(x.shape[0])
cs = CubicSpline(xx[:], yy[:])
return np.array(cs(x_range)).transpose()
output = np.zeros(x.shape)
for i in range(x.shape[1]):
rc = _generate_random_curve(x[:,i], self.sigma, self.knot)
output[:,i] = x[:,i] * rc
return output
| [
"numpy.random.normal",
"numpy.copy",
"numpy.sqrt",
"numpy.random.rand",
"numpy.sum",
"numpy.zeros",
"numpy.arange"
] | [((397, 407), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (404, 407), True, 'import numpy as np\n'), ((1226, 1236), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (1233, 1236), True, 'import numpy as np\n'), ((1994, 2011), 'numpy.zeros', 'np.zeros', (['x.shape'], {}), '(x.shape)\n', (2002, 2011), True, 'import numpy as np\n'), ((420, 446), 'numpy.random.rand', 'np.random.rand', (['X.shape[0]'], {}), '(X.shape[0])\n', (434, 446), True, 'import numpy as np\n'), ((755, 792), 'numpy.sum', 'np.sum', (['(x ** 2)'], {'axis': '(0)', 'keepdims': '(True)'}), '(x ** 2, axis=0, keepdims=True)\n', (761, 792), True, 'import numpy as np\n'), ((1249, 1275), 'numpy.random.rand', 'np.random.rand', (['X.shape[0]'], {}), '(X.shape[0])\n', (1263, 1275), True, 'import numpy as np\n'), ((1781, 1837), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(1.0)', 'scale': 'sigma', 'size': '(knot + 2,)'}), '(loc=1.0, scale=sigma, size=(knot + 2,))\n', (1797, 1837), True, 'import numpy as np\n'), ((1858, 1879), 'numpy.arange', 'np.arange', (['x.shape[0]'], {}), '(x.shape[0])\n', (1867, 1879), True, 'import numpy as np\n'), ((880, 891), 'numpy.sqrt', 'np.sqrt', (['Np'], {}), '(Np)\n', (887, 891), True, 'import numpy as np\n'), ((1701, 1757), 'numpy.arange', 'np.arange', (['(0)', 'x.shape[0]', '((x.shape[0] - 1) // (knot + 1))'], {}), '(0, x.shape[0], (x.shape[0] - 1) // (knot + 1))\n', (1710, 1757), True, 'import numpy as np\n')] |
import pandas as pd
from sklearn.externals import joblib
from azureml.core.model import Model
import json
import pickle
import numpy as np
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType
from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType
input_sample = pd.DataFrame(data=[{'gender': 'Male', 'SeniorCitizen':0, 'Partner':1, 'Dependents':1, 'tenure':20, 'PhoneService':1, 'MultipleLines':1, 'InternetService':'Fiber optic', 'OnlineSecurity':1, 'OnlineBackup':1, 'DeviceProtection':1, 'TechSupport':1, 'StreamingTV':1, 'StreamingMovies':1, 'Contract': 'One year', 'PaperlessBilling':1, 'PaymentMethod':'Electronic check', 'MonthlyCharges':70, 'TotalCharges':900}])
output_sample = np.array([0])
def init():
global model
# This name is model.id of model that we want to deploy deserialize the model file back
# into a sklearn model
model_path = Model.get_model_path('Churn_model')
model = joblib.load(model_path)
@input_schema('data', PandasParameterType(input_sample))
@output_schema(NumpyParameterType(output_sample))
def run(data):
try:
result = model.predict(data)
return json.dumps({"result": result.tolist()})
except Exception as e:
result = str(e)
return json.dumps({"error": result}) | [
"inference_schema.parameter_types.pandas_parameter_type.PandasParameterType",
"sklearn.externals.joblib.load",
"inference_schema.parameter_types.numpy_parameter_type.NumpyParameterType",
"json.dumps",
"azureml.core.model.Model.get_model_path",
"numpy.array",
"pandas.DataFrame"
] | [((405, 855), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "[{'gender': 'Male', 'SeniorCitizen': 0, 'Partner': 1, 'Dependents': 1,\n 'tenure': 20, 'PhoneService': 1, 'MultipleLines': 1, 'InternetService':\n 'Fiber optic', 'OnlineSecurity': 1, 'OnlineBackup': 1,\n 'DeviceProtection': 1, 'TechSupport': 1, 'StreamingTV': 1,\n 'StreamingMovies': 1, 'Contract': 'One year', 'PaperlessBilling': 1,\n 'PaymentMethod': 'Electronic check', 'MonthlyCharges': 70,\n 'TotalCharges': 900}]"}), "(data=[{'gender': 'Male', 'SeniorCitizen': 0, 'Partner': 1,\n 'Dependents': 1, 'tenure': 20, 'PhoneService': 1, 'MultipleLines': 1,\n 'InternetService': 'Fiber optic', 'OnlineSecurity': 1, 'OnlineBackup': \n 1, 'DeviceProtection': 1, 'TechSupport': 1, 'StreamingTV': 1,\n 'StreamingMovies': 1, 'Contract': 'One year', 'PaperlessBilling': 1,\n 'PaymentMethod': 'Electronic check', 'MonthlyCharges': 70,\n 'TotalCharges': 900}])\n", (417, 855), True, 'import pandas as pd\n'), ((830, 843), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (838, 843), True, 'import numpy as np\n'), ((1011, 1046), 'azureml.core.model.Model.get_model_path', 'Model.get_model_path', (['"""Churn_model"""'], {}), "('Churn_model')\n", (1031, 1046), False, 'from azureml.core.model import Model\n'), ((1059, 1082), 'sklearn.externals.joblib.load', 'joblib.load', (['model_path'], {}), '(model_path)\n', (1070, 1082), False, 'from sklearn.externals import joblib\n'), ((1107, 1140), 'inference_schema.parameter_types.pandas_parameter_type.PandasParameterType', 'PandasParameterType', (['input_sample'], {}), '(input_sample)\n', (1126, 1140), False, 'from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType\n'), ((1157, 1190), 'inference_schema.parameter_types.numpy_parameter_type.NumpyParameterType', 'NumpyParameterType', (['output_sample'], {}), '(output_sample)\n', (1175, 1190), False, 'from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType\n'), ((1374, 1403), 'json.dumps', 'json.dumps', (["{'error': result}"], {}), "({'error': result})\n", (1384, 1403), False, 'import json\n')] |
###############################################################################
# Additional Evaluation Functions
#
# Author: <NAME>
#
# Contact: <EMAIL>
###############################################################################
__all__ = ['SubpixelAlignment', 'PairwiseDistance', 'PRTF', 'PSD', 'EigenMode']
import itertools
from tqdm import tqdm
import numpy as np
from numpy.linalg import svd
from scipy.ndimage import fourier_shift
from skimage.registration import phase_cross_correlation
def SubpixelAlignment(input, error = None, ref = None, subpixel = 1):
'''
subpixel alignment using phase cross-correlation
reference = https://doi.org/10.1364/OL.33.000156
input should be r-space data
automatically sort input with repect to error if error is given
args:
input = numpy float ndarray of size N * H * W
error = numpy float ndarray of size N (default = None)
subpixel = integer (default = 1)
returns:
output = numpy float array with size N * H * W
error = numpy float array with size N
'''
# sort array
if error is not None:
order = np.argsort(error)
error = error[order]
input = input[order, :, :]
# align array
if ref is None:
n_max = input.shape[0]
for n in tqdm(range(1, n_max), desc = 'subpixel alignment'):
arr = input[n]
arr_T = np.flip(arr)
s, err, _ = phase_cross_correlation(input[0], arr, upsample_factor = subpixel)
s_T, err_T, _ = phase_cross_correlation(input[0], arr_T, upsample_factor = subpixel)
if err_T < err:
input[n, :, :] = np.fft.ifft2(fourier_shift(np.fft.fft2(arr_T), s_T)).real
else:
input[n, :, :] = np.fft.ifft2(fourier_shift(np.fft.fft2(arr), s)).real
else:
n_max = input.shape[0]
for n in tqdm(range(0, n_max), desc = 'subpixel alignment'):
arr = input[n]
arr_T = np.flip(arr)
s, err, _ = phase_cross_correlation(ref, arr, upsample_factor = subpixel)
s_T, err_T, _ = phase_cross_correlation(ref, arr_T, upsample_factor = subpixel)
if err_T < err:
input[n, :, :] = np.fft.ifft2(fourier_shift(np.fft.fft2(arr_T), s_T)).real
else:
input[n, :, :] = np.fft.ifft2(fourier_shift(np.fft.fft2(arr), s)).real
# remove negative values due to alignment
input[input < 0] = 0
if error is not None:
return input, error
else:
return input
def PairwiseDistance(input):
'''
pairwise distance
distance is calculated by sum(|arr1-arr2|)/sum(|arr1+arr2|)
input should be aligned
args:
input = numpy float ndarray of size N * H * W
returns:
output = numpy float ndarray of size N(N-1)/2
'''
# calculate pairwise distance
n_max = input.shape[0]
count = n_max * (n_max - 1) // 2
dist = np.zeros(count)
for n, (i, j) in tqdm(enumerate(itertools.combinations(range(n_max), 2)), total = count, desc = 'pairwise distance'):
dist[n] = np.sum(np.abs(input[i] - input[j])) / np.sum(np.abs(input[i] + input[j]))
return dist
def PRTF(input, ref, mask = None):
'''
phase retrieval transfer function (PRTF)
reference = https://doi.org/10.1364/JOSAA.23.001179
input should be aligned r-space data
reference should be fftshifted k-space amplitude data for normalization
ignore masked value if mask is given
args:
input = numpy float ndarray of size N * H * W
ref = numpy float ndarray of size H * W
mask = numpy bool ndarray of size H * W (default = None)
returns:
output = numpy ndarray with size H * W
'''
# get Fourier transform of input
freq = np.fft.fftshift(np.fft.fft2(input))
freq = np.absolute(np.mean(freq, axis = 0))
# normalization
ref[ref == 0] = 1
freq = freq / ref
if mask is not None:
freq[mask] = 0
return freq
def PSD(input, mask = None):
'''
power spectral density (PSD)
input should be fftshifted k-space amplitude or intensity data
ignore masked value if mask is given
args:
input = numpy float ndarray of size H * W
mask = numpy bool ndarray of size H * W (default = None)
returns:
output = numpy float ndarray of size max(H,W)/2
'''
# get distance mesh
di = input.shape[0]
dj = input.shape[1]
li = np.linspace(-di / 2 + 0.5, di / 2 - 0.5, num = di)
lj = np.linspace(-dj / 2 + 0.5, dj / 2 - 0.5, num = dj)
mi, mj = np.meshgrid(li, lj, indexing = 'ij')
m = np.sqrt(np.power(mi, 2) + np.power(mj, 2))
# calculate psd
r_max = min(di, dj) // 2
psd = np.zeros(r_max)
for r in tqdm(range(r_max), desc = 'psd'):
drop = (m >= r) * (m < r + 1)
if mask is not None:
drop = drop * (1 - mask)
drop = drop > 0
if np.sum(drop) > 0:
psd[r] = np.mean(input[drop])
else:
psd[r] = np.nan
return psd
def EigenMode(input, k = None, lowrank = True):
'''
extract eigenmode of input
returns low-rank approximation of input if lowrank is True
k should be given for low-rank approximation
args:
input = numpy float ndarray of size N * H * W
k = integer (default = None)
lowrank = bool (default = True)
returns:
output = numpy float array of size (N or k) * H * W
s = numpy float array of size (N or k)
approx = numpy float array of size k * H * W
'''
h = input.shape[1]
w = input.shape[2]
input = input.reshape((-1, h * w)).T
# calculate singular value decomposition
u, s, vh = svd(input, full_matrices = False)
output = u.T.reshape((-1, h, w))
if k is None:
return output, s
else:
if not lowrank:
return output[:k], s[:k]
else:
# calculate low-rank approximation with order 1 to k
approx = np.zeros((k, h, w))
for l in range(1, k + 1):
temp = u[:, :l] @ np.diag(s[:l]) @ vh[:l, :]
temp = temp[:, 0].reshape((h, w))
approx[l - 1, :, :] = temp
return output[:k], s[:k], approx | [
"numpy.mean",
"numpy.flip",
"numpy.abs",
"numpy.power",
"numpy.fft.fft2",
"numpy.argsort",
"numpy.sum",
"numpy.zeros",
"numpy.linspace",
"skimage.registration.phase_cross_correlation",
"numpy.diag",
"numpy.linalg.svd",
"numpy.meshgrid"
] | [((3058, 3073), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (3066, 3073), True, 'import numpy as np\n'), ((4637, 4685), 'numpy.linspace', 'np.linspace', (['(-di / 2 + 0.5)', '(di / 2 - 0.5)'], {'num': 'di'}), '(-di / 2 + 0.5, di / 2 - 0.5, num=di)\n', (4648, 4685), True, 'import numpy as np\n'), ((4697, 4745), 'numpy.linspace', 'np.linspace', (['(-dj / 2 + 0.5)', '(dj / 2 - 0.5)'], {'num': 'dj'}), '(-dj / 2 + 0.5, dj / 2 - 0.5, num=dj)\n', (4708, 4745), True, 'import numpy as np\n'), ((4761, 4795), 'numpy.meshgrid', 'np.meshgrid', (['li', 'lj'], {'indexing': '"""ij"""'}), "(li, lj, indexing='ij')\n", (4772, 4795), True, 'import numpy as np\n'), ((4913, 4928), 'numpy.zeros', 'np.zeros', (['r_max'], {}), '(r_max)\n', (4921, 4928), True, 'import numpy as np\n'), ((5910, 5941), 'numpy.linalg.svd', 'svd', (['input'], {'full_matrices': '(False)'}), '(input, full_matrices=False)\n', (5913, 5941), False, 'from numpy.linalg import svd\n'), ((1162, 1179), 'numpy.argsort', 'np.argsort', (['error'], {}), '(error)\n', (1172, 1179), True, 'import numpy as np\n'), ((3945, 3963), 'numpy.fft.fft2', 'np.fft.fft2', (['input'], {}), '(input)\n', (3956, 3963), True, 'import numpy as np\n'), ((3988, 4009), 'numpy.mean', 'np.mean', (['freq'], {'axis': '(0)'}), '(freq, axis=0)\n', (3995, 4009), True, 'import numpy as np\n'), ((1434, 1446), 'numpy.flip', 'np.flip', (['arr'], {}), '(arr)\n', (1441, 1446), True, 'import numpy as np\n'), ((1471, 1535), 'skimage.registration.phase_cross_correlation', 'phase_cross_correlation', (['input[0]', 'arr'], {'upsample_factor': 'subpixel'}), '(input[0], arr, upsample_factor=subpixel)\n', (1494, 1535), False, 'from skimage.registration import phase_cross_correlation\n'), ((1566, 1632), 'skimage.registration.phase_cross_correlation', 'phase_cross_correlation', (['input[0]', 'arr_T'], {'upsample_factor': 'subpixel'}), '(input[0], arr_T, upsample_factor=subpixel)\n', (1589, 1632), False, 'from skimage.registration import phase_cross_correlation\n'), ((2033, 2045), 'numpy.flip', 'np.flip', (['arr'], {}), '(arr)\n', (2040, 2045), True, 'import numpy as np\n'), ((2070, 2129), 'skimage.registration.phase_cross_correlation', 'phase_cross_correlation', (['ref', 'arr'], {'upsample_factor': 'subpixel'}), '(ref, arr, upsample_factor=subpixel)\n', (2093, 2129), False, 'from skimage.registration import phase_cross_correlation\n'), ((2160, 2221), 'skimage.registration.phase_cross_correlation', 'phase_cross_correlation', (['ref', 'arr_T'], {'upsample_factor': 'subpixel'}), '(ref, arr_T, upsample_factor=subpixel)\n', (2183, 2221), False, 'from skimage.registration import phase_cross_correlation\n'), ((4814, 4829), 'numpy.power', 'np.power', (['mi', '(2)'], {}), '(mi, 2)\n', (4822, 4829), True, 'import numpy as np\n'), ((4832, 4847), 'numpy.power', 'np.power', (['mj', '(2)'], {}), '(mj, 2)\n', (4840, 4847), True, 'import numpy as np\n'), ((5115, 5127), 'numpy.sum', 'np.sum', (['drop'], {}), '(drop)\n', (5121, 5127), True, 'import numpy as np\n'), ((5154, 5174), 'numpy.mean', 'np.mean', (['input[drop]'], {}), '(input[drop])\n', (5161, 5174), True, 'import numpy as np\n'), ((6195, 6214), 'numpy.zeros', 'np.zeros', (['(k, h, w)'], {}), '((k, h, w))\n', (6203, 6214), True, 'import numpy as np\n'), ((3221, 3248), 'numpy.abs', 'np.abs', (['(input[i] - input[j])'], {}), '(input[i] - input[j])\n', (3227, 3248), True, 'import numpy as np\n'), ((3259, 3286), 'numpy.abs', 'np.abs', (['(input[i] + input[j])'], {}), '(input[i] + input[j])\n', (3265, 3286), True, 'import numpy as np\n'), ((6287, 6301), 'numpy.diag', 'np.diag', (['s[:l]'], {}), '(s[:l])\n', (6294, 6301), True, 'import numpy as np\n'), ((1723, 1741), 'numpy.fft.fft2', 'np.fft.fft2', (['arr_T'], {}), '(arr_T)\n', (1734, 1741), True, 'import numpy as np\n'), ((1832, 1848), 'numpy.fft.fft2', 'np.fft.fft2', (['arr'], {}), '(arr)\n', (1843, 1848), True, 'import numpy as np\n'), ((2312, 2330), 'numpy.fft.fft2', 'np.fft.fft2', (['arr_T'], {}), '(arr_T)\n', (2323, 2330), True, 'import numpy as np\n'), ((2421, 2437), 'numpy.fft.fft2', 'np.fft.fft2', (['arr'], {}), '(arr)\n', (2432, 2437), True, 'import numpy as np\n')] |
# example of calculating the frechet inception distance
import os
import json
import argparse
import numpy as np
from PIL import Image
from tqdm import tqdm
import torch
from torchvision import models, transforms
import torch.nn.functional as F
from skimage.measure import compare_ssim as ssim
import torch.nn as nn
frame2file = {1: 'disc_dataset_first_frame.json',
2: 'disc_dataset_second_frame.json',
3: 'disc_dataset_third_frame.json',
4: 'disc_dataset_fourth_frame.json',
5: 'disc_dataset.json'}
class InceptionFeatureExtractor(nn.Module):
def __init__(self):
super(InceptionFeatureExtractor, self).__init__()
model_ft = models.inception_v3(pretrained=True)
for param in model_ft.parameters():
param.requires_grad = False
for param in model_ft.parameters():
param.requires_grad = False
self.define_module(model_ft)
def define_module(self, model):
self.Conv2d_1a_3x3 = model.Conv2d_1a_3x3
self.Conv2d_2a_3x3 = model.Conv2d_2a_3x3
self.Conv2d_2b_3x3 = model.Conv2d_2b_3x3
self.Conv2d_3b_1x1 = model.Conv2d_3b_1x1
self.Conv2d_4a_3x3 = model.Conv2d_4a_3x3
self.Mixed_5b = model.Mixed_5b
self.Mixed_5c = model.Mixed_5c
self.Mixed_5d = model.Mixed_5d
self.Mixed_6a = model.Mixed_6a
self.Mixed_6b = model.Mixed_6b
self.Mixed_6c = model.Mixed_6c
self.Mixed_6d = model.Mixed_6d
self.Mixed_6e = model.Mixed_6e
self.Mixed_7a = model.Mixed_7a
self.Mixed_7b = model.Mixed_7b
self.Mixed_7c = model.Mixed_7c
def forward(self, x):
# --> fixed-size input: batch x 3 x 299 x 299
# x = nn.Upsample(size=(299, 299), mode='bilinear')(x)
# 299 x 299 x 3
x = self.Conv2d_1a_3x3(x)
# 149 x 149 x 32
x = self.Conv2d_2a_3x3(x)
# 147 x 147 x 32
x = self.Conv2d_2b_3x3(x)
# 147 x 147 x 64
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 73 x 73 x 64
x = self.Conv2d_3b_1x1(x)
# 73 x 73 x 80
x = self.Conv2d_4a_3x3(x)
# 71 x 71 x 192
x = F.max_pool2d(x, kernel_size=3, stride=2)
# 35 x 35 x 192
x = self.Mixed_5b(x)
# 35 x 35 x 256
x = self.Mixed_5c(x)
# 35 x 35 x 288
x = self.Mixed_5d(x)
# 35 x 35 x 288
x = self.Mixed_6a(x)
# 17 x 17 x 768
x = self.Mixed_6b(x)
# 17 x 17 x 768
x = self.Mixed_6c(x)
# 17 x 17 x 768
x = self.Mixed_6d(x)
# 17 x 17 x 768
x = self.Mixed_6e(x)
# 17 x 17 x 768
x = self.Mixed_7a(x)
# 8 x 8 x 1280
x = self.Mixed_7b(x)
# 8 x 8 x 2048
x = self.Mixed_7c(x)
# 8 x 8 x 2048
x = F.avg_pool2d(x, kernel_size=8)
# 1 x 1 x 2048
# x = F.dropout(x, training=self.training)
# 1 x 1 x 2048
# x = x.view(x.size(0), -1)
# 2048
return x.squeeze()
def set_parameter_requires_grad(model, feature_extracting):
if feature_extracting:
for param in model.parameters():
param.requires_grad = False
def initialize_model(use_pretrained=True, feature_extract=False):
# model_ft = models.vgg11_bn(pretrained=use_pretrained)
# input_size = 224
# model_ft.classifier = model_ft.classifier[:-1]
model_ft = InceptionFeatureExtractor()
input_size = 299
set_parameter_requires_grad(model_ft, feature_extract)
return model_ft, input_size
def sample_image(im):
shorter, longer = min(im.size[0], im.size[1]), max(im.size[0], im.size[1])
video_len = int(longer / shorter)
se = np.random.randint(0, video_len, 1)[0]
# print(se*shorter, shorter, (se+1)*shorter)
return im.crop((0, se * shorter, shorter, (se + 1) * shorter))
def eval(args):
top_1_acc = 0
top_2_acc = 0
train_id, val_id, test_id = np.load(os.path.join(args.data_dir, 'train_seen_unseen_ids.npy'), allow_pickle=True)
ids = val_id if args.mode == 'val' else test_id
disc_dataset = json.load(open(os.path.join(args.data_dir, frame2file[args.frame])))
print(len(disc_dataset.keys()), len(val_id), len(test_id))
img_size = 128
if args.metric == "cosine":
model, img_size = initialize_model(feature_extract=True)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
model.eval()
preprocess = transforms.Compose([
transforms.Resize(img_size),
transforms.CenterCrop(img_size),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
cosine_fn = torch.nn.CosineSimilarity(dim=1, eps=1e-6)
skipped = 0
for i, id in tqdm(enumerate(ids[:2304])):
# query image
query_img = Image.open(os.path.join(args.output_dir, 'img-%s-0.png' % i)).resize((img_size, img_size, ))
query_pix = np.array(query_img.getdata()).reshape(query_img.size[0], query_img.size[1], 3)
# load choices
try:
choices = [disc_dataset[str(id)]["target"]] + disc_dataset[str(id)]["choices"]
except KeyError:
skipped += 1
continue
# print(choices)
choice_imgs = [sample_image(Image.open(os.path.join(args.data_dir, c))).resize((img_size, img_size, )) for c in choices]
choice_pix = [np.array(c.getdata()).reshape(c.size[0], c.size[1], 3) for c in choice_imgs]
# compute ssims
# print(query_pix[:, 0, 0], choice_pix[0][:, 0, 0])
if args.metric == "ssim":
ssims = [ssim(query_pix, im, data_range=im.max() - im.min(), multichannel=True) for im in choice_pix]
ranks = [i for i, score in sorted(enumerate(ssims), key=lambda t: t[1], reverse=True)]
elif args.metric == "cosine":
input_tensor = torch.cat([preprocess(img).unsqueeze(0) for img in [query_img] + choice_imgs], dim=0)
features = model(input_tensor.to(device))
sims = cosine_fn(features[0, :].repeat(5, 1), features[1:, :]).cpu().numpy()
ranks = [i for i, score in sorted(enumerate(sims), key=lambda t: t[1], reverse=True)]
else:
raise ValueError
if 0 in ranks[0:1]:
top_1_acc += 1
if 0 in ranks[0:2]:
top_2_acc += 1
if i%100 == 0:
print(float(top_1_acc)/(i+1), float(top_2_acc)/(i+1))
print(top_1_acc, top_2_acc)
print(skipped)
if __name__ =="__main__":
parser = argparse.ArgumentParser(description='Evaluate Discriminative Dataset')
parser.add_argument('--data_dir', type=str, required=True)
parser.add_argument('--output_dir', type=str, required=True)
parser.add_argument('--metric', type=str, default='cosine')
parser.add_argument('--mode', default='val')
parser.add_argument('--frame', type=int, default=1)
args = parser.parse_args()
eval(args)
| [
"torchvision.transforms.CenterCrop",
"torch.nn.CosineSimilarity",
"argparse.ArgumentParser",
"os.path.join",
"torch.nn.functional.avg_pool2d",
"numpy.random.randint",
"torch.cuda.is_available",
"torchvision.models.inception_v3",
"torchvision.transforms.Normalize",
"torchvision.transforms.Resize",
... | [((6849, 6919), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Evaluate Discriminative Dataset"""'}), "(description='Evaluate Discriminative Dataset')\n", (6872, 6919), False, 'import argparse\n'), ((725, 761), 'torchvision.models.inception_v3', 'models.inception_v3', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (744, 761), False, 'from torchvision import models, transforms\n'), ((2072, 2112), 'torch.nn.functional.max_pool2d', 'F.max_pool2d', (['x'], {'kernel_size': '(3)', 'stride': '(2)'}), '(x, kernel_size=3, stride=2)\n', (2084, 2112), True, 'import torch.nn.functional as F\n'), ((2269, 2309), 'torch.nn.functional.max_pool2d', 'F.max_pool2d', (['x'], {'kernel_size': '(3)', 'stride': '(2)'}), '(x, kernel_size=3, stride=2)\n', (2281, 2309), True, 'import torch.nn.functional as F\n'), ((2954, 2984), 'torch.nn.functional.avg_pool2d', 'F.avg_pool2d', (['x'], {'kernel_size': '(8)'}), '(x, kernel_size=8)\n', (2966, 2984), True, 'import torch.nn.functional as F\n'), ((3865, 3899), 'numpy.random.randint', 'np.random.randint', (['(0)', 'video_len', '(1)'], {}), '(0, video_len, 1)\n', (3882, 3899), True, 'import numpy as np\n'), ((4123, 4179), 'os.path.join', 'os.path.join', (['args.data_dir', '"""train_seen_unseen_ids.npy"""'], {}), "(args.data_dir, 'train_seen_unseen_ids.npy')\n", (4135, 4179), False, 'import os\n'), ((4956, 4999), 'torch.nn.CosineSimilarity', 'torch.nn.CosineSimilarity', ([], {'dim': '(1)', 'eps': '(1e-06)'}), '(dim=1, eps=1e-06)\n', (4981, 4999), False, 'import torch\n'), ((4290, 4341), 'os.path.join', 'os.path.join', (['args.data_dir', 'frame2file[args.frame]'], {}), '(args.data_dir, frame2file[args.frame])\n', (4302, 4341), False, 'import os\n'), ((4572, 4597), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4595, 4597), False, 'import torch\n'), ((4722, 4749), 'torchvision.transforms.Resize', 'transforms.Resize', (['img_size'], {}), '(img_size)\n', (4739, 4749), False, 'from torchvision import models, transforms\n'), ((4764, 4795), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['img_size'], {}), '(img_size)\n', (4785, 4795), False, 'from torchvision import models, transforms\n'), ((4810, 4831), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4829, 4831), False, 'from torchvision import models, transforms\n'), ((4846, 4921), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (4866, 4921), False, 'from torchvision import models, transforms\n'), ((5120, 5169), 'os.path.join', 'os.path.join', (['args.output_dir', "('img-%s-0.png' % i)"], {}), "(args.output_dir, 'img-%s-0.png' % i)\n", (5132, 5169), False, 'import os\n'), ((5580, 5610), 'os.path.join', 'os.path.join', (['args.data_dir', 'c'], {}), '(args.data_dir, c)\n', (5592, 5610), False, 'import os\n')] |
import os
import cv2
import numpy as np
animals_fruits = 'animals'
for animals_fruits in ['animals', 'fruits']:
train_test = 'test'
zl_path = '/data/zl'
dir_path = f'{zl_path}/ai_challenger_zsl2018_train_test_a_20180321/zsl_a_{animals_fruits}_test_20180321'
images_test = os.listdir(dir_path)
X = np.load(f'{zl_path}/{animals_fruits}/x_{train_test}.npy')
for idx, path in enumerate(images_test):
s_img = X[idx]
b, g, r = cv2.split(s_img) # get b,g,r
rgb_img = cv2.merge([r, g, b]) # switch it to rgb
cv2.imwrite(f'{zl_path}/img_test/{animals_fruits}/{path}', rgb_img)
| [
"cv2.imwrite",
"cv2.merge",
"os.listdir",
"cv2.split",
"numpy.load"
] | [((290, 310), 'os.listdir', 'os.listdir', (['dir_path'], {}), '(dir_path)\n', (300, 310), False, 'import os\n'), ((320, 377), 'numpy.load', 'np.load', (['f"""{zl_path}/{animals_fruits}/x_{train_test}.npy"""'], {}), "(f'{zl_path}/{animals_fruits}/x_{train_test}.npy')\n", (327, 377), True, 'import numpy as np\n'), ((464, 480), 'cv2.split', 'cv2.split', (['s_img'], {}), '(s_img)\n', (473, 480), False, 'import cv2\n'), ((517, 537), 'cv2.merge', 'cv2.merge', (['[r, g, b]'], {}), '([r, g, b])\n', (526, 537), False, 'import cv2\n'), ((569, 636), 'cv2.imwrite', 'cv2.imwrite', (['f"""{zl_path}/img_test/{animals_fruits}/{path}"""', 'rgb_img'], {}), "(f'{zl_path}/img_test/{animals_fruits}/{path}', rgb_img)\n", (580, 636), False, 'import cv2\n')] |
import eel
import os
import glob
import shutil
import codecs
from OpenGL.GL import *
from OpenGL.WGL import *
from ctypes import *
import numpy
import pyaudio
import array
import re
class FileSystem():
def __init__(self):
self.categoryDir = './category'
self.extension = '.glsl'
self.defaultSrc = '''vec2 mainSound(int samp, float time){
return vec2(sin(6.2831*440.0*time)*exp(-3.0*time));
}
'''
if not os.path.exists(self.categoryDir):
os.mkdir(self.categoryDir)
if len(self.listCategory())==0:
self.newCategory('default')
def load(self, name):
src = ''
if os.path.exists(name):
f = codecs.open(name, 'r', 'utf-8')
src = f.read()
f.close()
return src
def save(self, name, src):
f = codecs.open(name, 'w', 'utf-8')
f.write(src)
f.close()
def pathCategory(self, category):
return self.categoryDir + '/' + category
def filenameShader(self, category, shader):
return self.pathCategory(category) + '/' + shader + self.extension
def listCategory(self):
files = glob.glob(self.pathCategory("*"))
files.sort(key=os.path.getatime, reverse=True)
return ",".join(list(map(lambda a:os.path.basename(a),files)))
def listShaders(self, category):
files = glob.glob(self.filenameShader(category, '*'))
files.sort(key=os.path.getmtime, reverse=True)
return ','.join(list(map(lambda a:os.path.basename(a).split('.')[0],files)))
def newShader(self, category):
name = self.uniqShader(category)
self.saveShader(category, name, self.defaultSrc)
return name
def newCategory(self, category):
if len(category)==0: return 0
name = self.pathCategory(category)
if not os.path.exists(name):
os.mkdir(name)
self.save(self.filenameShader(category, category), self.defaultSrc)
return 1
return 0
def forkShader(self, category, shader):
name = self.uniqShader(category, shader)
self.saveShader(category, name, self.loadShader(category, shader))
return name
def delShader(self, category, shader):
ret = 0
name = self.filenameShader(category, shader)
if os.path.exists(name): os.remove(name)
if len(self.listShaders(category))==0:
ret = 1
os.rmdir(self.pathCategory(category))
if len(self.listCategory())==0:
self.newCategory('default')
return ret
def renameCategory(self, old, new):
if len(new) == 0: return 0
if os.path.exists(self.pathCategory(new)):
return 0
os.rename(self.pathCategory(old), self.pathCategory(new))
return 1
def renameShader(self, category, old, new):
if len(new) == 0: return 0
if os.path.exists(self.filenameShader(category, new)):
return 0
else:
os.rename(self.filenameShader(category, old), self.filenameShader(category, new))
return 1
def uniqShader(self, category, shader = '', fork = True):
if (len(shader) is 0):
num = 0
while os.path.exists(self.filenameShader(category, category + "_" + str(num))):
num += 1
return category + "_" + str(num)
else:
num = 0
s = "_fork" if fork else "-"
shader = re.sub(r'_.*[0-9]*', '', shader)
while os.path.exists(self.filenameShader(category, shader + s + str(num))):
num += 1
return shader + s + str(num)
def shiftShader(self, old, new, shader):
name = self.uniqShader(new, shader, False)
shutil.move(
self.filenameShader(old, shader),
self.filenameShader(new, name))
if len(self.listShaders(old))==0:
os.rmdir(self.pathCategory(old))
return name
def forkShader(self, category, shader):
srcFilename = self.filenameShader(category, shader)
name = self.uniqShader(category, shader)
dstFilename = self.filenameShader(category, name)
self.save(dstFilename, self.load(srcFilename))
return name
def loadShader(self, category, shader):
filename = self.filenameShader(category, shader)
return self.load(filename)
def saveShader(self, category, shader, src):
filename = self.filenameShader(category, shader)
self.save(filename, src)
class SoundShader():
def __init__(self, chunk, rate):
self.chunk = chunk
self.rate = rate
self.channels = 2
self.head ='''
#version 430
out vec2 gain;
uniform float iFrameCount;
const float iChunk = {0:.1f};
const float iSampleRate = {1:.1f};
'''.format(self.chunk ,self.rate)
self.foot ='''
void main() {
float time = (iChunk * iFrameCount + float(gl_VertexID)) / iSampleRate;
int samp = int(iFrameCount);
gain = clamp(mainSound(samp, time), -1.0, 1.0);
}
'''
# OpenGL Context
self.hWnd = windll.user32.CreateWindowExA(0,0xC018,0,0,0,0,0,0,0,0,0,0)
self.hDC = windll.user32.GetDC(self.hWnd)
pfd = PIXELFORMATDESCRIPTOR(0,1,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0)
SetPixelFormat(self.hDC,ChoosePixelFormat(self.hDC, pfd), pfd)
self.hGLrc = wglCreateContext(self.hDC)
wglMakeCurrent(self.hDC, self.hGLrc)
# Buffer
self.samples = (c_float * self.chunk * self.channels)()
vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, sizeof(self.samples), None, GL_STATIC_DRAW)
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, vbo)
self.alive = False
self.success = False
self.program = glCreateProgram()
def audioData(self, frame_count):
if self.alive:
glUniform1f(glGetUniformLocation(self.program, "iFrameCount"), frame_count)
glEnable(GL_RASTERIZER_DISCARD)
glBeginTransformFeedback(GL_POINTS)
glDrawArrays(GL_POINTS, 0, self.chunk)
glEndTransformFeedback()
glDisable(GL_RASTERIZER_DISCARD)
glGetBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(self.samples), byref(self.samples))
return numpy.frombuffer(self.samples, dtype=numpy.float32)
def compile(self, src):
shader = glCreateShader(GL_VERTEX_SHADER)
glShaderSource(shader, self.head + src + self.foot)
glCompileShader(shader)
if glGetShaderiv(shader, GL_COMPILE_STATUS) != GL_TRUE:
self.success = False
return (glGetShaderInfoLog(shader).decode())
p = self.program
self.program = glCreateProgram()
glAttachShader(self.program, shader)
glDeleteShader(shader)
outs = cast((c_char_p*1)(b"gain"), POINTER(POINTER(c_char)))
glTransformFeedbackVaryings(self.program, 1, outs, GL_INTERLEAVED_ATTRIBS)
glLinkProgram(self.program)
glUseProgram(self.program)
glDeleteProgram(p)
self.success = True
return ("Success")
def close(self):
wglMakeCurrent(0, 0);
wglDeleteContext(self.hGLrc);
windll.user32.ReleaseDC(self.hWnd, self.hDC);
windll.user32.PostQuitMessage(0);
def trimSize(self, src):
src = re.compile(r'/\*.*?\*/', re.DOTALL).sub("", src)
src = re.sub(r"//.*", "", src)
src = re.sub(r"\t", " ", src)
src = re.sub(r" +", " ", src)
src = re.sub(r" *\n *", "\n", src)
src = re.sub(r"\n+", "\n", src)
src = re.sub(r"^\n", "", src)
L = src.split("\n")
for i in range(len(L)):
s = L[i]
if re.search("#", s) != None:
L[i] = "\n" + L[i] + "\n"
else:
s = re.sub(r" *\+ *" ,"+", s)
s = re.sub(r" *\- *" ,"-", s)
s = re.sub(r" *\* *" ,"*", s)
s = re.sub(r" */ *" ,"/", s)
s = re.sub(r" *= *" ,"=", s)
s = re.sub(r" *< *" ,"<", s)
s = re.sub(r" *> *" ,">", s)
s = re.sub(r" *& *" ,"&", s)
s = re.sub(r" *\| *" ,"|", s)
s = re.sub(r" *\( *" ,"(", s)
s = re.sub(r" *\) *" ,")", s)
s = re.sub(r" *\[ *" ,"[", s)
s = re.sub(r" *\] *" ,"]", s)
s = re.sub(r" *{ *" ,"{", s)
s = re.sub(r" *} *" ,"}", s)
s = re.sub(r" *; *" ,";", s)
s = re.sub(r" *, *" ,",", s)
L[i] = s
src = "".join(L)
src = re.sub(r"\n+", "\n", src)
src = re.sub(r"^\n", "", src)
return len(src)
class Tick():
def __init__(self, chunk, rate):
self.n = 0
self.chunk = chunk
self.rate = rate
self.startN = 0
self.endN = 1800
def clucN(self, sec):
return sec * self.rate / self.chunk
def clucTime(self, n):
return n * self.chunk / self.rate
def startTime(self, sec):
self.startN = self.clucN(sec)
self.n = max(self.startN, self.n)
def endTime(self, sec):
self.endN = self.clucN(sec)
self.n = min(self.endN, self.n)
def reset(self):
self.n = self.startN
def time(self):
return self.clucTime(self.n)
def tick(self):
self.n += 1
if self.endN < self.n:
self.n = self.startN
return self.n
@eel.expose
def charSize(src):
global s
return s.trimSize(src)
@eel.expose
def compile(src):
global s
s.alive = False
ret = s.compile(src)
s.alive = True
return ret
@eel.expose
def success():
global s
return s.success
@eel.expose
def listCategory():
global f
return f.listCategory()
@eel.expose
def listShaders(category):
global f
return f.listShaders(category)
@eel.expose
def newCategory(category):
global f
return f.newCategory(category)
@eel.expose
def newShader(category):
global f
return f.newShader(category)
@eel.expose
def forkShader(category, shader):
global f
return f.forkShader(category, shader)
@eel.expose
def delShader(category, shader):
global f
return f.delShader(category, shader)
@eel.expose
def renameCategory(old, new):
global f
return f.renameCategory(old, new)
@eel.expose
def renameShader(category, old, new):
global f
return f.renameShader(category, old, new)
@eel.expose
def shiftShader(old, new, shader):
global f
return f.shiftShader(old, new, shader)
@eel.expose
def loadShader(category, shader):
global f
return f.loadShader(category, shader)
@eel.expose
def saveShader(category, shader,src):
global f
return f.saveShader(category, shader, src)
@eel.expose
def reset():
global t
t.reset()
@eel.expose
def startTime(x):
global t
t.startTime(x)
@eel.expose
def endTime(x):
global t
t.endTime(x)
@eel.expose
def play():
global s
s.alive = s.success
return s.alive
@eel.expose
def stop():
global s
s.alive = False
@eel.expose
def close():
global alive
alive = False
##+++ main +++++++++++++++++
eel.init("web")
eel.start("index.html",port=8002, block=False)
chunk = 2048
rate = 44100
s = SoundShader(chunk, rate)
t = Tick(chunk, rate)
f = FileSystem()
alive = True
eel.data(s.audioData(0).tolist())
p = pyaudio.PyAudio()
stream = p.open(
format = pyaudio.paFloat32,
channels = 2,
rate = s.rate,
frames_per_buffer = s.chunk,
output=True,
input=False
)
stream.start_stream()
while alive:
eel.sleep(0.01)
if s.alive:
data = s.audioData(t.tick())
stream.write(array.array('f', data).tobytes())
eel.data(numpy.hstack((data[::2], data[1::2])).tolist())
eel.time(t.time())
stream.stop_stream()
s.close()
| [
"re.search",
"os.path.exists",
"eel.sleep",
"eel.start",
"array.array",
"eel.init",
"re.compile",
"numpy.hstack",
"os.mkdir",
"os.path.basename",
"re.sub",
"numpy.frombuffer",
"codecs.open",
"pyaudio.PyAudio",
"os.remove"
] | [((11905, 11920), 'eel.init', 'eel.init', (['"""web"""'], {}), "('web')\n", (11913, 11920), False, 'import eel\n'), ((11922, 11969), 'eel.start', 'eel.start', (['"""index.html"""'], {'port': '(8002)', 'block': '(False)'}), "('index.html', port=8002, block=False)\n", (11931, 11969), False, 'import eel\n'), ((12128, 12145), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (12143, 12145), False, 'import pyaudio\n'), ((12354, 12369), 'eel.sleep', 'eel.sleep', (['(0.01)'], {}), '(0.01)\n', (12363, 12369), False, 'import eel\n'), ((719, 739), 'os.path.exists', 'os.path.exists', (['name'], {}), '(name)\n', (733, 739), False, 'import os\n'), ((909, 940), 'codecs.open', 'codecs.open', (['name', '"""w"""', '"""utf-8"""'], {}), "(name, 'w', 'utf-8')\n", (920, 940), False, 'import codecs\n'), ((2468, 2488), 'os.path.exists', 'os.path.exists', (['name'], {}), '(name)\n', (2482, 2488), False, 'import os\n'), ((6672, 6723), 'numpy.frombuffer', 'numpy.frombuffer', (['self.samples'], {'dtype': 'numpy.float32'}), '(self.samples, dtype=numpy.float32)\n', (6688, 6723), False, 'import numpy\n'), ((7822, 7845), 're.sub', 're.sub', (['"""//.*"""', '""""""', 'src'], {}), "('//.*', '', src)\n", (7828, 7845), False, 'import re\n'), ((7866, 7889), 're.sub', 're.sub', (['"""\\\\t"""', '""" """', 'src'], {}), "('\\\\t', ' ', src)\n", (7872, 7889), False, 'import re\n'), ((7910, 7932), 're.sub', 're.sub', (['""" +"""', '""" """', 'src'], {}), "(' +', ' ', src)\n", (7916, 7932), False, 'import re\n'), ((7954, 7982), 're.sub', 're.sub', (['""" *\\\\n *"""', '"""\n"""', 'src'], {}), "(' *\\\\n *', '\\n', src)\n", (7960, 7982), False, 'import re\n'), ((7998, 8023), 're.sub', 're.sub', (['"""\\\\n+"""', '"""\n"""', 'src'], {}), "('\\\\n+', '\\n', src)\n", (8004, 8023), False, 'import re\n'), ((8046, 8069), 're.sub', 're.sub', (['"""^\\\\n"""', '""""""', 'src'], {}), "('^\\\\n', '', src)\n", (8052, 8069), False, 'import re\n'), ((9130, 9155), 're.sub', 're.sub', (['"""\\\\n+"""', '"""\n"""', 'src'], {}), "('\\\\n+', '\\n', src)\n", (9136, 9155), False, 'import re\n'), ((9171, 9194), 're.sub', 're.sub', (['"""^\\\\n"""', '""""""', 'src'], {}), "('^\\\\n', '', src)\n", (9177, 9194), False, 'import re\n'), ((480, 512), 'os.path.exists', 'os.path.exists', (['self.categoryDir'], {}), '(self.categoryDir)\n', (494, 512), False, 'import os\n'), ((527, 553), 'os.mkdir', 'os.mkdir', (['self.categoryDir'], {}), '(self.categoryDir)\n', (535, 553), False, 'import os\n'), ((758, 789), 'codecs.open', 'codecs.open', (['name', '"""r"""', '"""utf-8"""'], {}), "(name, 'r', 'utf-8')\n", (769, 789), False, 'import codecs\n'), ((1968, 1988), 'os.path.exists', 'os.path.exists', (['name'], {}), '(name)\n', (1982, 1988), False, 'import os\n'), ((2003, 2017), 'os.mkdir', 'os.mkdir', (['name'], {}), '(name)\n', (2011, 2017), False, 'import os\n'), ((2490, 2505), 'os.remove', 'os.remove', (['name'], {}), '(name)\n', (2499, 2505), False, 'import os\n'), ((3674, 3705), 're.sub', 're.sub', (['"""_.*[0-9]*"""', '""""""', 'shader'], {}), "('_.*[0-9]*', '', shader)\n", (3680, 3705), False, 'import re\n'), ((7758, 7794), 're.compile', 're.compile', (['"""/\\\\*.*?\\\\*/"""', 're.DOTALL'], {}), "('/\\\\*.*?\\\\*/', re.DOTALL)\n", (7768, 7794), False, 'import re\n'), ((8175, 8192), 're.search', 're.search', (['"""#"""', 's'], {}), "('#', s)\n", (8184, 8192), False, 'import re\n'), ((8285, 8310), 're.sub', 're.sub', (['""" *\\\\+ *"""', '"""+"""', 's'], {}), "(' *\\\\+ *', '+', s)\n", (8291, 8310), False, 'import re\n'), ((8332, 8357), 're.sub', 're.sub', (['""" *\\\\- *"""', '"""-"""', 's'], {}), "(' *\\\\- *', '-', s)\n", (8338, 8357), False, 'import re\n'), ((8379, 8404), 're.sub', 're.sub', (['""" *\\\\* *"""', '"""*"""', 's'], {}), "(' *\\\\* *', '*', s)\n", (8385, 8404), False, 'import re\n'), ((8426, 8449), 're.sub', 're.sub', (['""" */ *"""', '"""/"""', 's'], {}), "(' */ *', '/', s)\n", (8432, 8449), False, 'import re\n'), ((8473, 8496), 're.sub', 're.sub', (['""" *= *"""', '"""="""', 's'], {}), "(' *= *', '=', s)\n", (8479, 8496), False, 'import re\n'), ((8520, 8543), 're.sub', 're.sub', (['""" *< *"""', '"""<"""', 's'], {}), "(' *< *', '<', s)\n", (8526, 8543), False, 'import re\n'), ((8567, 8590), 're.sub', 're.sub', (['""" *> *"""', '""">"""', 's'], {}), "(' *> *', '>', s)\n", (8573, 8590), False, 'import re\n'), ((8614, 8637), 're.sub', 're.sub', (['""" *& *"""', '"""&"""', 's'], {}), "(' *& *', '&', s)\n", (8620, 8637), False, 'import re\n'), ((8661, 8686), 're.sub', 're.sub', (['""" *\\\\| *"""', '"""|"""', 's'], {}), "(' *\\\\| *', '|', s)\n", (8667, 8686), False, 'import re\n'), ((8708, 8733), 're.sub', 're.sub', (['""" *\\\\( *"""', '"""("""', 's'], {}), "(' *\\\\( *', '(', s)\n", (8714, 8733), False, 'import re\n'), ((8755, 8780), 're.sub', 're.sub', (['""" *\\\\) *"""', '""")"""', 's'], {}), "(' *\\\\) *', ')', s)\n", (8761, 8780), False, 'import re\n'), ((8802, 8827), 're.sub', 're.sub', (['""" *\\\\[ *"""', '"""["""', 's'], {}), "(' *\\\\[ *', '[', s)\n", (8808, 8827), False, 'import re\n'), ((8849, 8874), 're.sub', 're.sub', (['""" *\\\\] *"""', '"""]"""', 's'], {}), "(' *\\\\] *', ']', s)\n", (8855, 8874), False, 'import re\n'), ((8896, 8919), 're.sub', 're.sub', (['""" *{ *"""', '"""{"""', 's'], {}), "(' *{ *', '{', s)\n", (8902, 8919), False, 'import re\n'), ((8943, 8966), 're.sub', 're.sub', (['""" *} *"""', '"""}"""', 's'], {}), "(' *} *', '}', s)\n", (8949, 8966), False, 'import re\n'), ((8990, 9013), 're.sub', 're.sub', (['""" *; *"""', '""";"""', 's'], {}), "(' *; *', ';', s)\n", (8996, 9013), False, 'import re\n'), ((9037, 9060), 're.sub', 're.sub', (['""" *, *"""', '""","""', 's'], {}), "(' *, *', ',', s)\n", (9043, 9060), False, 'import re\n'), ((12447, 12469), 'array.array', 'array.array', (['"""f"""', 'data'], {}), "('f', data)\n", (12458, 12469), False, 'import array\n'), ((12499, 12536), 'numpy.hstack', 'numpy.hstack', (['(data[::2], data[1::2])'], {}), '((data[::2], data[1::2]))\n', (12511, 12536), False, 'import numpy\n'), ((1384, 1403), 'os.path.basename', 'os.path.basename', (['a'], {}), '(a)\n', (1400, 1403), False, 'import os\n'), ((1615, 1634), 'os.path.basename', 'os.path.basename', (['a'], {}), '(a)\n', (1631, 1634), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
# Project: dspus
# injections.py
# Created by @wenchieh on <1/12/2020>
__author__ = 'wenchieh'
# sys
from random import sample
# third-part libs
import numpy as np
from scipy import linalg
from scipy.sparse import *
# parameters in injection -
# spike(M, N, Dspike, C),
# gap(M, N, D0, Dgap, C)
def injectSpike(Nall, M, N, Dspike, C):
Nstart, i = Nall, Nall
injectEs = list()
injectUs, injectVs = range(Nall, Nall + M, 1), range(Nall, Nall + N, 1)
for m in range(M):
# standard normal distribution
v1, v2, w = 0.0, 0.0, 2.0
while w > 1.0:
v1 = random.random() * 2.0 - 1.0
v2 = random.random() * 2.0 - 1.0
w = v1 * v1 + v2 * v2
outd = int(Dspike + v1 * np.sqrt(-2.0 * np.log(w) / w))
if outd < 0: outd = Dspike
outdC = int(outd * C)
outdN = outd - outdC
Ns, Cs = set(), set()
for d in range(outdN):
Ns.add(Nstart + M + random.randint(N))
for d in range(outdC):
Cs.add(random.randint(Nall))
for j in Ns:
injectEs.append([i, j])
for j in Cs:
injectEs.append([i, j])
i += 1
return len(injectEs), injectEs, injectUs, injectVs
def injectGap(Nall, M, N, D0, Dgap, C):
injectEs = list()
injectUs, injectVs = range(Nall, Nall + M, 1), range(Nall, Nall + N, 1)
Nstart, i = Nall, Nall
Md = int(1.0 * M / (Dgap - D0 + 1))
for outd in range(D0, Dgap, 1):
for m in range(Md):
outdC = int(outd * C)
outdN = outd - outdC
Ns, Cs = set(), set()
for d in range(outdN):
Ns.add(Nstart + M + random.randint(N))
for d in range(outdC):
Cs.add(random.randint(Nall))
for j in Ns:
injectEs.append([i, j])
for j in Cs:
injectEs.append([i, j])
i += 1
return len(injectEs), injectEs, injectUs, injectVs
def genEvenDenseBlock(A, B, p):
m = []
for i in range(A):
a = np.random.binomial(1, p, B)
m.append(a)
return np.array(m)
def genHyperbolaDenseBlock(A, B, alpha, tau):
'this is from hyperbolic paper: i^\alpha * j^\alpha > \tau'
m = np.empty([A, B], dtype=int)
for i in range(A):
for j in range(B):
if (i+1)**alpha * (j+1)**alpha > tau:
m[i,j] = 1
else:
m[i,j] = 0
return m
def genDiHyperRectBlocks(A1, B1, A2, B2, alpha=-0.5, tau=None, p=1):
if tau is None:
tau = A1**alpha * B1**alpha
m1 = genEvenDenseBlock(A1, B1, p=p)
m2 = genHyperbolaDenseBlock(A2, B2, alpha, tau)
M = linalg.block_diag(m1, m2)
return M
def addnosie(M, A, B, p, black=True, A0=0, B0=0):
v = 1 if black else 0
for i in range(A-A0):
a = np.random.binomial(1, p, B-B0)
for j in a.nonzero()[0]:
M[A0+i,B0+j]=v
return M
# inject a clique of size m0 by n0 with density p.
# the last parameter `testIdx` determines the camouflage type.
# testIdx = 1: random camouflage, with camouflage density set so each fraudster outputs approximately equal number of fraudulent and camouflage edges
# testIdx = 2: random camouflage, with double the density as in the precious setting
# testIdx = 3: biased camouflage, more likely to add camouflage to high degree column
#
# def injectCliqueCamo(M, m0, n0, p, testIdx):
# (m,n) = M.shape
# M2 = M.copy().tolil()
#
# colSum = np.squeeze(M2.sum(axis = 0).A)
# colSumPart = colSum[n0:n]
# colSumPartPro = np.int_(colSumPart)
# colIdx = np.arange(n0, n, 1)
# population = np.repeat(colIdx, colSumPartPro, axis = 0)
#
# for i in range(m0):
# # inject clique
# for j in range(n0):
# if random.random() < p:
# M2[i,j] = 1
# # inject camo
# if testIdx == 1:
# thres = p * n0 / (n - n0)
# for j in range(n0, n):
# if random.random() < thres:
# M2[i,j] = 1
# if testIdx == 2:
# thres = 2 * p * n0 / (n - n0)
# for j in range(n0, n):
# if random.random() < thres:
# M2[i,j] = 1
# # biased camo
# if testIdx == 3:
# colRplmt = random.sample(population, int(n0 * p))
# M2[i,colRplmt] = 1
#
# return M2.tocsc()
# inject a clique of size m0 by n0 with density p.
# the last parameter `testIdx` determines the camouflage type.
# testIdx = 1: random camouflage, with camouflage density set so each fraudster outputs approximately equal number of fraudulent and camouflage edges
# testIdx = 2: random camouflage, with double the density as in the precious setting
# testIdx = 3: biased camouflage, more likely to add camouflage to high degree column
def injectCliqueCamo(M, m0, n0, p, testIdx):
(m, n) = M.shape
injectEs = list()
injectUs, injectVs = np.arange(m0), np.arange(n0)
if testIdx in [3, 4]: # popular biased camouflage
colSum = np.squeeze(M.sum(axis = 0).A)
colSumPart = colSum[n0:n]
colSumPartPro = np.int_(colSumPart)
colIdx = np.arange(n0, n, 1)
population = np.repeat(colIdx, colSumPartPro, axis = 0)
for i in range(m0):
# inject clique
for j in range(n0):
if np.random.random() < p:
injectEs.append([i,j])
if testIdx == 0:
continue
# inject random camo
if testIdx == 1:
thres = p * n0 / (n - n0)
for j in range(n0, n):
if np.random.random() < thres:
injectEs.append([i,j])
if testIdx == 2:
thres = 2 * p * n0 / (n - n0)
for j in range(n0, n):
if np.random.random() < thres:
injectEs.append([i,j])
# biased camo
if testIdx == 3:
colRplmt = sample(population, int(n0 * p))
for j in colRplmt:
injectEs.append([i,j])
if testIdx == 4:
colRplmt = sample(population, int(2* n0 * p))
for j in colRplmt:
injectEs.append([i,j])
return len(injectEs), injectEs, injectUs, injectVs
# inject appended m0 by n0 camouflages to background graph M (cpy & paste patterns)
# add new nodes and edges
def injectAppendCPsCamo(M, m0, n0, p, camos):
(m, n) = M.shape
injectEs = list()
injectUs, injectVs = np.arange(m0) + m, np.arange(n0) + n
col_sum = np.squeeze(M.sum(axis = 0).A)
col_sumpro = np.int_(col_sum)
col_idx = np.arange(n)
pops = np.repeat(col_idx, col_sumpro, axis = 0)
# inject dependent block
for i in injectUs:
for j in injectVs:
pe = random.random()
if pe < p: injectEs.append([i, j])
if camos == 0: pass # no camo
if camos == 1:
# random camo
thres = p * n0 / (n - n0)
for j in range(n):
pe = random.random()
if pe < thres: injectEs.append([i, j])
if camos == 2:
# popular biased camo
col_pops = random.sample(pops, int(n0 * p))
for j in col_pops: injectEs.append([i, j])
return len(injectEs), injectEs, injectUs, injectVs
# pick nodes in original graph and add new edges
def injectPromotCamo(M, ms, ns, p, camos):
(m, n) = M.shape
M2 = M.copy()
m0, n0 = len(ms), len(ns)
injectEs = list()
injectUs, injectVs = np.asarray(ms, dtype=int), np.asarray(ns, dtype=int)
if camos in [3, 4, 5]:
col_sum = np.squeeze(M2.sum(axis = 0).A)
col_idx = np.setdiff1d(np.arange(n, dtype=int), injectVs)
col_sumpart = col_sum[col_idx]
pops = np.repeat(col_idx, np.int_(col_sumpart), axis = 0)
for i in injectUs:
# inject clique
for j in injectVs:
if random.random() < p and M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
if camos == 0:
continue
if camos == 1:
# random camo
thres = p * n0 / (n - n0)
for j in range(n):
pe = random.random()
if pe < thres and M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
if camos == 2:
# random camo
thres = 2 * p * n0 / (n - n0)
for j in range(n):
pe = random.random()
if pe < thres and M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
if camos in [3, 4, 5]:
# popular biased camo
n0p = 0
if camos == 4: n0p = 0.5 * n0 *p
elif camos == 3: n0p = n0 * p
elif camos == 5: n0p = 2 * n0 * p
col_pops = random.sample(pops, int(n0p))
for j in col_pops:
if M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
return M2, injectEs, injectUs, injectVs
def injectFraudConstObjs(M, ms, ns, p, testIdx):
M2 = M.copy()
injectEs = list()
injectUs = np.asarray(ms, dtype=int)
injectVs = np.asarray(ns, dtype=int)
if testIdx == 0:
M2[ms, :][:, ns] = 0
nmps = int(p * len(ms))
for j in injectVs:
for i in random.sample(injectUs, nmps):
if M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
elif testIdx == 1:
for i in injectUs:
for j in injectVs:
if random.random() < p and M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
return M2, injectEs, injectUs, injectVs
def injectedCamos(M, ms, ns, p, camos):
(m, n) = M.shape
M1 = M.copy()
m0, n0 = len(ms), len(ns)
otherns = np.setdiff1d(np.arange(n, dtype=int), ns)
for i in ms:
if camos == 1: # random camo
thres = p * n0 / (n - n0)
for j in otherns:
if random.random() < thres:
M1[i, j] = 1
if camos in [3, 4, 5]: # biased camo
col_sum = np.squeeze(M.sum(axis = 0).A)
col_sumpart = col_sum[otherns]
pops = np.repeat(otherns, np.int_(col_sumpart), axis = 0)
n0p = n0 * p
if camos == 3: n0p *= 0.25
if camos == 4: n0p *= 0.5
col_pops = random.sample(pops, int(n0p))
for j in col_pops:
M1[i, j] = 1
return M1
def injectJellyAttack(M, ms, ns, pns, p1, p2):
(m, n) = M.shape
M2 = M.copy()
m0, n0, n1 = len(ms), len(ns), len(pns)
injectEs = list()
# col_idx = pns
# col_sum = np.squeeze(M2[:, pns].sum(axis = 0).A)
# pops = np.repeat(col_idx, np.int_(col_sum), axis = 0)
for i in ms:
for j in ns:
if random.random() < p1 and M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
for j in pns:
if random.random() < p2 and M2[i, j] == 0:
M2[i, j] = 1
injectEs.append([i, j])
return M2, injectEs, ms, ns
| [
"numpy.repeat",
"numpy.random.random",
"numpy.log",
"numpy.asarray",
"numpy.array",
"numpy.empty",
"numpy.random.binomial",
"scipy.linalg.block_diag",
"numpy.int_",
"numpy.arange"
] | [((2186, 2197), 'numpy.array', 'np.array', (['m'], {}), '(m)\n', (2194, 2197), True, 'import numpy as np\n'), ((2317, 2344), 'numpy.empty', 'np.empty', (['[A, B]'], {'dtype': 'int'}), '([A, B], dtype=int)\n', (2325, 2344), True, 'import numpy as np\n'), ((2756, 2781), 'scipy.linalg.block_diag', 'linalg.block_diag', (['m1', 'm2'], {}), '(m1, m2)\n', (2773, 2781), False, 'from scipy import linalg\n'), ((6670, 6686), 'numpy.int_', 'np.int_', (['col_sum'], {}), '(col_sum)\n', (6677, 6686), True, 'import numpy as np\n'), ((6701, 6713), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (6710, 6713), True, 'import numpy as np\n'), ((6725, 6763), 'numpy.repeat', 'np.repeat', (['col_idx', 'col_sumpro'], {'axis': '(0)'}), '(col_idx, col_sumpro, axis=0)\n', (6734, 6763), True, 'import numpy as np\n'), ((9294, 9319), 'numpy.asarray', 'np.asarray', (['ms'], {'dtype': 'int'}), '(ms, dtype=int)\n', (9304, 9319), True, 'import numpy as np\n'), ((9335, 9360), 'numpy.asarray', 'np.asarray', (['ns'], {'dtype': 'int'}), '(ns, dtype=int)\n', (9345, 9360), True, 'import numpy as np\n'), ((2127, 2154), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'p', 'B'], {}), '(1, p, B)\n', (2145, 2154), True, 'import numpy as np\n'), ((2910, 2942), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'p', '(B - B0)'], {}), '(1, p, B - B0)\n', (2928, 2942), True, 'import numpy as np\n'), ((5040, 5053), 'numpy.arange', 'np.arange', (['m0'], {}), '(m0)\n', (5049, 5053), True, 'import numpy as np\n'), ((5055, 5068), 'numpy.arange', 'np.arange', (['n0'], {}), '(n0)\n', (5064, 5068), True, 'import numpy as np\n'), ((5230, 5249), 'numpy.int_', 'np.int_', (['colSumPart'], {}), '(colSumPart)\n', (5237, 5249), True, 'import numpy as np\n'), ((5267, 5286), 'numpy.arange', 'np.arange', (['n0', 'n', '(1)'], {}), '(n0, n, 1)\n', (5276, 5286), True, 'import numpy as np\n'), ((5308, 5348), 'numpy.repeat', 'np.repeat', (['colIdx', 'colSumPartPro'], {'axis': '(0)'}), '(colIdx, colSumPartPro, axis=0)\n', (5317, 5348), True, 'import numpy as np\n'), ((7619, 7644), 'numpy.asarray', 'np.asarray', (['ms'], {'dtype': 'int'}), '(ms, dtype=int)\n', (7629, 7644), True, 'import numpy as np\n'), ((7646, 7671), 'numpy.asarray', 'np.asarray', (['ns'], {'dtype': 'int'}), '(ns, dtype=int)\n', (7656, 7671), True, 'import numpy as np\n'), ((10033, 10056), 'numpy.arange', 'np.arange', (['n'], {'dtype': 'int'}), '(n, dtype=int)\n', (10042, 10056), True, 'import numpy as np\n'), ((6570, 6583), 'numpy.arange', 'np.arange', (['m0'], {}), '(m0)\n', (6579, 6583), True, 'import numpy as np\n'), ((6590, 6603), 'numpy.arange', 'np.arange', (['n0'], {}), '(n0)\n', (6599, 6603), True, 'import numpy as np\n'), ((7780, 7803), 'numpy.arange', 'np.arange', (['n'], {'dtype': 'int'}), '(n, dtype=int)\n', (7789, 7803), True, 'import numpy as np\n'), ((7888, 7908), 'numpy.int_', 'np.int_', (['col_sumpart'], {}), '(col_sumpart)\n', (7895, 7908), True, 'import numpy as np\n'), ((5443, 5461), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5459, 5461), True, 'import numpy as np\n'), ((10442, 10462), 'numpy.int_', 'np.int_', (['col_sumpart'], {}), '(col_sumpart)\n', (10449, 10462), True, 'import numpy as np\n'), ((5699, 5717), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5715, 5717), True, 'import numpy as np\n'), ((5891, 5909), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5907, 5909), True, 'import numpy as np\n'), ((821, 830), 'numpy.log', 'np.log', (['w'], {}), '(w)\n', (827, 830), True, 'import numpy as np\n')] |
"""
feature set
<NAME>, University College Cork
Started: 06-09-2019
last update: Time-stamp: <2019-12-17 18:01:52 (otoolej)>
"""
import numpy as np
from matplotlib import pyplot as plt
from numba import jit
import math
from scipy.signal import hilbert, resample_poly
from burst_detector import utils, bd_parameters
def edo_feat(x, Fs, params=None, DBplot=False):
"""generate Envelope Derivative Operator (EDO). See [1] for details:
[1] <NAME> and <NAME>, “Assessing instantaneous energy in the EEG: a
non-negative, frequency-weighted energy operator”, In Engineering in Medicine and
Biology Society (EMBC), 2014 36th Annual International Conference of the IEEE,
pp. 3288-3291. IEEE, 2014.
Parameters
----------
x: ndarray
input signal
Fs: scale
sampling frequency
params: object, optional
dataclass object of parameters
DBplot: bool, optional
plot feature vs. signal
Returns
-------
edo : ndarray
EDO, same size as input signal x
"""
if params is None:
params = bd_parameters.bdParams()
N_x = len(x)
if Fs != params.Fs_edo:
Fs_orig = Fs
x = resample_poly(x, params.Fs_edo, Fs)
Fs = params.Fs_edo
else:
Fs_orig = []
# -------------------------------------------------------------------
# 1. bandpass filter the signal from 0.5 to 10 Hz
# -------------------------------------------------------------------
x = utils.do_bandpass_filter(x, Fs, params.band_pass_edo[1],
params.band_pass_edo[0])
# -------------------------------------------------------------------
# 2. envelope-derivated operator
# -------------------------------------------------------------------
N_start = len(x)
if (N_start % 2) != 0:
x = np.hstack((x, 0))
N = len(x)
Nh = np.ceil(N / 2).astype(int)
nl = np.arange(1, N - 1)
xx = np.zeros(N)
# calculate the Hilbert transform build the Hilbert transform in
# the frequency domain:
k = np.arange(N)
H = -1j * np.sign(Nh - k) * np.sign(k)
h = np.fft.ifft(np.fft.fft(x) * H)
h = np.real(h)
# implement with the central finite difference equation
xx[nl] = ((x[nl+1] ** 2) + (x[nl-1] ** 2) +
(h[nl+1] ** 2) + (h[nl-1] ** 2)) / 4 - ((x[nl+1] * x[nl-1] +
h[nl+1] * h[nl-1]) / 2)
# trim and zero-pad and the ends:
x_edo = np.pad(xx[2:(len(xx) - 2)], (2, 2),
'constant', constant_values=(0, 0))
x_edo = x_edo[0:N_start]
# ---------------------------------------------------------------------
# 3. smooth with window
# ---------------------------------------------------------------------
x_filt = utils.ma_filter(x_edo, Fs)
# zero pad the end:
L = len(x_filt)
x_edo[0:L] = x_filt
x_edo[L:-1] = 0
# ---------------------------------------------------------------------
# 4. downsample
# ---------------------------------------------------------------------
if Fs_orig:
x_edo = resample_poly(x_edo, Fs_orig, Fs)
# resampling may introduce very small negative values:
x_edo[x_edo < 0] = 0
if N_x != len(x_edo):
x_edo = x_edo[:N_x]
if DBplot:
plt.figure(1, clear=True)
plt.plot(x)
plt.plot(x_edo)
return(x_edo)
def feat_short_time_an(x, Fs, feat_type='envelope', **kwargs):
"""estimate median of envelope (using Hilbert transform) over a 2-second window
Parameters
----------
x: array_like
input signal
Fs: int
sampling frequency
feat_type: string
feature type, ('envelope', 'fd-higuchi', 'edo', 'if', 'psd_r2', 'spec-power')
freq_band: tuple (start, stop), default=(0.5, 3)
frequency band for feature
total_feat_band: tuple (start, stop), default=(0.5, 30)
total frequency band for feature
params: object, optional
dataclass object of parameters
DBplot: bool, optional
plot feature vs. signal
Returns
-------
t_stat : ndarray
feature vector generated from x (same dimension)
"""
default_args = {'freq_band': (0.5, 3),
'total_freq_band': (0.5, 30),
'params': None,
'DBplot': False}
arg_list = {**default_args, **kwargs}
# extract some arguments just for clarity:
f_band = arg_list['freq_band']
f_band_total = arg_list['total_freq_band']
params = arg_list['params']
DBcheck = False
if params is None:
params = bd_parameters.bdParams()
# -------------------------------------------------------------------
# set the epoch window parameters
# -------------------------------------------------------------------
idx = params.feature_set_final.index(feat_type)
epoch_p = utils.epoch_window(params.overlap, params.epoch_length[idx],
params.epoch_win_type[idx], Fs)
N = len(x)
N_epochs = np.floor(
(N - epoch_p['L_epoch']) / epoch_p['L_hop']).astype(int)
if N_epochs < 1:
N_epochs = 1
nw = np.arange(epoch_p['L_epoch'])
# -------------------------------------------------------------------
# different operations for different features
# (and anything else that should be defined outside of the
# short-time analysis)
# -------------------------------------------------------------------
if feat_type == 'envelope':
# -------------------------------------------------------------------
# envelope of the signal using the Hilbert transform
# -------------------------------------------------------------------
x = abs(hilbert(x))
elif feat_type == 'psd_r2':
# -------------------------------------------------------------------
# goodness-of-fit of line to log-log PSD
# -------------------------------------------------------------------
# define the frequency range and conver to log-scale
freq = np.linspace(0, Fs/2, params.N_freq)
irange = np.where((freq > f_band[0]) & (freq < f_band[1]))
freq_limit = freq[irange]
freq_db = 10 * np.log10(freq_limit)
if DBcheck:
print("frequencies between {0:g} and {1:g} Hz".format(
freq_limit[0], freq_limit[-1]))
elif feat_type == 'rel_spectral_power':
# -------------------------------------------------------------------
# relative spectral power
# -------------------------------------------------------------------
# define the frequency range (to keep the same as per Matlab code):
f_scale = params.N_freq / Fs
irange = np.arange(np.ceil(f_band[0] * f_scale).astype(int),
np.floor(f_band[1] * f_scale).astype(int) + 1)
irange_total = np.arange(np.ceil(f_band_total[0] * f_scale).astype(int),
np.floor(f_band_total[1] * f_scale).astype(int) + 1)
irange = irange - 1
irange_total = irange_total - 1
if DBcheck:
freq = np.linspace(
0, Fs/2, np.round(params.N_freq / 2).astype(int))
# irange = np.where((freq > f_band[0]) & (freq <= f_band[1]))
# irange_total = np.where(
# (freq > f_band_total[0]) & (freq <= f_band_total[1]))
freq_limit = freq[irange]
freq_limit_total = freq[irange_total]
print("frequencies between {0:g} and {1:g} Hz".format(
freq_limit[0], freq_limit[-1]))
print("Total frequencies between {0:g} and {1:g} Hz".format(
freq_limit_total[0], freq_limit_total[-1]))
print("i_BP =({0}, {1}); i_BP =({2}, {3});"
.format(irange[0], irange[-1],
irange_total[0], irange_total[-1]))
elif feat_type == 'if':
# -------------------------------------------------------------------
# instantaneous frequency estimate
# -------------------------------------------------------------------
# estimate instantaneous frequency (IF):
est_IF = estimate_IF(x, Fs)
# bind within frequency bands:
est_IF[est_IF > f_band[1]] = f_band[1]
est_IF[est_IF < f_band[0]] = f_band[0]
# normalized between 0 and 1 (need when combining features):
est_IF = (est_IF - f_band[0]) / (f_band[1] - f_band[0])
# invert:
x = 1 - est_IF
elif feat_type == 'fd_higuchi':
# -------------------------------------------------------------------
# Fractal Dimension estimate: band-pass filter from 0.5 to 30 Hz
# -------------------------------------------------------------------
x = utils.do_bandpass_filter(x, Fs, params.band_pass_fd[1],
params.band_pass_fd[0])
# -------------------------------------------------------------------
# iterate over all the epochs
# -------------------------------------------------------------------
z_all = np.zeros(N)
win_summed = np.zeros(N)
kshift = np.floor(epoch_p['L_epoch'] / (2 * epoch_p['L_hop'])).astype(int)
N_epochs_plus = N_epochs + kshift
# ev = np.zeros(N_epochs_plus)
for k in range(N_epochs):
nf = np.remainder(nw + (k * epoch_p['L_hop']), N)
x_epoch = x[nf] * epoch_p['win_epoch']
# -------------------------------------------------------------------
# different actions for different features:
# -------------------------------------------------------------------
if feat_type == 'envelope':
# median value over the epoch:
feat_x = np.median(x_epoch)
elif feat_type == 'psd_r2':
# generate the log-log spectrum and fit a line:
pxx = abs(np.fft.fft(x_epoch, params.N_freq))
pxx_db = 20 * np.log10(pxx[irange])
feat_x = ls_fit_params(freq_db, pxx_db, DBplot=False)
elif feat_type == 'rel_spectral_power':
# generate the log-log spectrum and fit a line:
pxx = abs(np.fft.fft(x_epoch, params.N_freq)) ** 2
feat_x = sum(pxx[irange]) / sum(pxx[irange_total])
elif feat_type == 'if':
feat_x = np.median(x_epoch)
elif feat_type == 'fd_higuchi':
feat_x = fd_hi(x_epoch, params.k_max)
feat_x = -feat_x
# upsample to EEG sampling rate:
z_all[nf] = z_all[nf] + (np.ones(epoch_p['L_epoch']) * feat_x)
win_summed[nf] = win_summed[nf] + np.ones(epoch_p['L_epoch'])
# remove the effect of the windowed approach:
win_summed[np.where(win_summed == 0)] = np.nan
t_stat = np.divide(z_all, win_summed)
if arg_list['DBplot']:
plt.figure(1, clear=True)
plt.plot(x)
plt.plot(t_stat)
return t_stat
def ls_fit_params(x, y, DBplot=False):
"""goodness of fit (r^2) for least-squares line fit
Parameters
----------
x: array_type
input vector of line
y: array_type
output vector of line
Returns
-------
r2 : scalar
fit of regression line
"""
# Setup matrices:
m = np.shape(x)[0]
X = np.matrix([np.ones(m), x]).T
Y = np.matrix(y).T
# Solve for projection matrix
params = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y)
# print(params)
# estimate goodness of fit:
y_fit = params[0] + params[1] * x
y_residuals = np.asarray(y - y_fit)
r2 = 1 - (((y_residuals ** 2).sum()) / (m * np.var(y)))
# Plot data, regression line
if DBplot:
# Find regression line
xx = np.linspace(min(x), max(x), 2)
yy = np.array(params[0] + params[1] * xx)
plt.figure(10, clear=True)
plt.plot(xx, yy.T, color='b')
plt.scatter(x, y, color='r')
plt.show()
return(r2)
def fit_line(x, y, DBplot=False):
"""least squares line fit
Parameters
----------
x: array_type
input vector of line
y: array_type
output vector of line
DBplot: bool, optional
plot feature vs. signal
Returns
-------
params : array_type
2 coefficients (c,m) from line fit
"""
# Setup matrices:
m = np.shape(x)[0]
X = np.matrix([np.ones(m), x]).T
Y = np.matrix(y).T
# Solve for projection matrix
params = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y)
# Plot data, regression line
if DBplot:
# Find regression line
xx = np.linspace(min(x), max(x), 2)
yy = np.array(params[0] + params[1] * xx)
plt.figure(10, clear=True)
plt.plot(xx, yy.T, color='b')
plt.scatter(x, y, color='r')
return(params)
def estimate_IF(x, Fs=1):
"""instantaneous frequency estimate from angle
of analytic signal
Parameters
----------
x: ndarray
input signal
Fs: scalar
sampling frequency
Returns
-------
if_a : ndarray
IF array
"""
if np.all(np.isreal(x)):
z = hilbert(x)
else:
z = x
N = len(z)
MF = 2 * np.pi
SCALE = Fs / (4 * np.pi)
if_a = np.zeros(N,)
n = np.arange(0, N - 2)
# central finite difference for IF:
z_diff = np.angle(z[n+2]) - np.angle(z[n])
if_a[n + 1] = np.mod(MF + z_diff, MF) * SCALE
return(if_a)
def fd_hi(x, kmax=[], DBplot=False):
"""fractal dimension estimate using the Higuchi approach [1]
[1] <NAME>, “Approach to an irregular time series on the basis of
the fractal theory,” Phys. D Nonlinear Phenom., vol. 31, pp. 277–283,
1988.
Parameters
----------
x: ndarray
input signal
kmax: scalar
maximum scale value (default = N/10)
DBplot: bool, optional
plot feature vs. signal
Returns
-------
fd : scalar
fractal dimension estimate
"""
N = len(x)
if not kmax:
kmax = math.floor(N / 10)
# what values of k to compute?
ik = 1
k_all = []
knew = 0
while knew < kmax:
if ik <= 4:
knew = ik
else:
knew = math.floor(2 ** ((ik + 5) / 4))
if knew <= kmax:
k_all.append(knew)
ik = ik + 1
# ---------------------------------------------------------------------
# curve length for each vector:
# ---------------------------------------------------------------------
L_avg = curve_lens(x, np.array(k_all).astype(int), N)
# -------------------------------------------------------------------
# form log-log plot of scale v. curve length
# -------------------------------------------------------------------
x1 = np.log2(k_all)
y1 = np.log2(L_avg)
c = fit_line(x1, y1, DBplot)
fd = -c[1, 0]
return(fd)
@jit(nopython=True, fastmath=False)
def curve_lens(x, k_all, N):
"""generate the different curve lengths at different scales
Parameters
----------
x: ndarray
time-domain signal
k_all: ndarray (int)
array of scale values
N: scalar
length of x
Returns
-------
L_avg : ndarray
curve length for different scale values
"""
inext = 0
L_avg = np.zeros(len(k_all), )
for k in k_all:
L = 0
for m in range(1, k + 1):
U_limit = math.floor((N - m) / k)
scale_factor = ((N - 1) / (U_limit * k)) / k
im = m - 1
L_tmp = 0
for ik in range(1, U_limit + 1):
ikk = im + ik * k
L_tmp += abs(x[ikk] - x[ikk - k])
L += L_tmp * scale_factor
L_avg[inext] = L / k
inext += 1
return(L_avg)
def gen_feature_set(x, Fs=None, params=None, DBplot=False):
"""generate feature set for signal x
Parameters
----------
x: ndarray
input signal
Fs: scalar
sampling frequency
params: object, optional
dataclass object of parameters
DBplot: bool, optional
plot feature vs. signal
Returns
-------
t_stat : ndarray
feature set
"""
if params is None:
params = bd_parameters.bdParams()
assert(Fs is not None), 'need to specify sampling frequency'
feat_set = params.feature_set_final
N = len(x)
# declare the empty feature matrix:
N_feats = len(feat_set)
t_stat = np.zeros((N_feats, N), dtype=float)
t_stat.fill(np.nan)
# for missing data, insert 0's when generating the features
inans = np.argwhere(np.isnan(x))
if inans.size > 0:
x[inans] = 0
#---------------------------------------------------------------------
# 1. do band-pass filtering first
#%---------------------------------------------------------------------
filter_bands=((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))
x_filt = {}
for n in range(len(filter_bands)):
# is this band needed?
match_fb = [p for p in range(len(params.feature_set_freqbands))
if params.feature_set_freqbands[p] == filter_bands[n]]
# print("for freq. band = {}; match={}".format(filter_bands[n], np.any(match_fb)))
if np.any(match_fb):
# print("from {} to {} Hz".format(params.freq_bands[n][1],params.freq_bands[n][0]))
x_f = utils.bandpass_butter_filt(x, Fs, params.freq_bands[n][1],
params.freq_bands[n][0], params.L_filt)
x_filt[filter_bands[n]] = x_f
total_freq_bands = (params.freq_bands[0][0], params.freq_bands[-1][-1])
# -------------------------------------------------------------------
# do for all features
# -------------------------------------------------------------------
for n in range(N_feats):
# find filter band:
if params.feature_set_freqbands[n] in x_filt.keys():
y = x_filt[params.feature_set_freqbands[n]]
freq_band = params.freq_bands[params.feature_set_freqbands[n].index(1)]
else:
y = x
freq_band = None
# special case for RSP:
if feat_set[n] == 'rel_spectral_power':
y = x
if feat_set[n] in ['envelope', 'psd_r2', 'if', 'rel_spectral_power', 'fd_higuchi']:
# -------------------------------------------------------------------
# short-time analysis for these features
# -------------------------------------------------------------------
t_stat[n, :] = feat_short_time_an(y, Fs, feat_type=feat_set[n],
freq_band=freq_band,
total_freq_band=total_freq_bands,
params=params)
elif feat_set[n] == 'edo':
# -------------------------------------------------------------------
# special case for the envelope-derivative operater as is
# calculate on the whole signal
# -------------------------------------------------------------------
t_stat[n, :] = edo_feat(y, Fs, params=params)
else:
raise ValueError('feature _ ' + feat_set[n] + ' _ not implemented')
# -------------------------------------------------------------------
# log transform any of the variables
# -------------------------------------------------------------------
if feat_set[n] in params.log_feats:
t_stat[n, :] = np.log( t_stat[n, :] + np.spacing(1))
# -------------------------------------------------------------------
# re-fill the NaNs
# -------------------------------------------------------------------
if inans.size > 0:
t_stat[:, inans] = np.nan
# -------------------------------------------------------------------
# plot
# -------------------------------------------------------------------
if DBplot:
plt.figure(1, clear=True)
for p in range(N_feats):
plt.plot(np.arange(N) / Fs, t_stat[p, :], label=feat_set[p])
plt.legend()
return(t_stat)
| [
"numpy.log10",
"numpy.hstack",
"scipy.signal.resample_poly",
"math.floor",
"numpy.array",
"numpy.isreal",
"numpy.mod",
"numpy.divide",
"numpy.arange",
"numpy.where",
"matplotlib.pyplot.plot",
"numpy.asarray",
"burst_detector.bd_parameters.bdParams",
"numpy.fft.fft",
"numpy.real",
"nump... | [((14975, 15009), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'fastmath': '(False)'}), '(nopython=True, fastmath=False)\n', (14978, 15009), False, 'from numba import jit\n'), ((1493, 1579), 'burst_detector.utils.do_bandpass_filter', 'utils.do_bandpass_filter', (['x', 'Fs', 'params.band_pass_edo[1]', 'params.band_pass_edo[0]'], {}), '(x, Fs, params.band_pass_edo[1], params.\n band_pass_edo[0])\n', (1517, 1579), False, 'from burst_detector import utils, bd_parameters\n'), ((1934, 1953), 'numpy.arange', 'np.arange', (['(1)', '(N - 1)'], {}), '(1, N - 1)\n', (1943, 1953), True, 'import numpy as np\n'), ((1963, 1974), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (1971, 1974), True, 'import numpy as np\n'), ((2081, 2093), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (2090, 2093), True, 'import numpy as np\n'), ((2184, 2194), 'numpy.real', 'np.real', (['h'], {}), '(h)\n', (2191, 2194), True, 'import numpy as np\n'), ((2825, 2851), 'burst_detector.utils.ma_filter', 'utils.ma_filter', (['x_edo', 'Fs'], {}), '(x_edo, Fs)\n', (2840, 2851), False, 'from burst_detector import utils, bd_parameters\n'), ((4944, 5041), 'burst_detector.utils.epoch_window', 'utils.epoch_window', (['params.overlap', 'params.epoch_length[idx]', 'params.epoch_win_type[idx]', 'Fs'], {}), '(params.overlap, params.epoch_length[idx], params.\n epoch_win_type[idx], Fs)\n', (4962, 5041), False, 'from burst_detector import utils, bd_parameters\n'), ((5227, 5256), 'numpy.arange', 'np.arange', (["epoch_p['L_epoch']"], {}), "(epoch_p['L_epoch'])\n", (5236, 5256), True, 'import numpy as np\n'), ((9222, 9233), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (9230, 9233), True, 'import numpy as np\n'), ((9251, 9262), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (9259, 9262), True, 'import numpy as np\n'), ((10876, 10904), 'numpy.divide', 'np.divide', (['z_all', 'win_summed'], {}), '(z_all, win_summed)\n', (10885, 10904), True, 'import numpy as np\n'), ((11638, 11659), 'numpy.asarray', 'np.asarray', (['(y - y_fit)'], {}), '(y - y_fit)\n', (11648, 11659), True, 'import numpy as np\n'), ((13327, 13338), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (13335, 13338), True, 'import numpy as np\n'), ((13348, 13367), 'numpy.arange', 'np.arange', (['(0)', '(N - 2)'], {}), '(0, N - 2)\n', (13357, 13367), True, 'import numpy as np\n'), ((14865, 14879), 'numpy.log2', 'np.log2', (['k_all'], {}), '(k_all)\n', (14872, 14879), True, 'import numpy as np\n'), ((14889, 14903), 'numpy.log2', 'np.log2', (['L_avg'], {}), '(L_avg)\n', (14896, 14903), True, 'import numpy as np\n'), ((16561, 16596), 'numpy.zeros', 'np.zeros', (['(N_feats, N)'], {'dtype': 'float'}), '((N_feats, N), dtype=float)\n', (16569, 16596), True, 'import numpy as np\n'), ((1083, 1107), 'burst_detector.bd_parameters.bdParams', 'bd_parameters.bdParams', ([], {}), '()\n', (1105, 1107), False, 'from burst_detector import utils, bd_parameters\n'), ((1187, 1222), 'scipy.signal.resample_poly', 'resample_poly', (['x', 'params.Fs_edo', 'Fs'], {}), '(x, params.Fs_edo, Fs)\n', (1200, 1222), False, 'from scipy.signal import hilbert, resample_poly\n'), ((1855, 1872), 'numpy.hstack', 'np.hstack', (['(x, 0)'], {}), '((x, 0))\n', (1864, 1872), True, 'import numpy as np\n'), ((2126, 2136), 'numpy.sign', 'np.sign', (['k'], {}), '(k)\n', (2133, 2136), True, 'import numpy as np\n'), ((3147, 3180), 'scipy.signal.resample_poly', 'resample_poly', (['x_edo', 'Fs_orig', 'Fs'], {}), '(x_edo, Fs_orig, Fs)\n', (3160, 3180), False, 'from scipy.signal import hilbert, resample_poly\n'), ((3352, 3377), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'clear': '(True)'}), '(1, clear=True)\n', (3362, 3377), True, 'from matplotlib import pyplot as plt\n'), ((3386, 3397), 'matplotlib.pyplot.plot', 'plt.plot', (['x'], {}), '(x)\n', (3394, 3397), True, 'from matplotlib import pyplot as plt\n'), ((3406, 3421), 'matplotlib.pyplot.plot', 'plt.plot', (['x_edo'], {}), '(x_edo)\n', (3414, 3421), True, 'from matplotlib import pyplot as plt\n'), ((4665, 4689), 'burst_detector.bd_parameters.bdParams', 'bd_parameters.bdParams', ([], {}), '()\n', (4687, 4689), False, 'from burst_detector import utils, bd_parameters\n'), ((9460, 9502), 'numpy.remainder', 'np.remainder', (["(nw + k * epoch_p['L_hop'])", 'N'], {}), "(nw + k * epoch_p['L_hop'], N)\n", (9472, 9502), True, 'import numpy as np\n'), ((10827, 10852), 'numpy.where', 'np.where', (['(win_summed == 0)'], {}), '(win_summed == 0)\n', (10835, 10852), True, 'import numpy as np\n'), ((10941, 10966), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'clear': '(True)'}), '(1, clear=True)\n', (10951, 10966), True, 'from matplotlib import pyplot as plt\n'), ((10975, 10986), 'matplotlib.pyplot.plot', 'plt.plot', (['x'], {}), '(x)\n', (10983, 10986), True, 'from matplotlib import pyplot as plt\n'), ((10995, 11011), 'matplotlib.pyplot.plot', 'plt.plot', (['t_stat'], {}), '(t_stat)\n', (11003, 11011), True, 'from matplotlib import pyplot as plt\n'), ((11364, 11375), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (11372, 11375), True, 'import numpy as np\n'), ((11424, 11436), 'numpy.matrix', 'np.matrix', (['y'], {}), '(y)\n', (11433, 11436), True, 'import numpy as np\n'), ((11857, 11893), 'numpy.array', 'np.array', (['(params[0] + params[1] * xx)'], {}), '(params[0] + params[1] * xx)\n', (11865, 11893), True, 'import numpy as np\n'), ((11903, 11929), 'matplotlib.pyplot.figure', 'plt.figure', (['(10)'], {'clear': '(True)'}), '(10, clear=True)\n', (11913, 11929), True, 'from matplotlib import pyplot as plt\n'), ((11938, 11967), 'matplotlib.pyplot.plot', 'plt.plot', (['xx', 'yy.T'], {'color': '"""b"""'}), "(xx, yy.T, color='b')\n", (11946, 11967), True, 'from matplotlib import pyplot as plt\n'), ((11976, 12004), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'color': '"""r"""'}), "(x, y, color='r')\n", (11987, 12004), True, 'from matplotlib import pyplot as plt\n'), ((12013, 12023), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12021, 12023), True, 'from matplotlib import pyplot as plt\n'), ((12421, 12432), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (12429, 12432), True, 'import numpy as np\n'), ((12481, 12493), 'numpy.matrix', 'np.matrix', (['y'], {}), '(y)\n', (12490, 12493), True, 'import numpy as np\n'), ((12723, 12759), 'numpy.array', 'np.array', (['(params[0] + params[1] * xx)'], {}), '(params[0] + params[1] * xx)\n', (12731, 12759), True, 'import numpy as np\n'), ((12769, 12795), 'matplotlib.pyplot.figure', 'plt.figure', (['(10)'], {'clear': '(True)'}), '(10, clear=True)\n', (12779, 12795), True, 'from matplotlib import pyplot as plt\n'), ((12804, 12833), 'matplotlib.pyplot.plot', 'plt.plot', (['xx', 'yy.T'], {'color': '"""b"""'}), "(xx, yy.T, color='b')\n", (12812, 12833), True, 'from matplotlib import pyplot as plt\n'), ((12842, 12870), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'color': '"""r"""'}), "(x, y, color='r')\n", (12853, 12870), True, 'from matplotlib import pyplot as plt\n'), ((13189, 13201), 'numpy.isreal', 'np.isreal', (['x'], {}), '(x)\n', (13198, 13201), True, 'import numpy as np\n'), ((13216, 13226), 'scipy.signal.hilbert', 'hilbert', (['x'], {}), '(x)\n', (13223, 13226), False, 'from scipy.signal import hilbert, resample_poly\n'), ((13422, 13440), 'numpy.angle', 'np.angle', (['z[n + 2]'], {}), '(z[n + 2])\n', (13430, 13440), True, 'import numpy as np\n'), ((13441, 13455), 'numpy.angle', 'np.angle', (['z[n]'], {}), '(z[n])\n', (13449, 13455), True, 'import numpy as np\n'), ((13474, 13497), 'numpy.mod', 'np.mod', (['(MF + z_diff)', 'MF'], {}), '(MF + z_diff, MF)\n', (13480, 13497), True, 'import numpy as np\n'), ((14105, 14123), 'math.floor', 'math.floor', (['(N / 10)'], {}), '(N / 10)\n', (14115, 14123), False, 'import math\n'), ((16325, 16349), 'burst_detector.bd_parameters.bdParams', 'bd_parameters.bdParams', ([], {}), '()\n', (16347, 16349), False, 'from burst_detector import utils, bd_parameters\n'), ((16710, 16721), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (16718, 16721), True, 'import numpy as np\n'), ((17369, 17385), 'numpy.any', 'np.any', (['match_fb'], {}), '(match_fb)\n', (17375, 17385), True, 'import numpy as np\n'), ((20187, 20212), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'clear': '(True)'}), '(1, clear=True)\n', (20197, 20212), True, 'from matplotlib import pyplot as plt\n'), ((20327, 20339), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20337, 20339), True, 'from matplotlib import pyplot as plt\n'), ((1898, 1912), 'numpy.ceil', 'np.ceil', (['(N / 2)'], {}), '(N / 2)\n', (1905, 1912), True, 'import numpy as np\n'), ((2108, 2123), 'numpy.sign', 'np.sign', (['(Nh - k)'], {}), '(Nh - k)\n', (2115, 2123), True, 'import numpy as np\n'), ((2157, 2170), 'numpy.fft.fft', 'np.fft.fft', (['x'], {}), '(x)\n', (2167, 2170), True, 'import numpy as np\n'), ((5101, 5154), 'numpy.floor', 'np.floor', (["((N - epoch_p['L_epoch']) / epoch_p['L_hop'])"], {}), "((N - epoch_p['L_epoch']) / epoch_p['L_hop'])\n", (5109, 5154), True, 'import numpy as np\n'), ((5816, 5826), 'scipy.signal.hilbert', 'hilbert', (['x'], {}), '(x)\n', (5823, 5826), False, 'from scipy.signal import hilbert, resample_poly\n'), ((6144, 6181), 'numpy.linspace', 'np.linspace', (['(0)', '(Fs / 2)', 'params.N_freq'], {}), '(0, Fs / 2, params.N_freq)\n', (6155, 6181), True, 'import numpy as np\n'), ((6197, 6246), 'numpy.where', 'np.where', (['((freq > f_band[0]) & (freq < f_band[1]))'], {}), '((freq > f_band[0]) & (freq < f_band[1]))\n', (6205, 6246), True, 'import numpy as np\n'), ((9276, 9329), 'numpy.floor', 'np.floor', (["(epoch_p['L_epoch'] / (2 * epoch_p['L_hop']))"], {}), "(epoch_p['L_epoch'] / (2 * epoch_p['L_hop']))\n", (9284, 9329), True, 'import numpy as np\n'), ((9862, 9880), 'numpy.median', 'np.median', (['x_epoch'], {}), '(x_epoch)\n', (9871, 9880), True, 'import numpy as np\n'), ((10733, 10760), 'numpy.ones', 'np.ones', (["epoch_p['L_epoch']"], {}), "(epoch_p['L_epoch'])\n", (10740, 10760), True, 'import numpy as np\n'), ((14297, 14328), 'math.floor', 'math.floor', (['(2 ** ((ik + 5) / 4))'], {}), '(2 ** ((ik + 5) / 4))\n', (14307, 14328), False, 'import math\n'), ((15507, 15530), 'math.floor', 'math.floor', (['((N - m) / k)'], {}), '((N - m) / k)\n', (15517, 15530), False, 'import math\n'), ((17501, 17604), 'burst_detector.utils.bandpass_butter_filt', 'utils.bandpass_butter_filt', (['x', 'Fs', 'params.freq_bands[n][1]', 'params.freq_bands[n][0]', 'params.L_filt'], {}), '(x, Fs, params.freq_bands[n][1], params.\n freq_bands[n][0], params.L_filt)\n', (17527, 17604), False, 'from burst_detector import utils, bd_parameters\n'), ((6304, 6324), 'numpy.log10', 'np.log10', (['freq_limit'], {}), '(freq_limit)\n', (6312, 6324), True, 'import numpy as np\n'), ((10653, 10680), 'numpy.ones', 'np.ones', (["epoch_p['L_epoch']"], {}), "(epoch_p['L_epoch'])\n", (10660, 10680), True, 'import numpy as np\n'), ((11398, 11408), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (11405, 11408), True, 'import numpy as np\n'), ((11708, 11717), 'numpy.var', 'np.var', (['y'], {}), '(y)\n', (11714, 11717), True, 'import numpy as np\n'), ((12455, 12465), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (12462, 12465), True, 'import numpy as np\n'), ((14621, 14636), 'numpy.array', 'np.array', (['k_all'], {}), '(k_all)\n', (14629, 14636), True, 'import numpy as np\n'), ((10000, 10034), 'numpy.fft.fft', 'np.fft.fft', (['x_epoch', 'params.N_freq'], {}), '(x_epoch, params.N_freq)\n', (10010, 10034), True, 'import numpy as np\n'), ((10062, 10083), 'numpy.log10', 'np.log10', (['pxx[irange]'], {}), '(pxx[irange])\n', (10070, 10083), True, 'import numpy as np\n'), ((19758, 19771), 'numpy.spacing', 'np.spacing', (['(1)'], {}), '(1)\n', (19768, 19771), True, 'import numpy as np\n'), ((20267, 20279), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (20276, 20279), True, 'import numpy as np\n'), ((8900, 8979), 'burst_detector.utils.do_bandpass_filter', 'utils.do_bandpass_filter', (['x', 'Fs', 'params.band_pass_fd[1]', 'params.band_pass_fd[0]'], {}), '(x, Fs, params.band_pass_fd[1], params.band_pass_fd[0])\n', (8924, 8979), False, 'from burst_detector import utils, bd_parameters\n'), ((10439, 10457), 'numpy.median', 'np.median', (['x_epoch'], {}), '(x_epoch)\n', (10448, 10457), True, 'import numpy as np\n'), ((6837, 6865), 'numpy.ceil', 'np.ceil', (['(f_band[0] * f_scale)'], {}), '(f_band[0] * f_scale)\n', (6844, 6865), True, 'import numpy as np\n'), ((6986, 7020), 'numpy.ceil', 'np.ceil', (['(f_band_total[0] * f_scale)'], {}), '(f_band_total[0] * f_scale)\n', (6993, 7020), True, 'import numpy as np\n'), ((10281, 10315), 'numpy.fft.fft', 'np.fft.fft', (['x_epoch', 'params.N_freq'], {}), '(x_epoch, params.N_freq)\n', (10291, 10315), True, 'import numpy as np\n'), ((6906, 6935), 'numpy.floor', 'np.floor', (['(f_band[1] * f_scale)'], {}), '(f_band[1] * f_scale)\n', (6914, 6935), True, 'import numpy as np\n'), ((7067, 7102), 'numpy.floor', 'np.floor', (['(f_band_total[1] * f_scale)'], {}), '(f_band_total[1] * f_scale)\n', (7075, 7102), True, 'import numpy as np\n'), ((7266, 7293), 'numpy.round', 'np.round', (['(params.N_freq / 2)'], {}), '(params.N_freq / 2)\n', (7274, 7293), True, 'import numpy as np\n')] |
import os
import sys
import pickle
import argparse
import numpy as np
sys.path.append(os.getcwd())
from solnml.bandits.second_layer_bandit import SecondLayerBandit
from solnml.components.utils.constants import MULTICLASS_CLS, BINARY_CLS, REGRESSION, CLS_TASKS
from solnml.datasets.utils import load_train_test_data
from solnml.components.metrics.metric import get_metric
from solnml.components.evaluators.base_evaluator import fetch_predict_estimator
parser = argparse.ArgumentParser()
parser.add_argument('--start_id', type=int, default=0)
parser.add_argument('--rep', type=int, default=3)
parser.add_argument('--datasets', type=str, default='diabetes')
parser.add_argument('--metrics', type=str, default='all')
parser.add_argument('--task', type=str, choices=['reg', 'cls'], default='cls')
parser.add_argument('--algo', type=str, default='all')
parser.add_argument('--r', type=int, default=20)
args = parser.parse_args()
datasets = args.datasets.split(',')
start_id, rep = args.start_id, args.rep
total_resource = args.r
save_dir = './data/meta_res/'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
cls_metrics = ['acc', 'f1', 'auc']
reg_metrics = ['mse', 'r2', 'mae']
def evaluate_ml_algorithm(dataset, algo, run_id, obj_metric, total_resource=20, seed=1, task_type=None):
print('EVALUATE-%s-%s-%s: run_id=%d' % (dataset, algo, obj_metric, run_id))
train_data, test_data = load_train_test_data(dataset, task_type=task_type)
if task_type in CLS_TASKS:
task_type = BINARY_CLS if len(set(train_data.data[1])) == 2 else MULTICLASS_CLS
print(set(train_data.data[1]))
metric = get_metric(obj_metric)
bandit = SecondLayerBandit(task_type, algo, train_data, metric, per_run_time_limit=300,
seed=seed, eval_type='holdout',
fe_algo='bo',
total_resource=total_resource)
bandit.optimize_fixed_pipeline()
val_score = bandit.incumbent_perf
best_config = bandit.inc['hpo']
fe_optimizer = bandit.optimizer['fe']
fe_optimizer.fetch_nodes(10)
best_data_node = fe_optimizer.fetch_incumbent
test_data_node = fe_optimizer.apply(test_data, best_data_node)
estimator = fetch_predict_estimator(task_type, best_config, best_data_node.data[0],
best_data_node.data[1],
weight_balance=best_data_node.enable_balance,
data_balance=best_data_node.data_balance)
score = metric(estimator, test_data_node.data[0], test_data_node.data[1]) * metric._sign
print('Test score', score)
save_path = save_dir + '%s-%s-%s-%d-%d.pkl' % (dataset, algo, obj_metric, run_id, total_resource)
with open(save_path, 'wb') as f:
pickle.dump([dataset, algo, score, val_score, task_type], f)
def check_datasets(datasets, task_type=None):
for _dataset in datasets:
try:
_, _ = load_train_test_data(_dataset, random_state=1, task_type=task_type)
except Exception as e:
raise ValueError('Dataset - %s does not exist!' % _dataset)
if __name__ == "__main__":
algorithms = ['lightgbm', 'random_forest',
'libsvm_svc', 'extra_trees',
'liblinear_svc', 'k_nearest_neighbors',
'logistic_regression',
'gradient_boosting', 'adaboost']
task_type = MULTICLASS_CLS
if args.task == 'reg':
task_type = REGRESSION
algorithms = ['lightgbm', 'random_forest',
'libsvm_svr', 'extra_trees',
'liblinear_svr', 'k_nearest_neighbors',
'lasso_regression',
'gradient_boosting', 'adaboost']
if args.algo != 'all':
algorithms = args.algo.split(',')
metrics = cls_metrics if args.task == 'cls' else reg_metrics
if args.metrics != 'all':
metrics = args.metrics.split(',')
check_datasets(datasets, task_type=task_type)
running_info = list()
log_filename = 'running-%d.txt' % os.getpid()
for dataset in datasets:
for obj_metric in metrics:
np.random.seed(1)
seeds = np.random.randint(low=1, high=10000, size=start_id + rep)
for algo in algorithms:
for run_id in range(start_id, start_id + rep):
seed = seeds[run_id]
try:
task_id = '%s-%s-%s-%d: %s' % (dataset, algo, obj_metric, run_id, 'success')
evaluate_ml_algorithm(dataset, algo, run_id, obj_metric, total_resource=total_resource,
seed=seed, task_type=task_type)
except Exception as e:
task_id = '%s-%s-%s-%d: %s' % (dataset, algo, obj_metric, run_id, str(e))
print(task_id)
running_info.append(task_id)
with open(save_dir + log_filename, 'a') as f:
f.write('\n' + task_id)
# Write down the error info.
with open(save_dir + 'failed-%s' % log_filename, 'w') as f:
f.write('\n'.join(running_info))
| [
"os.path.exists",
"pickle.dump",
"os.makedirs",
"argparse.ArgumentParser",
"solnml.datasets.utils.load_train_test_data",
"os.getcwd",
"solnml.bandits.second_layer_bandit.SecondLayerBandit",
"numpy.random.randint",
"numpy.random.seed",
"solnml.components.evaluators.base_evaluator.fetch_predict_esti... | [((462, 487), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (485, 487), False, 'import argparse\n'), ((87, 98), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (96, 98), False, 'import os\n'), ((1063, 1087), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (1077, 1087), False, 'import os\n'), ((1093, 1114), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n', (1104, 1114), False, 'import os\n'), ((1400, 1450), 'solnml.datasets.utils.load_train_test_data', 'load_train_test_data', (['dataset'], {'task_type': 'task_type'}), '(dataset, task_type=task_type)\n', (1420, 1450), False, 'from solnml.datasets.utils import load_train_test_data\n'), ((1618, 1640), 'solnml.components.metrics.metric.get_metric', 'get_metric', (['obj_metric'], {}), '(obj_metric)\n', (1628, 1640), False, 'from solnml.components.metrics.metric import get_metric\n'), ((1654, 1819), 'solnml.bandits.second_layer_bandit.SecondLayerBandit', 'SecondLayerBandit', (['task_type', 'algo', 'train_data', 'metric'], {'per_run_time_limit': '(300)', 'seed': 'seed', 'eval_type': '"""holdout"""', 'fe_algo': '"""bo"""', 'total_resource': 'total_resource'}), "(task_type, algo, train_data, metric, per_run_time_limit=\n 300, seed=seed, eval_type='holdout', fe_algo='bo', total_resource=\n total_resource)\n", (1671, 1819), False, 'from solnml.bandits.second_layer_bandit import SecondLayerBandit\n'), ((2225, 2416), 'solnml.components.evaluators.base_evaluator.fetch_predict_estimator', 'fetch_predict_estimator', (['task_type', 'best_config', 'best_data_node.data[0]', 'best_data_node.data[1]'], {'weight_balance': 'best_data_node.enable_balance', 'data_balance': 'best_data_node.data_balance'}), '(task_type, best_config, best_data_node.data[0],\n best_data_node.data[1], weight_balance=best_data_node.enable_balance,\n data_balance=best_data_node.data_balance)\n', (2248, 2416), False, 'from solnml.components.evaluators.base_evaluator import fetch_predict_estimator\n'), ((2801, 2861), 'pickle.dump', 'pickle.dump', (['[dataset, algo, score, val_score, task_type]', 'f'], {}), '([dataset, algo, score, val_score, task_type], f)\n', (2812, 2861), False, 'import pickle\n'), ((4089, 4100), 'os.getpid', 'os.getpid', ([], {}), '()\n', (4098, 4100), False, 'import os\n'), ((2972, 3039), 'solnml.datasets.utils.load_train_test_data', 'load_train_test_data', (['_dataset'], {'random_state': '(1)', 'task_type': 'task_type'}), '(_dataset, random_state=1, task_type=task_type)\n', (2992, 3039), False, 'from solnml.datasets.utils import load_train_test_data\n'), ((4178, 4195), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (4192, 4195), True, 'import numpy as np\n'), ((4216, 4273), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(10000)', 'size': '(start_id + rep)'}), '(low=1, high=10000, size=start_id + rep)\n', (4233, 4273), True, 'import numpy as np\n')] |
import numpy as np
def solve_power(self, LUT, Rs):
"""Solve EEC to achieve given input / output power with respect to voltage and current constraints
Parameters
----------
self : ElecLUTdq
a ElecLUTdq object
LUT : LUTdq
Calculated look-up table
Rs: float
Stator phase resistance [Ohm]
Returns
----------
out_dict: dict
Dict containing all output quantities
"""
# Get output, machine and OP
output = self.parent.parent
machine = output.simu.machine
OP = output.elec.OP
# Maximum voltage
Urms_max = self.Urms_max
# Maximum current
Irms_max = self.Irms_max
# Electrical frequency
felec = OP.get_felec()
# Electrical pulsation
ws = 2 * np.pi * felec
# Stator winding number of phases
qs = machine.stator.winding.qs
# Check if there is a loss model
is_loss_model = LUT.simu.loss is not None
# iteration until convergence is reached, and max number of iterations on EEC
delta_Pem = 1e10
delta_Pem_max = 0.1
Nmax = 20
niter_Pem = 1
Id_min = self.Id_min
Id_max = self.Id_max
Iq_min = self.Iq_min
Iq_max = self.Iq_max
Nd = (
self.n_Id
if self.n_Id == 1
else int(self.n_Id * self.n_interp / (self.n_Id + self.n_Iq))
)
Nq = (
self.n_Iq
if self.n_Iq == 1
else int(self.n_Iq * self.n_interp / (self.n_Id + self.n_Iq))
)
while abs(delta_Pem) > delta_Pem_max and niter_Pem < Nmax:
# Refine Id/Iq mesh
Id_vect = np.linspace(Id_min, Id_max, Nd)
Iq_vect = np.linspace(Iq_min, Iq_max, Nq)
Id, Iq = np.meshgrid(Id_vect, Iq_vect)
Id, Iq = Id.ravel(), Iq.ravel()
# Calculate maximum current
Imax_interp = np.sqrt(Id ** 2 + Iq ** 2)
# Interpolate Phid/Phiq on the refined mesh
(Phid, Phiq, Phih) = LUT.interp_Phi_dqh(Id, Iq)
# Calculate voltage (Ud/Uq) for the refined mesh
Ud = Rs * Id - Phiq * ws
Uq = Rs * Iq + Phid * ws
Umax_interp = np.sqrt(Ud ** 2 + Uq ** 2)
if is_loss_model:
# Interpolate losses from LUT:
# - 1st column : Joule losses
# - 2nd column : stator core losses
# - 3rd column : magnet losses
# - 4th column : rotor core losses
# - 5th column : proximity losses
Ploss_dqh = LUT.interp_Ploss_dqh(Id, Iq, N0=OP.N0)
Ploss_ovl = np.sum(Ploss_dqh, axis=1)
else:
# Only consider stator Joule losses
Ploss_ovl = qs * Rs * (Id ** 2 + Iq ** 2)
if is_loss_model:
# The input power must cover electrical power + additional losses
P_in = qs * (Ud * Id + Uq * Iq) + np.sum(Ploss_dqh[:, 1:], axis=1)
else:
# The input power must cover electrical power + Joule losses
P_in = qs * (Ud * Id + Uq * Iq)
# The output power is the input power minus all losses
P_out = P_in - Ploss_ovl
# Set input/ouput power condition
if OP.Pem_av_in is None:
P_cond = P_out >= OP.Pem_av_ref
else:
P_cond = P_in >= OP.Pem_av_in
# Set maximum voltage condition
U_cond = Umax_interp <= Urms_max
# Set maximum current condition
I_cond = Imax_interp <= Irms_max
# Finding indices of operating points satisfying voltage, current and power conditions
i0 = np.logical_and.reduce((U_cond, I_cond, P_cond))
if np.any(i0):
# Finding index of operating point with lowest losses among feasible operating points
imin = np.argmin(Ploss_ovl[i0])
# Get error between calculated and requested powers
if OP.Pem_av_in is None:
delta_Pem = P_out[i0][imin] - OP.Pem_av_ref
else:
delta_Pem = P_in[i0][imin] - OP.Pem_av_in
if abs(delta_Pem) > delta_Pem_max:
# Zoom in Id / Iq grid to achieve better accuracy on output values
jd = np.where(Id_vect == Id[i0][imin])[0][0]
jq = np.where(Iq_vect == Iq[i0][imin])[0][0]
jd_min = max([jd - 1, 0])
jd_max = min([jd + 1, Nd - 1])
jq_min = max([jq - 1, 0])
jq_max = min([jq + 1, Nq - 1])
Id_min = Id_vect[jd_min]
Id_max = Id_vect[jd_max]
Iq_min = Iq_vect[jq_min]
Iq_max = Iq_vect[jq_max]
niter_Pem = niter_Pem + 1
else:
# Find strategy to get closest to requested power although violating voltage / current constraints
i1 = np.logical_and(P_cond, U_cond)
i2 = np.logical_and(P_cond, I_cond)
if np.any(i1):
# Only consider requested power and voltage constraint
i0 = i1
elif np.any(i2):
# Only consider requested power and current constraint
i0 = i2
else:
# Only consider requested power
i0 = P_cond
if np.any(i0):
# Find indices of operating points that reaches power
if OP.Pem_av_in is None:
P_min = np.min(P_out[i0])
P_cond = P_out == P_min
else:
P_min = np.min(P_in[i0])
P_cond = P_out == P_min
if np.where(P_cond)[0].size == 1:
# Take the only point that reaches requested power
imin = 0
else:
# Take the operating point that minimizes voltage
imin = np.argmin(Umax_interp[i0])
# Get error between calculated and requested powers
if OP.Pem_av_in is None:
delta_Pem = P_out[i0][imin] - OP.Pem_av_ref
else:
delta_Pem = P_in[i0][imin] - OP.Pem_av_in
if abs(delta_Pem) > delta_Pem_max:
# Zoom in Id / Iq grid to achieve better accuracy on output values
jd = np.where(Id_vect == Id[i0][imin])[0][0]
jq = np.where(Iq_vect == Iq[i0][imin])[0][0]
jd_min = max([jd - 1, 0])
jd_max = min([jd + 1, Nd - 1])
jq_min = max([jq - 1, 0])
jq_max = min([jq + 1, Nq - 1])
Id_min = Id_vect[jd_min]
Id_max = Id_vect[jd_max]
Iq_min = Iq_vect[jq_min]
Iq_max = Iq_vect[jq_max]
niter_Pem = niter_Pem + 1
else:
# Find operating point that get closest to requested power
if OP.Pem_av_in is None:
P_max = np.max(P_out)
i0 = P_out == P_max
else:
P_max = np.max(P_in)
i0 = P_out == P_max
if np.where(i0)[0].size == 1:
# Take the closest point to requested power
imin = 0
else:
# Take the operating point that minimizes voltage
imin = np.argmin(Umax_interp[i0])
# Stop loop
delta_Pem = delta_Pem_max
# Launch warnings
if OP.Pem_av_in is None and P_out[i0][imin] < OP.Pem_av_ref:
self.get_logger().warning(
"Output power cannot be reached within current and voltage constraints, taking maximum feasible power"
)
elif OP.Pem_av_in is not None and P_in[i0][imin] < OP.Pem_av_in:
self.get_logger().warning(
"Input power cannot be reached within current and voltage constraints, taking maximum feasible power"
)
if Umax_interp[i0][imin] > Urms_max:
self.get_logger().warning("Voltage constraint cannot be reached")
if Imax_interp[i0][imin] > Irms_max:
self.get_logger().warning("Current constraint cannot be reached")
out_dict = dict()
out_dict["P_in"] = P_in[i0][imin]
out_dict["P_out"] = P_out[i0][imin]
out_dict["efficiency"] = out_dict["P_out"] / out_dict["P_in"]
if output.simu.input.is_generator:
# Calculate torque from input power
out_dict["Tem_av"] = out_dict["P_in"] / (2 * np.pi * OP.N0 / 60)
else:
# Calculate torque from output power
out_dict["Tem_av"] = out_dict["P_out"] / (2 * np.pi * OP.N0 / 60)
# Store voltage and currents
out_dict["Id"] = Id[i0][imin]
out_dict["Iq"] = Iq[i0][imin]
out_dict["Ud"] = Ud[i0][imin]
out_dict["Uq"] = Uq[i0][imin]
# Store dq fluxes
out_dict["Phid"] = Phid[i0][imin]
out_dict["Phiq"] = Phiq[i0][imin]
# Calculate flux linkage and back-emf
Phidqh_mag = LUT.get_Phi_dqh_mag_mean()
out_dict["Phid_mag"] = Phidqh_mag[0]
out_dict["Phiq_mag"] = Phidqh_mag[1]
out_dict["Erms"] = ws * Phidqh_mag[0]
if is_loss_model:
# Store losses
out_dict["Pjoule"] = Ploss_dqh[i0, 0][imin]
out_dict["Pstator"] = Ploss_dqh[i0, 1][imin]
out_dict["Pmagnet"] = Ploss_dqh[i0, 2][imin]
out_dict["Protor"] = Ploss_dqh[i0, 3][imin]
out_dict["Pprox"] = Ploss_dqh[i0, 4][imin]
else:
out_dict["Pjoule"] = Ploss_ovl[i0][imin]
# Calculate inductances
if Id[i0][imin] != 0:
out_dict["Ld"] = (Phid[i0][imin] - out_dict["Phid_mag"]) / Id[i0][imin]
if Iq[i0][imin] != 0:
out_dict["Lq"] = Phiq[i0][imin] / Iq[i0][imin]
# Calculate torque ripple
Tem_rip_pp = LUT.interp_Tem_rip_dqh(Id[i0][imin], Iq[i0][imin])
if Tem_rip_pp is not None:
out_dict["Tem_rip_pp"] = float(Tem_rip_pp)
if out_dict["Tem_av"] == 0:
out_dict["Tem_rip_norm"] = 0
else:
out_dict["Tem_rip_norm"] = np.abs(Tem_rip_pp / out_dict["Tem_av"])
return out_dict
| [
"numpy.abs",
"numpy.sqrt",
"numpy.logical_and",
"numpy.where",
"numpy.any",
"numpy.max",
"numpy.sum",
"numpy.linspace",
"numpy.logical_and.reduce",
"numpy.min",
"numpy.argmin",
"numpy.meshgrid"
] | [((1563, 1594), 'numpy.linspace', 'np.linspace', (['Id_min', 'Id_max', 'Nd'], {}), '(Id_min, Id_max, Nd)\n', (1574, 1594), True, 'import numpy as np\n'), ((1613, 1644), 'numpy.linspace', 'np.linspace', (['Iq_min', 'Iq_max', 'Nq'], {}), '(Iq_min, Iq_max, Nq)\n', (1624, 1644), True, 'import numpy as np\n'), ((1662, 1691), 'numpy.meshgrid', 'np.meshgrid', (['Id_vect', 'Iq_vect'], {}), '(Id_vect, Iq_vect)\n', (1673, 1691), True, 'import numpy as np\n'), ((1791, 1817), 'numpy.sqrt', 'np.sqrt', (['(Id ** 2 + Iq ** 2)'], {}), '(Id ** 2 + Iq ** 2)\n', (1798, 1817), True, 'import numpy as np\n'), ((2073, 2099), 'numpy.sqrt', 'np.sqrt', (['(Ud ** 2 + Uq ** 2)'], {}), '(Ud ** 2 + Uq ** 2)\n', (2080, 2099), True, 'import numpy as np\n'), ((3486, 3533), 'numpy.logical_and.reduce', 'np.logical_and.reduce', (['(U_cond, I_cond, P_cond)'], {}), '((U_cond, I_cond, P_cond))\n', (3507, 3533), True, 'import numpy as np\n'), ((3546, 3556), 'numpy.any', 'np.any', (['i0'], {}), '(i0)\n', (3552, 3556), True, 'import numpy as np\n'), ((2483, 2508), 'numpy.sum', 'np.sum', (['Ploss_dqh'], {'axis': '(1)'}), '(Ploss_dqh, axis=1)\n', (2489, 2508), True, 'import numpy as np\n'), ((3675, 3699), 'numpy.argmin', 'np.argmin', (['Ploss_ovl[i0]'], {}), '(Ploss_ovl[i0])\n', (3684, 3699), True, 'import numpy as np\n'), ((4717, 4747), 'numpy.logical_and', 'np.logical_and', (['P_cond', 'U_cond'], {}), '(P_cond, U_cond)\n', (4731, 4747), True, 'import numpy as np\n'), ((4765, 4795), 'numpy.logical_and', 'np.logical_and', (['P_cond', 'I_cond'], {}), '(P_cond, I_cond)\n', (4779, 4795), True, 'import numpy as np\n'), ((4812, 4822), 'numpy.any', 'np.any', (['i1'], {}), '(i1)\n', (4818, 4822), True, 'import numpy as np\n'), ((5153, 5163), 'numpy.any', 'np.any', (['i0'], {}), '(i0)\n', (5159, 5163), True, 'import numpy as np\n'), ((9931, 9970), 'numpy.abs', 'np.abs', (["(Tem_rip_pp / out_dict['Tem_av'])"], {}), "(Tem_rip_pp / out_dict['Tem_av'])\n", (9937, 9970), True, 'import numpy as np\n'), ((2776, 2808), 'numpy.sum', 'np.sum', (['Ploss_dqh[:, 1:]'], {'axis': '(1)'}), '(Ploss_dqh[:, 1:], axis=1)\n', (2782, 2808), True, 'import numpy as np\n'), ((4936, 4946), 'numpy.any', 'np.any', (['i2'], {}), '(i2)\n', (4942, 4946), True, 'import numpy as np\n'), ((5304, 5321), 'numpy.min', 'np.min', (['P_out[i0]'], {}), '(P_out[i0])\n', (5310, 5321), True, 'import numpy as np\n'), ((5416, 5432), 'numpy.min', 'np.min', (['P_in[i0]'], {}), '(P_in[i0])\n', (5422, 5432), True, 'import numpy as np\n'), ((5747, 5773), 'numpy.argmin', 'np.argmin', (['Umax_interp[i0]'], {}), '(Umax_interp[i0])\n', (5756, 5773), True, 'import numpy as np\n'), ((6883, 6896), 'numpy.max', 'np.max', (['P_out'], {}), '(P_out)\n', (6889, 6896), True, 'import numpy as np\n'), ((6987, 6999), 'numpy.max', 'np.max', (['P_in'], {}), '(P_in)\n', (6993, 6999), True, 'import numpy as np\n'), ((7299, 7325), 'numpy.argmin', 'np.argmin', (['Umax_interp[i0]'], {}), '(Umax_interp[i0])\n', (7308, 7325), True, 'import numpy as np\n'), ((4090, 4123), 'numpy.where', 'np.where', (['(Id_vect == Id[i0][imin])'], {}), '(Id_vect == Id[i0][imin])\n', (4098, 4123), True, 'import numpy as np\n'), ((4151, 4184), 'numpy.where', 'np.where', (['(Iq_vect == Iq[i0][imin])'], {}), '(Iq_vect == Iq[i0][imin])\n', (4159, 4184), True, 'import numpy as np\n'), ((5497, 5513), 'numpy.where', 'np.where', (['P_cond'], {}), '(P_cond)\n', (5505, 5513), True, 'import numpy as np\n'), ((6196, 6229), 'numpy.where', 'np.where', (['(Id_vect == Id[i0][imin])'], {}), '(Id_vect == Id[i0][imin])\n', (6204, 6229), True, 'import numpy as np\n'), ((6261, 6294), 'numpy.where', 'np.where', (['(Iq_vect == Iq[i0][imin])'], {}), '(Iq_vect == Iq[i0][imin])\n', (6269, 6294), True, 'import numpy as np\n'), ((7060, 7072), 'numpy.where', 'np.where', (['i0'], {}), '(i0)\n', (7068, 7072), True, 'import numpy as np\n')] |
# loosely based on https://medium.com/vacatronics/3-ways-to-calibrate-your-camera-using-opencv-and-python-395528a51615
import sys
from copy import deepcopy
import cv2
import numpy as np
import json
import time
from taggridscanner.aux.config import store_config, set_calibration
from taggridscanner.aux.threading import WorkerThreadWithResult, ThreadSafeContainer
from taggridscanner.aux.utils import Functor
from taggridscanner.pipeline.generate_calibration_pattern import (
GenerateCalibrationPattern,
)
from taggridscanner.pipeline.retrieve_image import RetrieveImage
from taggridscanner.pipeline.view_image import ViewImage
class CalibrateWorker(Functor):
def __init__(self, args):
super().__init__()
config_with_defaults = args["config-with-defaults"]
self.retrieve_image = RetrieveImage.create_from_config(config_with_defaults)
self.checkerboard = (args["rows"], args["cols"])
self.error_tolerance = args["tolerance"]
# stop the iteration when specified
# accuracy, epsilon, is reached or
# specified number of iterations are completed.
self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Vector for 3D points
self.threedpoints = []
# Vector for 2D points
self.twodpoints = []
# 3D points real world coordinates
self.objectp3d = np.zeros(
(1, self.checkerboard[0] * self.checkerboard[1], 3), np.float32
)
self.objectp3d[0, :, :2] = np.mgrid[
0 : self.checkerboard[0], 0 : self.checkerboard[1]
].T.reshape(-1, 2)
self.good_frame_ts = time.perf_counter()
self.last_error = float("inf")
def __call__(self):
frame = self.retrieve_image()
grayColor = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(
grayColor,
self.checkerboard,
cv2.CALIB_CB_ADAPTIVE_THRESH
+ cv2.CALIB_CB_FAST_CHECK
+ cv2.CALIB_CB_NORMALIZE_IMAGE,
)
# If desired number of corners can be detected then,
# refine the pixel coordinates and display
# them on the images of checker board
if ret:
# Refining pixel coordinates
# for given 2d points.
corners2 = cv2.cornerSubPix(
grayColor, corners, (11, 11), (-1, -1), self.criteria
)
# Draw and display the corners
frame = cv2.drawChessboardCorners(frame, self.checkerboard, corners2, ret)
error, *_ = cv2.calibrateCamera(
[self.objectp3d], [corners2], grayColor.shape[::-1], None, None
)
print("{} (tolerance: {})".format(error, self.error_tolerance))
ts = time.perf_counter()
if ts - self.good_frame_ts > 2 and error < self.error_tolerance:
# keep checkerboard coordinates
self.good_frame_ts = ts
self.threedpoints.append(self.objectp3d)
self.twodpoints.append(corners2)
print(
"{} frames captured for calibration (error: {})".format(
len(self.twodpoints), error
)
)
return (
frame,
deepcopy(self.threedpoints),
deepcopy(self.twodpoints),
)
def calibrate(args):
num_frames = args["n"]
generate_calibration_pattern = GenerateCalibrationPattern(
img_shape=(args["height"], args["width"]),
pattern_shape=(args["rows"], args["cols"]),
)
if not args["no_pattern"]:
view_pattern = ViewImage("calibration patter")
(generate_calibration_pattern | view_pattern)()
cv2.pollKey()
view_calibration = ViewImage("image to calibrate")
calibrate_worker = CalibrateWorker(args)
producer = WorkerThreadWithResult(calibrate_worker)
producer.start()
producer.result.wait()
view_calibration(
np.zeros((1, 1), dtype=np.uint8)
) # use dummy image, just to have a window for waitKey()
while True:
try:
(frame, threedpoints, twodpoints) = producer.result.get_nowait()
view_calibration(frame)
if len(twodpoints) >= num_frames:
producer.stop()
break
except ThreadSafeContainer.Empty:
pass
key = cv2.waitKey(1000 // 120)
if key == 27: # ESC
print("Aborting.", file=sys.stderr)
sys.exit(1)
(h, w, *_) = frame.shape
ret, camera_matrix, [distortion], r_vecs, t_vecs = cv2.calibrateCamera(
threedpoints, twodpoints, (w, h), None, None
)
res_matrix = np.array([[1 / w, 0, 0], [0, 1 / h, 0], [0, 0, 1]])
rel_camera_matrix = np.matmul(res_matrix, camera_matrix)
# Display required output
print(" Camera matrix:")
print(json.dumps(rel_camera_matrix.tolist()))
print("\n Distortion coefficient:")
print(json.dumps(distortion.tolist()))
undistorted = cv2.undistort(frame, camera_matrix, distortion, None, None)
view_calibration.title = "calibration result"
view_calibration(undistorted)
config_path = args["config-path"]
print(
"Press ENTER to save calibration profile to config file: {}".format(config_path)
)
print("Press any other key to abort.")
key = cv2.waitKey()
cv2.destroyAllWindows()
if key == 13: # <ENTER>
print("Saving calibration profile to: {}".format(config_path))
modified_raw_config = set_calibration(
args["raw-config"], rel_camera_matrix, distortion
)
store_config(modified_raw_config, config_path)
else:
print("Aborting.")
| [
"taggridscanner.aux.config.set_calibration",
"taggridscanner.pipeline.view_image.ViewImage",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.calibrateCamera",
"cv2.findChessboardCorners",
"cv2.pollKey",
"copy.deepcopy",
"cv2.cornerSubPix",
"sys.exit",
"cv2.undistort",
"time.perf_counter",
"tagg... | [((3522, 3639), 'taggridscanner.pipeline.generate_calibration_pattern.GenerateCalibrationPattern', 'GenerateCalibrationPattern', ([], {'img_shape': "(args['height'], args['width'])", 'pattern_shape': "(args['rows'], args['cols'])"}), "(img_shape=(args['height'], args['width']),\n pattern_shape=(args['rows'], args['cols']))\n", (3548, 3639), False, 'from taggridscanner.pipeline.generate_calibration_pattern import GenerateCalibrationPattern\n'), ((3848, 3879), 'taggridscanner.pipeline.view_image.ViewImage', 'ViewImage', (['"""image to calibrate"""'], {}), "('image to calibrate')\n", (3857, 3879), False, 'from taggridscanner.pipeline.view_image import ViewImage\n'), ((3941, 3981), 'taggridscanner.aux.threading.WorkerThreadWithResult', 'WorkerThreadWithResult', (['calibrate_worker'], {}), '(calibrate_worker)\n', (3963, 3981), False, 'from taggridscanner.aux.threading import WorkerThreadWithResult, ThreadSafeContainer\n'), ((4682, 4747), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['threedpoints', 'twodpoints', '(w, h)', 'None', 'None'], {}), '(threedpoints, twodpoints, (w, h), None, None)\n', (4701, 4747), False, 'import cv2\n'), ((4780, 4831), 'numpy.array', 'np.array', (['[[1 / w, 0, 0], [0, 1 / h, 0], [0, 0, 1]]'], {}), '([[1 / w, 0, 0], [0, 1 / h, 0], [0, 0, 1]])\n', (4788, 4831), True, 'import numpy as np\n'), ((4856, 4892), 'numpy.matmul', 'np.matmul', (['res_matrix', 'camera_matrix'], {}), '(res_matrix, camera_matrix)\n', (4865, 4892), True, 'import numpy as np\n'), ((5106, 5165), 'cv2.undistort', 'cv2.undistort', (['frame', 'camera_matrix', 'distortion', 'None', 'None'], {}), '(frame, camera_matrix, distortion, None, None)\n', (5119, 5165), False, 'import cv2\n'), ((5448, 5461), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (5459, 5461), False, 'import cv2\n'), ((5467, 5490), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5488, 5490), False, 'import cv2\n'), ((815, 869), 'taggridscanner.pipeline.retrieve_image.RetrieveImage.create_from_config', 'RetrieveImage.create_from_config', (['config_with_defaults'], {}), '(config_with_defaults)\n', (847, 869), False, 'from taggridscanner.pipeline.retrieve_image import RetrieveImage\n'), ((1404, 1477), 'numpy.zeros', 'np.zeros', (['(1, self.checkerboard[0] * self.checkerboard[1], 3)', 'np.float32'], {}), '((1, self.checkerboard[0] * self.checkerboard[1], 3), np.float32)\n', (1412, 1477), True, 'import numpy as np\n'), ((1665, 1684), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1682, 1684), False, 'import time\n'), ((1808, 1847), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1820, 1847), False, 'import cv2\n'), ((1872, 2024), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['grayColor', 'self.checkerboard', '(cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.\n CALIB_CB_NORMALIZE_IMAGE)'], {}), '(grayColor, self.checkerboard, cv2.\n CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.\n CALIB_CB_NORMALIZE_IMAGE)\n', (1897, 2024), False, 'import cv2\n'), ((3714, 3745), 'taggridscanner.pipeline.view_image.ViewImage', 'ViewImage', (['"""calibration patter"""'], {}), "('calibration patter')\n", (3723, 3745), False, 'from taggridscanner.pipeline.view_image import ViewImage\n'), ((3810, 3823), 'cv2.pollKey', 'cv2.pollKey', ([], {}), '()\n', (3821, 3823), False, 'import cv2\n'), ((4061, 4093), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {'dtype': 'np.uint8'}), '((1, 1), dtype=np.uint8)\n', (4069, 4093), True, 'import numpy as np\n'), ((4471, 4495), 'cv2.waitKey', 'cv2.waitKey', (['(1000 // 120)'], {}), '(1000 // 120)\n', (4482, 4495), False, 'import cv2\n'), ((5622, 5688), 'taggridscanner.aux.config.set_calibration', 'set_calibration', (["args['raw-config']", 'rel_camera_matrix', 'distortion'], {}), "(args['raw-config'], rel_camera_matrix, distortion)\n", (5637, 5688), False, 'from taggridscanner.aux.config import store_config, set_calibration\n'), ((5719, 5765), 'taggridscanner.aux.config.store_config', 'store_config', (['modified_raw_config', 'config_path'], {}), '(modified_raw_config, config_path)\n', (5731, 5765), False, 'from taggridscanner.aux.config import store_config, set_calibration\n'), ((2360, 2431), 'cv2.cornerSubPix', 'cv2.cornerSubPix', (['grayColor', 'corners', '(11, 11)', '(-1, -1)', 'self.criteria'], {}), '(grayColor, corners, (11, 11), (-1, -1), self.criteria)\n', (2376, 2431), False, 'import cv2\n'), ((2526, 2592), 'cv2.drawChessboardCorners', 'cv2.drawChessboardCorners', (['frame', 'self.checkerboard', 'corners2', 'ret'], {}), '(frame, self.checkerboard, corners2, ret)\n', (2551, 2592), False, 'import cv2\n'), ((2618, 2706), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['[self.objectp3d]', '[corners2]', 'grayColor.shape[::-1]', 'None', 'None'], {}), '([self.objectp3d], [corners2], grayColor.shape[::-1],\n None, None)\n', (2637, 2706), False, 'import cv2\n'), ((2828, 2847), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2845, 2847), False, 'import time\n'), ((3359, 3386), 'copy.deepcopy', 'deepcopy', (['self.threedpoints'], {}), '(self.threedpoints)\n', (3367, 3386), False, 'from copy import deepcopy\n'), ((3400, 3425), 'copy.deepcopy', 'deepcopy', (['self.twodpoints'], {}), '(self.twodpoints)\n', (3408, 3425), False, 'from copy import deepcopy\n'), ((4585, 4596), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4593, 4596), False, 'import sys\n')] |
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib.pyplot as plt
from set_style import set_style
set_style('default', w=1, h=3.5)
fig, [ax1, ax2, ax3, ax4, ax5] = plt.subplots(5,1)
data = np.load('../data/figure3.npz')
t = data['t']
phi_msn = data['phi_msn']
phi_mdn = data['phi_mdn']
phi_msg = data['phi_msg']
phi_mdg = data['phi_mdg']
Na_se = data['cNa_se']
K_se = data['cK_se']
Cl_se = data['cCl_se']
Ca_se = data['cCa_se']
Na_de = data['cNa_de']
K_de = data['cK_de']
Cl_de = data['cCl_de']
Ca_de = data['cCa_de']
V_sn = data['V_sn']
V_se = data['V_se']
V_sg = data['V_sg']
V_dn = data['V_dn']
V_de = data['V_de']
V_dg = data['V_dg']
### Panel A ###
l01 = ax1.plot(t, phi_msn*1000, 'k', label='neuron')[0]
l02 = ax1.plot(t, phi_msg*1000, '#9467bd', label='glia')[0]
ax1.set_ylabel('$\phi\mathrm{_{ms}}$ [mV]')
ax1.set_yticks([-70, 0])
fig.legend([l01, l02], ['neuron', 'glia'], \
loc=(0.65,0.88), ncol=1, fontsize='small', handlelength=0.8, handletextpad=0.4)
### Panel B ###
l001 = ax2.plot(t, phi_msn*1000, 'k')[0]
l002 = ax2.plot(t, phi_mdn*1000, 'k:')[0]
l003 = ax2.plot(t, phi_msg*1000, '#9467bd')[0]
l004 = ax2.plot(t, phi_mdg*1000, '#9467bd', ls=':')[0]
ax2.set_ylabel('$\phi\mathrm{_{m}}$ [mV]')
ax2.set_yticks([-70, 0])
ax2.set_xticks([0.99, 1.0, 1.02, 1.04, 1.06,1.08])
ax2.set_xlim(0.99,1.08)
fig.legend([l001, l002, l003, l004], ['neuronal soma', 'neuronal dendrite', 'glial soma', 'glial dendrite'], \
loc=(0.65,0.69), ncol=1, fontsize='small', handlelength=0.8, handletextpad=0.4)
#### Panel C ###
l1 = ax3.plot(t, Na_se-Na_se[0], zorder=10)[0]
l2 = ax3.plot(t, K_se-K_se[0], zorder=10)[0]
l3 = ax3.plot(t, Cl_se-Cl_se[0], zorder=10)[0]
l4 = ax3.plot(t, Ca_se-Ca_se[0], zorder=10)[0]
ax3.set_ylabel('$\Delta \mathrm{[k]_{se}}$ [mM]')
fig.legend([l1, l2, l3, l4], ['$\mathrm{Na^+}$', '$\mathrm{K^+}$', '$\mathrm{Cl^-}$', '$\mathrm{Ca^{2+}}$'], \
loc=(0.65,0.54), ncol=2, fontsize='small', handlelength=0.8, handletextpad=0.4, columnspacing=0.4)
ax3.set_ylim(-0.62,0.7)
### Panel D ###
ax4.plot(t, Na_de-Na_de[0], zorder=10)
ax4.plot(t, K_de-K_de[0], zorder=10)
ax4.plot(t, Cl_de-Cl_de[0], zorder=10)
ax4.plot(t, Ca_de-Ca_de[0], zorder=10)
ax4.set_ylabel('$\Delta \mathrm{[k]_{de}}$ [mM]')
ax4.set_ylim(-0.62,0.7)
### Panel E ###
ax5.plot(t, ((V_sn+V_dn)-(V_sn[0]+V_dn[0]))/(V_sn[0]+V_dn[0])*100, 'k', label='neuron')
ax5.plot(t, ((V_se+V_de)-(V_se[0]+V_de[0]))/(V_se[0]+V_de[0])*100, 'k:', label='ECS')
ax5.plot(t, ((V_sg+V_dg)-(V_sg[0]+V_dg[0]))/(V_sg[0]+V_dg[0])*100, 'k--', label='glia')
ax5.set_ylabel('$\Delta V$ [\%]')
ax5.legend(fontsize='small', handlelength=0.8, handletextpad=0.4, loc='lower right', labelspacing=0.01)
ax5.set_yticks([-1.5, -1, 0, 1])
for ax in [ax1, ax3, ax4, ax5]:
ax.set_xlim(0,1400)
for ax in [ax1, ax2, ax3, ax4, ax5]:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax5.set_xlabel('time [s]')
# ABC
panel = np.array(['A', 'B', 'C', 'D', 'E'])
i = 0
for ax in [ax1, ax2, ax3, ax4, ax5]:
ax.text(-0.05, 1.2, panel[i], transform=ax.transAxes, fontsize=12, fontweight='bold', va='top', ha='right')
i += 1
plt.tight_layout()
plt.savefig('figure3.pdf', dpi=600)
| [
"warnings.filterwarnings",
"matplotlib.pyplot.savefig",
"numpy.array",
"matplotlib.pyplot.tight_layout",
"numpy.load",
"matplotlib.pyplot.subplots",
"set_style.set_style"
] | [((16, 49), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (39, 49), False, 'import warnings\n'), ((134, 166), 'set_style.set_style', 'set_style', (['"""default"""'], {'w': '(1)', 'h': '(3.5)'}), "('default', w=1, h=3.5)\n", (143, 166), False, 'from set_style import set_style\n'), ((201, 219), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(1)'], {}), '(5, 1)\n', (213, 219), True, 'import matplotlib.pyplot as plt\n'), ((227, 257), 'numpy.load', 'np.load', (['"""../data/figure3.npz"""'], {}), "('../data/figure3.npz')\n", (234, 257), True, 'import numpy as np\n'), ((2956, 2991), 'numpy.array', 'np.array', (["['A', 'B', 'C', 'D', 'E']"], {}), "(['A', 'B', 'C', 'D', 'E'])\n", (2964, 2991), True, 'import numpy as np\n'), ((3159, 3177), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3175, 3177), True, 'import matplotlib.pyplot as plt\n'), ((3178, 3213), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""figure3.pdf"""'], {'dpi': '(600)'}), "('figure3.pdf', dpi=600)\n", (3189, 3213), True, 'import matplotlib.pyplot as plt\n')] |
import numpy as np
import tensorflow as tf
import hetu as ht
def test_embedding(executor_ctx=ht.gpu(0)):
embedding = ht.Variable('embeddingtable', value=np.random.rand(5, 5))
index = ht.Variable(name="index")
ids = [[0, 1], [0, 1]]
ids = np.array(ids)
ids = ht.array(ids, ctx=executor_ctx)
y = ht.embedding_lookup_op(embedding, index)
opt = ht.optim.SGDOptimizer(0.1)
train_op = opt.minimize(y)
executor = ht.Executor([y, train_op], ctx=executor_ctx)
print("embedding:",
executor.config.placeholder_to_arr_map[embedding].asnumpy())
print("ids:", ids.asnumpy())
out, _ = executor.run(feed_dict={index: ids})
print(out.asnumpy())
print(executor.config.placeholder_to_arr_map[embedding].asnumpy())
def test_embedding_with_tf(opt_name, iters=10000, executor_ctx=ht.gpu(0)):
from time import time
value = np.random.rand(5, 5)
ids = [[0, 1], [0, 1]]
ids = np.array(ids)
# tf part
tf_embedding = tf.Variable(value, dtype=tf.float32)
tf_ids = tf.placeholder(tf.int32)
tf_y = tf.nn.embedding_lookup(tf_embedding, tf_ids)
tf_opts = {
'sgd': tf.train.GradientDescentOptimizer(0.1),
'momentum': tf.train.MomentumOptimizer(0.1, momentum=0.9),
'nesterov': tf.train.MomentumOptimizer(0.1, momentum=0.9, use_nesterov=True),
'adagrad': tf.train.AdagradOptimizer(0.1, initial_accumulator_value=1e-7, use_locking=True),
'adam': tf.train.AdamOptimizer(0.1, epsilon=1e-7, use_locking=True),
}
tf_opt = tf_opts[opt_name]
tf_trainop = tf_opt.minimize(tf_y)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
start = time()
for i in range(iters):
tf_out, _ = sess.run([tf_y, tf_trainop], feed_dict={tf_ids: ids})
end = time()
print('tensorflow time using: ', end - start)
tf_new_embedding = sess.run([tf_embedding])[0]
print(tf_out)
print(tf_new_embedding)
print()
# hetu part
embedding = ht.Variable('embeddingtable', value=value)
index = ht.Variable(name="index")
ids = ht.array(ids, ctx=executor_ctx)
y = ht.embedding_lookup_op(embedding, index)
hetu_opts = {
'sgd': ht.optim.SGDOptimizer(0.1),
'momentum': ht.optim.MomentumOptimizer(0.1),
'nesterov': ht.optim.MomentumOptimizer(0.1, nesterov=True),
'adagrad': ht.optim.AdaGradOptimizer(0.1),
'adam': ht.optim.AdamOptimizer(0.1),
}
opt = hetu_opts[opt_name]
train_op = opt.minimize(y)
executor = ht.Executor([y, train_op], ctx=executor_ctx)
start = time()
for i in range(iters):
out, _ = executor.run(feed_dict={index: ids})
end = time()
print('hetu time using: ', end - start)
out = out.asnumpy()
new_embedding = executor.config.placeholder_to_arr_map[embedding].asnumpy()
print(out)
print(new_embedding)
np.testing.assert_allclose(out, tf_out, rtol=1e-5)
np.testing.assert_allclose(new_embedding, tf_new_embedding, rtol=1e-5)
test_embedding()
test_embedding(ht.cpu(0))
test_embedding_with_tf(opt_name='sgd')
test_embedding_with_tf(opt_name='sgd', executor_ctx=ht.cpu(0))
test_embedding_with_tf(opt_name='momentum')
test_embedding_with_tf(opt_name='nesterov', iters=1000)
test_embedding_with_tf(opt_name='adagrad')
test_embedding_with_tf(opt_name='adam')
| [
"numpy.random.rand",
"hetu.optim.AdamOptimizer",
"numpy.array",
"tensorflow.nn.embedding_lookup",
"tensorflow.Session",
"tensorflow.placeholder",
"numpy.testing.assert_allclose",
"hetu.Executor",
"tensorflow.train.AdamOptimizer",
"hetu.optim.MomentumOptimizer",
"hetu.Variable",
"tensorflow.Var... | [((95, 104), 'hetu.gpu', 'ht.gpu', (['(0)'], {}), '(0)\n', (101, 104), True, 'import hetu as ht\n'), ((193, 218), 'hetu.Variable', 'ht.Variable', ([], {'name': '"""index"""'}), "(name='index')\n", (204, 218), True, 'import hetu as ht\n'), ((256, 269), 'numpy.array', 'np.array', (['ids'], {}), '(ids)\n', (264, 269), True, 'import numpy as np\n'), ((280, 311), 'hetu.array', 'ht.array', (['ids'], {'ctx': 'executor_ctx'}), '(ids, ctx=executor_ctx)\n', (288, 311), True, 'import hetu as ht\n'), ((320, 360), 'hetu.embedding_lookup_op', 'ht.embedding_lookup_op', (['embedding', 'index'], {}), '(embedding, index)\n', (342, 360), True, 'import hetu as ht\n'), ((371, 397), 'hetu.optim.SGDOptimizer', 'ht.optim.SGDOptimizer', (['(0.1)'], {}), '(0.1)\n', (392, 397), True, 'import hetu as ht\n'), ((444, 488), 'hetu.Executor', 'ht.Executor', (['[y, train_op]'], {'ctx': 'executor_ctx'}), '([y, train_op], ctx=executor_ctx)\n', (455, 488), True, 'import hetu as ht\n'), ((829, 838), 'hetu.gpu', 'ht.gpu', (['(0)'], {}), '(0)\n', (835, 838), True, 'import hetu as ht\n'), ((880, 900), 'numpy.random.rand', 'np.random.rand', (['(5)', '(5)'], {}), '(5, 5)\n', (894, 900), True, 'import numpy as np\n'), ((938, 951), 'numpy.array', 'np.array', (['ids'], {}), '(ids)\n', (946, 951), True, 'import numpy as np\n'), ((986, 1022), 'tensorflow.Variable', 'tf.Variable', (['value'], {'dtype': 'tf.float32'}), '(value, dtype=tf.float32)\n', (997, 1022), True, 'import tensorflow as tf\n'), ((1036, 1060), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), '(tf.int32)\n', (1050, 1060), True, 'import tensorflow as tf\n'), ((1072, 1116), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['tf_embedding', 'tf_ids'], {}), '(tf_embedding, tf_ids)\n', (1094, 1116), True, 'import tensorflow as tf\n'), ((2042, 2084), 'hetu.Variable', 'ht.Variable', (['"""embeddingtable"""'], {'value': 'value'}), "('embeddingtable', value=value)\n", (2053, 2084), True, 'import hetu as ht\n'), ((2097, 2122), 'hetu.Variable', 'ht.Variable', ([], {'name': '"""index"""'}), "(name='index')\n", (2108, 2122), True, 'import hetu as ht\n'), ((2134, 2165), 'hetu.array', 'ht.array', (['ids'], {'ctx': 'executor_ctx'}), '(ids, ctx=executor_ctx)\n', (2142, 2165), True, 'import hetu as ht\n'), ((2174, 2214), 'hetu.embedding_lookup_op', 'ht.embedding_lookup_op', (['embedding', 'index'], {}), '(embedding, index)\n', (2196, 2214), True, 'import hetu as ht\n'), ((2576, 2620), 'hetu.Executor', 'ht.Executor', (['[y, train_op]'], {'ctx': 'executor_ctx'}), '([y, train_op], ctx=executor_ctx)\n', (2587, 2620), True, 'import hetu as ht\n'), ((2634, 2640), 'time.time', 'time', ([], {}), '()\n', (2638, 2640), False, 'from time import time\n'), ((2732, 2738), 'time.time', 'time', ([], {}), '()\n', (2736, 2738), False, 'from time import time\n'), ((2932, 2983), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['out', 'tf_out'], {'rtol': '(1e-05)'}), '(out, tf_out, rtol=1e-05)\n', (2958, 2983), True, 'import numpy as np\n'), ((2987, 3058), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['new_embedding', 'tf_new_embedding'], {'rtol': '(1e-05)'}), '(new_embedding, tf_new_embedding, rtol=1e-05)\n', (3013, 3058), True, 'import numpy as np\n'), ((3092, 3101), 'hetu.cpu', 'ht.cpu', (['(0)'], {}), '(0)\n', (3098, 3101), True, 'import hetu as ht\n'), ((1148, 1186), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['(0.1)'], {}), '(0.1)\n', (1181, 1186), True, 'import tensorflow as tf\n'), ((1208, 1253), 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['(0.1)'], {'momentum': '(0.9)'}), '(0.1, momentum=0.9)\n', (1234, 1253), True, 'import tensorflow as tf\n'), ((1275, 1339), 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['(0.1)'], {'momentum': '(0.9)', 'use_nesterov': '(True)'}), '(0.1, momentum=0.9, use_nesterov=True)\n', (1301, 1339), True, 'import tensorflow as tf\n'), ((1360, 1446), 'tensorflow.train.AdagradOptimizer', 'tf.train.AdagradOptimizer', (['(0.1)'], {'initial_accumulator_value': '(1e-07)', 'use_locking': '(True)'}), '(0.1, initial_accumulator_value=1e-07, use_locking\n =True)\n', (1385, 1446), True, 'import tensorflow as tf\n'), ((1458, 1518), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['(0.1)'], {'epsilon': '(1e-07)', 'use_locking': '(True)'}), '(0.1, epsilon=1e-07, use_locking=True)\n', (1480, 1518), True, 'import tensorflow as tf\n'), ((1606, 1618), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1616, 1618), True, 'import tensorflow as tf\n'), ((1696, 1702), 'time.time', 'time', ([], {}), '()\n', (1700, 1702), False, 'from time import time\n'), ((1826, 1832), 'time.time', 'time', ([], {}), '()\n', (1830, 1832), False, 'from time import time\n'), ((2248, 2274), 'hetu.optim.SGDOptimizer', 'ht.optim.SGDOptimizer', (['(0.1)'], {}), '(0.1)\n', (2269, 2274), True, 'import hetu as ht\n'), ((2296, 2327), 'hetu.optim.MomentumOptimizer', 'ht.optim.MomentumOptimizer', (['(0.1)'], {}), '(0.1)\n', (2322, 2327), True, 'import hetu as ht\n'), ((2349, 2395), 'hetu.optim.MomentumOptimizer', 'ht.optim.MomentumOptimizer', (['(0.1)'], {'nesterov': '(True)'}), '(0.1, nesterov=True)\n', (2375, 2395), True, 'import hetu as ht\n'), ((2416, 2446), 'hetu.optim.AdaGradOptimizer', 'ht.optim.AdaGradOptimizer', (['(0.1)'], {}), '(0.1)\n', (2441, 2446), True, 'import hetu as ht\n'), ((2464, 2491), 'hetu.optim.AdamOptimizer', 'ht.optim.AdamOptimizer', (['(0.1)'], {}), '(0.1)\n', (2486, 2491), True, 'import hetu as ht\n'), ((3194, 3203), 'hetu.cpu', 'ht.cpu', (['(0)'], {}), '(0)\n', (3200, 3203), True, 'import hetu as ht\n'), ((159, 179), 'numpy.random.rand', 'np.random.rand', (['(5)', '(5)'], {}), '(5, 5)\n', (173, 179), True, 'import numpy as np\n'), ((1645, 1678), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1676, 1678), True, 'import tensorflow as tf\n')] |
import warnings
import csv
import collections
from functools import reduce
import itertools
import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
import sklearn
import pmdarima as pm
import arch
from arch.__future__ import reindexing
from sklearn.decomposition import PCA
from sklearn_extra.cluster import KMedoids
import static.param_estimator as param_estimator
import static.objective_functions as objective_functions
import static.efficient_frontier as efficient_frontier
import psycopg2.extensions
psycopg2.extensions.register_adapter(np.int64, psycopg2._psycopg.AsIs)
warnings.filterwarnings("ignore")
conn = psycopg2.connect(
host='database-1.csuf8nkuxrw3.us-east-2.rds.amazonaws.com',
port=5432,
user='postgres',
password='<PASSWORD>',
database='can2_etfs'
)
conn.autocommit = True
cursor = conn.cursor()
pd.options.mode.chained_assignment = None # default='warn'
def historical_avg(returns, freq, trade_horizon=12):
mu = returns.agg(lambda data: reduce(lambda x, y: x*y, [x+1 for x in data])**(1/freq) - 1)
mu.rename("mu", inplace=True)
cov = param_estimator.sample_cov(returns, returns_data=True, frequency=freq)
return [mu for _ in range(trade_horizon)], [cov for _ in range(trade_horizon)]
def get_factor_mu(model_name, model, asset_list, factor_columns, ag):
mu_factor = []
for month in range(12):
mu_month = []
for tick in asset_list:
data = [ag[model_name[:3]][factor_name][1][month - 1] for factor_name in factor_columns]
mu = model[(tick, model_name)][0].predict(np.array(data).reshape(1, -1))
mu_month.append(mu[0])
mu_factor.append(mu_month)
mu_factor = [pd.Series(mu_factor[i]) for i in range(12)]
return mu_factor
def get_scenarios(model_name, model, asset_list, factor_columns, ag, res, num_s):
scenarios = []
for s in range(num_s):
mu_factor = []
for month in range(12):
mu_month = []
for idx, tick in enumerate(asset_list):
data = [ag[model_name[:3]][factor_name][1][month - 1] for factor_name in factor_columns]
mu = model[(tick, model_name)][0].predict(np.array(data).reshape(1, -1))
mu_month.append(mu[0] + np.random.normal(0.0, res[idx][month]**0.5))
mu_factor.append(mu_month)
mu_factor = [pd.Series(mu_factor[i]) for i in range(12)]
scenarios.append(mu_factor)
return scenarios
if __name__ == '__main__':
stock_picks = ['DIS', 'IBM', 'JPM', 'KO', 'WMT']
weights_dict = collections.OrderedDict()
returns_dict = collections.OrderedDict()
assets_dict = collections.OrderedDict()
val_periods = [(f'{str(year)}-01-01', f'{str(year+4)}-12-31', f'{str(year+5)}-01-01', f'{str(year+5)}-12-31')
for year in range(2001, 2011)]
for val in val_periods:
print(val)
train_start, train_end, test_start, test_end = val
etf_table = 'americanetfs'
etf_tickers = param_estimator.get_all_tickers(etf_table)
etf_returns_by_tick = []
for tick in etf_tickers:
returns = param_estimator.get_returns(tick, etf_table, train_start, test_end, freq='monthly')
if returns.empty:
continue
returns[tick] = returns['adj_close']
etf_returns_by_tick += [returns[[tick]]]
etf_returns = pd.concat(etf_returns_by_tick, axis=1).T.dropna()
train_etf_returns = etf_returns.T.head(12*5)
test_etf_returns = etf_returns.T.tail(12*1)
valid_etf_tickers = train_etf_returns.columns
print(f'number of etfs: {train_etf_returns.shape[1]}, number of months: {train_etf_returns.shape[0]}')
# market return
market_return = historical_avg(train_etf_returns[['SPY']], 60)[0][0].tolist()[0]
print(f'market return: {market_return}')
pca = PCA(n_components='mle')
principal_comp = pca.fit_transform(train_etf_returns.T)
print(f'number of principal components: {principal_comp.shape[1]}')
n_clusters = 10
X = np.asarray(principal_comp)
k_medoids = KMedoids(n_clusters=n_clusters, method='pam', init='k-medoids++').fit(X)
selected_etfs = [valid_etf_tickers[np.where(X == k)[0][0]] for k in k_medoids.cluster_centers_]
inertia = k_medoids.inertia_
print(f'selected etfs: {selected_etfs}, cluster inertia: {inertia}')
stock_table = 'spy'
stock_returns_by_tick = []
for tick in stock_picks:
returns = param_estimator.get_returns(tick, stock_table, train_start, test_end, freq='monthly')
if returns.empty:
continue
returns[tick] = returns['adj_close']
stock_returns_by_tick += [returns[[tick]]]
stock_returns = pd.concat(stock_returns_by_tick, axis=1).T.dropna()
train_stock_returns = stock_returns.T.head(12*5)
test_stock_returns = stock_returns.T.tail(12*1)
# Fama-French factors
train_factors = param_estimator.get_factors(start=int(train_start[0:4] + train_start[5:7]), end=int(train_end[0:4] + train_end[5:7]), freq='monthly')
test_factors = param_estimator.get_factors(start=int(test_start[0:4] + test_start[5:7]), end=int(test_end[0:4] + test_end[5:7]), freq='monthly')
asset_universe = stock_picks + selected_etfs
train_returns = pd.concat([train_stock_returns, train_etf_returns], axis=1)
test_returns = pd.concat([test_stock_returns, test_etf_returns], axis=1)
assets_dict[test_start] = asset_universe
returns_dict[test_start] = test_returns
# historical average param. estimation
mu, cov = historical_avg(train_returns, 12*5, 12)
# print(mu[0])
# print(cov[0] / 60.0)
print('data collected')
factor_models = collections.OrderedDict()
for tick in asset_universe:
merged = pd.merge(train_factors, train_returns[[tick]], left_on='date', right_on='date', how="inner", sort=False)
ff3 = merged[['excess', 'smb', 'hml']]
ff5 = merged[['excess', 'smb', 'hml', 'rmw', 'cma']]
merged[tick] = merged[tick] - merged['riskfree'].astype('float')/100.0
adj_returns = merged[[tick]]
alphas = [1e-2, 1e-1, 0.0]
l1_ratios = list(np.arange(0, 0.1, 0.05))
mlr3, r_sq3 = param_estimator.MLR(ff3, adj_returns[tick])
factor_models[(tick, 'ff3_mlr')] = (mlr3, r_sq3)
mlr5, r_sq5 = param_estimator.MLR(ff5, adj_returns[tick])
factor_models[(tick, 'ff5_mlr')] = (mlr5, r_sq5)
for alpha, l1_ratio in list(itertools.product(alphas, l1_ratios)):
en3, en_r_sq3 = param_estimator.EN(ff3, adj_returns[tick], alpha=alpha, l1_ratio=l1_ratio)
factor_models[(tick, f'ff3_en_{alpha}_{l1_ratio}')] = (en3, en_r_sq3)
en5, en_r_sq5 = param_estimator.EN(ff5, adj_returns[tick], alpha=alpha, l1_ratio=l1_ratio)
factor_models[(tick, f'ff5_en_{alpha}_{l1_ratio}')] = (en5, en_r_sq5)
# arima-garch
ag = dict()
ag['ff3'] = param_estimator.arima_garch(train_factors[['excess', 'smb', 'hml']], trade_horizon=12, columns=['excess', 'smb', 'hml'])
ag['ff5'] = param_estimator.arima_garch(train_factors[['excess', 'smb', 'hml', 'rmw', 'cma']], trade_horizon=12, columns=['excess', 'smb', 'hml', 'rmw', 'cma'])
months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
model_names = []
mu_factor = collections.OrderedDict()
cov_factor = collections.OrderedDict()
scenarios_factor = collections.OrderedDict()
for key, value in factor_models.items():
tick, model_name = key
model, r_sq = value
model_names += [model_name]
model_names = list(set(model_names))
for model_name in model_names:
factor_columns = ['excess', 'smb', 'hml', 'rmw', 'cma'] if model_name[:3] == 'ff5' else ['excess', 'smb', 'hml']
mu_factor[model_name] = get_factor_mu(model_name, factor_models, asset_universe, factor_columns, ag)
factor_cov = train_factors[factor_columns].cov()
factor_loadings = []
r = []
for tick in asset_universe:
factor_loadings += [factor_models[(tick, model_name)][0].coef_]
res_var = [ag[model_name[:3]][factor][3].residual_variance.values.tolist()[0] for factor in
factor_columns]
r.append([sum(i[0] * i[1] for i in zip([k ** 2 for k in factor_models[(tick, model_name)][0].coef_], [j[month] for j in res_var])) for month in range(12)])
factor_loadings = pd.DataFrame(factor_loadings, columns=factor_columns)
res_diag = [np.diag([res[month] for res in r]) for month in range(12)]
cov_factor[model_name] = [pd.DataFrame(np.dot(factor_loadings, np.dot(factor_cov, factor_loadings.T)) + res_diag[month], columns=asset_universe) for month in range(12)]
scenarios = get_scenarios(model_name, factor_models, asset_universe, factor_columns, ag, r, 1000)
scenarios_factor[model_name] = scenarios
print('generating portfolios')
# TODO: transaction cost, ellipsoidal uncertainty, multi-period leverage
weight_constraints = {'DIS':(0.05, 1.0), 'IBM':(0.05, 1.0), 'JPM':(0.05, 1.0), 'KO':(0.05, 1.0), 'WMT':(0.05, 1.0)}
for model_name in model_names:
# robust MVO
for conf in [1.645, 1.960, 2.576]:
ef = efficient_frontier.EfficientFrontier(mu_factor[model_name], cov_factor[model_name], trade_horizon=12)
# ef.add_objective(objective_functions.transaction_cost, w_prev=np.zeros(len(asset_universe)), k=0.001)
card = np.zeros(shape=len(asset_universe))
control = 0.50
for i in range(len(stock_picks)):
card[i] = 1
ef.add_constraint(lambda w: card @ w >= control, broadcast=False, var_list=[0])
for i in range(len(stock_picks)):
min = np.zeros(shape=len(asset_universe))
max = np.ones(shape=len(asset_universe))
min[i] = weight_constraints[asset_universe[i]][0]
max[i] = weight_constraints[asset_universe[i]][1]
ef.add_constraint(lambda w: w >= min, broadcast=False, var_list=[0])
ef.add_constraint(lambda w: w <= max, broadcast=False, var_list=[0])
ef.robust_efficient_frontier(target_return=market_return, conf=conf)
weights = ef.clean_weights()
weights_dict[(test_start, model_name, conf)] = weights
# risk parity
ef = efficient_frontier.EfficientFrontier(mu_factor[model_name], cov_factor[model_name], trade_horizon=12)
# ef.add_objective(objective_functions.transaction_cost, w_prev=np.zeros(len(asset_universe)), k=0.001)
card = np.zeros(shape=len(asset_universe))
control = 0.50
for i in range(len(stock_picks)):
card[i] = 1
ef.add_constraint(lambda w: card @ w >= control, broadcast=False, var_list=[0])
for i in range(len(stock_picks)):
min = np.zeros(shape=len(asset_universe))
max = np.ones(shape=len(asset_universe))
min[i] = weight_constraints[asset_universe[i]][0]
max[i] = weight_constraints[asset_universe[i]][1]
ef.add_constraint(lambda w: w >= min, broadcast=False, var_list=[0])
ef.add_constraint(lambda w: w <= max, broadcast=False, var_list=[0])
ef.risk_parity()
weights = ef.clean_weights()
weights_dict[(test_start, model_name, None)] = weights
# max sharpe ratio
ef = efficient_frontier.EfficientFrontier([mu_factor[model_name][0] for _ in range(2)], [cov_factor[model_name][0] for _ in range(2)], trade_horizon=2)
# ef.add_objective(objective_functions.transaction_cost, w_prev=np.zeros(len(asset_universe)), k=0.001)
card = np.zeros(shape=len(asset_universe))
control = 0.50
for i in range(len(stock_picks)):
card[i] = 1
ef.add_constraint(lambda w: card @ w >= control, broadcast=False, var_list=[0])
for i in range(len(stock_picks)):
min = np.zeros(shape=len(asset_universe))
max = np.ones(shape=len(asset_universe))
min[i] = weight_constraints[asset_universe[i]][0]
max[i] = weight_constraints[asset_universe[i]][1]
ef.add_constraint(lambda w: w >= min, broadcast=False, var_list=[0])
ef.add_constraint(lambda w: w <= max, broadcast=False, var_list=[0])
ef.max_sharpe()
weights = ef.clean_weights()
weights_dict[(test_start, model_name, None)] = weights
# cvar opt.
for alpha in [0.90, 0.95, 0.99]:
ef = efficient_frontier.EfficientFrontier(mu_factor[model_name], cov_factor[model_name], trade_horizon=12)
# ef.add_objective(objective_functions.transaction_cost, w_prev=np.zeros(len(asset_universe)), k=0.001)
card = np.zeros(shape=len(asset_universe))
control = 0.50
for i in range(len(stock_picks)):
card[i] = 1
ef.add_constraint(lambda w: card @ w >= control, broadcast=False, var_list=[0])
for i in range(len(stock_picks)):
min = np.zeros(shape=len(asset_universe))
max = np.ones(shape=len(asset_universe))
min[i] = weight_constraints[asset_universe[i]][0]
max[i] = weight_constraints[asset_universe[i]][1]
ef.add_constraint(lambda w: w >= min, broadcast=False, var_list=[0])
ef.add_constraint(lambda w: w <= max, broadcast=False, var_list=[0])
ef.min_cvar(target_return=market_return, scenarios=scenarios_factor[model_name], alpha=alpha)
weights = ef.clean_weights()
weights_dict[(test_start, model_name, alpha)] = weights
cursor.close() | [
"numpy.array",
"numpy.arange",
"sklearn.decomposition.PCA",
"numpy.where",
"itertools.product",
"numpy.asarray",
"numpy.dot",
"sklearn_extra.cluster.KMedoids",
"pandas.DataFrame",
"static.param_estimator.get_returns",
"numpy.random.normal",
"collections.OrderedDict",
"static.param_estimator.... | [((617, 650), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (640, 650), False, 'import warnings\n'), ((1156, 1226), 'static.param_estimator.sample_cov', 'param_estimator.sample_cov', (['returns'], {'returns_data': '(True)', 'frequency': 'freq'}), '(returns, returns_data=True, frequency=freq)\n', (1182, 1226), True, 'import static.param_estimator as param_estimator\n'), ((2625, 2650), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (2648, 2650), False, 'import collections\n'), ((2670, 2695), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (2693, 2695), False, 'import collections\n'), ((2714, 2739), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (2737, 2739), False, 'import collections\n'), ((1756, 1779), 'pandas.Series', 'pd.Series', (['mu_factor[i]'], {}), '(mu_factor[i])\n', (1765, 1779), True, 'import pandas as pd\n'), ((3068, 3110), 'static.param_estimator.get_all_tickers', 'param_estimator.get_all_tickers', (['etf_table'], {}), '(etf_table)\n', (3099, 3110), True, 'import static.param_estimator as param_estimator\n'), ((3960, 3983), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '"""mle"""'}), "(n_components='mle')\n", (3963, 3983), False, 'from sklearn.decomposition import PCA\n'), ((4161, 4187), 'numpy.asarray', 'np.asarray', (['principal_comp'], {}), '(principal_comp)\n', (4171, 4187), True, 'import numpy as np\n'), ((5472, 5531), 'pandas.concat', 'pd.concat', (['[train_stock_returns, train_etf_returns]'], {'axis': '(1)'}), '([train_stock_returns, train_etf_returns], axis=1)\n', (5481, 5531), True, 'import pandas as pd\n'), ((5555, 5612), 'pandas.concat', 'pd.concat', (['[test_stock_returns, test_etf_returns]'], {'axis': '(1)'}), '([test_stock_returns, test_etf_returns], axis=1)\n', (5564, 5612), True, 'import pandas as pd\n'), ((5929, 5954), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (5952, 5954), False, 'import collections\n'), ((7242, 7366), 'static.param_estimator.arima_garch', 'param_estimator.arima_garch', (["train_factors[['excess', 'smb', 'hml']]"], {'trade_horizon': '(12)', 'columns': "['excess', 'smb', 'hml']"}), "(train_factors[['excess', 'smb', 'hml']],\n trade_horizon=12, columns=['excess', 'smb', 'hml'])\n", (7269, 7366), True, 'import static.param_estimator as param_estimator\n'), ((7383, 7535), 'static.param_estimator.arima_garch', 'param_estimator.arima_garch', (["train_factors[['excess', 'smb', 'hml', 'rmw', 'cma']]"], {'trade_horizon': '(12)', 'columns': "['excess', 'smb', 'hml', 'rmw', 'cma']"}), "(train_factors[['excess', 'smb', 'hml', 'rmw',\n 'cma']], trade_horizon=12, columns=['excess', 'smb', 'hml', 'rmw', 'cma'])\n", (7410, 7535), True, 'import static.param_estimator as param_estimator\n'), ((7668, 7693), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (7691, 7693), False, 'import collections\n'), ((7715, 7740), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (7738, 7740), False, 'import collections\n'), ((7768, 7793), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (7791, 7793), False, 'import collections\n'), ((2423, 2446), 'pandas.Series', 'pd.Series', (['mu_factor[i]'], {}), '(mu_factor[i])\n', (2432, 2446), True, 'import pandas as pd\n'), ((3199, 3287), 'static.param_estimator.get_returns', 'param_estimator.get_returns', (['tick', 'etf_table', 'train_start', 'test_end'], {'freq': '"""monthly"""'}), "(tick, etf_table, train_start, test_end, freq=\n 'monthly')\n", (3226, 3287), True, 'import static.param_estimator as param_estimator\n'), ((4618, 4708), 'static.param_estimator.get_returns', 'param_estimator.get_returns', (['tick', 'stock_table', 'train_start', 'test_end'], {'freq': '"""monthly"""'}), "(tick, stock_table, train_start, test_end, freq=\n 'monthly')\n", (4645, 4708), True, 'import static.param_estimator as param_estimator\n'), ((6012, 6121), 'pandas.merge', 'pd.merge', (['train_factors', 'train_returns[[tick]]'], {'left_on': '"""date"""', 'right_on': '"""date"""', 'how': '"""inner"""', 'sort': '(False)'}), "(train_factors, train_returns[[tick]], left_on='date', right_on=\n 'date', how='inner', sort=False)\n", (6020, 6121), True, 'import pandas as pd\n'), ((6478, 6521), 'static.param_estimator.MLR', 'param_estimator.MLR', (['ff3', 'adj_returns[tick]'], {}), '(ff3, adj_returns[tick])\n', (6497, 6521), True, 'import static.param_estimator as param_estimator\n'), ((6609, 6652), 'static.param_estimator.MLR', 'param_estimator.MLR', (['ff5', 'adj_returns[tick]'], {}), '(ff5, adj_returns[tick])\n', (6628, 6652), True, 'import static.param_estimator as param_estimator\n'), ((8858, 8911), 'pandas.DataFrame', 'pd.DataFrame', (['factor_loadings'], {'columns': 'factor_columns'}), '(factor_loadings, columns=factor_columns)\n', (8870, 8911), True, 'import pandas as pd\n'), ((10952, 11058), 'static.efficient_frontier.EfficientFrontier', 'efficient_frontier.EfficientFrontier', (['mu_factor[model_name]', 'cov_factor[model_name]'], {'trade_horizon': '(12)'}), '(mu_factor[model_name], cov_factor[\n model_name], trade_horizon=12)\n', (10988, 11058), True, 'import static.efficient_frontier as efficient_frontier\n'), ((4208, 4273), 'sklearn_extra.cluster.KMedoids', 'KMedoids', ([], {'n_clusters': 'n_clusters', 'method': '"""pam"""', 'init': '"""k-medoids++"""'}), "(n_clusters=n_clusters, method='pam', init='k-medoids++')\n", (4216, 4273), False, 'from sklearn_extra.cluster import KMedoids\n'), ((6426, 6449), 'numpy.arange', 'np.arange', (['(0)', '(0.1)', '(0.05)'], {}), '(0, 0.1, 0.05)\n', (6435, 6449), True, 'import numpy as np\n'), ((6754, 6790), 'itertools.product', 'itertools.product', (['alphas', 'l1_ratios'], {}), '(alphas, l1_ratios)\n', (6771, 6790), False, 'import itertools\n'), ((6825, 6899), 'static.param_estimator.EN', 'param_estimator.EN', (['ff3', 'adj_returns[tick]'], {'alpha': 'alpha', 'l1_ratio': 'l1_ratio'}), '(ff3, adj_returns[tick], alpha=alpha, l1_ratio=l1_ratio)\n', (6843, 6899), True, 'import static.param_estimator as param_estimator\n'), ((7018, 7092), 'static.param_estimator.EN', 'param_estimator.EN', (['ff5', 'adj_returns[tick]'], {'alpha': 'alpha', 'l1_ratio': 'l1_ratio'}), '(ff5, adj_returns[tick], alpha=alpha, l1_ratio=l1_ratio)\n', (7036, 7092), True, 'import static.param_estimator as param_estimator\n'), ((8936, 8970), 'numpy.diag', 'np.diag', (['[res[month] for res in r]'], {}), '([res[month] for res in r])\n', (8943, 8970), True, 'import numpy as np\n'), ((9726, 9832), 'static.efficient_frontier.EfficientFrontier', 'efficient_frontier.EfficientFrontier', (['mu_factor[model_name]', 'cov_factor[model_name]'], {'trade_horizon': '(12)'}), '(mu_factor[model_name], cov_factor[\n model_name], trade_horizon=12)\n', (9762, 9832), True, 'import static.efficient_frontier as efficient_frontier\n'), ((13268, 13374), 'static.efficient_frontier.EfficientFrontier', 'efficient_frontier.EfficientFrontier', (['mu_factor[model_name]', 'cov_factor[model_name]'], {'trade_horizon': '(12)'}), '(mu_factor[model_name], cov_factor[\n model_name], trade_horizon=12)\n', (13304, 13374), True, 'import static.efficient_frontier as efficient_frontier\n'), ((1051, 1102), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', '[(x + 1) for x in data]'], {}), '(lambda x, y: x * y, [(x + 1) for x in data])\n', (1057, 1102), False, 'from functools import reduce\n'), ((3462, 3500), 'pandas.concat', 'pd.concat', (['etf_returns_by_tick'], {'axis': '(1)'}), '(etf_returns_by_tick, axis=1)\n', (3471, 3500), True, 'import pandas as pd\n'), ((4887, 4927), 'pandas.concat', 'pd.concat', (['stock_returns_by_tick'], {'axis': '(1)'}), '(stock_returns_by_tick, axis=1)\n', (4896, 4927), True, 'import pandas as pd\n'), ((1638, 1652), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1646, 1652), True, 'import numpy as np\n'), ((2318, 2363), 'numpy.random.normal', 'np.random.normal', (['(0.0)', '(res[idx][month] ** 0.5)'], {}), '(0.0, res[idx][month] ** 0.5)\n', (2334, 2363), True, 'import numpy as np\n'), ((4324, 4340), 'numpy.where', 'np.where', (['(X == k)'], {}), '(X == k)\n', (4332, 4340), True, 'import numpy as np\n'), ((2247, 2261), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2255, 2261), True, 'import numpy as np\n'), ((9070, 9107), 'numpy.dot', 'np.dot', (['factor_cov', 'factor_loadings.T'], {}), '(factor_cov, factor_loadings.T)\n', (9076, 9107), True, 'import numpy as np\n')] |
import torch
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import time
import sys
import pandas as pd
import numpy as np
import keras
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from Levenshtein import distance as levenshtein_distance
from edit_distance.train import load_edit_distance_dataset
from util.data_handling.data_loader import get_dataloaders
from util.ml_and_math.loss_functions import AverageMeter
import numpy as np
import pickle
import pandas as pd
from scipy.stats import mode
from edit_distance.task.dataset_generator_genomic import EditDistanceGenomicDatasetGenerator
# from hypersmorf.myfunctions import create_parser, generate_datasets, run_model
import torch
import torch.nn as nn
import numpy as np
from geomstats.geometry.poincare_ball import PoincareBall
numpy_type_map = {
'float64': torch.DoubleTensor,
'float32': torch.FloatTensor,
'float16': torch.HalfTensor,
'int64': torch.LongTensor,
'int32': torch.IntTensor,
'int16': torch.ShortTensor,
'int8': torch.CharTensor,
'uint8': torch.ByteTensor,
}
def square_distance(t1_emb, t2_emb,scale=1):
D = t1_emb - t2_emb
d = torch.sum(D * D, dim=-1)
return d
def euclidean_distance(t1_emb, t2_emb,scale=1):
D = t1_emb - t2_emb
d = torch.norm(D, dim=-1)
return d
def cosine_distance(t1_emb, t2_emb,scale=1):
return 1 - nn.functional.cosine_similarity(t1_emb, t2_emb, dim=-1, eps=1e-6)
def manhattan_distance(t1_emb, t2_emb,scale=1):
D = t1_emb - t2_emb
d = torch.sum(torch.abs(D), dim=-1)
return d
def hyperbolic_geomstats_distance(u,v,scale=1):
return PoincareBall(u.size()[1]).metric.dist(u,v)
def hyperbolic_distance(u, v, epsilon=1e-7): # changed from epsilon=1e-7 to reduce error
sqdist = torch.sum((u - v) ** 2, dim=-1)
squnorm = torch.sum(u ** 2, dim=-1)
sqvnorm = torch.sum(v ** 2, dim=-1)
x = 1 + 2 * sqdist / ((1 - squnorm) * (1 - sqvnorm)) + epsilon
z = torch.sqrt(x ** 2 - 1)
return torch.log(x + z)
def hyperbolic_distance_numpy(u, v, epsilon=1e-9):
sqdist = np.sum((u - v) ** 2, axis=-1)
squnorm = np.sum(u ** 2, axis=-1)
sqvnorm = np.sum(v ** 2, axis=-1)
x = 1 + 2 * sqdist / ((1 - squnorm) * (1 - sqvnorm)) + epsilon
z = np.sqrt(x ** 2 - 1)
return np.log(x + z)
DISTANCE_TORCH = {
'square': square_distance,
'euclidean': euclidean_distance,
'cosine': cosine_distance,
'manhattan': manhattan_distance,
'hyperbolic': hyperbolic_distance
}
import argparse
import os
import pickle
import sys
import time
from types import SimpleNamespace
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
from edit_distance.task.dataset import EditDistanceDatasetSampled, EditDistanceDatasetComplete,EditDistanceDatasetSampledCalculated
from edit_distance.task.dataset import EditDistanceDatasetCompleteCalculated
from edit_distance.models.hyperbolics import RAdam
from edit_distance.models.pair_encoder import PairEmbeddingDistance
from util.data_handling.data_loader import get_dataloaders
from util.ml_and_math.loss_functions import MAPE
from util.ml_and_math.loss_functions import AverageMeter
def general_arg_parser():
""" Parsing of parameters common to all the different models """
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, default='../../data/edit_qiita_small.pkl', help='Dataset path')
parser.add_argument('--no-cuda', action='store_true', default=False, help='Disables CUDA training (GPU)')
parser.add_argument('--seed', type=int, default=42, help='Random seed')
parser.add_argument('--epochs', type=int, default=2, help='Number of epochs to train')
parser.add_argument('--lr', type=float, default=0.001, help='Initial learning rate')
parser.add_argument('--weight_decay', type=float, default=0.0, help='Weight decay')
parser.add_argument('--dropout', type=float, default=0.0, help='Dropout rate (1 - keep probability)')
parser.add_argument('--patience', type=int, default=50, help='Patience')
parser.add_argument('--print_every', type=int, default=1, help='Print training results every')
parser.add_argument('--batch_size', type=int, default=128, help='Batch size')
parser.add_argument('--embedding_size', type=int, default=5, help='Size of embedding')
parser.add_argument('--distance', type=str, default='hyperbolic', help='Type of distance to use')
parser.add_argument('--workers', type=int, default=0, help='Number of workers')
parser.add_argument('--loss', type=str, default="mse", help='Loss function to use (mse, mape or mae)')
parser.add_argument('--plot', action='store_true', default=False, help='Plot real vs predicted distances')
parser.add_argument('--closest_data_path', type=str, default='', help='Dataset for closest string retrieval tests')
parser.add_argument('--hierarchical_data_path', type=str, default='', help='Dataset for hierarchical clustering')
parser.add_argument('--construct_msa_tree', type=str, default='False', help='Whether to construct NJ tree testset')
parser.add_argument('--extr_data_path', type=str, default='', help='Dataset for further edit distance tests')
parser.add_argument('--scaling', type=str, default='False', help='Project to hypersphere (for hyperbolic)')
parser.add_argument('--hyp_optimizer', type=str, default='Adam', help='Optimizer for hyperbolic (Adam or RAdam)')
return parser
def execute_train(model_class, model_args, args):
# set device
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = 'cpu'
print('Using device:', device)
# set the random seed
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
# load data
datasets = load_edit_distance_dataset(args.data)
loaders = get_dataloaders(datasets, batch_size=args.batch_size, workers=args.workers)
# fix hyperparameters
model_args = SimpleNamespace(**model_args)
model_args.device = device
model_args.len_sequence = datasets['train'].len_sequence
model_args.embedding_size = args.embedding_size
model_args.dropout = args.dropout
print("Length of sequence", datasets['train'].len_sequence)
args.scaling = True if args.scaling == 'True' else False
# generate model
embedding_model = model_class(**vars(model_args))
model = PairEmbeddingDistance(embedding_model=embedding_model, distance=args.distance, scaling=args.scaling)
model.to(device)
# select optimizer
if args.distance == 'hyperbolic' and args.hyp_optimizer == 'RAdam':
optimizer = RAdam(model.parameters(), lr=args.lr)
else:
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
# select loss
loss = None
if args.loss == "mse":
loss = nn.MSELoss()
elif args.loss == "mae":
loss = nn.L1Loss()
elif args.loss == "mape":
loss = MAPE
# print total number of parameters
total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print('Total params', total_params)
# Train model
t_total = time.time()
bad_counter = 0
best = 1e10
best_epoch = -1
start_epoch = 0
for epoch in range(start_epoch, args.epochs):
t = time.time()
loss_train = train(model, loaders['train'], optimizer, loss, device)
loss_val = test(model, loaders['val'], loss, device)
# print progress
if epoch % args.print_every == 0:
print('Epoch: {:04d}'.format(epoch + 1),
'loss_train: {:.6f}'.format(loss_train),
'loss_val: {:.6f} MAPE {:.4f}'.format(*loss_val),
'time: {:.4f}s'.format(time.time() - t))
sys.stdout.flush()
if loss_val[0] < best:
# save current model
torch.save(model.state_dict(), '{}.pkl'.format(epoch))
# remove previous model
if best_epoch >= 0:
os.remove('{}.pkl'.format(best_epoch))
# update training variables
best = loss_val[0]
best_epoch = epoch
bad_counter = 0
else:
bad_counter += 1
if bad_counter == args.patience:
print('Early stop at epoch {} (no improvement in last {} epochs)'.format(epoch + 1, bad_counter))
break
print('Optimization Finished!')
print('Total time elapsed: {:.4f}s'.format(time.time() - t_total))
# Restore best model
print('Loading {}th epoch'.format(best_epoch + 1))
model.load_state_dict(torch.load('{}.pkl'.format(best_epoch)))
# Testing
for dset in loaders.keys():
if args.plot:
avg_loss = test_and_plot(model, loaders[dset], loss, device, dset)
else:
avg_loss = test(model, loaders[dset], loss, device)
print('Final results {}: loss = {:.6f} MAPE {:.4f}'.format(dset, *avg_loss))
# Nearest neighbour retrieval
if args.closest_data_path != '':
print("Closest string retrieval")
closest_string_testing(encoder_model=model, data_path=args.closest_data_path,
batch_size=args.batch_size, device=device, distance=args.distance)
# Hierarchical clustering
if args.hierarchical_data_path != '':
print("Hierarchical clustering")
hierarchical_clustering_testing(encoder_model=model, data_path=args.hierarchical_data_path,
batch_size=args.batch_size, device=device, distance=args.distance)
# MSA tree construction on test set
if args.construct_msa_tree == 'True':
print("MSA tree construction")
approximate_guide_trees(encoder_model=model, dataset=datasets['test'],
batch_size=args.batch_size, device=device, distance=args.distance)
# Extra datasets testing (e.g. extrapolation)
if args.extr_data_path != '':
print("Extra datasets testing")
datasets = load_edit_distance_dataset(args.extr_data_path)
loaders = get_dataloaders(datasets, batch_size=max(1, args.batch_size // 8), workers=args.workers)
for dset in loaders.keys():
if args.plot:
avg_loss = test_and_plot(model, loaders[dset], loss, device, dset)
else:
avg_loss = test(model, loaders[dset], loss, device)
print('Final results {}: loss = {:.6f} MAPE {:.4f}'.format(dset, *avg_loss))
torch.save((model_class, model_args, model.embedding_model.state_dict(), args.distance),
'{}.pkl'.format(model_class.__name__))
def load_edit_distance_dataset(path):
with open(path, 'rb') as f:
sequences, distances = pickle.load(f)
datasets = {}
for key in sequences.keys():
if len(sequences[key].shape) == 2: # datasets without batches
if key == 'train':
datasets[key] = EditDistanceDatasetSampled(sequences[key].unsqueeze(0), distances[key].unsqueeze(0),
multiplicity=10)
else:
datasets[key] = EditDistanceDatasetComplete(sequences[key], distances[key])
else: # datasets with batches
datasets[key] = EditDistanceDatasetSampled(sequences[key], distances[key])
return datasets
def load_edit_distance_dataset_calculate(path):
with open(path, 'rb') as f:
sequences, distances = pickle.load(f)
datasets = {}
for key in sequences.keys():
if len(sequences[key].shape) == 2: # datasets without batches
if key == 'train':
datasets[key] = EditDistanceDatasetSampledCalculated(sequences[key].unsqueeze(0), distances[key].unsqueeze(0),
multiplicity=10)
else:
datasets[key] = EditDistanceDatasetCompleteCalculated(sequences[key], distances[key])
else: # datasets with batches
datasets[key] = EditDistanceDatasetSampledCalculated(sequences[key], distances[key])
return datasets
def train(model, loader, optimizer, loss, device):
device = 'cpu'
avg_loss = AverageMeter()
model.train()
for sequences, labels in loader:
# move examples to right device
# sequences, labels = sequences.to(device), labels.to(device)
with torch.autograd.set_detect_anomaly(True):
# forward propagation
optimizer.zero_grad()
output = model(sequences)
# loss and backpropagation
loss_train = loss(output, labels)
loss_train.backward()
optimizer.step()
# keep track of average loss
avg_loss.update(loss_train.data.item(), sequences.shape[0])
return avg_loss.avg
def test(model, loader, loss, device):
avg_loss = AverageMeter()
model.eval()
for sequences, labels in loader:
# move examples to right device
# sequences, labels = sequences.to(device), labels.to(device)
# forward propagation and loss computation
output = model(sequences)
loss_val = loss(output, labels).data.item()
avg_loss.update(loss_val, sequences.shape[0])
return avg_loss.avg
def test_and_plot(model, loader, loss, device, dataset):
avg_loss = AverageMeter(len_tuple=2)
model.eval()
output_list = []
labels_list = []
for sequences, labels in loader:
# move examples to right device
sequences, labels = sequences.to(device), labels.to(device)
# forward propagation and loss computation
output = model(sequences)
loss_val = loss[dt](output, labels).data.item()
mape = MAPE(output, labels).data.item()
avg_loss.update((loss_val, mape), sequences.shape[0])
# append real and predicted distances to lists
output_list.append(output.cpu().detach().numpy())
labels_list.append(labels.cpu().detach().numpy())
# save real and predicted distances for offline plotting
outputs = np.concatenate(output_list, axis=0)
labels = np.concatenate(labels_list, axis=0)
pickle.dump((outputs, labels), open(dataset + ".pkl", "wb"))
# plt.plot(outputs, labels, 'o', color='black')
# plt.show()
return avg_loss.avg
#%%
# Train my models
import os
os.environ['GEOMSTATS_BACKEND'] = 'pytorch'
import torch
from torch import nn
import torch.optim as optim
import time
import argparse
from edit_distance.task.dataset_generator_genomic import EditDistanceGenomicDatasetGenerator
from util.data_handling.data_loader import get_dataloaders
from edit_distance.train import load_edit_distance_dataset,train,test
from edit_distance.models.pair_encoder import PairEmbeddingDistance
class LinearEncoder(nn.Module):
""" Linear model which simply flattens the sequence and applies a linear transformation. """
def __init__(self, len_sequence, embedding_size, alphabet_size=4):
super(LinearEncoder, self).__init__()
self.encoder = nn.Linear(in_features=alphabet_size * len_sequence,
out_features=embedding_size)
def forward(self, sequence):
# flatten sequence and apply layer
B = sequence.shape[0]
sequence = sequence.reshape(B, -1)
emb = self.encoder(sequence)
return emb
def run_model(dataset_name, embedding_size, dist_type, string_size, n_epoch):
device = 'cpu'
torch.manual_seed(2021)
if device == 'cuda':
torch.cuda.manual_seed(2021)
# load data
datasets = load_edit_distance_dataset(dataset_name)
loaders = get_dataloaders(datasets, batch_size=128, workers=0)
# model, optimizer and loss
encoder = LinearEncoder(string_size, embedding_size)
model = PairEmbeddingDistance(embedding_model=encoder, distance=dist_type,scaling=True)
loss = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
optimizer.zero_grad()
# training
for epoch in range(0, n_epoch):
t = time.time()
loss_train = train(model, loaders['train'], optimizer, loss, device)
loss_val = test(model, loaders['val'], loss, device)
# print progress
if epoch % 5 == 0:
print('Epoch: {:02d}'.format(epoch),
'loss_train: {:.6f}'.format(loss_train),
'loss_val: '.format(loss_val),
'time: {:.4f}s'.format(time.time() - t))
# testing
for dset in loaders.keys():
avg_loss = test(model, loaders[dset], loss, device)
print('Final results {}: loss = {:.6f}'.format(dset, avg_loss))
return model, avg_loss
def create_parser(out, source, train,val,test):
parser = argparse.ArgumentParser()
parser.add_argument('--out', type=str, default=out, help='Output data path')
parser.add_argument('--train_size', type=int, default=train, help='Training sequences')
parser.add_argument('--val_size', type=int, default=val, help='Validation sequences')
parser.add_argument('--test_size', type=int, default=test, help='Test sequences')
parser.add_argument('--source_sequences', type=str, default=source, help='Sequences data path')
return parser
def generate_datasets(parser):
args, unknown = parser.parse_known_args()
# load and divide sequences
with open(args.source_sequences, 'rb') as f:
L = f.readlines()
L = [l[:-1].decode('UTF-8') for l in L]
strings = {
'train': L[:args.train_size],
'val': L[args.train_size:args.train_size + args.val_size],
'test': L[args.train_size + args.val_size:args.train_size + args.val_size + args.test_size]
}
data = EditDistanceGenomicDatasetGenerator(strings=strings)
data.save_as_pickle(args.out)
return strings
string_size=153
n_epoch = 10
e_size=np.logspace(1,9,num=9-1, base=2,endpoint=False, dtype=int)
# dist_types=['hyperbolic', 'euclidean', 'square', 'manhattan', 'cosine']
dist_types = ['hyperbolic']
model, avg_loss = np.zeros((len(dist_types),len(e_size)),dtype=object),np.zeros((len(dist_types),len(e_size)))
names = ['largest_group_strings', 'strings_test', 'strings_subset','clean_strings']
for name in names:
dataset_name = 'D:\hyperbolicEmbeddings' + name+'.pkl'
for i in range(len(dist_types)):
for j in range(len(e_size)):
print(dist_types[i])
model[i][j], avg_loss[i][j] = run_model(dataset_name,e_size[j],dist_types[i],string_size,n_epoch)
pickle.dump((model,avg_loss,e_size,dist_types), open('D:\hyperbolicEmbeddings'+name+'.pkl', "wb"))
# CLUSTERING BEGINS HERE
'''
Get the hyperbolic distances between models
'''
pickle_off = open("D:\hyperbolicEmbeddings\strings_test.pkl", "rb")
testStrings = pickle.load(pickle_off)
print(testStrings) | [
"numpy.sqrt",
"edit_distance.task.dataset.EditDistanceDatasetSampledCalculated",
"edit_distance.task.dataset.EditDistanceDatasetComplete",
"torch.nn.L1Loss",
"numpy.log",
"torch.sqrt",
"util.ml_and_math.loss_functions.MAPE",
"torch.nn.MSELoss",
"torch.cuda.is_available",
"torch.sum",
"argparse.A... | [((18496, 18559), 'numpy.logspace', 'np.logspace', (['(1)', '(9)'], {'num': '(9 - 1)', 'base': '(2)', 'endpoint': '(False)', 'dtype': 'int'}), '(1, 9, num=9 - 1, base=2, endpoint=False, dtype=int)\n', (18507, 18559), True, 'import numpy as np\n'), ((19449, 19472), 'pickle.load', 'pickle.load', (['pickle_off'], {}), '(pickle_off)\n', (19460, 19472), False, 'import pickle\n'), ((1291, 1315), 'torch.sum', 'torch.sum', (['(D * D)'], {'dim': '(-1)'}), '(D * D, dim=-1)\n', (1300, 1315), False, 'import torch\n'), ((1417, 1438), 'torch.norm', 'torch.norm', (['D'], {'dim': '(-1)'}), '(D, dim=-1)\n', (1427, 1438), False, 'import torch\n'), ((1937, 1968), 'torch.sum', 'torch.sum', (['((u - v) ** 2)'], {'dim': '(-1)'}), '((u - v) ** 2, dim=-1)\n', (1946, 1968), False, 'import torch\n'), ((1984, 2009), 'torch.sum', 'torch.sum', (['(u ** 2)'], {'dim': '(-1)'}), '(u ** 2, dim=-1)\n', (1993, 2009), False, 'import torch\n'), ((2025, 2050), 'torch.sum', 'torch.sum', (['(v ** 2)'], {'dim': '(-1)'}), '(v ** 2, dim=-1)\n', (2034, 2050), False, 'import torch\n'), ((2128, 2150), 'torch.sqrt', 'torch.sqrt', (['(x ** 2 - 1)'], {}), '(x ** 2 - 1)\n', (2138, 2150), False, 'import torch\n'), ((2163, 2179), 'torch.log', 'torch.log', (['(x + z)'], {}), '(x + z)\n', (2172, 2179), False, 'import torch\n'), ((2250, 2279), 'numpy.sum', 'np.sum', (['((u - v) ** 2)'], {'axis': '(-1)'}), '((u - v) ** 2, axis=-1)\n', (2256, 2279), True, 'import numpy as np\n'), ((2295, 2318), 'numpy.sum', 'np.sum', (['(u ** 2)'], {'axis': '(-1)'}), '(u ** 2, axis=-1)\n', (2301, 2318), True, 'import numpy as np\n'), ((2334, 2357), 'numpy.sum', 'np.sum', (['(v ** 2)'], {'axis': '(-1)'}), '(v ** 2, axis=-1)\n', (2340, 2357), True, 'import numpy as np\n'), ((2435, 2454), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 - 1)'], {}), '(x ** 2 - 1)\n', (2442, 2454), True, 'import numpy as np\n'), ((2467, 2480), 'numpy.log', 'np.log', (['(x + z)'], {}), '(x + z)\n', (2473, 2480), True, 'import numpy as np\n'), ((3495, 3520), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3518, 3520), False, 'import argparse\n'), ((5911, 5936), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (5925, 5936), True, 'import numpy as np\n'), ((5942, 5970), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (5959, 5970), False, 'import torch\n'), ((6068, 6105), 'edit_distance.train.load_edit_distance_dataset', 'load_edit_distance_dataset', (['args.data'], {}), '(args.data)\n', (6094, 6105), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((6121, 6196), 'util.data_handling.data_loader.get_dataloaders', 'get_dataloaders', (['datasets'], {'batch_size': 'args.batch_size', 'workers': 'args.workers'}), '(datasets, batch_size=args.batch_size, workers=args.workers)\n', (6136, 6196), False, 'from util.data_handling.data_loader import get_dataloaders\n'), ((6244, 6273), 'types.SimpleNamespace', 'SimpleNamespace', ([], {}), '(**model_args)\n', (6259, 6273), False, 'from types import SimpleNamespace\n'), ((6679, 6784), 'edit_distance.models.pair_encoder.PairEmbeddingDistance', 'PairEmbeddingDistance', ([], {'embedding_model': 'embedding_model', 'distance': 'args.distance', 'scaling': 'args.scaling'}), '(embedding_model=embedding_model, distance=args.\n distance, scaling=args.scaling)\n', (6700, 6784), False, 'from edit_distance.models.pair_encoder import PairEmbeddingDistance\n'), ((7473, 7484), 'time.time', 'time.time', ([], {}), '()\n', (7482, 7484), False, 'import time\n'), ((12655, 12669), 'util.ml_and_math.loss_functions.AverageMeter', 'AverageMeter', ([], {}), '()\n', (12667, 12669), False, 'from util.ml_and_math.loss_functions import AverageMeter\n'), ((13359, 13373), 'util.ml_and_math.loss_functions.AverageMeter', 'AverageMeter', ([], {}), '()\n', (13371, 13373), False, 'from util.ml_and_math.loss_functions import AverageMeter\n'), ((13846, 13871), 'util.ml_and_math.loss_functions.AverageMeter', 'AverageMeter', ([], {'len_tuple': '(2)'}), '(len_tuple=2)\n', (13858, 13871), False, 'from util.ml_and_math.loss_functions import AverageMeter\n'), ((14599, 14634), 'numpy.concatenate', 'np.concatenate', (['output_list'], {'axis': '(0)'}), '(output_list, axis=0)\n', (14613, 14634), True, 'import numpy as np\n'), ((14649, 14684), 'numpy.concatenate', 'np.concatenate', (['labels_list'], {'axis': '(0)'}), '(labels_list, axis=0)\n', (14663, 14684), True, 'import numpy as np\n'), ((16037, 16060), 'torch.manual_seed', 'torch.manual_seed', (['(2021)'], {}), '(2021)\n', (16054, 16060), False, 'import torch\n'), ((16160, 16200), 'edit_distance.train.load_edit_distance_dataset', 'load_edit_distance_dataset', (['dataset_name'], {}), '(dataset_name)\n', (16186, 16200), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((16216, 16268), 'util.data_handling.data_loader.get_dataloaders', 'get_dataloaders', (['datasets'], {'batch_size': '(128)', 'workers': '(0)'}), '(datasets, batch_size=128, workers=0)\n', (16231, 16268), False, 'from util.data_handling.data_loader import get_dataloaders\n'), ((16379, 16464), 'edit_distance.models.pair_encoder.PairEmbeddingDistance', 'PairEmbeddingDistance', ([], {'embedding_model': 'encoder', 'distance': 'dist_type', 'scaling': '(True)'}), '(embedding_model=encoder, distance=dist_type, scaling=True\n )\n', (16400, 16464), False, 'from edit_distance.models.pair_encoder import PairEmbeddingDistance\n'), ((16471, 16483), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (16481, 16483), False, 'from torch import nn\n'), ((17360, 17385), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (17383, 17385), False, 'import argparse\n'), ((18345, 18397), 'edit_distance.task.dataset_generator_genomic.EditDistanceGenomicDatasetGenerator', 'EditDistanceGenomicDatasetGenerator', ([], {'strings': 'strings'}), '(strings=strings)\n', (18380, 18397), False, 'from edit_distance.task.dataset_generator_genomic import EditDistanceGenomicDatasetGenerator\n'), ((1519, 1585), 'torch.nn.functional.cosine_similarity', 'nn.functional.cosine_similarity', (['t1_emb', 't2_emb'], {'dim': '(-1)', 'eps': '(1e-06)'}), '(t1_emb, t2_emb, dim=-1, eps=1e-06)\n', (1550, 1585), False, 'from torch import nn\n'), ((1682, 1694), 'torch.abs', 'torch.abs', (['D'], {}), '(D)\n', (1691, 1694), False, 'import torch\n'), ((5795, 5820), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5818, 5820), False, 'import torch\n'), ((5999, 6032), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['args.seed'], {}), '(args.seed)\n', (6021, 6032), False, 'import torch\n'), ((7149, 7161), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (7159, 7161), False, 'from torch import nn\n'), ((7631, 7642), 'time.time', 'time.time', ([], {}), '()\n', (7640, 7642), False, 'import time\n'), ((7665, 7720), 'edit_distance.train.train', 'train', (['model', "loaders['train']", 'optimizer', 'loss', 'device'], {}), "(model, loaders['train'], optimizer, loss, device)\n", (7670, 7720), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((7741, 7782), 'edit_distance.train.test', 'test', (['model', "loaders['val']", 'loss', 'device'], {}), "(model, loaders['val'], loss, device)\n", (7745, 7782), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((10413, 10460), 'edit_distance.train.load_edit_distance_dataset', 'load_edit_distance_dataset', (['args.extr_data_path'], {}), '(args.extr_data_path)\n', (10439, 10460), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((11157, 11171), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (11168, 11171), False, 'import pickle\n'), ((11903, 11917), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (11914, 11917), False, 'import pickle\n'), ((15602, 15687), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(alphabet_size * len_sequence)', 'out_features': 'embedding_size'}), '(in_features=alphabet_size * len_sequence, out_features=embedding_size\n )\n', (15611, 15687), False, 'from torch import nn\n'), ((16096, 16124), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['(2021)'], {}), '(2021)\n', (16118, 16124), False, 'import torch\n'), ((16641, 16652), 'time.time', 'time.time', ([], {}), '()\n', (16650, 16652), False, 'import time\n'), ((16675, 16730), 'edit_distance.train.train', 'train', (['model', "loaders['train']", 'optimizer', 'loss', 'device'], {}), "(model, loaders['train'], optimizer, loss, device)\n", (16680, 16730), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((16751, 16792), 'edit_distance.train.test', 'test', (['model', "loaders['val']", 'loss', 'device'], {}), "(model, loaders['val'], loss, device)\n", (16755, 16792), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((17151, 17191), 'edit_distance.train.test', 'test', (['model', 'loaders[dset]', 'loss', 'device'], {}), '(model, loaders[dset], loss, device)\n', (17155, 17191), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((7208, 7219), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (7217, 7219), False, 'from torch import nn\n'), ((8110, 8128), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (8126, 8128), False, 'import sys\n'), ((9199, 9239), 'edit_distance.train.test', 'test', (['model', 'loaders[dset]', 'loss', 'device'], {}), '(model, loaders[dset], loss, device)\n', (9203, 9239), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((11707, 11765), 'edit_distance.task.dataset.EditDistanceDatasetSampled', 'EditDistanceDatasetSampled', (['sequences[key]', 'distances[key]'], {}), '(sequences[key], distances[key])\n', (11733, 11765), False, 'from edit_distance.task.dataset import EditDistanceDatasetSampled, EditDistanceDatasetComplete, EditDistanceDatasetSampledCalculated\n'), ((12473, 12541), 'edit_distance.task.dataset.EditDistanceDatasetSampledCalculated', 'EditDistanceDatasetSampledCalculated', (['sequences[key]', 'distances[key]'], {}), '(sequences[key], distances[key])\n', (12509, 12541), False, 'from edit_distance.task.dataset import EditDistanceDatasetSampled, EditDistanceDatasetComplete, EditDistanceDatasetSampledCalculated\n'), ((12859, 12898), 'torch.autograd.set_detect_anomaly', 'torch.autograd.set_detect_anomaly', (['(True)'], {}), '(True)\n', (12892, 12898), False, 'import torch\n'), ((8831, 8842), 'time.time', 'time.time', ([], {}), '()\n', (8840, 8842), False, 'import time\n'), ((10766, 10806), 'edit_distance.train.test', 'test', (['model', 'loaders[dset]', 'loss', 'device'], {}), '(model, loaders[dset], loss, device)\n', (10770, 10806), False, 'from edit_distance.train import load_edit_distance_dataset, train, test\n'), ((11578, 11637), 'edit_distance.task.dataset.EditDistanceDatasetComplete', 'EditDistanceDatasetComplete', (['sequences[key]', 'distances[key]'], {}), '(sequences[key], distances[key])\n', (11605, 11637), False, 'from edit_distance.task.dataset import EditDistanceDatasetSampled, EditDistanceDatasetComplete, EditDistanceDatasetSampledCalculated\n'), ((12334, 12403), 'edit_distance.task.dataset.EditDistanceDatasetCompleteCalculated', 'EditDistanceDatasetCompleteCalculated', (['sequences[key]', 'distances[key]'], {}), '(sequences[key], distances[key])\n', (12371, 12403), False, 'from edit_distance.task.dataset import EditDistanceDatasetCompleteCalculated\n'), ((14248, 14268), 'util.ml_and_math.loss_functions.MAPE', 'MAPE', (['output', 'labels'], {}), '(output, labels)\n', (14252, 14268), False, 'from util.ml_and_math.loss_functions import MAPE\n'), ((8079, 8090), 'time.time', 'time.time', ([], {}), '()\n', (8088, 8090), False, 'import time\n'), ((17055, 17066), 'time.time', 'time.time', ([], {}), '()\n', (17064, 17066), False, 'import time\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 01 14:01:01 2016
Copyright (c) 2013-2016, CEA/DSV/I2BM/Neurospin. All rights reserved.
@author: <NAME>
@email: <EMAIL>
@license: BSD 3-clause.
"""
import unittest
import numpy as np
from tests import TestCase
import simulate.beta as beta
import simulate.utils as utils
class TestBeta(TestCase):
def test_beta(self):
rs = np.random.RandomState(42)
rng01 = utils.RandomUniform(0, 1, random_state=rs)
x = np.array([[0.0],
[0.0],
[0.0],
[0.0],
[0.0],
[0.15601864],
[0.37454012],
[0.59865848],
[0.73199394],
[0.95071431]])
x2 = beta.random((10, 1), density=0.5, rng=rng01, sort=True,
normalise=False)
assert(np.linalg.norm(x - x2) < utils.TOLERANCE)
rs = np.random.RandomState(1337)
rng11 = utils.RandomUniform(-1, 1, random_state=rs)
x = np.array([[0.0],
[-0.24365074],
[0.02503597],
[-0.0553771],
[-0.3239276],
[-0.46459304],
[0.64803846],
[-0.30201006],
[0.0],
[-0.32403887]])
x2 = beta.random((10, 1), density=0.75, rng=rng11, sort=False,
normalise=True)
assert(np.linalg.norm(x - x2) < utils.TOLERANCE)
assert(abs(np.linalg.norm(x2) - 1) < utils.TOLERANCE)
if __name__ == '__main__':
import doctest
doctest.testmod()
unittest.main()
| [
"simulate.utils.RandomUniform",
"numpy.array",
"doctest.testmod",
"numpy.linalg.norm",
"unittest.main",
"simulate.beta.random",
"numpy.random.RandomState"
] | [((1712, 1729), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (1727, 1729), False, 'import doctest\n'), ((1734, 1749), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1747, 1749), False, 'import unittest\n'), ((391, 416), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (412, 416), True, 'import numpy as np\n'), ((433, 475), 'simulate.utils.RandomUniform', 'utils.RandomUniform', (['(0)', '(1)'], {'random_state': 'rs'}), '(0, 1, random_state=rs)\n', (452, 475), True, 'import simulate.utils as utils\n'), ((489, 609), 'numpy.array', 'np.array', (['[[0.0], [0.0], [0.0], [0.0], [0.0], [0.15601864], [0.37454012], [0.59865848\n ], [0.73199394], [0.95071431]]'], {}), '([[0.0], [0.0], [0.0], [0.0], [0.0], [0.15601864], [0.37454012], [\n 0.59865848], [0.73199394], [0.95071431]])\n', (497, 609), True, 'import numpy as np\n'), ((817, 889), 'simulate.beta.random', 'beta.random', (['(10, 1)'], {'density': '(0.5)', 'rng': 'rng01', 'sort': '(True)', 'normalise': '(False)'}), '((10, 1), density=0.5, rng=rng01, sort=True, normalise=False)\n', (828, 889), True, 'import simulate.beta as beta\n'), ((987, 1014), 'numpy.random.RandomState', 'np.random.RandomState', (['(1337)'], {}), '(1337)\n', (1008, 1014), True, 'import numpy as np\n'), ((1031, 1074), 'simulate.utils.RandomUniform', 'utils.RandomUniform', (['(-1)', '(1)'], {'random_state': 'rs'}), '(-1, 1, random_state=rs)\n', (1050, 1074), True, 'import simulate.utils as utils\n'), ((1088, 1233), 'numpy.array', 'np.array', (['[[0.0], [-0.24365074], [0.02503597], [-0.0553771], [-0.3239276], [-\n 0.46459304], [0.64803846], [-0.30201006], [0.0], [-0.32403887]]'], {}), '([[0.0], [-0.24365074], [0.02503597], [-0.0553771], [-0.3239276], [\n -0.46459304], [0.64803846], [-0.30201006], [0.0], [-0.32403887]])\n', (1096, 1233), True, 'import numpy as np\n'), ((1441, 1514), 'simulate.beta.random', 'beta.random', (['(10, 1)'], {'density': '(0.75)', 'rng': 'rng11', 'sort': '(False)', 'normalise': '(True)'}), '((10, 1), density=0.75, rng=rng11, sort=False, normalise=True)\n', (1452, 1514), True, 'import simulate.beta as beta\n'), ((931, 953), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - x2)'], {}), '(x - x2)\n', (945, 953), True, 'import numpy as np\n'), ((1556, 1578), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - x2)'], {}), '(x - x2)\n', (1570, 1578), True, 'import numpy as np\n'), ((1617, 1635), 'numpy.linalg.norm', 'np.linalg.norm', (['x2'], {}), '(x2)\n', (1631, 1635), True, 'import numpy as np\n')] |
import numpy as np
from scipy.special import logsumexp, gammaln
from astropy import constants, units as au
from astropy.units import Quantity
Gauss = 1e-4 * au.T
au.set_enabled_equivalencies(au.dimensionless_angles())
def pad_with_absorbing_boundary_conditions(k2, k02, N, *coords, dn_max=0.05):
if dn_max is None:
dn_max = np.max(np.abs(np.sqrt(k2 / k02) - 1.))
print("Using the dn_max={}".format(dn_max))
alpha = np.abs(dn_max)*np.sqrt(k02)#/(np.pi*2.)
l = N / alpha
print("Extinction alpha={}".format(alpha))
print("Extinction l={}".format(l))
def log_Pn(alpha, x, N):
log_res = -np.inf
for n in range(N + 1):
log_res = np.logaddexp(n * (np.log(alpha * x)) - gammaln(n + 1.), log_res)
return np.where(x > 0, log_res, 0.)
def evaluate_k2(alpha, x):
k2 = k02 + alpha**2 - 2j*alpha*np.sqrt(k02)
return k02*np.ones(x.shape)
def _evaluate_k2(alpha, x, N):
return alpha**2 * np.exp(np.log(N - alpha * x + 2j * np.sqrt(k02) * x) + (N - 1) * (np.log(alpha * x))
- log_Pn(alpha, x, N) - gammaln(N + 1.)) + k02
def _add_other_dims(v, shape, i):
"""
[
Args:
v: [D]
shape: (s0,s1,s2,...)
i: int
Returns: same shape as `shape` except ith dim which is D.
"""
dims = list(range(len(shape)))
del dims[i]
v = np.expand_dims(v, dims)
grow = list(shape)
grow[i] = 1
return np.tile(v,grow)
m = []
out_coords = []
for i,x in enumerate(coords):
dx = x[1] - x[0]
M = int(l / dx) + 1
m.append(M)
print("Dimension {} padded by {}".format(i, M))
x_pad = np.arange(1,M+1)*dx
k2_pad = evaluate_k2(alpha, x_pad)
k2_before = _add_other_dims(k2_pad[::-1], k2.shape, i)
k2_after = _add_other_dims(k2_pad, k2.shape, i)
k2 = np.concatenate([k2_before, k2, k2_after], axis=i)
x_out = np.concatenate([x[0] - np.arange(1,M+1)[::-1]*dx, x, x[-1]+np.arange(1,M+1)*dx])
out_coords.append(x_out)
return k2, m, tuple(out_coords)
def pad_with_vacuum_conditions(k2, k02, pad_size, *coords):
def evaluate_k2(x):
return k02*np.ones(x.shape)
def _add_other_dims(v, shape, i):
"""
[
Args:
v: [D]
shape: (s0,s1,s2,...)
i: int
Returns: same shape as `shape` except ith dim which is D.
"""
dims = list(range(len(shape)))
del dims[i]
v = np.expand_dims(v, dims)
grow = list(shape)
grow[i] = 1
return np.tile(v,grow)
m = []
out_coords = []
for i,x in enumerate(coords):
print("Dimension {} padded by {}".format(i, pad_size))
dx = x[1] - x[0]
x_pad = np.arange(1,pad_size+1)*dx
k2_pad = evaluate_k2(x_pad)
m.append(pad_size)
k2_before = _add_other_dims(k2_pad[::-1], k2.shape, i)
k2_after = _add_other_dims(k2_pad, k2.shape, i)
k2 = np.concatenate([k2_before, k2, k2_after], axis=i)
x_out = np.concatenate([x[0] - np.arange(1,pad_size+1)[::-1]*dx, x, x[-1]+np.arange(1, pad_size+1)*dx])
out_coords.append(x_out)
return k2, m, tuple(out_coords)
def appleton_hartree(ne, nu):
def _plasma_freqency_squared(fed):
omega_p_squared = fed * (constants.e.si ** 2 / constants.eps0 / constants.m_e)
return omega_p_squared
omega_0_squared = _plasma_freqency_squared(ne)
dn = omega_0_squared / (2 * np.pi * nu) ** 2
return 1. - dn
def partial_blockage(N, nu, sinusoidal_blockage=False):
"""
| * source
|
| _________________
| | n = 1 - dn
| |________________
|
|
| x receiver
|(0,0)
Args:
x:
z:
nu:
Returns:
"""
ne = 2e12 / au.m ** 3
wavelength = constants.c.si / nu
x = np.arange(-N//2, N-N//2,1) * 0.25 * wavelength
z = np.arange(-N//2, N-N//2,1) * 0.25 * wavelength
n_ionosphere = appleton_hartree(ne, nu)
k0 = 2. * np.pi / wavelength
X, Z = np.meshgrid(x, z, indexing='ij')
z_bar_bottom = z.min() + 0.5 * (z.max() - z.min())
z_bar_top = z_bar_bottom + 10. * wavelength
x_bar_left = x.min() + 0. * (x.max() - x.min())
where_bar = (X > x_bar_left) & (Z > z_bar_bottom) & (Z < z_bar_top)
if sinusoidal_blockage:
refractive_index = np.where(where_bar, 1. - (1. - n_ionosphere) * np.cos(2 * np.pi * X / (10. * wavelength)),
1.)
else:
refractive_index = np.where(where_bar, n_ionosphere, 1.)
k2 = 4. * np.pi ** 2 * refractive_index ** 2 / wavelength ** 2
return x, z, k2, k0 ** 2
def single_blob(N, nu, l):
"""
| * source
|
| _________________
| | n = 1 - dn
| |________________
|
|
| x receiver
|(0,0)
Args:
x:
z:
nu:
Returns:
"""
ne = 2e12 / au.m ** 3
wavelength = constants.c.si / nu
x = np.arange(-N//2, N-N//2,1) * 0.25 * wavelength
z = np.arange(-N//2, N-N//2,1) * 0.25 * wavelength
n_ionosphere = appleton_hartree(ne, nu)
k0 = 2. * np.pi / wavelength
X, Z = np.meshgrid(x, z, indexing='ij')
z_blob = z.min() + 0.5 * (z.max() - z.min())
x_blob = x.min() + 0.5 * (x.max() - x.min())
refractive_index = (n_ionosphere - 1) * np.exp(-0.5*((X-x_blob)**2 + (Z-z_blob)**2)/l**2) + 1.
k2 = 4. * np.pi ** 2 * refractive_index ** 2 / wavelength ** 2
return x, z, k2, k0 ** 2
def test_partial_blockage():
import pylab as plt
nu = 100e6 / au.s
N = 1000
x, z, k2, k02 = partial_blockage(N, nu)
scattering_potential = k2 - k02
plt.imshow(scattering_potential.T.value, interpolation='nearest', origin='lower',
extent=(x.min().value, x.max().value, z.min().value, z.max().value),
cmap='bone')
plt.title(r'Partial blockage potential ($k^2(\mathbf{{x}}) - k_0^2$) at {}'.format(nu.to(au.MHz)))
plt.colorbar(label='potential [{}]'.format(scattering_potential.unit))
plt.show()
x, z, k2, k02 = partial_blockage(N, nu, sinusoidal_blockage=True)
scattering_potential = k2 - k02
plt.imshow(scattering_potential.T.value, interpolation='nearest', origin='lower',
extent=(x.min().value, x.max().value, z.min().value, z.max().value),
cmap='bone')
plt.title(r'Sinusoidal partial blockage potential ($k^2(\mathbf{{x}}) - k_0^2$) at {}'.format(nu.to(au.MHz)))
plt.colorbar(label='potential [{}]'.format(scattering_potential.unit))
plt.show()
k2, m, (x,z) = pad_with_absorbing_boundary_conditions(k2, k02, 4, x, z, dn_max=0.01)
scattering_potential = k2 - k02
plt.imshow(np.abs(scattering_potential.T.value), interpolation='nearest', origin='lower',
extent=(x.min().value, x.max().value, z.min().value, z.max().value),
cmap='bone')
print(x)
plt.plot(Quantity([x[m[0]], x[-m[0]], x[-m[0]], x[m[0]], x[m[0]]]).value, Quantity([z[m[1]], z[m[1]],z[-m[1]],z[-m[1]],z[m[1]]]).value, c='red')
plt.title(r'Sinusoidal partial blockage potential ($k^2(\mathbf{{x}}) - k_0^2$) at {} with boundary'.format(nu.to(au.MHz)))
plt.colorbar(label='potential [{}]'.format(scattering_potential.unit))
plt.show()
| [
"numpy.abs",
"numpy.tile",
"astropy.units.Quantity",
"numpy.sqrt",
"numpy.ones",
"scipy.special.gammaln",
"numpy.where",
"numpy.log",
"numpy.exp",
"astropy.units.dimensionless_angles",
"numpy.cos",
"numpy.expand_dims",
"numpy.concatenate",
"numpy.meshgrid",
"numpy.arange",
"pylab.show"... | [((192, 217), 'astropy.units.dimensionless_angles', 'au.dimensionless_angles', ([], {}), '()\n', (215, 217), True, 'from astropy import constants, units as au\n'), ((4153, 4185), 'numpy.meshgrid', 'np.meshgrid', (['x', 'z'], {'indexing': '"""ij"""'}), "(x, z, indexing='ij')\n", (4164, 4185), True, 'import numpy as np\n'), ((5281, 5313), 'numpy.meshgrid', 'np.meshgrid', (['x', 'z'], {'indexing': '"""ij"""'}), "(x, z, indexing='ij')\n", (5292, 5313), True, 'import numpy as np\n'), ((6162, 6172), 'pylab.show', 'plt.show', ([], {}), '()\n', (6170, 6172), True, 'import pylab as plt\n'), ((6672, 6682), 'pylab.show', 'plt.show', ([], {}), '()\n', (6680, 6682), True, 'import pylab as plt\n'), ((7385, 7395), 'pylab.show', 'plt.show', ([], {}), '()\n', (7393, 7395), True, 'import pylab as plt\n'), ((442, 456), 'numpy.abs', 'np.abs', (['dn_max'], {}), '(dn_max)\n', (448, 456), True, 'import numpy as np\n'), ((457, 469), 'numpy.sqrt', 'np.sqrt', (['k02'], {}), '(k02)\n', (464, 469), True, 'import numpy as np\n'), ((775, 804), 'numpy.where', 'np.where', (['(x > 0)', 'log_res', '(0.0)'], {}), '(x > 0, log_res, 0.0)\n', (783, 804), True, 'import numpy as np\n'), ((1438, 1461), 'numpy.expand_dims', 'np.expand_dims', (['v', 'dims'], {}), '(v, dims)\n', (1452, 1461), True, 'import numpy as np\n'), ((1524, 1540), 'numpy.tile', 'np.tile', (['v', 'grow'], {}), '(v, grow)\n', (1531, 1540), True, 'import numpy as np\n'), ((1945, 1994), 'numpy.concatenate', 'np.concatenate', (['[k2_before, k2, k2_after]'], {'axis': 'i'}), '([k2_before, k2, k2_after], axis=i)\n', (1959, 1994), True, 'import numpy as np\n'), ((2583, 2606), 'numpy.expand_dims', 'np.expand_dims', (['v', 'dims'], {}), '(v, dims)\n', (2597, 2606), True, 'import numpy as np\n'), ((2669, 2685), 'numpy.tile', 'np.tile', (['v', 'grow'], {}), '(v, grow)\n', (2676, 2685), True, 'import numpy as np\n'), ((3076, 3125), 'numpy.concatenate', 'np.concatenate', (['[k2_before, k2, k2_after]'], {'axis': 'i'}), '([k2_before, k2, k2_after], axis=i)\n', (3090, 3125), True, 'import numpy as np\n'), ((4638, 4676), 'numpy.where', 'np.where', (['where_bar', 'n_ionosphere', '(1.0)'], {}), '(where_bar, n_ionosphere, 1.0)\n', (4646, 4676), True, 'import numpy as np\n'), ((6825, 6861), 'numpy.abs', 'np.abs', (['scattering_potential.T.value'], {}), '(scattering_potential.T.value)\n', (6831, 6861), True, 'import numpy as np\n'), ((907, 923), 'numpy.ones', 'np.ones', (['x.shape'], {}), '(x.shape)\n', (914, 923), True, 'import numpy as np\n'), ((1750, 1769), 'numpy.arange', 'np.arange', (['(1)', '(M + 1)'], {}), '(1, M + 1)\n', (1759, 1769), True, 'import numpy as np\n'), ((2268, 2284), 'numpy.ones', 'np.ones', (['x.shape'], {}), '(x.shape)\n', (2275, 2284), True, 'import numpy as np\n'), ((2854, 2880), 'numpy.arange', 'np.arange', (['(1)', '(pad_size + 1)'], {}), '(1, pad_size + 1)\n', (2863, 2880), True, 'import numpy as np\n'), ((3961, 3994), 'numpy.arange', 'np.arange', (['(-N // 2)', '(N - N // 2)', '(1)'], {}), '(-N // 2, N - N // 2, 1)\n', (3970, 3994), True, 'import numpy as np\n'), ((4016, 4049), 'numpy.arange', 'np.arange', (['(-N // 2)', '(N - N // 2)', '(1)'], {}), '(-N // 2, N - N // 2, 1)\n', (4025, 4049), True, 'import numpy as np\n'), ((5089, 5122), 'numpy.arange', 'np.arange', (['(-N // 2)', '(N - N // 2)', '(1)'], {}), '(-N // 2, N - N // 2, 1)\n', (5098, 5122), True, 'import numpy as np\n'), ((5144, 5177), 'numpy.arange', 'np.arange', (['(-N // 2)', '(N - N // 2)', '(1)'], {}), '(-N // 2, N - N // 2, 1)\n', (5153, 5177), True, 'import numpy as np\n'), ((5458, 5521), 'numpy.exp', 'np.exp', (['(-0.5 * ((X - x_blob) ** 2 + (Z - z_blob) ** 2) / l ** 2)'], {}), '(-0.5 * ((X - x_blob) ** 2 + (Z - z_blob) ** 2) / l ** 2)\n', (5464, 5521), True, 'import numpy as np\n'), ((7042, 7099), 'astropy.units.Quantity', 'Quantity', (['[x[m[0]], x[-m[0]], x[-m[0]], x[m[0]], x[m[0]]]'], {}), '([x[m[0]], x[-m[0]], x[-m[0]], x[m[0]], x[m[0]]])\n', (7050, 7099), False, 'from astropy.units import Quantity\n'), ((7107, 7164), 'astropy.units.Quantity', 'Quantity', (['[z[m[1]], z[m[1]], z[-m[1]], z[-m[1]], z[m[1]]]'], {}), '([z[m[1]], z[m[1]], z[-m[1]], z[-m[1]], z[m[1]]])\n', (7115, 7164), False, 'from astropy.units import Quantity\n'), ((875, 887), 'numpy.sqrt', 'np.sqrt', (['k02'], {}), '(k02)\n', (882, 887), True, 'import numpy as np\n'), ((353, 370), 'numpy.sqrt', 'np.sqrt', (['(k2 / k02)'], {}), '(k2 / k02)\n', (360, 370), True, 'import numpy as np\n'), ((734, 750), 'scipy.special.gammaln', 'gammaln', (['(n + 1.0)'], {}), '(n + 1.0)\n', (741, 750), False, 'from scipy.special import logsumexp, gammaln\n'), ((4517, 4560), 'numpy.cos', 'np.cos', (['(2 * np.pi * X / (10.0 * wavelength))'], {}), '(2 * np.pi * X / (10.0 * wavelength))\n', (4523, 4560), True, 'import numpy as np\n'), ((713, 730), 'numpy.log', 'np.log', (['(alpha * x)'], {}), '(alpha * x)\n', (719, 730), True, 'import numpy as np\n'), ((1117, 1133), 'scipy.special.gammaln', 'gammaln', (['(N + 1.0)'], {}), '(N + 1.0)\n', (1124, 1133), False, 'from scipy.special import logsumexp, gammaln\n'), ((2070, 2089), 'numpy.arange', 'np.arange', (['(1)', '(M + 1)'], {}), '(1, M + 1)\n', (2079, 2089), True, 'import numpy as np\n'), ((3208, 3234), 'numpy.arange', 'np.arange', (['(1)', '(pad_size + 1)'], {}), '(1, pad_size + 1)\n', (3217, 3234), True, 'import numpy as np\n'), ((2034, 2053), 'numpy.arange', 'np.arange', (['(1)', '(M + 1)'], {}), '(1, M + 1)\n', (2043, 2053), True, 'import numpy as np\n'), ((3165, 3191), 'numpy.arange', 'np.arange', (['(1)', '(pad_size + 1)'], {}), '(1, pad_size + 1)\n', (3174, 3191), True, 'import numpy as np\n'), ((1052, 1069), 'numpy.log', 'np.log', (['(alpha * x)'], {}), '(alpha * x)\n', (1058, 1069), True, 'import numpy as np\n'), ((1021, 1033), 'numpy.sqrt', 'np.sqrt', (['k02'], {}), '(k02)\n', (1028, 1033), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
"""
Investigate DSC data.
Created on Fri Sep 13 12:44:01 2019
@author: slevy
"""
import dsc_extract_physio
import nibabel as nib
import numpy as np
import os
import matplotlib.pyplot as plt
import scipy.signal
import scipy.stats
import pydicom
from matplotlib import cm
from lmfit.models import GaussianModel
from datetime import datetime
import warnings
def extract_signal_within_roi(image, mask):
if len(image.shape) > 3:
nrep = image.shape[3]
s_along_reps = np.zeros((nrep))
s_along_reps_by_slice = np.zeros((nrep, image.shape[2]))
for i_rep in range(nrep):
img_rep_i = image[:, :, :, i_rep]
s_along_reps[i_rep] = np.mean(img_rep_i[mask > 0])
for i_z in range(image.shape[2]):
s_along_reps_by_slice[i_rep, i_z] = np.mean(img_rep_i[mask[:, :, i_z] > 0, i_z])
return s_along_reps, s_along_reps_by_slice
else:
s_whole_mask = np.mean(image[mask > 0])
s_by_slice = np.zeros((image.shape[2]))
for i_z in range(image.shape[2]):
s_by_slice[i_z] = np.mean(image[mask[:, :, i_z] > 0, i_z])
return s_whole_mask, s_by_slice
# def detect_outliers(signal, time):
#
# # thresholds for detection
# sd_t = np.std(signal[1:]) # first point is always outlier
# mean_baseline = np.mean(signal[0, 1:12])
#
#
# # find outliers =================================================================================
# signal_reptimes = np.vstack((s_along_reps, reps_acqtime))
# signal_reptimes_outliers = np.zeros((2, 1))
# signal_reptimes_outliers[:, 0] = signal_reptimes[:, 0] # save the first point as outlier because it is always corrupted in those data
# signal_reptimes_without_outliers = signal_reptimes[:, 1:] # remove the first point which is always corrupted with this sequence
#
# # if above 3 standard-deviation it is an outlier
# idx_outliers = np.where(np.abs(signal_reptimes_without_outliers[0, :] - mean_baseline) >= 3*sd_t) # find indexes of outliers
# signal_reptimes_outliers = np.hstack((signal_reptimes_outliers, signal_reptimes_without_outliers[:, idx_outliers[0]])) # save the detected outliers
# signal_reptimes_without_outliers = np.delete(signal_reptimes_without_outliers, idx_outliers, axis=1) # remove the outliers
# # by slice
# s_along_reps_by_slice = np.delete(s_along_reps_by_slice, 0, axis=0) # first point is always outlier
# sd_t_by_slice = np.std(s_along_reps_by_slice, axis=0) # temporal SD for each slice
# s_along_reps_by_slice_without_outliers = [] # [[signal, acqtimes], [,], [,] ]
# for i_z in range(dsc.shape[2]):
# idx_outliers_z_i = np.where(np.abs(s_along_reps_by_slice[:, i_z] - np.mean(s_along_reps_by_slice[0:11, i_z])) >= 3 * sd_t_by_slice[i_z]) # find indexes of outliers
# s_along_reps_by_slice_without_outliers.append([np.delete(s_along_reps_by_slice[:, i_z], idx_outliers_z_i), np.delete(signal_reptimes[1, 1:], idx_outliers_z_i)])
#
# return idx_outliers, signal_without_outliers, signal_outliers, time_without_outliers_time_outliers
def smooth_signal(signal, baseline_nb=10, windowLength=23, outPlotFname=''):
"""
Smooth signal.
:param signal: MRI signal, already regridded to a regular sampling
:param time:
:param baseline_nb:
:param increase_res_factor:
:return:
"""
# first point is always an outlier (and a NaN actually because of the TReff normalization)
# --> replace it by the mean signal at baseline
signal[0] = np.mean(signal[1:baseline_nb])
# # interpolate signal on regular grid
# t_regular_sampling = np.linspace(np.min(time), np.max(time), increase_res_factor * len(time))
# signal_interp = np.interp(t_regular_sampling, time, signal)
# replace
# signal_interp_smoothed = scipy.signal.savgol_filter(signal_interp, window_length=25, polyorder=3)
signal_smoothed = scipy.signal.savgol_filter(signal, window_length=windowLength, polyorder=5, mode='constant', cval=signal[0])
if outPlotFname:
# plot results
fig, ((ax1)) = plt.subplots(1, 1, figsize=(20, 9.5))
ax1.set_title('Final signal smoothing')
ax1.set_xlabel('Points')
ax1.plot(np.arange(signal.size), signal, label='original signal', color='black', lw=0.3, marker='+')
ax1.plot(np.arange(signal.size), signal_smoothed, label='smoothed signal', color='tab:blue', lw=0.3, marker='o', fillstyle='none')
ax1.legend()
ax1.grid()
fig.savefig(outPlotFname)
plt.close()
return signal_smoothed
def smoothlyCropSignal(mriSignalRegrid, firstPassStartRepRegrid, firstPassEndRepRegrid, injRepRegrid, outPlotFname=''):
"""
:param mriSignalRegrid:
:param baselineLastRepRegrid:
:param firstPassEndRepRegrid:
:param outPlotFname:
:return: mriSignalCropSmooth: signal cropped before first pass start and after first pass end with smooth transitions
mriSignalCropEndSmooth_forAIF: signal cropped only after half time of first pass (start time + (end time -
start time)/2) with smooth transition, to be used for AIF detection
"""
# calculate the baseline before and after contrast agent first pass
baselineBefore = np.mean(mriSignalRegrid[0:firstPassStartRepRegrid])
baselineAfter = np.mean(mriSignalRegrid[firstPassEndRepRegrid:-1])
# replace them in original signal
mriSignalCrop = np.copy(mriSignalRegrid)
mriSignalCrop[0:firstPassStartRepRegrid] = baselineBefore
mriSignalCrop[firstPassEndRepRegrid:-1] = baselineAfter
# crop larger for AIF detection
mriSignalCropEnd_forAIF = np.copy(mriSignalRegrid)
firstPassMiddleRep = int(np.ceil(firstPassStartRepRegrid + (firstPassEndRepRegrid - firstPassStartRepRegrid)/2))
mriSignalCropEnd_forAIF[0:injRepRegrid] = baselineBefore
mriSignalCropEnd_forAIF[firstPassMiddleRep:-1] = baselineAfter
# smooth whole signal to avoid sharp transitions
mriSignalCropSmooth = scipy.signal.savgol_filter(mriSignalCrop, window_length=25, polyorder=3, mode='nearest')
mriSignalCropEndSmooth_forAIF = scipy.signal.savgol_filter(mriSignalCropEnd_forAIF, window_length=25, polyorder=3, mode='nearest')
if outPlotFname:
# plot results
fig, ((ax1, ax2)) = plt.subplots(2, 1, figsize=(20, 9.5))
ax1.set_title('Final smooth & crop of signal')
ax1.set_xlabel('Points')
ax1.plot(np.arange(mriSignalRegrid.size), mriSignalRegrid, label='original signal', color='black', lw=0.7, marker='+')
ax1.plot(np.arange(mriSignalRegrid.size), mriSignalCrop, label='cropped signal', color='tab:blue', lw=0.7, marker='.')
ax1.plot(np.arange(mriSignalRegrid.size), mriSignalCropSmooth, label='smoothly cropped signal', color='tab:red', lw=0.7, marker='.')
ax1.axvline(x=firstPassStartRepRegrid, label='first pass start', color='green', lw=1)
ax1.axvline(x=firstPassEndRepRegrid, label='first pass end', color='red', lw=1)
ax1.legend()
ax1.grid()
ax2.set_title('Final smooth & crop of signal for AIF detection')
ax2.set_xlabel('Points')
ax2.plot(np.arange(mriSignalRegrid.size), mriSignalRegrid, label='original signal', color='black', lw=0.7, marker='+')
ax2.plot(np.arange(mriSignalRegrid.size), mriSignalCropEnd_forAIF, label='cropped signal', color='tab:blue', lw=0.7, marker='.')
ax2.plot(np.arange(mriSignalRegrid.size), mriSignalCropEndSmooth_forAIF, label='smoothly cropped signal', color='tab:red', lw=0.7, marker='.')
ax2.axvline(x=firstPassStartRepRegrid, label='first pass start', color='green', lw=1)
ax2.axvline(x=firstPassEndRepRegrid, label='first pass end', color='red', lw=1)
ax2.axvline(x=firstPassMiddleRep, label='first pass middle', color='orange', lw=1)
ax2.legend()
ax2.grid()
fig.savefig(outPlotFname)
plt.close()
return mriSignalCropSmooth, mriSignalCropEndSmooth_forAIF
def plot_signal_vs_TReff(effTR, signal, time, ofname=''):
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(20, 9.7))
ax1.set_xlabel('Effective TR (ms)')
ax1.set_ylabel('Signal')
ax1.set_title("Signal vs effective TR: (Pearson\'s R, p-value)={}".format(tuple(np.round(scipy.stats.pearsonr(effTR[1:], signal[1:]), decimals=4))))
ax1.grid(which='both')
ax1.plot(effTR, signal, linewidth=0, marker='+', markersize=5.0)
ax2.set_xlabel('$1 - e^{-TR_{eff}/T_{1}} (TR_{eff}\\ in\\ ms)$')
ax2.set_ylabel('Signal')
pearsonr, pval = scipy.stats.pearsonr(1 - np.exp(-effTR[1:]/1251.0), signal[1:])
ax2.set_title("Signal vs $1 - e^{-TR_{eff}/T_{1}}$: (Pearson\'s R, p-value)=(%.4f, %.4f)" % (pearsonr, pval))
ax2.grid(which='both')
ax2.plot(1 - np.exp(-effTR/1251.0), signal, linewidth=0, marker='+', markersize=5.0)
ax3.set_xlabel('Time (ms)')
ax3.set_ylabel('Signal')
ax3.set_title("Signal and effective TR vs time")
ax3.grid(which='both')
ax3.plot(time/1000, signal, linewidth=1.0, marker='+', markersize=7.0)
ax3_effTR = ax3.twinx()
ax3_effTR.plot(time/1000, effTR, linewidth=1.0, marker='+', markersize=7.0, color='orange')
ax3_effTR.tick_params(axis='y', labelcolor='orange')
ax3_exp_effTR = ax3.twinx()
ax3_exp_effTR.plot(time/1000, 1 - np.exp(-effTR/1251.0), linewidth=1.0, marker='+', markersize=7.0, color='green')
ax3_exp_effTR.tick_params(axis='y', labelcolor='green')
ax4.set_xlabel('Time (ms)')
ax4.set_ylabel('Signal', color='green')
ax4.set_title("Signal vs time")
ax4.grid(which='both')
signal_norm_exp = np.divide(signal, (1 - np.exp(-effTR/1251.0)))
ax4.plot(time/1000, signal_norm_exp, linewidth=1, marker='+', markersize=7.0, color='green', label='norm by $1 - e^{-TR_{eff}/T_{1}}$: COV='+str(round(100*np.std(signal_norm_exp[1:])/np.mean(signal_norm_exp[1:]), 2))+'%')
ax4.tick_params(axis='y', color='green')
ax4.legend(loc="lower left")
ax4_effTR = ax4.twinx()
signal_norm_TR = np.divide(signal, effTR)
ax4_effTR.plot(time/1000, signal_norm_TR, linewidth=1, marker='+', markersize=7.0, color='orange', label='norm by $TR_{eff}$: COV='+str(round(100*np.std(signal_norm_TR[1:])/np.mean(signal_norm_TR[1:]), 2))+'%')
ax4_effTR.set_ylabel('Signal', color='orange')
ax4_effTR.tick_params(axis='y', color='orange')
ax4_effTR.legend(loc="lower right")
ax4_rawsignal = ax4.twinx()
ax4_rawsignal.plot(time/1000, signal, linewidth=1, marker='+', markersize=7.0, color='blue', label='raw signal: COV='+str(round(100*np.std(signal[1:])/np.mean(signal[1:]), 2))+'%')
ax4_rawsignal.set_ylabel('Signal', color='blue')
ax4_rawsignal.tick_params(axis='y', color='blue')
ax4_rawsignal.legend(loc="upper right")
plt.show(block=True)
if ofname:
fig.savefig(ofname+'_signal_vs_TReff.png')
def plot_signal_vs_time(time, signal, time_interp, signal_interp, signal_smoothed, signal_by_slice_smoothed, ofname='', baseline_nb=50):
fig, (axtime, axtime_norm) = plt.subplots(1, 2, figsize=(20, 9.5))
plt.subplots_adjust(wspace=0.2, left=0.05, right=0.95)
axtime.set_xlabel('Time (s)')
axtime.set_ylabel('Signal')
axtime.grid(which='both')
axtime.plot(time/1000., signal, marker='+', linewidth=0.2, color='black', label='raw signal')
# baseline and injection
axtime.axvline(x=time[baseline_nb+1]/1000, linestyle='-', label='injection', color='red', linewidth=1.0)
axtime.axhline(y=np.mean(signal[0:baseline_nb]), linestyle='-', label='baseline', color='gray', alpha=0.7, linewidth=3.0)
axtime.legend()
# display repetition numbers on top x-axis
time_ticks_locs = axtime.get_xticks()
reps_nb_interp_to_time_ticks_locs = np.interp(time_ticks_locs, time / 1000, range(len(time)))
axreps = axtime.twiny()
axreps.plot(time/1000., signal, marker='', linewidth=0) # fake plot to get the same x-axis
axreps.set_xticklabels(np.round(reps_nb_interp_to_time_ticks_locs, decimals=0).astype(int))
axreps.set_xlabel('Repetition number')
# add effective TR
axTR = axtime.twinx()
axTR.plot(time / 1000, np.append(np.nan, np.diff(time)), color='orange', linewidth=0.8, label='effective TR')
axTR.set_ylabel('Effective TR (ms)', color='orange')
axTR.tick_params(axis='y', labelcolor='orange')
# plot normalized signal
axtime_norm.set_xlabel('Time (s)')
axtime_norm.set_ylabel('Signal')
axtime_norm.grid(which='both')
axtime_norm.plot(time_interp/1000., signal_interp, linestyle='-', color='gray', alpha=0.7, label='S$_{inter}$')
axtime_norm.plot(time_interp/1000., signal_smoothed, linestyle='-', color='green', label='S$_{smoothed}$')
# plt.plot(signal_reptimes_outliers[1, :]/1000., signal_reptimes_outliers[0, :], marker='+', linewidth=0., color='red', label='outliers')
# plot by slice
colors = [cm.jet(slc) for slc in np.linspace(0.0, 1.0, signal_by_slice_smoothed.shape[1])]
for iz, color in enumerate(colors):
axtime_norm.plot(time/1000., signal_by_slice_smoothed[:, iz], label="z="+str(iz), color=color, lw=1, marker='.', ms=2.)
axtime_norm.axvline(x=time[baseline_nb+1]/1000, linestyle='-', label='injection', color='red', linewidth=1.0)
axtime_norm.legend()
# # plot physio on the same graph but different scale
# ax_physio = plt.gca().twinx()
# ax_physio.plot(time/1000., physio_values, marker=None, color='cyan', label='pulseOx')
if ofname:
fig.savefig(ofname+'_signal_vs_time.png')
def extract_acqtime_and_physio(log_fname, nrep_nii, physioplot_out_fname=''):
# pulseOx ----------------------------
if os.path.exists(log_fname+'.puls'):
time_puls, puls_values, epi_acqtime_puls, epi_event_puls, acq_window_puls = dsc_extract_physio.read_physiolog(log_fname+'.puls', sampling_period=20) # extract physio signal
reps_table_puls, slice_table_puls = dsc_extract_physio.sort_event_times(epi_acqtime_puls, epi_event_puls) # sort event times
if physioplot_out_fname:
dsc_extract_physio.plot_physio(time_puls, puls_values, epi_acqtime_puls, reps_table_puls, acq_window_puls, physioplot_out_fname+'_pulseOx') # plot physio signal
# calculate acquisition time for each rep
nrep_pulseOxLog = np.sum(reps_table_puls[:, 1])
if nrep_nii != nrep_pulseOxLog:
os.error('Number of repetitions in image is different from the number of repetitions recorded in pulseOx physiolog.')
reps_acqtime_pulseOx = np.squeeze(np.mean(slice_table_puls[np.where(reps_table_puls[:, 1] == 1), :], axis=2))
else:
reps_acqtime_pulseOx = 900*np.arange(0, nrep_nii)
time_puls = np.linspace(np.min(reps_acqtime_pulseOx), np.max(reps_acqtime_pulseOx), int((np.max(reps_acqtime_pulseOx) - np.min(reps_acqtime_pulseOx))/20000))
puls_values = None
# respiration ----------------------------
if os.path.exists(log_fname+'.resp'):
time_resp, resp_values, epi_acqtime_resp, epi_event_resp, acq_window_resp = dsc_extract_physio.read_physiolog(log_fname+'.resp', sampling_period=20) # extract physio signal
reps_table_resp, slice_table_resp = dsc_extract_physio.sort_event_times(epi_acqtime_resp, epi_event_resp) # sort event times
if physioplot_out_fname:
dsc_extract_physio.plot_physio(time_resp, resp_values, epi_acqtime_resp, reps_table_resp, acq_window_resp, physioplot_out_fname+'_resp') # plot physio signal
# calculate acquisition time for each rep
nrep_respLog = np.sum(reps_table_resp[:, 1])
if nrep_nii != nrep_respLog:
os.error('Number of repetitions in image is different from the number of repetitions recorded in respiration physiolog.')
reps_acqtime_resp = np.squeeze(np.mean(slice_table_resp[np.where(reps_table_resp[:, 1] == 1), :], axis=2))
else:
reps_acqtime_resp = 900*np.arange(0, nrep_nii)
time_resp = np.linspace(np.min(reps_acqtime_resp), np.max(reps_acqtime_resp), int((np.max(reps_acqtime_resp) - np.min(reps_acqtime_resp))/20000))
resp_values = None
return reps_acqtime_pulseOx, time_puls, puls_values, reps_acqtime_resp, time_resp, resp_values
def extract_acqtime_and_physio_by_slice(log_fname, nSlices, nAcqs, acqTime_firstImg, TR=1000):
"""
:param log_fname:
:param nSlices:
:param nAcqs:
:return: repsAcqTime: ((SC+all slices) x Nacq x (PulseOx, Resp)
timePhysio: N_pulseOx_points x ((PulseOx, Resp)
valuesPhysio: N_pulseOx_points x ((PulseOx, Resp)
"""
# repsAcqTime: ((SC+all slices) x Nacq x (PulseOx, Resp)
# timePhysio: N_pulseOx_points x ((PulseOx, Resp)
# valuesPhysio: N_pulseOx_points x ((PulseOx, Resp)
repsAcqTime = np.zeros((1+nSlices, nAcqs, 2))
# pulseOx ----------------------------
if os.path.exists(log_fname+'.puls'):
print('Processing pulseOx log: '+log_fname+'.puls')
if 'slr' in os.path.basename(log_fname):
print('\t[\'slr\'-type physiolog]')
time_puls, puls_values, epi_acqtime_puls, epi_event_puls, acq_window_puls = dsc_extract_physio.read_physiolog(log_fname+'.puls', sampling_period=20) # extract physio signal
reps_table_puls, slices_table_puls = dsc_extract_physio.sort_event_times(epi_acqtime_puls, epi_event_puls) # sort event times
nrep_pulseOxLog = np.sum(reps_table_puls[:, 1])
if nAcqs != nrep_pulseOxLog:
os.error('Number of repetitions in image is different from the number of repetitions recorded in pulseOx physiolog.')
# get acquisition time for each slice
repsAcqTime[1:, :, 0] = np.squeeze(slices_table_puls[np.where(reps_table_puls[:, 1] == 1), :]).T
else:
print('\t[\'CMRR\'-type physiolog]')
time_puls, trigger_start_times_puls, trigger_end_times_puls, puls_values, acq_window_puls, acqStartTime_puls = dsc_extract_physio.read_physiolog_cmrr(log_fname+'.puls')
triggerStartTimes_imgOnly_puls = dsc_extract_physio.extract_acqTimes_cmrr(trigger_start_times_puls, acqTime_firstImg, acqStartTime_puls, trigger_end_times_puls)
repsAcqTime[1:, :, 0] = np.tile(triggerStartTimes_imgOnly_puls, (nSlices, 1)) + np.tile(TR/nSlices * np.arange(0, nSlices), (nAcqs, 1)).T
else:
print('\nNo log found for pulseOx.')
repsAcqTime[1:, :, 0] = TR*np.tile(np.arange(0, nAcqs), (nSlices, 1)) + np.tile(TR/nSlices*np.arange(0, nSlices), (nAcqs, 1)).T
time_puls = np.arange(np.min(repsAcqTime), np.max(repsAcqTime), step=20)
puls_values = None
# take the mean acquisition time across slices for the whole rep (SC)
repsAcqTime[0, :, 0] = np.mean(repsAcqTime[1:nSlices, :, 0], axis=0)
# respiration ----------------------------
if os.path.exists(log_fname+'.resp'):
print('Processing respiration log: '+log_fname+'.resp')
if 'slr' in os.path.basename(log_fname):
print('\t[\'slr\'-type physiolog]')
time_resp, resp_values, epi_acqtime_resp, epi_event_resp, acq_window_resp = dsc_extract_physio.read_physiolog(log_fname+'.resp', sampling_period=20) # extract physio signal
reps_table_resp, slices_table_resp = dsc_extract_physio.sort_event_times(epi_acqtime_resp, epi_event_resp) # sort event times
nrep_respLog = np.sum(reps_table_resp[:, 1])
if nAcqs != nrep_respLog:
os.error('Number of repetitions in image is different from the number of repetitions recorded in respiration physiolog.')
# get acquisition time for each slice
repsAcqTime[1:, :, 1] = np.squeeze(slices_table_resp[np.where(reps_table_resp[:, 1] == 1), :]).T
else:
print('\t[\'CMRR\'-type physiolog]')
time_resp, trigger_start_times_resp, trigger_end_times_resp, resp_values, acq_window_resp, acqStartTime_resp = dsc_extract_physio.read_physiolog_cmrr(log_fname+'.resp')
else:
print('\nNo log found for respiration.\n')
repsAcqTime[1:, :, 1] = TR*np.tile(np.arange(0, nAcqs), (nSlices, 1)) + np.tile(TR/nSlices*np.arange(0, nSlices), (nAcqs, 1)).T
time_resp = np.arange(np.min(repsAcqTime), np.max(repsAcqTime), step=20)
resp_values = None
# take the mean acquisition time across slices for the whole rep (SC)
repsAcqTime[0, :, 1] = np.mean(repsAcqTime[1:nSlices, :, 1], axis=0)
# merge the two physiological signal into one array each (for time and physio values)
if time_puls.size > time_resp.size:
time_resp = np.hstack((time_resp, time_puls[time_resp.size:]))
resp_values = np.pad(resp_values, (0, puls_values.size - resp_values.size), 'reflect')
elif time_puls.size < time_resp.size:
time_puls = np.hstack((time_puls, time_resp[time_puls.size:]))
puls_values = np.pad(puls_values, (0, resp_values.size - puls_values.size), 'reflect')
timePhysio = np.vstack((time_puls, time_resp)).T
valuesPhysio = np.vstack((puls_values, resp_values)).T
return repsAcqTime, timePhysio, valuesPhysio
def plot_pulseOx_and_resp(pulseTime, pulseVal, pulseAcqTimes, respTime, respVal, respAcqTime, ofname=''):
fig, ((ax1)) = plt.subplots(1, 1, figsize=(20, 9.5))
ax1.plot(pulseTime, pulseVal, color='red', label='PulseOx signal')
ax1.plot(respTime, respVal, color='blue', label='Respiration signal')
for acqtime in pulseAcqTimes:
ax1.axvline(x=acqtime, ymin=0, ymax=.5, color='red', lw=0.8, label='reps' if np.where(pulseAcqTimes==acqtime)[0][0] == 0 else "_nolegend_")
for acqtime in respAcqTime:
ax1.axvline(x=acqtime, ymin=.5, ymax=1, color='blue', lw=0.8, label='reps' if np.where(respAcqTime==acqtime)[0][0] == 0 else "_nolegend_")
ax1.legend()
ax1.grid()
fig.show()
if ofname:
ax1.set_title('Saved to: ' + ofname + '.png')
fig.savefig(ofname+'.png')
plt.close()
def plot_signal_vs_resp(respTime, respSignal, mriTime, mriSignal, ofname=''):
# interpolate respiration signal to MRI signal sampling
respSignalSampledToMRISignal = np.interp(mriTime, respTime, respSignal)
# remove points where respiration signal is saturated
mriSignal_noRespSat = np.delete(mriSignal, np.where((respSignalSampledToMRISignal == 0) | (respSignalSampledToMRISignal == 4095)))
respSignal_noRespSat = np.delete(respSignalSampledToMRISignal, np.where((respSignalSampledToMRISignal == 0) | (respSignalSampledToMRISignal == 4095)))
mriTime_noRespSat = np.delete(mriTime, np.where((respSignalSampledToMRISignal == 0) | (respSignalSampledToMRISignal == 4095)))
# interpolate MRI signal to respiration signal sampling
mriSignalSampledToRespSignal = np.interp(respTime, mriTime, mriSignal)
mriSignalSampledToRespSignal = mriSignalSampledToRespSignal[np.abs(respTime - np.min(mriTime)).argmin():np.abs(respTime - np.max(mriTime)).argmin()]
respTimeCropToMRI = respTime[np.abs(respTime - np.min(mriTime)).argmin():np.abs(respTime - np.max(mriTime)).argmin()]
respSignalCropToMRI = respSignal[np.abs(respTime - np.min(mriTime)).argmin():np.abs(respTime - np.max(mriTime)).argmin()]
# remove points where respiration signal is saturated
mriSignalOverSampled_noRespSat = np.delete(mriSignalSampledToRespSignal, np.where((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095)))
respSignalCropToMRI_noRespSat = np.delete(respSignalCropToMRI, np.where((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095)))
respTimeCropToMRI_noRespSat = np.delete(respTimeCropToMRI, np.where((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095)))
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(20, 9.7))
plt.subplots_adjust(wspace=0.3, left=0.05, right=0.95, hspace=0.3, bottom=0.05, top=0.95)
ax1.set_title("Signal vs time")
ax1.set_xlabel('Time (ms)')
ax1.set_ylabel('Signal', color='green')
ax1.grid(which='both')
ax1.plot(mriTime/1000, mriSignal, linewidth=1, marker='+', markersize=7.0, color='green', label='$S_{MRI}$: COV='+str(round(100*np.std(mriSignal)/np.mean(mriSignal), 2))+'%')
ax1.plot(respTimeCropToMRI/1000, mriSignalSampledToRespSignal, linewidth=1.2, marker=None, color='gray', label='$S_{MRI} interp$: COV='+str(round(100*np.std(mriSignalSampledToRespSignal)/np.mean(mriSignalSampledToRespSignal), 2))+'%')
ax1.tick_params(axis='y', labelcolor='green')
ax1.legend(loc="lower left")
ax1_resp = ax1.twinx()
ax1_resp.set_ylabel('Signal')
ax1_resp.grid(which='both')
ax1_resp.plot(respTime/1000, respSignal, linewidth=1, marker=None, color='blue', label='$S_{resp}$: COV=' + str(round(100 * np.std(respSignal) / np.mean(respSignal), 2)) + '%')
ax1_resp.plot(mriTime/1000, respSignalSampledToMRISignal, linewidth=0, marker='+', color='red', label='$S_{resp}$: COV=' + str(round(100 * np.std(respSignalSampledToMRISignal) / np.mean(respSignalSampledToMRISignal), 2)) + '%')
ax1_resp.plot(mriTime_noRespSat/1000, respSignal_noRespSat, linewidth=0, marker='+', color='blue', label='$S_{resp}$ no sat')
ax1_resp.tick_params(axis='y', labelcolor='blue')
ax1_resp.legend(loc="lower right")
ax2.set_title("MRI signal vs Respiration signal: (Pearson\'s R, p-value)={}".format(tuple(np.round(scipy.stats.pearsonr(mriSignalOverSampled_noRespSat, respSignalCropToMRI_noRespSat), decimals=4))))
ax2.set_xlabel('Respiration signal')
ax2.set_ylabel('MRI signal (interpolated to respiration sampling)')
ax2.grid(which='both')
# ax2.plot(respSignalSampledToMRISignal, mriSignal, linewidth=0, marker='+', markersize=7.0, color='tab:red', label='all points')
# ax2.plot(respSignal_noRespSat, mriSignal_noRespSat, linewidth=0, marker='+', markersize=7.0, color='tab:blue', label='without respiration signal saturation')
# ax2.plot(respSignalCropToMRI, mriSignalSampledToRespSignal, linewidth=0, marker='+', markersize=7.0, color='tab:orange', label='all points')
ax2.plot(respSignalCropToMRI_noRespSat, mriSignalOverSampled_noRespSat, linewidth=0, marker='+', markersize=7.0, color='tab:green', label='without respiration signal saturation')
ax2.legend()
ax3.set_title("Signal vs time interpolated to respiration sampling") # --------------------------------------------
ax3.set_xlabel('Time (ms)')
ax3.set_ylabel('Signal', color='green')
ax3.grid(which='both')
ax3.plot(respTimeCropToMRI/1000, mriSignalSampledToRespSignal, linewidth=0, marker='.', markersize=3.0, color='tab:red', label='$S_{MRI} interp to resp$')
ax3.plot(respTimeCropToMRI_noRespSat/1000, mriSignalOverSampled_noRespSat, linewidth=0, marker='.', markersize=3.0, color='green', label='$S_{MRI} interp to resp NO RESP SAT$')
ax3.tick_params(axis='y', labelcolor='green')
ax3.legend(loc="lower left")
ax3_resp = ax3.twinx()
ax3_resp.set_ylabel('Signal')
ax3_resp.plot(respTimeCropToMRI/1000, respSignalCropToMRI, linewidth=0, marker='.', markersize=3.0, color='tab:red', label='$S_{resp}$ crop')
ax3_resp.plot(respTimeCropToMRI_noRespSat/1000, respSignalCropToMRI_noRespSat, linewidth=0, marker='.', markersize=3.0, color='blue', label='$S_{resp}$ NO RESP SAT')
ax3_resp.tick_params(axis='y', labelcolor='blue')
ax3_resp.legend(loc="lower right")
ax3_respPeriod = ax3.twinx()
respSignalMax, respSignalMin = peakdet(respSignalCropToMRI, 300)
respPeriod = np.append(np.nan, np.diff(respTimeCropToMRI[respSignalMax[:, 0]]))/1000
ax3_respPeriod.plot(respTimeCropToMRI[respSignalMax[:, 0]]/1000, respPeriod, linewidth=3.0, marker='+', markersize=10, color='tab:pink', label='Resp period')
ax3_respPeriod.tick_params(axis='y', labelcolor='tab:pink')
ax3_respPeriod.set_ylabel('Resp period is s (mean = '+str(round(np.mean(respPeriod[1:]), 2))+' ['+str(np.min(respPeriod[1:]))+', '+str(np.max(respPeriod[1:]))+']', color='tab:pink')
for tPeak in respTimeCropToMRI[respSignalMax[:, 0]]/1000:
ax3_respPeriod.axvline(x=tPeak, linestyle='-', color='tab:pink', linewidth=1.0)
ax3_corr = ax3.twinx()
ax3_corr.plot(respTimeCropToMRI_noRespSat/1000, scipy.signal.correlate(mriSignalOverSampled_noRespSat, respSignalCropToMRI_noRespSat, mode='same', method='direct'), linewidth=1, marker=None, markersize=0, color='tab:orange', label='Cross-corr')
ax3_corr.legend(loc="upper right")
ax4.set_title("FFT") # --------------------------------------------------------------------------------------------
# respSignal_FFT = np.fft.fft((respSignalCropToMRI - np.mean(respSignalCropToMRI))/np.std(respSignalCropToMRI))
# mriSignal_FFT = np.fft.fft((mriSignalSampledToRespSignal - np.mean(mriSignalSampledToRespSignal))/np.std(mriSignalSampledToRespSignal))
# freq = np.fft.fftfreq(respTimeCropToMRI.size, d=respTimeCropToMRI[1]-respTimeCropToMRI[0]) # in MHz
# idx_f0 = np.where(freq == 0)[0]
# idx_ascending_freq = np.argsort(freq)
freqResMRI, respSignalResMRI_FFT = fft_warpper(mriTime, respSignalSampledToMRISignal, increase_res_factor=5)
freqResMRI, mriSignalResMRI_FFT = fft_warpper(mriTime, mriSignal, increase_res_factor=5)
ax4.set_xlabel('Frequency (Hz)')
ax4.set_ylabel('Signal')
ax4.grid(which='both')
# ax4.plot(freq[idx_ascending_freq]*1000, np.abs(respSignal_FFT[idx_ascending_freq]), linewidth=0.9, marker='.', markersize=0, color='black', label='$S_{resp}$')
# ax4.plot(freq[idx_ascending_freq]*1000, np.abs(mriSignal_FFT[idx_ascending_freq]), linewidth=0.9, marker='.', markersize=0, color='green', label='$S_{MRI}\ interp\ to\ resp$')
ax4.plot(freqResMRI*1000, respSignalResMRI_FFT, label='$S_{resp}\ res\ MRI$', linewidth=0.9, marker='+', markersize=0, color='black')
ax4.plot(freqResMRI*1000, mriSignalResMRI_FFT, label='$S_{MRI}\ res\ MRI$', linewidth=0.9, marker='+', markersize=0, color='green')
ax4.axvspan(xmin=1/np.min(respPeriod[1:]), xmax=1/np.max(respPeriod[1:]), label='respiration frequency range', color='tab:pink', alpha=0.2)
ax4.legend(loc="upper right")
ax4.set_xlim(left=0, right=1.5)
ax4_corr = ax4.twinx()
ax4_corr.plot(freqResMRI*1000, scipy.signal.correlate(respSignalResMRI_FFT, mriSignalResMRI_FFT, mode='same', method='direct'), label='Cross-corr', linewidth=1, marker=None, markersize=0, color='tab:orange')
ax4_corr.legend(loc="lower right")
plt.show(block=True)
if ofname:
fig.suptitle('Saved to: '+ofname+'_signal_vs_resp.png')
fig.savefig(ofname+'_signal_vs_resp.png')
def calculateB1Factor(timePulseOx, signalPulseOx, measuredFAB1map, b1mapVoltage, DSCvoltage, selectedFlipAngle, T1=1251):
# calculate subject's cardiac cycle
pulseOxSignalMax, pulseOxSignalMin = peakdet(signalPulseOx, 600)
cardiacPeriods = np.diff(timePulseOx[pulseOxSignalMax[:, 0].astype(int)]) # in milliseconds
cardiacPeriodMean = np.mean(cardiacPeriods)
# calculate required excitation flip angle
excFArequired = 180 - np.arccos(np.exp(-cardiacPeriodMean/T1))*180/np.pi # scalar
# actual B1
B1actual = (measuredFAB1map * DSCvoltage/b1mapVoltage)/45.0 # matrix
# actual excitation flip angle
excFAactual = selectedFlipAngle * B1actual # matrix
# actual refocusing flip angle
refocFAactual = 180 * B1actual # matrix
# final factor of used signal
usedSignalFactor = (excFAactual/excFArequired) * (refocFAactual/180) # matrix
return usedSignalFactor
def discardWrongTRs(TReff, timePulseOx, signalPulseOx, mriSignal, repsAcqTime_PulseOx, repsAcqTime_Resp, outPlotFname=''):
"""
Detect points where sequence missed a cardiac window, loosing steady state.
Normal cardiac beat varies between 700 and 1400 ms, anything above 1400 ms is probably due to a missed trigger.
:param TReff:
:param mriSignal:
:return:
"""
# calculate subject's cardiac cycle
pulseOxSignalMax, pulseOxSignalMin = peakdet(signalPulseOx, 599, outPlotFname=outPlotFname)
cardiacPeriods = np.diff(timePulseOx[pulseOxSignalMax[:, 0].astype(int)]) # in milliseconds
# find a threshold to detect misssed triggers
cardiacPeriodMean_withOutliers = np.mean(cardiacPeriods)
cardiacPeriodStd_withOutliers = np.std(cardiacPeriods)
print('\nMean +/- SD cardiac cycle WITH outliers (ms) = %d +/- %d' % (cardiacPeriodMean_withOutliers, cardiacPeriodStd_withOutliers))
cardiacPeriods_withoutOutliers = cardiacPeriods[(cardiacPeriods < cardiacPeriodMean_withOutliers + 2*cardiacPeriodStd_withOutliers) & (cardiacPeriods > cardiacPeriodMean_withOutliers - 2*cardiacPeriodStd_withOutliers)]
cardiacPeriodMean_withoutOutliers = np.mean(cardiacPeriods_withoutOutliers)
cardiacPeriodStd_withoutOutliers = np.std(cardiacPeriods_withoutOutliers)
print('Mean +/- SD cardiac cycle WITHOUT outliers (ms) = %d +/- %d' % (cardiacPeriodMean_withoutOutliers, cardiacPeriodStd_withoutOutliers))
# discard acquisitions with effective TR outside mean cardiac cylce +/- 3 true SD (without outliers)
idxAcqWithBadTR = np.argwhere((TReff >= cardiacPeriodMean_withoutOutliers+4*cardiacPeriodStd_withoutOutliers) | (TReff <= cardiacPeriodMean_withoutOutliers-4*cardiacPeriodStd_withoutOutliers))
# also discard the repetition following a missed trigger AND the first two repetitions of the set
idxAcqToDiscard = np.concatenate((np.array([[0], [1]]), idxAcqWithBadTR, idxAcqWithBadTR[idxAcqWithBadTR[:,0] < (TReff.size-1), :]+1))
idxAcqToDiscard = np.unique(idxAcqToDiscard)
# discard data
mriSignal_TRfiltered = np.delete(mriSignal, idxAcqToDiscard, axis=-1)
repsAcqTime_PulseOx_TRfiltered = np.delete(repsAcqTime_PulseOx, idxAcqToDiscard, axis=-1)
repsAcqTime_Resp_TRfiltered = np.delete(repsAcqTime_Resp, idxAcqToDiscard, axis=-1)
print('\nDiscarded '+str(len(idxAcqToDiscard))+' points due to inconsistent effective TR.')
# plot filtering results if asked
if outPlotFname and len(mriSignal.shape) == 1:
fig, ((ax1, ax2)) = plt.subplots(2, 1, figsize=(20, 9.7))
plt.subplots_adjust(left=0.05, right=0.95, hspace=0.25, bottom=0.05, top=0.9)
ax2.set_title("Effective TR")
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Effective TR (ms)')
ax2.grid(which='both')
ax2.plot(repsAcqTime_PulseOx/1000, TReff, linewidth=0, marker='+', markersize=7.0, color='red', label='Discarded points')
ax2.plot(repsAcqTime_PulseOx_TRfiltered/1000, np.delete(TReff, idxAcqToDiscard, axis=-1), linewidth=0, marker='+', markersize=7.0, color='black', label='Kept points')
ax2.axhline(y=cardiacPeriodMean_withoutOutliers+4*cardiacPeriodStd_withoutOutliers, linewidth=3, color='red', label='Threshold (mean RR = '+str(round(cardiacPeriodMean_withoutOutliers,2))+'+/-'+str(round(cardiacPeriodStd_withoutOutliers,2))+' ms)')
ax2.axhline(y=cardiacPeriodMean_withoutOutliers-4*cardiacPeriodStd_withoutOutliers, linewidth=3, color='red')
ax2.legend(loc="lower left")
ax1.set_title("Effective TR filtering")
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Signal')
ax1.grid(which='both')
ax1.plot(repsAcqTime_PulseOx/1000, mriSignal, linewidth=0, marker='+', markersize=7.0, color='red', label='Discarded points')
ax1.plot(repsAcqTime_PulseOx_TRfiltered/1000, mriSignal_TRfiltered, linewidth=0, marker='+', markersize=7.0, color='black', label='Kept points')
ax1.legend(loc="lower left")
fig.suptitle('Effective TR filtering\nSaved to: '+outPlotFname)
fig.savefig(outPlotFname)
plt.show()
return mriSignal_TRfiltered, repsAcqTime_PulseOx_TRfiltered, repsAcqTime_Resp_TRfiltered, idxAcqToDiscard, cardiacPeriodMean_withoutOutliers
# def deduce_wrongTR_3Tdata(TReff, timePulseOx, signalPulseOx, mriSignal, repsAcqTime_PulseOx, repsAcqTime_Resp, outPlotFname=''):
# """
# Detect points where sequence missed a cardiac window, loosing steady state.
# Normal cardiac beat varies between 700 and 1400 ms, anything above 1400 ms is probably due to a missed trigger.
# :param TReff:
# :param mriSignal:
# :return:
# """
#
#
# # sliding window
#
# # calculate subject's cardiac cycle
# pulseOxSignalMax, pulseOxSignalMin = peakdet(signalPulseOx, 599, outPlotFname=outPlotFname)
# cardiacPeriods = np.diff(timePulseOx[pulseOxSignalMax[:, 0].astype(int)]) # in milliseconds
# cardiacPeriodMean = np.mean(cardiacPeriods)
# cardiacPeriodMin = np.min(cardiacPeriods)
# print('\nMean +/- SD cardiac cycle (ms) = %d +/- %d' % (cardiacPeriodMean, np.std(cardiacPeriods)))
#
# # discard acquisitions with effective TR >= 1.8 times the minimum cardiac cycle of the subject
# idxAcqWithBadTR = np.argwhere((TReff >= 1.5*cardiacPeriodMean) | (TReff <= 0.5*cardiacPeriodMean))
# # also discard the repetition following a missed trigger AND the first two repetitions of the set
# idxAcqToDiscard = np.concatenate((np.array([[0], [1]]), idxAcqWithBadTR, idxAcqWithBadTR+1))
# # discard data
# mriSignal_TRfiltered = np.delete(mriSignal, idxAcqToDiscard, axis=-1)
# repsAcqTime_PulseOx_TRfiltered = np.delete(repsAcqTime_PulseOx, idxAcqToDiscard, axis=-1)
# repsAcqTime_Resp_TRfiltered = np.delete(repsAcqTime_Resp, idxAcqToDiscard, axis=-1)
# print('\nDiscarded '+str(len(idxAcqToDiscard))+' points due to inconsistent effective TR.')
#
# # plot filtering results if asked
# if outPlotFname and len(mriSignal.shape) == 1:
#
# fig, ((ax1, ax2)) = plt.subplots(2, 1, figsize=(20, 9.7))
# plt.subplots_adjust(left=0.05, right=0.95, hspace=0.25, bottom=0.05, top=0.9)
#
# ax2.set_title("Effective TR")
# ax2.set_xlabel('Time (s)')
# ax2.set_ylabel('Effective TR (ms)')
# ax2.grid(which='both')
# ax2.plot(repsAcqTime_PulseOx/1000, TReff, linewidth=0, marker='+', markersize=7.0, color='red', label='Discarded points')
# ax2.plot(repsAcqTime_PulseOx_TRfiltered/1000, np.delete(TReff, idxAcqToDiscard, axis=-1), linewidth=0, marker='+', markersize=7.0, color='black', label='Kept points')
# ax2.axhline(y=1.5*cardiacPeriodMean, linewidth=3, color='red', label='Threshold (mean RR = '+str(cardiacPeriodMean)+'ms)')
# ax2.axhline(y=0.5*cardiacPeriodMean, linewidth=3, color='red')
# ax2.legend(loc="lower left")
#
# ax1.set_title("Effective TR filtering")
# ax1.set_xlabel('Time (s)')
# ax1.set_ylabel('Signal')
# ax1.grid(which='both')
# ax1.plot(repsAcqTime_PulseOx/1000, mriSignal, linewidth=0, marker='+', markersize=7.0, color='red', label='Discarded points')
# ax1.plot(repsAcqTime_PulseOx_TRfiltered/1000, mriSignal_TRfiltered, linewidth=0, marker='+', markersize=7.0, color='black', label='Kept points')
# ax1.legend(loc="lower left")
#
# fig.suptitle('Effective TR filtering\nSaved to: '+outPlotFname)
# fig.savefig(outPlotFname)
# plt.show()
#
# return mriSignal_TRfiltered, repsAcqTime_PulseOx_TRfiltered, repsAcqTime_Resp_TRfiltered, idxAcqWithBadTR
#%% Functions related to breathing frequencies filtering
def filterResp(mriSignal, mriTime, respSignal, respTime, outPlotFname, cardiacPeriod=0.5, freqDetection='temporal'):
"""Becareful that mriTime and respTime are synchronized correctly AND that mriSignal is sampled regularly."""
# crop respiration signal to the same time window as MRI signal
respTimeCrop = respTime[np.abs(respTime - np.min(mriTime)).argmin():np.abs(respTime - np.max(mriTime)).argmin()]
respSignalCrop = respSignal[np.abs(respTime - np.min(mriTime)).argmin():np.abs(respTime - np.max(mriTime)).argmin()]
# calculate respiration frequencies and determine cutoffs in Hz
lowFreqCut, highFreqCut = calculate_respFreq_cutoff(respTimeCrop/1000, respSignalCrop, freqDetection, cardiacPeriod=cardiacPeriod/1000, outPlotFname='')
# remove the frequency range (in Hz) of respiration signal from MRI signal
mriSampling_rate = 1000/(mriTime[1]-mriTime[0])
if highFreqCut <= mriSampling_rate/2:
mriSignalFiltered = butter_bandstop_filter(mriSignal, lowFreqCut, highFreqCut, mriSampling_rate, outPlotFname=outPlotFname)
else:
warnings.warn("***** WARNING *****\nMRI data sampling rate is lower than the maximum breathing frequency"
" detected\n==> cannot filter breathing frequencies\n==> MRI signal not filtered")
mriSignalFiltered = mriSignal
return mriSignalFiltered, np.array([lowFreqCut, highFreqCut])
def calculate_respFreq_cutoff(respTime, respSignal, freqDetectionMethod, cardiacPeriod=0.5, outPlotFname=''):
"""
:param respTime: in seconds
:param respSignal:
:param freqDetectionMethod:
:param outPlotFname:
:return:
"""
# find peaks of respiration signal
respSignalMax, respSignalMin = peakdet(respSignal, 975, outPlotFname='')
respPeriod = np.diff(respTime[respSignalMax[:, 0].astype(int)]) # in seconds
# remove too short periods which are outliers due to aorta beat in the respiratory bellows during apnea
respPeriod = respPeriod[respPeriod > 2*cardiacPeriod]
respFreq = 1 / respPeriod
print('\nMean +/- SD breathing cycle (seconds) = %.2f +/- %.2f' % (np.mean(respPeriod), np.std(respPeriod)))
if freqDetectionMethod == 'fourier':
# Fourier transform
frequencies, fftAbs = fft_warpper(respTime, respSignal, increase_res_factor=2)
# fit gaussian model only on frequencies > 0 (symmetry)
fit_domain = (frequencies >= 0) & (frequencies <= 1)
gmodel = GaussianModel()
params = gmodel.guess(fftAbs[fit_domain], x=frequencies[fit_domain])
gfit = gmodel.fit(fftAbs[fit_domain], params, x=frequencies[fit_domain])
# take -2sigmas and +2sigmas as low and high frequency cutoffs but if low cutoff frequency is lower than 0.1 Hz,
# increase it (and decrease the high cutoff) until reaching this threshold
rangeFact = 2
lowFreqCut, highFreqCut = gfit.values['center'] - rangeFact*gfit.values['sigma'], gfit.values['center'] + rangeFact*gfit.values['sigma']
while lowFreqCut < 0.1:
rangeFact -= 0.1
lowFreqCut, highFreqCut = gfit.values['center'] - rangeFact * gfit.values['sigma'], gfit.values['center'] + rangeFact * gfit.values['sigma']
if outPlotFname:
figResFreqFit, axis = plt.subplots()
axis.plot(frequencies[fit_domain], fftAbs[fit_domain], 'bo')
axis.plot(frequencies[fit_domain], gfit.init_fit, 'k--', label='initial fit')
axis.plot(frequencies[fit_domain], gfit.best_fit, 'r-', label='best fit')
axis.axvspan(xmin=np.min(respFreq), xmax=np.max(respFreq), label='respiration freq range from temporal analysis', color='tab:olive', alpha=0.2)
axis.axvspan(xmin=lowFreqCut, xmax=highFreqCut, label='frequency cutoffs', color='tab:pink', alpha=0.2)
axis.legend(loc='best')
figResFreqFit.savefig(outPlotFname, transparent=True)
plt.show()
elif freqDetectionMethod == 'temporal':
# take min and max
lowFreqCut, highFreqCut = np.min(respFreq), np.max(respFreq)
print('\nRespiration cutoff frequencies: '+str(round(lowFreqCut,4))+' Hz to '+str(round(highFreqCut,4))+' Hz.\n')
return lowFreqCut, highFreqCut
def butter_bandstop_filter(data, lowcut, highcut, fs, order=3, outPlotFname=''):
# remove NaN from data (otherwise filter will output only NaN)
dataNoNan = data[~np.isnan(data)]
fft = np.fft.fft(dataNoNan, norm='ortho')
fftFreq = np.fft.fftfreq(dataNoNan.size, d=1/fs) # in MHz
idx_ascending_freq = np.argsort(fftFreq)
# create a bandpass Butterworth filter
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = scipy.signal.butter(order, [low, high], btype='bandstop')
w, h = scipy.signal.freqz(b, a, worN=len(dataNoNan)) # double number of points
# add also for negative frequencies
filter = np.concatenate((np.flip(h), h[1:]))
filterFreq = np.concatenate((-(fs * 0.5 / np.pi) * np.flip(w), (fs * 0.5 / np.pi) * w[1:]))
# interpolate to initial resolution
filterInterp = np.interp(fftFreq, filterFreq, filter)
# apply filter by multiplying FFT by filter
fftFiltered = fft * filterInterp
# come back to temporal domain
dataFiltered = np.fft.ifft(fftFiltered, norm='ortho')
# add NaN back
dataFilteredNan = np.repeat(np.nan, data.shape) #.astype(dataFiltered.dtype)
dataFilteredNan[~np.isnan(data)] = dataFiltered
if outPlotFname:
# plot results
fig, ((ax1, ax2)) = plt.subplots(2, 1, figsize=(20, 9.5))
plt.subplots_adjust(hspace=0.3, bottom=0.05, top=0.92)
# calculate normalized FFT of both signals for plotting
freqIdx, fftOriginalSignalAbs = fft_warpper(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataNoNan, increase_res_factor=2)
freqIdx, fftFilteredSignalAbs = fft_warpper(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataFiltered.astype(float), increase_res_factor=2)
ax1.set_title('Frequency domain')
ax1.set_xlabel('Frequency (Hz)')
ax1.plot(freqIdx, fftOriginalSignalAbs, label='original signal', color='black', lw=0.3, marker='+')
ax1.plot(freqIdx, fftFilteredSignalAbs, label='filtered signal', color='tab:blue', lw=0.3, marker='o', fillstyle='none')
ax1.axvspan(xmin=lowcut, xmax=highcut, label='respiration frequency range', color='tab:pink', alpha=0.2)
ax1.axvspan(xmin=-highcut, xmax=-lowcut, label='_nolegend_', color='tab:pink', alpha=0.2)
ax1.plot(fftFreq[idx_ascending_freq], np.abs(filterInterp[idx_ascending_freq]), label='filter frequency response', color='tab:pink', lw=2)
ax1.legend()
ax1.grid()
ax2.set_title('Time domain')
ax2.set_xlabel('Time (s)')
ax2.plot(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataNoNan, label='original signal: COV='+str(round(100*np.std(dataNoNan)/np.mean(dataNoNan), 2))+'%', color='black', lw=1, marker='+')
ax2.plot(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataFiltered.astype(float), label='filtered signal: COV='+str(round(100*np.std(dataFiltered.astype(float))/np.mean(dataFiltered.astype(float)), 2))+'%', color='tab:blue', lw=1, marker='o', fillstyle='none')
ax2.legend()
ax2.grid()
fig.suptitle('Saved to: '+outPlotFname)
fig.savefig(outPlotFname)
plt.close()
return dataFilteredNan
# def butter_bandpass(lowcut, highcut, fs, order=3):
# nyq = 0.5 * fs
# low = lowcut / nyq
# high = highcut / nyq
# b, a = scipy.signal.butter(order, [low, high], btype='bandpass')
# return b, a
def filterHighFreq(mriSignal, mriTime, respSignal, respTime, outPlotFname):
"""Filter high breathing frequencies from MRI signal (made for baseline filtering).
Be careful that mriTime and respTime are synchronized correctly AND that mriSignal is sampled regularly.
"""
# crop respiration signal to the same time window as MRI signal
respTimeCrop = respTime[np.abs(respTime - np.min(mriTime)).argmin():np.abs(respTime - np.max(mriTime)).argmin()]
respSignalCrop = respSignal[np.abs(respTime - np.min(mriTime)).argmin():np.abs(respTime - np.max(mriTime)).argmin()]
# calculate respiration frequencies
respSignalMax, respSignalMin = peakdet(respSignalCrop, 850, outPlotFname='')
respPeriod = np.diff(respTimeCrop[respSignalMax[:, 0].astype(int)]) / 1000 # in seconds
respFreq = 1 / respPeriod
# remove the frequency range of respiration signal from MRI signal
mriSignalFiltered = butter_lowpass_filter(mriSignal, np.min(respFreq), 1000/(mriTime[1]-mriTime[0]), outPlotFname=outPlotFname)
# mriSignalFiltered = butter_lowpass_filter_conventional(mriSignal, np.min(respFreq), 1000/(mriTime[1]-mriTime[0]), outPlotFname=outPlotFname)
return mriSignalFiltered
def butter_lowpass_filter(data, lowcut, fs, order=5, outPlotFname=''):
# remove NaN from data (otherwise filter will output only NaN)
dataNoNan = data[~np.isnan(data)]
fft = np.fft.fft(dataNoNan, norm='ortho')
fftFreq = np.fft.fftfreq(dataNoNan.size, d=1/fs) # in MHz
idx_ascending_freq = np.argsort(fftFreq)
# create a bandpass Butterworth filter
nyq = 0.5 * fs
low = lowcut / nyq
b, a = scipy.signal.butter(order, low, btype='lowpass', analog=False)
w, h = scipy.signal.freqz(b, a, worN=len(dataNoNan)) # double number of points
# add also for negative frequencies
filter = np.concatenate((np.flip(h), h[1:]))
filterFreq = np.concatenate((-(fs * 0.5 / np.pi) * np.flip(w), (fs * 0.5 / np.pi) * w[1:]))
# interpolate to initial resolution
filterInterp = np.interp(fftFreq, filterFreq, filter)
# apply filter by multiplying FFT by filter
fftFiltered = fft * filterInterp
# come back to temporal domain
dataFiltered = np.fft.ifft(fftFiltered, norm='ortho')
# add NaN back
dataFilteredNan = np.repeat(np.nan, data.shape) #.astype(dataFiltered.dtype)
dataFilteredNan[~np.isnan(data)] = dataFiltered
if outPlotFname:
# plot results
fig, ((ax1, ax2)) = plt.subplots(2, 1, figsize=(20, 9.5))
plt.subplots_adjust(hspace=0.3, bottom=0.05, top=0.92)
# calculate normalized FFT of both signals for plotting
freqAxis, fftOriginalSignalAbs = fft_warpper(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataNoNan, increase_res_factor=1)
freqAxis, fftFilteredSignalAbs = fft_warpper(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataFiltered.astype(float), increase_res_factor=1)
ax1.set_title('Frequency domain')
ax1.set_xlabel('Frequency (Hz)')
ax1.plot(freqAxis, fftOriginalSignalAbs, label='original signal', color='black', lw=0.3, marker='+')
ax1.plot(freqAxis, fftFilteredSignalAbs, label='filtered signal', color='tab:blue', lw=0.3, marker='o', fillstyle='none')
ax1.axvspan(xmin=lowcut, xmax=fs/2-fs/len(dataNoNan), label='filtered frequencies', color='tab:pink', alpha=0.2)
ax1.axvspan(xmin=-fs/2, xmax=-lowcut, label='_nolegend_', color='tab:pink', alpha=0.2)
ax1.plot(fftFreq[idx_ascending_freq], np.abs(filterInterp[idx_ascending_freq]), label='filter frequency response', color='tab:pink', lw=2)
ax1.legend()
ax1.grid()
ax2.set_title('Time domain')
ax2.set_xlabel('Time (s)')
ax2.plot(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataNoNan, label='original signal: COV='+str(round(100*np.std(dataNoNan)/np.mean(dataNoNan), 2))+'%', color='black', lw=1, marker='+')
ax2.plot(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataFiltered.astype(float), label='filtered signal: COV='+str(round(100*np.std(dataFiltered.astype(float))/np.mean(dataFiltered.astype(float)), 2))+'%', color='tab:blue', lw=1, marker='o', fillstyle='none')
ax2.legend()
ax2.grid()
fig.suptitle('Saved to: ' + outPlotFname)
fig.savefig(outPlotFname)
plt.close()
return dataFilteredNan
def butter_lowpass_filter_conventional(data, lowcut, fs, order=5, outPlotFname=''):
"""
Code from https://medium.com/analytics-vidhya/how-to-filter-noise-with-a-low-pass-filter-python-885223e5e9b7
(Dec 27 2019)
:param data:
:param cutoff:
:param fs:
:param order:
:return:
"""
# remove NaN from data (otherwise filter will output only NaN)
dataNoNan = data[~np.isnan(data)]
nyq = 0.5 * fs # Nyquist Frequency
normal_cutoff = lowcut / nyq
# Get the filter coefficients
b, a = scipy.signal.butter(order, normal_cutoff, btype='low', analog=False)
dataFiltered = scipy.signal.filtfilt(b, a, dataNoNan)
if outPlotFname:
# plot results
fig, ((ax1, ax2)) = plt.subplots(2, 1, figsize=(20, 9.5))
plt.subplots_adjust(hspace=0.3, bottom=0.05, top=0.92)
# calculate normalized FFT of both signals for plotting
freqAxis, fftOriginalSignalAbs = fft_warpper(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataNoNan, increase_res_factor=1)
freqAxis, fftFilteredSignalAbs = fft_warpper(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataFiltered.astype(float), increase_res_factor=1)
ax1.set_title('Frequency domain')
ax1.set_xlabel('Frequency (Hz)')
ax1.plot(freqAxis, fftOriginalSignalAbs, label='original signal', color='black', lw=0.3, marker='+')
ax1.plot(freqAxis, fftFilteredSignalAbs, label='filtered signal', color='tab:blue', lw=0.3, marker='o', fillstyle='none')
ax1.axvspan(xmin=lowcut, xmax=fs/2-fs/len(dataNoNan), label='filtered frequencies', color='tab:pink', alpha=0.2)
ax1.axvspan(xmin=-fs/2, xmax=-lowcut, label='_nolegend_', color='tab:pink', alpha=0.2)
# ax1.plot(fftFreq[idx_ascending_freq], np.abs(filterInterp[idx_ascending_freq]), label='filter frequency response', color='tab:pink', lw=2)
ax1.legend()
ax1.grid()
ax2.set_title('Time domain')
ax2.set_xlabel('Time (s)')
ax2.plot(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataNoNan, label='original signal: COV='+str(round(100*np.std(dataNoNan)/np.mean(dataNoNan), 2))+'%', color='black', lw=1, marker='+')
ax2.plot(np.linspace(0, 1/fs*len(dataNoNan), len(dataNoNan)), dataFiltered.astype(float), label='filtered signal: COV='+str(round(100*np.std(dataFiltered.astype(float))/np.mean(dataFiltered.astype(float)), 2))+'%', color='tab:blue', lw=1, marker='o', fillstyle='none')
ax2.legend()
ax2.grid()
fig.suptitle('Saved to: ' + outPlotFname)
fig.savefig(outPlotFname)
plt.close()
return dataFiltered
def fft_warpper(time, signal, increase_res_factor=2):
# resample to regular grid
t_regular_sampling = np.linspace(np.min(time), np.max(time), increase_res_factor * len(time))
signal_resampled = np.interp(t_regular_sampling, time, signal)
# normalize (to remove central frequency and amplitude difference between signals)
signal_norm = (signal_resampled - np.mean(signal_resampled))/np.std(signal_resampled)
# calculate FFT and frequency axis
fft = np.fft.fft(signal_norm, norm='ortho')
freq = np.fft.fftfreq(t_regular_sampling.size, d=np.mean(np.diff(t_regular_sampling))) # in MHz
idx_ascending_freq = np.argsort(freq)
return freq[idx_ascending_freq], np.abs(fft[idx_ascending_freq])
def peakdet(v, delta, x=None, outPlotFname=''):
"""
Converted from MATLAB script at http://billauer.co.il/peakdet.html
Returns two arrays
function [maxtab, mintab]=peakdet(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% contains indices in V, and column 2 the found values.
%
% With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices
% in MAXTAB and MINTAB are replaced with the corresponding
% X-values.
%
% A point is considered a maximum peak if it has the maximal
% value, and was preceded (to the left) by a value lower by
% DELTA.
% <NAME>, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed.
"""
maxtab = []
mintab = []
if x is None:
x = np.arange(len(v))
v = np.asarray(v)
if len(v) != len(x):
os.error('Input vectors v and x must have same length')
if not np.isscalar(delta):
os.error('Input argument delta must be a scalar')
if delta <= 0:
os.error('Input argument delta must be positive')
mn, mx = np.Inf, -np.Inf
mnpos, mxpos = np.NaN, np.NaN
lookformax = True
for i in np.arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx - delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn + delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
if outPlotFname:
fig, ((ax1)) = plt.subplots(1, 1, figsize=(20, 9.5))
ax1.set_title('Pulse detection')
ax1.set_xlabel('Time (s)')
time = np.arange(v.size)*20*1e-3
ax1.plot(time, v, label='Pulse Ox signal', color='blue', lw=0.3, marker='+')
for xc in np.array(maxtab)[:, 0]:
plt.axvline(x=time[xc.astype(int)], color='r', label='peak' if np.where(np.array(maxtab)[:, 0] == xc)[0][0] == 0 else "_nolegend_")
ax1.legend()
ax1.grid()
# plt.show()
fig.savefig(outPlotFname)
return np.array(maxtab), np.array(mintab)
def removeRVSfreq(mriSignalInjectRegrid, samplingFreq, rvsDataFname, rvsMaskname, rvsPhysioLogFname, outPlotFname=''):
# ----------------------------------------------------------------------------------------------------------------------
# load data
# ----------------------------------------------------------------------------------------------------------------------
rvsImg = nib.load(rvsDataFname).get_data() # MRI image
rvsMask = nib.load(rvsMaskname).get_data() # masks
# ----------------------------------------------------------------------------------------------------------------------
# extract mean signal in mask within RVS data (no injection)
# ----------------------------------------------------------------------------------------------------------------------
rvsMriSignal, _ = extract_signal_within_roi(rvsImg, rvsMask)
# ----------------------------------------------------------------------------------------------------------------------
# Physio processing
# ----------------------------------------------------------------------------------------------------------------------
rvsRepsAcqTime_PulseOx, rvsTime_PulseOx, rvsValues_PulseOx, rvsRepsAcqTime_Resp, rvsTime_Resp, rvsValues_Resp = extract_acqtime_and_physio(rvsPhysioLogFname, rvsImg.shape[3])
# ----------------------------------------------------------------------------------------------------------------------
# Normalize by 1 - exp(-TReffective/T1)
# ----------------------------------------------------------------------------------------------------------------------
rvsTReff = np.append(np.diff(rvsRepsAcqTime_PulseOx)[0], np.diff(rvsRepsAcqTime_PulseOx))
rvsMriSignal_normTR = np.divide(rvsMriSignal, rvsTReff)
# ----------------------------------------------------------------------------------------------------------------------
# Filter out points where TR was too long (missed a trigger)
# ----------------------------------------------------------------------------------------------------------------------
rvsMriSignal_TRfiltered, rvsRepsAcqTime_PulseOx_TRfiltered, rvsRepsAcqTime_Resp_TRfiltered = discardWrongTRs(rvsTReff, rvsTime_PulseOx, rvsValues_PulseOx, rvsMriSignal_normTR, rvsRepsAcqTime_PulseOx, rvsRepsAcqTime_Resp, '')
# ----------------------------------------------------------------------------------------------------------------------
# Regrid RVS data to the same sampling as the INJECT data were resampled
# ----------------------------------------------------------------------------------------------------------------------
# MRI
rvsTimeRegGrid = np.linspace(np.min(rvsRepsAcqTime_PulseOx), np.max(rvsRepsAcqTime_PulseOx), (np.max(rvsRepsAcqTime_PulseOx) - np.min(rvsRepsAcqTime_PulseOx))*samplingFreq/1000)
rvsSignalRegGrid = np.interp(rvsTimeRegGrid, rvsRepsAcqTime_PulseOx_TRfiltered, rvsMriSignal_TRfiltered)
# ----------------------------------------------------------------------------------------------------------------------
# FFT manipulation
# ----------------------------------------------------------------------------------------------------------------------
# remove NaN from data (otherwise filter will output only NaN)
rvsDataNoNan = rvsSignalRegGrid[~np.isnan(rvsSignalRegGrid)]
rvsFFT = np.fft.fft(rvsDataNoNan, norm='ortho')
rvsFFTFreq = np.fft.fftfreq(rvsDataNoNan.size, d=1/samplingFreq) # in MHz
rvs_idx_ascending_freq = np.argsort(rvsFFTFreq)
# same for inject data
injectDataNoNan = mriSignalInjectRegrid[~np.isnan(mriSignalInjectRegrid)]
injectFFT = np.fft.fft(injectDataNoNan, norm='ortho')
injectFFTFreq = np.fft.fftfreq(injectDataNoNan.size, d=1/samplingFreq) # in MHz
inject_idx_ascending_freq = np.argsort(injectFFTFreq)
# design filter
filterFreqResp = np.ones(len(injectFFT))
rvsFFT_interp = np.interp(injectFFTFreq[inject_idx_ascending_freq], rvsFFTFreq[rvs_idx_ascending_freq], rvsFFT[rvs_idx_ascending_freq])
rvsFFT_interp_ishift = np.fft.ifftshift(rvsFFT_interp)
filterFreqResp[np.abs(np.abs(rvsFFT_interp_ishift) - np.abs(injectFFT)) < 0.015] = 0
filterFreqResp_smoothed = scipy.signal.savgol_filter(filterFreqResp, window_length=7, polyorder=5)
filterFreqResp_smoothed[filterFreqResp_smoothed > 1] = 1
filterFreqResp_smoothed[filterFreqResp_smoothed < 0] = 0
# apply filter
injectFFTfiltered = injectFFT * filterFreqResp
injectFFTfilteredSmooth = injectFFT * filterFreqResp_smoothed
# be sure that we don't change f0
inject_idxF0 = inject_idx_ascending_freq[np.argwhere(injectFFTFreq == 0)][0]
injectFFTfiltered[inject_idxF0] = injectFFT[inject_idxF0]
injectFFTfilteredSmooth[inject_idxF0] = injectFFT[inject_idxF0]
# come back to temporal domain
dataFiltered = np.fft.ifft(injectFFTfiltered, norm='ortho')
dataFilteredSmoothed = np.fft.ifft(injectFFTfilteredSmooth, norm='ortho')
# add NaN back
dataFilteredNan = np.repeat(np.nan, mriSignalInjectRegrid.shape) #.astype(dataFiltered.dtype)
dataFilteredNan[~np.isnan(mriSignalInjectRegrid)] = dataFiltered
dataFilteredSmoothedNan = np.repeat(np.nan, mriSignalInjectRegrid.shape) #.astype(dataFiltered.dtype)
dataFilteredSmoothedNan[~np.isnan(mriSignalInjectRegrid)] = dataFilteredSmoothed
if outPlotFname:
# plot results
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(20, 9.5))
plt.subplots_adjust(hspace=0.3, bottom=0.05, top=0.92)
# # calculate normalized FFT of both signals for plotting
# freqIdxInject, fftInjectSignalAbs = fft_warpper(np.linspace(0, 1/samplingFreq*len(injectDataNoNan), len(injectDataNoNan)), injectDataNoNan, increase_res_factor=1)
# freqIdxRvs, fftRvsSignalAbs = fft_warpper(np.linspace(0, 1/samplingFreq*len(rvsDataNoNan), len(rvsDataNoNan)), rvsDataNoNan.astype(float), increase_res_factor=1)
# freqIdxRvsInterp, fftRvsInterpSignalAbs = fft_warpper(np.linspace(0, 1/samplingFreq*len(rvsDataNoNan), len(rvsDataNoNan)), np.fft.ifft(rvsFFT_smoothed, norm='ortho').astype(float), increase_res_factor=1)
ax1.set_title('Frequency domain')
ax1.set_xlabel('Frequency (Hz)')
# ax1.plot(freqIdxInject, fftInjectSignalAbs, label='signal with injection', color='black', lw=0.3, marker='+')
# ax1.plot(freqIdxRvs, fftRvsSignalAbs, label='signal without injection', color='tab:blue', lw=0.3, marker='+')
# ax1.plot(freqIdxRvsInterp, fftRvsInterpSignalAbs, label='signal without injection interp', color='tab:green', lw=0.3, marker='+')
ax1.plot(rvsFFTFreq[rvs_idx_ascending_freq], np.abs(rvsFFT[rvs_idx_ascending_freq]), label='signal without injection', color='tab:blue', lw=0.3, marker='+')
ax1.plot(injectFFTFreq[inject_idx_ascending_freq], filterFreqResp_smoothed[inject_idx_ascending_freq], label='filter frequency response smoothed', color='tab:orange', lw=0.3, marker='+')
ax1.plot(injectFFTFreq[inject_idx_ascending_freq], filterFreqResp[inject_idx_ascending_freq], label='filter frequency response', color='tab:green', lw=0.3, marker='+')
ax1.plot(injectFFTFreq[inject_idx_ascending_freq], np.abs(injectFFT[inject_idx_ascending_freq]), label='signal with injection', color='black', lw=0.3, marker='+')
ax1.legend()
ax1.grid()
ax2.set_title('Time domain')
ax2.set_xlabel('Time (s)')
ax2.plot(np.linspace(0, 1/samplingFreq*len(injectDataNoNan), len(injectDataNoNan)), injectDataNoNan, label='signal with injection', color='black', lw=0.3, marker='+')
ax2.plot(np.linspace(0, 1/samplingFreq*len(rvsDataNoNan), len(rvsDataNoNan)), rvsDataNoNan.astype(float), label='signal without injection', color='tab:blue', lw=0.3, marker='+')
ax2.legend()
ax2.grid()
freqIdxInjectFiltered, fftInjectSignalFilteredAbs = fft_warpper(np.linspace(0, 1/samplingFreq*len(injectDataNoNan), len(injectDataNoNan)), dataFilteredNan, increase_res_factor=1)
ax3.set_xlabel('Frequency (Hz)')
ax3.set_ylabel('Filtered signal')
# ax3.plot(freqIdxInjectFiltered, fftInjectSignalFilteredAbs, label='signal with injection filtered', color='black', lw=0.3, marker='+')
ax3.plot(injectFFTFreq[inject_idx_ascending_freq], np.abs(injectFFT[inject_idx_ascending_freq]), label='original signal with injection', color='black', lw=0.3, marker='+')
ax3.plot(injectFFTFreq[inject_idx_ascending_freq], np.abs(injectFFTfiltered[inject_idx_ascending_freq]), label='signal with injection filtered', color='tab:blue', lw=0.3, marker='+')
ax3.plot(injectFFTFreq[inject_idx_ascending_freq], np.abs(injectFFTfilteredSmooth[inject_idx_ascending_freq]), label='signal with injection filtered with smooth filter', color='red', lw=0.3, marker='+')
ax3.legend()
ax3.grid()
ax4.set_xlabel('Time (s)')
ax4.plot(np.linspace(0, 1/samplingFreq*len(injectDataNoNan), len(injectDataNoNan)), injectDataNoNan, label='original signal with injection', color='black', lw=0.3, marker='+')
ax4.plot(np.linspace(0, 1/samplingFreq*len(injectDataNoNan), len(injectDataNoNan)), dataFilteredNan, label='signal with injection filtered', color='tab:blue', lw=0.3, marker='+')
ax4.plot(np.linspace(0, 1/samplingFreq*len(injectDataNoNan), len(injectDataNoNan)), dataFilteredSmoothed, label='signal with injection filtered', color='red', lw=0.3, marker='+')
ax4.legend()
ax4.grid()
fig.suptitle('Saved to: '+outPlotFname)
fig.savefig(outPlotFname)
plt.close()
return dataFilteredSmoothed
#%%
def get_physiologFname_TE_injRep(subjID, filename='', baseDir='/Users/slevy/data/cei'):
"""
:param subjID:
:return:
"""
if filename:
shFile = open(baseDir+'/'+subjID+'/'+filename, 'r')
else:
shFile = open(baseDir+'/'+subjID+'/epi/'+subjID+'_process_inject.sh', 'r')
injRep = 0
firstPassStart, firstPassEnd = 0.0, 0.0
content = shFile.readlines()
for line in content:
if 'physiologFolder=' in line:
physiologFolder = line.split('physiologFolder=')[1].strip()
physiologFolder_absPath = os.path.abspath(os.path.dirname(shFile.name)+'/'+physiologFolder)
if line[0:4] == 'seq_':
dcmFileName = line.split('=')[1].strip()
if 'dcm_path=' in line:
dcmDir = line.split('dcm_path=')[1].strip()
if 'injRepNb=' in line:
injRep = int(line.split('injRepNb=')[1].strip())
if 'CApass_start=' in line:
firstPassStart = 1000*float(line.split('CApass_start=')[1].strip())
if 'CApass_end=' in line:
firstPassEnd = 1000*float(line.split('CApass_end=')[1].strip())
# get absolute path of physiolog file and dcm file
dcm_absPath = os.path.abspath(os.path.dirname(shFile.name)+'/' + dcmDir + '/' + dcmFileName)
shFile.close()
# # return absolute path of physiolog file and dcm file
# if filename:
# shFile_dir = os.path.dirname(subjID+'/'+filename)
# physiolog_absPath = baseDir + '/' + shFile_dir + '/' + physiologFname
# dcm_absPath = baseDir + '/' + shFile_dir + '/' + dcmDir + '/' + dcmFileName
# else:
# physiolog_absPath = baseDir+'/'+subjID+'/epi/'+physiologFname
# dcm_absPath = baseDir+'/'+subjID+'/epi/' + dcmDir + '/' + dcmFileName
# read dcm and extract TE and gap between slices
# dcm = pydicom.dcmread(dcm_absPath+'/'+os.listdir(dcm_absPath)[-1])
# TE = float(dcm.EchoTime)
# gap = float(dcm.SpacingBetweenSlices)
# TR = float(dcm.RepetitionTime)
# print('\t>>> Echo time: '+ str(TE) +' ms')
# print('\t>>> Spacing between slices: '+ str(gap) + ' mm\n')
physiolog_absPath, TE, gap, TR, acqTime_firstImg, resolution = get_physiologFname_from_dcm(dcm_absPath, physiologFolder_absPath)
print('\nDicom file path for subject #'+subjID+': '+dcm_absPath+'\n')
return physiolog_absPath, TE, injRep, gap, TR, acqTime_firstImg, firstPassStart, firstPassEnd, resolution
#%%
def get_physiologFname_from_dcm(dcmFolder, physiologFolder):
"""
:param:
:return:
"""
# read dcm and extract TE and gap between slices
dcmFiles = sorted([filename for filename in os.listdir(dcmFolder) if filename.endswith('.dcm')])
dcm = pydicom.dcmread(dcmFolder+'/'+dcmFiles[0])
TE = float(dcm.EchoTime)
gap = float(dcm.SpacingBetweenSlices)
TR = float(dcm.RepetitionTime)
acqTime_firstImg = datetime.strptime(dcm.AcquisitionDate+'-'+dcm.AcquisitionTime, "%Y%m%d-%H%M%S.%f")
resolution = np.array(dcm.PixelSpacing)
print('\t>>> Echo time: '+ str(TE) +' ms')
print('\t>>> Repetition time: '+ str(TR) + ' ms\n')
print('\t>>> Spacing between slices: '+ str(gap) + ' mm\n')
print('\t>>> Acquisition time: '+ str(acqTime_firstImg) + '\n')
print('\t>>> Resolution: '+ str(resolution) + '\n')
# find physiolog filename
physiologFname_list = [filename for filename in os.listdir(physiologFolder) if filename.endswith('.puls')]
physiologAcqTime_list = []
for filename in physiologFname_list:
# get acquisition time of physiolog
if 'T' in filename:
physio_time = filename.split('T')[1].split('.')[0][0:6]
physio_date = filename.split('T')[0][-8:]
else:
physio_time = filename.split('_')[3]
physio_date = filename.split('_')[2]
physiologAcqTime_list.append(datetime.strptime(physio_date+'-'+physio_time, "%Y%m%d-%H%M%S"))
# find the closest from the dicom tag
timeDiff = np.abs(np.subtract(np.array(physiologAcqTime_list), acqTime_firstImg))
physiologFname = physiologFname_list[timeDiff.argmin()]
physiolog_absPath = os.path.abspath(physiologFolder+'/'+physiologFname).split('.puls')[0]
print('\nPhysiolog file path: '+physiolog_absPath+'\n')
return physiolog_absPath, TE, gap, TR, acqTime_firstImg, resolution
#%%
def get_temporalCOV(signal):
"""
:param signal:
:return:
"""
cov = 100*np.std(signal, axis=-1)/np.mean(signal, axis=-1)
print('Temporal COV = '+str(np.round(cov, 2))+' %')
return cov
#%%
def plot_DeltaR2_perSlice(time,
signal,
TE,
axis,
lateralTitle='',
superiorTitle='',
xlabel='',
injTime=0,
ylims=[],
signalLabels=['whole SC', 'Inferior slice', 'Middle slice', 'Superior slice'],
timeAcqToDiscard=[],
cardiacPeriod=0,
stats=True,
colorSlices = ['tab:blue', 'tab:orange', 'tab:brown', 'tab:purple', 'tab:green', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']):
"""
Define function to plot ∆R2 along time on a given axis.
:param time:
:param signal: (SC cord, slice 0, slice 1, slice 2) X (repetitions)
:param TE:
:param injectionRep:
:return:
"""
# convert signal to ∆R2
if injTime:
injRep = np.abs(time - injTime).argmin(axis=-1)
else:
injRep = 0
DeltaR2, tSD, _ = calculateDeltaR2(signal, TE, injRep=injRep)
# plot each slice
if lateralTitle:
ylabel = axis.set_ylabel('$\Delta{}R_2^{(*)}\ (s^{-1})$', rotation=90, labelpad=0.5, fontsize=15)
axis.text(ylabel.get_position()[0]-0.31, ylabel.get_position()[1], lateralTitle, fontsize=17, transform=axis.transAxes)
axis.set_title(superiorTitle, fontsize=18, pad=30)
axis.set_xlabel(xlabel, fontsize=18)
# axes[i_subj].set_xlim([0, np.min([np.max(data['acqTimeRegrid'] - data['timeOffset']) for data in sliceWiseSignal])/1000])
axis.axhline(y=0, color='tab:gray', lw=0.8, alpha=0.5, label='_nolegend_')
if injTime:
axis.axvline(x=injTime, label='injection', color='red', lw=3)
if signalLabels: signalLabels.insert(0, 'injection')
# axes[i_subj].axvspan(xmin=CApassTimes[i_subj][0], xmax=CApassTimes[i_subj][1], label='contrast agent pass', color='r', lw=1, alpha=0.2)
for i_slice in range(signal.shape[0]):
axis.plot(time[i_slice, :], DeltaR2[i_slice, :], color=colorSlices[i_slice], lw=1.5)
if signalLabels: axis.legend(signalLabels, loc='center', bbox_to_anchor=(0.5, 1.17), ncol=4, fancybox=True, shadow=True, fontsize=17)
if stats: axis.text(0.01, 0.01, 'tSD for '+', '.join(signalLabels[1:])+' = '+str(np.array2string(tSD, precision=2, separator=' | ')), transform=axis.transAxes, fontsize=9, verticalalignment='bottom', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=11)
if ylims: axis.set_ylim(ylims)
# plot discarded acquisitions if asked
for t in timeAcqToDiscard:
if cardiacPeriod:
axis.axvspan(xmin=t-cardiacPeriod/2, xmax=t+cardiacPeriod/2, ymin=0.01, ymax=0.99, color='white', zorder=10)
else:
axis.axvline(x=t, color='tab:gray', alpha=0.3, ls=':')
axis.tick_params(labelsize=16)
if not xlabel:
axis.tick_params(axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
return axis.get_ylim()
#%%
def calculateDeltaR2(signal, TE, injRep=0, r2=1):
"""
Convert signal to ∆R2.
:param signal:
:param TE: in ms
:param injRep:
:return:
"""
# convert signal to ∆R2
if np.array(injRep).any():
S0 = np.array([np.mean(signal[i_signal, 0:injRep[i_signal]+1]) for i_signal in range(signal.shape[0])])
else:
S0 = np.mean(signal, axis=-1)
S_over_S0 = np.divide(signal, np.tile(S0, (signal.shape[1], 1)).T)
DeltaR2 = - np.log( S_over_S0 ) / ( r2 * TE / 1000 )
# calculate tSD (and not tCOV because in ∆R2 the mean is 0)
if np.array([injRep]).any():
tSD = np.array([np.std(DeltaR2[i_signal, 0:injRep[i_signal]+1]) for i_signal in range(signal.shape[0])]) #cov_baseline = dsc_utils.get_temporalCOV(DeltaR2[:, 0:injRep])
else:
tSD = np.std(DeltaR2, axis=-1) #cov_baseline = dsc_utils.get_temporalCOV(DeltaR2)
return DeltaR2, tSD, S0
def saveAsNifti(OldNii, data, oFname, dataType=np.float32):
# if nifty1
if OldNii.header['sizeof_hdr'] == 348:
newNii = nib.Nifti1Image(data, OldNii.affine, header=OldNii.header)
# if nifty2
elif OldNii.header['sizeof_hdr'] == 540:
newNii = nib.Nifti2Image(data, OldNii.affine, header=OldNii.header)
else:
raise IOError('Input image header problem')
# save file
newNii.set_data_dtype(dataType) # set header data type to float
nib.save(newNii, oFname+'.nii.gz')
| [
"numpy.hstack",
"nibabel.load",
"numpy.array2string",
"numpy.log",
"os.error",
"numpy.argsort",
"numpy.array",
"matplotlib.cm.jet",
"numpy.divide",
"numpy.arange",
"numpy.mean",
"os.path.exists",
"numpy.flip",
"numpy.repeat",
"pydicom.dcmread",
"numpy.isscalar",
"dsc_extract_physio.r... | [((3579, 3609), 'numpy.mean', 'np.mean', (['signal[1:baseline_nb]'], {}), '(signal[1:baseline_nb])\n', (3586, 3609), True, 'import numpy as np\n'), ((5307, 5358), 'numpy.mean', 'np.mean', (['mriSignalRegrid[0:firstPassStartRepRegrid]'], {}), '(mriSignalRegrid[0:firstPassStartRepRegrid])\n', (5314, 5358), True, 'import numpy as np\n'), ((5379, 5429), 'numpy.mean', 'np.mean', (['mriSignalRegrid[firstPassEndRepRegrid:-1]'], {}), '(mriSignalRegrid[firstPassEndRepRegrid:-1])\n', (5386, 5429), True, 'import numpy as np\n'), ((5489, 5513), 'numpy.copy', 'np.copy', (['mriSignalRegrid'], {}), '(mriSignalRegrid)\n', (5496, 5513), True, 'import numpy as np\n'), ((5703, 5727), 'numpy.copy', 'np.copy', (['mriSignalRegrid'], {}), '(mriSignalRegrid)\n', (5710, 5727), True, 'import numpy as np\n'), ((8145, 8182), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(20, 9.7)'}), '(2, 2, figsize=(20, 9.7))\n', (8157, 8182), True, 'import matplotlib.pyplot as plt\n'), ((10088, 10112), 'numpy.divide', 'np.divide', (['signal', 'effTR'], {}), '(signal, effTR)\n', (10097, 10112), True, 'import numpy as np\n'), ((10845, 10865), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (10853, 10865), True, 'import matplotlib.pyplot as plt\n'), ((11105, 11142), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(20, 9.5)'}), '(1, 2, figsize=(20, 9.5))\n', (11117, 11142), True, 'import matplotlib.pyplot as plt\n'), ((11147, 11201), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.2)', 'left': '(0.05)', 'right': '(0.95)'}), '(wspace=0.2, left=0.05, right=0.95)\n', (11166, 11201), True, 'import matplotlib.pyplot as plt\n'), ((13721, 13756), 'os.path.exists', 'os.path.exists', (["(log_fname + '.puls')"], {}), "(log_fname + '.puls')\n", (13735, 13756), False, 'import os\n'), ((14990, 15025), 'os.path.exists', 'os.path.exists', (["(log_fname + '.resp')"], {}), "(log_fname + '.resp')\n", (15004, 15025), False, 'import os\n'), ((16846, 16879), 'numpy.zeros', 'np.zeros', (['(1 + nSlices, nAcqs, 2)'], {}), '((1 + nSlices, nAcqs, 2))\n', (16854, 16879), True, 'import numpy as np\n'), ((16929, 16964), 'os.path.exists', 'os.path.exists', (["(log_fname + '.puls')"], {}), "(log_fname + '.puls')\n", (16943, 16964), False, 'import os\n'), ((18811, 18856), 'numpy.mean', 'np.mean', (['repsAcqTime[1:nSlices, :, 0]'], {'axis': '(0)'}), '(repsAcqTime[1:nSlices, :, 0], axis=0)\n', (18818, 18856), True, 'import numpy as np\n'), ((18912, 18947), 'os.path.exists', 'os.path.exists', (["(log_fname + '.resp')"], {}), "(log_fname + '.resp')\n", (18926, 18947), False, 'import os\n'), ((20479, 20524), 'numpy.mean', 'np.mean', (['repsAcqTime[1:nSlices, :, 1]'], {'axis': '(0)'}), '(repsAcqTime[1:nSlices, :, 1], axis=0)\n', (20486, 20524), True, 'import numpy as np\n'), ((21321, 21358), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(20, 9.5)'}), '(1, 1, figsize=(20, 9.5))\n', (21333, 21358), True, 'import matplotlib.pyplot as plt\n'), ((22023, 22034), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (22032, 22034), True, 'import matplotlib.pyplot as plt\n'), ((22211, 22251), 'numpy.interp', 'np.interp', (['mriTime', 'respTime', 'respSignal'], {}), '(mriTime, respTime, respSignal)\n', (22220, 22251), True, 'import numpy as np\n'), ((22827, 22866), 'numpy.interp', 'np.interp', (['respTime', 'mriTime', 'mriSignal'], {}), '(respTime, mriTime, mriSignal)\n', (22836, 22866), True, 'import numpy as np\n'), ((23782, 23819), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(20, 9.7)'}), '(2, 2, figsize=(20, 9.7))\n', (23794, 23819), True, 'import matplotlib.pyplot as plt\n'), ((23824, 23918), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.3)', 'left': '(0.05)', 'right': '(0.95)', 'hspace': '(0.3)', 'bottom': '(0.05)', 'top': '(0.95)'}), '(wspace=0.3, left=0.05, right=0.95, hspace=0.3, bottom=\n 0.05, top=0.95)\n', (23843, 23918), True, 'import matplotlib.pyplot as plt\n'), ((30454, 30474), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (30462, 30474), True, 'import matplotlib.pyplot as plt\n'), ((30958, 30981), 'numpy.mean', 'np.mean', (['cardiacPeriods'], {}), '(cardiacPeriods)\n', (30965, 30981), True, 'import numpy as np\n'), ((32240, 32263), 'numpy.mean', 'np.mean', (['cardiacPeriods'], {}), '(cardiacPeriods)\n', (32247, 32263), True, 'import numpy as np\n'), ((32300, 32322), 'numpy.std', 'np.std', (['cardiacPeriods'], {}), '(cardiacPeriods)\n', (32306, 32322), True, 'import numpy as np\n'), ((32724, 32763), 'numpy.mean', 'np.mean', (['cardiacPeriods_withoutOutliers'], {}), '(cardiacPeriods_withoutOutliers)\n', (32731, 32763), True, 'import numpy as np\n'), ((32803, 32841), 'numpy.std', 'np.std', (['cardiacPeriods_withoutOutliers'], {}), '(cardiacPeriods_withoutOutliers)\n', (32809, 32841), True, 'import numpy as np\n'), ((33115, 33306), 'numpy.argwhere', 'np.argwhere', (['((TReff >= cardiacPeriodMean_withoutOutliers + 4 *\n cardiacPeriodStd_withoutOutliers) | (TReff <= \n cardiacPeriodMean_withoutOutliers - 4 * cardiacPeriodStd_withoutOutliers))'], {}), '((TReff >= cardiacPeriodMean_withoutOutliers + 4 *\n cardiacPeriodStd_withoutOutliers) | (TReff <= \n cardiacPeriodMean_withoutOutliers - 4 * cardiacPeriodStd_withoutOutliers))\n', (33126, 33306), True, 'import numpy as np\n'), ((33553, 33579), 'numpy.unique', 'np.unique', (['idxAcqToDiscard'], {}), '(idxAcqToDiscard)\n', (33562, 33579), True, 'import numpy as np\n'), ((33626, 33672), 'numpy.delete', 'np.delete', (['mriSignal', 'idxAcqToDiscard'], {'axis': '(-1)'}), '(mriSignal, idxAcqToDiscard, axis=-1)\n', (33635, 33672), True, 'import numpy as np\n'), ((33710, 33766), 'numpy.delete', 'np.delete', (['repsAcqTime_PulseOx', 'idxAcqToDiscard'], {'axis': '(-1)'}), '(repsAcqTime_PulseOx, idxAcqToDiscard, axis=-1)\n', (33719, 33766), True, 'import numpy as np\n'), ((33801, 33854), 'numpy.delete', 'np.delete', (['repsAcqTime_Resp', 'idxAcqToDiscard'], {'axis': '(-1)'}), '(repsAcqTime_Resp, idxAcqToDiscard, axis=-1)\n', (33810, 33854), True, 'import numpy as np\n'), ((43686, 43721), 'numpy.fft.fft', 'np.fft.fft', (['dataNoNan'], {'norm': '"""ortho"""'}), "(dataNoNan, norm='ortho')\n", (43696, 43721), True, 'import numpy as np\n'), ((43736, 43776), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['dataNoNan.size'], {'d': '(1 / fs)'}), '(dataNoNan.size, d=1 / fs)\n', (43750, 43776), True, 'import numpy as np\n'), ((43810, 43829), 'numpy.argsort', 'np.argsort', (['fftFreq'], {}), '(fftFreq)\n', (43820, 43829), True, 'import numpy as np\n'), ((44338, 44376), 'numpy.interp', 'np.interp', (['fftFreq', 'filterFreq', 'filter'], {}), '(fftFreq, filterFreq, filter)\n', (44347, 44376), True, 'import numpy as np\n'), ((44518, 44556), 'numpy.fft.ifft', 'np.fft.ifft', (['fftFiltered'], {'norm': '"""ortho"""'}), "(fftFiltered, norm='ortho')\n", (44529, 44556), True, 'import numpy as np\n'), ((44599, 44628), 'numpy.repeat', 'np.repeat', (['np.nan', 'data.shape'], {}), '(np.nan, data.shape)\n', (44608, 44628), True, 'import numpy as np\n'), ((48313, 48348), 'numpy.fft.fft', 'np.fft.fft', (['dataNoNan'], {'norm': '"""ortho"""'}), "(dataNoNan, norm='ortho')\n", (48323, 48348), True, 'import numpy as np\n'), ((48363, 48403), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['dataNoNan.size'], {'d': '(1 / fs)'}), '(dataNoNan.size, d=1 / fs)\n', (48377, 48403), True, 'import numpy as np\n'), ((48437, 48456), 'numpy.argsort', 'np.argsort', (['fftFreq'], {}), '(fftFreq)\n', (48447, 48456), True, 'import numpy as np\n'), ((48945, 48983), 'numpy.interp', 'np.interp', (['fftFreq', 'filterFreq', 'filter'], {}), '(fftFreq, filterFreq, filter)\n', (48954, 48983), True, 'import numpy as np\n'), ((49125, 49163), 'numpy.fft.ifft', 'np.fft.ifft', (['fftFiltered'], {'norm': '"""ortho"""'}), "(fftFiltered, norm='ortho')\n", (49136, 49163), True, 'import numpy as np\n'), ((49206, 49235), 'numpy.repeat', 'np.repeat', (['np.nan', 'data.shape'], {}), '(np.nan, data.shape)\n', (49215, 49235), True, 'import numpy as np\n'), ((54175, 54218), 'numpy.interp', 'np.interp', (['t_regular_sampling', 'time', 'signal'], {}), '(t_regular_sampling, time, signal)\n', (54184, 54218), True, 'import numpy as np\n'), ((54447, 54484), 'numpy.fft.fft', 'np.fft.fft', (['signal_norm'], {'norm': '"""ortho"""'}), "(signal_norm, norm='ortho')\n", (54457, 54484), True, 'import numpy as np\n'), ((54611, 54627), 'numpy.argsort', 'np.argsort', (['freq'], {}), '(freq)\n', (54621, 54627), True, 'import numpy as np\n'), ((55760, 55773), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (55770, 55773), True, 'import numpy as np\n'), ((59048, 59081), 'numpy.divide', 'np.divide', (['rvsMriSignal', 'rvsTReff'], {}), '(rvsMriSignal, rvsTReff)\n', (59057, 59081), True, 'import numpy as np\n'), ((60170, 60259), 'numpy.interp', 'np.interp', (['rvsTimeRegGrid', 'rvsRepsAcqTime_PulseOx_TRfiltered', 'rvsMriSignal_TRfiltered'], {}), '(rvsTimeRegGrid, rvsRepsAcqTime_PulseOx_TRfiltered,\n rvsMriSignal_TRfiltered)\n', (60179, 60259), True, 'import numpy as np\n'), ((60675, 60713), 'numpy.fft.fft', 'np.fft.fft', (['rvsDataNoNan'], {'norm': '"""ortho"""'}), "(rvsDataNoNan, norm='ortho')\n", (60685, 60713), True, 'import numpy as np\n'), ((60731, 60784), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['rvsDataNoNan.size'], {'d': '(1 / samplingFreq)'}), '(rvsDataNoNan.size, d=1 / samplingFreq)\n', (60745, 60784), True, 'import numpy as np\n'), ((60822, 60844), 'numpy.argsort', 'np.argsort', (['rvsFFTFreq'], {}), '(rvsFFTFreq)\n', (60832, 60844), True, 'import numpy as np\n'), ((60967, 61008), 'numpy.fft.fft', 'np.fft.fft', (['injectDataNoNan'], {'norm': '"""ortho"""'}), "(injectDataNoNan, norm='ortho')\n", (60977, 61008), True, 'import numpy as np\n'), ((61029, 61085), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['injectDataNoNan.size'], {'d': '(1 / samplingFreq)'}), '(injectDataNoNan.size, d=1 / samplingFreq)\n', (61043, 61085), True, 'import numpy as np\n'), ((61126, 61151), 'numpy.argsort', 'np.argsort', (['injectFFTFreq'], {}), '(injectFFTFreq)\n', (61136, 61151), True, 'import numpy as np\n'), ((61238, 61362), 'numpy.interp', 'np.interp', (['injectFFTFreq[inject_idx_ascending_freq]', 'rvsFFTFreq[rvs_idx_ascending_freq]', 'rvsFFT[rvs_idx_ascending_freq]'], {}), '(injectFFTFreq[inject_idx_ascending_freq], rvsFFTFreq[\n rvs_idx_ascending_freq], rvsFFT[rvs_idx_ascending_freq])\n', (61247, 61362), True, 'import numpy as np\n'), ((61385, 61416), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['rvsFFT_interp'], {}), '(rvsFFT_interp)\n', (61401, 61416), True, 'import numpy as np\n'), ((62172, 62216), 'numpy.fft.ifft', 'np.fft.ifft', (['injectFFTfiltered'], {'norm': '"""ortho"""'}), "(injectFFTfiltered, norm='ortho')\n", (62183, 62216), True, 'import numpy as np\n'), ((62244, 62294), 'numpy.fft.ifft', 'np.fft.ifft', (['injectFFTfilteredSmooth'], {'norm': '"""ortho"""'}), "(injectFFTfilteredSmooth, norm='ortho')\n", (62255, 62294), True, 'import numpy as np\n'), ((62337, 62383), 'numpy.repeat', 'np.repeat', (['np.nan', 'mriSignalInjectRegrid.shape'], {}), '(np.nan, mriSignalInjectRegrid.shape)\n', (62346, 62383), True, 'import numpy as np\n'), ((62513, 62559), 'numpy.repeat', 'np.repeat', (['np.nan', 'mriSignalInjectRegrid.shape'], {}), '(np.nan, mriSignalInjectRegrid.shape)\n', (62522, 62559), True, 'import numpy as np\n'), ((69709, 69755), 'pydicom.dcmread', 'pydicom.dcmread', (["(dcmFolder + '/' + dcmFiles[0])"], {}), "(dcmFolder + '/' + dcmFiles[0])\n", (69724, 69755), False, 'import pydicom\n'), ((69881, 69971), 'datetime.datetime.strptime', 'datetime.strptime', (["(dcm.AcquisitionDate + '-' + dcm.AcquisitionTime)", '"""%Y%m%d-%H%M%S.%f"""'], {}), "(dcm.AcquisitionDate + '-' + dcm.AcquisitionTime,\n '%Y%m%d-%H%M%S.%f')\n", (69898, 69971), False, 'from datetime import datetime\n'), ((69981, 70007), 'numpy.array', 'np.array', (['dcm.PixelSpacing'], {}), '(dcm.PixelSpacing)\n', (69989, 70007), True, 'import numpy as np\n'), ((76328, 76364), 'nibabel.save', 'nib.save', (['newNii', "(oFname + '.nii.gz')"], {}), "(newNii, oFname + '.nii.gz')\n", (76336, 76364), True, 'import nibabel as nib\n'), ((514, 528), 'numpy.zeros', 'np.zeros', (['nrep'], {}), '(nrep)\n', (522, 528), True, 'import numpy as np\n'), ((563, 595), 'numpy.zeros', 'np.zeros', (['(nrep, image.shape[2])'], {}), '((nrep, image.shape[2]))\n', (571, 595), True, 'import numpy as np\n'), ((969, 993), 'numpy.mean', 'np.mean', (['image[mask > 0]'], {}), '(image[mask > 0])\n', (976, 993), True, 'import numpy as np\n'), ((1015, 1039), 'numpy.zeros', 'np.zeros', (['image.shape[2]'], {}), '(image.shape[2])\n', (1023, 1039), True, 'import numpy as np\n'), ((4139, 4176), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(20, 9.5)'}), '(1, 1, figsize=(20, 9.5))\n', (4151, 4176), True, 'import matplotlib.pyplot as plt\n'), ((4590, 4601), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4599, 4601), True, 'import matplotlib.pyplot as plt\n'), ((5757, 5849), 'numpy.ceil', 'np.ceil', (['(firstPassStartRepRegrid + (firstPassEndRepRegrid - firstPassStartRepRegrid\n ) / 2)'], {}), '(firstPassStartRepRegrid + (firstPassEndRepRegrid -\n firstPassStartRepRegrid) / 2)\n', (5764, 5849), True, 'import numpy as np\n'), ((6350, 6387), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(20, 9.5)'}), '(2, 1, figsize=(20, 9.5))\n', (6362, 6387), True, 'import matplotlib.pyplot as plt\n'), ((7972, 7983), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7981, 7983), True, 'import matplotlib.pyplot as plt\n'), ((12949, 12960), 'matplotlib.cm.jet', 'cm.jet', (['slc'], {}), '(slc)\n', (12955, 12960), False, 'from matplotlib import cm\n'), ((13841, 13915), 'dsc_extract_physio.read_physiolog', 'dsc_extract_physio.read_physiolog', (["(log_fname + '.puls')"], {'sampling_period': '(20)'}), "(log_fname + '.puls', sampling_period=20)\n", (13874, 13915), False, 'import dsc_extract_physio\n'), ((13983, 14052), 'dsc_extract_physio.sort_event_times', 'dsc_extract_physio.sort_event_times', (['epi_acqtime_puls', 'epi_event_puls'], {}), '(epi_acqtime_puls, epi_event_puls)\n', (14018, 14052), False, 'import dsc_extract_physio\n'), ((14356, 14385), 'numpy.sum', 'np.sum', (['reps_table_puls[:, 1]'], {}), '(reps_table_puls[:, 1])\n', (14362, 14385), True, 'import numpy as np\n'), ((15110, 15184), 'dsc_extract_physio.read_physiolog', 'dsc_extract_physio.read_physiolog', (["(log_fname + '.resp')"], {'sampling_period': '(20)'}), "(log_fname + '.resp', sampling_period=20)\n", (15143, 15184), False, 'import dsc_extract_physio\n'), ((15252, 15321), 'dsc_extract_physio.sort_event_times', 'dsc_extract_physio.sort_event_times', (['epi_acqtime_resp', 'epi_event_resp'], {}), '(epi_acqtime_resp, epi_event_resp)\n', (15287, 15321), False, 'import dsc_extract_physio\n'), ((15619, 15648), 'numpy.sum', 'np.sum', (['reps_table_resp[:, 1]'], {}), '(reps_table_resp[:, 1])\n', (15625, 15648), True, 'import numpy as np\n'), ((20676, 20726), 'numpy.hstack', 'np.hstack', (['(time_resp, time_puls[time_resp.size:])'], {}), '((time_resp, time_puls[time_resp.size:]))\n', (20685, 20726), True, 'import numpy as np\n'), ((20749, 20821), 'numpy.pad', 'np.pad', (['resp_values', '(0, puls_values.size - resp_values.size)', '"""reflect"""'], {}), "(resp_values, (0, puls_values.size - resp_values.size), 'reflect')\n", (20755, 20821), True, 'import numpy as np\n'), ((21048, 21081), 'numpy.vstack', 'np.vstack', (['(time_puls, time_resp)'], {}), '((time_puls, time_resp))\n', (21057, 21081), True, 'import numpy as np\n'), ((21103, 21140), 'numpy.vstack', 'np.vstack', (['(puls_values, resp_values)'], {}), '((puls_values, resp_values))\n', (21112, 21140), True, 'import numpy as np\n'), ((22357, 22448), 'numpy.where', 'np.where', (['((respSignalSampledToMRISignal == 0) | (respSignalSampledToMRISignal == 4095))'], {}), '((respSignalSampledToMRISignal == 0) | (\n respSignalSampledToMRISignal == 4095))\n', (22365, 22448), True, 'import numpy as np\n'), ((22512, 22603), 'numpy.where', 'np.where', (['((respSignalSampledToMRISignal == 0) | (respSignalSampledToMRISignal == 4095))'], {}), '((respSignalSampledToMRISignal == 0) | (\n respSignalSampledToMRISignal == 4095))\n', (22520, 22603), True, 'import numpy as np\n'), ((22643, 22734), 'numpy.where', 'np.where', (['((respSignalSampledToMRISignal == 0) | (respSignalSampledToMRISignal == 4095))'], {}), '((respSignalSampledToMRISignal == 0) | (\n respSignalSampledToMRISignal == 4095))\n', (22651, 22734), True, 'import numpy as np\n'), ((23404, 23472), 'numpy.where', 'np.where', (['((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095))'], {}), '((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095))\n', (23412, 23472), True, 'import numpy as np\n'), ((23541, 23609), 'numpy.where', 'np.where', (['((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095))'], {}), '((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095))\n', (23549, 23609), True, 'import numpy as np\n'), ((23674, 23742), 'numpy.where', 'np.where', (['((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095))'], {}), '((respSignalCropToMRI == 0) | (respSignalCropToMRI == 4095))\n', (23682, 23742), True, 'import numpy as np\n'), ((34070, 34107), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(20, 9.7)'}), '(2, 1, figsize=(20, 9.7))\n', (34082, 34107), True, 'import matplotlib.pyplot as plt\n'), ((34116, 34193), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.05)', 'right': '(0.95)', 'hspace': '(0.25)', 'bottom': '(0.05)', 'top': '(0.9)'}), '(left=0.05, right=0.95, hspace=0.25, bottom=0.05, top=0.9)\n', (34135, 34193), True, 'import matplotlib.pyplot as plt\n'), ((35647, 35657), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (35655, 35657), True, 'import matplotlib.pyplot as plt\n'), ((40328, 40524), 'warnings.warn', 'warnings.warn', (['"""***** WARNING *****\nMRI data sampling rate is lower than the maximum breathing frequency detected\n==> cannot filter breathing frequencies\n==> MRI signal not filtered"""'], {}), '(\n """***** WARNING *****\nMRI data sampling rate is lower than the maximum breathing frequency detected\n==> cannot filter breathing frequencies\n==> MRI signal not filtered"""\n )\n', (40341, 40524), False, 'import warnings\n'), ((40608, 40643), 'numpy.array', 'np.array', (['[lowFreqCut, highFreqCut]'], {}), '([lowFreqCut, highFreqCut])\n', (40616, 40643), True, 'import numpy as np\n'), ((41709, 41724), 'lmfit.models.GaussianModel', 'GaussianModel', ([], {}), '()\n', (41722, 41724), False, 'from lmfit.models import GaussianModel\n'), ((44784, 44821), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(20, 9.5)'}), '(2, 1, figsize=(20, 9.5))\n', (44796, 44821), True, 'import matplotlib.pyplot as plt\n'), ((44830, 44884), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.3)', 'bottom': '(0.05)', 'top': '(0.92)'}), '(hspace=0.3, bottom=0.05, top=0.92)\n', (44849, 44884), True, 'import matplotlib.pyplot as plt\n'), ((46651, 46662), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (46660, 46662), True, 'import matplotlib.pyplot as plt\n'), ((47872, 47888), 'numpy.min', 'np.min', (['respFreq'], {}), '(respFreq)\n', (47878, 47888), True, 'import numpy as np\n'), ((49391, 49428), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(20, 9.5)'}), '(2, 1, figsize=(20, 9.5))\n', (49403, 49428), True, 'import matplotlib.pyplot as plt\n'), ((49437, 49491), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.3)', 'bottom': '(0.05)', 'top': '(0.92)'}), '(hspace=0.3, bottom=0.05, top=0.92)\n', (49456, 49491), True, 'import matplotlib.pyplot as plt\n'), ((51269, 51280), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (51278, 51280), True, 'import matplotlib.pyplot as plt\n'), ((52049, 52086), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(20, 9.5)'}), '(2, 1, figsize=(20, 9.5))\n', (52061, 52086), True, 'import matplotlib.pyplot as plt\n'), ((52095, 52149), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.3)', 'bottom': '(0.05)', 'top': '(0.92)'}), '(hspace=0.3, bottom=0.05, top=0.92)\n', (52114, 52149), True, 'import matplotlib.pyplot as plt\n'), ((53929, 53940), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (53938, 53940), True, 'import matplotlib.pyplot as plt\n'), ((54091, 54103), 'numpy.min', 'np.min', (['time'], {}), '(time)\n', (54097, 54103), True, 'import numpy as np\n'), ((54105, 54117), 'numpy.max', 'np.max', (['time'], {}), '(time)\n', (54111, 54117), True, 'import numpy as np\n'), ((54372, 54396), 'numpy.std', 'np.std', (['signal_resampled'], {}), '(signal_resampled)\n', (54378, 54396), True, 'import numpy as np\n'), ((54666, 54697), 'numpy.abs', 'np.abs', (['fft[idx_ascending_freq]'], {}), '(fft[idx_ascending_freq])\n', (54672, 54697), True, 'import numpy as np\n'), ((55808, 55863), 'os.error', 'os.error', (['"""Input vectors v and x must have same length"""'], {}), "('Input vectors v and x must have same length')\n", (55816, 55863), False, 'import os\n'), ((55876, 55894), 'numpy.isscalar', 'np.isscalar', (['delta'], {}), '(delta)\n', (55887, 55894), True, 'import numpy as np\n'), ((55904, 55953), 'os.error', 'os.error', (['"""Input argument delta must be a scalar"""'], {}), "('Input argument delta must be a scalar')\n", (55912, 55953), False, 'import os\n'), ((55982, 56031), 'os.error', 'os.error', (['"""Input argument delta must be positive"""'], {}), "('Input argument delta must be positive')\n", (55990, 56031), False, 'import os\n'), ((56726, 56763), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(20, 9.5)'}), '(1, 1, figsize=(20, 9.5))\n', (56738, 56763), True, 'import matplotlib.pyplot as plt\n'), ((57259, 57275), 'numpy.array', 'np.array', (['maxtab'], {}), '(maxtab)\n', (57267, 57275), True, 'import numpy as np\n'), ((57277, 57293), 'numpy.array', 'np.array', (['mintab'], {}), '(mintab)\n', (57285, 57293), True, 'import numpy as np\n'), ((58989, 59020), 'numpy.diff', 'np.diff', (['rvsRepsAcqTime_PulseOx'], {}), '(rvsRepsAcqTime_PulseOx)\n', (58996, 59020), True, 'import numpy as np\n'), ((59998, 60028), 'numpy.min', 'np.min', (['rvsRepsAcqTime_PulseOx'], {}), '(rvsRepsAcqTime_PulseOx)\n', (60004, 60028), True, 'import numpy as np\n'), ((60030, 60060), 'numpy.max', 'np.max', (['rvsRepsAcqTime_PulseOx'], {}), '(rvsRepsAcqTime_PulseOx)\n', (60036, 60060), True, 'import numpy as np\n'), ((62760, 62797), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(20, 9.5)'}), '(2, 2, figsize=(20, 9.5))\n', (62772, 62797), True, 'import matplotlib.pyplot as plt\n'), ((62806, 62860), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.3)', 'bottom': '(0.05)', 'top': '(0.92)'}), '(hspace=0.3, bottom=0.05, top=0.92)\n', (62825, 62860), True, 'import matplotlib.pyplot as plt\n'), ((66936, 66947), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (66945, 66947), True, 'import matplotlib.pyplot as plt\n'), ((71458, 71482), 'numpy.mean', 'np.mean', (['signal'], {'axis': '(-1)'}), '(signal, axis=-1)\n', (71465, 71482), True, 'import numpy as np\n'), ((75284, 75308), 'numpy.mean', 'np.mean', (['signal'], {'axis': '(-1)'}), '(signal, axis=-1)\n', (75291, 75308), True, 'import numpy as np\n'), ((75736, 75760), 'numpy.std', 'np.std', (['DeltaR2'], {'axis': '(-1)'}), '(DeltaR2, axis=-1)\n', (75742, 75760), True, 'import numpy as np\n'), ((75981, 76039), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['data', 'OldNii.affine'], {'header': 'OldNii.header'}), '(data, OldNii.affine, header=OldNii.header)\n', (75996, 76039), True, 'import nibabel as nib\n'), ((710, 738), 'numpy.mean', 'np.mean', (['img_rep_i[mask > 0]'], {}), '(img_rep_i[mask > 0])\n', (717, 738), True, 'import numpy as np\n'), ((1114, 1154), 'numpy.mean', 'np.mean', (['image[mask[:, :, i_z] > 0, i_z]'], {}), '(image[mask[:, :, i_z] > 0, i_z])\n', (1121, 1154), True, 'import numpy as np\n'), ((4276, 4298), 'numpy.arange', 'np.arange', (['signal.size'], {}), '(signal.size)\n', (4285, 4298), True, 'import numpy as np\n'), ((4385, 4407), 'numpy.arange', 'np.arange', (['signal.size'], {}), '(signal.size)\n', (4394, 4407), True, 'import numpy as np\n'), ((6494, 6525), 'numpy.arange', 'np.arange', (['mriSignalRegrid.size'], {}), '(mriSignalRegrid.size)\n', (6503, 6525), True, 'import numpy as np\n'), ((6621, 6652), 'numpy.arange', 'np.arange', (['mriSignalRegrid.size'], {}), '(mriSignalRegrid.size)\n', (6630, 6652), True, 'import numpy as np\n'), ((6748, 6779), 'numpy.arange', 'np.arange', (['mriSignalRegrid.size'], {}), '(mriSignalRegrid.size)\n', (6757, 6779), True, 'import numpy as np\n'), ((7218, 7249), 'numpy.arange', 'np.arange', (['mriSignalRegrid.size'], {}), '(mriSignalRegrid.size)\n', (7227, 7249), True, 'import numpy as np\n'), ((7345, 7376), 'numpy.arange', 'np.arange', (['mriSignalRegrid.size'], {}), '(mriSignalRegrid.size)\n', (7354, 7376), True, 'import numpy as np\n'), ((7482, 7513), 'numpy.arange', 'np.arange', (['mriSignalRegrid.size'], {}), '(mriSignalRegrid.size)\n', (7491, 7513), True, 'import numpy as np\n'), ((8647, 8674), 'numpy.exp', 'np.exp', (['(-effTR[1:] / 1251.0)'], {}), '(-effTR[1:] / 1251.0)\n', (8653, 8674), True, 'import numpy as np\n'), ((8844, 8867), 'numpy.exp', 'np.exp', (['(-effTR / 1251.0)'], {}), '(-effTR / 1251.0)\n', (8850, 8867), True, 'import numpy as np\n'), ((9384, 9407), 'numpy.exp', 'np.exp', (['(-effTR / 1251.0)'], {}), '(-effTR / 1251.0)\n', (9390, 9407), True, 'import numpy as np\n'), ((9710, 9733), 'numpy.exp', 'np.exp', (['(-effTR / 1251.0)'], {}), '(-effTR / 1251.0)\n', (9716, 9733), True, 'import numpy as np\n'), ((11556, 11586), 'numpy.mean', 'np.mean', (['signal[0:baseline_nb]'], {}), '(signal[0:baseline_nb])\n', (11563, 11586), True, 'import numpy as np\n'), ((12227, 12240), 'numpy.diff', 'np.diff', (['time'], {}), '(time)\n', (12234, 12240), True, 'import numpy as np\n'), ((12972, 13028), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'signal_by_slice_smoothed.shape[1]'], {}), '(0.0, 1.0, signal_by_slice_smoothed.shape[1])\n', (12983, 13028), True, 'import numpy as np\n'), ((14118, 14263), 'dsc_extract_physio.plot_physio', 'dsc_extract_physio.plot_physio', (['time_puls', 'puls_values', 'epi_acqtime_puls', 'reps_table_puls', 'acq_window_puls', "(physioplot_out_fname + '_pulseOx')"], {}), "(time_puls, puls_values, epi_acqtime_puls,\n reps_table_puls, acq_window_puls, physioplot_out_fname + '_pulseOx')\n", (14148, 14263), False, 'import dsc_extract_physio\n'), ((14438, 14565), 'os.error', 'os.error', (['"""Number of repetitions in image is different from the number of repetitions recorded in pulseOx physiolog."""'], {}), "(\n 'Number of repetitions in image is different from the number of repetitions recorded in pulseOx physiolog.'\n )\n", (14446, 14565), False, 'import os\n'), ((14719, 14741), 'numpy.arange', 'np.arange', (['(0)', 'nrep_nii'], {}), '(0, nrep_nii)\n', (14728, 14741), True, 'import numpy as np\n'), ((14774, 14802), 'numpy.min', 'np.min', (['reps_acqtime_pulseOx'], {}), '(reps_acqtime_pulseOx)\n', (14780, 14802), True, 'import numpy as np\n'), ((14804, 14832), 'numpy.max', 'np.max', (['reps_acqtime_pulseOx'], {}), '(reps_acqtime_pulseOx)\n', (14810, 14832), True, 'import numpy as np\n'), ((15387, 15529), 'dsc_extract_physio.plot_physio', 'dsc_extract_physio.plot_physio', (['time_resp', 'resp_values', 'epi_acqtime_resp', 'reps_table_resp', 'acq_window_resp', "(physioplot_out_fname + '_resp')"], {}), "(time_resp, resp_values, epi_acqtime_resp,\n reps_table_resp, acq_window_resp, physioplot_out_fname + '_resp')\n", (15417, 15529), False, 'import dsc_extract_physio\n'), ((15698, 15829), 'os.error', 'os.error', (['"""Number of repetitions in image is different from the number of repetitions recorded in respiration physiolog."""'], {}), "(\n 'Number of repetitions in image is different from the number of repetitions recorded in respiration physiolog.'\n )\n", (15706, 15829), False, 'import os\n'), ((15977, 15999), 'numpy.arange', 'np.arange', (['(0)', 'nrep_nii'], {}), '(0, nrep_nii)\n', (15986, 15999), True, 'import numpy as np\n'), ((16032, 16057), 'numpy.min', 'np.min', (['reps_acqtime_resp'], {}), '(reps_acqtime_resp)\n', (16038, 16057), True, 'import numpy as np\n'), ((16059, 16084), 'numpy.max', 'np.max', (['reps_acqtime_resp'], {}), '(reps_acqtime_resp)\n', (16065, 16084), True, 'import numpy as np\n'), ((17045, 17072), 'os.path.basename', 'os.path.basename', (['log_fname'], {}), '(log_fname)\n', (17061, 17072), False, 'import os\n'), ((17210, 17284), 'dsc_extract_physio.read_physiolog', 'dsc_extract_physio.read_physiolog', (["(log_fname + '.puls')"], {'sampling_period': '(20)'}), "(log_fname + '.puls', sampling_period=20)\n", (17243, 17284), False, 'import dsc_extract_physio\n'), ((17357, 17426), 'dsc_extract_physio.sort_event_times', 'dsc_extract_physio.sort_event_times', (['epi_acqtime_puls', 'epi_event_puls'], {}), '(epi_acqtime_puls, epi_event_puls)\n', (17392, 17426), False, 'import dsc_extract_physio\n'), ((17478, 17507), 'numpy.sum', 'np.sum', (['reps_table_puls[:, 1]'], {}), '(reps_table_puls[:, 1])\n', (17484, 17507), True, 'import numpy as np\n'), ((18028, 18087), 'dsc_extract_physio.read_physiolog_cmrr', 'dsc_extract_physio.read_physiolog_cmrr', (["(log_fname + '.puls')"], {}), "(log_fname + '.puls')\n", (18066, 18087), False, 'import dsc_extract_physio\n'), ((18131, 18262), 'dsc_extract_physio.extract_acqTimes_cmrr', 'dsc_extract_physio.extract_acqTimes_cmrr', (['trigger_start_times_puls', 'acqTime_firstImg', 'acqStartTime_puls', 'trigger_end_times_puls'], {}), '(trigger_start_times_puls,\n acqTime_firstImg, acqStartTime_puls, trigger_end_times_puls)\n', (18171, 18262), False, 'import dsc_extract_physio\n'), ((18631, 18650), 'numpy.min', 'np.min', (['repsAcqTime'], {}), '(repsAcqTime)\n', (18637, 18650), True, 'import numpy as np\n'), ((18652, 18671), 'numpy.max', 'np.max', (['repsAcqTime'], {}), '(repsAcqTime)\n', (18658, 18671), True, 'import numpy as np\n'), ((19032, 19059), 'os.path.basename', 'os.path.basename', (['log_fname'], {}), '(log_fname)\n', (19048, 19059), False, 'import os\n'), ((19197, 19271), 'dsc_extract_physio.read_physiolog', 'dsc_extract_physio.read_physiolog', (["(log_fname + '.resp')"], {'sampling_period': '(20)'}), "(log_fname + '.resp', sampling_period=20)\n", (19230, 19271), False, 'import dsc_extract_physio\n'), ((19344, 19413), 'dsc_extract_physio.sort_event_times', 'dsc_extract_physio.sort_event_times', (['epi_acqtime_resp', 'epi_event_resp'], {}), '(epi_acqtime_resp, epi_event_resp)\n', (19379, 19413), False, 'import dsc_extract_physio\n'), ((19462, 19491), 'numpy.sum', 'np.sum', (['reps_table_resp[:, 1]'], {}), '(reps_table_resp[:, 1])\n', (19468, 19491), True, 'import numpy as np\n'), ((20013, 20072), 'dsc_extract_physio.read_physiolog_cmrr', 'dsc_extract_physio.read_physiolog_cmrr', (["(log_fname + '.resp')"], {}), "(log_fname + '.resp')\n", (20051, 20072), False, 'import dsc_extract_physio\n'), ((20299, 20318), 'numpy.min', 'np.min', (['repsAcqTime'], {}), '(repsAcqTime)\n', (20305, 20318), True, 'import numpy as np\n'), ((20320, 20339), 'numpy.max', 'np.max', (['repsAcqTime'], {}), '(repsAcqTime)\n', (20326, 20339), True, 'import numpy as np\n'), ((20884, 20934), 'numpy.hstack', 'np.hstack', (['(time_puls, time_resp[time_puls.size:])'], {}), '((time_puls, time_resp[time_puls.size:]))\n', (20893, 20934), True, 'import numpy as np\n'), ((20957, 21029), 'numpy.pad', 'np.pad', (['puls_values', '(0, resp_values.size - puls_values.size)', '"""reflect"""'], {}), "(puls_values, (0, resp_values.size - puls_values.size), 'reflect')\n", (20963, 21029), True, 'import numpy as np\n'), ((27531, 27578), 'numpy.diff', 'np.diff', (['respTimeCropToMRI[respSignalMax[:, 0]]'], {}), '(respTimeCropToMRI[respSignalMax[:, 0]])\n', (27538, 27578), True, 'import numpy as np\n'), ((33430, 33450), 'numpy.array', 'np.array', (['[[0], [1]]'], {}), '([[0], [1]])\n', (33438, 33450), True, 'import numpy as np\n'), ((34527, 34569), 'numpy.delete', 'np.delete', (['TReff', 'idxAcqToDiscard'], {'axis': '(-1)'}), '(TReff, idxAcqToDiscard, axis=-1)\n', (34536, 34569), True, 'import numpy as np\n'), ((42529, 42543), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (42541, 42543), True, 'import matplotlib.pyplot as plt\n'), ((43179, 43189), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (43187, 43189), True, 'import matplotlib.pyplot as plt\n'), ((43660, 43674), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (43668, 43674), True, 'import numpy as np\n'), ((44163, 44173), 'numpy.flip', 'np.flip', (['h'], {}), '(h)\n', (44170, 44173), True, 'import numpy as np\n'), ((44680, 44694), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (44688, 44694), True, 'import numpy as np\n'), ((45823, 45863), 'numpy.abs', 'np.abs', (['filterInterp[idx_ascending_freq]'], {}), '(filterInterp[idx_ascending_freq])\n', (45829, 45863), True, 'import numpy as np\n'), ((48287, 48301), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (48295, 48301), True, 'import numpy as np\n'), ((48770, 48780), 'numpy.flip', 'np.flip', (['h'], {}), '(h)\n', (48777, 48780), True, 'import numpy as np\n'), ((49287, 49301), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (49295, 49301), True, 'import numpy as np\n'), ((50439, 50479), 'numpy.abs', 'np.abs', (['filterInterp[idx_ascending_freq]'], {}), '(filterInterp[idx_ascending_freq])\n', (50445, 50479), True, 'import numpy as np\n'), ((51714, 51728), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (51722, 51728), True, 'import numpy as np\n'), ((54345, 54370), 'numpy.mean', 'np.mean', (['signal_resampled'], {}), '(signal_resampled)\n', (54352, 54370), True, 'import numpy as np\n'), ((56984, 57000), 'numpy.array', 'np.array', (['maxtab'], {}), '(maxtab)\n', (56992, 57000), True, 'import numpy as np\n'), ((57695, 57717), 'nibabel.load', 'nib.load', (['rvsDataFname'], {}), '(rvsDataFname)\n', (57703, 57717), True, 'import nibabel as nib\n'), ((57756, 57777), 'nibabel.load', 'nib.load', (['rvsMaskname'], {}), '(rvsMaskname)\n', (57764, 57777), True, 'import nibabel as nib\n'), ((58953, 58984), 'numpy.diff', 'np.diff', (['rvsRepsAcqTime_PulseOx'], {}), '(rvsRepsAcqTime_PulseOx)\n', (58960, 58984), True, 'import numpy as np\n'), ((60634, 60660), 'numpy.isnan', 'np.isnan', (['rvsSignalRegGrid'], {}), '(rvsSignalRegGrid)\n', (60642, 60660), True, 'import numpy as np\n'), ((60918, 60949), 'numpy.isnan', 'np.isnan', (['mriSignalInjectRegrid'], {}), '(mriSignalInjectRegrid)\n', (60926, 60949), True, 'import numpy as np\n'), ((61951, 61982), 'numpy.argwhere', 'np.argwhere', (['(injectFFTFreq == 0)'], {}), '(injectFFTFreq == 0)\n', (61962, 61982), True, 'import numpy as np\n'), ((62435, 62466), 'numpy.isnan', 'np.isnan', (['mriSignalInjectRegrid'], {}), '(mriSignalInjectRegrid)\n', (62443, 62466), True, 'import numpy as np\n'), ((62619, 62650), 'numpy.isnan', 'np.isnan', (['mriSignalInjectRegrid'], {}), '(mriSignalInjectRegrid)\n', (62627, 62650), True, 'import numpy as np\n'), ((64004, 64042), 'numpy.abs', 'np.abs', (['rvsFFT[rvs_idx_ascending_freq]'], {}), '(rvsFFT[rvs_idx_ascending_freq])\n', (64010, 64042), True, 'import numpy as np\n'), ((64546, 64590), 'numpy.abs', 'np.abs', (['injectFFT[inject_idx_ascending_freq]'], {}), '(injectFFT[inject_idx_ascending_freq])\n', (64552, 64590), True, 'import numpy as np\n'), ((65647, 65691), 'numpy.abs', 'np.abs', (['injectFFT[inject_idx_ascending_freq]'], {}), '(injectFFT[inject_idx_ascending_freq])\n', (65653, 65691), True, 'import numpy as np\n'), ((65827, 65879), 'numpy.abs', 'np.abs', (['injectFFTfiltered[inject_idx_ascending_freq]'], {}), '(injectFFTfiltered[inject_idx_ascending_freq])\n', (65833, 65879), True, 'import numpy as np\n'), ((66018, 66076), 'numpy.abs', 'np.abs', (['injectFFTfilteredSmooth[inject_idx_ascending_freq]'], {}), '(injectFFTfilteredSmooth[inject_idx_ascending_freq])\n', (66024, 66076), True, 'import numpy as np\n'), ((70382, 70409), 'os.listdir', 'os.listdir', (['physiologFolder'], {}), '(physiologFolder)\n', (70392, 70409), False, 'import os\n'), ((70856, 70923), 'datetime.datetime.strptime', 'datetime.strptime', (["(physio_date + '-' + physio_time)", '"""%Y%m%d-%H%M%S"""'], {}), "(physio_date + '-' + physio_time, '%Y%m%d-%H%M%S')\n", (70873, 70923), False, 'from datetime import datetime\n'), ((70997, 71028), 'numpy.array', 'np.array', (['physiologAcqTime_list'], {}), '(physiologAcqTime_list)\n', (71005, 71028), True, 'import numpy as np\n'), ((71434, 71457), 'numpy.std', 'np.std', (['signal'], {'axis': '(-1)'}), '(signal, axis=-1)\n', (71440, 71457), True, 'import numpy as np\n'), ((75125, 75141), 'numpy.array', 'np.array', (['injRep'], {}), '(injRep)\n', (75133, 75141), True, 'import numpy as np\n'), ((75343, 75376), 'numpy.tile', 'np.tile', (['S0', '(signal.shape[1], 1)'], {}), '(S0, (signal.shape[1], 1))\n', (75350, 75376), True, 'import numpy as np\n'), ((75396, 75413), 'numpy.log', 'np.log', (['S_over_S0'], {}), '(S_over_S0)\n', (75402, 75413), True, 'import numpy as np\n'), ((75508, 75526), 'numpy.array', 'np.array', (['[injRep]'], {}), '([injRep])\n', (75516, 75526), True, 'import numpy as np\n'), ((76118, 76176), 'nibabel.Nifti2Image', 'nib.Nifti2Image', (['data', 'OldNii.affine'], {'header': 'OldNii.header'}), '(data, OldNii.affine, header=OldNii.header)\n', (76133, 76176), True, 'import nibabel as nib\n'), ((837, 881), 'numpy.mean', 'np.mean', (['img_rep_i[mask[:, :, i_z] > 0, i_z]'], {}), '(img_rep_i[mask[:, :, i_z] > 0, i_z])\n', (844, 881), True, 'import numpy as np\n'), ((12020, 12075), 'numpy.round', 'np.round', (['reps_nb_interp_to_time_ticks_locs'], {'decimals': '(0)'}), '(reps_nb_interp_to_time_ticks_locs, decimals=0)\n', (12028, 12075), True, 'import numpy as np\n'), ((17565, 17692), 'os.error', 'os.error', (['"""Number of repetitions in image is different from the number of repetitions recorded in pulseOx physiolog."""'], {}), "(\n 'Number of repetitions in image is different from the number of repetitions recorded in pulseOx physiolog.'\n )\n", (17573, 17692), False, 'import os\n'), ((18295, 18348), 'numpy.tile', 'np.tile', (['triggerStartTimes_imgOnly_puls', '(nSlices, 1)'], {}), '(triggerStartTimes_imgOnly_puls, (nSlices, 1))\n', (18302, 18348), True, 'import numpy as np\n'), ((19546, 19677), 'os.error', 'os.error', (['"""Number of repetitions in image is different from the number of repetitions recorded in respiration physiolog."""'], {}), "(\n 'Number of repetitions in image is different from the number of repetitions recorded in respiration physiolog.'\n )\n", (19554, 19677), False, 'import os\n'), ((29979, 30001), 'numpy.min', 'np.min', (['respPeriod[1:]'], {}), '(respPeriod[1:])\n', (29985, 30001), True, 'import numpy as np\n'), ((30010, 30032), 'numpy.max', 'np.max', (['respPeriod[1:]'], {}), '(respPeriod[1:])\n', (30016, 30032), True, 'import numpy as np\n'), ((41366, 41385), 'numpy.mean', 'np.mean', (['respPeriod'], {}), '(respPeriod)\n', (41373, 41385), True, 'import numpy as np\n'), ((41387, 41405), 'numpy.std', 'np.std', (['respPeriod'], {}), '(respPeriod)\n', (41393, 41405), True, 'import numpy as np\n'), ((43297, 43313), 'numpy.min', 'np.min', (['respFreq'], {}), '(respFreq)\n', (43303, 43313), True, 'import numpy as np\n'), ((43315, 43331), 'numpy.max', 'np.max', (['respFreq'], {}), '(respFreq)\n', (43321, 43331), True, 'import numpy as np\n'), ((44238, 44248), 'numpy.flip', 'np.flip', (['w'], {}), '(w)\n', (44245, 44248), True, 'import numpy as np\n'), ((48845, 48855), 'numpy.flip', 'np.flip', (['w'], {}), '(w)\n', (48852, 48855), True, 'import numpy as np\n'), ((54546, 54573), 'numpy.diff', 'np.diff', (['t_regular_sampling'], {}), '(t_regular_sampling)\n', (54553, 54573), True, 'import numpy as np\n'), ((56855, 56872), 'numpy.arange', 'np.arange', (['v.size'], {}), '(v.size)\n', (56864, 56872), True, 'import numpy as np\n'), ((69646, 69667), 'os.listdir', 'os.listdir', (['dcmFolder'], {}), '(dcmFolder)\n', (69656, 69667), False, 'import os\n'), ((71133, 71188), 'os.path.abspath', 'os.path.abspath', (["(physiologFolder + '/' + physiologFname)"], {}), "(physiologFolder + '/' + physiologFname)\n", (71148, 71188), False, 'import os\n'), ((72557, 72579), 'numpy.abs', 'np.abs', (['(time - injTime)'], {}), '(time - injTime)\n', (72563, 72579), True, 'import numpy as np\n'), ((75172, 75221), 'numpy.mean', 'np.mean', (['signal[i_signal, 0:injRep[i_signal] + 1]'], {}), '(signal[i_signal, 0:injRep[i_signal] + 1])\n', (75179, 75221), True, 'import numpy as np\n'), ((75558, 75607), 'numpy.std', 'np.std', (['DeltaR2[i_signal, 0:injRep[i_signal] + 1]'], {}), '(DeltaR2[i_signal, 0:injRep[i_signal] + 1])\n', (75564, 75607), True, 'import numpy as np\n'), ((18508, 18527), 'numpy.arange', 'np.arange', (['(0)', 'nAcqs'], {}), '(0, nAcqs)\n', (18517, 18527), True, 'import numpy as np\n'), ((20176, 20195), 'numpy.arange', 'np.arange', (['(0)', 'nAcqs'], {}), '(0, nAcqs)\n', (20185, 20195), True, 'import numpy as np\n'), ((27950, 27972), 'numpy.max', 'np.max', (['respPeriod[1:]'], {}), '(respPeriod[1:])\n', (27956, 27972), True, 'import numpy as np\n'), ((31066, 31097), 'numpy.exp', 'np.exp', (['(-cardiacPeriodMean / T1)'], {}), '(-cardiacPeriodMean / T1)\n', (31072, 31097), True, 'import numpy as np\n'), ((42823, 42839), 'numpy.min', 'np.min', (['respFreq'], {}), '(respFreq)\n', (42829, 42839), True, 'import numpy as np\n'), ((42846, 42862), 'numpy.max', 'np.max', (['respFreq'], {}), '(respFreq)\n', (42852, 42862), True, 'import numpy as np\n'), ((60063, 60093), 'numpy.max', 'np.max', (['rvsRepsAcqTime_PulseOx'], {}), '(rvsRepsAcqTime_PulseOx)\n', (60069, 60093), True, 'import numpy as np\n'), ((60096, 60126), 'numpy.min', 'np.min', (['rvsRepsAcqTime_PulseOx'], {}), '(rvsRepsAcqTime_PulseOx)\n', (60102, 60126), True, 'import numpy as np\n'), ((61443, 61471), 'numpy.abs', 'np.abs', (['rvsFFT_interp_ishift'], {}), '(rvsFFT_interp_ishift)\n', (61449, 61471), True, 'import numpy as np\n'), ((61474, 61491), 'numpy.abs', 'np.abs', (['injectFFT'], {}), '(injectFFT)\n', (61480, 61491), True, 'import numpy as np\n'), ((71515, 71531), 'numpy.round', 'np.round', (['cov', '(2)'], {}), '(cov, 2)\n', (71523, 71531), True, 'import numpy as np\n'), ((73927, 73977), 'numpy.array2string', 'np.array2string', (['tSD'], {'precision': '(2)', 'separator': '""" | """'}), "(tSD, precision=2, separator=' | ')\n", (73942, 73977), True, 'import numpy as np\n'), ((14623, 14659), 'numpy.where', 'np.where', (['(reps_table_puls[:, 1] == 1)'], {}), '(reps_table_puls[:, 1] == 1)\n', (14631, 14659), True, 'import numpy as np\n'), ((14839, 14867), 'numpy.max', 'np.max', (['reps_acqtime_pulseOx'], {}), '(reps_acqtime_pulseOx)\n', (14845, 14867), True, 'import numpy as np\n'), ((14870, 14898), 'numpy.min', 'np.min', (['reps_acqtime_pulseOx'], {}), '(reps_acqtime_pulseOx)\n', (14876, 14898), True, 'import numpy as np\n'), ((15884, 15920), 'numpy.where', 'np.where', (['(reps_table_resp[:, 1] == 1)'], {}), '(reps_table_resp[:, 1] == 1)\n', (15892, 15920), True, 'import numpy as np\n'), ((16091, 16116), 'numpy.max', 'np.max', (['reps_acqtime_resp'], {}), '(reps_acqtime_resp)\n', (16097, 16116), True, 'import numpy as np\n'), ((16119, 16144), 'numpy.min', 'np.min', (['reps_acqtime_resp'], {}), '(reps_acqtime_resp)\n', (16125, 16144), True, 'import numpy as np\n'), ((18564, 18585), 'numpy.arange', 'np.arange', (['(0)', 'nSlices'], {}), '(0, nSlices)\n', (18573, 18585), True, 'import numpy as np\n'), ((20232, 20253), 'numpy.arange', 'np.arange', (['(0)', 'nSlices'], {}), '(0, nSlices)\n', (20241, 20253), True, 'import numpy as np\n'), ((67577, 67605), 'os.path.dirname', 'os.path.dirname', (['shFile.name'], {}), '(shFile.name)\n', (67592, 67605), False, 'import os\n'), ((68209, 68237), 'os.path.dirname', 'os.path.dirname', (['shFile.name'], {}), '(shFile.name)\n', (68224, 68237), False, 'import os\n'), ((17798, 17834), 'numpy.where', 'np.where', (['(reps_table_puls[:, 1] == 1)'], {}), '(reps_table_puls[:, 1] == 1)\n', (17806, 17834), True, 'import numpy as np\n'), ((18372, 18393), 'numpy.arange', 'np.arange', (['(0)', 'nSlices'], {}), '(0, nSlices)\n', (18381, 18393), True, 'import numpy as np\n'), ((19783, 19819), 'numpy.where', 'np.where', (['(reps_table_resp[:, 1] == 1)'], {}), '(reps_table_resp[:, 1] == 1)\n', (19791, 19819), True, 'import numpy as np\n'), ((22949, 22964), 'numpy.min', 'np.min', (['mriTime'], {}), '(mriTime)\n', (22955, 22964), True, 'import numpy as np\n'), ((22993, 23008), 'numpy.max', 'np.max', (['mriTime'], {}), '(mriTime)\n', (22999, 23008), True, 'import numpy as np\n'), ((23071, 23086), 'numpy.min', 'np.min', (['mriTime'], {}), '(mriTime)\n', (23077, 23086), True, 'import numpy as np\n'), ((23115, 23130), 'numpy.max', 'np.max', (['mriTime'], {}), '(mriTime)\n', (23121, 23130), True, 'import numpy as np\n'), ((23197, 23212), 'numpy.min', 'np.min', (['mriTime'], {}), '(mriTime)\n', (23203, 23212), True, 'import numpy as np\n'), ((23241, 23256), 'numpy.max', 'np.max', (['mriTime'], {}), '(mriTime)\n', (23247, 23256), True, 'import numpy as np\n'), ((27917, 27939), 'numpy.min', 'np.min', (['respPeriod[1:]'], {}), '(respPeriod[1:])\n', (27923, 27939), True, 'import numpy as np\n'), ((39586, 39601), 'numpy.min', 'np.min', (['mriTime'], {}), '(mriTime)\n', (39592, 39601), True, 'import numpy as np\n'), ((39630, 39645), 'numpy.max', 'np.max', (['mriTime'], {}), '(mriTime)\n', (39636, 39645), True, 'import numpy as np\n'), ((39707, 39722), 'numpy.min', 'np.min', (['mriTime'], {}), '(mriTime)\n', (39713, 39722), True, 'import numpy as np\n'), ((39751, 39766), 'numpy.max', 'np.max', (['mriTime'], {}), '(mriTime)\n', (39757, 39766), True, 'import numpy as np\n'), ((47306, 47321), 'numpy.min', 'np.min', (['mriTime'], {}), '(mriTime)\n', (47312, 47321), True, 'import numpy as np\n'), ((47350, 47365), 'numpy.max', 'np.max', (['mriTime'], {}), '(mriTime)\n', (47356, 47365), True, 'import numpy as np\n'), ((47427, 47442), 'numpy.min', 'np.min', (['mriTime'], {}), '(mriTime)\n', (47433, 47442), True, 'import numpy as np\n'), ((47471, 47486), 'numpy.max', 'np.max', (['mriTime'], {}), '(mriTime)\n', (47477, 47486), True, 'import numpy as np\n'), ((9921, 9949), 'numpy.mean', 'np.mean', (['signal_norm_exp[1:]'], {}), '(signal_norm_exp[1:])\n', (9928, 9949), True, 'import numpy as np\n'), ((10290, 10317), 'numpy.mean', 'np.mean', (['signal_norm_TR[1:]'], {}), '(signal_norm_TR[1:])\n', (10297, 10317), True, 'import numpy as np\n'), ((10659, 10678), 'numpy.mean', 'np.mean', (['signal[1:]'], {}), '(signal[1:])\n', (10666, 10678), True, 'import numpy as np\n'), ((21624, 21658), 'numpy.where', 'np.where', (['(pulseAcqTimes == acqtime)'], {}), '(pulseAcqTimes == acqtime)\n', (21632, 21658), True, 'import numpy as np\n'), ((21805, 21837), 'numpy.where', 'np.where', (['(respAcqTime == acqtime)'], {}), '(respAcqTime == acqtime)\n', (21813, 21837), True, 'import numpy as np\n'), ((24204, 24222), 'numpy.mean', 'np.mean', (['mriSignal'], {}), '(mriSignal)\n', (24211, 24222), True, 'import numpy as np\n'), ((24424, 24461), 'numpy.mean', 'np.mean', (['mriSignalSampledToRespSignal'], {}), '(mriSignalSampledToRespSignal)\n', (24431, 24461), True, 'import numpy as np\n'), ((24798, 24817), 'numpy.mean', 'np.mean', (['respSignal'], {}), '(respSignal)\n', (24805, 24817), True, 'import numpy as np\n'), ((25012, 25049), 'numpy.mean', 'np.mean', (['respSignalSampledToMRISignal'], {}), '(respSignalSampledToMRISignal)\n', (25019, 25049), True, 'import numpy as np\n'), ((9893, 9920), 'numpy.std', 'np.std', (['signal_norm_exp[1:]'], {}), '(signal_norm_exp[1:])\n', (9899, 9920), True, 'import numpy as np\n'), ((10263, 10289), 'numpy.std', 'np.std', (['signal_norm_TR[1:]'], {}), '(signal_norm_TR[1:])\n', (10269, 10289), True, 'import numpy as np\n'), ((10640, 10658), 'numpy.std', 'np.std', (['signal[1:]'], {}), '(signal[1:])\n', (10646, 10658), True, 'import numpy as np\n'), ((24186, 24203), 'numpy.std', 'np.std', (['mriSignal'], {}), '(mriSignal)\n', (24192, 24203), True, 'import numpy as np\n'), ((24387, 24423), 'numpy.std', 'np.std', (['mriSignalSampledToRespSignal'], {}), '(mriSignalSampledToRespSignal)\n', (24393, 24423), True, 'import numpy as np\n'), ((24777, 24795), 'numpy.std', 'np.std', (['respSignal'], {}), '(respSignal)\n', (24783, 24795), True, 'import numpy as np\n'), ((24973, 25009), 'numpy.std', 'np.std', (['respSignalSampledToMRISignal'], {}), '(respSignalSampledToMRISignal)\n', (24979, 25009), True, 'import numpy as np\n'), ((46180, 46198), 'numpy.mean', 'np.mean', (['dataNoNan'], {}), '(dataNoNan)\n', (46187, 46198), True, 'import numpy as np\n'), ((50796, 50814), 'numpy.mean', 'np.mean', (['dataNoNan'], {}), '(dataNoNan)\n', (50803, 50814), True, 'import numpy as np\n'), ((53456, 53474), 'numpy.mean', 'np.mean', (['dataNoNan'], {}), '(dataNoNan)\n', (53463, 53474), True, 'import numpy as np\n'), ((27879, 27902), 'numpy.mean', 'np.mean', (['respPeriod[1:]'], {}), '(respPeriod[1:])\n', (27886, 27902), True, 'import numpy as np\n'), ((46162, 46179), 'numpy.std', 'np.std', (['dataNoNan'], {}), '(dataNoNan)\n', (46168, 46179), True, 'import numpy as np\n'), ((50778, 50795), 'numpy.std', 'np.std', (['dataNoNan'], {}), '(dataNoNan)\n', (50784, 50795), True, 'import numpy as np\n'), ((53438, 53455), 'numpy.std', 'np.std', (['dataNoNan'], {}), '(dataNoNan)\n', (53444, 53455), True, 'import numpy as np\n'), ((57092, 57108), 'numpy.array', 'np.array', (['maxtab'], {}), '(maxtab)\n', (57100, 57108), True, 'import numpy as np\n')] |
import numpy as np
from pathlib import Path
class Experiment_Information:
def __init__(self, name, path, parameters, modulation):
'''
name: str
path: str
parameters: dict
'''
self.name = name
self.path = path
self.parameters = parameters
self.modulation = modulation
class DataReport:
def __init__(self, file = ''):
'''
file: pathlib Path or str
Path to file
'''
self.filename = 'not specified'
self.experiment_code = 'not specified'
self.conditions = {}
self.analysis_details = {}
self.series_values = np.array([])
self.series_unit = 'not specified'
self.data = {}
self.errors = {}
if file == '':
pass
else:
self.read_from_file(file)
def import_file_section(self, file, start_token, end_token):
'''
Parameters
----------
file: path to file
start_token: str
String in line to start reading file from.
end_token:
String in line to end reading file from.
'''
spl_lin = lambda x : [e for e in x.strip('\n').split(',') if e != '']
readstate = False
c_set = []
with open(file, 'r', encoding = 'latin-1') as f:
for c,line in enumerate(f):
if start_token in line:
readstate = True
line = next(f)
if end_token in line:
readstate = False
if readstate:
newline = spl_lin(line)
c_set.append(newline)
return c_set
def read_from_file(self, file):
'''
Parameters
----------
file: pathlib Path or str
'''
spl_lin = lambda x : [e for e in x.strip('\n').split(',') if e != '']
if type(file) == str:
file = Path(file)
self.filename = file.name
with open(file, 'r', encoding = 'latin-1') as f:
for line in f:
ins = spl_lin(line)
if 'Dataset' in line:
self.experiment_code = ins[1]
condset = self.import_file_section(file, "start_conditions",
"end_conditions")
c_out = {}
for c in condset:
entry = [float(x) for x in c[1:]]
if len(entry) == 1:
self.conditions[c[0]] = entry[0]
else:
self.conditions[c[0]] = np.array(entry)
dataset = self.import_file_section(file, "start_data", "end_data")
transposed_datalines = [list(i) for i in zip(*dataset)]
d_out = {}
for s in transposed_datalines:
d_out[s[0]] = np.array([0 if x == 'nan' else float(x) for x in s[1:]])
self.series_unit = dataset[0][0]
self.series_values = d_out[self.series_unit]
del d_out[self.series_unit]
self.data = d_out
errors = self.import_file_section(file, "start_errors", "end_errors")
if len(errors) == 0:
self.errors = {d:np.zeros(len(self.series_values)) for d in self.data}
else:
transposed_error_lines = [list(i) for i in zip(*errors)]
errors_out = {}
for s in transposed_error_lines:
errors_out[s[0]] = np.array([0 if x == 'nan' else float(x) for x in s[1:]])
del errors_out[self.series_unit]
self.errors = errors_out
analysis = self.import_file_section(file, "start_analysis_details",
"end_analysis_details")
for a in analysis:
self.analysis_details[a[0]] = [x for x in a[1:]]
def rows_from_dict(self, dict_container):
'''
Converts the keys and values in a dict_container
into rows of a .csv file, organised in a list.
The values of dict_container are expected to be either iterable
(e.g. list of numpy array) or float/string variables.
Output is a list of strings
Parameters
----------
dict_container: dict
Returns
-------
output_lines: list
'''
output_lines = []
for c in dict_container:
line_str = f'{c},'
if type(dict_container[c]) == float:
line_str += f"{dict_container[c]}"
else:
for x in dict_container[c]:
line_str += f"{x},"
line_str = line_str.strip(',')
output_lines.append(line_str)
return output_lines
def columns_from_dict(self, dict_container):
'''
Converts the keys and values in a dict_container
into columns of a .csv file, organised in a list.
The values of dict_container are expected to be iterable
(e.g. list of numpy array).
Output is a list of strings
Parameters
----------
dict_container: dict
Returns
-------
output_lines: list
'''
output_lines = []
header = [*dict_container]
output_lines.append(','.join(header))
for c, v in enumerate(dict_container[header[0]]):
line_str = ''
for h in header:
line_str += f"{dict_container[h][c]},"
line_str = line_str.strip(',')
output_lines.append(line_str)
return output_lines
def to_string(self):
import numpy as np
if 'Chromatography_method' in self.analysis_details:
an_type = self.analysis_details['Chromatography_method'][0]
else:
an_type = 'not specified'
sorted_keys = sorted([*self.data], key = lambda x:x.count('C'))
p_header = [self.series_unit]
data_section = {self.series_unit: self.series_values}
for d in self.data:
data_section[d] = self.data[d]
error_section = {self.series_unit: self.series_values}
for e in self.errors:
error_section[d] = self.errors[d]
output_lines = []
output_lines.append(f"Dataset,{self.experiment_code}")
output_lines.append("start_conditions")
output_lines.extend(self.rows_from_dict(self.conditions))
output_lines.append("end_conditions")
output_lines.append("start_analysis_details")
output_lines.extend(self.rows_from_dict(self.analysis_details))
output_lines.append("end_analysis_details")
output_lines.append("start_data")
output_lines.extend(self.columns_from_dict(data_section))
output_lines.append("end_data")
output_lines.append("start_errors")
output_lines.extend(self.columns_from_dict(error_section))
output_lines.append("end_errors")
text = '\n'.join(output_lines)
return text
def write_to_file(self, filename = '', path = None):
'''
Parameters
----------
filename: str
name for file
path: pathlib Path object
Path to folder for file storage.
'''
if filename == '':
filename = self.filename
elif not filename.endswith('.csv'):
filename = filename + '.csv'
if path == None:
fname = filename
else:
fname = path/filename
with open(fname, 'w') as outfile:
f.write(self.to_string())
def find_repeat_data_entries(self):
'''
Find compound entries which are repeated in self.data
'''
entries = []
repeat_entries = []
for d in self.data:
token = d.split(' ')[0]
if token in entries:
repeat_entries.append(token)
entries.append(token)
return list(set(repeat_entries))
def remove_repeat_entries(self):
'''
Remove compound entries which are repeated in self.data
'''
import numpy as np
# deleting duplicate entries: taking the entry with the higher signal using the
# signal sum as a discriminant.
repeat_entries = self.find_repeat_data_entries()
for r in repeat_entries:
compare_keys = []
for d in self.data:
if r in d:
compare_keys.append(d)
checkline = np.zeros(len(compare_keys))
for c,comp in enumerate(compare_keys):
checkline[c] = np.sum(self.data[comp])
i_min = np.argmin(checkline)
del self.data[compare_keys[i_min]]
def remove_specific_entries(self,remove_list):
'''
remove entries in remove list from self.data
Parameters
----------
remove_list: list
List of entries to remove from self.data
'''
for r in remove_list:
del self.data[r]
def remove_entries_below_threshold(self, threshold):
'''
remove entries whose maximum value does not exceed threshold
Parameters
----------
threshold: float
threshold below which entries will be removed.
'''
import numpy as np
# remove entries whose concentrations/integrals do not cross a defined boundary
del_list = []
for d in self.data:
if np.amax(self.data[d]) < threshold:
del_list.append(d)
self.remove_specific_entries(del_list)
class DataSet:
'''
Container for multiple data reports
'''
def __init__(self, data_reports = []):
'''
data_reports: list of NorthNet DataReport objects
data reports to create the data set
'''
self.data_reports = {}
self.compounds = []
if len(data_reports) == 0:
pass
else:
for d in data_reports:
self.add_data_report(d)
def add_data_report(self, data_report):
'''
Add data report to DataSet
data_report: NorthNet DataReport
DataReport to be added.
'''
self.data_reports[len(self.data_reports)+1] = data_report
for d in data_report.data:
if d not in self.compounds:
self.compounds.append(d)
def find_entry(self,entry_name):
'''
Get the series_values and values of a given compound.
entry_name: str
Key to the compound in DataReport.data, e.g. [C=O]/ M
Returns: tuple of 1D numpy arrays
(series_values, variable)
'''
x_ax = np.array([])
y_ax = np.array([])
for d in self.data_reports:
if entry_name in self.data_reports[d].data:
y_ax = np.hstack((y_ax, self.data_reports[d].data[entry_name]))
x_ax = np.hstack((x_ax, self.data_reports[d].series_values))
return x_ax, y_ax
def get_entry(self, entry_name):
'''
Wrapper for find_entry(). Sorts the arrays so x_ax values are increasing
with increasing index.
entry_name: str
Key to the compound in DataReport.data, e.g. [C=O]/ M
Returns: tuple of 1D numpy arrays
(series_values, variable)
'''
x_ax, y_ax = self.find_entry(entry_name)
i = np.argsort(x_ax)
x_ax = x_ax[i]
y_ax = y_ax[i]
return x_ax, y_ax
def get_entry_indices(self,entry):
'''
Get the indices which order the data so x_ax values are increasing
with increasing index.
entry: str
Key to the compound in DataReport.data, e.g. [C=O]/ M
returns: i
numpy array of int
'''
x_ax, y_ax = self.find_entry(entry)
i = np.argsort(x_ax)
return i
| [
"pathlib.Path",
"numpy.hstack",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.argmin",
"numpy.amax"
] | [((661, 673), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (669, 673), True, 'import numpy as np\n'), ((10695, 10707), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (10703, 10707), True, 'import numpy as np\n'), ((10723, 10735), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (10731, 10735), True, 'import numpy as np\n'), ((11421, 11437), 'numpy.argsort', 'np.argsort', (['x_ax'], {}), '(x_ax)\n', (11431, 11437), True, 'import numpy as np\n'), ((11874, 11890), 'numpy.argsort', 'np.argsort', (['x_ax'], {}), '(x_ax)\n', (11884, 11890), True, 'import numpy as np\n'), ((1973, 1983), 'pathlib.Path', 'Path', (['file'], {}), '(file)\n', (1977, 1983), False, 'from pathlib import Path\n'), ((8625, 8645), 'numpy.argmin', 'np.argmin', (['checkline'], {}), '(checkline)\n', (8634, 8645), True, 'import numpy as np\n'), ((2590, 2605), 'numpy.array', 'np.array', (['entry'], {}), '(entry)\n', (2598, 2605), True, 'import numpy as np\n'), ((8580, 8603), 'numpy.sum', 'np.sum', (['self.data[comp]'], {}), '(self.data[comp])\n', (8586, 8603), True, 'import numpy as np\n'), ((9454, 9475), 'numpy.amax', 'np.amax', (['self.data[d]'], {}), '(self.data[d])\n', (9461, 9475), True, 'import numpy as np\n'), ((10851, 10907), 'numpy.hstack', 'np.hstack', (['(y_ax, self.data_reports[d].data[entry_name])'], {}), '((y_ax, self.data_reports[d].data[entry_name]))\n', (10860, 10907), True, 'import numpy as np\n'), ((10931, 10984), 'numpy.hstack', 'np.hstack', (['(x_ax, self.data_reports[d].series_values)'], {}), '((x_ax, self.data_reports[d].series_values))\n', (10940, 10984), True, 'import numpy as np\n')] |
"""
Base classes
"""
from abc import ABC, abstractmethod
from torch.optim import SGD, Adam, AdamW
from torch.nn.utils import clip_grad_norm_
import numpy as np
from ..buffers import ReplayBuffer
from ..config.configuration import LocalConfig
from ..networks.actors import FCActorDiscrete, FCActorContinuous
from ..networks.critics import FCCritic, LSTMCritic
class BaseAgent(ABC):
"""
Base agent class
"""
def __init__(self, config, noise):
# Configuration
self.config = config
# Noise process
self.noise = noise
super().__init__()
def _set_policy(self, optimizer=True):
"""
Creates the network defined in the [ACTOR] subsection
of the configuration file.
Parameters
----------
opmizer: bool
Wether define the optimizer or not
"""
actor_config = self.config.ACTOR
# FC architecture
if actor_config.ARCHITECTURE == 'fc':
# Continuous
if self.config.ACTION_SPACE == 'continuous':
policy = FCActorContinuous(self.config.STATE_SIZE,
self.config.ACTION_SIZE,
actor_config.HIDDEN_SIZE,
self.config.SEED,
actor_config.HIDDEN_ACTIV,
actor_config.OUTPUT_LOC_ACTIV,
actor_config.OUTPUT_SCALE_ACTIV,
actor_config.OUTPUT_LOC_SCALER,
self.config.ACTION_RANGE)
# Discrete
elif self.config.ACTION_SPACE == 'discrete':
policy = FCActorDiscrete(self.config.STATE_SIZE,
self.config.ACTION_SIZE,
actor_config.HIDDEN_SIZE,
self.config.SEED,
actor_config.HIDDEN_ACTIV)
# TODO LSTM architecture ACTORS
# Move to device
policy = policy.to(self.config.DEVICE)
# Add optimizer
if optimizer:
policy.__setattr__("optimizer",
self._set_optimizer(policy.parameters(),
actor_config))
return policy
def _set_val_func(self, optimizer=True):
"""
Creates the network defined in the [CRITIC] subsection
of the configuration file.
Parameters
----------
opmizer: bool
Wether define the optimizer or not
"""
critic_config = self.config.CRITIC
if critic_config.ARCHITECTURE == 'fc':
val_func = FCCritic(self.config.STATE_SIZE,
self.config.ACTION_SIZE,
critic_config.HIDDEN_SIZE,
self.config.SEED)
elif critic_config.ARCHITECTURE == 'lstm':
val_func = LSTMCritic(self.config.STATE_SIZE,
self.config.ACTION_SIZE,
critic_config.HIDDEN_SIZE,
self.config.SEED)
# Move to device and return
val_func = val_func.to(self.config.DEVICE)
# Add optimizer
if optimizer:
val_func.__setattr__("optimizer",
self._set_optimizer(val_func.parameters(),
critic_config))
return val_func
def _set_optimizer(self, parameters, config):
if config.OPTIMIZER == 'sgd':
optimizer = SGD(parameters, lr=config.LR,
momentum=config.MOMENTUM)
elif config.OPTIMIZER == 'adamw':
optimizer = AdamW(parameters, lr=config.LR,
weight_decay=config.WEIGHT_DECAY)
else:
# Default
optimizer = Adam(parameters, lr=config.LR,
weight_decay=config.WEIGHT_DECAY)
return optimizer
def _set_buffer(self):
"""
Set the buffer defined in the [BUFFER] subsection
of the configuration file.
"""
buffer_config = self.config.BUFFER
if buffer_config.TYPE == 'replay':
buffer = ReplayBuffer(buffer_config)
else:
msg = f"Noise type {buffer_config.TYPE} not implemented yet."
raise NotImplementedError(msg)
return buffer
def _add_action_noise(self, action):
"""
Modify the action with noise
"""
# Continuous actions
if self.config.ACTION_SPACE == "continuous":
action += self.noise.sample()
# Clipped action
action = np.clip(action,
*self.config.ACTION_RANGE)
# Discrete Actions
elif self.config.ACTION_SPACE == "discrete":
action = self.noise.sample(action)
return action
def _clip_gradient(self, model):
"""
Perform graient clipping in given model
"""
# Gradient clipping
if self.config.TRAINING.GRADIENT_CLIP != 0:
clip_grad_norm_(model.parameters(),
self.config.TRAINING.GRADIENT_CLIP)
@abstractmethod
def step(self):
"""
Perform one step of the agent learning process.
"""
pass
@abstractmethod
def act(self):
pass
@abstractmethod
def _learn(self):
pass
class BaseNoise(ABC):
"""
Base class for noise processes
"""
def __init__(self, config):
self.config = LocalConfig(config)
super().__init__()
@abstractmethod
def sample(self,):
pass
@abstractmethod
def reset(self):
pass
| [
"numpy.clip",
"torch.optim.Adam",
"torch.optim.SGD",
"torch.optim.AdamW"
] | [((3789, 3844), 'torch.optim.SGD', 'SGD', (['parameters'], {'lr': 'config.LR', 'momentum': 'config.MOMENTUM'}), '(parameters, lr=config.LR, momentum=config.MOMENTUM)\n', (3792, 3844), False, 'from torch.optim import SGD, Adam, AdamW\n'), ((4924, 4966), 'numpy.clip', 'np.clip', (['action', '*self.config.ACTION_RANGE'], {}), '(action, *self.config.ACTION_RANGE)\n', (4931, 4966), True, 'import numpy as np\n'), ((3939, 4004), 'torch.optim.AdamW', 'AdamW', (['parameters'], {'lr': 'config.LR', 'weight_decay': 'config.WEIGHT_DECAY'}), '(parameters, lr=config.LR, weight_decay=config.WEIGHT_DECAY)\n', (3944, 4004), False, 'from torch.optim import SGD, Adam, AdamW\n'), ((4095, 4159), 'torch.optim.Adam', 'Adam', (['parameters'], {'lr': 'config.LR', 'weight_decay': 'config.WEIGHT_DECAY'}), '(parameters, lr=config.LR, weight_decay=config.WEIGHT_DECAY)\n', (4099, 4159), False, 'from torch.optim import SGD, Adam, AdamW\n')] |
import numpy as np
import mytorch
import mytorch.functions as F
class LinearRegression:
def __init__(self, input_dim):
self.W = mytorch.Variable(np.zeros(input_dim))
self.b = mytorch.Variable(np.zeros(input_dim))
def predict(self, x):
return self.W * x + self.b
def zerograd(self):
self.W.zerograd()
self.b.zerograd()
def update_weight(self, lr):
self.W.data -= lr * self.W.grad.data
self.b.data -= lr * self.b.grad.data
def mean_square_error(predict, Y):
return F.sum((predict-Y) ** 2) / len(predict)
def linear_regression():
x = np.random.rand(1000, 1)
y = 5 + x * 2 + np.random.rand(1000, 1)
model = LinearRegression((1, 1))
lr = 0.25
iters = 10000
for i in range(iters):
model.zerograd()
pred = model.predict(x)
loss = mean_square_error(pred, y)
loss.backward()
model.update_weight(lr)
if i % 100 == 0:
print(i, model.W, model.b, loss)
print(f"{10} * 2 + 5 = {model.predict(10).data[0][0]}")
linear_regression()
| [
"mytorch.functions.sum",
"numpy.zeros",
"numpy.random.rand"
] | [((621, 644), 'numpy.random.rand', 'np.random.rand', (['(1000)', '(1)'], {}), '(1000, 1)\n', (635, 644), True, 'import numpy as np\n'), ((547, 572), 'mytorch.functions.sum', 'F.sum', (['((predict - Y) ** 2)'], {}), '((predict - Y) ** 2)\n', (552, 572), True, 'import mytorch.functions as F\n'), ((665, 688), 'numpy.random.rand', 'np.random.rand', (['(1000)', '(1)'], {}), '(1000, 1)\n', (679, 688), True, 'import numpy as np\n'), ((159, 178), 'numpy.zeros', 'np.zeros', (['input_dim'], {}), '(input_dim)\n', (167, 178), True, 'import numpy as np\n'), ((214, 233), 'numpy.zeros', 'np.zeros', (['input_dim'], {}), '(input_dim)\n', (222, 233), True, 'import numpy as np\n')] |
'''
Created on Jan 26, 2018
@author: enerve
'''
from __future__ import division
import logging
import math
import numpy as np
class GaussianPlugInClassifier(object):
def __init__(self, X, Y, num_classes=2):
self.X = X
self.Y = Y
self.num_classes = num_classes
self.logger = logging.getLogger(__name__)
# Function that tests data classification for a gaussian plug-in classifier
# and returns confusion matrix
def classify(self, X_test, Y_test, class_weights=None):
if class_weights is None:
class_weights = [1.0 for x in range(self.num_classes)]
num = self.Y.shape[0]
# Precomputed variables
meanX = []
sX_inv = []
coeff = []
pdensity = []
for c in range(self.num_classes):
i_c = self.Y == c # Indices where y==c
num_c = np.sum(i_c)
prior_c = num_c / num
X_c = self.X[i_c] # All class datapoints
# Compute sigma covariance matrix of the gaussian
meanX_c = np.mean(X_c, axis=0)
diffX_c = X_c - meanX_c
# TODO: remove?
diffX_c += np.random.randn(X_c.shape[0], X_c.shape[1]) * 1
self.logger.debug("diffX_c last col: %s", np.sum(diffX_c[:, -1]))
self.logger.debug("X_c last col: %s", np.sum(X_c[:, -1]))
self.logger.debug("Bayes class %d diffX=%s", c, np.sum(diffX_c, axis=0))
sX_c = (1.0 / num_c) * np.dot(diffX_c.T, diffX_c)# + 0.00001
self.logger.debug("Bayes class %d sigma=%s", c, sX_c)
coeff_c = prior_c / math.sqrt(np.linalg.det(sX_c))
sX_inv_c = np.linalg.pinv(sX_c)
meanX.append(meanX_c)
coeff.append(coeff_c)
sX_inv.append(sX_inv_c)
pdensity.append([])
# Quadratic Discriminant Analysis
# b = np.dot(meanX_1, sX_1_inv) - np.dot(meanX_0, sX_0_inv)
# print b.astype(int)
# A = sX_0_inv /2 - sX_1_inv / 2
# print A.astype(int)
c_matrix = np.zeros((self.num_classes, self.num_classes))
# TODO: vectorize
for i in range(X_test.shape[0]):
y = int(Y_test[i])
x = X_test[i]
max_prob = -1
for c in range(self.num_classes):
dx_c = x - meanX[c] # diff
pYx_c = coeff[c] \
* np.exp(-0.5 * np.dot(dx_c, np.dot(sX_inv[c], dx_c.T)))
pdensity[c].append(pYx_c)
if max_prob < pYx_c * class_weights[c]:
max_prob = pYx_c * class_weights[c]
class_prediction = c
c_matrix[y, class_prediction] += 1
return c_matrix, pdensity
| [
"logging.getLogger",
"numpy.mean",
"numpy.linalg.pinv",
"numpy.linalg.det",
"numpy.sum",
"numpy.zeros",
"numpy.dot",
"numpy.random.randn"
] | [((319, 346), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (336, 346), False, 'import logging\n'), ((2176, 2222), 'numpy.zeros', 'np.zeros', (['(self.num_classes, self.num_classes)'], {}), '((self.num_classes, self.num_classes))\n', (2184, 2222), True, 'import numpy as np\n'), ((916, 927), 'numpy.sum', 'np.sum', (['i_c'], {}), '(i_c)\n', (922, 927), True, 'import numpy as np\n'), ((1116, 1136), 'numpy.mean', 'np.mean', (['X_c'], {'axis': '(0)'}), '(X_c, axis=0)\n', (1123, 1136), True, 'import numpy as np\n'), ((1744, 1764), 'numpy.linalg.pinv', 'np.linalg.pinv', (['sX_c'], {}), '(sX_c)\n', (1758, 1764), True, 'import numpy as np\n'), ((1224, 1267), 'numpy.random.randn', 'np.random.randn', (['X_c.shape[0]', 'X_c.shape[1]'], {}), '(X_c.shape[0], X_c.shape[1])\n', (1239, 1267), True, 'import numpy as np\n'), ((1326, 1348), 'numpy.sum', 'np.sum', (['diffX_c[:, -1]'], {}), '(diffX_c[:, -1])\n', (1332, 1348), True, 'import numpy as np\n'), ((1400, 1418), 'numpy.sum', 'np.sum', (['X_c[:, -1]'], {}), '(X_c[:, -1])\n', (1406, 1418), True, 'import numpy as np\n'), ((1493, 1516), 'numpy.sum', 'np.sum', (['diffX_c'], {'axis': '(0)'}), '(diffX_c, axis=0)\n', (1499, 1516), True, 'import numpy as np\n'), ((1553, 1579), 'numpy.dot', 'np.dot', (['diffX_c.T', 'diffX_c'], {}), '(diffX_c.T, diffX_c)\n', (1559, 1579), True, 'import numpy as np\n'), ((1700, 1719), 'numpy.linalg.det', 'np.linalg.det', (['sX_c'], {}), '(sX_c)\n', (1713, 1719), True, 'import numpy as np\n'), ((2553, 2578), 'numpy.dot', 'np.dot', (['sX_inv[c]', 'dx_c.T'], {}), '(sX_inv[c], dx_c.T)\n', (2559, 2578), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
def sp_net(radius):
base_angle = np.linspace(-90, 90, 100)
base_length = 1 / np.cos(base_angle * np.pi / 180)
angle2point = (180 / np.pi) * np.arctan(1/base_length)
angle_inner = 45 - angle2point* 0.5
opposite = radius * np.tan(angle_inner * np.pi / 180)
x = opposite * np.cos(base_angle * np.pi / 180)
y = opposite * np.sin(base_angle * np.pi / 180)
diag = radius * np.cos(np.pi/4)
diag_m = np.linspace(-diag, diag)
orth = np.linspace(-radius, radius, 2)
plt.plot(x, y, c='k')
plt.plot(-x, y, c='k')
plt.plot(y, x, c='k')
plt.plot(y, -x, c='k')
plt.plot(diag_m, diag_m, c='k')
plt.plot(diag_m, -diag_m, c='k')
plt.plot(np.zeros(2), orth, c='k')
plt.plot(orth, np.zeros(2), c='k')
circle1 = plt.Circle((0, 0), radius, color='k', fill = False)
plt.gca().add_patch(circle1)
plt.gca().set_aspect('equal', adjustable='box')
#plt.show()
| [
"matplotlib.pyplot.Circle",
"numpy.tan",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.plot",
"numpy.linspace",
"numpy.zeros",
"numpy.cos",
"numpy.sin",
"numpy.arctan"
] | [((89, 114), 'numpy.linspace', 'np.linspace', (['(-90)', '(90)', '(100)'], {}), '(-90, 90, 100)\n', (100, 114), True, 'import numpy as np\n'), ((482, 506), 'numpy.linspace', 'np.linspace', (['(-diag)', 'diag'], {}), '(-diag, diag)\n', (493, 506), True, 'import numpy as np\n'), ((519, 550), 'numpy.linspace', 'np.linspace', (['(-radius)', 'radius', '(2)'], {}), '(-radius, radius, 2)\n', (530, 550), True, 'import numpy as np\n'), ((556, 577), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'c': '"""k"""'}), "(x, y, c='k')\n", (564, 577), True, 'import matplotlib.pyplot as plt\n'), ((582, 604), 'matplotlib.pyplot.plot', 'plt.plot', (['(-x)', 'y'], {'c': '"""k"""'}), "(-x, y, c='k')\n", (590, 604), True, 'import matplotlib.pyplot as plt\n'), ((609, 630), 'matplotlib.pyplot.plot', 'plt.plot', (['y', 'x'], {'c': '"""k"""'}), "(y, x, c='k')\n", (617, 630), True, 'import matplotlib.pyplot as plt\n'), ((635, 657), 'matplotlib.pyplot.plot', 'plt.plot', (['y', '(-x)'], {'c': '"""k"""'}), "(y, -x, c='k')\n", (643, 657), True, 'import matplotlib.pyplot as plt\n'), ((663, 694), 'matplotlib.pyplot.plot', 'plt.plot', (['diag_m', 'diag_m'], {'c': '"""k"""'}), "(diag_m, diag_m, c='k')\n", (671, 694), True, 'import matplotlib.pyplot as plt\n'), ((699, 731), 'matplotlib.pyplot.plot', 'plt.plot', (['diag_m', '(-diag_m)'], {'c': '"""k"""'}), "(diag_m, -diag_m, c='k')\n", (707, 731), True, 'import matplotlib.pyplot as plt\n'), ((826, 875), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(0, 0)', 'radius'], {'color': '"""k"""', 'fill': '(False)'}), "((0, 0), radius, color='k', fill=False)\n", (836, 875), True, 'import matplotlib.pyplot as plt\n'), ((137, 169), 'numpy.cos', 'np.cos', (['(base_angle * np.pi / 180)'], {}), '(base_angle * np.pi / 180)\n', (143, 169), True, 'import numpy as np\n'), ((204, 230), 'numpy.arctan', 'np.arctan', (['(1 / base_length)'], {}), '(1 / base_length)\n', (213, 230), True, 'import numpy as np\n'), ((293, 326), 'numpy.tan', 'np.tan', (['(angle_inner * np.pi / 180)'], {}), '(angle_inner * np.pi / 180)\n', (299, 326), True, 'import numpy as np\n'), ((347, 379), 'numpy.cos', 'np.cos', (['(base_angle * np.pi / 180)'], {}), '(base_angle * np.pi / 180)\n', (353, 379), True, 'import numpy as np\n'), ((399, 431), 'numpy.sin', 'np.sin', (['(base_angle * np.pi / 180)'], {}), '(base_angle * np.pi / 180)\n', (405, 431), True, 'import numpy as np\n'), ((453, 470), 'numpy.cos', 'np.cos', (['(np.pi / 4)'], {}), '(np.pi / 4)\n', (459, 470), True, 'import numpy as np\n'), ((746, 757), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (754, 757), True, 'import numpy as np\n'), ((791, 802), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (799, 802), True, 'import numpy as np\n'), ((882, 891), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (889, 891), True, 'import matplotlib.pyplot as plt\n'), ((916, 925), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (923, 925), True, 'import matplotlib.pyplot as plt\n')] |
import json
import numpy as np
import logging
logger = logging.getLogger(__name__)
class DirichletDist():
def __init__(self, config, **kwargs):
n_classes = config.n_classes
prior_alpha = np.zeros((n_classes, n_classes))
if config.worker.prior.type == 'predefined_homegeneous' or len(kwargs) == 0:
logger.debug('Use Predefined worker prior')
neg_density = config.worker.prior.predefined_params.neg_count / n_classes
prior_alpha += config.worker.prior.predefined_params.neg_count / n_classes
prior_alpha += np.eye(n_classes) * (config.worker.prior.predefined_params.pos_count - neg_density)
else:
logger.debug('Use worker prior: {}'.format(config.worker.prior.type))
if config.worker.prior.type == 'homegeneous_workers':
# Diagonal terms are initialized by the correctness of all the workers
# Off-diagonal terms are initialized by the incorrecness of all the workers
global_cm = kwargs['global_cm']
off_diagonal_density = (global_cm.sum(1).mean() - global_cm.diagonal().mean()) / (n_classes-1)
prior_alpha += off_diagonal_density
np.fill_diagonal(prior_alpha, np.ones(n_classes) * global_cm.diagonal().mean())
elif config.worker.prior.type == 'homegeneous_workers_diagonal_perfect':
# Diagonal terms are initialized by the per-class correctness of all the workers
# Off-diagonal terms are initialized by the per-class incorrecness of all the workers
global_cm = kwargs['global_cm']
off_diagonal_density = global_cm.sum(1) - global_cm.diagonal()
off_diagonal_density = off_diagonal_density.reshape(-1, 1) / (n_classes - 1)
prior_alpha += off_diagonal_density
np.fill_diagonal(prior_alpha, global_cm.diagonal())
elif config.worker.prior.type == 'homegeneous_workers_perfect':
# Diagonal terms are initialized by the per-class correctness of all the workers
# Off-diagonal terms are initialized by the per-class-per-prediction incorrecness of all the workers
global_cm = kwargs['global_cm']
prior_alpha = global_cm
elif config.worker.prior.type == 'heterogeneous_workers':
# Diagonal terms are initialized by the correctness of the workers
# Off-diagonal terms are initialized by the incorrecness of the workers
worker_cm = kwargs['worker_cm']
off_diagonal_density = (worker_cm.sum(1).mean() - worker_cm.diagonal().mean()) / (n_classes-1)
prior_alpha += off_diagonal_density
np.fill_diagonal(prior_alpha, np.ones(n_classes) * worker_cm.diagonal().mean())
elif config.worker.prior.type == 'heterogeneous_workers_diagonal_perfect':
# Diagonal terms are initialized by the per-class correctness of the workers
# Off-diagonal terms are initialized by the per-class incorrecness of the workers
worker_cm = kwargs['worker_cm']
off_diagonal_density = worker_cm.sum(1) - worker_cm.diagonal()
off_diagonal_density = off_diagonal_density.reshape(-1, 1) / (n_classes - 1)
prior_alpha += off_diagonal_density
np.fill_diagonal(prior_alpha, worker_cm.diagonal())
elif config.worker.prior.type == 'heterogeneous_workers_perfect':
# Diagonal terms are initialized by the per-class correctness of all the workers
# Off-diagonal terms are initialized by the per-class-per-prediction incorrecness of all the workers
worker_cm = kwargs['worker_cm']
prior_alpha = worker_cm
else:
raise ValueError
self.prior_alpha = prior_alpha * config.worker.prior.strength
self.n_classes = n_classes
self.init_posterior()
def init_posterior(self):
self.posterior_alpha = np.zeros((self.n_classes, self.n_classes))
def save_state(self):
return json.dumps({'posterior_alpha': self.posterior_alpha.tolist(),
'prior_alpha': self.prior_alpha.tolist()})
def load_state(self, state):
state = json.loads(state)
self.posterior_alpha = state['posterior_alpha']
def batch_confidence(self, belief):
# belief: (n_samples, n_classes)
if len(belief.shape) == 1:
belief = belief.reshape(1, -1)
cm = self.prior_alpha + self.posterior_alpha
cm = cm / cm.sum(1, keepdims=True)
c = (belief * cm.diagonal().reshape(1, -1)).sum(1).mean()
return c
def p_z_given_y(self, z):
cm = self.prior_alpha + self.posterior_alpha
cm = cm / cm.sum(1, keepdims=True)
return cm[:, z]
def update(self, eval_list):
posterior_alpha = np.zeros((self.n_classes, self.n_classes))
for i in eval_list:
prob, z = i
pred = np.argmax(prob + np.random.rand(self.n_classes)*1e-8) # Add noise to break tie
posterior_alpha[pred, z] += 1.
self.posterior_alpha = posterior_alpha
| [
"logging.getLogger",
"numpy.eye",
"json.loads",
"numpy.ones",
"numpy.random.rand",
"numpy.zeros"
] | [((56, 83), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (73, 83), False, 'import logging\n'), ((211, 243), 'numpy.zeros', 'np.zeros', (['(n_classes, n_classes)'], {}), '((n_classes, n_classes))\n', (219, 243), True, 'import numpy as np\n'), ((4122, 4164), 'numpy.zeros', 'np.zeros', (['(self.n_classes, self.n_classes)'], {}), '((self.n_classes, self.n_classes))\n', (4130, 4164), True, 'import numpy as np\n'), ((4390, 4407), 'json.loads', 'json.loads', (['state'], {}), '(state)\n', (4400, 4407), False, 'import json\n'), ((5015, 5057), 'numpy.zeros', 'np.zeros', (['(self.n_classes, self.n_classes)'], {}), '((self.n_classes, self.n_classes))\n', (5023, 5057), True, 'import numpy as np\n'), ((585, 602), 'numpy.eye', 'np.eye', (['n_classes'], {}), '(n_classes)\n', (591, 602), True, 'import numpy as np\n'), ((1267, 1285), 'numpy.ones', 'np.ones', (['n_classes'], {}), '(n_classes)\n', (1274, 1285), True, 'import numpy as np\n'), ((5146, 5176), 'numpy.random.rand', 'np.random.rand', (['self.n_classes'], {}), '(self.n_classes)\n', (5160, 5176), True, 'import numpy as np\n'), ((2817, 2835), 'numpy.ones', 'np.ones', (['n_classes'], {}), '(n_classes)\n', (2824, 2835), True, 'import numpy as np\n')] |
# Requires sklearn!
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification, make_hastie_10_2
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from autorank import autorank, create_report
clf_names = ["Linear SVM", "RBF SVM", "Decision Tree", "Random Forest", "Neural Net", "Naive Bayes"]
classifiers = [
SVC(kernel="linear", C=0.025),
SVC(gamma=2, C=1),
DecisionTreeClassifier(max_depth=5),
RandomForestClassifier(max_depth=5, n_estimators=100, max_features=1),
MLPClassifier(alpha=1, max_iter=1000),
GaussianNB()]
data_names = []
datasets = []
for i in range(0, 5):
X, y = make_classification(n_features=2, n_redundant=0, n_informative=2,
random_state=i, n_clusters_per_class=1)
rng = np.random.RandomState(i)
X += 2 * rng.uniform(size=X.shape)
linearly_separable = (X, y)
data_names.append('moons_%i' % i)
data_names.append('circles_%i' % i)
data_names.append('linsep_%i' % i)
data_names.append('hastie_%i' % i)
datasets.append(make_moons(noise=0.3, random_state=i))
datasets.append(make_circles(noise=0.2, factor=0.5, random_state=i))
datasets.append(linearly_separable)
datasets.append(make_hastie_10_2(1000, random_state=i))
results = pd.DataFrame(index=data_names, columns=clf_names)
for data_name, data in zip(data_names, datasets):
X, y = data
X = StandardScaler().fit_transform(X)
scores = []
# iterate over classifiers
for clf_name, clf in zip(clf_names, classifiers):
print("Applying %s to %s" % (clf_name, data_name))
res = cross_val_score(estimator=clf, X=X, y=y, cv=10, scoring='accuracy')
results.at[data_name, clf_name] = res.mean()
res = autorank(results)
create_report(res)
plot_stats(res)
plt.show()
latex_table(res) | [
"sklearn.neural_network.MLPClassifier",
"matplotlib.pyplot.show",
"sklearn.model_selection.cross_val_score",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.datasets.make_hastie_10_2",
"sklearn.datasets.make_moons",
"sklearn.preprocessing.StandardScaler",
"... | [((1614, 1663), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'data_names', 'columns': 'clf_names'}), '(index=data_names, columns=clf_names)\n', (1626, 1663), True, 'import pandas as pd\n'), ((2075, 2092), 'autorank.autorank', 'autorank', (['results'], {}), '(results)\n', (2083, 2092), False, 'from autorank import autorank, create_report\n'), ((2093, 2111), 'autorank.create_report', 'create_report', (['res'], {}), '(res)\n', (2106, 2111), False, 'from autorank import autorank, create_report\n'), ((2128, 2138), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2136, 2138), True, 'import matplotlib.pyplot as plt\n'), ((676, 705), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""', 'C': '(0.025)'}), "(kernel='linear', C=0.025)\n", (679, 705), False, 'from sklearn.svm import SVC\n'), ((711, 728), 'sklearn.svm.SVC', 'SVC', ([], {'gamma': '(2)', 'C': '(1)'}), '(gamma=2, C=1)\n', (714, 728), False, 'from sklearn.svm import SVC\n'), ((734, 769), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'max_depth': '(5)'}), '(max_depth=5)\n', (756, 769), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((775, 844), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'max_depth': '(5)', 'n_estimators': '(100)', 'max_features': '(1)'}), '(max_depth=5, n_estimators=100, max_features=1)\n', (797, 844), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((850, 887), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'alpha': '(1)', 'max_iter': '(1000)'}), '(alpha=1, max_iter=1000)\n', (863, 887), False, 'from sklearn.neural_network import MLPClassifier\n'), ((893, 905), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (903, 905), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((971, 1080), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_features': '(2)', 'n_redundant': '(0)', 'n_informative': '(2)', 'random_state': 'i', 'n_clusters_per_class': '(1)'}), '(n_features=2, n_redundant=0, n_informative=2,\n random_state=i, n_clusters_per_class=1)\n', (990, 1080), False, 'from sklearn.datasets import make_moons, make_circles, make_classification, make_hastie_10_2\n'), ((1118, 1142), 'numpy.random.RandomState', 'np.random.RandomState', (['i'], {}), '(i)\n', (1139, 1142), True, 'import numpy as np\n'), ((1391, 1428), 'sklearn.datasets.make_moons', 'make_moons', ([], {'noise': '(0.3)', 'random_state': 'i'}), '(noise=0.3, random_state=i)\n', (1401, 1428), False, 'from sklearn.datasets import make_moons, make_circles, make_classification, make_hastie_10_2\n'), ((1450, 1501), 'sklearn.datasets.make_circles', 'make_circles', ([], {'noise': '(0.2)', 'factor': '(0.5)', 'random_state': 'i'}), '(noise=0.2, factor=0.5, random_state=i)\n', (1462, 1501), False, 'from sklearn.datasets import make_moons, make_circles, make_classification, make_hastie_10_2\n'), ((1563, 1601), 'sklearn.datasets.make_hastie_10_2', 'make_hastie_10_2', (['(1000)'], {'random_state': 'i'}), '(1000, random_state=i)\n', (1579, 1601), False, 'from sklearn.datasets import make_moons, make_circles, make_classification, make_hastie_10_2\n'), ((1947, 2014), 'sklearn.model_selection.cross_val_score', 'cross_val_score', ([], {'estimator': 'clf', 'X': 'X', 'y': 'y', 'cv': '(10)', 'scoring': '"""accuracy"""'}), "(estimator=clf, X=X, y=y, cv=10, scoring='accuracy')\n", (1962, 2014), False, 'from sklearn.model_selection import cross_val_score\n'), ((1739, 1755), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1753, 1755), False, 'from sklearn.preprocessing import StandardScaler\n')] |
import numpy as np
def clipit(data, low, high, method, center):
"""Clips data in the current segment"""
# For the center point, take the median (if center_code==0), else the mean
if center == 'mad':
mid = np.nanmedian(data)
else:
mid = np.nanmean(data)
data = np.nan_to_num(data)
diff = data - mid
if method == 'median':
cutoff = np.nanmedian(np.abs(data - mid))
else:
cutoff = np.nanstd(data)
# Clip values high (low) times the threshold (in MAD or STDEV)
data[diff > high * cutoff] = np.nan
data[diff < -low * cutoff] = np.nan
return data
def slide_clip(time, data, window_length, low=3, high=3, method=None, center=None):
"""Sliding time-windowed outlier clipper.
Parameters
----------
time : array-like
Time values
flux : array-like
Flux values for every time point
window_length : float
The length of the filter window in units of ``time`` (usually days)
low : float or int
Lower bound factor of clipping. Default is 3.
high : float or int
Lower bound factor of clipping. Default is 3.
method : ``mad`` (median absolute deviation; default) or ``std`` (standard deviation)
Outliers more than ``low`` and ``high`` times the ``mad`` (or the ``std``) from
the middle point are clipped
center : ``median`` (default) or ``mean``
Method to determine the middle point
Returns
-------
clipped : array-like
Input array with clipped elements replaced by ``NaN`` values.
"""
if method is None:
method = 'mad'
if center is None:
center = 'median'
low_index = np.min(time)
hi_index = np.max(time)
idx_start = 0
idx_end = 0
size = len(time)
half_window = window_length / 2
clipped_data = np.full(size, np.nan)
for i in range(size-1):
if time[i] > low_index and time[i] < hi_index:
# Nice style would be:
# idx_start = numpy.argmax(time > time[i] - window_length/2)
# idx_end = numpy.argmax(time > time[i] + window_length/2)
# But that's too slow (factor 10). Instead, we write:
while time[idx_start] < time[i] - half_window:
idx_start += 1
while time[idx_end] < time[i] + half_window and idx_end < size-1:
idx_end += 1
# Clip the current sliding segment
clipped_data[idx_start:idx_end] = clipit(
data[idx_start:idx_end], low, high, method, center)
return clipped_data
| [
"numpy.abs",
"numpy.nanstd",
"numpy.nanmedian",
"numpy.max",
"numpy.nanmean",
"numpy.min",
"numpy.full",
"numpy.nan_to_num"
] | [((299, 318), 'numpy.nan_to_num', 'np.nan_to_num', (['data'], {}), '(data)\n', (312, 318), True, 'import numpy as np\n'), ((1699, 1711), 'numpy.min', 'np.min', (['time'], {}), '(time)\n', (1705, 1711), True, 'import numpy as np\n'), ((1727, 1739), 'numpy.max', 'np.max', (['time'], {}), '(time)\n', (1733, 1739), True, 'import numpy as np\n'), ((1850, 1871), 'numpy.full', 'np.full', (['size', 'np.nan'], {}), '(size, np.nan)\n', (1857, 1871), True, 'import numpy as np\n'), ((228, 246), 'numpy.nanmedian', 'np.nanmedian', (['data'], {}), '(data)\n', (240, 246), True, 'import numpy as np\n'), ((271, 287), 'numpy.nanmean', 'np.nanmean', (['data'], {}), '(data)\n', (281, 287), True, 'import numpy as np\n'), ((446, 461), 'numpy.nanstd', 'np.nanstd', (['data'], {}), '(data)\n', (455, 461), True, 'import numpy as np\n'), ((399, 417), 'numpy.abs', 'np.abs', (['(data - mid)'], {}), '(data - mid)\n', (405, 417), True, 'import numpy as np\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.spatial.transform import Rotation as R
from scipy.spatial.transform import Slerp
from airobot.utils import common
class Position:
"""
Class for representing 3D positions.
Attributes:
x (float): x coordinate.
y (float): y coordinate.
z (float): z coordinate.
"""
def __init__(self):
self.x = 0.
self.y = 0.
self.z = 0.
class Orientation:
"""
Class for representing 3D orientations,
as a quaternion.
Attributes:
x (float): qx value.
y (float): qy value.
z (float): qz value.
w (float): qw value.
"""
def __init__(self):
self.x = 0.
self.y = 0.
self.z = 0.
self.w = 0.
class Pose:
"""
Class to represent a 6D pose, using a 3D position and
3D orientation, represented as a quaternion.
Attributes:
position (Position): 3D position.
orientation (Orientation): 3D orientation (quaternion).
"""
def __init__(self, position, orientation):
self.position = position
self.orientation = orientation
class Header:
"""
Class to represent the header that would accompany a
6D pose, containing a frame name.
Attributes:
frame_id (string): Name of coordinate frame.
"""
def __init__(self):
self.frame_id = "world"
class PoseStamped():
"""
Class to represent a 6D pose, expressed in a particular frame.
Attributes:
pose (Pose): 6D pose.
header (Header): Header, with frame information.
"""
def __init__(self):
position = Position()
orientation = Orientation()
pose = Pose(position, orientation)
header = Header()
self.pose = pose
self.header = header
def pose_stamped2list(msg):
"""
Function to convert a pose_stamped into a list
Args:
msg (PoseStamped): 6D pose.
Returns:
list: 6D pose, as list [x, y, z, qx, qy, qz, qw].
"""
return [float(msg.pose.position.x),
float(msg.pose.position.y),
float(msg.pose.position.z),
float(msg.pose.orientation.x),
float(msg.pose.orientation.y),
float(msg.pose.orientation.z),
float(msg.pose.orientation.w),
]
def list2pose_stamped(pose, frame_id="world"):
"""
Function to convert a list into a pose_stamped
Args:
pose (list): 6D pose, as list [x, y, z, qx, qy, qz, qw].
frame_id (str, optional): Frame this pose is expressed in.
Returns:
PoseStamped: 6D pose as a PoseStamped.
"""
msg = PoseStamped()
msg.header.frame_id = frame_id
msg.pose.position.x = pose[0]
msg.pose.position.y = pose[1]
msg.pose.position.z = pose[2]
msg.pose.orientation.x = pose[3]
msg.pose.orientation.y = pose[4]
msg.pose.orientation.z = pose[5]
msg.pose.orientation.w = pose[6]
return msg
def unit_pose():
"""
Function to create a canonical pose, centered as the origin
and not rotated about any axis.
Returns:
PoseStamped: 6D canonical pose.
"""
return list2pose_stamped([0, 0, 0, 0, 0, 0, 1])
def matrix_from_pose(pose):
"""
Function to convert from a PoseStamped to a
homogeneous transformation matrix.
Args:
pose (PoseStamped): 6D pose, to convert to transformation matrix.
Returns:
np.ndarray: Homogeneous transformation matrix representation of
the pose.
"""
pose_list = pose_stamped2list(pose)
trans, quat = pose_list[:3], pose_list[3:]
T = np.eye(4)
T[:-1, :-1] = common.quat2rot(quat)
T[0:3, 3] = trans
return T
def pose_from_matrix(matrix, frame_id="world"):
"""
Function to convert from a homogeneous transformation matrix to
a PoseStamped.
Args:
matrix (np.ndarray): Homogeneous transformation matrix,
shape :math:`4x4`.
frame_id (str, optional): Reference frame of the pose.
Returns:
PoseStamped: 6D pose representation of the transformation matrix.
"""
quat = common.rot2quat(matrix[:-1, :-1])
trans = matrix[:-1, -1]
pose = list(trans) + list(quat)
pose = list2pose_stamped(pose, frame_id=frame_id)
return pose
def get_transform(pose_frame_target, pose_frame_source):
"""
Function to find a transform that transforms pose source to
pose target. Both poses must be expressed in the same reference frame.
Args:
pose_frame_target (PoseStamped): Target 6D pose.
pose_frame_source (PoseStamped): Source 6D pose.
Returns:
PoseStamped: Relative pose, which, if applied to pose_frame_source,
will transform it to pose_frame_target.
"""
#both poses must be expressed in same reference frame
T_target_world = matrix_from_pose(pose_frame_target)
T_source_world = matrix_from_pose(pose_frame_source)
T_relative_world = np.matmul(T_target_world, np.linalg.inv(T_source_world))
pose_relative_world = pose_from_matrix(
T_relative_world, frame_id=pose_frame_source.header.frame_id)
return pose_relative_world
def convert_reference_frame(pose_source, pose_frame_target, pose_frame_source,
frame_id="world"):
"""
Function to represent a pose expressed in a source reference frame, in a
different target reference frame.
Args:
pose_source (PoseStamped): 6D pose, expressed in pose_frame_source reference frame.
pose_frame_target (PoseStamped): Reference frame to express the returned pose with
respect to.
pose_frame_source (PoseStamped): Reference frame that pose_source is expressed in.
frame_id (str): Name to add to the PoseStamped, indicating the name of the target
reference frame.
Returns:
PoseStamped: 6D pose expressed in the target frame.
"""
T_pose_source = matrix_from_pose(pose_source)
pose_transform_target2source = get_transform(
pose_frame_source, pose_frame_target)
T_pose_transform_target2source = matrix_from_pose(
pose_transform_target2source)
T_pose_target = np.matmul(T_pose_transform_target2source, T_pose_source)
pose_target = pose_from_matrix(T_pose_target, frame_id=frame_id)
return pose_target
def transform_pose(pose_source, pose_transform):
"""
Function to apply a world frame transformation to a 6D pose.
Args:
pose_source (PoseStamped): Original source pose to apply transformation to.
pose_transform (PoseStamped): Transformation to apply to source pose.
Returns:
PoseStamped: Transformed 6D pose.
"""
T_pose_source = matrix_from_pose(pose_source)
T_transform_source = matrix_from_pose(pose_transform)
T_pose_final_source = np.matmul(T_transform_source, T_pose_source)
pose_final_source = pose_from_matrix(
T_pose_final_source, frame_id=pose_source.header.frame_id)
return pose_final_source
def transform_body(pose_source_world, pose_transform_target_body):
"""
Function to apply a body frame transformation to a 6D pose.
Args:
pose_source_world (PoseStamped): Original source pose to transform
pose_transform_target_body (PoseStamped): Body frame transformation
to apply to source pose.
Returns:
PoseStamped: Transformed 6D pose.
"""
#convert source to target frame
pose_source_body = convert_reference_frame(pose_source_world,
pose_source_world,
unit_pose(),
frame_id="body_frame")
#perform transformation in body frame
pose_source_rotated_body = transform_pose(pose_source_body,
pose_transform_target_body)
# rotate back
pose_source_rotated_world = convert_reference_frame(pose_source_rotated_body,
unit_pose(),
pose_source_world,
frame_id="yumi_body")
return pose_source_rotated_world
def interpolate_pose(pose_initial, pose_final, N):
"""
Function to interpolate between two poses using a combination of
linear position interpolation and quaternion spherical-linear
interpolation (SLERP)
Args:
pose_initial (PoseStamped): Initial pose
pose_final (PoseStamped): Final pose
N (int): Number of intermediate points.
Returns:
list: List of poses that interpolates between initial and final pose.
Each element is PoseStamped.
"""
frame_id = pose_initial.header.frame_id
pose_initial_list = pose_stamped2list(pose_initial)
pose_final_list = pose_stamped2list(pose_final)
trans_initial = pose_initial_list[:3]
quat_initial = pose_initial_list[3:]
trans_final = pose_final_list[:3]
quat_final = pose_final_list[3:]
trans_interp_total = [np.linspace(trans_initial[0], trans_final[0], num=N),
np.linspace(trans_initial[1], trans_final[1], num=N),
np.linspace(trans_initial[2], trans_final[2], num=N)]
key_rots = R.from_quat([quat_initial, quat_final])
slerp = Slerp(np.arange(2), key_rots)
interp_rots = slerp(np.linspace(0, 1, N))
quat_interp_total = interp_rots.as_quat()
pose_interp = []
for counter in range(N):
pose_tmp = [
trans_interp_total[0][counter],
trans_interp_total[1][counter],
trans_interp_total[2][counter],
quat_interp_total[counter][0],
quat_interp_total[counter][1],
quat_interp_total[counter][2],
quat_interp_total[counter][3],
]
pose_interp.append(list2pose_stamped(pose_tmp, frame_id=frame_id))
return pose_interp
| [
"numpy.eye",
"airobot.utils.common.rot2quat",
"scipy.spatial.transform.Rotation.from_quat",
"numpy.linspace",
"numpy.linalg.inv",
"numpy.matmul",
"airobot.utils.common.quat2rot",
"numpy.arange"
] | [((3754, 3763), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (3760, 3763), True, 'import numpy as np\n'), ((3782, 3803), 'airobot.utils.common.quat2rot', 'common.quat2rot', (['quat'], {}), '(quat)\n', (3797, 3803), False, 'from airobot.utils import common\n'), ((4261, 4294), 'airobot.utils.common.rot2quat', 'common.rot2quat', (['matrix[:-1, :-1]'], {}), '(matrix[:-1, :-1])\n', (4276, 4294), False, 'from airobot.utils import common\n'), ((6330, 6386), 'numpy.matmul', 'np.matmul', (['T_pose_transform_target2source', 'T_pose_source'], {}), '(T_pose_transform_target2source, T_pose_source)\n', (6339, 6386), True, 'import numpy as np\n'), ((6976, 7020), 'numpy.matmul', 'np.matmul', (['T_transform_source', 'T_pose_source'], {}), '(T_transform_source, T_pose_source)\n', (6985, 7020), True, 'import numpy as np\n'), ((9491, 9530), 'scipy.spatial.transform.Rotation.from_quat', 'R.from_quat', (['[quat_initial, quat_final]'], {}), '([quat_initial, quat_final])\n', (9502, 9530), True, 'from scipy.spatial.transform import Rotation as R\n'), ((5131, 5160), 'numpy.linalg.inv', 'np.linalg.inv', (['T_source_world'], {}), '(T_source_world)\n', (5144, 5160), True, 'import numpy as np\n'), ((9257, 9309), 'numpy.linspace', 'np.linspace', (['trans_initial[0]', 'trans_final[0]'], {'num': 'N'}), '(trans_initial[0], trans_final[0], num=N)\n', (9268, 9309), True, 'import numpy as np\n'), ((9337, 9389), 'numpy.linspace', 'np.linspace', (['trans_initial[1]', 'trans_final[1]'], {'num': 'N'}), '(trans_initial[1], trans_final[1], num=N)\n', (9348, 9389), True, 'import numpy as np\n'), ((9417, 9469), 'numpy.linspace', 'np.linspace', (['trans_initial[2]', 'trans_final[2]'], {'num': 'N'}), '(trans_initial[2], trans_final[2], num=N)\n', (9428, 9469), True, 'import numpy as np\n'), ((9549, 9561), 'numpy.arange', 'np.arange', (['(2)'], {}), '(2)\n', (9558, 9561), True, 'import numpy as np\n'), ((9597, 9617), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'N'], {}), '(0, 1, N)\n', (9608, 9617), True, 'import numpy as np\n')] |
import numpy as np
import os, datetime
import matplotlib
from scipy.misc import imsave
def makeFile(f):
if not os.path.exists(f):
os.makedirs(f)
def getDateTime(minutes=False):
t = datetime.datetime.now()
dt = ('%s_%s' % (t.month, t.day))
if minutes:
dt += '_%s-%s-%s' % (t.hour, t.minute, t.second)
return dt
def checkEmpty(a_list):
if len(a_list) == 0:
raise Exception('Empty list')
def readList(list_path,ignore_head=False):
lists = []
with open(list_path) as f:
lists = f.read().splitlines()
if ignore_head:
lists = lists[1:]
return lists
def readFloFile(filename, short=True):
with open(filename, 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
if magic != 202021.25:
raise Exception('Magic number incorrect: %s' % filename)
w = int(np.fromfile(f, np.int32, count=1))
h = int(np.fromfile(f, np.int32, count=1))
if short:
flow = np.fromfile(f, np.int16, count=h*w*2)
flow = flow.astype(np.float32)
else:
flow = np.fromfile(f, np.float32, count=h * w * 2)
flow = flow.reshape((h, w, 2))
return flow
def flowToMap(F_mag, F_dir):
sz = F_mag.shape
flow_color = np.zeros((sz[0], sz[1], 3), dtype=float)
flow_color[:,:,0] = (F_dir+np.pi) / (2 * np.pi)
f_dir =(F_dir+np.pi) / (2 * np.pi)
flow_color[:,:,1] = F_mag / 255 #F_mag.max()
flow_color[:,:,2] = 1
flow_color = matplotlib.colors.hsv_to_rgb(flow_color)*255
return flow_color
def flowToColor(flow):
F_dx = flow[:,:,1].copy().astype(float)
F_dy = flow[:,:,0].copy().astype(float)
F_mag = np.sqrt(np.power(F_dx, 2) + np.power(F_dy, 2))
F_dir = np.arctan2(F_dy, F_dx)
flow_color = flowToMap(F_mag, F_dir)
return flow_color.astype(np.uint8)
def saveResultsSeparate(prefix, results):
for key in results:
save_name = prefix + '_' + key
value = results[key]
if key == 'mask' or key == 'rho':
save_name += '.png'
else:
save_name += '.jpg'
imsave(save_name, value)
| [
"os.path.exists",
"numpy.fromfile",
"os.makedirs",
"numpy.power",
"scipy.misc.imsave",
"datetime.datetime.now",
"numpy.zeros",
"numpy.arctan2",
"matplotlib.colors.hsv_to_rgb"
] | [((199, 222), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (220, 222), False, 'import os, datetime\n'), ((1284, 1324), 'numpy.zeros', 'np.zeros', (['(sz[0], sz[1], 3)'], {'dtype': 'float'}), '((sz[0], sz[1], 3), dtype=float)\n', (1292, 1324), True, 'import numpy as np\n'), ((1758, 1780), 'numpy.arctan2', 'np.arctan2', (['F_dy', 'F_dx'], {}), '(F_dy, F_dx)\n', (1768, 1780), True, 'import numpy as np\n'), ((116, 133), 'os.path.exists', 'os.path.exists', (['f'], {}), '(f)\n', (130, 133), False, 'import os, datetime\n'), ((143, 157), 'os.makedirs', 'os.makedirs', (['f'], {}), '(f)\n', (154, 157), False, 'import os, datetime\n'), ((719, 754), 'numpy.fromfile', 'np.fromfile', (['f', 'np.float32'], {'count': '(1)'}), '(f, np.float32, count=1)\n', (730, 754), True, 'import numpy as np\n'), ((1508, 1548), 'matplotlib.colors.hsv_to_rgb', 'matplotlib.colors.hsv_to_rgb', (['flow_color'], {}), '(flow_color)\n', (1536, 1548), False, 'import matplotlib\n'), ((2124, 2148), 'scipy.misc.imsave', 'imsave', (['save_name', 'value'], {}), '(save_name, value)\n', (2130, 2148), False, 'from scipy.misc import imsave\n'), ((871, 904), 'numpy.fromfile', 'np.fromfile', (['f', 'np.int32'], {'count': '(1)'}), '(f, np.int32, count=1)\n', (882, 904), True, 'import numpy as np\n'), ((922, 955), 'numpy.fromfile', 'np.fromfile', (['f', 'np.int32'], {'count': '(1)'}), '(f, np.int32, count=1)\n', (933, 955), True, 'import numpy as np\n'), ((1003, 1044), 'numpy.fromfile', 'np.fromfile', (['f', 'np.int16'], {'count': '(h * w * 2)'}), '(f, np.int16, count=h * w * 2)\n', (1014, 1044), True, 'import numpy as np\n'), ((1117, 1160), 'numpy.fromfile', 'np.fromfile', (['f', 'np.float32'], {'count': '(h * w * 2)'}), '(f, np.float32, count=h * w * 2)\n', (1128, 1160), True, 'import numpy as np\n'), ((1707, 1724), 'numpy.power', 'np.power', (['F_dx', '(2)'], {}), '(F_dx, 2)\n', (1715, 1724), True, 'import numpy as np\n'), ((1727, 1744), 'numpy.power', 'np.power', (['F_dy', '(2)'], {}), '(F_dy, 2)\n', (1735, 1744), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import pytest
from pyleecan.Classes.MeshMat import MeshMat
from pyleecan.Classes.CellMat import CellMat
from pyleecan.Classes.MeshSolution import MeshSolution
from pyleecan.Classes.PointMat import PointMat
import numpy as np
DELTA = 1e-10
@pytest.mark.METHODS
@pytest.mark.MeshSol
# @pytest.mark.DEV
def test_MeshMat_1group():
"""unittest for 1 group"""
mesh = MeshMat()
mesh.cell["triangle"] = CellMat(nb_pt_per_cell=3)
mesh.point = PointMat()
mesh.point.add_point(np.array([0, 0]))
mesh.point.add_point(np.array([1, 0]))
mesh.point.add_point(np.array([1, 2]))
mesh.point.add_point(np.array([2, 3]))
mesh.point.add_point(np.array([3, 3]))
mesh.add_cell(np.array([0, 1, 2]), "triangle")
mesh.add_cell(np.array([1, 2, 3]), "triangle")
mesh.add_cell(np.array([4, 2, 3]), "triangle")
meshsol = MeshSolution()
meshsol.mesh = [mesh]
meshsol.group = dict()
meshsol.group["stator"] = np.array([0, 1])
meshsol.group["rotor"] = np.array([2])
MS_grp = meshsol.get_group("stator")
cells_grp, nb_cell, indices = MS_grp.get_mesh().get_cell()
solution = np.array([[0, 1, 2], [1, 2, 3]])
result_tgl = cells_grp["triangle"]
testA = np.sum(abs(solution - result_tgl))
msg = "Wrong output: returned " + str(result_tgl) + ", expected: " + str(solution)
assert testA == pytest.approx(0, rel=DELTA), msg
MS_grp = meshsol.get_group("rotor")
cells_grp, nb_cell, indices = MS_grp.get_mesh().get_cell()
solution = np.array([[3, 3], [1, 2], [2, 3]])
results = cells_grp["triangle"] # The point indices have changed !
points = MS_grp.get_mesh().get_point(results)
testA = np.sum(abs(solution - points))
msg = "Wrong output: returned " + str(results) + ", expected: " + str(solution)
assert testA == pytest.approx(0, rel=DELTA), msg
if __name__ == "__main__":
Xout = test_MeshMat_1group()
| [
"pytest.approx",
"pyleecan.Classes.MeshSolution.MeshSolution",
"numpy.array",
"pyleecan.Classes.PointMat.PointMat",
"pyleecan.Classes.MeshMat.MeshMat",
"pyleecan.Classes.CellMat.CellMat"
] | [((399, 408), 'pyleecan.Classes.MeshMat.MeshMat', 'MeshMat', ([], {}), '()\n', (406, 408), False, 'from pyleecan.Classes.MeshMat import MeshMat\n'), ((437, 462), 'pyleecan.Classes.CellMat.CellMat', 'CellMat', ([], {'nb_pt_per_cell': '(3)'}), '(nb_pt_per_cell=3)\n', (444, 462), False, 'from pyleecan.Classes.CellMat import CellMat\n'), ((480, 490), 'pyleecan.Classes.PointMat.PointMat', 'PointMat', ([], {}), '()\n', (488, 490), False, 'from pyleecan.Classes.PointMat import PointMat\n'), ((875, 889), 'pyleecan.Classes.MeshSolution.MeshSolution', 'MeshSolution', ([], {}), '()\n', (887, 889), False, 'from pyleecan.Classes.MeshSolution import MeshSolution\n'), ((973, 989), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (981, 989), True, 'import numpy as np\n'), ((1019, 1032), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (1027, 1032), True, 'import numpy as np\n'), ((1153, 1185), 'numpy.array', 'np.array', (['[[0, 1, 2], [1, 2, 3]]'], {}), '([[0, 1, 2], [1, 2, 3]])\n', (1161, 1185), True, 'import numpy as np\n'), ((1531, 1565), 'numpy.array', 'np.array', (['[[3, 3], [1, 2], [2, 3]]'], {}), '([[3, 3], [1, 2], [2, 3]])\n', (1539, 1565), True, 'import numpy as np\n'), ((516, 532), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (524, 532), True, 'import numpy as np\n'), ((559, 575), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (567, 575), True, 'import numpy as np\n'), ((602, 618), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (610, 618), True, 'import numpy as np\n'), ((645, 661), 'numpy.array', 'np.array', (['[2, 3]'], {}), '([2, 3])\n', (653, 661), True, 'import numpy as np\n'), ((688, 704), 'numpy.array', 'np.array', (['[3, 3]'], {}), '([3, 3])\n', (696, 704), True, 'import numpy as np\n'), ((725, 744), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (733, 744), True, 'import numpy as np\n'), ((776, 795), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (784, 795), True, 'import numpy as np\n'), ((827, 846), 'numpy.array', 'np.array', (['[4, 2, 3]'], {}), '([4, 2, 3])\n', (835, 846), True, 'import numpy as np\n'), ((1379, 1406), 'pytest.approx', 'pytest.approx', (['(0)'], {'rel': 'DELTA'}), '(0, rel=DELTA)\n', (1392, 1406), False, 'import pytest\n'), ((1835, 1862), 'pytest.approx', 'pytest.approx', (['(0)'], {'rel': 'DELTA'}), '(0, rel=DELTA)\n', (1848, 1862), False, 'import pytest\n')] |
"""
Class for reading data from a 3-brain Biocam system.
See:
https://www.3brain.com/products/single-well/biocam-x
Author : <NAME>
"""
from .baserawio import (BaseRawIO, _signal_channel_dtype, _signal_stream_dtype,
_spike_channel_dtype, _event_channel_dtype)
import numpy as np
try:
import h5py
HAVE_H5PY = True
except ImportError:
HAVE_H5PY = False
class BiocamRawIO(BaseRawIO):
"""
Class for reading data from a Biocam h5 file.
Usage:
>>> import neo.rawio
>>> r = neo.rawio.BiocamRawIO(filename='biocam.h5')
>>> r.parse_header()
>>> print(r)
>>> raw_chunk = r.get_analogsignal_chunk(block_index=0, seg_index=0,
i_start=0, i_stop=1024,
channel_names=channel_names)
>>> float_chunk = r.rescale_signal_raw_to_float(raw_chunk, dtype='float64',
channel_indexes=[0, 3, 6])
"""
extensions = ['h5']
rawmode = 'one-file'
def __init__(self, filename=''):
BaseRawIO.__init__(self)
self.filename = filename
def _source_name(self):
return self.filename
def _parse_header(self):
assert HAVE_H5PY, 'h5py is not installed'
self._header_dict = open_biocam_file_header(self.filename)
self._num_channels = self._header_dict["num_channels"]
self._num_frames = self._header_dict["num_frames"]
self._sampling_rate = self._header_dict["sampling_rate"]
self._filehandle = self._header_dict["file_handle"]
self._read_function = self._header_dict["read_function"]
self._channels = self._header_dict["channels"]
gain = self._header_dict["gain"]
offset = self._header_dict["offset"]
signal_streams = np.array([('Signals', '0')], dtype=_signal_stream_dtype)
sig_channels = []
for c, chan in enumerate(self._channels):
ch_name = f'ch{chan[0]}-{chan[1]}'
chan_id = str(c + 1)
sr = self._sampling_rate # Hz
dtype = "uint16"
units = 'uV'
gain = gain
offset = offset
stream_id = '0'
sig_channels.append((ch_name, chan_id, sr, dtype, units, gain, offset, stream_id))
sig_channels = np.array(sig_channels, dtype=_signal_channel_dtype)
# No events
event_channels = []
event_channels = np.array(event_channels, dtype=_event_channel_dtype)
# No spikes
spike_channels = []
spike_channels = np.array(spike_channels, dtype=_spike_channel_dtype)
self.header = {}
self.header['nb_block'] = 1
self.header['nb_segment'] = [1]
self.header['signal_streams'] = signal_streams
self.header['signal_channels'] = sig_channels
self.header['spike_channels'] = spike_channels
self.header['event_channels'] = event_channels
self._generate_minimal_annotations()
def _segment_t_start(self, block_index, seg_index):
all_starts = [[0.]]
return all_starts[block_index][seg_index]
def _segment_t_stop(self, block_index, seg_index):
t_stop = self._num_frames / self._sampling_rate
all_stops = [[t_stop]]
return all_stops[block_index][seg_index]
def _get_signal_size(self, block_index, seg_index, stream_index):
assert stream_index == 0
return self._num_frames
def _get_signal_t_start(self, block_index, seg_index, stream_index):
assert stream_index == 0
return self._segment_t_start(block_index, seg_index)
def _get_analogsignal_chunk(self, block_index, seg_index, i_start, i_stop,
stream_index, channel_indexes):
if i_start is None:
i_start = 0
if i_stop is None:
i_stop = self._num_frames
data = self._read_function(self._filehandle, i_start, i_stop, self._num_channels)
return np.squeeze(data[:, channel_indexes])
def open_biocam_file_header(filename):
"""Open a Biocam hdf5 file, read and return the recording info, pick te correct method to access raw data,
and return this to the caller."""
assert HAVE_H5PY, 'h5py is not installed'
rf = h5py.File(filename, 'r')
# Read recording variables
rec_vars = rf.require_group('3BRecInfo/3BRecVars/')
bit_depth = rec_vars['BitDepth'][0]
max_uv = rec_vars['MaxVolt'][0]
min_uv = rec_vars['MinVolt'][0]
n_frames = rec_vars['NRecFrames'][0]
sampling_rate = rec_vars['SamplingRate'][0]
signal_inv = rec_vars['SignalInversion'][0]
# Get the actual number of channels used in the recording
file_format = rf['3BData'].attrs.get('Version', None)
format_100 = False
if file_format == 100:
n_channels = len(rf['3BData/Raw'][0])
format_100 = True
elif file_format in (101, 102) or file_format is None:
n_channels = int(rf['3BData/Raw'].shape[0] / n_frames)
else:
raise Exception('Unknown data file format.')
# # get channels
channels = rf['3BRecInfo/3BMeaStreams/Raw/Chs'][:]
# determine correct function to read data
if format_100:
if signal_inv == 1:
read_function = readHDF5t_100
elif signal_inv == 1:
read_function = readHDF5t_100_i
else:
raise Exception("Unknown signal inversion")
else:
if signal_inv == 1:
read_function = readHDF5t_101
elif signal_inv == 1:
read_function = readHDF5t_101_i
else:
raise Exception("Unknown signal inversion")
gain = (max_uv - min_uv) / (2 ** bit_depth)
offset = min_uv
return dict(file_handle=rf, num_frames=n_frames, sampling_rate=sampling_rate, num_channels=n_channels,
channels=channels, file_format=file_format, signal_inv=signal_inv,
read_function=read_function, gain=gain, offset=offset)
def readHDF5t_100(rf, t0, t1, nch):
return rf['3BData/Raw'][t0:t1]
def readHDF5t_100_i(rf, t0, t1, nch):
return 4096 - rf['3BData/Raw'][t0:t1]
def readHDF5t_101(rf, t0, t1, nch):
return rf['3BData/Raw'][nch * t0:nch * t1].reshape((t1 - t0, nch), order='C')
def readHDF5t_101_i(rf, t0, t1, nch):
return 4096 - rf['3BData/Raw'][nch * t0:nch * t1].reshape((t1 - t0, nch), order='C')
| [
"numpy.array",
"numpy.squeeze",
"h5py.File"
] | [((4337, 4361), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (4346, 4361), False, 'import h5py\n'), ((1874, 1930), 'numpy.array', 'np.array', (["[('Signals', '0')]"], {'dtype': '_signal_stream_dtype'}), "([('Signals', '0')], dtype=_signal_stream_dtype)\n", (1882, 1930), True, 'import numpy as np\n'), ((2383, 2434), 'numpy.array', 'np.array', (['sig_channels'], {'dtype': '_signal_channel_dtype'}), '(sig_channels, dtype=_signal_channel_dtype)\n', (2391, 2434), True, 'import numpy as np\n'), ((2509, 2561), 'numpy.array', 'np.array', (['event_channels'], {'dtype': '_event_channel_dtype'}), '(event_channels, dtype=_event_channel_dtype)\n', (2517, 2561), True, 'import numpy as np\n'), ((2636, 2688), 'numpy.array', 'np.array', (['spike_channels'], {'dtype': '_spike_channel_dtype'}), '(spike_channels, dtype=_spike_channel_dtype)\n', (2644, 2688), True, 'import numpy as np\n'), ((4054, 4090), 'numpy.squeeze', 'np.squeeze', (['data[:, channel_indexes]'], {}), '(data[:, channel_indexes])\n', (4064, 4090), True, 'import numpy as np\n')] |
import cv2
import numpy as np
from aip import AipOcr
from PIL import Image, ImageDraw, ImageFont
import os, math
def crop_image(src_img, x_start, x_end, y_start, y_end):
"""
图片裁剪
:param src_img: 原始图片
:param x_start: x 起始坐标
:param x_end: x 结束坐标
:param y_start: y 开始坐标
:param y_end: y 结束坐标
:return:
"""
tmp_img = cv2.cvtColor(src_img, cv2.COLOR_BGR2RGB)
tmp_img = tmp_img[y_start:y_end, x_start:x_end] # 长,宽
return cv2.cvtColor(tmp_img, cv2.COLOR_RGB2BGR)
def adjust_lightness(src_img, lightness_value):
"""
:param src_img: 待调整亮度的图片
:param lightness_value: 亮度值
:return:
"""
height, width, channel = src_img.shape # 获取shape的数值,height和width、通道
# 新建全零图片数组src2,将height和width,类型设置为原图片的通道类型(色素全为零,输出为全黑图片)
src2 = np.zeros([height, width, channel], src_img.dtype)
# new_img = cv2.addWeighted(src_img, a, src2, 1 - a, lightnessValue) # 处理后的图片
new_img = cv2.addWeighted(src_img, 1, src2, 1, lightness_value) # 处理后的图片
return new_img
def add_watermark(src_img, water_text, position, color):
"""
添加水印
:param src_img: 原始图片
:param water_text: 水印文字
:param position: 水印位置
:param color: 水印文字颜色
:return:
"""
# 根据选择的位置,确定水印的起始位置
height, width, channel = src_img.shape
x_padding, y_padding = width * 0.05, height * 0.05 # 与边缘的间距
scale = min((width / 1000), (height / 1000)) # 按照图片的长宽大小对字体进行一个放大,scale 即为放大倍数
font_size = 20 + int(scale) * 5 # 根据 scale 增加字体的大小,从而使得字体大小适应图片的大小
font_path = "{0}/ui/font.ttf".format(os.getcwd())
font = ImageFont.truetype(font_path, font_size, encoding="utf-8") # 获取自定义的字体
(text_width, text_height) = font.getsize(water_text)
x_start, y_start = 0, 0 # 水印文字的左下角坐标
if position == "左上角":
x_start = x_padding
y_start = y_padding
elif position == "右上角":
x_start = width - text_width - x_padding
y_start = y_padding
elif position == "中间":
x_start = (width - text_width) / 2
y_start = (height - text_height) / 2
elif position == "左下角":
x_start = x_padding
y_start = height - y_padding - text_height
elif position == "右下角":
x_start = width - text_width - x_padding
y_start = height - y_padding - text_height
img_pil = Image.fromarray(cv2.cvtColor(src_img, cv2.COLOR_BGR2RGB)) # 将 OpenCV 的 BGR 色彩转换成 PIL 需要的 RGB 色彩
draw = ImageDraw.Draw(img_pil)
draw.text((x_start, y_start), water_text, color, font=font)
return cv2.cvtColor(np.asarray(img_pil), cv2.COLOR_RGB2BGR) # 将 PIL 的 RGB 色彩转换成 OpenCV 的 BGR 色彩
def gaussian_blur(src_img, x_start, x_end, y_start, y_end, ksize, sigmaX):
"""
高斯模糊
"""
blur = src_img[y_start:y_end, x_start:x_end]
blur = cv2.GaussianBlur(blur, ksize, sigmaX)
src_img[y_start:y_end, x_start:x_end] = blur
return src_img
def compress_img(src_img, size):
"""
调整图片到指定大小
"""
return cv2.resize(src_img, size, interpolation=cv2.INTER_AREA)
def img_stitching(images):
"""
图片拼接
"""
stitcher = cv2.Stitcher_create()
status, stitch_img = stitcher.stitch(images)
if status != cv2.Stitcher_OK:
print(f"合拼图片失败,status = {status}")
return stitch_img
def img_encoding(image, dir_path):
"""
图片加密
:return:
"""
height, width, channel = image.shape
# 随机创建密钥文件
img_key = np.random.randint(0, 256, size=[height, width, channel], dtype=np.uint8)
# 保存密钥
np.save(dir_path + "/" + "img_key2", img_key)
# 返回加密后的图片
return cv2.bitwise_xor(image, img_key)
def img_decoding(image, key_file_path):
"""
图片解密
"""
img_key = np.load(key_file_path)
return cv2.bitwise_xor(image, img_key)
def img_ocr(image):
"""
OCR 文字识别
"""
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
text = client.basicGeneral(image)
words_result = text["words_result"]
result_str = "" # 存储最终的结果
for w in words_result:
result_str = result_str + w["words"] + "\n"
return result_str
# 滤镜效果
def black_white_filter(src_img):
"""
黑白滤镜
"""
return cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY) # 直接将图片转换为灰度图片即可
def sketch_filter(src_img):
"""
素描滤镜
"""
# 图像灰度处理
gray_img = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)
# 高斯滤波降噪
gaussian = cv2.GaussianBlur(gray_img, (5, 5), 0)
# Canny算子
canny = cv2.Canny(gaussian, 50, 150)
# 阈值化处理
ret, result = cv2.threshold(canny, 100, 255, cv2.THRESH_BINARY_INV)
return result
def embossment_filter(src_img):
"""
浮雕滤镜
"""
# 获取图像行和列
height, width = src_img.shape[:2]
# 图像灰度处理
gray_img = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)
result = np.zeros(gray_img.shape, np.uint8)
for w in range(0, width - 1):
new_value = np.int32(gray_img[:, w]) - np.int32(gray_img[:, w + 1]) + 120
new_value[new_value > 255] = 255
new_value[new_value < 0] = 0
result[:, w] = new_value
return result
def reminiscence_filter(src_img):
"""
怀旧滤镜
"""
# 图像怀旧特效
B = 0.272 * src_img[:, :, 2] + 0.534 * src_img[:, :, 1] + 0.131 * src_img[:, :, 0]
G = 0.349 * src_img[:, :, 2] + 0.686 * src_img[:, :, 1] + 0.168 * src_img[:, :, 0]
R = 0.393 * src_img[:, :, 2] + 0.769 * src_img[:, :, 1] + 0.189 * src_img[:, :, 0]
# 像素值大于 255 的,则直接赋值为 255
B[B > 255] = 255
G[G > 255] = 255
R[R > 255] = 255
filter_result = np.dstack((B, G, R)) # 加了滤镜效果后的图片
return np.uint8(filter_result) # 将像素值从 numpy.float64 类型转换成 np.uint8 类型,从而可以正常显示
# for i in range(rows):
# for j in range(cols):
# B = 0.272 * src_img[i, j][2] + 0.534 * src_img[i, j][1] + 0.131 * src_img[i, j][0]
# G = 0.349 * src_img[i, j][2] + 0.686 * src_img[i, j][1] + 0.168 * src_img[i, j][0]
# R = 0.393 * src_img[i, j][2] + 0.769 * src_img[i, j][1] + 0.189 * src_img[i, j][0]
# if B > 255:
# B = 255
# if G > 255:
# G = 255
# if R > 255:
# R = 255
# dst[i, j] = np.uint8((B, G, R))
# return dst
def add_filter(src_img, filter_type):
"""
为图片添加滤镜效果
:param src_img: 原始图片
:param filter_type: 滤镜类型
"""
if filter_type == "黑白":
return black_white_filter(src_img)
elif filter_type == "素描":
return sketch_filter(src_img)
elif filter_type == "浮雕":
return embossment_filter(src_img)
elif filter_type == "怀旧":
return reminiscence_filter(src_img)
| [
"numpy.uint8",
"numpy.int32",
"PIL.ImageDraw.Draw",
"cv2.Stitcher_create",
"numpy.save",
"cv2.threshold",
"numpy.asarray",
"PIL.ImageFont.truetype",
"cv2.addWeighted",
"aip.AipOcr",
"cv2.cvtColor",
"cv2.resize",
"cv2.Canny",
"cv2.GaussianBlur",
"cv2.bitwise_xor",
"numpy.dstack",
"os.... | [((355, 395), 'cv2.cvtColor', 'cv2.cvtColor', (['src_img', 'cv2.COLOR_BGR2RGB'], {}), '(src_img, cv2.COLOR_BGR2RGB)\n', (367, 395), False, 'import cv2\n'), ((466, 506), 'cv2.cvtColor', 'cv2.cvtColor', (['tmp_img', 'cv2.COLOR_RGB2BGR'], {}), '(tmp_img, cv2.COLOR_RGB2BGR)\n', (478, 506), False, 'import cv2\n'), ((794, 843), 'numpy.zeros', 'np.zeros', (['[height, width, channel]', 'src_img.dtype'], {}), '([height, width, channel], src_img.dtype)\n', (802, 843), True, 'import numpy as np\n'), ((941, 994), 'cv2.addWeighted', 'cv2.addWeighted', (['src_img', '(1)', 'src2', '(1)', 'lightness_value'], {}), '(src_img, 1, src2, 1, lightness_value)\n', (956, 994), False, 'import cv2\n'), ((1580, 1638), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_path', 'font_size'], {'encoding': '"""utf-8"""'}), "(font_path, font_size, encoding='utf-8')\n", (1598, 1638), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2411, 2434), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img_pil'], {}), '(img_pil)\n', (2425, 2434), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2762, 2799), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['blur', 'ksize', 'sigmaX'], {}), '(blur, ksize, sigmaX)\n', (2778, 2799), False, 'import cv2\n'), ((2944, 2999), 'cv2.resize', 'cv2.resize', (['src_img', 'size'], {'interpolation': 'cv2.INTER_AREA'}), '(src_img, size, interpolation=cv2.INTER_AREA)\n', (2954, 2999), False, 'import cv2\n'), ((3069, 3090), 'cv2.Stitcher_create', 'cv2.Stitcher_create', ([], {}), '()\n', (3088, 3090), False, 'import cv2\n'), ((3385, 3457), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '[height, width, channel]', 'dtype': 'np.uint8'}), '(0, 256, size=[height, width, channel], dtype=np.uint8)\n', (3402, 3457), True, 'import numpy as np\n'), ((3473, 3518), 'numpy.save', 'np.save', (["(dir_path + '/' + 'img_key2')", 'img_key'], {}), "(dir_path + '/' + 'img_key2', img_key)\n", (3480, 3518), True, 'import numpy as np\n'), ((3547, 3578), 'cv2.bitwise_xor', 'cv2.bitwise_xor', (['image', 'img_key'], {}), '(image, img_key)\n', (3562, 3578), False, 'import cv2\n'), ((3660, 3682), 'numpy.load', 'np.load', (['key_file_path'], {}), '(key_file_path)\n', (3667, 3682), True, 'import numpy as np\n'), ((3694, 3725), 'cv2.bitwise_xor', 'cv2.bitwise_xor', (['image', 'img_key'], {}), '(image, img_key)\n', (3709, 3725), False, 'import cv2\n'), ((3876, 3911), 'aip.AipOcr', 'AipOcr', (['APP_ID', 'API_KEY', 'SECRET_KEY'], {}), '(APP_ID, API_KEY, SECRET_KEY)\n', (3882, 3911), False, 'from aip import AipOcr\n'), ((4201, 4242), 'cv2.cvtColor', 'cv2.cvtColor', (['src_img', 'cv2.COLOR_BGR2GRAY'], {}), '(src_img, cv2.COLOR_BGR2GRAY)\n', (4213, 4242), False, 'import cv2\n'), ((4344, 4385), 'cv2.cvtColor', 'cv2.cvtColor', (['src_img', 'cv2.COLOR_BGR2GRAY'], {}), '(src_img, cv2.COLOR_BGR2GRAY)\n', (4356, 4385), False, 'import cv2\n'), ((4415, 4452), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['gray_img', '(5, 5)', '(0)'], {}), '(gray_img, (5, 5), 0)\n', (4431, 4452), False, 'import cv2\n'), ((4480, 4508), 'cv2.Canny', 'cv2.Canny', (['gaussian', '(50)', '(150)'], {}), '(gaussian, 50, 150)\n', (4489, 4508), False, 'import cv2\n'), ((4540, 4593), 'cv2.threshold', 'cv2.threshold', (['canny', '(100)', '(255)', 'cv2.THRESH_BINARY_INV'], {}), '(canny, 100, 255, cv2.THRESH_BINARY_INV)\n', (4553, 4593), False, 'import cv2\n'), ((4751, 4792), 'cv2.cvtColor', 'cv2.cvtColor', (['src_img', 'cv2.COLOR_BGR2GRAY'], {}), '(src_img, cv2.COLOR_BGR2GRAY)\n', (4763, 4792), False, 'import cv2\n'), ((4807, 4841), 'numpy.zeros', 'np.zeros', (['gray_img.shape', 'np.uint8'], {}), '(gray_img.shape, np.uint8)\n', (4815, 4841), True, 'import numpy as np\n'), ((5538, 5558), 'numpy.dstack', 'np.dstack', (['(B, G, R)'], {}), '((B, G, R))\n', (5547, 5558), True, 'import numpy as np\n'), ((5584, 5607), 'numpy.uint8', 'np.uint8', (['filter_result'], {}), '(filter_result)\n', (5592, 5607), True, 'import numpy as np\n'), ((1556, 1567), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1565, 1567), False, 'import os, math\n'), ((2319, 2359), 'cv2.cvtColor', 'cv2.cvtColor', (['src_img', 'cv2.COLOR_BGR2RGB'], {}), '(src_img, cv2.COLOR_BGR2RGB)\n', (2331, 2359), False, 'import cv2\n'), ((2523, 2542), 'numpy.asarray', 'np.asarray', (['img_pil'], {}), '(img_pil)\n', (2533, 2542), True, 'import numpy as np\n'), ((4897, 4921), 'numpy.int32', 'np.int32', (['gray_img[:, w]'], {}), '(gray_img[:, w])\n', (4905, 4921), True, 'import numpy as np\n'), ((4924, 4952), 'numpy.int32', 'np.int32', (['gray_img[:, w + 1]'], {}), '(gray_img[:, w + 1])\n', (4932, 4952), True, 'import numpy as np\n')] |
# Adapted from https://github.com/biubug6/Pytorch_Retinaface
# Original license: MIT
import torch
import cv2
import numpy as np
from .. import torch_utils
from .models.retinaface import RetinaFace
from ..box_utils import batched_decode
from .utils import decode_landm
from .config import cfg_re50
from .prior_box import PriorBox
from torch.hub import load_state_dict_from_url
class RetinaNetDetectorONNX(torch.nn.Module):
def __init__(self, input_imshape, inference_imshape):
super().__init__()
self.device = torch.device("cpu")
cfg = cfg_re50
state_dict = load_state_dict_from_url(
"https://folk.ntnu.no/haakohu/RetinaFace_ResNet50.pth",
map_location=torch_utils.get_device()
)
state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
net = RetinaFace(cfg=cfg)
net.eval()
net.load_state_dict(state_dict)
self.net = net.to(self.device)
self.input_imshape = input_imshape
self.inference_imshape = inference_imshape # (height, width)
self.mean = np.array([104, 117, 123], dtype=np.float32)
self.mean = torch.from_numpy(self.mean).reshape((1, 3, 1, 1))
self.mean = torch.nn.Parameter(self.mean).float().to(self.device)
prior_box = PriorBox(cfg, image_size=self.inference_imshape)
self.priors = prior_box.forward().to(self.device).data
self.priors = torch.nn.Parameter(self.priors).float()
self.variance = torch.nn.Parameter(torch.tensor([0.1, 0.2])).float()
def export_onnx(self, onnx_filepath):
try:
image = cv2.imread("images/1.hd.jpeg")
except:
raise FileNotFoundError()
height, width = self.input_imshape
image = cv2.resize(image, (width, height))
example_inputs = np.moveaxis(image, -1, 0)
example_inputs = example_inputs[None]
np.save("inputs.npy", example_inputs.astype(np.float32))
example_inputs = torch.from_numpy(example_inputs).float()
actual_outputs = self.forward(example_inputs).cpu().numpy()
output_names = ["loc"]
torch.onnx.export(
self, example_inputs,
onnx_filepath,
verbose=True,
input_names=["image"],
output_names=output_names,
export_params=True,
opset_version=10 # functional interpolate does not support opset 11+
)
np.save(f"outputs.npy", actual_outputs)
@torch.no_grad()
def forward(self, image):
"""
image: shape [1, 3, H, W]
Exports model where outputs are NOT thresholded or performed NMS on.
"""
image = torch.nn.functional.interpolate(image, self.inference_imshape, mode="nearest")
# Expects BGR
image = image - self.mean
assert image.shape[2] == self.inference_imshape[0]
assert image.shape[3] == self.inference_imshape[1]
assert image.shape[0] == 1,\
"The ONNX export only supports one image at a time tensors currently"
loc, conf, landms = self.net(image) # forward pass
assert conf.shape[2] == 2
scores = conf[:, :, 1:]
boxes = batched_decode(loc, self.priors.data, self.variance, to_XYXY=False)
landms = decode_landm(landms, self.priors.data, self.variance)
boxes, landms, scores = [_[0] for _ in [boxes, landms, scores]]
x0, y0, W, H = [boxes[:, i] for i in range(4)]
assert boxes.shape[1] == 4
height, width = image.shape[2:]
x0 = x0 - W / 2
y0 = y0 - H / 2
x1 = x0 + W
y1 = y0 + H
boxes = torch.stack((x0, y0, x1, y1), dim=-1)
return torch.cat((boxes, landms, scores), dim=-1)
| [
"torch.onnx.export",
"torch.stack",
"torch.from_numpy",
"numpy.array",
"torch.cat",
"torch.nn.Parameter",
"torch.tensor",
"torch.nn.functional.interpolate",
"numpy.moveaxis",
"torch.no_grad",
"cv2.resize",
"cv2.imread",
"numpy.save",
"torch.device"
] | [((2521, 2536), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2534, 2536), False, 'import torch\n'), ((532, 551), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (544, 551), False, 'import torch\n'), ((1096, 1139), 'numpy.array', 'np.array', (['[104, 117, 123]'], {'dtype': 'np.float32'}), '([104, 117, 123], dtype=np.float32)\n', (1104, 1139), True, 'import numpy as np\n'), ((1788, 1822), 'cv2.resize', 'cv2.resize', (['image', '(width, height)'], {}), '(image, (width, height))\n', (1798, 1822), False, 'import cv2\n'), ((1849, 1874), 'numpy.moveaxis', 'np.moveaxis', (['image', '(-1)', '(0)'], {}), '(image, -1, 0)\n', (1860, 1874), True, 'import numpy as np\n'), ((2160, 2324), 'torch.onnx.export', 'torch.onnx.export', (['self', 'example_inputs', 'onnx_filepath'], {'verbose': '(True)', 'input_names': "['image']", 'output_names': 'output_names', 'export_params': '(True)', 'opset_version': '(10)'}), "(self, example_inputs, onnx_filepath, verbose=True,\n input_names=['image'], output_names=output_names, export_params=True,\n opset_version=10)\n", (2177, 2324), False, 'import torch\n'), ((2475, 2514), 'numpy.save', 'np.save', (['f"""outputs.npy"""', 'actual_outputs'], {}), "(f'outputs.npy', actual_outputs)\n", (2482, 2514), True, 'import numpy as np\n'), ((2726, 2804), 'torch.nn.functional.interpolate', 'torch.nn.functional.interpolate', (['image', 'self.inference_imshape'], {'mode': '"""nearest"""'}), "(image, self.inference_imshape, mode='nearest')\n", (2757, 2804), False, 'import torch\n'), ((3688, 3725), 'torch.stack', 'torch.stack', (['(x0, y0, x1, y1)'], {'dim': '(-1)'}), '((x0, y0, x1, y1), dim=-1)\n', (3699, 3725), False, 'import torch\n'), ((3741, 3783), 'torch.cat', 'torch.cat', (['(boxes, landms, scores)'], {'dim': '(-1)'}), '((boxes, landms, scores), dim=-1)\n', (3750, 3783), False, 'import torch\n'), ((1631, 1661), 'cv2.imread', 'cv2.imread', (['"""images/1.hd.jpeg"""'], {}), "('images/1.hd.jpeg')\n", (1641, 1661), False, 'import cv2\n'), ((1160, 1187), 'torch.from_numpy', 'torch.from_numpy', (['self.mean'], {}), '(self.mean)\n', (1176, 1187), False, 'import torch\n'), ((1438, 1469), 'torch.nn.Parameter', 'torch.nn.Parameter', (['self.priors'], {}), '(self.priors)\n', (1456, 1469), False, 'import torch\n'), ((2011, 2043), 'torch.from_numpy', 'torch.from_numpy', (['example_inputs'], {}), '(example_inputs)\n', (2027, 2043), False, 'import torch\n'), ((1521, 1545), 'torch.tensor', 'torch.tensor', (['[0.1, 0.2]'], {}), '([0.1, 0.2])\n', (1533, 1545), False, 'import torch\n'), ((1230, 1259), 'torch.nn.Parameter', 'torch.nn.Parameter', (['self.mean'], {}), '(self.mean)\n', (1248, 1259), False, 'import torch\n')] |
from __future__ import print_function, division
import numpy as np
from tensorflow import keras
class MDStackGenerator(keras.utils.Sequence):
"""
The `MDDataGenerator` load data from a `NpzFile` generated by the
preprocess function with `kdtree` mode. The file contain
the following keyword variables.
traj_coords: np.float32 arrays with shape (F, N, 3), stores the coordinates
of each atom in each frame.
lattices: np.float32 arrays with shape (F, 3, 3), stores the lattice
matrix of the simulation box in each frame. In the lattice matrix,
each row represents a lattice vector.
atom_types: np.int32 arrays with shape (N,), stores the atomic number of
each atom in the MD simulation.
target_index: np.int32 arrays with shape (n,), stores the indexes of
the target atoms. (`n <= N`)
nbr_lists: np.int32 arrays with shape (F, N, n_nbrs), stores the indices
of the neighboring atoms in the constructed graphs
"""
def __init__(self, fnames, tau=1, n_classes=2,
batch_size=1024, random_seed=123, shuffle=True):
self.fnames = fnames
self.tau = tau
self.n_classes = n_classes
self.batch_size = batch_size
self.random_seed = random_seed
self.shuffle = shuffle
try:
self.load_data()
except KeyError:
raise KeyError('Data loader failed: choose `--mode direct` to load'
' data preprocessed using `direct` backend.')
self.indices = np.arange(self.n_traj * (self.n_frames - self.tau))
self.random_seed = random_seed
if self.shuffle:
np.random.shuffle(self.indices)
def load_data(self):
traj_coords, atom_types, lattices, nbr_lists, target_index =\
[], [], [], [], []
for fname in self.fnames:
with np.load(fname) as data:
traj_coords.append(data['traj_coords'])
atom_types.append(data['atom_types'])
lattices.append(data['lattices'])
nbr_lists.append(data['nbr_lists'])
target_index.append(data['target_index'])
all_types = np.stack(atom_types)
all_target_index = np.stack(target_index)
assert np.all(all_types == all_types[0]), 'Atoms should be the '\
'same for each trajectory'
assert np.all(all_target_index == all_target_index[0])
self.atom_types = atom_types[0]
self.target_index = all_target_index[0]
self.traj_coords = np.stack(traj_coords, axis=0)
self.nbr_lists = np.stack(nbr_lists, axis=0)
self.lattices = np.stack(lattices, axis=0)
self.n_traj, self.n_frames = self.traj_coords.shape[:2]
def on_epoch_end(self):
if self.shuffle:
np.random.shuffle(self.indices)
def __len__(self):
return int(np.ceil(len(self.indices) / self.batch_size))
def __getitem__(self, index):
cur_indices = self.indices[index * self.batch_size:
(index + 1) * self.batch_size]
b_size = len(cur_indices)
traj_indices, frame_indices = np.unravel_index(
cur_indices, (self.n_traj, self.n_frames - self.tau))
stacked_coords = np.stack(
[self.traj_coords[traj_indices, frame_indices],
self.traj_coords[traj_indices, frame_indices + self.tau]],
axis=-1)
stacked_lattices = np.stack(
[self.lattices[traj_indices, frame_indices],
self.lattices[traj_indices, frame_indices + self.tau]],
axis=-1)
stacked_nbr_lists = np.stack(
[self.nbr_lists[traj_indices, frame_indices],
self.nbr_lists[traj_indices, frame_indices + self.tau]],
axis=-1)
atom_types = np.tile(self.atom_types, (b_size, 1))
target_index = np.tile(self.target_index, (b_size, 1))
batch_Y = np.zeros([b_size, self.n_classes * 2], dtype='float32')
return ([stacked_coords, stacked_lattices, stacked_nbr_lists,
atom_types, target_index], batch_Y)
class MDStackGenerator_direct(keras.utils.Sequence):
"""
The `MDStackGenerator_direct` load data from a `NpzFile` generated by the
preprocess function with `direct` mode. The file contain
the following keyword variables.
traj_coords: np.float32 arrays with shape (F, N, 3), stores the coordinates
of each atom in each frame.
atom_types: np.int32 arrays with shape (N,), stores the atomic number of
each atom in the MD simulation.
target_index: np.int32 arrays with shape (n,), stores the indexes of
the target atoms. (`n <= N`)
nbr_lists: np.int32 arrays with shape (F, N, n_nbrs), stores the indices
of the neighboring atoms in the constructed graphs
nbr_dists: np.float32 arrays with shape (F, N, n_nbrs), stores the
distances between the center atom and the neighboring atoms in the
constructed graphs
"""
def __init__(self, fnames, tau=1, n_classes=2,
batch_size=1024, random_seed=123, shuffle=True):
self.fnames = fnames
self.tau = tau
self.n_classes = n_classes
self.batch_size = batch_size
self.random_seed = random_seed
self.shuffle = shuffle
try:
self.load_data()
except KeyError:
raise KeyError('Data loader failed: choose `--mode kdtree` to load'
' data preprocessed using `kdtree` backend.')
self.indices = np.arange(self.n_traj * (self.n_frames - self.tau))
self.random_seed = random_seed
if self.shuffle:
np.random.shuffle(self.indices)
def load_data(self):
traj_coords, atom_types, nbr_lists, nbr_dists, target_index =\
[], [], [], [], []
for fname in self.fnames:
with np.load(fname) as data:
traj_coords.append(data['traj_coords'])
atom_types.append(data['atom_types'])
nbr_lists.append(data['nbr_lists'])
nbr_dists.append(data['nbr_dists'])
target_index.append(data['target_index'])
all_types = np.stack(atom_types)
all_target_index = np.stack(target_index)
assert np.all(all_types == all_types[0]), 'Atoms should be the '\
'same for each trajectory'
assert np.all(all_target_index == all_target_index[0])
self.atom_types = all_types[0]
self.target_index = all_target_index[0]
self.traj_coords = np.stack(traj_coords, axis=0)
self.nbr_lists = np.stack(nbr_lists, axis=0)
self.nbr_dists = np.stack(nbr_dists, axis=0)
self.n_traj, self.n_frames = self.traj_coords.shape[:2]
def on_epoch_end(self):
if self.shuffle:
np.random.shuffle(self.indices)
def __len__(self):
return int(np.ceil(len(self.indices) / self.batch_size))
def __getitem__(self, index):
cur_indices = self.indices[index * self.batch_size:
(index + 1) * self.batch_size]
b_size = len(cur_indices)
traj_indices, frame_indices = np.unravel_index(
cur_indices, (self.n_traj, self.n_frames - self.tau))
nbr_list_1 = self.nbr_lists[traj_indices, frame_indices]
nbr_list_2 = self.nbr_lists[traj_indices, frame_indices + self.tau]
nbr_dist_1 = self.nbr_dists[traj_indices, frame_indices]
nbr_dist_2 = self.nbr_dists[traj_indices, frame_indices + self.tau]
atom_types = np.tile(self.atom_types, (b_size, 1))
target_index = np.tile(self.target_index, (b_size, 1))
batch_Y = np.zeros([b_size, self.n_classes * 2], dtype='float32')
return ([atom_types, target_index, nbr_dist_1, nbr_list_1,
nbr_dist_2, nbr_list_2], batch_Y)
class MDStackGenerator_vannila(keras.utils.Sequence):
"""
The `MDStackGenerator_vannila` load data from a `NpzFile` generated by the
preprocess function with both `kdtree` and `direct` modes.
traj_coords: np.float32 arrays with shape (F, N, 3), stores the coordinates
of each atom in each frame.
atom_types: np.int32 arrays with shape (N,), stores the atomic number of
each atom in the MD simulation.
target_index: np.int32 arrays with shape (n,), stores the indexes of
the target atoms. (`n <= N`)
"""
def __init__(self, fnames, tau=1, n_classes=2,
batch_size=1024, random_seed=123, shuffle=True):
self.fnames = fnames
self.tau = tau
self.n_classes = n_classes
self.batch_size = batch_size
self.random_seed = random_seed
self.shuffle = shuffle
self.load_data()
self.indices = np.arange(self.n_traj * (self.n_frames - self.tau))
self.random_seed = random_seed
if self.shuffle:
np.random.shuffle(self.indices)
def load_data(self):
traj_coords, atom_types, target_index = [], [], []
for fname in self.fnames:
with np.load(fname) as data:
traj_coords.append(data['traj_coords'])
atom_types.append(data['atom_types'])
target_index.append(data['target_index'])
all_types = np.stack(atom_types)
all_target_index = np.stack(target_index)
assert np.all(all_types == all_types[0]), 'Atoms should be the '\
'same for each trajectory'
assert np.all(all_target_index == all_target_index[0])
self.atom_types = all_types[0]
self.target_index = all_target_index[0]
self.traj_coords = np.stack(traj_coords, axis=0)
self.n_traj, self.n_frames = self.traj_coords.shape[:2]
def on_epoch_end(self):
if self.shuffle:
np.random.shuffle(self.indices)
def __len__(self):
return int(np.ceil(len(self.indices) / self.batch_size))
def __getitem__(self, index):
cur_indices = self.indices[index * self.batch_size:
(index + 1) * self.batch_size]
b_size = len(cur_indices)
traj_indices, frame_indices = np.unravel_index(
cur_indices, (self.n_traj, self.n_frames - self.tau))
traj_coords_1 = self.traj_coords[traj_indices, frame_indices][
:, self.target_index]
traj_coords_2 = self.traj_coords[traj_indices,
frame_indices + self.tau][
:, self.target_index]
batch_Y = np.zeros([b_size, self.n_classes * 2], dtype='float32')
return ([traj_coords_1, traj_coords_2], batch_Y)
| [
"numpy.tile",
"numpy.stack",
"numpy.zeros",
"numpy.unravel_index",
"numpy.all",
"numpy.load",
"numpy.arange",
"numpy.random.shuffle"
] | [((1557, 1608), 'numpy.arange', 'np.arange', (['(self.n_traj * (self.n_frames - self.tau))'], {}), '(self.n_traj * (self.n_frames - self.tau))\n', (1566, 1608), True, 'import numpy as np\n'), ((2209, 2229), 'numpy.stack', 'np.stack', (['atom_types'], {}), '(atom_types)\n', (2217, 2229), True, 'import numpy as np\n'), ((2257, 2279), 'numpy.stack', 'np.stack', (['target_index'], {}), '(target_index)\n', (2265, 2279), True, 'import numpy as np\n'), ((2295, 2328), 'numpy.all', 'np.all', (['(all_types == all_types[0])'], {}), '(all_types == all_types[0])\n', (2301, 2328), True, 'import numpy as np\n'), ((2408, 2455), 'numpy.all', 'np.all', (['(all_target_index == all_target_index[0])'], {}), '(all_target_index == all_target_index[0])\n', (2414, 2455), True, 'import numpy as np\n'), ((2571, 2600), 'numpy.stack', 'np.stack', (['traj_coords'], {'axis': '(0)'}), '(traj_coords, axis=0)\n', (2579, 2600), True, 'import numpy as np\n'), ((2626, 2653), 'numpy.stack', 'np.stack', (['nbr_lists'], {'axis': '(0)'}), '(nbr_lists, axis=0)\n', (2634, 2653), True, 'import numpy as np\n'), ((2678, 2704), 'numpy.stack', 'np.stack', (['lattices'], {'axis': '(0)'}), '(lattices, axis=0)\n', (2686, 2704), True, 'import numpy as np\n'), ((3189, 3259), 'numpy.unravel_index', 'np.unravel_index', (['cur_indices', '(self.n_traj, self.n_frames - self.tau)'], {}), '(cur_indices, (self.n_traj, self.n_frames - self.tau))\n', (3205, 3259), True, 'import numpy as np\n'), ((3298, 3427), 'numpy.stack', 'np.stack', (['[self.traj_coords[traj_indices, frame_indices], self.traj_coords[\n traj_indices, frame_indices + self.tau]]'], {'axis': '(-1)'}), '([self.traj_coords[traj_indices, frame_indices], self.traj_coords[\n traj_indices, frame_indices + self.tau]], axis=-1)\n', (3306, 3427), True, 'import numpy as np\n'), ((3488, 3611), 'numpy.stack', 'np.stack', (['[self.lattices[traj_indices, frame_indices], self.lattices[traj_indices, \n frame_indices + self.tau]]'], {'axis': '(-1)'}), '([self.lattices[traj_indices, frame_indices], self.lattices[\n traj_indices, frame_indices + self.tau]], axis=-1)\n', (3496, 3611), True, 'import numpy as np\n'), ((3673, 3798), 'numpy.stack', 'np.stack', (['[self.nbr_lists[traj_indices, frame_indices], self.nbr_lists[traj_indices, \n frame_indices + self.tau]]'], {'axis': '(-1)'}), '([self.nbr_lists[traj_indices, frame_indices], self.nbr_lists[\n traj_indices, frame_indices + self.tau]], axis=-1)\n', (3681, 3798), True, 'import numpy as np\n'), ((3853, 3890), 'numpy.tile', 'np.tile', (['self.atom_types', '(b_size, 1)'], {}), '(self.atom_types, (b_size, 1))\n', (3860, 3890), True, 'import numpy as np\n'), ((3914, 3953), 'numpy.tile', 'np.tile', (['self.target_index', '(b_size, 1)'], {}), '(self.target_index, (b_size, 1))\n', (3921, 3953), True, 'import numpy as np\n'), ((3972, 4027), 'numpy.zeros', 'np.zeros', (['[b_size, self.n_classes * 2]'], {'dtype': '"""float32"""'}), "([b_size, self.n_classes * 2], dtype='float32')\n", (3980, 4027), True, 'import numpy as np\n'), ((5605, 5656), 'numpy.arange', 'np.arange', (['(self.n_traj * (self.n_frames - self.tau))'], {}), '(self.n_traj * (self.n_frames - self.tau))\n', (5614, 5656), True, 'import numpy as np\n'), ((6260, 6280), 'numpy.stack', 'np.stack', (['atom_types'], {}), '(atom_types)\n', (6268, 6280), True, 'import numpy as np\n'), ((6308, 6330), 'numpy.stack', 'np.stack', (['target_index'], {}), '(target_index)\n', (6316, 6330), True, 'import numpy as np\n'), ((6346, 6379), 'numpy.all', 'np.all', (['(all_types == all_types[0])'], {}), '(all_types == all_types[0])\n', (6352, 6379), True, 'import numpy as np\n'), ((6459, 6506), 'numpy.all', 'np.all', (['(all_target_index == all_target_index[0])'], {}), '(all_target_index == all_target_index[0])\n', (6465, 6506), True, 'import numpy as np\n'), ((6621, 6650), 'numpy.stack', 'np.stack', (['traj_coords'], {'axis': '(0)'}), '(traj_coords, axis=0)\n', (6629, 6650), True, 'import numpy as np\n'), ((6676, 6703), 'numpy.stack', 'np.stack', (['nbr_lists'], {'axis': '(0)'}), '(nbr_lists, axis=0)\n', (6684, 6703), True, 'import numpy as np\n'), ((6729, 6756), 'numpy.stack', 'np.stack', (['nbr_dists'], {'axis': '(0)'}), '(nbr_dists, axis=0)\n', (6737, 6756), True, 'import numpy as np\n'), ((7241, 7311), 'numpy.unravel_index', 'np.unravel_index', (['cur_indices', '(self.n_traj, self.n_frames - self.tau)'], {}), '(cur_indices, (self.n_traj, self.n_frames - self.tau))\n', (7257, 7311), True, 'import numpy as np\n'), ((7628, 7665), 'numpy.tile', 'np.tile', (['self.atom_types', '(b_size, 1)'], {}), '(self.atom_types, (b_size, 1))\n', (7635, 7665), True, 'import numpy as np\n'), ((7689, 7728), 'numpy.tile', 'np.tile', (['self.target_index', '(b_size, 1)'], {}), '(self.target_index, (b_size, 1))\n', (7696, 7728), True, 'import numpy as np\n'), ((7747, 7802), 'numpy.zeros', 'np.zeros', (['[b_size, self.n_classes * 2]'], {'dtype': '"""float32"""'}), "([b_size, self.n_classes * 2], dtype='float32')\n", (7755, 7802), True, 'import numpy as np\n'), ((8838, 8889), 'numpy.arange', 'np.arange', (['(self.n_traj * (self.n_frames - self.tau))'], {}), '(self.n_traj * (self.n_frames - self.tau))\n', (8847, 8889), True, 'import numpy as np\n'), ((9346, 9366), 'numpy.stack', 'np.stack', (['atom_types'], {}), '(atom_types)\n', (9354, 9366), True, 'import numpy as np\n'), ((9394, 9416), 'numpy.stack', 'np.stack', (['target_index'], {}), '(target_index)\n', (9402, 9416), True, 'import numpy as np\n'), ((9432, 9465), 'numpy.all', 'np.all', (['(all_types == all_types[0])'], {}), '(all_types == all_types[0])\n', (9438, 9465), True, 'import numpy as np\n'), ((9545, 9592), 'numpy.all', 'np.all', (['(all_target_index == all_target_index[0])'], {}), '(all_target_index == all_target_index[0])\n', (9551, 9592), True, 'import numpy as np\n'), ((9707, 9736), 'numpy.stack', 'np.stack', (['traj_coords'], {'axis': '(0)'}), '(traj_coords, axis=0)\n', (9715, 9736), True, 'import numpy as np\n'), ((10221, 10291), 'numpy.unravel_index', 'np.unravel_index', (['cur_indices', '(self.n_traj, self.n_frames - self.tau)'], {}), '(cur_indices, (self.n_traj, self.n_frames - self.tau))\n', (10237, 10291), True, 'import numpy as np\n'), ((10585, 10640), 'numpy.zeros', 'np.zeros', (['[b_size, self.n_classes * 2]'], {'dtype': '"""float32"""'}), "([b_size, self.n_classes * 2], dtype='float32')\n", (10593, 10640), True, 'import numpy as np\n'), ((1685, 1716), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (1702, 1716), True, 'import numpy as np\n'), ((2835, 2866), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (2852, 2866), True, 'import numpy as np\n'), ((5733, 5764), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (5750, 5764), True, 'import numpy as np\n'), ((6887, 6918), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (6904, 6918), True, 'import numpy as np\n'), ((8966, 8997), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (8983, 8997), True, 'import numpy as np\n'), ((9867, 9898), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (9884, 9898), True, 'import numpy as np\n'), ((1895, 1909), 'numpy.load', 'np.load', (['fname'], {}), '(fname)\n', (1902, 1909), True, 'import numpy as np\n'), ((5944, 5958), 'numpy.load', 'np.load', (['fname'], {}), '(fname)\n', (5951, 5958), True, 'import numpy as np\n'), ((9134, 9148), 'numpy.load', 'np.load', (['fname'], {}), '(fname)\n', (9141, 9148), True, 'import numpy as np\n')] |
#-*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
__all__ = ["img_01",
"img_02",
"img_03",
"img_04",
"img_05",
"img_06",
"img_07"]
def img_01():
x = np.linspace(0,10)
y = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
plt.savefig("img_01.png")
def img_02():
T = [50, 60, 70, 80, 90, 100, 110, 120]
P = [12, 20, 33, 54, 90, 148, 244, 403]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(T, P)
ax.set_xlabel(u"Temperatura (°C)")
ax.set_ylabel(u"Presión (KPa)")
ax.set_title(u"Relación P-T")
plt.savefig("img_02.png")
def img_03():
x = np.linspace(0,10)
y = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, lw=2)
ax.plot(x, y+1, lw=4)
ax.plot(x, y+2, linewidth=6)
plt.savefig("img_03c.png")
def img_04():
theta = np.linspace(0,2*np.pi,1000)
r = 0.25*np.cos(3*theta)
fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")
ax.plot(theta, r)
plt.savefig("img_04.png")
def img_05():pass
def img_06():pass
def img_07():pass
def img_08():pass
if __name__=='__main__':
[eval(fun+"()") for fun in __all__]
| [
"numpy.linspace",
"matplotlib.pyplot.savefig",
"numpy.cos",
"matplotlib.pyplot.figure"
] | [((206, 224), 'numpy.linspace', 'np.linspace', (['(0)', '(10)'], {}), '(0, 10)\n', (217, 224), True, 'import numpy as np\n'), ((229, 238), 'numpy.cos', 'np.cos', (['x'], {}), '(x)\n', (235, 238), True, 'import numpy as np\n'), ((247, 259), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (257, 259), True, 'import matplotlib.pyplot as plt\n'), ((306, 331), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""img_01.png"""'], {}), "('img_01.png')\n", (317, 331), True, 'import matplotlib.pyplot as plt\n'), ((438, 450), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (448, 450), True, 'import matplotlib.pyplot as plt\n'), ((597, 622), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""img_02.png"""'], {}), "('img_02.png')\n", (608, 622), True, 'import matplotlib.pyplot as plt\n'), ((644, 662), 'numpy.linspace', 'np.linspace', (['(0)', '(10)'], {}), '(0, 10)\n', (655, 662), True, 'import numpy as np\n'), ((667, 676), 'numpy.cos', 'np.cos', (['x'], {}), '(x)\n', (673, 676), True, 'import numpy as np\n'), ((685, 697), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (695, 697), True, 'import matplotlib.pyplot as plt\n'), ((803, 829), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""img_03c.png"""'], {}), "('img_03c.png')\n", (814, 829), True, 'import matplotlib.pyplot as plt\n'), ((855, 886), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(1000)'], {}), '(0, 2 * np.pi, 1000)\n', (866, 886), True, 'import numpy as np\n'), ((917, 929), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (927, 929), True, 'import matplotlib.pyplot as plt\n'), ((1000, 1025), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""img_04.png"""'], {}), "('img_04.png')\n", (1011, 1025), True, 'import matplotlib.pyplot as plt\n'), ((893, 910), 'numpy.cos', 'np.cos', (['(3 * theta)'], {}), '(3 * theta)\n', (899, 910), True, 'import numpy as np\n')] |
import smplx
import os
import pickle
import pyrender
import trimesh
import numpy as np
import json
import torch
from tqdm import tqdm
import PIL.Image as pil_img
from human_body_prior.tools.model_loader import load_vposer
from temp_prox.camera import create_camera
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def read_prox_pkl(pkl_path):
body_params_dict = {}
with open(pkl_path, 'rb') as f:
data = pickle.load(f)
# data keys: camera_rotation, camera_translation, (useless)
# transl, global_orient, betas, body_pose, pose_embedding
# left_hand_pose, right_hand_pose,
# jaw_pose, leye_pose, reye_pose, expression
body_params_dict['transl'] = data['transl'][0]
body_params_dict['global_orient'] = data['global_orient'][0]
body_params_dict['betas'] = data['betas'][0]
body_params_dict['body_pose'] = data['body_pose'][0] # array, [63,]
body_params_dict['pose_embedding'] = data['pose_embedding'][0]
body_params_dict['left_hand_pose'] = data['left_hand_pose'][0]
body_params_dict['right_hand_pose'] = data['right_hand_pose'][0]
body_params_dict['jaw_pose'] = data['jaw_pose'][0]
body_params_dict['leye_pose'] = data['leye_pose'][0]
body_params_dict['reye_pose'] = data['reye_pose'][0]
body_params_dict['expression'] = data['expression'][0]
return body_params_dict
scene_name = 'BasementSittingBooth'
seq_name_list = ['BasementSittingBooth_00142_01', 'BasementSittingBooth_00145_01']
# scene_name = 'MPH112'
# seq_name_list = ['MPH112_00034_01','MPH112_00150_01', 'MPH112_00151_01', 'MPH112_00157_01', 'MPH112_00169_01']
# scene_name = 'MPH11'
# seq_name_list = ['MPH11_00034_01', 'MPH11_00150_01', 'MPH11_00151_01', 'MPH11_03515_01']
# scene_name = 'MPH16'
# seq_name_list = ['MPH16_00157_01']
# scene_name = 'MPH1Library'
# seq_name_list = ['MPH1Library_00034_01']
# scene_name = 'MPH8'
# seq_name_list = ['MPH8_00168_01']
# scene_name = 'N0SittingBooth'
# seq_name_list = ['N0SittingBooth_00162_01', 'N0SittingBooth_00169_01', 'N0SittingBooth_00169_02',
# 'N0SittingBooth_03301_01', 'N0SittingBooth_03403_01']
# scene_name = 'N0Sofa'
# seq_name_list = ['N0Sofa_00034_01', 'N0Sofa_00034_02', 'N0Sofa_00141_01', 'N0Sofa_00145_01']
# scene_name = 'N3Library'
# seq_name_list = ['N3Library_00157_01', 'N3Library_00157_02', 'N3Library_03301_01', 'N3Library_03301_02',
# 'N3Library_03375_01', 'N3Library_03375_02', 'N3Library_03403_01', 'N3Library_03403_02']
# scene_name = 'N3Office'
# seq_name_list = ['N3Office_00034_01', 'N3Office_00139_01', 'N3Office_00139_02', 'N3Office_00150_01',
# 'N3Office_00153_01', 'N3Office_00159_01', 'N3Office_03301_01']
# scene_name = 'N3OpenArea'
# seq_name_list = ['N3OpenArea_00157_01', 'N3OpenArea_00157_02', 'N3OpenArea_00158_01', 'N3OpenArea_00158_02',
# 'N3OpenArea_03301_01', 'N3OpenArea_03403_01']
# scene_name = 'Werkraum'
# seq_name_list = ['Werkraum_03301_01', 'Werkraum_03403_01', 'Werkraum_03516_01', 'Werkraum_03516_02']
for seq_name in seq_name_list:
prox_params_folder = '/mnt/hdd/PROX/PROXD/{}'.format(seq_name)
img_folder = '/mnt/hdd/PROX/recordings/{}/Color'.format(seq_name)
scene_mesh_path = '/mnt/hdd/PROX/scenes/{}.ply'.format(scene_name)
keyp_folder = '/mnt/hdd/PROX/keypoints/{}'.format(seq_name)
save_img_folder = '/local/home/szhang/temp_prox/mask_render_imgs/{}'.format(seq_name)
save_mask_folder = '/local/home/szhang/temp_prox/mask_joint/{}'.format(seq_name)
# if not os.path.exists(save_img_folder):
# os.makedirs(save_img_folder)
cam2world_dir = '/mnt/hdd/PROX/cam2world'
with open(os.path.join(cam2world_dir, scene_name + '.json'), 'r') as f:
cam2world = np.array(json.load(f)) # [4, 4] last row: [0,0,0,1]
########## smplx/vposer model
vposer_model_path = '/mnt/hdd/PROX/body_models/vposer_v1_0'
smplx_model_path = '/mnt/hdd/PROX/body_models/smplx_model'
smplx_model = smplx.create(smplx_model_path, model_type='smplx',
gender='male', ext='npz',
num_pca_comps=12,
create_global_orient=True,
create_body_pose=True,
create_betas=True,
create_left_hand_pose=True,
create_right_hand_pose=True,
create_expression=True,
create_jaw_pose=True,
create_leye_pose=True,
create_reye_pose=True,
create_transl=True,
batch_size=1
).to(device)
print('[INFO] smplx model loaded.')
vposer_model, _ = load_vposer(vposer_model_path, vp_model='snapshot')
vposer_model = vposer_model.to(device)
print('[INFO] vposer model loaded')
########### render settings
camera_center = np.array([951.30, 536.77])
camera_pose = np.eye(4)
camera_pose = np.array([1.0, -1.0, -1.0, 1.0]).reshape(-1, 1) * camera_pose
camera_render = pyrender.camera.IntrinsicsCamera(
fx=1060.53, fy=1060.38,
cx=camera_center[0], cy=camera_center[1])
light = pyrender.DirectionalLight(color=np.ones(3), intensity=2.0)
material = pyrender.MetallicRoughnessMaterial(
metallicFactor=0.0,
alphaMode='OPAQUE',
baseColorFactor=(1.0, 1.0, 0.9, 1.0))
static_scene = trimesh.load(scene_mesh_path)
trans = np.linalg.inv(cam2world)
static_scene.apply_transform(trans)
static_scene_mesh = pyrender.Mesh.from_trimesh(static_scene)
####################### create camera object ########################
camera_center = torch.tensor(camera_center).float().reshape(1, 2) # # tensor, [1,2]
camera = create_camera(focal_length_x=1060.53,
focal_length_y=1060.53,
center= camera_center,
batch_size=1,)
if hasattr(camera, 'rotation'):
camera.rotation.requires_grad = False
camera = camera.to(device)
############################# redering scene #######################
scene = pyrender.Scene()
scene.add(camera_render, pose=camera_pose)
scene.add(light, pose=camera_pose)
scene.add(static_scene_mesh, 'mesh')
r = pyrender.OffscreenRenderer(viewport_width=1920,
viewport_height=1080)
color_scene, depth_scene = r.render(scene) # color [1080, 1920, 3], depth [1080, 1920]
# color_scene = color_scene.astype(np.float32) / 255.0
# img_scene = (color_scene * 255).astype(np.uint8)
############# render, mask
img_list = os.listdir(img_folder)
img_list = sorted(img_list)
seq_mask = []
cnt = 0
for img_fn in tqdm(img_list):
cnt += 1
# if cnt == 1000:
# break
if img_fn.endswith('.png') or img_fn.endswith('.jpg') and not img_fn.startswith('.'):
mask = np.ones([25])
######## get smplx body mesh
prox_params_dir = os.path.join(prox_params_folder, 'results', img_fn[0:-4], '000.pkl')
params_dict = read_prox_pkl(prox_params_dir)
for param_name in params_dict:
params_dict[param_name] = np.expand_dims(params_dict[param_name], axis=0)
params_dict[param_name] = torch.from_numpy(params_dict[param_name]).to(device)
smplx_output = smplx_model(return_verts=True, **params_dict) # generated human body mesh
body_verts = smplx_output.vertices.detach().cpu().numpy()[0]
body_mesh = trimesh.Trimesh(body_verts, smplx_model.faces, process=False)
body_mesh = pyrender.Mesh.from_trimesh(body_mesh, material=material)
############################# redering body #######################
scene = pyrender.Scene()
scene.add(camera_render, pose=camera_pose)
scene.add(light, pose=camera_pose)
# scene.add(static_scene_mesh, 'mesh')
scene.add(body_mesh, 'mesh')
r = pyrender.OffscreenRenderer(viewport_width=1920,
viewport_height=1080)
color_body, depth_body = r.render(scene) # color [1080, 1920, 3], depth [1080, 1920]
# color_body = color_body.astype(np.float32) / 255.0
# img_body = (color_body * 255).astype(np.uint8)
######### body joints --> set mask
body_joints = smplx_output.joints
projected_joints = camera(body_joints) # [1, n, 2]
projected_joints = projected_joints[0][0:25].detach().cpu().numpy() # [25, 2]
projected_joints = projected_joints.astype(int)
for j_id in range(25):
# for j_id in [5, 8, 11, 4, 7, 10]: # todo: only mask joints in legs/feet
x_coord, y_coord = projected_joints[j_id][0], projected_joints[j_id][1]
if 0 <= x_coord < 1920 and 0 <= y_coord < 1080:
if depth_body[y_coord][x_coord] - depth_scene[y_coord][x_coord] > 0.1 \
and depth_scene[y_coord][x_coord] != 0: # todo: set threshold
mask[j_id] = 0 # occlusion happens, mask corresponding joint
seq_mask.append(mask)
# ############################# render body+scene (for visualization)
# scene = pyrender.Scene()
# scene.add(camera_render, pose=camera_pose)
# scene.add(light, pose=camera_pose)
# scene.add(static_scene_mesh, 'mesh')
# scene.add(body_mesh, 'mesh')
# r = pyrender.OffscreenRenderer(viewport_width=1920,
# viewport_height=1080)
# color, _ = r.render(scene) # color [1080, 1920, 3], depth [1080, 1920]
# color = color.astype(np.float32) / 255.0
# save_img = (color * 255).astype(np.uint8)
#
# ########## for visualization
# for k in range(len(projected_joints)):
# for p in range(max(0, projected_joints[k][0] - 3), min(1920 - 1, projected_joints[k][0] + 3)):
# for q in range(max(0, projected_joints[k][1] - 3), min(1080 - 1, projected_joints[k][1] + 3)):
# if mask[k] == 1:
# save_img[q][p][0] = 255
# save_img[q][p][1] = 0
# save_img[q][p][2] = 0
# else:
# save_img[q][p][0] = 0
# save_img[q][p][1] = 255
# save_img[q][p][2] = 0
#
# ######### save img (for visualization)
# # img_scene = pil_img.fromarray(img_scene.astype(np.uint8))
# # img_scene.save('img_scene.png')
# # img_body = pil_img.fromarray(img_body.astype(np.uint8))
# # img_body.save('img_body.png')
# save_img = pil_img.fromarray(save_img.astype(np.uint8))
# save_img.save('{}/{}'.format(save_img_folder, img_fn))
if not os.path.exists(save_mask_folder):
os.makedirs(save_mask_folder)
seq_mask = np.asarray(seq_mask)
np.save('{}/mask_joint.npy'.format(save_mask_folder), seq_mask)
| [
"torch.from_numpy",
"numpy.array",
"torch.cuda.is_available",
"os.path.exists",
"os.listdir",
"numpy.asarray",
"pyrender.camera.IntrinsicsCamera",
"numpy.eye",
"pyrender.Mesh.from_trimesh",
"numpy.ones",
"smplx.create",
"pickle.load",
"temp_prox.camera.create_camera",
"trimesh.Trimesh",
... | [((4956, 5007), 'human_body_prior.tools.model_loader.load_vposer', 'load_vposer', (['vposer_model_path'], {'vp_model': '"""snapshot"""'}), "(vposer_model_path, vp_model='snapshot')\n", (4967, 5007), False, 'from human_body_prior.tools.model_loader import load_vposer\n'), ((5145, 5170), 'numpy.array', 'np.array', (['[951.3, 536.77]'], {}), '([951.3, 536.77])\n', (5153, 5170), True, 'import numpy as np\n'), ((5190, 5199), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (5196, 5199), True, 'import numpy as np\n'), ((5300, 5403), 'pyrender.camera.IntrinsicsCamera', 'pyrender.camera.IntrinsicsCamera', ([], {'fx': '(1060.53)', 'fy': '(1060.38)', 'cx': 'camera_center[0]', 'cy': 'camera_center[1]'}), '(fx=1060.53, fy=1060.38, cx=camera_center[0\n ], cy=camera_center[1])\n', (5332, 5403), False, 'import pyrender\n'), ((5502, 5618), 'pyrender.MetallicRoughnessMaterial', 'pyrender.MetallicRoughnessMaterial', ([], {'metallicFactor': '(0.0)', 'alphaMode': '"""OPAQUE"""', 'baseColorFactor': '(1.0, 1.0, 0.9, 1.0)'}), "(metallicFactor=0.0, alphaMode='OPAQUE',\n baseColorFactor=(1.0, 1.0, 0.9, 1.0))\n", (5536, 5618), False, 'import pyrender\n'), ((5660, 5689), 'trimesh.load', 'trimesh.load', (['scene_mesh_path'], {}), '(scene_mesh_path)\n', (5672, 5689), False, 'import trimesh\n'), ((5702, 5726), 'numpy.linalg.inv', 'np.linalg.inv', (['cam2world'], {}), '(cam2world)\n', (5715, 5726), True, 'import numpy as np\n'), ((5791, 5831), 'pyrender.Mesh.from_trimesh', 'pyrender.Mesh.from_trimesh', (['static_scene'], {}), '(static_scene)\n', (5817, 5831), False, 'import pyrender\n'), ((6011, 6113), 'temp_prox.camera.create_camera', 'create_camera', ([], {'focal_length_x': '(1060.53)', 'focal_length_y': '(1060.53)', 'center': 'camera_center', 'batch_size': '(1)'}), '(focal_length_x=1060.53, focal_length_y=1060.53, center=\n camera_center, batch_size=1)\n', (6024, 6113), False, 'from temp_prox.camera import create_camera\n'), ((6391, 6407), 'pyrender.Scene', 'pyrender.Scene', ([], {}), '()\n', (6405, 6407), False, 'import pyrender\n'), ((6543, 6612), 'pyrender.OffscreenRenderer', 'pyrender.OffscreenRenderer', ([], {'viewport_width': '(1920)', 'viewport_height': '(1080)'}), '(viewport_width=1920, viewport_height=1080)\n', (6569, 6612), False, 'import pyrender\n'), ((6902, 6924), 'os.listdir', 'os.listdir', (['img_folder'], {}), '(img_folder)\n', (6912, 6924), False, 'import os\n'), ((7005, 7019), 'tqdm.tqdm', 'tqdm', (['img_list'], {}), '(img_list)\n', (7009, 7019), False, 'from tqdm import tqdm\n'), ((11467, 11487), 'numpy.asarray', 'np.asarray', (['seq_mask'], {}), '(seq_mask)\n', (11477, 11487), True, 'import numpy as np\n'), ((298, 323), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (321, 323), False, 'import torch\n'), ((443, 457), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (454, 457), False, 'import pickle\n'), ((11380, 11412), 'os.path.exists', 'os.path.exists', (['save_mask_folder'], {}), '(save_mask_folder)\n', (11394, 11412), False, 'import os\n'), ((11422, 11451), 'os.makedirs', 'os.makedirs', (['save_mask_folder'], {}), '(save_mask_folder)\n', (11433, 11451), False, 'import os\n'), ((3728, 3777), 'os.path.join', 'os.path.join', (['cam2world_dir', "(scene_name + '.json')"], {}), "(cam2world_dir, scene_name + '.json')\n", (3740, 3777), False, 'import os\n'), ((3819, 3831), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3828, 3831), False, 'import json\n'), ((4044, 4408), 'smplx.create', 'smplx.create', (['smplx_model_path'], {'model_type': '"""smplx"""', 'gender': '"""male"""', 'ext': '"""npz"""', 'num_pca_comps': '(12)', 'create_global_orient': '(True)', 'create_body_pose': '(True)', 'create_betas': '(True)', 'create_left_hand_pose': '(True)', 'create_right_hand_pose': '(True)', 'create_expression': '(True)', 'create_jaw_pose': '(True)', 'create_leye_pose': '(True)', 'create_reye_pose': '(True)', 'create_transl': '(True)', 'batch_size': '(1)'}), "(smplx_model_path, model_type='smplx', gender='male', ext='npz',\n num_pca_comps=12, create_global_orient=True, create_body_pose=True,\n create_betas=True, create_left_hand_pose=True, create_right_hand_pose=\n True, create_expression=True, create_jaw_pose=True, create_leye_pose=\n True, create_reye_pose=True, create_transl=True, batch_size=1)\n", (4056, 4408), False, 'import smplx\n'), ((5460, 5470), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (5467, 5470), True, 'import numpy as np\n'), ((7197, 7210), 'numpy.ones', 'np.ones', (['[25]'], {}), '([25])\n', (7204, 7210), True, 'import numpy as np\n'), ((7283, 7351), 'os.path.join', 'os.path.join', (['prox_params_folder', '"""results"""', 'img_fn[0:-4]', '"""000.pkl"""'], {}), "(prox_params_folder, 'results', img_fn[0:-4], '000.pkl')\n", (7295, 7351), False, 'import os\n'), ((7836, 7897), 'trimesh.Trimesh', 'trimesh.Trimesh', (['body_verts', 'smplx_model.faces'], {'process': '(False)'}), '(body_verts, smplx_model.faces, process=False)\n', (7851, 7897), False, 'import trimesh\n'), ((7922, 7978), 'pyrender.Mesh.from_trimesh', 'pyrender.Mesh.from_trimesh', (['body_mesh'], {'material': 'material'}), '(body_mesh, material=material)\n', (7948, 7978), False, 'import pyrender\n'), ((8081, 8097), 'pyrender.Scene', 'pyrender.Scene', ([], {}), '()\n', (8095, 8097), False, 'import pyrender\n'), ((8308, 8377), 'pyrender.OffscreenRenderer', 'pyrender.OffscreenRenderer', ([], {'viewport_width': '(1920)', 'viewport_height': '(1080)'}), '(viewport_width=1920, viewport_height=1080)\n', (8334, 8377), False, 'import pyrender\n'), ((5218, 5250), 'numpy.array', 'np.array', (['[1.0, -1.0, -1.0, 1.0]'], {}), '([1.0, -1.0, -1.0, 1.0])\n', (5226, 5250), True, 'import numpy as np\n'), ((7494, 7541), 'numpy.expand_dims', 'np.expand_dims', (['params_dict[param_name]'], {'axis': '(0)'}), '(params_dict[param_name], axis=0)\n', (7508, 7541), True, 'import numpy as np\n'), ((5929, 5956), 'torch.tensor', 'torch.tensor', (['camera_center'], {}), '(camera_center)\n', (5941, 5956), False, 'import torch\n'), ((7584, 7625), 'torch.from_numpy', 'torch.from_numpy', (['params_dict[param_name]'], {}), '(params_dict[param_name])\n', (7600, 7625), False, 'import torch\n')] |
import numpy as np
import torch
from torch.autograd import Variable
from tqdm import tqdm
def hessian_spectral_norm_approx(model, loader, criterion, M=20, seed=777, logger=None):
model.train()
def get_Hv(v):
flat_grad_loss = None
flat_Hv = None
ind = 0
for batch_idx, (inputs, targets) in tqdm(enumerate(loader), total=int(0.1*len(loader))):
ind += 1
if ind > 0.1 * len(loader):
break
model.zero_grad()
if torch.cuda.is_available():
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = Variable(inputs), Variable(targets)
outputs = model(inputs)
loss = criterion(outputs, targets)
grads = torch.autograd.grad(loss, model.parameters(), create_graph=True)
flat_grad_loss = torch.cat([grad.view(-1) for grad in grads])
grad_dot_v = (flat_grad_loss * v).sum()
Hv = torch.autograd.grad(grad_dot_v, model.parameters())
if flat_Hv is None:
flat_Hv = torch.cat([grad.contiguous().view(-1) for grad in Hv])
else:
flat_Hv.data.add_(torch.cat([grad.contiguous().view(-1) for grad in Hv]).data)
flat_Hv.data.mul_(1./ind)
return flat_Hv
p_order = [p[0] for p in model.named_parameters()]
params = model.state_dict()
init_w = np.concatenate([params[w].cpu().numpy().reshape(-1,) for w in p_order])
rng = np.random.RandomState(seed)
if torch.cuda.is_available():
v = Variable(torch.from_numpy(rng.normal(0.0, scale=1.0, size=init_w.shape).astype("float32")).cuda())
else:
v = Variable(torch.from_numpy(rng.normal(0.0, scale=1.0, size=init_w.shape).astype("float32")))
for i in range(M):
Hv = get_Hv(v)
pmax = torch.max(Hv.data).item()
nmax = torch.min(Hv.data).item()
if pmax < np.abs(nmax):
spec_norm = nmax
else:
spec_norm = pmax
v = Hv.detach()
v.data.mul_(1./spec_norm)
if logger is not None:
logger.info('iter: {}/{}, spectral norm: {} '.format(i, M, spec_norm))
return spec_norm
| [
"numpy.abs",
"torch.max",
"torch.min",
"torch.cuda.is_available",
"torch.autograd.Variable",
"numpy.random.RandomState"
] | [((1507, 1534), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (1528, 1534), True, 'import numpy as np\n'), ((1543, 1568), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1566, 1568), False, 'import torch\n'), ((514, 539), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (537, 539), False, 'import torch\n'), ((1942, 1954), 'numpy.abs', 'np.abs', (['nmax'], {}), '(nmax)\n', (1948, 1954), True, 'import numpy as np\n'), ((635, 651), 'torch.autograd.Variable', 'Variable', (['inputs'], {}), '(inputs)\n', (643, 651), False, 'from torch.autograd import Variable\n'), ((653, 670), 'torch.autograd.Variable', 'Variable', (['targets'], {}), '(targets)\n', (661, 670), False, 'from torch.autograd import Variable\n'), ((1857, 1875), 'torch.max', 'torch.max', (['Hv.data'], {}), '(Hv.data)\n', (1866, 1875), False, 'import torch\n'), ((1898, 1916), 'torch.min', 'torch.min', (['Hv.data'], {}), '(Hv.data)\n', (1907, 1916), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 28 16:39:43 2018
Covariance Matrix Decomposition
@author: Satie
"""
import numpy as np
from numpy.linalg import matrix_rank
from multiprocessing import Pool
class Decomposer(object):
def __init__(self, data, preavg, delta):
self.__data = data
self.__sigma = preavg
self.__N, self.__p = data.shape # N by p
self.delta = delta # observation frequency
def __l1_norm_off_diag(self, matrix):
matrix_off = np.abs(matrix - np.diag(np.diag(matrix)))
return matrix_off.sum()
def __Obj(self, S, F, T, lam):
err = 0.5 * (np.linalg.norm(S - F - T, 'fro') ** 2)
reg_F = lam[0] * np.linalg.norm(F, 'nuc')
reg_T = lam[1] * self.__l1_norm_off_diag(T)
return err + reg_F + reg_T
def __Lag(self, S, F, T, F_cp, T_cp, LAM1, LAM2, mu, lam):
penF = ((2 * mu[0]) ** (-1)) * (np.linalg.norm(F - F_cp, 'fro') ** 2)
penT = ((2 * mu[1]) ** (-1)) * (np.linalg.norm(T - T_cp, 'fro') ** 2)
duaF = (LAM1 * (F_cp - F)).sum()
duaT = (LAM2 * (T_cp - T)).sum()
return self.__Obj(S, F, T, lam) + penF + penT + duaF + duaT
def Proj_SoftThres(self, matrix, eps):
_p, _q = matrix.shape
assert _p == _q
diag = matrix * np.eye(_p)
off = matrix - diag
truc = np.abs(off) - eps
sign = np.sign(off)
truc[truc < 0] = 0
sign[truc < 0] = 0
return sign * truc + diag
def Proj_SVT(self, matrix, eps):
_p, _q = matrix.shape
assert _p == _q
s, V = np.linalg.eig(matrix)
s = s - eps
s[s <= 0] = 0
return np.dot(V, np.dot(np.diag(s), V.T))
def Proj_PD(self, matrix, eps):
_p, _q = matrix.shape
assert _p == _q
e, V = np.linalg.eig(matrix)
# Handle complex eigenvalues due to numerical rounding.
if isinstance(e[0], complex):
if np.allclose(matrix, matrix.T):
e = np.real(e)
V = np.real(V)
else:
raise ValueError('Proj_PD: Complex eigens encountered.')
e[e < eps] = eps
return np.dot(V, np.dot(np.diag(e), V.T))
def GCV_Alt(self, L, S, lam1, eps, dof = 1):
# Temp version
def DoF1(eigens, lam):
b, V = np.linalg.eig(L)
b = np.real(b)
sig2 = np.outer(eigens, np.ones(len(eigens)))
deno = (sig2 - sig2.T)
np.fill_diagonal(deno, np.inf)
deno[deno == 0] = np.inf
assert np.all(deno != 0)
deno = deno ** -1
cons = np.sqrt(eigens) * (np.sqrt(eigens) - lam)
dof = 1 + 2 * cons * deno.sum(0)
ind = (b > 0).astype('int')
return np.dot(1 + 2 * dof, ind)
def DoF2(eigens, lam):
ind = (eigens >= lam).astype('int'); res = 0
for i in range(ind.sum()):
res1 = 0; res2 = 0
for jj in range(len(eigens)):
if jj != i:
res2 += eigens[i] / eigens[i] - eigens[jj]
if jj > ind.sum():
res1 += eigens[jj] / eigens[i] - eigens[jj]
res += res1 - 2 * lam * res2
return (2 * len(eigens) - ind.sum()) * ind.sum() + res
s, V = np.linalg.eig(self.__sigma - S)
s[s < eps] = eps; s = np.real(s) # Note s is already sorted.
if dof == 1:
df1 = DoF1(s, lam1)
else:
df1 = DoF2(s, lam1)
tot_df = df1 + np.count_nonzero(S)
err = np.linalg.norm(self.__sigma - L - S, 'fro')
aic = np.log(err) + (2 * tot_df) / (self.__p ** 2)
if self.__p ** 2 <= tot_df:
gcv = 999999
else:
gcv = err / (self.__p ** 2 - tot_df)
return gcv, aic
def __Initializer(self, S, mode, lam, verbose = False):
_p, _q = S.shape
if mode == 'SP':
res = self.Proj_SoftThres(S, lam)
elif mode == 'LR':
res = self.Proj_SVT(S, lam)
elif mode == 'random':
res = np.random.uniform(S.min(), S.max(), size = _p * _p)
res = res.reshape((_p, _p))
res = 0.5 * (res + res.T)
else:
res = np.zeros_like(S)
return res
def Solver_ADMM(self, lam, verbose = 2, args_dict = {}):
# def Solver_ADMM(self, params):
# lam, verbose, args_dict = map(params.get, ['lam', 'verbose', 'args_dict'])
params = {'tol': 1e-4, 'max_iter': 200,
'eps': 1e-4, 'mu': (2, 2), 'monitor': 1}
params.update(args_dict)
_S = self.__sigma
_p, _q = _S.shape
assert _p == _q
# Initialize.
if verbose >= 2:
print('------------------------------------')
print('Solver_ADMM: Initializing.')
lam1, lam2 = lam
mu1, mu2 = params['mu']
LAM1 = np.zeros((_p, _p))
LAM2 = np.zeros((_p, _p))
F = self.__Initializer(0.5 * _S, 'LR', lam1)
T = self.__Initializer(0.5 * _S, 'SP', lam2)
epoch = 1; converge = False; err = np.linalg.norm(_S - F - T, 'fro')
while (epoch <= params['max_iter']) and (not converge):
if verbose == 2:
print('Epoch: {}'.format(epoch))
last_F = F; last_T = T
if params['monitor'] >= 2:
last_e, last_V = np.linalg.eig(last_F)
# Low-rank: Projection.
F_cp = self.Proj_PD(F + mu1 * LAM1, 0.)
# Low-rank: Main update.
F = (1 + mu1) ** (-1) * self.Proj_SVT(mu1 * (_S - T - LAM1) + F_cp, lam1 * mu1)
# Low-rank: Dual update.
LAM1 = LAM1 + mu1 ** (-1) * (F - F_cp)
# Sparse: Projection.
T_cp = self.Proj_PD(T + mu2 * LAM2, params['eps'])
# Sparse: Main update.
T = (1 + mu2) ** (-1) * self.Proj_SoftThres(mu2 * (_S - F - LAM2) + T_cp, lam2 * mu2)
# Sparse: Dual update.
LAM2 = LAM2 - mu2 ** (-1) * (T_cp - T)
# Post processing.
epoch += 1
if params['monitor'] >= 2:
cur_e, cur_V = np.linalg.eig(F)
err = np.linalg.norm(cur_e - last_e, 2)
err += np.linalg.norm(cur_V - last_V, 'fro')
err += np.linalg.norm(T - last_T, 'fro')
else:
err = np.linalg.norm(last_F + last_T - F - T, 'fro')
if verbose >= 2:
print('Solver_ADMM: Frobenius error: {}.'.format(
np.linalg.norm(_S - F - T, 'fro')))
print('Solver_ADMM: Objective value: {}.'.format(
self.__Obj(_S, F, T, lam)))
print('Solver_ADMM: Lag value: {}.'.format(
self.__Lag(_S, F, T, F_cp, T_cp, LAM1, LAM2, params['mu'], lam)))
if np.abs(err) < params['tol']:
converge = True
if verbose:
print('Solver_ADMM: Converged with achieved tol {},'.format(err))
if epoch > params['max_iter'] and verbose:
print('Solver_ADMM: Maximum iteration {} reached.'.format(params['max_iter']))
return F, T
def __D(self, F, T, F_next, T_next):
return np.linalg.norm(F - F_next, 'fro') + np.linalg.norm(T - T_next, 'fro')
def Estimator(self, params_lam, params_gam, solver_args_dict = {},
verbose = 3, grid = False, use = 'GCV'):
# Fixme: Reduce args
solver_args = {'tol': 1e-3, 'max_iter': 100, 'eps': 1e-4, 'monitor': 1}
solver_args.update(solver_args_dict); solver_args['eps']
# Low rank penalty
if params_lam is None:
params_lam = (-2, 2, 20)
# Sparse penalty
if params_gam is None:
params_gam = (-2, 2, 20)
lam_try = 10 ** (np.linspace(*params_lam))
gam_try = 10 ** (np.linspace(*params_gam))
nl, ng = (params_lam[2], params_gam[2])
D = {'GCV': {'lam1': np.zeros(nl), 'lam2': np.zeros(ng)},
'AIC': {'lam1': np.zeros(nl), 'lam2': np.zeros(ng)}}
# Deal with use
if len(use) == 4:
dof = int(use[-1])
use = use[:3]
assert dof <= 2 and dof > 0
assert use in ['GCV', 'AIC']
elif use in ['GCV', 'AIC']:
dof = 1
else:
raise ValueError()
# Select lambda
for l in range(nl):
if verbose:
print("Estimator: Tuning lambda {} / {}".format(l + 1, nl))
lam_cur = (lam_try[l], gam_try[0])
f, t = self.Solver_ADMM(lam_cur, verbose - 1, solver_args)
D['GCV']['lam1'][l], D['AIC']['lam1'][l] = self.GCV_Alt(f, t, lam_cur[0], eps, dof)
if verbose:
print("Estimator: Current GCV {}".format(D['GCV']['lam1'][l]))
print("Estimator: Current AIC {}".format(D['AIC']['lam1'][l]))
lam_final = lam_try[D[use]['lam1'].argmin()] # Fixme: possible duplication
# Select gamma for lam_final
for g in range(ng):
if verbose:
print("Estimator: Tuning gamma {} / {}".format(g + 1, nl))
lam_cur = (lam_final, gam_try[g])
f, t = self.Solver_ADMM(lam_cur, verbose - 1, solver_args)
D['GCV']['lam2'][g], D['AIC']['lam2'][g] = self.GCV_Alt(f, t, lam_cur[0], eps)
if verbose:
print("Estimator: Current GCV {}".format(D['GCV']['lam2'][g]))
print("Estimator: Current AIC {}".format(D['AIC']['lam2'][g]))
gam_final = gam_try[D[use]['lam2'].argmin()]
lam_final_pair = (lam_final, gam_final)
if verbose:
print("Finalizing Results.")
print("Selected lam: {}".format(lam_final_pair))
print("Best {}: {}".format(use, D[use]['lam2'].min()))
# Finalize
f, t = self.Solver_ADMM(lam_final_pair, verbose - 1, solver_args)
if grid:
return f, t, D, lam_final_pair
else:
return f, t
def Estimator_Parallel_FullGrid(self, params_lam, params_gam, npool,
solver_args_dict = {}, grid = False,
use = 'GCV'):
# M by N grid search. Parallel computation over N for each m in [M].
solver_args = {'tol': 1e-3, 'max_iter': 100, 'eps': 1e-4, 'monitor': 1}
solver_args.update(solver_args_dict); eps = solver_args['eps']
# Low rank penalty
if params_lam is None:
params_lam = (-2, 2, 20)
# Sparse penalty
if params_gam is None:
params_gam = (-2, 2, 20)
lam_try = 10 ** (np.linspace(*params_lam))
gam_try = 10 ** (np.linspace(*params_gam))
D = {'GCV': np.zeros((len(lam_try), len(gam_try))),
'AIC': np.zeros((len(lam_try), len(gam_try)))}
# Deal with use
if len(use) == 4:
dof = int(use[-1])
use = use[:3]
assert dof <= 2 and dof > 0
assert use in ['GCV', 'AIC']
elif use in ['GCV', 'AIC']:
dof = 1
else:
raise ValueError()
for l in range(len(lam_try)):
pool = Pool(npool)
iteg = [((lam_try[l], g), 0, solver_args) for g in gam_try]
ft = pool.starmap(self.Solver_ADMM, iteg)
pool.terminate()
for g in range(len(gam_try)):
D['GCV'][l, g], D['AIC'][l, g] = self.GCV_Alt(ft[g][0], ft[g][1],
lam_try[l], eps, dof)
best_pos = np.unravel_index(D[use].argmin(), D[use].shape)
lam_final_pair = (lam_try[best_pos[0]], gam_try[best_pos[1]])
print("Finalizing Results.")
print("Selected lam: {}".format(lam_final_pair))
print("Best {}: {}".format(use, D[use][best_pos]))
print('-' * 30)
f, t = self.Solver_ADMM(lam_final_pair, 2, solver_args)
if grid:
return f, t, D, lam_final_pair
else:
return f, t
def Estimator_Parallel_Simplified(self, params_lam, params_gam, npool,
solver_args_dict = {}, grid = False,
use = 'GCV'):
# Offer M + N grid search.
solver_args = {'tol': 1e-3, 'max_iter': 100, 'eps': 1e-4, 'monitor': 1}
solver_args.update(solver_args_dict); eps = solver_args['eps']
# Low rank penalty
if params_lam is None:
params_lam = (-2, 2, 20)
# Sparse penalty
if params_gam is None:
params_gam = (-2, 2, 20)
lam_try = 10 ** (np.linspace(*params_lam))
gam_try = 10 ** (np.linspace(*params_gam))
nl, ng = (params_lam[2], params_gam[2])
D = {'GCV': {'lam1': np.zeros(nl), 'lam2': np.zeros(ng)},
'AIC': {'lam1': np.zeros(nl), 'lam2': np.zeros(ng)}}
# Deal with use
if len(use) == 4:
dof = int(use[-1])
use = use[:3]
assert dof <= 2 and dof > 0
assert use in ['GCV', 'AIC']
elif use in ['GCV', 'AIC']:
dof = 1
else:
raise ValueError()
# Select lambda
pool = Pool(npool)
ite1 = [((l, gam_try[0]), 0, solver_args) for l in lam_try]
ft = pool.starmap(self.Solver_ADMM, ite1)
# ite1 = [{'lam': (l, gam_try[0]), 'verbose': 0, 'args_dict': solver_args} for l in lam_try]
# ft = pool.map(self.Solver_ADMM, ite1)
pool.terminate()
for l in range(nl):
D['GCV']['lam1'][l], D['AIC']['lam1'][l] = self.GCV_Alt(ft[l][0], ft[l][1], lam_try[l], eps, dof)
lam_final = lam_try[D[use]['lam1'].argmin()] # Fixme: possible duplication
# Select gamma for lam_final
pool = Pool(npool)
ite2 = [((lam_final, g), 0, solver_args) for g in gam_try]
ft = pool.starmap(self.Solver_ADMM, ite2)
# ite2 = [{'lam': (lam_final, g), 'verbose': 0, 'args_dict': solver_args} for g in gam_try]
# ft = pool.map(self.Solver_ADMM, ite2)
pool.terminate()
for g in range(ng):
D['GCV']['lam2'][g], D['AIC']['lam2'][g] = self.GCV_Alt(ft[g][0], ft[g][1], lam_final, eps, dof)
gam_final = gam_try[D[use]['lam2'].argmin()]
lam_final_pair = (lam_final, gam_final)
# Finalize
print("Finalizing Results.")
print("Selected lam: {}".format(lam_final_pair))
print("Best {}: {}".format(use, D[use]['lam2'].min()))
print('-' * 30)
f, t = self.Solver_ADMM(lam_final_pair, 2, solver_args)
if grid:
return f, t, D, lam_final_pair
else:
return f, t
| [
"numpy.abs",
"numpy.eye",
"numpy.allclose",
"numpy.sqrt",
"numpy.linalg.eig",
"numpy.log",
"numpy.fill_diagonal",
"numpy.diag",
"numpy.count_nonzero",
"numpy.real",
"numpy.zeros",
"numpy.dot",
"numpy.linspace",
"numpy.sign",
"multiprocessing.Pool",
"numpy.linalg.norm",
"numpy.all",
... | [((1638, 1650), 'numpy.sign', 'np.sign', (['off'], {}), '(off)\n', (1645, 1650), True, 'import numpy as np\n'), ((1908, 1929), 'numpy.linalg.eig', 'np.linalg.eig', (['matrix'], {}), '(matrix)\n', (1921, 1929), True, 'import numpy as np\n'), ((2190, 2211), 'numpy.linalg.eig', 'np.linalg.eig', (['matrix'], {}), '(matrix)\n', (2203, 2211), True, 'import numpy as np\n'), ((3961, 3992), 'numpy.linalg.eig', 'np.linalg.eig', (['(self.__sigma - S)'], {}), '(self.__sigma - S)\n', (3974, 3992), True, 'import numpy as np\n'), ((4024, 4034), 'numpy.real', 'np.real', (['s'], {}), '(s)\n', (4031, 4034), True, 'import numpy as np\n'), ((4238, 4281), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.__sigma - L - S)', '"""fro"""'], {}), "(self.__sigma - L - S, 'fro')\n", (4252, 4281), True, 'import numpy as np\n'), ((5879, 5897), 'numpy.zeros', 'np.zeros', (['(_p, _p)'], {}), '((_p, _p))\n', (5887, 5897), True, 'import numpy as np\n'), ((5914, 5932), 'numpy.zeros', 'np.zeros', (['(_p, _p)'], {}), '((_p, _p))\n', (5922, 5932), True, 'import numpy as np\n'), ((6105, 6138), 'numpy.linalg.norm', 'np.linalg.norm', (['(_S - F - T)', '"""fro"""'], {}), "(_S - F - T, 'fro')\n", (6119, 6138), True, 'import numpy as np\n'), ((15399, 15410), 'multiprocessing.Pool', 'Pool', (['npool'], {}), '(npool)\n', (15403, 15410), False, 'from multiprocessing import Pool\n'), ((16014, 16025), 'multiprocessing.Pool', 'Pool', (['npool'], {}), '(npool)\n', (16018, 16025), False, 'from multiprocessing import Pool\n'), ((838, 862), 'numpy.linalg.norm', 'np.linalg.norm', (['F', '"""nuc"""'], {}), "(F, 'nuc')\n", (852, 862), True, 'import numpy as np\n'), ((1547, 1557), 'numpy.eye', 'np.eye', (['_p'], {}), '(_p)\n', (1553, 1557), True, 'import numpy as np\n'), ((1604, 1615), 'numpy.abs', 'np.abs', (['off'], {}), '(off)\n', (1610, 1615), True, 'import numpy as np\n'), ((2366, 2395), 'numpy.allclose', 'np.allclose', (['matrix', 'matrix.T'], {}), '(matrix, matrix.T)\n', (2377, 2395), True, 'import numpy as np\n'), ((2857, 2873), 'numpy.linalg.eig', 'np.linalg.eig', (['L'], {}), '(L)\n', (2870, 2873), True, 'import numpy as np\n'), ((2891, 2901), 'numpy.real', 'np.real', (['b'], {}), '(b)\n', (2898, 2901), True, 'import numpy as np\n'), ((3012, 3042), 'numpy.fill_diagonal', 'np.fill_diagonal', (['deno', 'np.inf'], {}), '(deno, np.inf)\n', (3028, 3042), True, 'import numpy as np\n'), ((3101, 3118), 'numpy.all', 'np.all', (['(deno != 0)'], {}), '(deno != 0)\n', (3107, 3118), True, 'import numpy as np\n'), ((3351, 3375), 'numpy.dot', 'np.dot', (['(1 + 2 * dof)', 'ind'], {}), '(1 + 2 * dof, ind)\n', (3357, 3375), True, 'import numpy as np\n'), ((4200, 4219), 'numpy.count_nonzero', 'np.count_nonzero', (['S'], {}), '(S)\n', (4216, 4219), True, 'import numpy as np\n'), ((4300, 4311), 'numpy.log', 'np.log', (['err'], {}), '(err)\n', (4306, 4311), True, 'import numpy as np\n'), ((8610, 8643), 'numpy.linalg.norm', 'np.linalg.norm', (['(F - F_next)', '"""fro"""'], {}), "(F - F_next, 'fro')\n", (8624, 8643), True, 'import numpy as np\n'), ((8646, 8679), 'numpy.linalg.norm', 'np.linalg.norm', (['(T - T_next)', '"""fro"""'], {}), "(T - T_next, 'fro')\n", (8660, 8679), True, 'import numpy as np\n'), ((9289, 9313), 'numpy.linspace', 'np.linspace', (['*params_lam'], {}), '(*params_lam)\n', (9300, 9313), True, 'import numpy as np\n'), ((9341, 9365), 'numpy.linspace', 'np.linspace', (['*params_gam'], {}), '(*params_gam)\n', (9352, 9365), True, 'import numpy as np\n'), ((12543, 12567), 'numpy.linspace', 'np.linspace', (['*params_lam'], {}), '(*params_lam)\n', (12554, 12567), True, 'import numpy as np\n'), ((12595, 12619), 'numpy.linspace', 'np.linspace', (['*params_gam'], {}), '(*params_gam)\n', (12606, 12619), True, 'import numpy as np\n'), ((13123, 13134), 'multiprocessing.Pool', 'Pool', (['npool'], {}), '(npool)\n', (13127, 13134), False, 'from multiprocessing import Pool\n'), ((14751, 14775), 'numpy.linspace', 'np.linspace', (['*params_lam'], {}), '(*params_lam)\n', (14762, 14775), True, 'import numpy as np\n'), ((14803, 14827), 'numpy.linspace', 'np.linspace', (['*params_gam'], {}), '(*params_gam)\n', (14814, 14827), True, 'import numpy as np\n'), ((763, 795), 'numpy.linalg.norm', 'np.linalg.norm', (['(S - F - T)', '"""fro"""'], {}), "(S - F - T, 'fro')\n", (777, 795), True, 'import numpy as np\n'), ((1090, 1121), 'numpy.linalg.norm', 'np.linalg.norm', (['(F - F_cp)', '"""fro"""'], {}), "(F - F_cp, 'fro')\n", (1104, 1121), True, 'import numpy as np\n'), ((1169, 1200), 'numpy.linalg.norm', 'np.linalg.norm', (['(T - T_cp)', '"""fro"""'], {}), "(T - T_cp, 'fro')\n", (1183, 1200), True, 'import numpy as np\n'), ((2017, 2027), 'numpy.diag', 'np.diag', (['s'], {}), '(s)\n', (2024, 2027), True, 'import numpy as np\n'), ((2436, 2446), 'numpy.real', 'np.real', (['e'], {}), '(e)\n', (2443, 2446), True, 'import numpy as np\n'), ((2468, 2478), 'numpy.real', 'np.real', (['V'], {}), '(V)\n', (2475, 2478), True, 'import numpy as np\n'), ((2691, 2701), 'numpy.diag', 'np.diag', (['e'], {}), '(e)\n', (2698, 2701), True, 'import numpy as np\n'), ((3184, 3199), 'numpy.sqrt', 'np.sqrt', (['eigens'], {}), '(eigens)\n', (3191, 3199), True, 'import numpy as np\n'), ((6453, 6474), 'numpy.linalg.eig', 'np.linalg.eig', (['last_F'], {}), '(last_F)\n', (6466, 6474), True, 'import numpy as np\n'), ((7352, 7368), 'numpy.linalg.eig', 'np.linalg.eig', (['F'], {}), '(F)\n', (7365, 7368), True, 'import numpy as np\n'), ((7395, 7428), 'numpy.linalg.norm', 'np.linalg.norm', (['(cur_e - last_e)', '(2)'], {}), '(cur_e - last_e, 2)\n', (7409, 7428), True, 'import numpy as np\n'), ((7453, 7490), 'numpy.linalg.norm', 'np.linalg.norm', (['(cur_V - last_V)', '"""fro"""'], {}), "(cur_V - last_V, 'fro')\n", (7467, 7490), True, 'import numpy as np\n'), ((7515, 7548), 'numpy.linalg.norm', 'np.linalg.norm', (['(T - last_T)', '"""fro"""'], {}), "(T - last_T, 'fro')\n", (7529, 7548), True, 'import numpy as np\n'), ((7595, 7641), 'numpy.linalg.norm', 'np.linalg.norm', (['(last_F + last_T - F - T)', '"""fro"""'], {}), "(last_F + last_T - F - T, 'fro')\n", (7609, 7641), True, 'import numpy as np\n'), ((8126, 8137), 'numpy.abs', 'np.abs', (['err'], {}), '(err)\n', (8132, 8137), True, 'import numpy as np\n'), ((9465, 9477), 'numpy.zeros', 'np.zeros', (['nl'], {}), '(nl)\n', (9473, 9477), True, 'import numpy as np\n'), ((9487, 9499), 'numpy.zeros', 'np.zeros', (['ng'], {}), '(ng)\n', (9495, 9499), True, 'import numpy as np\n'), ((9532, 9544), 'numpy.zeros', 'np.zeros', (['nl'], {}), '(nl)\n', (9540, 9544), True, 'import numpy as np\n'), ((9554, 9566), 'numpy.zeros', 'np.zeros', (['ng'], {}), '(ng)\n', (9562, 9566), True, 'import numpy as np\n'), ((14927, 14939), 'numpy.zeros', 'np.zeros', (['nl'], {}), '(nl)\n', (14935, 14939), True, 'import numpy as np\n'), ((14949, 14961), 'numpy.zeros', 'np.zeros', (['ng'], {}), '(ng)\n', (14957, 14961), True, 'import numpy as np\n'), ((14994, 15006), 'numpy.zeros', 'np.zeros', (['nl'], {}), '(nl)\n', (15002, 15006), True, 'import numpy as np\n'), ((15016, 15028), 'numpy.zeros', 'np.zeros', (['ng'], {}), '(ng)\n', (15024, 15028), True, 'import numpy as np\n'), ((622, 637), 'numpy.diag', 'np.diag', (['matrix'], {}), '(matrix)\n', (629, 637), True, 'import numpy as np\n'), ((3203, 3218), 'numpy.sqrt', 'np.sqrt', (['eigens'], {}), '(eigens)\n', (3210, 3218), True, 'import numpy as np\n'), ((5072, 5088), 'numpy.zeros_like', 'np.zeros_like', (['S'], {}), '(S)\n', (5085, 5088), True, 'import numpy as np\n'), ((7784, 7817), 'numpy.linalg.norm', 'np.linalg.norm', (['(_S - F - T)', '"""fro"""'], {}), "(_S - F - T, 'fro')\n", (7798, 7817), True, 'import numpy as np\n')] |
#================================================================================
# <NAME> [marion dot neumann at uni-bonn dot de]
# <NAME> [marthaler at ge dot com]
# <NAME> [shan dot huang at iais dot fraunhofer dot de]
# <NAME> [kristian dot kersting at cs dot tu-dortmund dot de]
#
# This file is part of pyGP_PR.
# The software package is released under the BSD 2-Clause (FreeBSD) License.
#
# Copyright (c) by
# <NAME>, <NAME>, <NAME> & <NAME>, 20/05/2013
#================================================================================
# likelihood functions are provided to be used by the gp.py function:
#
# likErf (Error function, classification, probit regression)
# likLogistic [NOT IMPLEMENTED!] (Logistic, classification, logit regression)
# likUni [NOT IMPLEMENTED!] (Uniform likelihood, classification)
#
# likGauss (Gaussian, regression)
# likLaplace [NOT IMPLEMENTED!] (Laplacian or double exponential, regression)
# likSech2 [NOT IMPLEMENTED!] (Sech-square, regression)
# likT [NOT IMPLEMENTED!] (Student's t, regression)
#
# likPoisson [NOT IMPLEMENTED!] (Poisson regression, count data)
#
# likMix [NOT IMPLEMENTED!] (Mixture of individual covariance functions)
#
# The likelihood functions have three possible modes, the mode being selected
# as follows (where "lik" stands for any likelihood function defined as lik*):
#
# 1) With one or no input arguments: [REPORT NUMBER OF HYPERPARAMETERS]
#
# s = lik OR s = lik(hyp)
#
# The likelihood function returns a string telling how many hyperparameters it
# expects, using the convention that "D" is the dimension of the input space.
# For example, calling "likLogistic" returns the string '0'.
#
#
# 2) With three or four input arguments: [PREDICTION MODE]
#
# lp = lik(hyp, y, mu) OR [lp, ymu, ys2] = lik(hyp, y, mu, s2)
#
# This allows to evaluate the predictive distribution. Let p(y_*|f_*) be the
# likelihood of a test point and N(f_*|mu,s2) an approximation to the posterior
# marginal p(f_*|x_*,x,y) as returned by an inference method. The predictive
# distribution p(y_*|x_*,x,y) is approximated by.
# q(y_*) = \int N(f_*|mu,s2) p(y_*|f_*) df_*
#
# lp = log( q(y) ) for a particular value of y, if s2 is [] or 0, this
# corresponds to log( p(y|mu) )
# ymu and ys2 the mean and variance of the predictive marginal q(y)
# note that these two numbers do not depend on a particular
# value of y
# All vectors have the same size.
#
#
# 3) With five or six input arguments, the fifth being a string [INFERENCE MODE]
#
# [varargout] = lik(hyp, y, mu, s2, inf) OR
# [varargout] = lik(hyp, y, mu, s2, inf, i)
#
# There are three cases for inf, namely a) infLaplace, b) infEP and c) infVB.
# The last input i, refers to derivatives w.r.t. the ith hyperparameter.
#
# a1) [lp,dlp,d2lp,d3lp] = lik(hyp, y, f, [], 'infLaplace')
# lp, dlp, d2lp and d3lp correspond to derivatives of the log likelihood
# log(p(y|f)) w.r.t. to the latent location f.
# lp = log( p(y|f) )
# dlp = d log( p(y|f) ) / df
# d2lp = d^2 log( p(y|f) ) / df^2
# d3lp = d^3 log( p(y|f) ) / df^3
#
# a2) [lp_dhyp,dlp_dhyp,d2lp_dhyp] = lik(hyp, y, f, [], 'infLaplace', i)
# returns derivatives w.r.t. to the ith hyperparameter
# lp_dhyp = d log( p(y|f) ) / ( dhyp_i)
# dlp_dhyp = d^2 log( p(y|f) ) / (df dhyp_i)
# d2lp_dhyp = d^3 log( p(y|f) ) / (df^2 dhyp_i)
#
#
# b1) [lZ,dlZ,d2lZ] = lik(hyp, y, mu, s2, 'infEP')
# let Z = \int p(y|f) N(f|mu,s2) df then
# lZ = log(Z)
# dlZ = d log(Z) / dmu
# d2lZ = d^2 log(Z) / dmu^2
#
# b2) [dlZhyp] = lik(hyp, y, mu, s2, 'infEP', i)
# returns derivatives w.r.t. to the ith hyperparameter
# dlZhyp = d log(Z) / dhyp_i
#
#
# c1) [h,b,dh,db,d2h,d2b] = lik(hyp, y, [], ga, 'infVB')
# ga is the variance of a Gaussian lower bound to the likelihood p(y|f).
# p(y|f) \ge exp( b*f - f.^2/(2*ga) - h(ga)/2 ) \propto N(f|b*ga,ga)
# The function returns the linear part b and the "scaling function" h(ga) and derivatives
# dh = d h/dga
# db = d b/dga
# d2h = d^2 h/dga
# d2b = d^2 b/dga
#
# c2) [dhhyp] = lik(hyp, y, [], ga, 'infVB', i)
# dhhyp = dh / dhyp_i, the derivative w.r.t. the ith hyperparameter
#
# Cumulative likelihoods are designed for binary classification. Therefore, they
# only look at the sign of the targets y; zero values are treated as +1.
#
# See the documentation for the individual likelihood for the computations specific
# to each likelihood function.
#
# @author: <NAME> (Fall 2012)
# Substantial updates by Shan Huang (Sep. 2013)
#
# This is a python implementation of gpml functionality (Copyright (c) by
# <NAME> and <NAME>, 2013-01-21).
#
# Copyright (c) by <NAME> and <NAME>, 20/05/2013
import numpy as np
from scipy.special import erf
import src.Tools.general
def likErf(hyp=None, y=None, mu=None, s2=None, inffunc=None, der=None, nargout=None):
''' likErf - Error function or cumulative Gaussian likelihood function for binary
classification or probit regression. The expression for the likelihood is
likErf(t) = (1+erf(t/sqrt(2)))/2 = normcdf(t).
Several modes are provided, for computing likelihoods, derivatives and moments
respectively, see lik.py for the details. In general, care is taken
to avoid numerical issues when the arguments are extreme.
'''
if mu == None:
return [0] # report number of hyperparameters
if not y == None:
y = np.sign(y)
y[y==0] = 1
else:
y = 1; # allow only +/- 1 values
if inffunc == None: # prediction mode if inf is not present
y = y*np.ones_like(mu) # make y a vector
s2zero = True;
if not s2 == None:
if np.linalg.norm(s2)>0:
s2zero = False # s2==0 ?
if s2zero: # log probability evaluation
[p,lp] = _cumGauss(y,mu,2)
else: # prediction
lp = src.Tools.general.feval(['likelihoods.likErf'],hyp, y, mu, s2, 'inferences.infEP',None,1)
p = np.exp(lp)
if nargout>1:
ymu = 2*p-1 # first y moment
if nargout>2:
ys2 = 4*p*(1-p) # second y moment
varargout = [lp,ymu,ys2]
else:
varargout = [lp,ymu]
else:
varargout = lp
else: # inference mode
if inffunc == 'inferences.infLaplace':
if der == None: # no derivative mode
f = mu; yf = y*f # product latents and labels
[p,lp] = _cumGauss(y,f,2)
if nargout>1: # derivative of log likelihood
n_p = _gauOverCumGauss(yf,p)
dlp = y*n_p # derivative of log likelihood
if nargout>2: # 2nd derivative of log likelihood
d2lp = -n_p**2 - yf*n_p
if nargout>3: # 3rd derivative of log likelihood
d3lp = 2*y*n_p**3 + 3*f*n_p**2 + y*(f**2-1)*n_p
varargout = [lp,dlp,d2lp,d3lp]
else:
varargout = [lp,dlp,d2lp]
else:
varargout = [lp,dlp]
else:
varargout = lp
else: # derivative mode
varargout = nargout*[] # derivative w.r.t. hypers
if inffunc == 'inferences.infEP':
if der == None: # no derivative mode
z = mu/np.sqrt(1+s2)
[junk,lZ] = _cumGauss(y,z,2) # log part function
if not y == None:
z = z*y
if nargout>1:
if y == None:
y = 1
n_p = _gauOverCumGauss(z,np.exp(lZ))
dlZ = y*n_p/np.sqrt(1.+s2) # 1st derivative wrt mean
if nargout>2:
d2lZ = -n_p*(z+n_p)/(1.+s2) # 2nd derivative wrt mean
varargout = [lZ,dlZ,d2lZ]
else:
varargout = [lZ,dlZ]
else:
varargout = lZ
else: # derivative mode
varargout = 0 # deriv. wrt hyp.lik
#end
if inffunc == 'inferences.infVB':
if der == None: # no derivative mode
# naive variational lower bound based on asymptotical properties of lik
# normcdf(t) -> -(t*A_hat^2-2dt+c)/2 for t->-np.inf (tight lower bound)
d = 0.158482605320942;
c = -1.785873318175113;
ga = s2; n = len(ga); b = d*y*np.ones((n,1)); db = np.zeros((n,1)); d2b = db
h = -2.*c*np.ones((n,1)); h[ga>1] = np.inf; dh = np.zeros((n,1)); d2h = dh
varargout = [h,b,dh,db,d2h,d2b]
else: # derivative mode
varargout = [] # deriv. wrt hyp.lik
return varargout
def _cumGauss(y=None,f=None,nargout=1):
''' Safe implementation of the log of phi(x) = \int_{-\infty}^x N(f|0,1) df
_logphi(z) = log(normcdf(z))
'''
if not y == None:
yf = y*f
else:
yf = f
# product of latents and labels
p = (1. + erf(yf/np.sqrt(2.)))/2. # likelihood
if nargout>1:
lp = _logphi(yf,p)
return p,lp
else:
return p
def _logphi(z,p):
lp = np.zeros_like(z) # initialize
zmin = -6.2; zmax = -5.5;
ok = z>zmax # safe evaluation for large values
bd = z<zmin # use asymptotics
nok = np.logical_not(ok)
ip = np.logical_and(nok,np.logical_not(bd)) # interpolate between both of them
lam = 1/(1.+np.exp( 25.*(0.5-(z[ip]-zmin)/(zmax-zmin)) )) # interp. weights
lp[ok] = np.log(p[ok])
# use lower and upper bound acoording to Abramowitz&Stegun 7.1.13 for z<0
# lower -log(pi)/2 -z.^2/2 -log( sqrt(z.^2/2+2 ) -z/sqrt(2) )
# upper -log(pi)/2 -z.^2/2 -log( sqrt(z.^2/2+4/pi) -z/sqrt(2) )
# the lower bound captures the asymptotics
lp[nok] = -np.log(np.pi)/2. -z[nok]**2/2. - np.log( np.sqrt(z[nok]**2/2.+2.) - z[nok]/np.sqrt(2.) )
lp[ip] = (1-lam)*lp[ip] + lam*np.log( p[ip] )
return lp
def _gauOverCumGauss(f,p):
n_p = np.zeros_like(f) # safely compute Gaussian over cumulative Gaussian
ok = f>-5 # naive evaluation for large values of f
n_p[ok] = (np.exp(-f[ok]**2/2)/np.sqrt(2*np.pi)) / p[ok]
bd = f<-6 # tight upper bound evaluation
n_p[bd] = np.sqrt(f[bd]**2/4+1)-f[bd]/2
interp = np.logical_and(np.logical_not(ok),np.logical_not(bd)) # linearly interpolate between both of them
tmp = f[interp]
lam = -5. - f[interp]
n_p[interp] = (1-lam)*(np.exp(-tmp**2/2)/np.sqrt(2*np.pi))/p[interp] + \
lam *(np.sqrt(tmp**2/4+1)-tmp/2);
return n_p
def likGauss(hyp=None, y=None, mu=None, s2=None, inffunc=None, der=None, nargout=1):
''' likGauss - Gaussian likelihood function for regression. The expression for the likelihood is
likGauss(t) = exp(-(t-y)^2/2*sn^2) / sqrt(2*pi*sn^2),
where y is the mean and sn is the standard deviation.
The hyperparameters are:
hyp = [ log(sn) ]
Several modes are provided, for computing likelihoods, derivatives and moments
respectively, see lik.py for the details. In general, care is taken
to avoid numerical issues when the arguments are extreme.
'''
if mu == None:
return [1] # report number of hyperparameters
sn2 = np.exp(2.*hyp)
if inffunc == None: # prediction mode if inffunc is not present
if y == None:
y = np.zeros_like(mu)
s2zero = True
if not (s2 == None):
if np.linalg.norm(s2) > 0:
s2zero = False
if s2zero: # s2==0 ?
lp = -(y-mu)**2 /sn2/2 - np.log(2.*np.pi*sn2)/2. # log probability
s2 = 0.
else:
lp = src.Tools.general.feval(['likelihoods.likGauss'],hyp, y, mu, s2, 'inferences.infEP',None,1) # prediction
if nargout>1:
ymu = mu; # first y moment
if nargout>2:
ys2 = s2 + sn2; # second y moment
varargout = [lp,ymu,ys2]
else:
varargout = [lp,ymu]
else:
varargout = lp
else:
if inffunc == 'inferences.infLaplace':
if der == None: # no derivative mode
if y == None: y=0 #end
ymmu = y-mu
lp = -ymmu**2/(2*sn2) - np.log(2*np.pi*sn2)/2.
if nargout>1:
dlp = ymmu/sn2 # dlp, derivative of log likelihood
if nargout>2: # d2lp, 2nd derivative of log likelihood
d2lp = -np.ones_like(ymmu)/sn2
if nargout>3: # d3lp, 3rd derivative of log likelihood
d3lp = np.zeros_like(ymmu)
varargout = [lp,dlp,d2lp,d3lp]
else:
varargout = [lp,dlp,d2lp]
else:
varargout = [lp,dlp]
else:
varargout = lp
else: # derivative mode
lp_dhyp = (y-mu)**2/sn2 - 1 # derivative of log likelihood w.r.t. hypers
dlp_dhyp = 2*(mu-y)/sn2 # first derivative,
d2lp_dhyp = 2*np.ones_like(mu)/sn2 # and also of the second mu derivative
varargout = [lp_dhyp,dlp_dhyp,d2lp_dhyp]
elif inffunc == 'inferences.infEP':
if der == None: # no derivative mode
lZ = -(y-mu)**2/(sn2+s2)/2. - np.log(2*np.pi*(sn2+s2))/2. # log part function
if nargout>1:
dlZ = (y-mu)/(sn2+s2) # 1st derivative w.r.t. mean
if nargout>2:
d2lZ = -1/(sn2+s2) # 2nd derivative w.r.t. mean
varargout = [lZ,dlZ,d2lZ]
else:
varargout = [lZ,dlZ]
else:
varargout = lZ
else: # derivative mode
dlZhyp = ((y-mu)**2/(sn2+s2)-1) / (1+s2/sn2) # deriv. w.r.t. hyp.lik
varargout = dlZhyp
elif inffunc == 'inferences.infVB':
if der == None:
# variational lower site bound
# t(s) = exp(-(y-s)^2/2sn2)/sqrt(2*pi*sn2)
# the bound has the form: b*s - s.^2/(2*ga) - h(ga)/2 with b=y/ga
ga = s2; n = len(ga); b = y/ga; y = y*np.ones((n,1))
db = -y/ga**2
d2b = 2*y/ga**3
h = np.zeros((n,1)); dh = h; d2h = h # allocate memory for return args
id = (ga <= sn2 + 1e-8) # OK below noise variance
h[id] = y[id]**2/ga[id] + np.log(2*np.pi*sn2); h[np.logical_not(id)] = np.inf
dh[id] = -y[id]**2/ga[id]**2
d2h[id] = 2*y[id]**2/ga[id]**3
id = ga < 0; h[id] = np.inf; dh[id] = 0; d2h[id] = 0 # neg. var. treatment
varargout = [h,b,dh,db,d2h,d2b]
else:
ga = s2; n = len(ga);
dhhyp = np.zeros((n,1)); dhhyp[ga<=sn2] = 2
dhhyp[ga<0] = 0 # negative variances get a special treatment
varargout = dhhyp # deriv. w.r.t. hyp.lik
else:
raise Exception('Incorrect inference in lik.Gauss\n');
return varargout
| [
"numpy.ones_like",
"numpy.sqrt",
"numpy.ones",
"numpy.log",
"numpy.logical_not",
"numpy.exp",
"numpy.zeros",
"numpy.sign",
"numpy.linalg.norm",
"numpy.zeros_like"
] | [((10717, 10733), 'numpy.zeros_like', 'np.zeros_like', (['z'], {}), '(z)\n', (10730, 10733), True, 'import numpy as np\n'), ((11006, 11024), 'numpy.logical_not', 'np.logical_not', (['ok'], {}), '(ok)\n', (11020, 11024), True, 'import numpy as np\n'), ((11219, 11232), 'numpy.log', 'np.log', (['p[ok]'], {}), '(p[ok])\n', (11225, 11232), True, 'import numpy as np\n'), ((11702, 11718), 'numpy.zeros_like', 'np.zeros_like', (['f'], {}), '(f)\n', (11715, 11718), True, 'import numpy as np\n'), ((13207, 13224), 'numpy.exp', 'np.exp', (['(2.0 * hyp)'], {}), '(2.0 * hyp)\n', (13213, 13224), True, 'import numpy as np\n'), ((5802, 5812), 'numpy.sign', 'np.sign', (['y'], {}), '(y)\n', (5809, 5812), True, 'import numpy as np\n'), ((11053, 11071), 'numpy.logical_not', 'np.logical_not', (['bd'], {}), '(bd)\n', (11067, 11071), True, 'import numpy as np\n'), ((12096, 12123), 'numpy.sqrt', 'np.sqrt', (['(f[bd] ** 2 / 4 + 1)'], {}), '(f[bd] ** 2 / 4 + 1)\n', (12103, 12123), True, 'import numpy as np\n'), ((12155, 12173), 'numpy.logical_not', 'np.logical_not', (['ok'], {}), '(ok)\n', (12169, 12173), True, 'import numpy as np\n'), ((12174, 12192), 'numpy.logical_not', 'np.logical_not', (['bd'], {}), '(bd)\n', (12188, 12192), True, 'import numpy as np\n'), ((6052, 6068), 'numpy.ones_like', 'np.ones_like', (['mu'], {}), '(mu)\n', (6064, 6068), True, 'import numpy as np\n'), ((6625, 6635), 'numpy.exp', 'np.exp', (['lp'], {}), '(lp)\n', (6631, 6635), True, 'import numpy as np\n'), ((11140, 11193), 'numpy.exp', 'np.exp', (['(25.0 * (0.5 - (z[ip] - zmin) / (zmax - zmin)))'], {}), '(25.0 * (0.5 - (z[ip] - zmin) / (zmax - zmin)))\n', (11146, 11193), True, 'import numpy as np\n'), ((11632, 11645), 'numpy.log', 'np.log', (['p[ip]'], {}), '(p[ip])\n', (11638, 11645), True, 'import numpy as np\n'), ((11935, 11958), 'numpy.exp', 'np.exp', (['(-f[ok] ** 2 / 2)'], {}), '(-f[ok] ** 2 / 2)\n', (11941, 11958), True, 'import numpy as np\n'), ((11955, 11973), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (11962, 11973), True, 'import numpy as np\n'), ((13369, 13386), 'numpy.zeros_like', 'np.zeros_like', (['mu'], {}), '(mu)\n', (13382, 13386), True, 'import numpy as np\n'), ((6187, 6205), 'numpy.linalg.norm', 'np.linalg.norm', (['s2'], {}), '(s2)\n', (6201, 6205), True, 'import numpy as np\n'), ((9835, 9851), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (9843, 9851), True, 'import numpy as np\n'), ((9926, 9942), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (9934, 9942), True, 'import numpy as np\n'), ((11550, 11582), 'numpy.sqrt', 'np.sqrt', (['(z[nok] ** 2 / 2.0 + 2.0)'], {}), '(z[nok] ** 2 / 2.0 + 2.0)\n', (11557, 11582), True, 'import numpy as np\n'), ((12417, 12442), 'numpy.sqrt', 'np.sqrt', (['(tmp ** 2 / 4 + 1)'], {}), '(tmp ** 2 / 4 + 1)\n', (12424, 12442), True, 'import numpy as np\n'), ((13462, 13480), 'numpy.linalg.norm', 'np.linalg.norm', (['s2'], {}), '(s2)\n', (13476, 13480), True, 'import numpy as np\n'), ((8491, 8506), 'numpy.sqrt', 'np.sqrt', (['(1 + s2)'], {}), '(1 + s2)\n', (8498, 8506), True, 'import numpy as np\n'), ((9814, 9829), 'numpy.ones', 'np.ones', (['(n, 1)'], {}), '((n, 1))\n', (9821, 9829), True, 'import numpy as np\n'), ((9887, 9902), 'numpy.ones', 'np.ones', (['(n, 1)'], {}), '((n, 1))\n', (9894, 9902), True, 'import numpy as np\n'), ((10540, 10552), 'numpy.sqrt', 'np.sqrt', (['(2.0)'], {}), '(2.0)\n', (10547, 10552), True, 'import numpy as np\n'), ((11509, 11522), 'numpy.log', 'np.log', (['np.pi'], {}), '(np.pi)\n', (11515, 11522), True, 'import numpy as np\n'), ((11584, 11596), 'numpy.sqrt', 'np.sqrt', (['(2.0)'], {}), '(2.0)\n', (11591, 11596), True, 'import numpy as np\n'), ((12312, 12333), 'numpy.exp', 'np.exp', (['(-tmp ** 2 / 2)'], {}), '(-tmp ** 2 / 2)\n', (12318, 12333), True, 'import numpy as np\n'), ((12330, 12348), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (12337, 12348), True, 'import numpy as np\n'), ((13682, 13707), 'numpy.log', 'np.log', (['(2.0 * np.pi * sn2)'], {}), '(2.0 * np.pi * sn2)\n', (13688, 13707), True, 'import numpy as np\n'), ((8794, 8804), 'numpy.exp', 'np.exp', (['lZ'], {}), '(lZ)\n', (8800, 8804), True, 'import numpy as np\n'), ((8838, 8855), 'numpy.sqrt', 'np.sqrt', (['(1.0 + s2)'], {}), '(1.0 + s2)\n', (8845, 8855), True, 'import numpy as np\n'), ((14499, 14522), 'numpy.log', 'np.log', (['(2 * np.pi * sn2)'], {}), '(2 * np.pi * sn2)\n', (14505, 14522), True, 'import numpy as np\n'), ((15537, 15553), 'numpy.ones_like', 'np.ones_like', (['mu'], {}), '(mu)\n', (15549, 15553), True, 'import numpy as np\n'), ((17026, 17042), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (17034, 17042), True, 'import numpy as np\n'), ((17631, 17647), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (17639, 17647), True, 'import numpy as np\n'), ((14953, 14972), 'numpy.zeros_like', 'np.zeros_like', (['ymmu'], {}), '(ymmu)\n', (14966, 14972), True, 'import numpy as np\n'), ((15864, 15894), 'numpy.log', 'np.log', (['(2 * np.pi * (sn2 + s2))'], {}), '(2 * np.pi * (sn2 + s2))\n', (15870, 15894), True, 'import numpy as np\n'), ((16924, 16939), 'numpy.ones', 'np.ones', (['(n, 1)'], {}), '((n, 1))\n', (16931, 16939), True, 'import numpy as np\n'), ((17259, 17282), 'numpy.log', 'np.log', (['(2 * np.pi * sn2)'], {}), '(2 * np.pi * sn2)\n', (17265, 17282), True, 'import numpy as np\n'), ((17282, 17300), 'numpy.logical_not', 'np.logical_not', (['id'], {}), '(id)\n', (17296, 17300), True, 'import numpy as np\n'), ((14790, 14808), 'numpy.ones_like', 'np.ones_like', (['ymmu'], {}), '(ymmu)\n', (14802, 14808), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Provides simple functions for reading in TSP problems from known test problems.
Text file format from TSPLib: https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/
Requires knowledge about the volumne of meta_data.
Slight issue - numpy.loadtxt does not like EOF. This is what is in the tsp files
my workaround is to delete EOF from the file!!
"""
import numpy as np
def read_coordinates(file_path, md_rows):
"""
Return numpy array of city coordinates.
Excludes meta data (first 6 rows) and first column (city number)
"""
return np.loadtxt(file_path, skiprows = md_rows, usecols = (1,2))
def read_meta_data(file_path, md_rows):
"""
Returns meta dat/paraetmers a from specified tsp file
"""
with open(file_path) as tspfile:
return [next(tspfile).rstrip('\n') for x in range(md_rows - 1)]
| [
"numpy.loadtxt"
] | [((610, 665), 'numpy.loadtxt', 'np.loadtxt', (['file_path'], {'skiprows': 'md_rows', 'usecols': '(1, 2)'}), '(file_path, skiprows=md_rows, usecols=(1, 2))\n', (620, 665), True, 'import numpy as np\n')] |
import os
import numpy as np
import pandas as pd
from hyperactive import Hyperactive
from hyperactive.dashboards import ProgressBoard
from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend
from hyperactive.dashboards.progress_board.progress_io import ProgressIO
def test_progress_io_0():
search_id = "test_model"
_io_ = ProgressIO("./")
_io_.get_filter_file_path(search_id)
def test_progress_io_1():
search_id = "test_model"
_io_ = ProgressIO("./")
_io_.get_progress_data_path(search_id)
def test_progress_io_2():
search_id = "test_model"
_io_ = ProgressIO("./")
_io_.remove_filter(search_id)
filter_ = _io_.load_filter(search_id)
assert filter_ is None
def test_progress_io_3():
search_id = "test_model"
_io_ = ProgressIO("./")
_io_.remove_progress(search_id)
progress_ = _io_.load_progress(search_id)
assert progress_ is None
def test_progress_io_4():
search_id = "test_model"
search_space = {
"x1": np.arange(-100, 101, 1),
}
_io_ = ProgressIO("./")
_io_.remove_progress(search_id)
_io_.create_filter(search_id, search_space)
progress_ = _io_.load_filter(search_id)
assert progress_ is not None
def test_filter_data_0():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
def objective_function(opt):
score = -opt["x1"] * opt["x1"]
return score
search_space = {
"x1": np.arange(-100, 101, 1),
}
hyper = Hyperactive()
hyper.add_search(objective_function, search_space, n_iter=200)
hyper.run()
search_data = hyper.results(objective_function)
indices = list(search_space.keys()) + ["score"]
filter_dict = {
"parameter": indices,
"lower bound": "---",
"upper bound": "---",
}
filter_df = pd.DataFrame(filter_dict)
threshold = -1000
filter_df["lower bound"].iloc[1] = threshold
board = StreamlitBackend(search_ids)
progress_data = board.filter_data(search_data, filter_df)
assert not np.all(search_data["score"].values >= threshold)
assert np.all(progress_data["score"].values >= threshold)
def test_streamlit_backend_0():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
board = StreamlitBackend(search_ids)
progress_data = board.get_progress_data(search_id1)
assert progress_data is None
def test_streamlit_backend_1():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
board = StreamlitBackend(search_ids)
def objective_function(opt):
score = -opt["x1"] * opt["x1"]
return score
search_space = {
"x1": np.arange(-100, 101, 1),
}
hyper = Hyperactive()
hyper.add_search(objective_function, search_space, n_iter=200)
hyper.run()
search_data = hyper.results(objective_function)
search_data["nth_iter"] = 0
search_data["score_best"] = 0
search_data["nth_process"] = 0
pyplot_fig = board.pyplot(search_data)
assert pyplot_fig is not None
def test_streamlit_backend_2():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
board = StreamlitBackend(search_ids)
def objective_function(opt):
score = -opt["x1"] * opt["x1"]
return score
search_space = {
"x1": np.arange(-100, 101, 1),
}
hyper = Hyperactive()
hyper.add_search(objective_function, search_space, n_iter=200)
hyper.run()
search_data = hyper.results(objective_function)
search_data["nth_iter"] = 0
search_data["score_best"] = 0
search_data["nth_process"] = 0
search_data["best"] = 0
plotly_fig = board.plotly(search_data, search_id1)
assert plotly_fig is not None
def test_streamlit_backend_3():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
board = StreamlitBackend(search_ids)
df_empty = pd.DataFrame()
board.pyplot(df_empty)
def test_streamlit_backend_4():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
board = StreamlitBackend(search_ids)
df_empty = pd.DataFrame([], columns=["nth_iter", "score_best", "nth_process"])
board.pyplot(df_empty)
def test_streamlit_backend_5():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
board = StreamlitBackend(search_ids)
df_empty = pd.DataFrame()
board.plotly(df_empty, search_id1)
def test_streamlit_backend_6():
search_id1 = "test_model1"
search_id2 = "test_model2"
search_id3 = "test_model3"
search_ids = [search_id1, search_id2, search_id3]
board = StreamlitBackend(search_ids)
df_empty = pd.DataFrame([], columns=["nth_iter", "score_best", "nth_process"])
board.plotly(df_empty, search_id1)
| [
"hyperactive.dashboards.progress_board.progress_io.ProgressIO",
"hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend",
"pandas.DataFrame",
"numpy.all",
"numpy.arange",
"hyperactive.Hyperactive"
] | [((361, 377), 'hyperactive.dashboards.progress_board.progress_io.ProgressIO', 'ProgressIO', (['"""./"""'], {}), "('./')\n", (371, 377), False, 'from hyperactive.dashboards.progress_board.progress_io import ProgressIO\n'), ((488, 504), 'hyperactive.dashboards.progress_board.progress_io.ProgressIO', 'ProgressIO', (['"""./"""'], {}), "('./')\n", (498, 504), False, 'from hyperactive.dashboards.progress_board.progress_io import ProgressIO\n'), ((617, 633), 'hyperactive.dashboards.progress_board.progress_io.ProgressIO', 'ProgressIO', (['"""./"""'], {}), "('./')\n", (627, 633), False, 'from hyperactive.dashboards.progress_board.progress_io import ProgressIO\n'), ((807, 823), 'hyperactive.dashboards.progress_board.progress_io.ProgressIO', 'ProgressIO', (['"""./"""'], {}), "('./')\n", (817, 823), False, 'from hyperactive.dashboards.progress_board.progress_io import ProgressIO\n'), ((1072, 1088), 'hyperactive.dashboards.progress_board.progress_io.ProgressIO', 'ProgressIO', (['"""./"""'], {}), "('./')\n", (1082, 1088), False, 'from hyperactive.dashboards.progress_board.progress_io import ProgressIO\n'), ((1601, 1614), 'hyperactive.Hyperactive', 'Hyperactive', ([], {}), '()\n', (1612, 1614), False, 'from hyperactive import Hyperactive\n'), ((1935, 1960), 'pandas.DataFrame', 'pd.DataFrame', (['filter_dict'], {}), '(filter_dict)\n', (1947, 1960), True, 'import pandas as pd\n'), ((2045, 2073), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (2061, 2073), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((2212, 2262), 'numpy.all', 'np.all', (["(progress_data['score'].values >= threshold)"], {}), "(progress_data['score'].values >= threshold)\n", (2218, 2262), True, 'import numpy as np\n'), ((2458, 2486), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (2474, 2486), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((2772, 2800), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (2788, 2800), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((2975, 2988), 'hyperactive.Hyperactive', 'Hyperactive', ([], {}), '()\n', (2986, 2988), False, 'from hyperactive import Hyperactive\n'), ((3499, 3527), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (3515, 3527), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((3702, 3715), 'hyperactive.Hyperactive', 'Hyperactive', ([], {}), '()\n', (3713, 3715), False, 'from hyperactive import Hyperactive\n'), ((4266, 4294), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (4282, 4294), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((4311, 4325), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4323, 4325), True, 'import pandas as pd\n'), ((4549, 4577), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (4565, 4577), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((4594, 4661), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {'columns': "['nth_iter', 'score_best', 'nth_process']"}), "([], columns=['nth_iter', 'score_best', 'nth_process'])\n", (4606, 4661), True, 'import pandas as pd\n'), ((4885, 4913), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (4901, 4913), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((4930, 4944), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4942, 4944), True, 'import pandas as pd\n'), ((5180, 5208), 'hyperactive.dashboards.progress_board.streamlit_backend.StreamlitBackend', 'StreamlitBackend', (['search_ids'], {}), '(search_ids)\n', (5196, 5208), False, 'from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend\n'), ((5225, 5292), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {'columns': "['nth_iter', 'score_best', 'nth_process']"}), "([], columns=['nth_iter', 'score_best', 'nth_process'])\n", (5237, 5292), True, 'import pandas as pd\n'), ((1029, 1052), 'numpy.arange', 'np.arange', (['(-100)', '(101)', '(1)'], {}), '(-100, 101, 1)\n', (1038, 1052), True, 'import numpy as np\n'), ((1557, 1580), 'numpy.arange', 'np.arange', (['(-100)', '(101)', '(1)'], {}), '(-100, 101, 1)\n', (1566, 1580), True, 'import numpy as np\n'), ((2152, 2200), 'numpy.all', 'np.all', (["(search_data['score'].values >= threshold)"], {}), "(search_data['score'].values >= threshold)\n", (2158, 2200), True, 'import numpy as np\n'), ((2931, 2954), 'numpy.arange', 'np.arange', (['(-100)', '(101)', '(1)'], {}), '(-100, 101, 1)\n', (2940, 2954), True, 'import numpy as np\n'), ((3658, 3681), 'numpy.arange', 'np.arange', (['(-100)', '(101)', '(1)'], {}), '(-100, 101, 1)\n', (3667, 3681), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 19:51:51 2020
@author: Philipe_Leal
"""
import pandas as pd
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import os, sys
import matplotlib.ticker as mticker
pd.set_option('display.max_rows', 5000)
pd.set_option('display.max_columns', 5000)
import xarray as xr
def get_k_nearest_values_from_vector(arr, k):
idx = np.argsort(arr)
if k<0:
return arr, idx
if k>0:
return arr[idx[:k]], idx
def apply_kernel_over_distance_array(dd, p):
dd = dd**(-p) # dd = weight = 1.0 / (dd**power)
dd = dd/np.sum(dd) # normalized weights
return dd
def get_interpolatedValue(xd,yd,Vd, xpp,ypp, p,smoothing, k=4):
dx = xpp - xd; dy = ypp - yd
dd = np.sqrt(dx**p + dy**p + smoothing**p) # distance
dd = np.where(np.abs(dd) <10**(-3), 10**(-3), dd) # limit too small distances
dd_Nearest, idx = get_k_nearest_values_from_vector(dd, k) # getting k nearest
dd_Nearest = apply_kernel_over_distance_array(dd_Nearest, p)
Vd[np.isnan(Vd)] = 0 # Setting nans to zero
if k>0:
K_nearest_Values = Vd[idx[:k]]
else:
K_nearest_Values = Vd
print('dd_Nearest shape', dd_Nearest.shape)
print('K_nearest_Values shape', K_nearest_Values.shape)
Vi = np.dot(dd_Nearest,K_nearest_Values) # interpolated value = scalar product <weight, value>
return Vi
def interpolateDistInvers(xd,yd,Vd, xp,yp, power,smoothing, k):
nx = len(xp)
VI = np.zeros_like(xp) # initialize the output with zero
for i in range(nx): # run through the output grid
VI[i] = get_interpolatedValue(xd,yd,Vd, xp[i],yp[i], power, smoothing, k)
return VI.T
def run_InvDist_interpolation(output_grid,
input_grid,
input_grid_values,
power=2.0,
smoothing=0.1,
k=4):
xp, yp = output_grid.T
xs, ys = input_grid.T
#---- run through the grid and get the interpolated value at each point
Vp = interpolateDistInvers(xs,ys,input_grid_values, xp,yp, power,smoothing, k)
return Vp
def xr_to_2D_array(da, xcor='xc', ycor='yc'):
data = da.data.ravel()
xcor = da.coords[xcor].data.ravel()
ycor = da.coords[ycor].data.ravel()
print(xcor.shape, ycor.shape, data.shape)
input_grid = np.stack([xcor, ycor], axis=1)
return input_grid, data
def create_output_grid(xmin, xmax, xres, ymin, ymax, yres):
Xcoords = np.arange(xmin,xmax, xres)
Ycoords = np.arange(ymin, ymax, yres)
xgrid, ygrid = [x.ravel() for x in np.meshgrid(Xcoords, Ycoords)]
output_grid = np.stack([xgrid, ygrid], axis=1)
output_shape = (Xcoords.size, Ycoords.size)
return output_grid, output_shape, Xcoords, Ycoords
def get_coord_limits_from_dataarray(da, xcor='xc', ycor='yc'):
xmin = float(da.coords[xcor].min())
xmax = float(da.coords[xcor].max())
ymin = float(da.coords[ycor].min())
ymax = float(da.coords[ycor].max())
return xmin, xmax, ymin, ymax
def rebuild_dataarray(arr, xcoor, ycoor, xdim, ydim):
return xr.DataArray(arr.T,
coords={ydim:ycoor,
xdim:xcoor},
dims=[ydim,
xdim])
def plot_dataArray(arr, transform=ccrs.PlateCarree(), x='lon', y='lat', figsup=None):
fig, ax = plt.subplots(subplot_kw={'projection':ccrs.PlateCarree()})
arr.plot(ax=ax, transform=transform,
x=x, y=y,
add_colorbar=True)
ax.gridlines(draw_labels=True)
ax.coastlines()
fig.suptitle(figsup)
fig.show()
if '__main__' == __name__:
ds = xr.tutorial.open_dataset('rasm').load()
Tair = ds['Tair']
Tair_T1 = Tair.isel(time=0)
input_grid, input_grid_values = xr_to_2D_array(Tair_T1)
xres = 5
yres = 5
K = 100
xmin, xmax, ymin, ymax = get_coord_limits_from_dataarray(Tair_T1)
output_grid, output_shape, Xcoords, Ycoords = create_output_grid(xmin, xmax, xres, ymin, ymax, yres)
Interp_IDW = run_InvDist_interpolation(output_grid,
input_grid,
input_grid_values,
power=2.0,
smoothing=0.1, k=K)
Interp_IDW = Interp_IDW.reshape(output_shape)
dataArray_interpolated = rebuild_dataarray(Interp_IDW,
Xcoords,
Ycoords,
xdim='lon',
ydim='lat')
plot_dataArray(Tair_T1, transform=ccrs.PlateCarree(),
x='xc', y='yc', figsup='Data Original')
plot_dataArray(dataArray_interpolated, transform=ccrs.PlateCarree(),
x='lon', y='lat', figsup='Interp - IDW')
| [
"numpy.abs",
"numpy.sqrt",
"cartopy.crs.PlateCarree",
"pandas.set_option",
"numpy.argsort",
"numpy.stack",
"numpy.dot",
"numpy.sum",
"numpy.isnan",
"xarray.DataArray",
"xarray.tutorial.open_dataset",
"numpy.meshgrid",
"numpy.zeros_like",
"numpy.arange"
] | [((241, 280), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(5000)'], {}), "('display.max_rows', 5000)\n", (254, 280), True, 'import pandas as pd\n'), ((281, 323), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(5000)'], {}), "('display.max_columns', 5000)\n", (294, 323), True, 'import pandas as pd\n'), ((408, 423), 'numpy.argsort', 'np.argsort', (['arr'], {}), '(arr)\n', (418, 423), True, 'import numpy as np\n'), ((814, 857), 'numpy.sqrt', 'np.sqrt', (['(dx ** p + dy ** p + smoothing ** p)'], {}), '(dx ** p + dy ** p + smoothing ** p)\n', (821, 857), True, 'import numpy as np\n'), ((1406, 1442), 'numpy.dot', 'np.dot', (['dd_Nearest', 'K_nearest_Values'], {}), '(dd_Nearest, K_nearest_Values)\n', (1412, 1442), True, 'import numpy as np\n'), ((1610, 1627), 'numpy.zeros_like', 'np.zeros_like', (['xp'], {}), '(xp)\n', (1623, 1627), True, 'import numpy as np\n'), ((2591, 2621), 'numpy.stack', 'np.stack', (['[xcor, ycor]'], {'axis': '(1)'}), '([xcor, ycor], axis=1)\n', (2599, 2621), True, 'import numpy as np\n'), ((2731, 2758), 'numpy.arange', 'np.arange', (['xmin', 'xmax', 'xres'], {}), '(xmin, xmax, xres)\n', (2740, 2758), True, 'import numpy as np\n'), ((2777, 2804), 'numpy.arange', 'np.arange', (['ymin', 'ymax', 'yres'], {}), '(ymin, ymax, yres)\n', (2786, 2804), True, 'import numpy as np\n'), ((2904, 2936), 'numpy.stack', 'np.stack', (['[xgrid, ygrid]'], {'axis': '(1)'}), '([xgrid, ygrid], axis=1)\n', (2912, 2936), True, 'import numpy as np\n'), ((3410, 3483), 'xarray.DataArray', 'xr.DataArray', (['arr.T'], {'coords': '{ydim: ycoor, xdim: xcoor}', 'dims': '[ydim, xdim]'}), '(arr.T, coords={ydim: ycoor, xdim: xcoor}, dims=[ydim, xdim])\n', (3422, 3483), True, 'import xarray as xr\n'), ((3632, 3650), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (3648, 3650), True, 'import cartopy.crs as ccrs\n'), ((649, 659), 'numpy.sum', 'np.sum', (['dd'], {}), '(dd)\n', (655, 659), True, 'import numpy as np\n'), ((1128, 1140), 'numpy.isnan', 'np.isnan', (['Vd'], {}), '(Vd)\n', (1136, 1140), True, 'import numpy as np\n'), ((889, 899), 'numpy.abs', 'np.abs', (['dd'], {}), '(dd)\n', (895, 899), True, 'import numpy as np\n'), ((2849, 2878), 'numpy.meshgrid', 'np.meshgrid', (['Xcoords', 'Ycoords'], {}), '(Xcoords, Ycoords)\n', (2860, 2878), True, 'import numpy as np\n'), ((4011, 4043), 'xarray.tutorial.open_dataset', 'xr.tutorial.open_dataset', (['"""rasm"""'], {}), "('rasm')\n", (4035, 4043), True, 'import xarray as xr\n'), ((5070, 5088), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (5086, 5088), True, 'import cartopy.crs as ccrs\n'), ((5218, 5236), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (5234, 5236), True, 'import cartopy.crs as ccrs\n'), ((3741, 3759), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (3757, 3759), True, 'import cartopy.crs as ccrs\n')] |
import torch
from torch import nn
import numpy as np
from evocraft_ga.nn.torch_utils import * # noqa
class Linear(nn.Module):
def __init__(self, noise_dims, x_dims, y_dims, z_dims, num_classes=1):
super(Linear, self).__init__()
self.noise_dims = noise_dims
self.x_dims = x_dims
self.y_dims = y_dims
self.z_dims = z_dims
self.num_classes = num_classes
self.linear1 = create_linear_torch(noise_dims, 64, relu=True)
self.linear2 = create_linear_torch(64, 256, relu=True)
self.output_linear = create_linear_torch(
256, x_dims * y_dims * z_dims * num_classes
)
self.layers = [
self.linear1,
self.linear2,
self.output_linear,
]
self._net = nn.Sequential(*self.layers)
def forward(self, x):
x = self._net(x)
return x
def generate(self, mean=0.0, std=1.0, to_numpy=False, squeeze=False, seed=None):
if seed is None:
seed = np.random.randint(1, high=2 ** 31 - 1)
np.random.seed(seed)
noise = torch.from_numpy(
np.random.normal(loc=mean, scale=std, size=(1, self.noise_dims))
).float()
out = self.forward(noise)
out = out.view(self.x_dims, self.y_dims, self.z_dims, self.num_classes)
out = nn.Softmax(dim=-1)(out)
if squeeze:
out = torch.squeeze(out)
if to_numpy:
out = out.detach().numpy()
return out
| [
"numpy.random.normal",
"torch.nn.Softmax",
"torch.nn.Sequential",
"numpy.random.randint",
"numpy.random.seed",
"torch.squeeze"
] | [((794, 821), 'torch.nn.Sequential', 'nn.Sequential', (['*self.layers'], {}), '(*self.layers)\n', (807, 821), False, 'from torch import nn\n'), ((1068, 1088), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1082, 1088), True, 'import numpy as np\n'), ((1021, 1059), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(2 ** 31 - 1)'}), '(1, high=2 ** 31 - 1)\n', (1038, 1059), True, 'import numpy as np\n'), ((1346, 1364), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (1356, 1364), False, 'from torch import nn\n'), ((1408, 1426), 'torch.squeeze', 'torch.squeeze', (['out'], {}), '(out)\n', (1421, 1426), False, 'import torch\n'), ((1135, 1199), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'mean', 'scale': 'std', 'size': '(1, self.noise_dims)'}), '(loc=mean, scale=std, size=(1, self.noise_dims))\n', (1151, 1199), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn import model_selection
from sklearn.preprocessing import MinMaxScaler,StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import LogisticRegression
from sklearn import svm,tree
from sklearn.ensemble import RandomForestClassifier
from dython.nominal import compute_associations
from scipy.stats import wasserstein_distance
from scipy.spatial import distance
import warnings
warnings.filterwarnings("ignore")
def supervised_model_training(x_train, y_train, x_test,
y_test, model_name):
if model_name == 'lr':
model = LogisticRegression(random_state=42,max_iter=500)
elif model_name == 'svm':
model = svm.SVC(random_state=42,probability=True)
elif model_name == 'dt':
model = tree.DecisionTreeClassifier(random_state=42)
elif model_name == 'rf':
model = RandomForestClassifier(random_state=42)
elif model_name == "mlp":
model = MLPClassifier(random_state=42,max_iter=100)
model.fit(x_train, y_train)
pred = model.predict(x_test)
if len(np.unique(y_train))>2:
predict = model.predict_proba(x_test)
acc = metrics.accuracy_score(y_test,pred)*100
auc = metrics.roc_auc_score(y_test, predict,average="weighted",multi_class="ovr")
f1_score = metrics.precision_recall_fscore_support(y_test, pred,average="weighted")[2]
return [acc, auc,f1_score]
else:
predict = model.predict_proba(x_test)[:,1]
acc = metrics.accuracy_score(y_test,pred)*100
auc = metrics.roc_auc_score(y_test, predict)
f1_score = metrics.precision_recall_fscore_support(y_test,pred)[2].mean()
return [acc, auc,f1_score]
def get_utility_metrics(real_path,fake_paths,scaler="MinMax",classifiers=["lr","dt","rf","mlp"],test_ratio=.20):
data_real = pd.read_csv(real_path).to_numpy()
data_dim = data_real.shape[1]
data_real_y = data_real[:,-1]
data_real_X = data_real[:,:data_dim-1]
X_train_real, X_test_real, y_train_real, y_test_real = model_selection.train_test_split(data_real_X ,data_real_y, test_size=test_ratio, stratify=data_real_y,random_state=42)
if scaler=="MinMax":
scaler_real = MinMaxScaler()
else:
scaler_real = StandardScaler()
scaler_real.fit(data_real_X)
X_train_real_scaled = scaler_real.transform(X_train_real)
X_test_real_scaled = scaler_real.transform(X_test_real)
all_real_results = []
for classifier in classifiers:
real_results = supervised_model_training(X_train_real_scaled,y_train_real,X_test_real_scaled,y_test_real,classifier)
all_real_results.append(real_results)
all_fake_results_avg = []
for fake_path in fake_paths:
data_fake = pd.read_csv(fake_path).to_numpy()
data_fake_y = data_fake[:,-1]
data_fake_X = data_fake[:,:data_dim-1]
X_train_fake, _ , y_train_fake, _ = model_selection.train_test_split(data_fake_X ,data_fake_y, test_size=test_ratio, stratify=data_fake_y,random_state=42)
if scaler=="MinMax":
scaler_fake = MinMaxScaler()
else:
scaler_fake = StandardScaler()
scaler_fake.fit(data_fake_X)
X_train_fake_scaled = scaler_fake.transform(X_train_fake)
all_fake_results = []
for classifier in classifiers:
fake_results = supervised_model_training(X_train_fake_scaled,y_train_fake,X_test_real_scaled,y_test_real,classifier)
all_fake_results.append(fake_results)
all_fake_results_avg.append(all_fake_results)
diff_results = np.array(all_real_results)- np.array(all_fake_results_avg).mean(axis=0)
return diff_results
def stat_sim(real_path,fake_path,cat_cols=None):
Stat_dict={}
real = pd.read_csv(real_path)
fake = pd.read_csv(fake_path)
really = real.copy()
fakey = fake.copy()
real_corr = compute_associations(real, nominal_columns=cat_cols)
fake_corr = compute_associations(fake, nominal_columns=cat_cols)
corr_dist = np.linalg.norm(real_corr - fake_corr)
cat_stat = []
num_stat = []
for column in real.columns:
if column in cat_cols:
real_pdf=(really[column].value_counts()/really[column].value_counts().sum())
fake_pdf=(fakey[column].value_counts()/fakey[column].value_counts().sum())
categories = (fakey[column].value_counts()/fakey[column].value_counts().sum()).keys().tolist()
sorted_categories = sorted(categories)
real_pdf_values = []
fake_pdf_values = []
for i in sorted_categories:
real_pdf_values.append(real_pdf[i])
fake_pdf_values.append(fake_pdf[i])
if len(real_pdf)!=len(fake_pdf):
zero_cats = set(really[column].value_counts().keys())-set(fakey[column].value_counts().keys())
for z in zero_cats:
real_pdf_values.append(real_pdf[z])
fake_pdf_values.append(0)
Stat_dict[column]=(distance.jensenshannon(real_pdf_values,fake_pdf_values, 2.0))
cat_stat.append(Stat_dict[column])
else:
scaler = MinMaxScaler()
scaler.fit(real[column].values.reshape(-1,1))
l1 = scaler.transform(real[column].values.reshape(-1,1)).flatten()
l2 = scaler.transform(fake[column].values.reshape(-1,1)).flatten()
Stat_dict[column]= (wasserstein_distance(l1,l2))
num_stat.append(Stat_dict[column])
return [np.mean(num_stat),np.mean(cat_stat),corr_dist]
def privacy_metrics(real_path,fake_path,data_percent=15):
real = pd.read_csv(real_path).drop_duplicates(keep=False)
fake = pd.read_csv(fake_path).drop_duplicates(keep=False)
real_refined = real.sample(n=int(len(real)*(.01*data_percent)), random_state=42).to_numpy()
fake_refined = fake.sample(n=int(len(fake)*(.01*data_percent)), random_state=42).to_numpy()
scalerR = StandardScaler()
scalerR.fit(real_refined)
scalerF = StandardScaler()
scalerF.fit(fake_refined)
df_real_scaled = scalerR.transform(real_refined)
df_fake_scaled = scalerF.transform(fake_refined)
dist_rf = metrics.pairwise_distances(df_real_scaled, Y=df_fake_scaled, metric='minkowski', n_jobs=-1)
dist_rr = metrics.pairwise_distances(df_real_scaled, Y=None, metric='minkowski', n_jobs=-1)
rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1)
dist_ff = metrics.pairwise_distances(df_fake_scaled, Y=None, metric='minkowski', n_jobs=-1)
rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1)
smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))]
smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))]
smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))]
smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))]
smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))]
smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr])
nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff])
nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf])
nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5)
nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5)
nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5)
min_dist_rf = np.array([i[0] for i in smallest_two_rf])
fifth_perc_rf = np.percentile(min_dist_rf,5)
min_dist_rr = np.array([i[0] for i in smallest_two_rr])
fifth_perc_rr = np.percentile(min_dist_rr,5)
min_dist_ff = np.array([i[0] for i in smallest_two_ff])
fifth_perc_ff = np.percentile(min_dist_ff,5)
return np.array([fifth_perc_rf,fifth_perc_rr,fifth_perc_ff,nn_fifth_perc_rf,nn_fifth_perc_rr,nn_fifth_perc_ff]).reshape(1,6) | [
"pandas.read_csv",
"sklearn.metrics.roc_auc_score",
"numpy.array",
"numpy.linalg.norm",
"scipy.spatial.distance.jensenshannon",
"numpy.mean",
"sklearn.tree.DecisionTreeClassifier",
"scipy.stats.wasserstein_distance",
"sklearn.preprocessing.MinMaxScaler",
"numpy.eye",
"sklearn.model_selection.tra... | [((507, 540), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (530, 540), False, 'import warnings\n'), ((2131, 2255), 'sklearn.model_selection.train_test_split', 'model_selection.train_test_split', (['data_real_X', 'data_real_y'], {'test_size': 'test_ratio', 'stratify': 'data_real_y', 'random_state': '(42)'}), '(data_real_X, data_real_y, test_size=\n test_ratio, stratify=data_real_y, random_state=42)\n', (2163, 2255), False, 'from sklearn import model_selection\n'), ((3909, 3931), 'pandas.read_csv', 'pd.read_csv', (['real_path'], {}), '(real_path)\n', (3920, 3931), True, 'import pandas as pd\n'), ((3944, 3966), 'pandas.read_csv', 'pd.read_csv', (['fake_path'], {}), '(fake_path)\n', (3955, 3966), True, 'import pandas as pd\n'), ((4039, 4091), 'dython.nominal.compute_associations', 'compute_associations', (['real'], {'nominal_columns': 'cat_cols'}), '(real, nominal_columns=cat_cols)\n', (4059, 4091), False, 'from dython.nominal import compute_associations\n'), ((4111, 4163), 'dython.nominal.compute_associations', 'compute_associations', (['fake'], {'nominal_columns': 'cat_cols'}), '(fake, nominal_columns=cat_cols)\n', (4131, 4163), False, 'from dython.nominal import compute_associations\n'), ((4183, 4220), 'numpy.linalg.norm', 'np.linalg.norm', (['(real_corr - fake_corr)'], {}), '(real_corr - fake_corr)\n', (4197, 4220), True, 'import numpy as np\n'), ((6230, 6246), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (6244, 6246), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((6293, 6309), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (6307, 6309), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((6470, 6566), 'sklearn.metrics.pairwise_distances', 'metrics.pairwise_distances', (['df_real_scaled'], {'Y': 'df_fake_scaled', 'metric': '"""minkowski"""', 'n_jobs': '(-1)'}), "(df_real_scaled, Y=df_fake_scaled, metric=\n 'minkowski', n_jobs=-1)\n", (6496, 6566), False, 'from sklearn import metrics\n'), ((6577, 6662), 'sklearn.metrics.pairwise_distances', 'metrics.pairwise_distances', (['df_real_scaled'], {'Y': 'None', 'metric': '"""minkowski"""', 'n_jobs': '(-1)'}), "(df_real_scaled, Y=None, metric='minkowski',\n n_jobs=-1)\n", (6603, 6662), False, 'from sklearn import metrics\n'), ((6767, 6852), 'sklearn.metrics.pairwise_distances', 'metrics.pairwise_distances', (['df_fake_scaled'], {'Y': 'None', 'metric': '"""minkowski"""', 'n_jobs': '(-1)'}), "(df_fake_scaled, Y=None, metric='minkowski',\n n_jobs=-1)\n", (6793, 6852), False, 'from sklearn import metrics\n'), ((7533, 7583), 'numpy.array', 'np.array', (['[(i[0] / i[1]) for i in smallest_two_rr]'], {}), '([(i[0] / i[1]) for i in smallest_two_rr])\n', (7541, 7583), True, 'import numpy as np\n'), ((7599, 7649), 'numpy.array', 'np.array', (['[(i[0] / i[1]) for i in smallest_two_ff]'], {}), '([(i[0] / i[1]) for i in smallest_two_ff])\n', (7607, 7649), True, 'import numpy as np\n'), ((7665, 7715), 'numpy.array', 'np.array', (['[(i[0] / i[1]) for i in smallest_two_rf]'], {}), '([(i[0] / i[1]) for i in smallest_two_rf])\n', (7673, 7715), True, 'import numpy as np\n'), ((7736, 7765), 'numpy.percentile', 'np.percentile', (['nn_ratio_rr', '(5)'], {}), '(nn_ratio_rr, 5)\n', (7749, 7765), True, 'import numpy as np\n'), ((7789, 7818), 'numpy.percentile', 'np.percentile', (['nn_ratio_ff', '(5)'], {}), '(nn_ratio_ff, 5)\n', (7802, 7818), True, 'import numpy as np\n'), ((7842, 7871), 'numpy.percentile', 'np.percentile', (['nn_ratio_rf', '(5)'], {}), '(nn_ratio_rf, 5)\n', (7855, 7871), True, 'import numpy as np\n'), ((7892, 7933), 'numpy.array', 'np.array', (['[i[0] for i in smallest_two_rf]'], {}), '([i[0] for i in smallest_two_rf])\n', (7900, 7933), True, 'import numpy as np\n'), ((7955, 7984), 'numpy.percentile', 'np.percentile', (['min_dist_rf', '(5)'], {}), '(min_dist_rf, 5)\n', (7968, 7984), True, 'import numpy as np\n'), ((8003, 8044), 'numpy.array', 'np.array', (['[i[0] for i in smallest_two_rr]'], {}), '([i[0] for i in smallest_two_rr])\n', (8011, 8044), True, 'import numpy as np\n'), ((8066, 8095), 'numpy.percentile', 'np.percentile', (['min_dist_rr', '(5)'], {}), '(min_dist_rr, 5)\n', (8079, 8095), True, 'import numpy as np\n'), ((8114, 8155), 'numpy.array', 'np.array', (['[i[0] for i in smallest_two_ff]'], {}), '([i[0] for i in smallest_two_ff])\n', (8122, 8155), True, 'import numpy as np\n'), ((8177, 8206), 'numpy.percentile', 'np.percentile', (['min_dist_ff', '(5)'], {}), '(min_dist_ff, 5)\n', (8190, 8206), True, 'import numpy as np\n'), ((697, 746), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'random_state': '(42)', 'max_iter': '(500)'}), '(random_state=42, max_iter=500)\n', (715, 746), False, 'from sklearn.linear_model import LogisticRegression\n'), ((1307, 1384), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['y_test', 'predict'], {'average': '"""weighted"""', 'multi_class': '"""ovr"""'}), "(y_test, predict, average='weighted', multi_class='ovr')\n", (1328, 1384), False, 'from sklearn import metrics\n'), ((1633, 1671), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['y_test', 'predict'], {}), '(y_test, predict)\n', (1654, 1671), False, 'from sklearn import metrics\n'), ((2302, 2316), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (2314, 2316), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((2351, 2367), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (2365, 2367), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((3029, 3153), 'sklearn.model_selection.train_test_split', 'model_selection.train_test_split', (['data_fake_X', 'data_fake_y'], {'test_size': 'test_ratio', 'stratify': 'data_fake_y', 'random_state': '(42)'}), '(data_fake_X, data_fake_y, test_size=\n test_ratio, stratify=data_fake_y, random_state=42)\n', (3061, 3153), False, 'from sklearn import model_selection\n'), ((3716, 3742), 'numpy.array', 'np.array', (['all_real_results'], {}), '(all_real_results)\n', (3724, 3742), True, 'import numpy as np\n'), ((5777, 5794), 'numpy.mean', 'np.mean', (['num_stat'], {}), '(num_stat)\n', (5784, 5794), True, 'import numpy as np\n'), ((5795, 5812), 'numpy.mean', 'np.mean', (['cat_stat'], {}), '(cat_stat)\n', (5802, 5812), True, 'import numpy as np\n'), ((790, 832), 'sklearn.svm.SVC', 'svm.SVC', ([], {'random_state': '(42)', 'probability': '(True)'}), '(random_state=42, probability=True)\n', (797, 832), False, 'from sklearn import svm, tree\n'), ((1171, 1189), 'numpy.unique', 'np.unique', (['y_train'], {}), '(y_train)\n', (1180, 1189), True, 'import numpy as np\n'), ((1256, 1292), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_test', 'pred'], {}), '(y_test, pred)\n', (1278, 1292), False, 'from sklearn import metrics\n'), ((1399, 1472), 'sklearn.metrics.precision_recall_fscore_support', 'metrics.precision_recall_fscore_support', (['y_test', 'pred'], {'average': '"""weighted"""'}), "(y_test, pred, average='weighted')\n", (1438, 1472), False, 'from sklearn import metrics\n'), ((1582, 1618), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_test', 'pred'], {}), '(y_test, pred)\n', (1604, 1618), False, 'from sklearn import metrics\n'), ((1921, 1943), 'pandas.read_csv', 'pd.read_csv', (['real_path'], {}), '(real_path)\n', (1932, 1943), True, 'import pandas as pd\n'), ((3202, 3216), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (3214, 3216), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((3253, 3269), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (3267, 3269), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((5263, 5324), 'scipy.spatial.distance.jensenshannon', 'distance.jensenshannon', (['real_pdf_values', 'fake_pdf_values', '(2.0)'], {}), '(real_pdf_values, fake_pdf_values, 2.0)\n', (5285, 5324), False, 'from scipy.spatial import distance\n'), ((5418, 5432), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (5430, 5432), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((5685, 5713), 'scipy.stats.wasserstein_distance', 'wasserstein_distance', (['l1', 'l2'], {}), '(l1, l2)\n', (5705, 5713), False, 'from scipy.stats import wasserstein_distance\n'), ((5903, 5925), 'pandas.read_csv', 'pd.read_csv', (['real_path'], {}), '(real_path)\n', (5914, 5925), True, 'import pandas as pd\n'), ((5966, 5988), 'pandas.read_csv', 'pd.read_csv', (['fake_path'], {}), '(fake_path)\n', (5977, 5988), True, 'import pandas as pd\n'), ((8224, 8337), 'numpy.array', 'np.array', (['[fifth_perc_rf, fifth_perc_rr, fifth_perc_ff, nn_fifth_perc_rf,\n nn_fifth_perc_rr, nn_fifth_perc_ff]'], {}), '([fifth_perc_rf, fifth_perc_rr, fifth_perc_ff, nn_fifth_perc_rf,\n nn_fifth_perc_rr, nn_fifth_perc_ff])\n', (8232, 8337), True, 'import numpy as np\n'), ((874, 918), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'random_state': '(42)'}), '(random_state=42)\n', (901, 918), False, 'from sklearn import svm, tree\n'), ((2869, 2891), 'pandas.read_csv', 'pd.read_csv', (['fake_path'], {}), '(fake_path)\n', (2880, 2891), True, 'import pandas as pd\n'), ((3744, 3774), 'numpy.array', 'np.array', (['all_fake_results_avg'], {}), '(all_fake_results_avg)\n', (3752, 3774), True, 'import numpy as np\n'), ((966, 1005), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'random_state': '(42)'}), '(random_state=42)\n', (988, 1005), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((1688, 1741), 'sklearn.metrics.precision_recall_fscore_support', 'metrics.precision_recall_fscore_support', (['y_test', 'pred'], {}), '(y_test, pred)\n', (1727, 1741), False, 'from sklearn import metrics\n'), ((6686, 6722), 'numpy.eye', 'np.eye', (['dist_rr.shape[0]'], {'dtype': 'bool'}), '(dist_rr.shape[0], dtype=bool)\n', (6692, 6722), True, 'import numpy as np\n'), ((6876, 6912), 'numpy.eye', 'np.eye', (['dist_ff.shape[0]'], {'dtype': 'bool'}), '(dist_ff.shape[0], dtype=bool)\n', (6882, 6912), True, 'import numpy as np\n'), ((1048, 1092), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'random_state': '(42)', 'max_iter': '(100)'}), '(random_state=42, max_iter=100)\n', (1061, 1092), False, 'from sklearn.neural_network import MLPClassifier\n')] |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
sonar_data = pd.read_csv("C:/Users/Sakthi/Desktop/Copy of sonar data.csv",
header=None)
sonar_data.head()
sonar_data.shape
sonar_data.describe()
sonar_data[60].value_counts()
sonar_data.groupby(60).mean()
X = sonar_data.drop(columns=60, axis=1)
Y = sonar_data[60]
print(X)
print(Y)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.1,
stratify=Y, random_state=1)
print(X.shape, X_train.shape, X_test.shape)
print(Y.shape, Y_train.shape, Y_test.shape)
print(X_train)
print(Y_train)
model = LogisticRegression()
model.fit(X_train, Y_train)
model.fit(X_train, Y_train)
X_train_prediction = model.predict(X_train)
training_data_accuracy = accuracy_score(X_train_prediction, Y_train)
print("Accuracy on training data : ", training_data_accuracy)
X_test_prediction = model.predict(X_test)
test_data_accuracy = accuracy_score(X_test_prediction, Y_test)
print("Accuracy on test data :" , test_data_accuracy)
Input_data = (0.0307,0.0523,0.0653,0.0521,0.0611,0.0577,0.0665,0.0664,0.1460,
0.2792,0.3877,0.4992,0.4981,0.4972,0.5607,0.7339,0.8230,0.9173,
0.9975,0.9911,0.8240,0.6498,0.5980,0.4862,0.3150,0.1543,0.0989,
0.0284,0.1008,0.2636,0.2694,0.2930,0.2925,0.3998,0.3660,0.3172,
0.4609,0.4374,0.1820,0.3376,0.6202,0.4448,0.1863,0.1420,0.0589,
0.0576,0.0672,0.0269,0.0245,0.0190,0.0063,0.0321,0.0189,0.0137,
0.0277,0.0152,0.0052,0.0121,0.0124,0.0055)
input_data_as_numpy_array = np.asarray(Input_data)
input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)
prediction = model.predict(input_data_reshaped)
print(prediction)
if (prediction[0]=="R"):
print("The object is a Rock")
else:
print("The object is a mine")
| [
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.accuracy_score"
] | [((207, 281), 'pandas.read_csv', 'pd.read_csv', (['"""C:/Users/Sakthi/Desktop/Copy of sonar data.csv"""'], {'header': 'None'}), "('C:/Users/Sakthi/Desktop/Copy of sonar data.csv', header=None)\n", (218, 281), True, 'import pandas as pd\n'), ((565, 630), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.1)', 'stratify': 'Y', 'random_state': '(1)'}), '(X, Y, test_size=0.1, stratify=Y, random_state=1)\n', (581, 630), False, 'from sklearn.model_selection import train_test_split\n'), ((824, 844), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (842, 844), False, 'from sklearn.linear_model import LogisticRegression\n'), ((980, 1023), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['X_train_prediction', 'Y_train'], {}), '(X_train_prediction, Y_train)\n', (994, 1023), False, 'from sklearn.metrics import accuracy_score\n'), ((1156, 1197), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['X_test_prediction', 'Y_test'], {}), '(X_test_prediction, Y_test)\n', (1170, 1197), False, 'from sklearn.metrics import accuracy_score\n'), ((1820, 1842), 'numpy.asarray', 'np.asarray', (['Input_data'], {}), '(Input_data)\n', (1830, 1842), True, 'import numpy as np\n')] |
from keras.models import Sequential
from keras.datasets import boston_housing
from keras.layers import Dense
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping
import numpy as np
import matplotlib.pyplot as plt
from utils import randomize
# Hyper-parameters
EPOCHS = 500
NUM_HIDDEN_UNITS = 64
LEARNING_RATE = 0.001
BATCH_SIZE = 32
# Load the Boston Housing Prices dataset
(X_train, y_train), (X_test, y_test) = boston_housing.load_data()
num_features = X_train.shape[1]
# Shuffle the training set
X_train, y_train = randomize(X_train, y_train)
print("Train data size -> input: {}, output: {}".format(X_train.shape, y_train.shape))
print("Test data size: -> input: {}, output: {}".format(X_test.shape, y_test.shape))
# Normalize features
# Test data is *not* used when calculating the mean and std
mean = X_train.mean(axis=0)
std = X_train.std(axis=0)
X_train = (X_train - mean) / std
X_test = (X_test - mean) / std
# Build the model
model = Sequential()
model.add(Dense(NUM_HIDDEN_UNITS, activation='relu', input_shape=(num_features,)))
model.add(Dense(1, activation='linear'))
model.compile(loss='mse', optimizer=Adam(lr=LEARNING_RATE), metrics=['mae'])
# Let's print a summary of the network structure
model.summary()
# Stop training when a monitored quantity has stopped improving
# The patience parameter is the amount of epochs to check for improvement
early_stop = EarlyStopping(monitor='val_loss', patience=20)
# Start Training
history = model.fit(X_train, y_train, epochs=EPOCHS, batch_size=BATCH_SIZE,
validation_split=0.2, verbose=1, callbacks=[early_stop])
# Let's plot the error values through training epochs
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [1000$]')
plt.plot(history.epoch, np.array(history.history['mean_absolute_error']), label='Train Loss')
plt.plot(history.epoch, np.array(history.history['val_mean_absolute_error']), label='Val loss')
plt.legend()
plt.ylim([0, 5])
# Let's check the error value on test data
[loss, mae] = model.evaluate(X_test, y_test, verbose=0)
print("\n Testing set Mean Abs Error: ${:7.2f}".format(mae * 1000))
# Predict
y_pred = model.predict(X_test).flatten()
plt.figure()
plt.scatter(y_test, y_pred)
plt.xlabel('True Values [1000$]')
plt.ylabel('Predictions [1000$]')
plt.axis('equal')
plt.xlim(plt.xlim())
plt.ylim(plt.ylim())
plt.plot([-100, 100], [-100, 100], color='red')
plt.figure()
error = y_pred - y_test
plt.hist(error, bins=50)
plt.xlabel("Prediction Error [1000$]")
plt.ylabel("Count")
plt.show()
print()
| [
"keras.optimizers.Adam",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"keras.datasets.boston_housing.load_data",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"keras.models.Sequential",
"matplotlib.pyplot.axis",
"numpy.array",
"matplotlib.pyplot.figur... | [((438, 464), 'keras.datasets.boston_housing.load_data', 'boston_housing.load_data', ([], {}), '()\n', (462, 464), False, 'from keras.datasets import boston_housing\n'), ((544, 571), 'utils.randomize', 'randomize', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (553, 571), False, 'from utils import randomize\n'), ((972, 984), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (982, 984), False, 'from keras.models import Sequential\n'), ((1404, 1450), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': '(20)'}), "(monitor='val_loss', patience=20)\n", (1417, 1450), False, 'from keras.callbacks import EarlyStopping\n'), ((1677, 1689), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1687, 1689), True, 'import matplotlib.pyplot as plt\n'), ((1690, 1709), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (1700, 1709), True, 'import matplotlib.pyplot as plt\n'), ((1710, 1746), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mean Abs Error [1000$]"""'], {}), "('Mean Abs Error [1000$]')\n", (1720, 1746), True, 'import matplotlib.pyplot as plt\n'), ((1937, 1949), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1947, 1949), True, 'import matplotlib.pyplot as plt\n'), ((1950, 1966), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 5]'], {}), '([0, 5])\n', (1958, 1966), True, 'import matplotlib.pyplot as plt\n'), ((2188, 2200), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2198, 2200), True, 'import matplotlib.pyplot as plt\n'), ((2201, 2228), 'matplotlib.pyplot.scatter', 'plt.scatter', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (2212, 2228), True, 'import matplotlib.pyplot as plt\n'), ((2229, 2262), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""True Values [1000$]"""'], {}), "('True Values [1000$]')\n", (2239, 2262), True, 'import matplotlib.pyplot as plt\n'), ((2263, 2296), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Predictions [1000$]"""'], {}), "('Predictions [1000$]')\n", (2273, 2296), True, 'import matplotlib.pyplot as plt\n'), ((2297, 2314), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (2305, 2314), True, 'import matplotlib.pyplot as plt\n'), ((2357, 2404), 'matplotlib.pyplot.plot', 'plt.plot', (['[-100, 100]', '[-100, 100]'], {'color': '"""red"""'}), "([-100, 100], [-100, 100], color='red')\n", (2365, 2404), True, 'import matplotlib.pyplot as plt\n'), ((2406, 2418), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2416, 2418), True, 'import matplotlib.pyplot as plt\n'), ((2443, 2467), 'matplotlib.pyplot.hist', 'plt.hist', (['error'], {'bins': '(50)'}), '(error, bins=50)\n', (2451, 2467), True, 'import matplotlib.pyplot as plt\n'), ((2468, 2506), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Prediction Error [1000$]"""'], {}), "('Prediction Error [1000$]')\n", (2478, 2506), True, 'import matplotlib.pyplot as plt\n'), ((2507, 2526), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Count"""'], {}), "('Count')\n", (2517, 2526), True, 'import matplotlib.pyplot as plt\n'), ((2527, 2537), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2535, 2537), True, 'import matplotlib.pyplot as plt\n'), ((995, 1066), 'keras.layers.Dense', 'Dense', (['NUM_HIDDEN_UNITS'], {'activation': '"""relu"""', 'input_shape': '(num_features,)'}), "(NUM_HIDDEN_UNITS, activation='relu', input_shape=(num_features,))\n", (1000, 1066), False, 'from keras.layers import Dense\n'), ((1078, 1107), 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""linear"""'}), "(1, activation='linear')\n", (1083, 1107), False, 'from keras.layers import Dense\n'), ((1771, 1819), 'numpy.array', 'np.array', (["history.history['mean_absolute_error']"], {}), "(history.history['mean_absolute_error'])\n", (1779, 1819), True, 'import numpy as np\n'), ((1865, 1917), 'numpy.array', 'np.array', (["history.history['val_mean_absolute_error']"], {}), "(history.history['val_mean_absolute_error'])\n", (1873, 1917), True, 'import numpy as np\n'), ((2324, 2334), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (2332, 2334), True, 'import matplotlib.pyplot as plt\n'), ((2345, 2355), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (2353, 2355), True, 'import matplotlib.pyplot as plt\n'), ((1145, 1167), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'LEARNING_RATE'}), '(lr=LEARNING_RATE)\n', (1149, 1167), False, 'from keras.optimizers import Adam\n')] |
"""
This is the main tester script for point cloud generation evaluation.
Use scripts/eval_gen_pc_vae_chair.sh to run.
"""
import os
import sys
import json
import shutil
from argparse import ArgumentParser
import numpy as np
import torch
import utils
from torchvision.models import vgg16
import torch.nn as nn
from config import add_eval_args
from data import PartNetDataset, Tree
from image_encoder import ImageEncoder
# os.environ["CUDA_VISIBLE_DEVICES"] = "3"
torch.set_num_threads(1)
parser = ArgumentParser()
parser = add_eval_args(parser)
parser.add_argument('--num_gen', type=int, default=20, help='how many shapes to generate?')
eval_conf = parser.parse_args()
if __name__ == '__main__':
device = 'cuda:3'
models = utils.get_model_module('model_part_vst_fea')
conf = torch.load('/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_img_encoder/conf.pth')
# load object category information
Tree.load_category_info(conf.category)
# merge training and evaluation configurations, giving evaluation parameters precendence
conf.__dict__.update(eval_conf.__dict__)
conf.num_point = 3000
conf.exp_name = 'part_pc_ae_chair_3000_vst_fea_kl0'
conf.hidden_size=512
conf.feature_size=512
img_encoder=ImageEncoder(512).to(device)
img_encoder.load_state_dict(torch.load('/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_train/47_net_part_pc_encoder.pth',map_location={'cuda:0':device}))
decoder = models.PartImgDecoder(feat_len=256, num_point=conf.num_point).to(device)
decoder.load_state_dict(torch.load(f'/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_train/47_net_part_pc_decoder.pth',map_location={'cuda:0':device}))
img_encoder.eval()
decoder.eval()
# net = torch.randn(1, 100).to(device)
with torch.set_grad_enabled(False):
imgs_1 = np.load('/home/zhangxc/tmp/structurenet/data/partnetdata/chair_img_3000/173.npz')['image'][4:8]
imgs_2 = np.load('/home/zhangxc/tmp/structurenet/data/partnetdata/chair_img_3000/186.npz')['image'][1:2]
imgs = np.concatenate((imgs_2,imgs_1),axis=0)
print(imgs.shape)
imgs = torch.tensor(imgs, dtype=torch.float32).permute(0,3,1,2).to(device)
root_codes=img_encoder(imgs)
root_code=root_codes[0]
pred = decoder(root_code.unsqueeze(0))
output_filename = os.path.join(conf.result_path,'pc_ae_chair_image_encoder_test', 'object-result.obj')
output_filename2 = os.path.join(conf.result_path,'pc_ae_chair_image_encoder_test', 'img-result.obj')
pc=pred[0].squeeze(0).cpu()
img=pred[1].squeeze(1).cpu()
pc = np.hstack((np.full([pc.shape[0], 1], 'v'), pc))
np.savetxt(output_filename, pc, fmt='%s', delimiter=' ')
| [
"utils.get_model_module",
"numpy.full",
"argparse.ArgumentParser",
"data.Tree.load_category_info",
"config.add_eval_args",
"image_encoder.ImageEncoder",
"torch.load",
"os.path.join",
"torch.set_num_threads",
"torch.tensor",
"numpy.concatenate",
"numpy.savetxt",
"torch.set_grad_enabled",
"n... | [((472, 496), 'torch.set_num_threads', 'torch.set_num_threads', (['(1)'], {}), '(1)\n', (493, 496), False, 'import torch\n'), ((507, 523), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (521, 523), False, 'from argparse import ArgumentParser\n'), ((533, 554), 'config.add_eval_args', 'add_eval_args', (['parser'], {}), '(parser)\n', (546, 554), False, 'from config import add_eval_args\n'), ((743, 787), 'utils.get_model_module', 'utils.get_model_module', (['"""model_part_vst_fea"""'], {}), "('model_part_vst_fea')\n", (765, 787), False, 'import utils\n'), ((799, 944), 'torch.load', 'torch.load', (['"""/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_img_encoder/conf.pth"""'], {}), "(\n '/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_img_encoder/conf.pth'\n )\n", (809, 944), False, 'import torch\n'), ((978, 1016), 'data.Tree.load_category_info', 'Tree.load_category_info', (['conf.category'], {}), '(conf.category)\n', (1001, 1016), False, 'from data import PartNetDataset, Tree\n'), ((1366, 1556), 'torch.load', 'torch.load', (['"""/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_train/47_net_part_pc_encoder.pth"""'], {'map_location': "{'cuda:0': device}"}), "(\n '/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_train/47_net_part_pc_encoder.pth'\n , map_location={'cuda:0': device})\n", (1376, 1556), False, 'import torch\n'), ((1661, 1852), 'torch.load', 'torch.load', (['f"""/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_train/47_net_part_pc_decoder.pth"""'], {'map_location': "{'cuda:0': device}"}), "(\n f'/home/zhangxc/tmp/structurenet-master/data/models/part_pc_ae_chair_3000_vst_fea_kl0.01_multi_2_parts_train/47_net_part_pc_decoder.pth'\n , map_location={'cuda:0': device})\n", (1671, 1852), False, 'import torch\n'), ((1936, 1965), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (1958, 1965), False, 'import torch\n'), ((2208, 2248), 'numpy.concatenate', 'np.concatenate', (['(imgs_2, imgs_1)'], {'axis': '(0)'}), '((imgs_2, imgs_1), axis=0)\n', (2222, 2248), True, 'import numpy as np\n'), ((2498, 2587), 'os.path.join', 'os.path.join', (['conf.result_path', '"""pc_ae_chair_image_encoder_test"""', '"""object-result.obj"""'], {}), "(conf.result_path, 'pc_ae_chair_image_encoder_test',\n 'object-result.obj')\n", (2510, 2587), False, 'import os\n'), ((2610, 2696), 'os.path.join', 'os.path.join', (['conf.result_path', '"""pc_ae_chair_image_encoder_test"""', '"""img-result.obj"""'], {}), "(conf.result_path, 'pc_ae_chair_image_encoder_test',\n 'img-result.obj')\n", (2622, 2696), False, 'import os\n'), ((2836, 2892), 'numpy.savetxt', 'np.savetxt', (['output_filename', 'pc'], {'fmt': '"""%s"""', 'delimiter': '""" """'}), "(output_filename, pc, fmt='%s', delimiter=' ')\n", (2846, 2892), True, 'import numpy as np\n'), ((1305, 1322), 'image_encoder.ImageEncoder', 'ImageEncoder', (['(512)'], {}), '(512)\n', (1317, 1322), False, 'from image_encoder import ImageEncoder\n'), ((1984, 2070), 'numpy.load', 'np.load', (['"""/home/zhangxc/tmp/structurenet/data/partnetdata/chair_img_3000/173.npz"""'], {}), "(\n '/home/zhangxc/tmp/structurenet/data/partnetdata/chair_img_3000/173.npz')\n", (1991, 2070), True, 'import numpy as np\n'), ((2097, 2183), 'numpy.load', 'np.load', (['"""/home/zhangxc/tmp/structurenet/data/partnetdata/chair_img_3000/186.npz"""'], {}), "(\n '/home/zhangxc/tmp/structurenet/data/partnetdata/chair_img_3000/186.npz')\n", (2104, 2183), True, 'import numpy as np\n'), ((2791, 2821), 'numpy.full', 'np.full', (['[pc.shape[0], 1]', '"""v"""'], {}), "([pc.shape[0], 1], 'v')\n", (2798, 2821), True, 'import numpy as np\n'), ((2288, 2327), 'torch.tensor', 'torch.tensor', (['imgs'], {'dtype': 'torch.float32'}), '(imgs, dtype=torch.float32)\n', (2300, 2327), False, 'import torch\n')] |
# Make metadata table for DECaLS images
# Using NSA and DECALS catalogs (matched previously), derive
# a) astrometrics e.g. absolute size, magnitude by band (expanded from catalog)
# b) galaxy zoo metadata e.g. url location, 'retire_at'
# Runs on the 'goodimgs' catalog output after matching catalogs and downloading/checking fits
# 'not_gz': these are galaxies which are part of the sdss lost set (and actually are now in gz)
# Not yet clear how to find which galaxies these are - what makes the data file?
import os
import warnings
import numpy as np
from astropy import units as u
from astropy.cosmology import WMAP9
from astropy.io import fits
from astropy.table import Table
warnings.simplefilter("ignore", RuntimeWarning)
version = '0_1_2'
nsa_not_gz = fits.getdata('../fits/nsa_v{0}_not_in_GZ_all_in_one.fits'.format(version), 1)
N = len(nsa_not_gz)
t = Table()
t['coords.0'] = nsa_not_gz['RA']
t['coords.1'] = nsa_not_gz['DEC']
# Calculate absolute size in kpc
size = WMAP9.kpc_proper_per_arcmin(nsa_not_gz['Z']).to(u.kpc/u.arcsec)*(nsa_not_gz['PETROTHETA']*u.arcsec)
size[nsa_not_gz['Z']<0] = -99.*u.kpc
# Calculate absolute and apparent magnitude
absmag_r = nsa_not_gz['ABSMAG'][:, 4].astype(float)
mag = 22.5 - 2.5*np.log10(nsa_not_gz['NMGY']).astype(float)
mag[~np.isfinite(mag)] = -99.
fluxarr = nsa_not_gz['PETROFLUX'][:, 4].astype(float)
url_stub = "http://www.galaxyzoo.org.s3.amazonaws.com/subjects/sdss_lost_set"
for imgtype in ('standard', 'inverted', 'thumbnail'):
lst = url_stub + '/{0}/'.format(imgtype) + nsa_not_gz['IAUNAME'] + '.jpeg'
t['location.{0}'.format(imgtype)] = lst
t['nsa_id'] = np.char.add('NSA_', nsa_not_gz['NSAID'].astype(str))
t['metadata.absolute_size'] = size.value
t['metadata.counters.feature'] = np.zeros(N, dtype=int)
t['metadata.counters.smooth'] = np.zeros(N, dtype=int)
t['metadata.counters.star'] = np.zeros(N, dtype=int)
t['metadata.mag.faruv'] = mag[:, 0]
t['metadata.mag.nearuv'] = mag[:, 1]
t['metadata.mag.u'] = mag[:, 2]
t['metadata.mag.g'] = mag[:, 3]
t['metadata.mag.r'] = mag[:, 4]
t['metadata.mag.i'] = mag[:, 5]
t['metadata.mag.z'] = mag[:, 6]
t['metadata.mag.abs_r'] = absmag_r
t['metadata.petrorad_50_r'] = nsa_not_gz['PETROTH50']
t['metadata.petroflux_r'] = fluxarr
t['metadata.petrorad_r'] = nsa_not_gz['PETROTHETA']
t['metadata.redshift'] = nsa_not_gz['Z']
t['metadata.retire_at'] = [40] * N
t['survey'] = ['decals'] * N
# Check format and content
#t[:5].show_in_browser()
# Write to table
ftypes = ('csv', 'fits')
for ft in ftypes:
fname = '../fits/nsa_not_gz_metadata.{0}'.format(ft)
if os.path.isfile(fname):
os.remove(fname)
t.write(fname)
| [
"astropy.cosmology.WMAP9.kpc_proper_per_arcmin",
"numpy.log10",
"astropy.table.Table",
"os.path.isfile",
"numpy.zeros",
"numpy.isfinite",
"warnings.simplefilter",
"os.remove"
] | [((686, 733), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'RuntimeWarning'], {}), "('ignore', RuntimeWarning)\n", (707, 733), False, 'import warnings\n'), ((870, 877), 'astropy.table.Table', 'Table', ([], {}), '()\n', (875, 877), False, 'from astropy.table import Table\n'), ((1768, 1790), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'int'}), '(N, dtype=int)\n', (1776, 1790), True, 'import numpy as np\n'), ((1823, 1845), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'int'}), '(N, dtype=int)\n', (1831, 1845), True, 'import numpy as np\n'), ((1876, 1898), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'int'}), '(N, dtype=int)\n', (1884, 1898), True, 'import numpy as np\n'), ((2594, 2615), 'os.path.isfile', 'os.path.isfile', (['fname'], {}), '(fname)\n', (2608, 2615), False, 'import os\n'), ((1288, 1304), 'numpy.isfinite', 'np.isfinite', (['mag'], {}), '(mag)\n', (1299, 1304), True, 'import numpy as np\n'), ((2625, 2641), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (2634, 2641), False, 'import os\n'), ((988, 1032), 'astropy.cosmology.WMAP9.kpc_proper_per_arcmin', 'WMAP9.kpc_proper_per_arcmin', (["nsa_not_gz['Z']"], {}), "(nsa_not_gz['Z'])\n", (1015, 1032), False, 'from astropy.cosmology import WMAP9\n'), ((1240, 1268), 'numpy.log10', 'np.log10', (["nsa_not_gz['NMGY']"], {}), "(nsa_not_gz['NMGY'])\n", (1248, 1268), True, 'import numpy as np\n')] |
import numpy as np
import os
import sys
import wave
import copy
import math
from keras.models import Sequential, Model
from keras.layers.core import Dense, Activation
from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D,Dropout
from keras.layers.wrappers import TimeDistributed
from keras.optimizers import SGD, Adam, RMSprop
from keras.layers.normalization import BatchNormalization
from sklearn.preprocessing import label_binarize
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing import sequence
from features import *
from helper import *
code_path = os.path.dirname(os.path.realpath(os.getcwd()))
emotions_used = np.array(['ang', 'exc', 'neu', 'sad'])
data_path = code_path + "/../data/sessions/"
sessions = ['Session1', 'Session2', 'Session3', 'Session4', 'Session5']
framerate = 16000
import pickle
with open(data_path + '/../'+'data_collected.pickle', 'rb') as handle:
data2 = pickle.load(handle)
text = []
for ses_mod in data2:
text.append(ses_mod['transcription'])
MAX_SEQUENCE_LENGTH = 500
tokenizer = Tokenizer()
tokenizer.fit_on_texts(text)
token_tr_X = tokenizer.texts_to_sequences(text)
x_train_text = []
x_train_text = sequence.pad_sequences(token_tr_X, maxlen=MAX_SEQUENCE_LENGTH)
import codecs
EMBEDDING_DIM = 300
word_index = tokenizer.word_index
print('Found %s unique tokens' % len(word_index))
file_loc = data_path + '../glove.42B.300d.txt'
print (file_loc)
gembeddings_index = {}
with codecs.open(file_loc, encoding='utf-8') as f:
for line in f:
values = line.split(' ')
word = values[0]
gembedding = np.asarray(values[1:], dtype='float32')
gembeddings_index[word] = gembedding
#
f.close()
print('G Word embeddings:', len(gembeddings_index))
nb_words = len(word_index) +1
g_word_embedding_matrix = np.zeros((nb_words, EMBEDDING_DIM))
for word, i in word_index.items():
gembedding_vector = gembeddings_index.get(word)
if gembedding_vector is not None:
g_word_embedding_matrix[i] = gembedding_vector
print('G Null word embeddings: %d' % np.sum(np.sum(g_word_embedding_matrix, axis=1) == 0))
Y=[]
for ses_mod in data2:
Y.append(ses_mod['emotion'])
Y = label_binarize(Y,emotions_used)
Y.shape
model = Sequential()
#model.add(Embedding(2737, 128, input_length=MAX_SEQUENCE_LENGTH))
model.add(Embedding(nb_words,
EMBEDDING_DIM,
weights = [g_word_embedding_matrix],
input_length = MAX_SEQUENCE_LENGTH,
trainable = True))
model.add(Convolution1D(256, 3, border_mode='same'))
model.add(Dropout(0.2))
model.add(Activation('relu'))
model.add(Convolution1D(128, 3, border_mode='same'))
model.add(Dropout(0.2))
model.add(Activation('relu'))
model.add(Convolution1D(64, 3, border_mode='same'))
model.add(Dropout(0.2))
model.add(Activation('relu'))
model.add(Convolution1D(32, 3, border_mode='same'))
model.add(Dropout(0.2))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(4))
model.add(Activation('softmax'))
#sgd = optimizers.SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',optimizer='adam' ,metrics=['acc'])
## compille it here according to instructions
#model.compile()
model.summary()
print("Model1 Built")
hist = model.fit(x_train_text, Y,
batch_size=100, nb_epoch=125, verbose=1,
validation_split=0.2)
| [
"sklearn.preprocessing.label_binarize",
"keras.preprocessing.text.Tokenizer",
"keras.layers.core.Activation",
"keras.layers.Flatten",
"pickle.load",
"numpy.asarray",
"keras.models.Sequential",
"os.getcwd",
"numpy.array",
"numpy.zeros",
"keras.layers.Convolution1D",
"numpy.sum",
"codecs.open"... | [((726, 764), 'numpy.array', 'np.array', (["['ang', 'exc', 'neu', 'sad']"], {}), "(['ang', 'exc', 'neu', 'sad'])\n", (734, 764), True, 'import numpy as np\n'), ((1134, 1145), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (1143, 1145), False, 'from keras.preprocessing.text import Tokenizer\n'), ((1258, 1320), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['token_tr_X'], {'maxlen': 'MAX_SEQUENCE_LENGTH'}), '(token_tr_X, maxlen=MAX_SEQUENCE_LENGTH)\n', (1280, 1320), False, 'from keras.preprocessing import sequence\n'), ((1886, 1921), 'numpy.zeros', 'np.zeros', (['(nb_words, EMBEDDING_DIM)'], {}), '((nb_words, EMBEDDING_DIM))\n', (1894, 1921), True, 'import numpy as np\n'), ((2272, 2304), 'sklearn.preprocessing.label_binarize', 'label_binarize', (['Y', 'emotions_used'], {}), '(Y, emotions_used)\n', (2286, 2304), False, 'from sklearn.preprocessing import label_binarize\n'), ((2322, 2334), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2332, 2334), False, 'from keras.models import Sequential, Model\n'), ((998, 1017), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (1009, 1017), False, 'import pickle\n'), ((1536, 1575), 'codecs.open', 'codecs.open', (['file_loc'], {'encoding': '"""utf-8"""'}), "(file_loc, encoding='utf-8')\n", (1547, 1575), False, 'import codecs\n'), ((2412, 2535), 'keras.layers.Embedding', 'Embedding', (['nb_words', 'EMBEDDING_DIM'], {'weights': '[g_word_embedding_matrix]', 'input_length': 'MAX_SEQUENCE_LENGTH', 'trainable': '(True)'}), '(nb_words, EMBEDDING_DIM, weights=[g_word_embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH, trainable=True)\n', (2421, 2535), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((2629, 2670), 'keras.layers.Convolution1D', 'Convolution1D', (['(256)', '(3)'], {'border_mode': '"""same"""'}), "(256, 3, border_mode='same')\n", (2642, 2670), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((2682, 2694), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (2689, 2694), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((2706, 2724), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2716, 2724), False, 'from keras.layers.core import Dense, Activation\n'), ((2736, 2777), 'keras.layers.Convolution1D', 'Convolution1D', (['(128)', '(3)'], {'border_mode': '"""same"""'}), "(128, 3, border_mode='same')\n", (2749, 2777), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((2789, 2801), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (2796, 2801), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((2813, 2831), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2823, 2831), False, 'from keras.layers.core import Dense, Activation\n'), ((2843, 2883), 'keras.layers.Convolution1D', 'Convolution1D', (['(64)', '(3)'], {'border_mode': '"""same"""'}), "(64, 3, border_mode='same')\n", (2856, 2883), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((2895, 2907), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (2902, 2907), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((2919, 2937), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2929, 2937), False, 'from keras.layers.core import Dense, Activation\n'), ((2949, 2989), 'keras.layers.Convolution1D', 'Convolution1D', (['(32)', '(3)'], {'border_mode': '"""same"""'}), "(32, 3, border_mode='same')\n", (2962, 2989), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((3001, 3013), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (3008, 3013), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((3025, 3043), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3035, 3043), False, 'from keras.layers.core import Dense, Activation\n'), ((3055, 3064), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3062, 3064), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((3076, 3088), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (3083, 3088), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((3100, 3110), 'keras.layers.core.Dense', 'Dense', (['(256)'], {}), '(256)\n', (3105, 3110), False, 'from keras.layers.core import Dense, Activation\n'), ((3122, 3140), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3132, 3140), False, 'from keras.layers.core import Dense, Activation\n'), ((3153, 3165), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (3160, 3165), False, 'from keras.layers import LSTM, Input, Flatten, Merge, Embedding, Convolution1D, Dropout\n'), ((3177, 3185), 'keras.layers.core.Dense', 'Dense', (['(4)'], {}), '(4)\n', (3182, 3185), False, 'from keras.layers.core import Dense, Activation\n'), ((3197, 3218), 'keras.layers.core.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (3207, 3218), False, 'from keras.layers.core import Dense, Activation\n'), ((696, 707), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (705, 707), False, 'import os\n'), ((1680, 1719), 'numpy.asarray', 'np.asarray', (['values[1:]'], {'dtype': '"""float32"""'}), "(values[1:], dtype='float32')\n", (1690, 1719), True, 'import numpy as np\n'), ((2155, 2194), 'numpy.sum', 'np.sum', (['g_word_embedding_matrix'], {'axis': '(1)'}), '(g_word_embedding_matrix, axis=1)\n', (2161, 2194), True, 'import numpy as np\n')] |
import numpy as np
from deep_utils.utils.box_utils.boxes import Point
def resize(img, dsize, in_source='Numpy', mode='cv2', interpolation=None):
mode = 'cv2' if mode is None else mode
if mode == 'cv2':
dsize = Point.point2point(dsize, in_source=in_source, to_source=Point.PointSource.CV)
new_img = cv2_resize(img, dsize=dsize, interpolation=interpolation)
elif mode.lower() == 'pil':
from PIL import Image
img = img if isinstance(img, Image.Image) else Image.fromarray(img)
new_img = img.resize(dsize, interpolation)
else:
raise ValueError(f'{mode} is not supported, supported types: cv2, ')
return new_img
def cv2_resize(img, dsize, dst=None, fx=None, fy=None, interpolation=None):
import cv2
if len(img.shape) == 3:
return cv2.resize(img, dsize, dst, fx, fy, interpolation)
elif len(img.shape) == 4:
return np.array([cv2.resize(im, dsize, dst, fx, fy, interpolation) for im in img])
def get_img_shape(img):
if len(img.shape) == 4:
return img.shape
elif len(img.shape) == 3:
return np.expand_dims(img, axis=0).shape
else:
raise Exception(f'shape: {img.shape} is not an image')
def resize_ratio(img, size: int, pad: bool = False, mode: str = 'cv2', pad_val: int = 0, return_pad: bool = False):
"""
Resize an image while keeping aspect-ratio
Args:
img: input image
size: max-size
mode: cv2 or pil
pad: Pad the smaller size to become equal to the bigger one.
pad_val: Value for padding
return_pad: returns pad values for further processes, default is false. return: image, (h_top, h_bottom, w_left, w_right)
Returns: resized image
"""
if mode == 'cv2':
import cv2
import math
h, w = img.shape[:2]
ratio = h / w
if ratio > 1:
h = size
w = int(size / ratio)
h_top, h_bottom = 0, 0
w_pad = (size - w)
w_left, w_right = math.ceil(w_pad / 2), w_pad // 2
elif ratio < 1:
h = int(size * ratio)
w = size
w_left, w_right = 0, 0
h_pad = (size - h)
h_top, h_bottom = math.ceil(h_pad / 2), h_pad // 2
else:
h, w = size, size
w_left, w_right, h_bottom, h_top = 0, 0, 0, 0
image = cv2.resize(img, (w, h), interpolation=cv2.INTER_NEAREST)
if pad:
image = cv2.copyMakeBorder(image, h_top, h_bottom, w_left, w_right, cv2.BORDER_CONSTANT, value=pad_val)
if return_pad:
return image, (h_top, h_bottom, w_left, w_right)
return image
else:
raise ValueError(f"Requested mode: {mode} is not supported!")
def resize_save_aspect_ratio(img, size):
from PIL import Image
from torchvision import transforms
import torch.nn.functional as F
w, h = img.size
ratio = h / w
if ratio > 1:
h = size
w = int(size / ratio)
elif ratio < 1:
h = int(size * ratio)
w = size
else:
return img.resize((size, size), Image.NEAREST)
image = img.resize((w, h), Image.NEAREST)
im = transforms.ToTensor()(image)
val = h - w
if val < 0:
a = 0
b = int(-val / 2)
else:
a = int(val / 2)
b = 0
result = F.pad(input=im, pad=(a, a, b, b))
image = transforms.ToPILImage()(result)
return image
if __name__ == '__main__':
import cv2
img = cv2.imread("/home/ai/projects/Irancel-Service/hard_samples/0013903470.jpg")
print(f"[INFO] input shape: {img.shape}")
img = resize_ratio(img, 900)
print(f"[INFO] output shape: {img.shape}")
cv2.imshow('', img)
cv2.waitKey(0)
| [
"deep_utils.utils.box_utils.boxes.Point.point2point",
"PIL.Image.fromarray",
"math.ceil",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.ToTensor",
"cv2.copyMakeBorder",
"cv2.imshow",
"numpy.expand_dims",
"torch.nn.functional.pad",
"cv2.resize",
"cv2.waitKey",
"cv2.imread"
] | [((3369, 3402), 'torch.nn.functional.pad', 'F.pad', ([], {'input': 'im', 'pad': '(a, a, b, b)'}), '(input=im, pad=(a, a, b, b))\n', (3374, 3402), True, 'import torch.nn.functional as F\n'), ((3520, 3595), 'cv2.imread', 'cv2.imread', (['"""/home/ai/projects/Irancel-Service/hard_samples/0013903470.jpg"""'], {}), "('/home/ai/projects/Irancel-Service/hard_samples/0013903470.jpg')\n", (3530, 3595), False, 'import cv2\n'), ((3726, 3745), 'cv2.imshow', 'cv2.imshow', (['""""""', 'img'], {}), "('', img)\n", (3736, 3745), False, 'import cv2\n'), ((3750, 3764), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (3761, 3764), False, 'import cv2\n'), ((228, 305), 'deep_utils.utils.box_utils.boxes.Point.point2point', 'Point.point2point', (['dsize'], {'in_source': 'in_source', 'to_source': 'Point.PointSource.CV'}), '(dsize, in_source=in_source, to_source=Point.PointSource.CV)\n', (245, 305), False, 'from deep_utils.utils.box_utils.boxes import Point\n'), ((813, 863), 'cv2.resize', 'cv2.resize', (['img', 'dsize', 'dst', 'fx', 'fy', 'interpolation'], {}), '(img, dsize, dst, fx, fy, interpolation)\n', (823, 863), False, 'import cv2\n'), ((2387, 2443), 'cv2.resize', 'cv2.resize', (['img', '(w, h)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(img, (w, h), interpolation=cv2.INTER_NEAREST)\n', (2397, 2443), False, 'import cv2\n'), ((3205, 3226), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3224, 3226), False, 'from torchvision import transforms\n'), ((3415, 3438), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (3436, 3438), False, 'from torchvision import transforms\n'), ((2480, 2580), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['image', 'h_top', 'h_bottom', 'w_left', 'w_right', 'cv2.BORDER_CONSTANT'], {'value': 'pad_val'}), '(image, h_top, h_bottom, w_left, w_right, cv2.\n BORDER_CONSTANT, value=pad_val)\n', (2498, 2580), False, 'import cv2\n'), ((499, 519), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (514, 519), False, 'from PIL import Image\n'), ((1109, 1136), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (1123, 1136), True, 'import numpy as np\n'), ((2028, 2048), 'math.ceil', 'math.ceil', (['(w_pad / 2)'], {}), '(w_pad / 2)\n', (2037, 2048), False, 'import math\n'), ((919, 968), 'cv2.resize', 'cv2.resize', (['im', 'dsize', 'dst', 'fx', 'fy', 'interpolation'], {}), '(im, dsize, dst, fx, fy, interpolation)\n', (929, 968), False, 'import cv2\n'), ((2236, 2256), 'math.ceil', 'math.ceil', (['(h_pad / 2)'], {}), '(h_pad / 2)\n', (2245, 2256), False, 'import math\n')] |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from warnings import warn
from iminuit.iminuit_warnings import InitialParamWarning
from iminuit import util as mutil
import numpy as np
def pedantic(self, parameters, kwds, errordef):
def w(msg):
warn(msg, InitialParamWarning, stacklevel=3)
for vn in parameters:
if vn not in kwds:
w('Parameter %s does not have initial value. Assume 0.' % vn)
if 'error_' + vn not in kwds and 'fix_' + mutil.param_name(vn) not in kwds:
w('Parameter %s is floating but does not have initial step size. Assume 1.' % vn)
for vlim in mutil.extract_limit(kwds):
if mutil.param_name(vlim) not in parameters:
w('%s is given. But there is no parameter %s. Ignore.' % (vlim, mutil.param_name(vlim)))
for vfix in mutil.extract_fix(kwds):
if mutil.param_name(vfix) not in parameters:
w('%s is given. But there is no parameter %s. Ignore.' % (vfix, mutil.param_name(vfix)))
for verr in mutil.extract_error(kwds):
if mutil.param_name(verr) not in parameters:
w('%s float. But there is no parameter %s. Ignore.' % (verr, mutil.param_name(verr)))
if errordef is None:
w('errordef is not given. Default to 1.')
def draw_profile(self, vname, x, y, s=None, band=True, text=True):
from matplotlib import pyplot as plt
x = np.array(x)
y = np.array(y)
if s is not None:
s = np.array(s, dtype=bool)
x = x[s]
y = y[s]
plt.plot(x, y)
plt.grid(True)
plt.xlabel(vname)
plt.ylabel('FCN')
try:
minpos = np.argmin(y)
# Scan to the right of minimum until greater than min + errordef.
# Note: We need to find the *first* crossing of up, right from the
# minimum, because there can be several. If the loop is replaced by
# some numpy calls, make sure that this property is retained.
yup = self.errordef + y[minpos]
best = float("infinity")
for i in range(minpos, len(y)):
z = abs(y[i] - yup)
if z < best:
rightpos = i
best = z
else:
break
else:
raise ValueError("right edge not found")
# Scan to the left of minimum until greater than min + errordef.
best = float("infinity")
for i in range(minpos, 0, -1):
z = abs(y[i] - yup)
if z < best:
leftpos = i
best = z
else:
break
else:
raise ValueError("left edge not found")
plt.plot([x[leftpos], x[minpos], x[rightpos]],
[y[leftpos], y[minpos], y[rightpos]], 'o')
if band:
plt.axvspan(x[leftpos], x[rightpos], facecolor='g', alpha=0.5)
if text:
plt.title('%s = %.3g - %.3g + %.3g (scan)' % (vname, x[minpos],
x[minpos] - x[leftpos],
x[rightpos] - x[minpos]),
fontsize="large")
except ValueError:
warn(RuntimeWarning('band and text is requested but '
'the bound is too narrow.'))
return x, y, s
def draw_contour(self, x, y, bins=20, bound=2, args=None, show_sigma=False):
from matplotlib import pyplot as plt
vx, vy, vz = self.contour(x, y, bins, bound, args, subtract_min=True)
v = [self.errordef * ((i + 1) ** 2) for i in range(bound)]
CS = plt.contour(vx, vy, vz, v, colors=['b', 'k', 'r'])
if not show_sigma:
plt.clabel(CS, v)
else:
tmp = dict((vv, r'%i $\sigma$' % (i + 1)) for i, vv in enumerate(v))
plt.clabel(CS, v, fmt=tmp, fontsize=16)
plt.xlabel(x)
plt.ylabel(y)
plt.axhline(self.values[y], color='k', ls='--')
plt.axvline(self.values[x], color='k', ls='--')
plt.grid(True)
return vx, vy, vz
def draw_mncontour(self, x, y, nsigma=2, numpoints=20):
from matplotlib import pyplot as plt
from matplotlib.contour import ContourSet
c_val = []
c_pts = []
for sigma in range(1, nsigma + 1):
pts = self.mncontour(x, y, numpoints, sigma)[2]
# close curve
pts.append(pts[0])
c_val.append(sigma)
c_pts.append([pts]) # level can have more than one contour in mpl
cs = ContourSet(plt.gca(), c_val, c_pts)
plt.clabel(cs, inline=1, fontsize=10)
plt.xlabel(x)
plt.ylabel(y)
return cs
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.axvspan",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.clabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.axhline",
"numpy.array",
"matplotlib.pyplot.contour",
"num... | [((685, 710), 'iminuit.util.extract_limit', 'mutil.extract_limit', (['kwds'], {}), '(kwds)\n', (704, 710), True, 'from iminuit import util as mutil\n'), ((882, 905), 'iminuit.util.extract_fix', 'mutil.extract_fix', (['kwds'], {}), '(kwds)\n', (899, 905), True, 'from iminuit import util as mutil\n'), ((1077, 1102), 'iminuit.util.extract_error', 'mutil.extract_error', (['kwds'], {}), '(kwds)\n', (1096, 1102), True, 'from iminuit import util as mutil\n'), ((1449, 1460), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1457, 1460), True, 'import numpy as np\n'), ((1469, 1480), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1477, 1480), True, 'import numpy as np\n'), ((1578, 1592), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (1586, 1592), True, 'from matplotlib import pyplot as plt\n'), ((1597, 1611), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (1605, 1611), True, 'from matplotlib import pyplot as plt\n'), ((1616, 1633), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['vname'], {}), '(vname)\n', (1626, 1633), True, 'from matplotlib import pyplot as plt\n'), ((1638, 1655), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""FCN"""'], {}), "('FCN')\n", (1648, 1655), True, 'from matplotlib import pyplot as plt\n'), ((3624, 3674), 'matplotlib.pyplot.contour', 'plt.contour', (['vx', 'vy', 'vz', 'v'], {'colors': "['b', 'k', 'r']"}), "(vx, vy, vz, v, colors=['b', 'k', 'r'])\n", (3635, 3674), True, 'from matplotlib import pyplot as plt\n'), ((3863, 3876), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x'], {}), '(x)\n', (3873, 3876), True, 'from matplotlib import pyplot as plt\n'), ((3881, 3894), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y'], {}), '(y)\n', (3891, 3894), True, 'from matplotlib import pyplot as plt\n'), ((3899, 3946), 'matplotlib.pyplot.axhline', 'plt.axhline', (['self.values[y]'], {'color': '"""k"""', 'ls': '"""--"""'}), "(self.values[y], color='k', ls='--')\n", (3910, 3946), True, 'from matplotlib import pyplot as plt\n'), ((3951, 3998), 'matplotlib.pyplot.axvline', 'plt.axvline', (['self.values[x]'], {'color': '"""k"""', 'ls': '"""--"""'}), "(self.values[x], color='k', ls='--')\n", (3962, 3998), True, 'from matplotlib import pyplot as plt\n'), ((4003, 4017), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (4011, 4017), True, 'from matplotlib import pyplot as plt\n'), ((4512, 4549), 'matplotlib.pyplot.clabel', 'plt.clabel', (['cs'], {'inline': '(1)', 'fontsize': '(10)'}), '(cs, inline=1, fontsize=10)\n', (4522, 4549), True, 'from matplotlib import pyplot as plt\n'), ((4554, 4567), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x'], {}), '(x)\n', (4564, 4567), True, 'from matplotlib import pyplot as plt\n'), ((4572, 4585), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y'], {}), '(y)\n', (4582, 4585), True, 'from matplotlib import pyplot as plt\n'), ((319, 363), 'warnings.warn', 'warn', (['msg', 'InitialParamWarning'], {'stacklevel': '(3)'}), '(msg, InitialParamWarning, stacklevel=3)\n', (323, 363), False, 'from warnings import warn\n'), ((1515, 1538), 'numpy.array', 'np.array', (['s'], {'dtype': 'bool'}), '(s, dtype=bool)\n', (1523, 1538), True, 'import numpy as np\n'), ((1683, 1695), 'numpy.argmin', 'np.argmin', (['y'], {}), '(y)\n', (1692, 1695), True, 'import numpy as np\n'), ((2694, 2788), 'matplotlib.pyplot.plot', 'plt.plot', (['[x[leftpos], x[minpos], x[rightpos]]', '[y[leftpos], y[minpos], y[rightpos]]', '"""o"""'], {}), "([x[leftpos], x[minpos], x[rightpos]], [y[leftpos], y[minpos], y[\n rightpos]], 'o')\n", (2702, 2788), True, 'from matplotlib import pyplot as plt\n'), ((3706, 3723), 'matplotlib.pyplot.clabel', 'plt.clabel', (['CS', 'v'], {}), '(CS, v)\n', (3716, 3723), True, 'from matplotlib import pyplot as plt\n'), ((3819, 3858), 'matplotlib.pyplot.clabel', 'plt.clabel', (['CS', 'v'], {'fmt': 'tmp', 'fontsize': '(16)'}), '(CS, v, fmt=tmp, fontsize=16)\n', (3829, 3858), True, 'from matplotlib import pyplot as plt\n'), ((4483, 4492), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (4490, 4492), True, 'from matplotlib import pyplot as plt\n'), ((723, 745), 'iminuit.util.param_name', 'mutil.param_name', (['vlim'], {}), '(vlim)\n', (739, 745), True, 'from iminuit import util as mutil\n'), ((918, 940), 'iminuit.util.param_name', 'mutil.param_name', (['vfix'], {}), '(vfix)\n', (934, 940), True, 'from iminuit import util as mutil\n'), ((1115, 1137), 'iminuit.util.param_name', 'mutil.param_name', (['verr'], {}), '(verr)\n', (1131, 1137), True, 'from iminuit import util as mutil\n'), ((2831, 2893), 'matplotlib.pyplot.axvspan', 'plt.axvspan', (['x[leftpos]', 'x[rightpos]'], {'facecolor': '"""g"""', 'alpha': '(0.5)'}), "(x[leftpos], x[rightpos], facecolor='g', alpha=0.5)\n", (2842, 2893), True, 'from matplotlib import pyplot as plt\n'), ((2924, 3059), 'matplotlib.pyplot.title', 'plt.title', (["('%s = %.3g - %.3g + %.3g (scan)' % (vname, x[minpos], x[minpos] - x[\n leftpos], x[rightpos] - x[minpos]))"], {'fontsize': '"""large"""'}), "('%s = %.3g - %.3g + %.3g (scan)' % (vname, x[minpos], x[minpos] -\n x[leftpos], x[rightpos] - x[minpos]), fontsize='large')\n", (2933, 3059), True, 'from matplotlib import pyplot as plt\n'), ((541, 561), 'iminuit.util.param_name', 'mutil.param_name', (['vn'], {}), '(vn)\n', (557, 561), True, 'from iminuit import util as mutil\n'), ((841, 863), 'iminuit.util.param_name', 'mutil.param_name', (['vlim'], {}), '(vlim)\n', (857, 863), True, 'from iminuit import util as mutil\n'), ((1036, 1058), 'iminuit.util.param_name', 'mutil.param_name', (['vfix'], {}), '(vfix)\n', (1052, 1058), True, 'from iminuit import util as mutil\n'), ((1230, 1252), 'iminuit.util.param_name', 'mutil.param_name', (['verr'], {}), '(verr)\n', (1246, 1252), True, 'from iminuit import util as mutil\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 15:38:14 2019
@author: marcelo
"""
try:
from numpy import array, transpose
import pandas as pd
from sklearn.model_selection import cross_val_score, cross_validate
from time import time
from sklearn.svm import SVC
except Exception as e:
print(e)
raise Exception('Alguns módulos não foram instalados...')
class MyGridSearch:
def __init__(self, model, grid_params, cv, metrics):
self.model = model
self.grid_params = grid_params
self.cv = cv
self.metrics = metrics
def fit(self, x_train, y_train):
results = []
params = []
count = 0
for kernel in self.grid_params['kernel']:
for c in self.grid_params['C']:
if kernel == 'linear':
self.model.set_params(C=c, kernel=kernel)
scores = cross_validate(self.model, x_train, y_train, cv=self.cv, \
scoring=self.metrics, n_jobs=-1, verbose=1, return_train_score=False)
param = {
'kernel':kernel,
'c': c
}
results.append(scores)
params.append(param)
count += 1
elif kernel == 'poly':
for gamma in self.grid_params['gamma']:
for degree in self.grid_params['degree']:
self.model.set_params(C=c, kernel=kernel, gamma=gamma, \
degree=degree)
scores = cross_validate(self.model, x_train, y_train, cv=self.cv, \
scoring=self.metrics, n_jobs=-1, verbose=1, return_train_score=False)
param = {
'kernel':kernel,
'c': c,
'gamma':gamma,
'degree':degree
}
results.append(scores)
params.append(param)
count += 1
elif kernel == 'rbf':
for gamma in self.grid_params['gamma']:
self.model.set_params(C=c, kernel=kernel, gamma=gamma)
scores = cross_validate(self.model, x_train, y_train, cv=self.cv, \
scoring=self.metrics, n_jobs=-1, verbose=1, return_train_score=False)
param={
'kernel':kernel,
'c':c,
'gamma':gamma
}
results.append(scores)
params.append(param)
count += 1
else: #'sigmoid'
for gamma in self.grid_params['gamma']:
self.model.set_params(C=c, kernel=kernel, gamma=gamma)
scores = cross_validate(self.model, x_train, y_train, cv=self.cv, \
scoring=self.metrics, n_jobs=-1, verbose=1, return_train_score=False)
param={
'kernel':kernel,
'c':c,
'gamma':gamma
}
results.append(scores)
params.append(param)
count += 1
print('Quantidade de modelos treinados: {}'.format(count))
return results, params
def __str__(self,):
return str(self.grid_params)
def main():
svm = SVC()
metrics = ['f1_macro', 'accuracy', 'precision_macro','recall_macro']
grid_params = {
'C': [1, 10, 50, 100],
'kernel': ['rbf', 'linear', 'poly', 'sigmoid'],
'gamma': [0.0001, 0.00001, 0.000001],
'degree': [2, 3]
}
#Testando...
gs = MyGridSearch(model=svm, grid_params=grid_params, cv=2, metrics=metrics)
x = array([[2,1,2,2], [3,2,4,3], [5,4,4,3], [3,4,6,6], [6,5,5,4], [3,2,8,7], [5,3,4,5], [6,2,1,7], [2,1,2,1], [8,4,4,3], [6,4,3,2], [4,3,4,3]])
y = array([1,1,1,1,2,2,2,2,3,3,3,3])
results, params = gs.fit(x, y)
df_results = pd.DataFrame(results)
df_params = pd.DataFrame(params)
df_conc = pd.concat([df_results, df_params], axis=1)
df_conc.to_csv('teste.csv')
print(results)
if __name__ == '__main__':
main() | [
"sklearn.model_selection.cross_validate",
"numpy.array",
"pandas.DataFrame",
"pandas.concat",
"sklearn.svm.SVC"
] | [((3866, 3871), 'sklearn.svm.SVC', 'SVC', ([], {}), '()\n', (3869, 3871), False, 'from sklearn.svm import SVC\n'), ((4239, 4423), 'numpy.array', 'array', (['[[2, 1, 2, 2], [3, 2, 4, 3], [5, 4, 4, 3], [3, 4, 6, 6], [6, 5, 5, 4], [3, \n 2, 8, 7], [5, 3, 4, 5], [6, 2, 1, 7], [2, 1, 2, 1], [8, 4, 4, 3], [6, 4,\n 3, 2], [4, 3, 4, 3]]'], {}), '([[2, 1, 2, 2], [3, 2, 4, 3], [5, 4, 4, 3], [3, 4, 6, 6], [6, 5, 5, 4],\n [3, 2, 8, 7], [5, 3, 4, 5], [6, 2, 1, 7], [2, 1, 2, 1], [8, 4, 4, 3], [\n 6, 4, 3, 2], [4, 3, 4, 3]])\n', (4244, 4423), False, 'from numpy import array, transpose\n'), ((4387, 4430), 'numpy.array', 'array', (['[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]'], {}), '([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])\n', (4392, 4430), False, 'from numpy import array, transpose\n'), ((4474, 4495), 'pandas.DataFrame', 'pd.DataFrame', (['results'], {}), '(results)\n', (4486, 4495), True, 'import pandas as pd\n'), ((4512, 4532), 'pandas.DataFrame', 'pd.DataFrame', (['params'], {}), '(params)\n', (4524, 4532), True, 'import pandas as pd\n'), ((4547, 4589), 'pandas.concat', 'pd.concat', (['[df_results, df_params]'], {'axis': '(1)'}), '([df_results, df_params], axis=1)\n', (4556, 4589), True, 'import pandas as pd\n'), ((940, 1071), 'sklearn.model_selection.cross_validate', 'cross_validate', (['self.model', 'x_train', 'y_train'], {'cv': 'self.cv', 'scoring': 'self.metrics', 'n_jobs': '(-1)', 'verbose': '(1)', 'return_train_score': '(False)'}), '(self.model, x_train, y_train, cv=self.cv, scoring=self.\n metrics, n_jobs=-1, verbose=1, return_train_score=False)\n', (954, 1071), False, 'from sklearn.model_selection import cross_val_score, cross_validate\n'), ((1733, 1864), 'sklearn.model_selection.cross_validate', 'cross_validate', (['self.model', 'x_train', 'y_train'], {'cv': 'self.cv', 'scoring': 'self.metrics', 'n_jobs': '(-1)', 'verbose': '(1)', 'return_train_score': '(False)'}), '(self.model, x_train, y_train, cv=self.cv, scoring=self.\n metrics, n_jobs=-1, verbose=1, return_train_score=False)\n', (1747, 1864), False, 'from sklearn.model_selection import cross_val_score, cross_validate\n'), ((2500, 2631), 'sklearn.model_selection.cross_validate', 'cross_validate', (['self.model', 'x_train', 'y_train'], {'cv': 'self.cv', 'scoring': 'self.metrics', 'n_jobs': '(-1)', 'verbose': '(1)', 'return_train_score': '(False)'}), '(self.model, x_train, y_train, cv=self.cv, scoring=self.\n metrics, n_jobs=-1, verbose=1, return_train_score=False)\n', (2514, 2631), False, 'from sklearn.model_selection import cross_val_score, cross_validate\n'), ((3204, 3335), 'sklearn.model_selection.cross_validate', 'cross_validate', (['self.model', 'x_train', 'y_train'], {'cv': 'self.cv', 'scoring': 'self.metrics', 'n_jobs': '(-1)', 'verbose': '(1)', 'return_train_score': '(False)'}), '(self.model, x_train, y_train, cv=self.cv, scoring=self.\n metrics, n_jobs=-1, verbose=1, return_train_score=False)\n', (3218, 3335), False, 'from sklearn.model_selection import cross_val_score, cross_validate\n')] |
# Authors: CommPy contributors
# License: BSD 3-Clause
"""
==================================================
Sequences (:mod:`commpy.sequences`)
==================================================
.. autosummary::
:toctree: generated/
pnsequence -- PN Sequence Generator.
zcsequence -- Zadoff-Chu (ZC) Sequence Generator.
"""
__all__ = ['pnsequence', 'zcsequence']
import numpy as np
from numpy import empty, exp, pi, arange, int8, fromiter, sum
def pnsequence(pn_order, pn_seed, pn_mask, seq_length):
"""
Generate a PN (Pseudo-Noise) sequence using a Linear Feedback Shift Register (LFSR).
Seed and mask are ordered so that:
- seed[-1] will be the first output
- the new bit computed as :math:`sum(shift_register & mask) % 2` is inserted in shift[0]
Parameters
----------
pn_order : int
Number of delay elements used in the LFSR.
pn_seed : iterable providing 0's and 1's
Seed for the initialization of the LFSR delay elements.
The length of this string must be equal to 'pn_order'.
pn_mask : iterable providing 0's and 1's
Mask representing which delay elements contribute to the feedback
in the LFSR. The length of this string must be equal to 'pn_order'.
seq_length : int
Length of the PN sequence to be generated. Usually (2^pn_order - 1)
Returns
-------
pnseq : 1D ndarray of ints
PN sequence generated.
Raises
------
ValueError
If the pn_order is equal to the length of the strings pn_seed and pn_mask.
"""
# Check if pn_order is equal to the length of the strings 'pn_seed' and 'pn_mask'
if len(pn_seed) != pn_order:
raise ValueError('pn_seed has not the same length as pn_order')
if len(pn_mask) != pn_order:
raise ValueError('pn_mask has not the same length as pn_order')
# Pre-allocate memory for output
pnseq = empty(seq_length, int8)
# Convert input as array
sr = fromiter(pn_seed, int8, pn_order)
mask = fromiter(pn_mask, int8, pn_order)
for i in range(seq_length):
pnseq[i] = sr[-1]
new_bit = sum(sr & mask) % 2
sr[1:] = sr[:-1]
sr[0] = new_bit
return pnseq
def zcsequence(u, seq_length, q=0):
"""
Generate a Zadoff-Chu (ZC) sequence.
Parameters
----------
u : int
Root index of the the ZC sequence: u>0.
seq_length : int
Length of the sequence to be generated. Usually a prime number:
u<seq_length, greatest-common-denominator(u,seq_length)=1.
q : int
Cyclic shift of the sequence (default 0).
Returns
-------
zcseq : 1D ndarray of complex floats
ZC sequence generated.
"""
for el in [u,seq_length,q]:
if not float(el).is_integer():
raise ValueError('{} is not an integer'.format(el))
if u<=0:
raise ValueError('u is not stricly positive')
if u>=seq_length:
raise ValueError('u is not stricly smaller than seq_length')
if np.gcd(u,seq_length)!=1:
raise ValueError('the greatest common denominator of u and seq_length is not 1')
cf = seq_length%2
n = np.arange(seq_length)
zcseq = np.exp( -1j * np.pi * u * n * (n+cf+2.*q) / seq_length)
return zcseq
| [
"numpy.fromiter",
"numpy.exp",
"numpy.sum",
"numpy.empty",
"numpy.gcd",
"numpy.arange"
] | [((1949, 1972), 'numpy.empty', 'empty', (['seq_length', 'int8'], {}), '(seq_length, int8)\n', (1954, 1972), False, 'from numpy import empty, exp, pi, arange, int8, fromiter, sum\n'), ((2012, 2045), 'numpy.fromiter', 'fromiter', (['pn_seed', 'int8', 'pn_order'], {}), '(pn_seed, int8, pn_order)\n', (2020, 2045), False, 'from numpy import empty, exp, pi, arange, int8, fromiter, sum\n'), ((2057, 2090), 'numpy.fromiter', 'fromiter', (['pn_mask', 'int8', 'pn_order'], {}), '(pn_mask, int8, pn_order)\n', (2065, 2090), False, 'from numpy import empty, exp, pi, arange, int8, fromiter, sum\n'), ((3206, 3227), 'numpy.arange', 'np.arange', (['seq_length'], {}), '(seq_length)\n', (3215, 3227), True, 'import numpy as np\n'), ((3240, 3303), 'numpy.exp', 'np.exp', (['(-1.0j * np.pi * u * n * (n + cf + 2.0 * q) / seq_length)'], {}), '(-1.0j * np.pi * u * n * (n + cf + 2.0 * q) / seq_length)\n', (3246, 3303), True, 'import numpy as np\n'), ((3061, 3082), 'numpy.gcd', 'np.gcd', (['u', 'seq_length'], {}), '(u, seq_length)\n', (3067, 3082), True, 'import numpy as np\n'), ((2168, 2182), 'numpy.sum', 'sum', (['(sr & mask)'], {}), '(sr & mask)\n', (2171, 2182), False, 'from numpy import empty, exp, pi, arange, int8, fromiter, sum\n')] |
import cv2
import numpy as np
import os
import csv
import sys
from PIL import Image
import random
minValue = 70
skinkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
low_range = np.array([0, 70, 100])
upper_range = np.array([20, 200, 255])
# cv2.imshow("final",img)
# cv2.waitKey(0)
kernel = np.ones((5, 5), np.uint8)
def preprocess(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# gray = cv2.bilateralFilter(gray, 11, 17, 17)
# edged = cv2.Canny(gray, 30, 90)
# th3 = cv2.adaptiveThreshold(
# blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, thresh1 = cv2.threshold(
blur, 70, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
return thresh1
# th3 = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,11,2)
# ret, res = cv2.threshold(th3, minValue, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# cv2.imshow("final",blur)
# cv2.waitKey(0)
# hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# #Apply skin color range
# mask = cv2.inRange(hsv, low_range, upper_range)
# mask = cv2.erode(mask, skinkernel, iterations = 1)
# mask = cv2.dilate(mask, skinkernel, iterations = 1)
# #blur
# mask = cv2.GaussianBlur(mask, (15,15), 1)
# #cv2.imshow("Blur", mask)
# #bitwise and mask original frame
# res = cv2.bitwise_and(img, img, mask = mask)
# # color to grayscale
# res = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)
# cv2.imshow("final",res)
# cv2.waitKey(0)
# Useful function
def createFileList(myDir, format='.jpg'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=False):
for name in files:
if name.endswith(format):
fullName = os.path.join(root, name)
fileList.append(fullName)
return fileList
# load the original image
myFileList = createFileList('Dataset/ARROW_LEFT')
val = []
val.append("label")
for i in range(1, 2501):
val.append("pixel"+str(i))
with open("train.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(val)
with open("validation.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(val)
with open("test.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(val)
train = []
test = []
validation = []
myFileList = createFileList('Dataset/ARROW_LEFT')
ctr = 0
for file in myFileList:
print(file)
img_file = cv2.imread(file)
width, height = 50, 50
img_grey = preprocess(img_file)
value = img_grey.flatten()
ctr = ctr + 1
value = np.insert(value, 0, 1)
if(ctr <= 6):
print("Train")
train.append(value)
elif(ctr <= 8):
print('Validation')
validation.append(value)
else:
print("Test")
test.append(value)
if(ctr == 10):
ctr = 0
myFileList = createFileList('Dataset/ARROW_RIGHT')
ctr = 0
for file in myFileList:
print(file)
img_file = cv2.imread(file)
width, height = 50, 50
img_grey = preprocess(img_file)
value = img_grey.flatten()
ctr = ctr + 1
value = np.insert(value, 0, 2)
if(ctr <= 6):
print("Train")
train.append(value)
elif(ctr <= 8):
print("Validation")
validation.append(value)
else:
print("Test")
test.append(value)
if(ctr == 10):
ctr = 0
myFileList = createFileList('Dataset/STOP')
ctr = 0
for file in myFileList:
print(file)
img_file = cv2.imread(file)
width, height = 50, 50
img_grey = preprocess(img_file)
value = img_grey.flatten()
ctr = ctr + 1
value = np.insert(value, 0, 0)
if(ctr <= 6):
print("Train")
train.append(value)
elif(ctr <= 8):
print("Validation")
validation.append(value)
else:
print("Test")
test.append(value)
if(ctr == 10):
ctr = 0
myFileList = createFileList('Dataset/PLAIN')
ctr = 0
for file in myFileList:
print(file)
img_file = cv2.imread(file)
width, height = 50, 50
img_grey = preprocess(img_file)
value = img_grey.flatten()
ctr = ctr + 1
value = np.insert(value, 0, 3)
if(ctr <= 6):
print("Train")
train.append(value)
elif(ctr <= 8):
print("Validation")
validation.append(value)
else:
print("Test")
test.append(value)
if(ctr == 10):
ctr = 0
random.shuffle(train)
random.shuffle(validation)
random.shuffle(test)
print('Train')
for i in range(0, len(train)):
with open("train.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(train[i])
print('VALID')
for i in range(0, len(validation)):
with open("validation.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(validation[i])
print('TEST')
for i in range(0, len(test)):
with open("test.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(test[i])
| [
"numpy.insert",
"random.shuffle",
"numpy.ones",
"cv2.threshold",
"csv.writer",
"os.path.join",
"numpy.array",
"cv2.cvtColor",
"cv2.GaussianBlur",
"cv2.getStructuringElement",
"os.walk",
"cv2.imread"
] | [((126, 178), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(5, 5)'], {}), '(cv2.MORPH_ELLIPSE, (5, 5))\n', (151, 178), False, 'import cv2\n'), ((191, 213), 'numpy.array', 'np.array', (['[0, 70, 100]'], {}), '([0, 70, 100])\n', (199, 213), True, 'import numpy as np\n'), ((228, 252), 'numpy.array', 'np.array', (['[20, 200, 255]'], {}), '([20, 200, 255])\n', (236, 252), True, 'import numpy as np\n'), ((307, 332), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (314, 332), True, 'import numpy as np\n'), ((4427, 4448), 'random.shuffle', 'random.shuffle', (['train'], {}), '(train)\n', (4441, 4448), False, 'import random\n'), ((4449, 4475), 'random.shuffle', 'random.shuffle', (['validation'], {}), '(validation)\n', (4463, 4475), False, 'import random\n'), ((4476, 4496), 'random.shuffle', 'random.shuffle', (['test'], {}), '(test)\n', (4490, 4496), False, 'import random\n'), ((367, 404), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (379, 404), False, 'import cv2\n'), ((416, 449), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['gray', '(5, 5)', '(0)'], {}), '(gray, (5, 5), 0)\n', (432, 449), False, 'import cv2\n'), ((676, 745), 'cv2.threshold', 'cv2.threshold', (['blur', '(70)', '(255)', '(cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)'], {}), '(blur, 70, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n', (689, 745), False, 'import cv2\n'), ((1630, 1659), 'os.walk', 'os.walk', (['myDir'], {'topdown': '(False)'}), '(myDir, topdown=False)\n', (1637, 1659), False, 'import os\n'), ((2052, 2065), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2062, 2065), False, 'import csv\n'), ((2144, 2157), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2154, 2157), False, 'import csv\n'), ((2230, 2243), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2240, 2243), False, 'import csv\n'), ((2422, 2438), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (2432, 2438), False, 'import cv2\n'), ((2563, 2585), 'numpy.insert', 'np.insert', (['value', '(0)', '(1)'], {}), '(value, 0, 1)\n', (2572, 2585), True, 'import numpy as np\n'), ((2954, 2970), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (2964, 2970), False, 'import cv2\n'), ((3096, 3118), 'numpy.insert', 'np.insert', (['value', '(0)', '(2)'], {}), '(value, 0, 2)\n', (3105, 3118), True, 'import numpy as np\n'), ((3481, 3497), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (3491, 3497), False, 'import cv2\n'), ((3623, 3645), 'numpy.insert', 'np.insert', (['value', '(0)', '(0)'], {}), '(value, 0, 0)\n', (3632, 3645), True, 'import numpy as np\n'), ((4008, 4024), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (4018, 4024), False, 'import cv2\n'), ((4150, 4172), 'numpy.insert', 'np.insert', (['value', '(0)', '(3)'], {}), '(value, 0, 3)\n', (4159, 4172), True, 'import numpy as np\n'), ((4599, 4612), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (4609, 4612), False, 'import csv\n'), ((4759, 4772), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (4769, 4772), False, 'import csv\n'), ((4911, 4924), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (4921, 4924), False, 'import csv\n'), ((1753, 1777), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (1765, 1777), False, 'import os\n')] |
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import config as cfg
import networks.invresnet
from datasets import ds_utils
from utils import vis
from networks.archs import D_net_gauss, Discriminator
from networks import resnet_ae, archs
from utils.nn import to_numpy, calc_triplet_loss
def calc_acc(outputs, labels):
assert(outputs.shape[1] == 8)
assert(len(outputs) == len(labels))
_, preds = torch.max(outputs, 1)
corrects = torch.sum(preds == labels)
acc = corrects.double()/float(outputs.size(0))
return acc.item()
class SAAE(nn.Module):
def __init__(self, pretrained_encoder=False):
super(SAAE, self).__init__()
dim_ft = cfg.EXPRESSION_DIMS
dim_pose = 3
self.z_dim = dim_ft*3 + 3
input_channels = 3
if cfg.ARCH == 'dcgan':
self.Q = archs.DCGAN_Encoder(self.z_dim).cuda()
self.P = archs.DCGAN_Decoder(self.z_dim).cuda()
elif cfg.ARCH == 'resnet':
self.Q = resnet_ae.resnet18(pretrained=pretrained_encoder,
num_classes=self.z_dim,
input_size=cfg.INPUT_SIZE,
input_channels=input_channels,
layer_normalization=cfg.ENCODER_LAYER_NORMALIZATION).cuda()
if cfg.DECODER_FIXED_ARCH:
decoder_class = networks.invresnet.InvResNet
else:
decoder_class = networks.invresnet.InvResNet_old
num_blocks = [cfg.DECODER_PLANES_PER_BLOCK] * 4
self.P = decoder_class(networks.invresnet.InvBasicBlock,
num_blocks,
input_dims=self.z_dim,
output_size=cfg.INPUT_SIZE,
output_channels=input_channels,
layer_normalization=cfg.DECODER_LAYER_NORMALIZATION).cuda()
else:
raise ValueError('Unknown network architecture!')
self.D_z = D_net_gauss(self.z_dim).cuda()
self.D = Discriminator().cuda()
# Disentanglement
self.factors = ['pose', 'id', 'shape', 'expression']
self.E = archs.EncoderLvlParallel(self.z_dim, dim_ft).cuda()
self.G = archs.DecoderLvlParallel(dim_pose + 3 * dim_ft, self.z_dim).cuda()
self.fp, self.fi, self.fs, self.se = None, None, None, None
# Emotion classification from Z vector
self.znet = archs.ZNet(dim_ft).cuda()
self.cross_entropy_loss = nn.CrossEntropyLoss().cuda()
# lr_l = 0.00002
lr_l = 0.00008
betas_disent = (0.9, 0.999)
self.optimizer_E = optim.Adam(self.E.parameters(), lr=lr_l, betas=betas_disent)
self.optimizer_G = optim.Adam(self.G.parameters(), lr=lr_l, betas=betas_disent)
self.optimizer_znet = optim.Adam(self.znet.parameters(), lr=lr_l)
def count_parameters(m):
return sum(p.numel() for p in m.parameters() if p.requires_grad)
print("Trainable params Q: {:,}".format(count_parameters(self.Q)))
print("Trainable params P: {:,}".format(count_parameters(self.P)))
print("Trainable params D_z: {:,}".format(count_parameters(self.D_z)))
print("Trainable params D: {:,}".format(count_parameters(self.D)))
print("Trainable params E: {:,}".format(count_parameters(self.E)))
print("Trainable params G: {:,}".format(count_parameters(self.G)))
self.total_iter = 0
self.iter = 0
self.z = None
self.images = None
self.current_dataset = None
def z_vecs(self):
return [to_numpy(self.z)]
def z_vecs_pre(self):
return [to_numpy(self.z_pre)]
def id_vec(self):
if cfg.WITH_PARALLEL_DISENTANGLEMENT:
try:
return to_numpy(self.f_parallel[1])
except:
return None
def res_vec(self, exclude_fid):
if cfg.WITH_PARALLEL_DISENTANGLEMENT:
try:
h = torch.cat([self.f_parallel[i] for i in range(len(self.f_parallel)) if i != exclude_fid], dim=1)
return to_numpy(h)
except:
return None
def exp_vec(self):
if cfg.WITH_PARALLEL_DISENTANGLEMENT:
try:
return to_numpy(self.f_parallel[3])
except:
return None
def f_vec(self, i):
if cfg.WITH_PARALLEL_DISENTANGLEMENT:
try:
return to_numpy(self.f_parallel[i])
except:
return None
def poses_pred(self):
try:
return to_numpy(self.f_parallel[0])
except:
return None
def emotions_pred(self):
try:
if self.emotion_probs is not None:
return np.argmax(to_numpy(self.emotion_probs), axis=1)
except AttributeError:
pass
return None
def forward(self, X, Y=None, skip_disentanglement=False):
self.z_pre = self.Q(X)
if skip_disentanglement:
self.z = self.z_pre
self.emotion_probs = None
else:
self.z = self.run_disentanglement(self.z_pre, Y=Y)[0]
return self.P(self.z)
def run_disentanglement(self, z, Y=None, train=False):
if train:
return self.__train_disenglement_parallel(z, Y)
else:
return self.__forward_disentanglement_parallel(z, Y)
def __forward_disentanglement_parallel(self, z, Y=None):
iter_stats = {}
with torch.no_grad():
self.f_parallel = self.E(z)
z_recon = self.G(*self.f_parallel)
ft_id = 3
try:
y = Y[ft_id]
except TypeError:
y = None
y_f = self.f_parallel[3]
try:
y_p = self.f_parallel[0]
def calc_err(outputs, target):
return np.abs(np.rad2deg(F.l1_loss(outputs, target, reduction='none').detach().cpu().numpy()))
iter_stats['err_pose'] = calc_err(y_p, Y[0])
except TypeError:
pass
clprobs = self.znet(y_f)
self.emotion_probs = clprobs
if y is not None:
emotion_labels = y[:, 0].long()
loss_cls = self.cross_entropy_loss(clprobs, emotion_labels)
acc_cls = calc_acc(clprobs, emotion_labels)
iter_stats['loss_cls'] = loss_cls.item()
iter_stats['acc_cls'] = acc_cls
iter_stats['emotion_probs'] = to_numpy(clprobs)
iter_stats['emotion_labels'] = to_numpy(emotion_labels)
f_parallel_recon = self.E(self.Q(self.P(z_recon)[:,:3]))
l1_err = torch.abs(torch.cat(f_parallel_recon, dim=1) - torch.cat(self.f_parallel, dim=1)).mean(dim=1)
iter_stats['l1_dis_cycle'] = to_numpy(l1_err)
return z_recon, iter_stats, None
def __train_disenglement_parallel(self, z, Y=None, train=True):
iter_stats = {}
self.E.train(train)
self.G.train(train)
self.optimizer_E.zero_grad()
self.optimizer_G.zero_grad()
#
# Autoencoding phase
#
fts = self.E(z)
fp, fi, fs, fe = fts
z_recon = self.G(fp, fi, fs, fe)
loss_z_recon = F.l1_loss(z, z_recon) * cfg.W_Z_RECON
if not cfg.WITH_Z_RECON_LOSS:
loss_z_recon *= 0
#
# Info min/max phase
#
loss_I = loss_z_recon
loss_G = torch.zeros(1, requires_grad=True).cuda()
def calc_err(outputs, target):
return np.abs(np.rad2deg(F.l1_loss(outputs, target, reduction='none').detach().cpu().numpy().mean(axis=0)))
def cosine_loss(outputs, targets):
return (1 - F.cosine_similarity(outputs, targets, dim=1)).mean()
if Y[3] is not None and Y[3].sum() > 0: # Has expression -> AffectNet
available_factors = [3,3,3]
if cfg.WITH_POSE:
available_factors = [0] + available_factors
elif Y[2][1] is not None: # has vids -> VoxCeleb
available_factors = [2]
elif Y[1] is not None: # Has identities
available_factors = [1,1,1]
if cfg.WITH_POSE:
available_factors = [0] + available_factors
elif Y[0] is not None: # Any dataset with pose
available_factors = [0,1,3]
lvl = available_factors[self.iter % len(available_factors)]
name = self.factors[lvl]
try:
y = Y[lvl]
except TypeError:
y = None
# if y is not None and name != 'shape':
def calc_feature_loss(name, y_f, y, show_triplets=False, wnd_title=None):
if name == 'id' or name == 'shape' or name == 'expression':
display_images = None
if show_triplets:
display_images = self.images
loss_I_f, err_f = calc_triplet_loss(y_f, y, return_acc=True, images=display_images, feature_name=name,
wnd_title=wnd_title)
if name == 'expression':
loss_I_f *= 2.0
elif name == 'pose':
# loss_I_f, err_f = F.l1_loss(y_f, y), calc_err(y_f, y)
loss_I_f, err_f = F.mse_loss(y_f, y)*1, calc_err(y_f, y)
# loss_I_f, err_f = cosine_loss(y_f, y), calc_err(y_f, y)
else:
raise ValueError("Unknown feature name!")
return loss_I_f, err_f
if y is not None and cfg.WITH_FEATURE_LOSS:
show_triplets = (self.iter + 1) % self.print_interval == 0
y_f = fts[lvl]
loss_I_f, err_f = calc_feature_loss(name, y_f, y, show_triplets=show_triplets)
loss_I += cfg.W_FEAT * loss_I_f
iter_stats[name+'_loss_f'] = loss_I_f.item()
iter_stats[name+'_err_f'] = np.mean(err_f)
# train expression classifier
if name == 'expression':
self.znet.zero_grad()
emotion_labels = y[:,0].long()
clprobs = self.znet(y_f.detach()) # train only znet
# clprobs = self.znet(y_f) # train enoder and znet
# loss_cls = self.cross_entropy_loss(clprobs, emotion_labels)
loss_cls = self.weighted_CE_loss(clprobs, emotion_labels)
acc_cls = calc_acc(clprobs, emotion_labels)
if train:
loss_cls.backward(retain_graph=False)
self.optimizer_znet.step()
iter_stats['loss_cls'] = loss_cls.item()
iter_stats['acc_cls'] = acc_cls
iter_stats['expression_y_probs'] = to_numpy(clprobs)
iter_stats['expression_y'] = to_numpy(y)
# cycle loss
# other_levels = [0,1,2,3]
# other_levels.remove(lvl)
# shuffle_lvl = np.random.permutation(other_levels)[0]
shuffle_lvl = lvl
# print("shuffling level {}...".format(shuffle_lvl))
if cfg.WITH_DISENT_CYCLE_LOSS:
# z_random = torch.rand_like(z).cuda()
# fts_random = self.E(z_random)
# create modified feature vectors
fts[0] = fts[0].detach()
fts[1] = fts[1].detach()
fts[2] = fts[2].detach()
fts[3] = fts[3].detach()
fts_mod = fts.copy()
shuffled_ids = torch.randperm(len(fts[shuffle_lvl]))
y_mod = None
if y is not None:
if name == 'shape':
y_mod = [y[0][shuffled_ids], y[1][shuffled_ids]]
else:
y_mod = y[shuffled_ids]
fts_mod[shuffle_lvl] = fts[shuffle_lvl][shuffled_ids]
# predict full cycle
z_random_mod = self.G(*fts_mod)
X_random_mod = self.P(z_random_mod)[:,:3]
z_random_mod_recon = self.Q(X_random_mod)
fts2 = self.E(z_random_mod_recon)
# recon error in unmodified part
# h = torch.cat([fts_mod[i] for i in range(len(fts_mod)) if i != lvl], dim=1)
# h2 = torch.cat([fts2[i] for i in range(len(fts2)) if i != lvl], dim=1)
# l1_err_h = torch.abs(h - h2).mean(dim=1)
# l1_err_h = torch.abs(torch.cat(fts_mod, dim=1) - torch.cat(fts2, dim=1)).mean(dim=1)
# recon error in modified part
# l1_err_f = np.rad2deg(to_numpy(torch.abs(fts_mod[lvl] - fts2[lvl]).mean(dim=1)))
# recon error in entire vector
l1_err = torch.abs(torch.cat(fts_mod, dim=1)[:,3:] - torch.cat(fts2, dim=1)[:,3:]).mean(dim=1)
loss_dis_cycle = F.l1_loss(torch.cat(fts_mod, dim=1)[:,3:], torch.cat(fts2, dim=1)[:,3:]) * cfg.W_CYCLE
iter_stats['loss_dis_cycle'] = loss_dis_cycle.item()
loss_I += loss_dis_cycle
# cycle augmentation loss
if cfg.WITH_AUGMENTATION_LOSS and y_mod is not None:
y_f_2 = fts2[lvl]
loss_I_f_2, err_f_2 = calc_feature_loss(name, y_f_2, y_mod, show_triplets=show_triplets, wnd_title='aug')
loss_I += loss_I_f_2 * cfg.W_AUG
iter_stats[name+'_loss_f_2'] = loss_I_f_2.item()
iter_stats[name+'_err_f_2'] = np.mean(err_f_2)
#
# Adversarial loss of modified generations
#
GAN = False
if GAN and train:
eps = 0.00001
# #######################
# # GAN discriminator phase
# #######################
update_D = False
if update_D:
self.D.zero_grad()
err_real = self.D(self.images)
err_fake = self.D(X_random_mod.detach())
# err_fake = self.D(X_z_recon.detach())
loss_D = -torch.mean(torch.log(err_real + eps) + torch.log(1.0 - err_fake + eps)) * 0.1
loss_D.backward()
self.optimizer_D.step()
iter_stats.update({'loss_D': loss_D.item()})
#######################
# Generator loss
#######################
self.D.zero_grad()
err_fake = self.D(X_random_mod)
# err_fake = self.D(X_z_recon)
loss_G += -torch.mean(torch.log(err_fake + eps))
iter_stats.update({'loss_G': loss_G.item()})
# iter_stats.update({'err_real': err_real.mean().item(), 'err_fake': loss_G.mean().item()})
# debug visualization
show = True
if show:
if (self.iter+1) % self.print_interval in [0,1]:
if Y[3] is None:
emotion_gt = np.zeros(len(z), dtype=int)
emotion_gt_mod = np.zeros(len(z), dtype=int)
else:
emotion_gt = Y[3][:,0].long()
emotion_gt_mod = Y[3][shuffled_ids,0].long()
with torch.no_grad():
self.znet.eval()
self.G.eval()
emotion_preds = torch.max(self.znet(fe.detach()), 1)[1]
emotion_mod = torch.max(self.znet(fts_mod[3].detach()), 1)[1]
emotion_mod_pred = torch.max(self.znet(fts2[3].detach()), 1)[1]
X_recon = self.P(z)[:,:3]
X_z_recon = self.P(z_recon)[:,:3]
X_random_mod_recon = self.P(self.G(*fts2))[:,:3]
self.znet.train(train)
self.G.train(train)
X_recon_errs = 255.0 * torch.abs(self.images - X_recon).reshape(len(self.images), -1).mean(dim=1)
X_z_recon_errs = 255.0 * torch.abs(self.images - X_z_recon).reshape(len(self.images), -1).mean(dim=1)
nimgs = 8
disp_input = vis.add_pose_to_images(ds_utils.denormalized(self.images)[:nimgs], Y[0], color=(0, 0, 1.0))
if name == 'expression':
disp_input = vis.add_emotion_to_images(disp_input, to_numpy(emotion_gt))
elif name == 'id':
disp_input = vis.add_id_to_images(disp_input, to_numpy(Y[1]))
disp_recon = vis.add_pose_to_images(ds_utils.denormalized(X_recon)[:nimgs], fts[0])
disp_recon = vis.add_error_to_images(disp_recon, errors=X_recon_errs, format_string='{:.1f}')
disp_z_recon = vis.add_pose_to_images(ds_utils.denormalized(X_z_recon)[:nimgs], fts[0])
disp_z_recon = vis.add_emotion_to_images(disp_z_recon, to_numpy(emotion_preds),
gt_emotions=to_numpy(emotion_gt) if name=='expression' else None)
disp_z_recon = vis.add_error_to_images(disp_z_recon, errors=X_z_recon_errs, format_string='{:.1f}')
disp_input_shuffle = vis.add_pose_to_images(ds_utils.denormalized(self.images[shuffled_ids])[:nimgs], fts[0][shuffled_ids])
disp_input_shuffle = vis.add_emotion_to_images(disp_input_shuffle, to_numpy(emotion_gt_mod))
if name == 'id':
disp_input_shuffle = vis.add_id_to_images(disp_input_shuffle, to_numpy(Y[1][shuffled_ids]))
disp_recon_shuffle = vis.add_pose_to_images(ds_utils.denormalized(X_random_mod)[:nimgs], fts_mod[0], color=(0, 0, 1.0))
disp_recon_shuffle = vis.add_emotion_to_images(disp_recon_shuffle, to_numpy(emotion_mod))
disp_cycle = vis.add_pose_to_images(ds_utils.denormalized(X_random_mod_recon)[:nimgs], fts2[0])
disp_cycle = vis.add_emotion_to_images(disp_cycle, to_numpy(emotion_mod_pred))
disp_cycle = vis.add_error_to_images(disp_cycle, errors=l1_err, format_string='{:.3f}',
size=0.6, thickness=2, vmin=0, vmax=0.1)
rows = [
# original input images
vis.make_grid(disp_input, nCols=nimgs),
# reconstructions without disentanglement
vis.make_grid(disp_recon, nCols=nimgs),
# reconstructions with disentanglement
vis.make_grid(disp_z_recon, nCols=nimgs),
# source for feature transfer
vis.make_grid(disp_input_shuffle, nCols=nimgs),
# reconstructions with modified feature vector (direkt)
vis.make_grid(disp_recon_shuffle, nCols=nimgs),
# reconstructions with modified feature vector (1 iters)
vis.make_grid(disp_cycle, nCols=nimgs)
]
f = 1.0 / cfg.INPUT_SCALE_FACTOR
disp_img = vis.make_grid(rows, nCols=1, normalize=False, fx=f, fy=f)
wnd_title = name
if self.current_dataset is not None:
wnd_title += ' ' + self.current_dataset.__class__.__name__
cv2.imshow(wnd_title, cv2.cvtColor(disp_img, cv2.COLOR_RGB2BGR))
cv2.waitKey(10)
loss_I *= cfg.W_DISENT
iter_stats['loss_disent'] = loss_I.item()
if train:
loss_I.backward(retain_graph=True)
return z_recon, iter_stats, loss_G[0]
def vis_reconstruction(net, inputs, ids=None, clips=None, poses=None, emotions=None, landmarks=None, landmarks_pred=None,
pytorch_ssim=None, fx=0.5, fy=0.5, ncols=10, skip_disentanglement=False):
net.eval()
cs_errs = None
with torch.no_grad():
X_recon = net(inputs, Y=None, skip_disentanglement=skip_disentanglement)
# second pass
# X_recon = net(X_recon, Y=None, skip_disentanglement=skip_disentanglement)
if pytorch_ssim is not None:
cs_errs = np.zeros(len(inputs))
for i in range(len(cs_errs)):
cs_errs[i] = 1 - pytorch_ssim(inputs[i].unsqueeze(0), X_recon[i].unsqueeze(0)).item()
return vis.draw_results(inputs, X_recon, net.z_vecs(),
ids=ids, poses=poses, poses_pred=net.poses_pred(),
emotions=emotions, emotions_pred=net.emotions_pred(),
cs_errs=cs_errs,
fx=fx, fy=fy, ncols=ncols)
| [
"torch.nn.CrossEntropyLoss",
"networks.archs.DCGAN_Encoder",
"torch.max",
"torch.sum",
"numpy.mean",
"networks.archs.EncoderLvlParallel",
"torch.nn.functional.cosine_similarity",
"networks.archs.D_net_gauss",
"utils.vis.add_error_to_images",
"cv2.waitKey",
"torch.nn.functional.l1_loss",
"utils... | [((489, 510), 'torch.max', 'torch.max', (['outputs', '(1)'], {}), '(outputs, 1)\n', (498, 510), False, 'import torch\n'), ((526, 552), 'torch.sum', 'torch.sum', (['(preds == labels)'], {}), '(preds == labels)\n', (535, 552), False, 'import torch\n'), ((20163, 20178), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (20176, 20178), False, 'import torch\n'), ((3772, 3788), 'utils.nn.to_numpy', 'to_numpy', (['self.z'], {}), '(self.z)\n', (3780, 3788), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((3833, 3853), 'utils.nn.to_numpy', 'to_numpy', (['self.z_pre'], {}), '(self.z_pre)\n', (3841, 3853), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((4774, 4802), 'utils.nn.to_numpy', 'to_numpy', (['self.f_parallel[0]'], {}), '(self.f_parallel[0])\n', (4782, 4802), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((5697, 5712), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5710, 5712), False, 'import torch\n'), ((7524, 7545), 'torch.nn.functional.l1_loss', 'F.l1_loss', (['z', 'z_recon'], {}), '(z, z_recon)\n', (7533, 7545), True, 'import torch.nn.functional as F\n'), ((10160, 10174), 'numpy.mean', 'np.mean', (['err_f'], {}), '(err_f)\n', (10167, 10174), True, 'import numpy as np\n'), ((2159, 2182), 'networks.archs.D_net_gauss', 'D_net_gauss', (['self.z_dim'], {}), '(self.z_dim)\n', (2170, 2182), False, 'from networks.archs import D_net_gauss, Discriminator\n'), ((2207, 2222), 'networks.archs.Discriminator', 'Discriminator', ([], {}), '()\n', (2220, 2222), False, 'from networks.archs import D_net_gauss, Discriminator\n'), ((2335, 2379), 'networks.archs.EncoderLvlParallel', 'archs.EncoderLvlParallel', (['self.z_dim', 'dim_ft'], {}), '(self.z_dim, dim_ft)\n', (2359, 2379), False, 'from networks import resnet_ae, archs\n'), ((2404, 2463), 'networks.archs.DecoderLvlParallel', 'archs.DecoderLvlParallel', (['(dim_pose + 3 * dim_ft)', 'self.z_dim'], {}), '(dim_pose + 3 * dim_ft, self.z_dim)\n', (2428, 2463), False, 'from networks import resnet_ae, archs\n'), ((2607, 2625), 'networks.archs.ZNet', 'archs.ZNet', (['dim_ft'], {}), '(dim_ft)\n', (2617, 2625), False, 'from networks import resnet_ae, archs\n'), ((2667, 2688), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2686, 2688), True, 'import torch.nn as nn\n'), ((3964, 3992), 'utils.nn.to_numpy', 'to_numpy', (['self.f_parallel[1]'], {}), '(self.f_parallel[1])\n', (3972, 3992), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((4280, 4291), 'utils.nn.to_numpy', 'to_numpy', (['h'], {}), '(h)\n', (4288, 4291), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((4450, 4478), 'utils.nn.to_numpy', 'to_numpy', (['self.f_parallel[3]'], {}), '(self.f_parallel[3])\n', (4458, 4478), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((4638, 4666), 'utils.nn.to_numpy', 'to_numpy', (['self.f_parallel[i]'], {}), '(self.f_parallel[i])\n', (4646, 4666), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((6742, 6759), 'utils.nn.to_numpy', 'to_numpy', (['clprobs'], {}), '(clprobs)\n', (6750, 6759), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((6807, 6831), 'utils.nn.to_numpy', 'to_numpy', (['emotion_labels'], {}), '(emotion_labels)\n', (6815, 6831), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((7069, 7085), 'utils.nn.to_numpy', 'to_numpy', (['l1_err'], {}), '(l1_err)\n', (7077, 7085), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((7728, 7762), 'torch.zeros', 'torch.zeros', (['(1)'], {'requires_grad': '(True)'}), '(1, requires_grad=True)\n', (7739, 7762), False, 'import torch\n'), ((9173, 9282), 'utils.nn.calc_triplet_loss', 'calc_triplet_loss', (['y_f', 'y'], {'return_acc': '(True)', 'images': 'display_images', 'feature_name': 'name', 'wnd_title': 'wnd_title'}), '(y_f, y, return_acc=True, images=display_images,\n feature_name=name, wnd_title=wnd_title)\n', (9190, 9282), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((10973, 10990), 'utils.nn.to_numpy', 'to_numpy', (['clprobs'], {}), '(clprobs)\n', (10981, 10990), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((11036, 11047), 'utils.nn.to_numpy', 'to_numpy', (['y'], {}), '(y)\n', (11044, 11047), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((13547, 13563), 'numpy.mean', 'np.mean', (['err_f_2'], {}), '(err_f_2)\n', (13554, 13563), True, 'import numpy as np\n'), ((912, 943), 'networks.archs.DCGAN_Encoder', 'archs.DCGAN_Encoder', (['self.z_dim'], {}), '(self.z_dim)\n', (931, 943), False, 'from networks import resnet_ae, archs\n'), ((972, 1003), 'networks.archs.DCGAN_Decoder', 'archs.DCGAN_Decoder', (['self.z_dim'], {}), '(self.z_dim)\n', (991, 1003), False, 'from networks import resnet_ae, archs\n'), ((4966, 4994), 'utils.nn.to_numpy', 'to_numpy', (['self.emotion_probs'], {}), '(self.emotion_probs)\n', (4974, 4994), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((16791, 16876), 'utils.vis.add_error_to_images', 'vis.add_error_to_images', (['disp_recon'], {'errors': 'X_recon_errs', 'format_string': '"""{:.1f}"""'}), "(disp_recon, errors=X_recon_errs, format_string='{:.1f}'\n )\n", (16814, 16876), False, 'from utils import vis\n'), ((17243, 17332), 'utils.vis.add_error_to_images', 'vis.add_error_to_images', (['disp_z_recon'], {'errors': 'X_z_recon_errs', 'format_string': '"""{:.1f}"""'}), "(disp_z_recon, errors=X_z_recon_errs, format_string=\n '{:.1f}')\n", (17266, 17332), False, 'from utils import vis\n'), ((18239, 18358), 'utils.vis.add_error_to_images', 'vis.add_error_to_images', (['disp_cycle'], {'errors': 'l1_err', 'format_string': '"""{:.3f}"""', 'size': '(0.6)', 'thickness': '(2)', 'vmin': '(0)', 'vmax': '(0.1)'}), "(disp_cycle, errors=l1_err, format_string='{:.3f}',\n size=0.6, thickness=2, vmin=0, vmax=0.1)\n", (18262, 18358), False, 'from utils import vis\n'), ((19346, 19403), 'utils.vis.make_grid', 'vis.make_grid', (['rows'], {'nCols': '(1)', 'normalize': '(False)', 'fx': 'f', 'fy': 'f'}), '(rows, nCols=1, normalize=False, fx=f, fy=f)\n', (19359, 19403), False, 'from utils import vis\n'), ((19687, 19702), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (19698, 19702), False, 'import cv2\n'), ((1067, 1259), 'networks.resnet_ae.resnet18', 'resnet_ae.resnet18', ([], {'pretrained': 'pretrained_encoder', 'num_classes': 'self.z_dim', 'input_size': 'cfg.INPUT_SIZE', 'input_channels': 'input_channels', 'layer_normalization': 'cfg.ENCODER_LAYER_NORMALIZATION'}), '(pretrained=pretrained_encoder, num_classes=self.z_dim,\n input_size=cfg.INPUT_SIZE, input_channels=input_channels,\n layer_normalization=cfg.ENCODER_LAYER_NORMALIZATION)\n', (1085, 1259), False, 'from networks import resnet_ae, archs\n'), ((7998, 8042), 'torch.nn.functional.cosine_similarity', 'F.cosine_similarity', (['outputs', 'targets'], {'dim': '(1)'}), '(outputs, targets, dim=1)\n', (8017, 8042), True, 'import torch.nn.functional as F\n'), ((12947, 12972), 'torch.cat', 'torch.cat', (['fts_mod'], {'dim': '(1)'}), '(fts_mod, dim=1)\n', (12956, 12972), False, 'import torch\n'), ((12980, 13002), 'torch.cat', 'torch.cat', (['fts2'], {'dim': '(1)'}), '(fts2, dim=1)\n', (12989, 13002), False, 'import torch\n'), ((14672, 14697), 'torch.log', 'torch.log', (['(err_fake + eps)'], {}), '(err_fake + eps)\n', (14681, 14697), False, 'import torch\n'), ((15359, 15374), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15372, 15374), False, 'import torch\n'), ((17056, 17079), 'utils.nn.to_numpy', 'to_numpy', (['emotion_preds'], {}), '(emotion_preds)\n', (17064, 17079), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((17560, 17584), 'utils.nn.to_numpy', 'to_numpy', (['emotion_gt_mod'], {}), '(emotion_gt_mod)\n', (17568, 17584), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((17967, 17988), 'utils.nn.to_numpy', 'to_numpy', (['emotion_mod'], {}), '(emotion_mod)\n', (17975, 17988), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((18178, 18204), 'utils.nn.to_numpy', 'to_numpy', (['emotion_mod_pred'], {}), '(emotion_mod_pred)\n', (18186, 18204), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((18514, 18552), 'utils.vis.make_grid', 'vis.make_grid', (['disp_input'], {'nCols': 'nimgs'}), '(disp_input, nCols=nimgs)\n', (18527, 18552), False, 'from utils import vis\n'), ((18645, 18683), 'utils.vis.make_grid', 'vis.make_grid', (['disp_recon'], {'nCols': 'nimgs'}), '(disp_recon, nCols=nimgs)\n', (18658, 18683), False, 'from utils import vis\n'), ((18773, 18813), 'utils.vis.make_grid', 'vis.make_grid', (['disp_z_recon'], {'nCols': 'nimgs'}), '(disp_z_recon, nCols=nimgs)\n', (18786, 18813), False, 'from utils import vis\n'), ((18894, 18940), 'utils.vis.make_grid', 'vis.make_grid', (['disp_input_shuffle'], {'nCols': 'nimgs'}), '(disp_input_shuffle, nCols=nimgs)\n', (18907, 18940), False, 'from utils import vis\n'), ((19047, 19093), 'utils.vis.make_grid', 'vis.make_grid', (['disp_recon_shuffle'], {'nCols': 'nimgs'}), '(disp_recon_shuffle, nCols=nimgs)\n', (19060, 19093), False, 'from utils import vis\n'), ((19201, 19239), 'utils.vis.make_grid', 'vis.make_grid', (['disp_cycle'], {'nCols': 'nimgs'}), '(disp_cycle, nCols=nimgs)\n', (19214, 19239), False, 'from utils import vis\n'), ((19624, 19665), 'cv2.cvtColor', 'cv2.cvtColor', (['disp_img', 'cv2.COLOR_RGB2BGR'], {}), '(disp_img, cv2.COLOR_RGB2BGR)\n', (19636, 19665), False, 'import cv2\n'), ((9547, 9565), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['y_f', 'y'], {}), '(y_f, y)\n', (9557, 9565), True, 'import torch.nn.functional as F\n'), ((16317, 16351), 'datasets.ds_utils.denormalized', 'ds_utils.denormalized', (['self.images'], {}), '(self.images)\n', (16338, 16351), False, 'from datasets import ds_utils\n'), ((16506, 16526), 'utils.nn.to_numpy', 'to_numpy', (['emotion_gt'], {}), '(emotion_gt)\n', (16514, 16526), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((16710, 16740), 'datasets.ds_utils.denormalized', 'ds_utils.denormalized', (['X_recon'], {}), '(X_recon)\n', (16731, 16740), False, 'from datasets import ds_utils\n'), ((16931, 16963), 'datasets.ds_utils.denormalized', 'ds_utils.denormalized', (['X_z_recon'], {}), '(X_z_recon)\n', (16952, 16963), False, 'from datasets import ds_utils\n'), ((17393, 17441), 'datasets.ds_utils.denormalized', 'ds_utils.denormalized', (['self.images[shuffled_ids]'], {}), '(self.images[shuffled_ids])\n', (17414, 17441), False, 'from datasets import ds_utils\n'), ((17709, 17737), 'utils.nn.to_numpy', 'to_numpy', (['Y[1][shuffled_ids]'], {}), '(Y[1][shuffled_ids])\n', (17717, 17737), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((17804, 17839), 'datasets.ds_utils.denormalized', 'ds_utils.denormalized', (['X_random_mod'], {}), '(X_random_mod)\n', (17825, 17839), False, 'from datasets import ds_utils\n'), ((18047, 18088), 'datasets.ds_utils.denormalized', 'ds_utils.denormalized', (['X_random_mod_recon'], {}), '(X_random_mod_recon)\n', (18068, 18088), False, 'from datasets import ds_utils\n'), ((6940, 6974), 'torch.cat', 'torch.cat', (['f_parallel_recon'], {'dim': '(1)'}), '(f_parallel_recon, dim=1)\n', (6949, 6974), False, 'import torch\n'), ((6977, 7010), 'torch.cat', 'torch.cat', (['self.f_parallel'], {'dim': '(1)'}), '(self.f_parallel, dim=1)\n', (6986, 7010), False, 'import torch\n'), ((12832, 12857), 'torch.cat', 'torch.cat', (['fts_mod'], {'dim': '(1)'}), '(fts_mod, dim=1)\n', (12841, 12857), False, 'import torch\n'), ((12866, 12888), 'torch.cat', 'torch.cat', (['fts2'], {'dim': '(1)'}), '(fts2, dim=1)\n', (12875, 12888), False, 'import torch\n'), ((16637, 16651), 'utils.nn.to_numpy', 'to_numpy', (['Y[1]'], {}), '(Y[1])\n', (16645, 16651), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((17154, 17174), 'utils.nn.to_numpy', 'to_numpy', (['emotion_gt'], {}), '(emotion_gt)\n', (17162, 17174), False, 'from utils.nn import to_numpy, calc_triplet_loss\n'), ((14176, 14201), 'torch.log', 'torch.log', (['(err_real + eps)'], {}), '(err_real + eps)\n', (14185, 14201), False, 'import torch\n'), ((14204, 14235), 'torch.log', 'torch.log', (['(1.0 - err_fake + eps)'], {}), '(1.0 - err_fake + eps)\n', (14213, 14235), False, 'import torch\n'), ((16028, 16060), 'torch.abs', 'torch.abs', (['(self.images - X_recon)'], {}), '(self.images - X_recon)\n', (16037, 16060), False, 'import torch\n'), ((16152, 16186), 'torch.abs', 'torch.abs', (['(self.images - X_z_recon)'], {}), '(self.images - X_z_recon)\n', (16161, 16186), False, 'import torch\n'), ((6114, 6158), 'torch.nn.functional.l1_loss', 'F.l1_loss', (['outputs', 'target'], {'reduction': '"""none"""'}), "(outputs, target, reduction='none')\n", (6123, 6158), True, 'import torch.nn.functional as F\n'), ((7847, 7891), 'torch.nn.functional.l1_loss', 'F.l1_loss', (['outputs', 'target'], {'reduction': '"""none"""'}), "(outputs, target, reduction='none')\n", (7856, 7891), True, 'import torch.nn.functional as F\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.