code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 12:48:20 2018
@author: <EMAIL>
"""
def swap_matrix_element (A, P):
import random as r
S1 = len(A)
S2 = len(A[0])
for i in range(P):
row1 = r.randint(0, S1-1)
row2 = r.randint(0, S1-1)
col1 = r.randint(0, S2-1)
col2 = r.randint(0, S2-1)
x = A[row1][col1]
y = A[row2][col2]
A[row1][col1] = y
A[row2][col2] = x
NODF= NODF_calc(A)
return(A, NODF)
def NODF_calc (A):
#print('Calcolo NODF della corrispondente matrice random.')
import statistics as stat
#import math
import numpy as np
#print('conn = ', conn)
#A = random_matrix(int(S1a),int(S2a),float(conn))
S1 = len(A)
S2 = len(A[0])
#print('S1 + S2 = ', S1+S2)
#print('S1 = ', S1)
#print('S2 = ', S2)
k_A = []
k_P = []
for i in range (len(A)):
x = 0
for j in range(len(A[i])):
x = x + A[i][j]
k_A.append(x)
for j in range(len(A[0])):
x = 0
for i in range(len(A)):
x = x + A[i][j]
k_P.append(x)
#print('k_A = ', k_A)
#print('k_P = ', k_P)
#sigma_deg_A = stat.stdev(k_A)
#sigma_deg_P = stat.stdev(k_P)
O_A = [ [] for x in range(S1)]
O_P = [ [] for x in range(S2)]
for i in range(S1):
for j in range(S1):
x = 0
for k in range(S2):
x = x + A[i][k]*A[j][k]
O_A[i].append(x)
for i in range(S2):
for j in range(S2):
x = 0
for k in range(S1):
x = x + A[k][i]*A[k][j]
O_P[i].append(x)
T_A = [ [] for x in range(S1)]
T_P = [ [] for x in range(S2)]
for i in range(S1):
for j in range(S1):
if k_A[i] == k_A[j]:
T_A[i].append(0)
elif O_A[i][j] == 0:
T_A[i].append(0)
else:
m = min( [k_A[i], k_A[j] ])
if m == 0:
print('Attenzione, min( [k_A[{}], k_A[{}] ]) = 0 '.format(i,j))
print('k_A[{}] = {}'.format(i, k_A[i]))
print('k_A[{}] = {}'.format(j, k_A[j]))
print('O_A[{}][{}] = {}'.format(i,j,O_A[i][j]))
m = 0.001
x = O_A[i][j]/m
T_A[i].append(x)
for i in range(S2):
for j in range(S2):
if k_P[i] == k_P[j]:
T_P[i].append(0)
elif O_P[i][j] == 0:
T_P[i].append(0)
else:
m = min( [k_P[i], k_P[j] ])
if m == 0:
print('Attenzione, min( [k_P[{}], k_P[{}] ]) = 0 '.format(i,j))
print('k_P[{}] = {}'.format(i, k_P[i]))
print('k_P[{}] = {}'.format(j, k_P[j]))
print('O_P[{}][{}] = {}'.format(i,j,O_P[i][j]))
m = 0.001
x = O_P[i][j]/m
T_P[i].append(x)
num_A = 0
for i in range(S1):
for j in range(i,S1):
num_A = num_A + T_A[i][j]
if np.isnan(num_A):
print('T_A[i][j] = ', T_A[i][j])
num_P = 0
for i in range(S2):
for j in range(i,S2):
num_P = num_P + T_P[i][j]
if np.isnan(num_P):
print('T_P[i][j] = ', T_P[i][j])
den_A = S1*(S1-1)/2
den_P = S2*(S2-1)/2
NODF = round((num_A + num_P)/(den_A + den_P),3)
#sigma = math.sqrt( pow(sigma_deg_A/S2,2) + pow(sigma_deg_P/S1,2))
return (NODF)
|
[
"random.randint",
"numpy.isnan"
] |
[((215, 235), 'random.randint', 'r.randint', (['(0)', '(S1 - 1)'], {}), '(0, S1 - 1)\n', (224, 235), True, 'import random as r\n'), ((249, 269), 'random.randint', 'r.randint', (['(0)', '(S1 - 1)'], {}), '(0, S1 - 1)\n', (258, 269), True, 'import random as r\n'), ((283, 303), 'random.randint', 'r.randint', (['(0)', '(S2 - 1)'], {}), '(0, S2 - 1)\n', (292, 303), True, 'import random as r\n'), ((317, 337), 'random.randint', 'r.randint', (['(0)', '(S2 - 1)'], {}), '(0, S2 - 1)\n', (326, 337), True, 'import random as r\n'), ((3179, 3194), 'numpy.isnan', 'np.isnan', (['num_A'], {}), '(num_A)\n', (3187, 3194), True, 'import numpy as np\n'), ((3388, 3403), 'numpy.isnan', 'np.isnan', (['num_P'], {}), '(num_P)\n', (3396, 3403), True, 'import numpy as np\n')]
|
import numpy as np
import keras,gc,nltk
import pandas as pd
from keras.utils import to_categorical
from sklearn import preprocessing
from supervised_BAE import *
from utils import *
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from sklearn import preprocessing
from utils import sample_test_mask
from sklearn.preprocessing import StandardScaler
import time
name_dat = "CIFAR-10"
__random_state__ = 20
np.random.seed(__random_state__)
def load_data(percentage_supervision,addval=1,reseed=0,seed_to_reseed=20):
(_, aux_t), (_, aux_test) = keras.datasets.cifar10.load_data()
labels = ["airplane", "automobile","bird", "cat","deer","dog","frog","horse","ship","truck"]
labels_t = np.asarray([labels[value[0]] for value in aux_t])
labels_test = np.asarray([labels[value[0]] for value in aux_test])
labels_t = np.concatenate((labels_t,labels_test),axis=0)
X_t = np.load("Data/cifar10_VGG_avg.npy") #mejora
X_t.shape
mask_train = sample_test_mask(labels_t, N=100)
X_test = X_t[~mask_train]
X_t = X_t[mask_train]
labels_test = enmask_data(labels_t, ~mask_train)
labels_t = enmask_data(labels_t, mask_train)
gc.collect()
std = StandardScaler(with_mean=True, with_std=True)
std.fit(X_t)
X_t = std.transform(X_t)
X_test = std.transform(X_test)
X_train, X_val, labels_train, labels_val = train_test_split(X_t, labels_t, random_state=20, test_size=len(X_test))
del X_t, labels_t
gc.collect()
X_train_input = X_train
X_val_input = X_val
X_test_input = X_test
X_total_input = np.concatenate((X_train_input,X_val_input),axis=0)
X_total = np.concatenate((X_train,X_val),axis=0)
labels_total = np.concatenate((labels_train,labels_val),axis=0)
#print("\n=====> Encoding Labels ...\n")
label_encoder = preprocessing.LabelEncoder()
label_encoder.fit(labels)
n_classes = len(labels)
y_train = label_encoder.transform(labels_train)
y_val = label_encoder.transform(labels_val)
y_test = label_encoder.transform(labels_test)
y_train_input = to_categorical(y_train,num_classes=n_classes)
y_val_input = to_categorical(y_val,num_classes=n_classes)
y_test_input = to_categorical(y_test,num_classes=n_classes)
##RESEED?
if reseed > 0:
np.random.seed(seed_to_reseed)
else:
np.random.seed(__random_state__)
idx_train = np.arange(0,len(y_train_input),1)
np.random.shuffle(idx_train)
np.random.shuffle(idx_train)
n_sup = int(np.floor(percentage_supervision*len(idx_train)))
idx_sup = idx_train[0:n_sup]
idx_unsup = idx_train[n_sup:]
if (len(idx_unsup) > 0):
for idx in idx_unsup:
y_train_input[idx,:] = np.zeros(n_classes)
Y_total_input = y_train_input
if addval > 0:
idx_val = np.arange(0,len(y_val_input),1)
np.random.shuffle(idx_val)
np.random.shuffle(idx_val)
n_sup_val = int(np.floor(percentage_supervision*len(idx_val)))
idx_sup_val = idx_val[0:n_sup_val]
idx_unsup_val = idx_val[n_sup_val:]
if (len(idx_unsup_val) > 0):
for idx in idx_unsup_val:
y_val_input[idx,:] = np.zeros(n_classes)
Y_total_input = np.concatenate((y_train_input,y_val_input),axis=0)
return n_classes, labels, labels_total, labels_test, X_total, X_test, X_total_input, X_test_input, Y_total_input
def run_CIFAR(model_id,percentage_supervision,nbits_for_hashing,alpha_val,lambda_val,beta_VAL,name_file, addval,reseed,seed_to_reseed, n_classes, labels, labels_total, labels_test, X_total, X_test, X_total_input, X_test_input, Y_total_input):
batch_size = 512
tf.keras.backend.clear_session()
tic = time.perf_counter()
if model_id == 1:
vae,encoder,generator = VDSHS(X_total.shape[1],n_classes,Nb=int(nbits_for_hashing),units=500,layers_e=2,layers_d=0,beta=beta_VAL,alpha=alpha_val)
vae.fit(X_total_input, [X_total, Y_total_input], epochs=10, batch_size=batch_size,verbose=1)
name_model = 'VDSH_S'
elif model_id == 2:
#MODIFICA ESEGUITA
#Vecchia versione: vae,encoder,generator = PSH_GS(X_total.shape[1],n_classes,Nb=int(nbits_for_hashing),units=500,layers_e=2,layers_d=0,beta=beta_VAL,alpha=alpha_val,gamma=gamma_val)
#Sostituisci gamma con lambda_ , e gamma_val con lambda_val
vae,encoder,generator = PSH_GS(X_total.shape[1],n_classes,Nb=int(nbits_for_hashing),units=500,layers_e=2,layers_d=0,beta=beta_VAL,alpha=alpha_val,lambda_=lambda_val)
vae.fit(X_total_input, [X_total, Y_total_input], epochs=10, batch_size=batch_size,verbose=1)
name_model = 'PHS_GS'
else:#elif model_id == 3:
#MODIFICA ESEGUITA
#Vecchia versione: vae,encoder,generator = SSBVAE(X_total.shape[1],n_classes,Nb=int(nbits_for_hashing),units=500,layers_e=2,layers_d=0,beta=beta_VAL,alpha=alpha_val,gamma=gamma_val)
#Sostituisci gamma con lambda_ , e gamma_val con lambda_val
vae,encoder,generator = SSBVAE(X_total.shape[1],n_classes,Nb=int(nbits_for_hashing),units=500,layers_e=2,layers_d=0,beta=beta_VAL,alpha=alpha_val,lambda_=lambda_val)
vae.fit(X_total_input, [X_total, Y_total_input], epochs=10, batch_size=batch_size,verbose=1)
name_model = 'SSB_VAE'
print("\n=====> Evaluate the Models ... \n")
if model_id == 1:#Gaussian VAE
total_hash, test_hash = hash_data(encoder,X_total_input,X_test_input, binary=False)
else:#Bernoulli VAE
total_hash, test_hash = hash_data(encoder,X_total_input,X_test_input)
p100_b,r100_b = evaluate_hashing_DE(labels,total_hash, test_hash,labels_total,labels_test,tipo="topK")
p5000_b = evaluate_hashing_DE(labels,total_hash, test_hash,labels_total,labels_test,tipo="topK",eval_tipo="Patk",K=5000)
p1000_b = evaluate_hashing_DE(labels,total_hash, test_hash,labels_total,labels_test,tipo="topK",eval_tipo="Patk",K=1000)
map5000_b = evaluate_hashing_DE(labels,total_hash, test_hash,labels_total,labels_test,tipo="topK",eval_tipo="MAP",K=5000)
map1000_b = evaluate_hashing_DE(labels,total_hash, test_hash,labels_total,labels_test,tipo="topK",eval_tipo="MAP",K=1000)
map100_b = evaluate_hashing_DE(labels,total_hash, test_hash,labels_total,labels_test,tipo="topK",eval_tipo="MAP",K=100)
file = open(name_file,"a")
file.write("%s, %s, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %d, %d\n"%(name_dat,name_model,percentage_supervision,alpha_val,beta_VAL,lambda_val,p100_b,r100_b,p1000_b,p5000_b,map100_b,map1000_b,map5000_b,addval,seed_to_reseed))
file.close()
del vae, total_hash, test_hash
gc.collect()
print("DONE ...")
import sys
from optparse import OptionParser
def testcifar(model,ps, addvalidation, alpha, beta, lambda_, repetitions, nbits, ofilename, reseed=0):
seeds_to_reseed = [20, 144, 1028, 2044, 101, 6077, 621, 1981, 2806, 79]
nbits = int(nbits)
if reseed > 0:
for rep in range(repetitions):
new_seed = seeds_to_reseed[rep%len(seeds_to_reseed)]
n_classes, labels, labels_total, labels_test, X_total, X_test, X_total_input, X_test_input, Y_total_input = load_data(ps,addval=addvalidation,reseed=reseed,seed_to_reseed=new_seed)
run_CIFAR(model,ps,nbits,alpha,lambda_,beta,ofilename,addvalidation,reseed,new_seed,n_classes, labels, labels_total, labels_test, X_total, X_test, X_total_input, X_test_input, Y_total_input)
del n_classes, labels, labels_total, labels_test, X_total, X_test, X_total_input, X_test_input, Y_total_input
gc.collect()
else:
n_classes, labels, labels_total, labels_test, X_total, X_test, X_total_input, X_test_input, Y_total_input = load_data(ps,addval=addvalidation,reseed=0,seed_to_reseed=20)
for rep in range(repetitions):
run_CIFAR(model,ps,nbits,alpha,lambda_,beta,ofilename,addvalidation,0,20,n_classes, labels, labels_total, labels_test, X_total, X_test, X_total_input, X_test_input, Y_total_input)
|
[
"numpy.load",
"numpy.random.seed",
"keras.datasets.cifar10.load_data",
"sklearn.preprocessing.StandardScaler",
"numpy.random.shuffle",
"numpy.asarray",
"utils.sample_test_mask",
"time.perf_counter",
"sklearn.preprocessing.LabelEncoder",
"numpy.zeros",
"gc.collect",
"numpy.concatenate",
"keras.utils.to_categorical"
] |
[((451, 483), 'numpy.random.seed', 'np.random.seed', (['__random_state__'], {}), '(__random_state__)\n', (465, 483), True, 'import numpy as np\n'), ((597, 631), 'keras.datasets.cifar10.load_data', 'keras.datasets.cifar10.load_data', ([], {}), '()\n', (629, 631), False, 'import keras, gc, nltk\n'), ((745, 794), 'numpy.asarray', 'np.asarray', (['[labels[value[0]] for value in aux_t]'], {}), '([labels[value[0]] for value in aux_t])\n', (755, 794), True, 'import numpy as np\n'), ((813, 865), 'numpy.asarray', 'np.asarray', (['[labels[value[0]] for value in aux_test]'], {}), '([labels[value[0]] for value in aux_test])\n', (823, 865), True, 'import numpy as np\n'), ((881, 928), 'numpy.concatenate', 'np.concatenate', (['(labels_t, labels_test)'], {'axis': '(0)'}), '((labels_t, labels_test), axis=0)\n', (895, 928), True, 'import numpy as np\n'), ((938, 973), 'numpy.load', 'np.load', (['"""Data/cifar10_VGG_avg.npy"""'], {}), "('Data/cifar10_VGG_avg.npy')\n", (945, 973), True, 'import numpy as np\n'), ((1014, 1047), 'utils.sample_test_mask', 'sample_test_mask', (['labels_t'], {'N': '(100)'}), '(labels_t, N=100)\n', (1030, 1047), False, 'from utils import sample_test_mask\n'), ((1212, 1224), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1222, 1224), False, 'import keras, gc, nltk\n'), ((1236, 1281), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_mean': '(True)', 'with_std': '(True)'}), '(with_mean=True, with_std=True)\n', (1250, 1281), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1512, 1524), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1522, 1524), False, 'import keras, gc, nltk\n'), ((1625, 1677), 'numpy.concatenate', 'np.concatenate', (['(X_train_input, X_val_input)'], {'axis': '(0)'}), '((X_train_input, X_val_input), axis=0)\n', (1639, 1677), True, 'import numpy as np\n'), ((1690, 1730), 'numpy.concatenate', 'np.concatenate', (['(X_train, X_val)'], {'axis': '(0)'}), '((X_train, X_val), axis=0)\n', (1704, 1730), True, 'import numpy as np\n'), ((1748, 1798), 'numpy.concatenate', 'np.concatenate', (['(labels_train, labels_val)'], {'axis': '(0)'}), '((labels_train, labels_val), axis=0)\n', (1762, 1798), True, 'import numpy as np\n'), ((1863, 1891), 'sklearn.preprocessing.LabelEncoder', 'preprocessing.LabelEncoder', ([], {}), '()\n', (1889, 1891), False, 'from sklearn import preprocessing\n'), ((2123, 2169), 'keras.utils.to_categorical', 'to_categorical', (['y_train'], {'num_classes': 'n_classes'}), '(y_train, num_classes=n_classes)\n', (2137, 2169), False, 'from keras.utils import to_categorical\n'), ((2187, 2231), 'keras.utils.to_categorical', 'to_categorical', (['y_val'], {'num_classes': 'n_classes'}), '(y_val, num_classes=n_classes)\n', (2201, 2231), False, 'from keras.utils import to_categorical\n'), ((2250, 2295), 'keras.utils.to_categorical', 'to_categorical', (['y_test'], {'num_classes': 'n_classes'}), '(y_test, num_classes=n_classes)\n', (2264, 2295), False, 'from keras.utils import to_categorical\n'), ((2474, 2502), 'numpy.random.shuffle', 'np.random.shuffle', (['idx_train'], {}), '(idx_train)\n', (2491, 2502), True, 'import numpy as np\n'), ((2507, 2535), 'numpy.random.shuffle', 'np.random.shuffle', (['idx_train'], {}), '(idx_train)\n', (2524, 2535), True, 'import numpy as np\n'), ((3760, 3779), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3777, 3779), False, 'import time\n'), ((6654, 6666), 'gc.collect', 'gc.collect', ([], {}), '()\n', (6664, 6666), False, 'import keras, gc, nltk\n'), ((2337, 2367), 'numpy.random.seed', 'np.random.seed', (['seed_to_reseed'], {}), '(seed_to_reseed)\n', (2351, 2367), True, 'import numpy as np\n'), ((2386, 2418), 'numpy.random.seed', 'np.random.seed', (['__random_state__'], {}), '(__random_state__)\n', (2400, 2418), True, 'import numpy as np\n'), ((2897, 2923), 'numpy.random.shuffle', 'np.random.shuffle', (['idx_val'], {}), '(idx_val)\n', (2914, 2923), True, 'import numpy as np\n'), ((2932, 2958), 'numpy.random.shuffle', 'np.random.shuffle', (['idx_val'], {}), '(idx_val)\n', (2949, 2958), True, 'import numpy as np\n'), ((3275, 3327), 'numpy.concatenate', 'np.concatenate', (['(y_train_input, y_val_input)'], {'axis': '(0)'}), '((y_train_input, y_val_input), axis=0)\n', (3289, 3327), True, 'import numpy as np\n'), ((2763, 2782), 'numpy.zeros', 'np.zeros', (['n_classes'], {}), '(n_classes)\n', (2771, 2782), True, 'import numpy as np\n'), ((7594, 7606), 'gc.collect', 'gc.collect', ([], {}), '()\n', (7604, 7606), False, 'import keras, gc, nltk\n'), ((3230, 3249), 'numpy.zeros', 'np.zeros', (['n_classes'], {}), '(n_classes)\n', (3238, 3249), True, 'import numpy as np\n')]
|
from __future__ import division, print_function, absolute_import
from shutil import copyfile
from src.TensorFlowModels import ModelConfig
from src.Miscellaneous import bcolors
import os
import glob
import tflearn
import numpy as np
import pandas as pd
import tensorflow as tf
import src.TensorFlowModels as TFModels
import matplotlib
matplotlib.use('Agg') # use('Agg') for saving to file and use('TkAgg') for interactive plot
import matplotlib.pyplot as plt
class ModelTrainer:
def __init__(self, config_path=None, training_data_path=None, validation_data_path=None,
prediction_data_path=None, results_path=None):
# --------------------------------------
# Objects
# --------------------------------------
self.cfg = ModelConfig()
self.cfg.load(config_path)
# --------------------------------------
# Directories
# --------------------------------------
self._input_config_path = config_path
self._results_root_path = results_path + self.cfg.model_name + '/'
self._output_config_path = self._results_root_path + 'config.csv'
self._log_directory = self._results_root_path + 'logs/'
# Output Training Directories
self._training_results_path = self._results_root_path + 'training/'
self._epoch_checkpoint_path = self._training_results_path + 'epoch_results/'
self._best_checkpoint_path = self._training_results_path + 'best_results/'
self._last_checkpoint_path = self._training_results_path + 'last_results/'
self._training_images_path = self._training_results_path + 'images/'
# Output Validation Directories
self._validation_results_path = self._results_root_path + 'validation/'
# Output Prediction Directories
self._prediction_results_path = self._results_root_path + 'prediction/'
# Input Directories
self._train_data_path = training_data_path
self._validation_data_path = validation_data_path
self._prediction_data_path = prediction_data_path
# --------------------------------------
# Normal Variables
# --------------------------------------
self.validation_accuracy = []
self.training_accuracy = []
self._model_files = {}
# --------------------------------------
# Execute initialization functions
# --------------------------------------
# NOTE: DO NOT CHANGE THIS ORDER
self._init_directories()
self._init_model_data()
def test_func(self):
in_keys = ['m1CMD', 'm2CMD', '<KEY>']
out_keys = ['pitch', 'roll']
inputs, targets, num_samples = self._parse_input_data(self._model_files['training'][0], in_keys, out_keys)
def train_from_scratch(self, input_data_keys=None, output_data_keys=None,
training_plot_callback=None, validation_plot_callback=None):
# Sanity check that our input/output size do indeed match our config file
assert(len(input_data_keys) == self.cfg.input_size)
assert(len(output_data_keys) == self.cfg.output_size)
# Save so we know what data was used in the I/O modeling
self.cfg.input_keys = input_data_keys
self.cfg.output_keys = output_data_keys
self.cfg.save(self._output_config_path)
print(bcolors.OKBLUE + 'STARTING TRAINING OF: ' + self.cfg.model_name + bcolors.ENDC)
tf.reset_default_graph()
assert (isinstance(self.cfg.variable_scope, str))
with tf.variable_scope(self.cfg.variable_scope):
assert (np.isscalar(self.cfg.max_cpu_cores))
assert (np.isscalar(self.cfg.max_gpu_mem))
assert (isinstance(self.cfg.training_device, str))
tflearn.init_graph(num_cores=self.cfg.max_cpu_cores, gpu_memory_fraction=self.cfg.max_gpu_mem)
with tf.device(self.cfg.training_device):
model = self._generate_training_model()
# ---------------------------------------
# Train on each file present in training folder
# ---------------------------------------
file_iteration = 0
for training_file in self._model_files['training']:
print(bcolors.OKGREEN + 'TRAINING WITH FILE: ' + training_file + bcolors.ENDC)
# Grab the full set of input data
inputs, targets, num_samples = self._parse_input_data(filename=training_file,
input_keys=input_data_keys,
output_keys=output_data_keys)
# Split the data into parts for training so that we don't exhaust RAM resources
# All the data is pre-generated to save training time
total_train_iterations = int(np.ceil(num_samples / self.cfg.train_data_len))
t_inputs, t_targets = self._generate_training_data(input_full=inputs,
output_full=targets,
num_iter=total_train_iterations,
total_samples=num_samples)
# Pre-load random validation data to reduce runtime
file_num = np.random.randint(len(self._model_files['validation']))
v_inputs, v_targets = self._generate_validation_data(self._model_files['validation'][file_num])
# ---------------------------------------
# Fit on each data set
# ---------------------------------------
for train_iteration in range(0, total_train_iterations):
print(bcolors.OKGREEN + 'Iteration ' + str(train_iteration+1) + ' of ' +
str(total_train_iterations) + bcolors.ENDC)
model.fit(X_inputs=t_inputs[train_iteration],
Y_targets=t_targets[train_iteration],
n_epoch=self.cfg.epoch_len,
batch_size=self.cfg.batch_len,
validation_batch_size=self.cfg.batch_len,
validation_set=(v_inputs, v_targets),
show_metric=True,
snapshot_epoch=True,
run_id=self.cfg.model_name)
# Generate validation scores for training round
self.validation_accuracy.append(model.evaluate(X=v_inputs,
Y=v_targets,
batch_size=self.cfg.batch_len)[0])
self.training_accuracy.append(model.evaluate(X=t_inputs[train_iteration],
Y=t_targets[train_iteration],
batch_size=self.cfg.batch_len)[0])
# Generate prediction data
t_predict = model.predict(t_inputs[train_iteration])
v_predict = model.predict(v_inputs)
# Plot training results
if callable(training_plot_callback):
training_plot_callback(t_targets[train_iteration], t_predict)
img_name = 'f' + str(file_iteration) + '_iter' + str(train_iteration) + '_train.pdf'
plt.savefig(self._training_images_path + img_name, format='pdf', dpi=600)
if callable(validation_plot_callback):
validation_plot_callback(v_targets, v_predict)
img_name = 'f' + str(file_iteration) + '_iter' + str(train_iteration) + '_validate.pdf'
plt.savefig(self._training_images_path + img_name, format='pdf', dpi=600)
# ---------------------------------------
# Post processing/updating variables
# ---------------------------------------
file_iteration += 1
def _init_directories(self):
"""
If a directory doesn't exist, create it. Otherwise, empty it of all files (not folders)
:return:
"""
def init_dir(path, clean=True):
if not os.path.exists(path):
os.makedirs(path)
elif clean:
files = glob.glob(path + '*')
for f in files:
if not os.path.isdir(f):
os.remove(f)
init_dir(self._results_root_path)
init_dir(self._training_results_path)
init_dir(self._validation_results_path)
init_dir(self._prediction_results_path)
init_dir(self._epoch_checkpoint_path)
init_dir(self._best_checkpoint_path)
init_dir(self._last_checkpoint_path)
init_dir(self._training_images_path)
init_dir(self._log_directory + self.cfg.model_name + '/') # Tensorboard logs like this for some reason
def _init_model_data(self):
# Grab all the files available in the training, validation, and prediction paths
self._model_files['training'] = glob.glob(self._train_data_path + '*.csv')
self._model_files['validation'] = glob.glob(self._validation_data_path + '*.csv')
self._model_files['prediction'] = glob.glob(self._prediction_data_path + '*.csv')
# Copy over the configuration file for later use
copyfile(self._input_config_path, self._output_config_path)
# Update the model logging paths, overwriting whatever the user had
self.cfg.load(self._output_config_path)
self.cfg.epoch_chkpt_path = self._epoch_checkpoint_path + self.cfg.model_name
self.cfg.best_chkpt_path = self._best_checkpoint_path + self.cfg.model_name
self.cfg.last_chkpt_path = self._last_checkpoint_path + self.cfg.model_name
self.cfg.image_data_path = self._training_images_path + self.cfg.model_name
self.cfg.save(self._output_config_path)
def _generate_training_model(self):
"""
A factory function to generate a system model based upon values in the
class config object
"""
if self.cfg.data_inversion:
model_input_shape = [None, self.cfg.input_size, self.cfg.input_depth]
else:
model_input_shape = [None, self.cfg.input_depth, self.cfg.input_size]
# Grab the particular model function in use
assert (isinstance(self.cfg.model_type, str))
if self.cfg.model_type in TFModels.function_dispatcher:
model_func = TFModels.function_dispatcher[self.cfg.model_type]
else:
raise ValueError(bcolors.FAIL + 'Invalid model type!' + bcolors.ENDC)
# All models are guaranteed to have this input form
return model_func(shape=model_input_shape,
dim_in=self.cfg.input_size,
dim_out=self.cfg.output_size,
past_depth=self.cfg.input_depth,
layer_neurons=self.cfg.neurons_per_layer,
layer_dropout=self.cfg.layer_dropout,
learning_rate=self.cfg.learning_rate,
checkpoint_path=self.cfg.epoch_chkpt_path,
best_checkpoint_path=self.cfg.best_chkpt_path,
log_dir=self._log_directory)
def _generate_training_data(self, input_full, output_full, num_iter, total_samples):
output_x = [[] for i in range(num_iter)]
output_y = [[] for i in range(num_iter)]
current_train_idx = 0
for iteration in range(0, num_iter):
# Grab a full set of data if we have enough left
if (current_train_idx + self.cfg.train_data_len) < total_samples:
train_x, train_y = self._fill_data(raw_inputs=input_full,
raw_targets=output_full,
start_idx=current_train_idx,
end_idx=current_train_idx+self.cfg.train_data_len)
# Otherwise, only get remaining data
else:
train_x, train_y = self._fill_data(raw_inputs=input_full,
raw_targets=output_full,
start_idx=current_train_idx,
end_idx=(total_samples - self.cfg.input_depth))
# Return the data in the correct format for direct input into the network
output_x[iteration], output_y[iteration] = self._reshape_data(train_x, train_y)
current_train_idx += self.cfg.train_data_len
return output_x, output_y
def _generate_validation_data(self, filename):
try:
input_full, output_full, num_samples = self._parse_input_data(filename=filename,
input_keys=self.cfg.input_keys,
output_keys=self.cfg.output_keys)
except:
print(bcolors.WARNING + 'Validation file doesn\'t exist!' + bcolors.ENDC)
return None, None
validation_x, validation_y = self._fill_data(input_full, output_full, 0, num_samples)
validation_x, validation_y = self._reshape_data(validation_x, validation_y)
return validation_x, validation_y
def _parse_input_data(self, filename, input_keys, output_keys):
# --------------------------------------
# Attempt to read all the input data requested
# --------------------------------------
try:
data_set = pd.read_csv(filename)
except:
raise ValueError(bcolors.FAIL + 'Could not open file: ' + filename + bcolors.ENDC)
try:
data = []
for key in input_keys:
value = data_set[key]
data.append(value)
input_full = np.array(data)
except:
raise ValueError(bcolors.FAIL + 'Key does not exist in input dataset!' + bcolors.ENDC)
try:
data = []
for key in output_keys:
value = data_set[key]
data.append(value)
output_full = np.array(data)
except:
raise ValueError(bcolors.FAIL + 'Key does not exist in dataset!' + bcolors.ENDC)
# --------------------------------------
# Reformat for later processing
# --------------------------------------
# Ensures data is in row-wise format [vars x samples]
if self.cfg.data_inversion:
num_samples = np.shape(input_full)[1]
# Ensures data is in column-wise format [samples x vars]
else:
input_full = input_full.transpose()
output_full = output_full.transpose()
num_samples = np.shape(input_full)[0]
return input_full, output_full, num_samples
def _reshape_data(self, inputs, targets):
"""
Reshapes the input data into the correct form for the neural network
:param inputs:
:param targets:
:return:
"""
if self.cfg.data_inversion:
inputs = np.reshape(inputs, [-1, self.cfg.input_size, self.cfg.input_depth])
targets = np.reshape(targets, [-1, self.cfg.output_size])
else:
inputs = np.reshape(inputs, [-1, self.cfg.input_depth, self.cfg.input_size])
targets = np.reshape(targets, [-1, self.cfg.output_size])
return inputs, targets
def _fill_data(self, raw_inputs, raw_targets, start_idx, end_idx):
"""
Takes a set of input/target data and creates two new data sets that are a subset
of the original. That subset spans from [start_idx, end_idx]
:param raw_inputs:
:param raw_targets:
:param start_idx:
:param end_idx:
:return:
"""
inputs = []
targets = []
# Data should be formatted row-wise [vars x samples]
if self.cfg.data_inversion:
for i in range(start_idx, end_idx-self.cfg.input_depth):
inputs.append(raw_inputs[0:self.cfg.input_size, i:i + self.cfg.input_depth])
targets.append(raw_targets[0:self.cfg.output_size, i + self.cfg.input_depth])
# Data should be formatted column-wise [samples x vars]
else:
for i in range(start_idx, end_idx-self.cfg.input_depth):
inputs.append(raw_inputs[i:i + self.cfg.input_depth, 0:self.cfg.input_size])
targets.append(raw_targets[i + self.cfg.input_depth, 0:self.cfg.output_size])
return inputs, targets
|
[
"os.remove",
"pandas.read_csv",
"tensorflow.reset_default_graph",
"numpy.shape",
"glob.glob",
"os.path.exists",
"tensorflow.variable_scope",
"numpy.reshape",
"shutil.copyfile",
"numpy.ceil",
"matplotlib.use",
"src.TensorFlowModels.ModelConfig",
"os.makedirs",
"numpy.isscalar",
"os.path.isdir",
"tensorflow.device",
"numpy.array",
"tflearn.init_graph",
"matplotlib.pyplot.savefig"
] |
[((337, 358), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (351, 358), False, 'import matplotlib\n'), ((778, 791), 'src.TensorFlowModels.ModelConfig', 'ModelConfig', ([], {}), '()\n', (789, 791), False, 'from src.TensorFlowModels import ModelConfig\n'), ((3483, 3507), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (3505, 3507), True, 'import tensorflow as tf\n'), ((9640, 9682), 'glob.glob', 'glob.glob', (["(self._train_data_path + '*.csv')"], {}), "(self._train_data_path + '*.csv')\n", (9649, 9682), False, 'import glob\n'), ((9725, 9772), 'glob.glob', 'glob.glob', (["(self._validation_data_path + '*.csv')"], {}), "(self._validation_data_path + '*.csv')\n", (9734, 9772), False, 'import glob\n'), ((9815, 9862), 'glob.glob', 'glob.glob', (["(self._prediction_data_path + '*.csv')"], {}), "(self._prediction_data_path + '*.csv')\n", (9824, 9862), False, 'import glob\n'), ((9929, 9988), 'shutil.copyfile', 'copyfile', (['self._input_config_path', 'self._output_config_path'], {}), '(self._input_config_path, self._output_config_path)\n', (9937, 9988), False, 'from shutil import copyfile\n'), ((3579, 3621), 'tensorflow.variable_scope', 'tf.variable_scope', (['self.cfg.variable_scope'], {}), '(self.cfg.variable_scope)\n', (3596, 3621), True, 'import tensorflow as tf\n'), ((3643, 3678), 'numpy.isscalar', 'np.isscalar', (['self.cfg.max_cpu_cores'], {}), '(self.cfg.max_cpu_cores)\n', (3654, 3678), True, 'import numpy as np\n'), ((3700, 3733), 'numpy.isscalar', 'np.isscalar', (['self.cfg.max_gpu_mem'], {}), '(self.cfg.max_gpu_mem)\n', (3711, 3733), True, 'import numpy as np\n'), ((3811, 3910), 'tflearn.init_graph', 'tflearn.init_graph', ([], {'num_cores': 'self.cfg.max_cpu_cores', 'gpu_memory_fraction': 'self.cfg.max_gpu_mem'}), '(num_cores=self.cfg.max_cpu_cores, gpu_memory_fraction=\n self.cfg.max_gpu_mem)\n', (3829, 3910), False, 'import tflearn\n'), ((14292, 14313), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (14303, 14313), True, 'import pandas as pd\n'), ((14595, 14609), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (14603, 14609), True, 'import numpy as np\n'), ((14897, 14911), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (14905, 14911), True, 'import numpy as np\n'), ((15859, 15926), 'numpy.reshape', 'np.reshape', (['inputs', '[-1, self.cfg.input_size, self.cfg.input_depth]'], {}), '(inputs, [-1, self.cfg.input_size, self.cfg.input_depth])\n', (15869, 15926), True, 'import numpy as np\n'), ((15949, 15996), 'numpy.reshape', 'np.reshape', (['targets', '[-1, self.cfg.output_size]'], {}), '(targets, [-1, self.cfg.output_size])\n', (15959, 15996), True, 'import numpy as np\n'), ((16033, 16100), 'numpy.reshape', 'np.reshape', (['inputs', '[-1, self.cfg.input_depth, self.cfg.input_size]'], {}), '(inputs, [-1, self.cfg.input_depth, self.cfg.input_size])\n', (16043, 16100), True, 'import numpy as np\n'), ((16123, 16170), 'numpy.reshape', 'np.reshape', (['targets', '[-1, self.cfg.output_size]'], {}), '(targets, [-1, self.cfg.output_size])\n', (16133, 16170), True, 'import numpy as np\n'), ((3923, 3958), 'tensorflow.device', 'tf.device', (['self.cfg.training_device'], {}), '(self.cfg.training_device)\n', (3932, 3958), True, 'import tensorflow as tf\n'), ((8757, 8777), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (8771, 8777), False, 'import os\n'), ((8795, 8812), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (8806, 8812), False, 'import os\n'), ((15284, 15304), 'numpy.shape', 'np.shape', (['input_full'], {}), '(input_full)\n', (15292, 15304), True, 'import numpy as np\n'), ((15512, 15532), 'numpy.shape', 'np.shape', (['input_full'], {}), '(input_full)\n', (15520, 15532), True, 'import numpy as np\n'), ((8861, 8882), 'glob.glob', 'glob.glob', (["(path + '*')"], {}), "(path + '*')\n", (8870, 8882), False, 'import glob\n'), ((4983, 5029), 'numpy.ceil', 'np.ceil', (['(num_samples / self.cfg.train_data_len)'], {}), '(num_samples / self.cfg.train_data_len)\n', (4990, 5029), True, 'import numpy as np\n'), ((7873, 7946), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(self._training_images_path + img_name)'], {'format': '"""pdf"""', 'dpi': '(600)'}), "(self._training_images_path + img_name, format='pdf', dpi=600)\n", (7884, 7946), True, 'import matplotlib.pyplot as plt\n'), ((8231, 8304), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(self._training_images_path + img_name)'], {'format': '"""pdf"""', 'dpi': '(600)'}), "(self._training_images_path + img_name, format='pdf', dpi=600)\n", (8242, 8304), True, 'import matplotlib.pyplot as plt\n'), ((8942, 8958), 'os.path.isdir', 'os.path.isdir', (['f'], {}), '(f)\n', (8955, 8958), False, 'import os\n'), ((8984, 8996), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (8993, 8996), False, 'import os\n')]
|
# ------------------------------------------------------------------------------
# Program: The LDAR Simulator (LDAR-Sim)
# File: methods.deployment.OGI_Camera
# Purpose: OGI company specific deployment classes and methods based on RK (2018)
#
# Copyright (C) 2018-2021 Intelligent Methane Monitoring and Management System (IM3S) Group
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the MIT License as published
# by the Free Software Foundation, version 3.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
# You should have received a copy of the MIT License
# along with this program. If not, see <https://opensource.org/licenses/MIT>.
#
# ------------------------------------------------------------------------------
import math
import numpy as np
from methods.funcs import measured_rate
from utils.attribution import update_tag
def detect_emissions(self, site, covered_leaks, covered_equipment_rates, covered_site_rate,
site_rate, venting, equipment_rates):
missed_leaks_str = '{}_missed_leaks'.format(self.config['label'])
equip_measured_rates = []
site_measured_rate = 0
found_leak = False
for leak in covered_leaks:
k = np.random.normal(4.9, 0.3)
x0 = np.random.normal(self.config['sensor']['MDL'][0], self.config['sensor']['MDL'][1])
x0 = math.log10(x0 * 3600) # Convert from g/s to g/h and take log
if leak['rate'] == 0:
prob_detect = 0
else:
x = math.log10(leak['rate'] * 3600) # Convert from g/s to g/h
prob_detect = 1 / (1 + math.exp(-k * (x - x0)))
if np.random.binomial(1, prob_detect):
found_leak = True
is_new_leak = update_tag(leak, site, self.timeseries, self.state['t'],
self.config['label'], self.id)
if is_new_leak:
site_measured_rate += measured_rate(leak['rate'], self.config['sensor']['QE'])
else:
site[missed_leaks_str] += 1
self.timeseries[missed_leaks_str][self.state['t'].current_timestep] += 1
site_dict = {
'site': site,
'leaks_present': covered_leaks,
'site_true_rate': site_rate,
'site_measured_rate': site_measured_rate,
'equip_measured_rates': equip_measured_rates,
'vent_rate': venting,
'found_leak': found_leak,
}
return site_dict
|
[
"math.exp",
"numpy.random.binomial",
"methods.funcs.measured_rate",
"math.log10",
"numpy.random.normal",
"utils.attribution.update_tag"
] |
[((1428, 1454), 'numpy.random.normal', 'np.random.normal', (['(4.9)', '(0.3)'], {}), '(4.9, 0.3)\n', (1444, 1454), True, 'import numpy as np\n'), ((1468, 1555), 'numpy.random.normal', 'np.random.normal', (["self.config['sensor']['MDL'][0]", "self.config['sensor']['MDL'][1]"], {}), "(self.config['sensor']['MDL'][0], self.config['sensor'][\n 'MDL'][1])\n", (1484, 1555), True, 'import numpy as np\n'), ((1564, 1585), 'math.log10', 'math.log10', (['(x0 * 3600)'], {}), '(x0 * 3600)\n', (1574, 1585), False, 'import math\n'), ((1846, 1880), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'prob_detect'], {}), '(1, prob_detect)\n', (1864, 1880), True, 'import numpy as np\n'), ((1715, 1746), 'math.log10', 'math.log10', (["(leak['rate'] * 3600)"], {}), "(leak['rate'] * 3600)\n", (1725, 1746), False, 'import math\n'), ((1938, 2030), 'utils.attribution.update_tag', 'update_tag', (['leak', 'site', 'self.timeseries', "self.state['t']", "self.config['label']", 'self.id'], {}), "(leak, site, self.timeseries, self.state['t'], self.config[\n 'label'], self.id)\n", (1948, 2030), False, 'from utils.attribution import update_tag\n'), ((2129, 2185), 'methods.funcs.measured_rate', 'measured_rate', (["leak['rate']", "self.config['sensor']['QE']"], {}), "(leak['rate'], self.config['sensor']['QE'])\n", (2142, 2185), False, 'from methods.funcs import measured_rate\n'), ((1809, 1832), 'math.exp', 'math.exp', (['(-k * (x - x0))'], {}), '(-k * (x - x0))\n', (1817, 1832), False, 'import math\n')]
|
import numpy as np
from tilitools.svdd_dual_qp import SvddDualQP
class LatentSVDD:
""" Latent variable support vector data description.
Written by <NAME>, TU Berlin, 2014
For more information see:
'Learning and Evaluation with non-i.i.d Label Noise'
Goernitz et al., AISTATS & JMLR W&CP, 2014
"""
PRECISION = 1e-3 # important: effects the threshold, support vectors and speed!
nu = 1.0 # (scalar) the regularization constant > 0
sobj = None # structured object contains various functions
# i.e. get_num_dims(), get_num_samples(), get_sample(i), argmin(sol,i)
sol = None # (vector) solution vector (after training, of course)
def __init__(self, sobj, nu=1.0):
self.nu = nu
self.sobj = sobj
def fit(self, max_iter=50):
""" Solve the LatentSVDD optimization problem with a
sequential convex programming/DC-programming
approach:
Iteratively, find the most likely configuration of
the latent variables and then, optimize for the
model parameter using fixed latent states.
"""
N = self.sobj.get_num_samples()
DIMS = self.sobj.get_num_dims()
# intermediate solutions
# latent variables
latent = [0]*N
sol = np.random.randn(DIMS).reshape((DIMS, 1))
psi = np.zeros((DIMS, N)) # (dim x exm)
old_psi = np.zeros((DIMS, N)) # (dim x exm)
threshold = 0.
obj = -1.
iter = 0
# terminate if objective function value doesn't change much
while iter<max_iter and (iter<2 or sum(sum(abs(np.array(psi-old_psi))))>=0.001):
print('Starting iteration {0}.'.format(iter))
print(sum(sum(abs(np.array(psi-old_psi)))))
iter += 1
old_psi = psi
# 1. linearize
# for the current solution compute the
# most likely latent variable configuration
for i in range(N):
# min_z ||sol - Psi(x,z)||^2 = ||sol||^2 + min_z -2<sol,Psi(x,z)> + ||Psi(x,z)||^2
# Hence => ||sol||^2 - max_z 2<sol,Psi(x,z)> - ||Psi(x,z)||^2
_, latent[i], foo = self.sobj.argmax(sol, i, opt_type='quadratic')
psi[:, i] = foo.ravel()
# 2. solve the intermediate convex optimization problem
svdd = SvddDualQP('linear', None, self.nu)
svdd.fit(psi)
threshold = svdd.get_radius()
sol = psi.dot(svdd.alphas)
self.sol = sol
self.latent = latent
return sol, latent, threshold
def apply(self, pred_sobj):
""" Application of the LatentSVDD:
anomaly_score = min_z ||c*-\Psi(x,z)||^2
latent_state = argmin_z ||c*-\Psi(x,z)||^2
"""
N = pred_sobj.get_num_samples()
norm2 = self.sol.T.dot(self.sol)
vals = np.zeros((N))
lats = [0]*N
for i in range(N):
# min_z ||sol - Psi(x,z)||^2 = ||sol||^2 + min_z -2<sol,Psi(x,z)> + ||Psi(x,z)||^2
# Hence => ||sol||^2 - max_z 2<sol,Psi(x,z)> - ||Psi(x,z)||^2
max_obj, lats[i], foo = pred_sobj.argmax(self.sol, i, opt_type='quadratic')
vals[i] = norm2 - max_obj
return vals, lats
|
[
"numpy.array",
"tilitools.svdd_dual_qp.SvddDualQP",
"numpy.zeros",
"numpy.random.randn"
] |
[((1386, 1405), 'numpy.zeros', 'np.zeros', (['(DIMS, N)'], {}), '((DIMS, N))\n', (1394, 1405), True, 'import numpy as np\n'), ((1439, 1458), 'numpy.zeros', 'np.zeros', (['(DIMS, N)'], {}), '((DIMS, N))\n', (1447, 1458), True, 'import numpy as np\n'), ((2933, 2944), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2941, 2944), True, 'import numpy as np\n'), ((2406, 2441), 'tilitools.svdd_dual_qp.SvddDualQP', 'SvddDualQP', (['"""linear"""', 'None', 'self.nu'], {}), "('linear', None, self.nu)\n", (2416, 2441), False, 'from tilitools.svdd_dual_qp import SvddDualQP\n'), ((1331, 1352), 'numpy.random.randn', 'np.random.randn', (['DIMS'], {}), '(DIMS)\n', (1346, 1352), True, 'import numpy as np\n'), ((1777, 1800), 'numpy.array', 'np.array', (['(psi - old_psi)'], {}), '(psi - old_psi)\n', (1785, 1800), True, 'import numpy as np\n'), ((1655, 1678), 'numpy.array', 'np.array', (['(psi - old_psi)'], {}), '(psi - old_psi)\n', (1663, 1678), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# coding: utf-8
# # ml lab5
# In[7]:
import os
import numpy as np
import scipy.optimize as opt
import scipy.io
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# ### 1. read `ex5data1.mat`
# In[4]:
data = scipy.io.loadmat('data/ex5data1.mat')
X = data['X']
y = np.squeeze(data['y'])
X.shape, y.size
# ### 2. plot data
# In[25]:
def plot_data(X, y, axes=None):
if axes == None:
axes = plt.gca()
axes.scatter(X[y == 1, 0], X[y == 1, 1], marker='x', c='g', s=30, label='y = 1')
axes.scatter(X[y == 0, 0], X[y == 0, 1], c='r', s=30, label='y = 0')
axes.set_xlabel('X1')
axes.set_ylabel('X2')
axes.legend(frameon= True, fancybox = True)
return axes
plot_data(X, y)
# ### 3. svm classifier
# In[8]:
from sklearn import svm
clf = svm.LinearSVC()
clf.fit(X, y)
# ### 4. descision boundary with `c=1`, `c=100`
# In[23]:
C_VALS = [1, 100]
fig, axes = plt.subplots(1, 2, sharey = True, figsize=(16, 6))
def get_meshgrid(X, num=100):
return np.meshgrid(
np.linspace(X[:, 0].min(), X[:, 0].max(), num=100),
np.linspace(X[:, 1].min(), X[:, 1].max(), num=100)
)
for i, C in enumerate(C_VALS):
X_1, X_2 = get_meshgrid(X)
clf = svm.LinearSVC(C=C, max_iter=100000)
clf.fit(X, y)
Z = clf.predict(np.array([X_1.ravel(), X_2.ravel()]).T).reshape(X_1.shape)
plot_data(X, y, axes[i])
axes[i].contour(X_1, X_2, Z, 1, colors='b')
axes[i].set_title(f'Descision Boundary with C={C}')
# > При `C=100` можно наблюдать переобученую модель: граница захватывает случайные выбросы. При `C=1` граница выглядит правильно.
# ### 5. svm gaussian kernel
# In[22]:
def gaussian_kernel(x1, x2, sigma):
return np.exp(-np.sum((x1 - x2) ** 2) / (2 * (sigma ** 2)))
def gaussian_kernel_gram_matrix(X, L, sigma, K_function=gaussian_kernel):
gram_matrix = np.zeros((X.shape[0], L.shape[0]))
for i, x in enumerate(X):
for j, l in enumerate(L):
gram_matrix[i, j] = K_function(x, l, sigma)
return gram_matrix
# ### 6-8. `ex5data2.mat` with svm gaussian kernel
# In[29]:
data = scipy.io.loadmat('data/ex5data2.mat')
X = data['X']
y = np.squeeze(data['y'])
L = X
sigma = 0.1
gram = gaussian_kernel_gram_matrix(X, L, sigma)
clf = svm.SVC(kernel='precomputed')
clf.fit(gram, y)
# ### 9. plot data
# In[30]:
ax = plot_data(X, y)
X_1, X_2 = get_meshgrid(X)
X_plot = np.array([X_1.ravel(), X_2.ravel()]).T
gram_plot = gaussian_kernel_gram_matrix(X_plot, L, sigma)
Z = clf.predict(gram_plot).reshape(X_1.shape)
ax.contour(X_1, X_2, Z, 1, colors='b')
# ### 10. read `ex5data3` data
# In[33]:
data = scipy.io.loadmat('data/ex5data3.mat')
X = data['X']
y = np.squeeze(data['y'])
X_val = data['Xval']
y_val = np.squeeze(data['yval'])
X.shape, X_val.shape
# ### 11. cross validation
# In[34]:
def cross_validate(X, y, X_val, y_val):
C_array = np.array([0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30])
sigma_array = np.array([0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30])
err_array = np.zeros([C_array.size, sigma_array.size])
for i in np.arange(C_array.size):
for j in np.arange(sigma_array.size):
sigma = sigma_array[j]
C = C_array[i]
gram = gaussian_kernel_gram_matrix(X, X, sigma)
clf = svm.SVC(C=C, kernel='precomputed')
clf.fit(gram, y)
predictions = clf.predict(gaussian_kernel_gram_matrix(X_val, X, sigma))
pred_error = np.mean(predictions != y_val)
err_array[i, j] = pred_error
idx = np.unravel_index(np.argmin(err_array, axis=None), err_array.shape)
C = C_array[idx[0]]
sigma = sigma_array[idx[1]]
return C, sigma
# In[35]:
C, sigma = cross_validate(X, y, X_val, y_val)
print(f'Found:\nC:\t{C}\nsigma:\t{sigma}')
# In[36]:
gram = gaussian_kernel_gram_matrix(X, X, sigma)
clf = svm.SVC(C=C, kernel='precomputed')
clf.fit(gram, y)
# ### 12. plot data
# In[37]:
ax = plot_data(X, y)
X_1, X_2 = get_meshgrid(X, num=50)
X_plot = np.array([X_1.ravel(), X_2.ravel()]).T
gram_plot = gaussian_kernel_gram_matrix(X_plot, X, sigma)
Z = clf.predict(gram_plot).reshape(X_1.shape)
ax.contour(X_1, X_2, Z, 1, colors='b')
# ### 13-15. read `spamTrain.mat` & `spamTest.mat` data
# In[38]:
spam_train = scipy.io.loadmat('data/spamTrain.mat')
X = spam_train['X']
y = np.squeeze(spam_train['y'])
spam_test = scipy.io.loadmat('data/spamTest.mat')
X_test = spam_test['Xtest']
y_test = np.squeeze(spam_test['ytest'])
# ### 14-16. svm + cross validation
# In[39]:
def spam_cross_validation(X, y, X_val, y_val):
C_array = np.array([0.01, 0.1, 0.3, 1, 10])
err_array = np.zeros(C_array.size)
for i in np.arange(C_array.size):
C = C_array[i]
clf = svm.SVC(C=C, kernel='linear')
clf.fit(X, y)
predictions = clf.predict(X_val)
pred_error = np.mean(predictions != y_val)
err_array[i] = pred_error
idx = np.unravel_index(np.argmin(err_array, axis=None), err_array.shape)
return C_array[idx[0]]
# In[40]:
C = spam_cross_validation(X, y, X_test, y_test)
print(f'Found:\nC:\t{C}\n')
# In[42]:
clf = svm.SVC(C=C, kernel='linear')
clf.fit(X, y)
train_accuracy = clf.score(X, y) * 100
test_accuracy = clf.score(X_test, y_test) * 100
print(f'Train accuracy:\t{train_accuracy}%')
print(f'Test accuracy:\t{test_accuracy}%')
# > Линейное ядро быстрее и точнее чем Гаусовское
# ### 17. text preprocessing
# In[44]:
import re
from nltk.stem import PorterStemmer
ps = PorterStemmer()
HTML_REGEX = r'<.*?>'
URL_REGEX = r'[http|https]://[^\s]*'
EMAIL_REGEX = r'[^\s]+@[^\s]+'
NUMBER_REGEX = r'[0-9]+'
DOLLAR_REGEX = r'[$]+'
def preprocess_data(data):
result = data.lower()
result = re.sub(HTML_REGEX, '', result)
result = re.sub(URL_REGEX, 'httpaddr', result)
result = re.sub(EMAIL_REGEX, 'emailaddr', result)
result = re.sub(NUMBER_REGEX, ' number ', result)
result = re.sub(DOLLAR_REGEX, ' dollar ', result)
result = re.sub(r'[^a-zA-Z\s]+', ' ', result)
result = result.replace('\n', ' ')
result = [ps.stem(token) for token in result.split(' ')]
result = ' '.join(result)
return result
# ### 18. read `vocab.txt`
# In[45]:
vocab_data = open('data/vocab.txt', 'r').read().split('\n')[:-1]
vocab = {}
for elem in vocab_data:
index, word = elem.split('\t')[:]
vocab[word] = index
# ### 19. word to code
# In[46]:
def map_to_vocabulary(data, vocab):
result = []
for word in data.split():
if len(word) > 1 and word in vocab:
result.append(int(vocab[word]))
return result
# ### 20. text to feature vector
# In[47]:
def map_to_feature(data, vocab):
n = len(vocab)
features = np.zeros((n,))
for i in data:
features[i] = 1
return features
# In[50]:
def generate_feature(data, vocab):
preprocessed = preprocess_data(data)
word_indexes = map_to_vocabulary(preprocessed, vocab)
feature = map_to_feature(word_indexes, vocab)
return feature
# ### 21. test classifier
# In[53]:
def predict_from_files(files, vocab, clf):
features = []
for file in files:
feature = generate_feature(open(f'data/{file}', 'r').read(), vocab)
features.append(feature)
features = np.array(features)
result = clf.predict(features)
return zip(files, result)
# In[54]:
FILES = ['emailSample1.txt', 'emailSample2.txt', 'spamSample1.txt', 'spamSample2.txt']
predicts = predict_from_files(FILES, vocab, clf)
for file, predict in predicts:
res = 'spam' if predict == 1 else 'not spam'
print(f'{file} - {res}')
# ### 22. get dataset from [`spamassassin.apache.org/old/publiccorpus`](http://spamassassin.apache.org/old/publiccorpus/)
# In[67]:
HAM_DIR = 'data/easy_ham'
SPAM_DIR = 'data/spam'
def read_data(data_dir, out):
files = os.listdir(data_dir)
for file_name in files:
if file_name == '.DS_Store':
continue
with open(f'{data_dir}/{file_name}', 'r') as f:
try:
out.append(f.read())
except:
continue
return out
X_data = []
X_data = read_data(HAM_DIR, X_data)
y_ham = np.zeros(len(X_data))
X_data = read_data(SPAM_DIR, X_data)
y_spam = np.ones(len(X_data) - len(y_ham))
y = np.concatenate((y_ham, y_spam))
len(X_data), y.size
# ### 24. build vocabulary
# In[68]:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
X_vocab = []
for data in X_data[100:]:
X_vocab.append(preprocess_data(data))
vectorizer = CountVectorizer()
vectorizer.fit(X_vocab)
n = 1000
vocab = {}
index = 0
for word in vectorizer.vocabulary_:
vocab[word] = index
index += 1
if index >= n:
break
# ### 25. test new dataset
# In[69]:
X = []
for data in X_data:
feature = generate_feature(data, vocab)
X.append(feature)
X = np.array(X)
# In[70]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# In[71]:
C = 0.1
clf = svm.SVC(C=C, kernel='linear')
clf.fit(X_train, y_train)
train_accuracy = clf.score(X, y) * 100
test_accuracy = clf.score(X_test, y_test) * 100
print(f'Train accuracy:\t{train_accuracy}%')
print(f'Test accuracy:\t{test_accuracy}%')
# In[73]:
FILES = ['emailSample1.txt', 'emailSample2.txt', 'spamSample1.txt', 'spamSample2.txt']
predicts = predict_from_files(FILES, vocab, clf)
for file, predict in predicts:
res = 'spam' if predict == 1 else 'not spam'
print(f'{file} - {res}')
# > Качество классификации сохранилось, тк новый датасет достаточно большой, что позволяет произвести обучение
# ### 26. conclusions
# Был рассмотрен метод опорных векторов, обучен класификатор с разными ядрами, подобраны параметры C и σ2. Протестирован анализатор спама в сообщениях как на готовом наборе признаков, так и на собственном словаре
# In[ ]:
|
[
"sklearn.feature_extraction.text.CountVectorizer",
"numpy.sum",
"nltk.stem.PorterStemmer",
"matplotlib.pyplot.gca",
"sklearn.model_selection.train_test_split",
"numpy.zeros",
"numpy.argmin",
"re.sub",
"numpy.mean",
"numpy.array",
"numpy.arange",
"sklearn.svm.SVC",
"numpy.squeeze",
"sklearn.svm.LinearSVC",
"matplotlib.pyplot.subplots",
"os.listdir",
"numpy.concatenate"
] |
[((311, 332), 'numpy.squeeze', 'np.squeeze', (["data['y']"], {}), "(data['y'])\n", (321, 332), True, 'import numpy as np\n'), ((839, 854), 'sklearn.svm.LinearSVC', 'svm.LinearSVC', ([], {}), '()\n', (852, 854), False, 'from sklearn import svm\n'), ((962, 1010), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'sharey': '(True)', 'figsize': '(16, 6)'}), '(1, 2, sharey=True, figsize=(16, 6))\n', (974, 1010), True, 'import matplotlib.pyplot as plt\n'), ((2217, 2238), 'numpy.squeeze', 'np.squeeze', (["data['y']"], {}), "(data['y'])\n", (2227, 2238), True, 'import numpy as np\n'), ((2312, 2341), 'sklearn.svm.SVC', 'svm.SVC', ([], {'kernel': '"""precomputed"""'}), "(kernel='precomputed')\n", (2319, 2341), False, 'from sklearn import svm\n'), ((2743, 2764), 'numpy.squeeze', 'np.squeeze', (["data['y']"], {}), "(data['y'])\n", (2753, 2764), True, 'import numpy as np\n'), ((2794, 2818), 'numpy.squeeze', 'np.squeeze', (["data['yval']"], {}), "(data['yval'])\n", (2804, 2818), True, 'import numpy as np\n'), ((3938, 3972), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': 'C', 'kernel': '"""precomputed"""'}), "(C=C, kernel='precomputed')\n", (3945, 3972), False, 'from sklearn import svm\n'), ((4421, 4448), 'numpy.squeeze', 'np.squeeze', (["spam_train['y']"], {}), "(spam_train['y'])\n", (4431, 4448), True, 'import numpy as np\n'), ((4537, 4567), 'numpy.squeeze', 'np.squeeze', (["spam_test['ytest']"], {}), "(spam_test['ytest'])\n", (4547, 4567), True, 'import numpy as np\n'), ((5241, 5270), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': 'C', 'kernel': '"""linear"""'}), "(C=C, kernel='linear')\n", (5248, 5270), False, 'from sklearn import svm\n'), ((5609, 5624), 'nltk.stem.PorterStemmer', 'PorterStemmer', ([], {}), '()\n', (5622, 5624), False, 'from nltk.stem import PorterStemmer\n'), ((8383, 8414), 'numpy.concatenate', 'np.concatenate', (['(y_ham, y_spam)'], {}), '((y_ham, y_spam))\n', (8397, 8414), True, 'import numpy as np\n'), ((8688, 8705), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (8703, 8705), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((9008, 9019), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (9016, 9019), True, 'import numpy as np\n'), ((9069, 9106), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (9085, 9106), False, 'from sklearn.model_selection import train_test_split\n'), ((9135, 9164), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': 'C', 'kernel': '"""linear"""'}), "(C=C, kernel='linear')\n", (9142, 9164), False, 'from sklearn import svm\n'), ((1271, 1306), 'sklearn.svm.LinearSVC', 'svm.LinearSVC', ([], {'C': 'C', 'max_iter': '(100000)'}), '(C=C, max_iter=100000)\n', (1284, 1306), False, 'from sklearn import svm\n'), ((1910, 1944), 'numpy.zeros', 'np.zeros', (['(X.shape[0], L.shape[0])'], {}), '((X.shape[0], L.shape[0]))\n', (1918, 1944), True, 'import numpy as np\n'), ((2937, 2983), 'numpy.array', 'np.array', (['[0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30]'], {}), '([0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30])\n', (2945, 2983), True, 'import numpy as np\n'), ((3002, 3048), 'numpy.array', 'np.array', (['[0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30]'], {}), '([0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30])\n', (3010, 3048), True, 'import numpy as np\n'), ((3065, 3107), 'numpy.zeros', 'np.zeros', (['[C_array.size, sigma_array.size]'], {}), '([C_array.size, sigma_array.size])\n', (3073, 3107), True, 'import numpy as np\n'), ((3126, 3149), 'numpy.arange', 'np.arange', (['C_array.size'], {}), '(C_array.size)\n', (3135, 3149), True, 'import numpy as np\n'), ((4680, 4713), 'numpy.array', 'np.array', (['[0.01, 0.1, 0.3, 1, 10]'], {}), '([0.01, 0.1, 0.3, 1, 10])\n', (4688, 4713), True, 'import numpy as np\n'), ((4730, 4752), 'numpy.zeros', 'np.zeros', (['C_array.size'], {}), '(C_array.size)\n', (4738, 4752), True, 'import numpy as np\n'), ((4767, 4790), 'numpy.arange', 'np.arange', (['C_array.size'], {}), '(C_array.size)\n', (4776, 4790), True, 'import numpy as np\n'), ((5830, 5860), 're.sub', 're.sub', (['HTML_REGEX', '""""""', 'result'], {}), "(HTML_REGEX, '', result)\n", (5836, 5860), False, 'import re\n'), ((5874, 5911), 're.sub', 're.sub', (['URL_REGEX', '"""httpaddr"""', 'result'], {}), "(URL_REGEX, 'httpaddr', result)\n", (5880, 5911), False, 'import re\n'), ((5925, 5965), 're.sub', 're.sub', (['EMAIL_REGEX', '"""emailaddr"""', 'result'], {}), "(EMAIL_REGEX, 'emailaddr', result)\n", (5931, 5965), False, 'import re\n'), ((5979, 6019), 're.sub', 're.sub', (['NUMBER_REGEX', '""" number """', 'result'], {}), "(NUMBER_REGEX, ' number ', result)\n", (5985, 6019), False, 'import re\n'), ((6033, 6073), 're.sub', 're.sub', (['DOLLAR_REGEX', '""" dollar """', 'result'], {}), "(DOLLAR_REGEX, ' dollar ', result)\n", (6039, 6073), False, 'import re\n'), ((6087, 6123), 're.sub', 're.sub', (['"""[^a-zA-Z\\\\s]+"""', '""" """', 'result'], {}), "('[^a-zA-Z\\\\s]+', ' ', result)\n", (6093, 6123), False, 'import re\n'), ((6818, 6832), 'numpy.zeros', 'np.zeros', (['(n,)'], {}), '((n,))\n', (6826, 6832), True, 'import numpy as np\n'), ((7369, 7387), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (7377, 7387), True, 'import numpy as np\n'), ((7942, 7962), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (7952, 7962), False, 'import os\n'), ((455, 464), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (462, 464), True, 'import matplotlib.pyplot as plt\n'), ((3168, 3195), 'numpy.arange', 'np.arange', (['sigma_array.size'], {}), '(sigma_array.size)\n', (3177, 3195), True, 'import numpy as np\n'), ((3636, 3667), 'numpy.argmin', 'np.argmin', (['err_array'], {'axis': 'None'}), '(err_array, axis=None)\n', (3645, 3667), True, 'import numpy as np\n'), ((4838, 4867), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': 'C', 'kernel': '"""linear"""'}), "(C=C, kernel='linear')\n", (4845, 4867), False, 'from sklearn import svm\n'), ((4961, 4990), 'numpy.mean', 'np.mean', (['(predictions != y_val)'], {}), '(predictions != y_val)\n', (4968, 4990), True, 'import numpy as np\n'), ((5054, 5085), 'numpy.argmin', 'np.argmin', (['err_array'], {'axis': 'None'}), '(err_array, axis=None)\n', (5063, 5085), True, 'import numpy as np\n'), ((3350, 3384), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': 'C', 'kernel': '"""precomputed"""'}), "(C=C, kernel='precomputed')\n", (3357, 3384), False, 'from sklearn import svm\n'), ((3536, 3565), 'numpy.mean', 'np.mean', (['(predictions != y_val)'], {}), '(predictions != y_val)\n', (3543, 3565), True, 'import numpy as np\n'), ((1772, 1794), 'numpy.sum', 'np.sum', (['((x1 - x2) ** 2)'], {}), '((x1 - x2) ** 2)\n', (1778, 1794), True, 'import numpy as np\n')]
|
import numpy as np
class simulated_parameter:
def __init__(self, parameter_name, parameter_mean, parameter_stddev, start_year, end_year):
self._parameter_name = parameter_name
self._parameter_mean = parameter_mean
self._parameter_stddev = parameter_stddev
self._start_year = start_year
self._end_year = end_year
def get_simulated_value(self):
return np.random.normal(
loc=self._parameter_mean,
scale=self._parameter_stddev,
size=1)[0]
def get_param_name(self):
return self._parameter_name
class recurring_payment:
"""
Represents a recurring payment (income for positive sums and expenses for negative sums).
Args:
name: the name of the payment
annual_sum: the annual total sum of the payment.
annual_change: the annual change in the annual sum.
payment_stdev: the standard deviation in the annual sum.
start_year: the year in which the payment starts.
end_year: the year in which the payment ends.
"""
def __init__(self, name, annual_sum, annual_change, payment_stdev, start_year, end_year):
self._name = name
self._annual_sum = annual_sum
self._initial_sum = annual_sum
self._annual_change = annual_change
self._payment_stdev = payment_stdev
self._start_year = start_year
self._end_year = end_year
def update_payment(self):
self._annual_sum = self._annual_sum * self._annual_change
def simulate_payment(self, year):
if year < self._start_year or year >= self._end_year:
return 0.0
sim = simulated_parameter(
parameter_name=self._name,
parameter_mean=self._annual_sum,
parameter_stddev=abs(self._annual_sum * self._payment_stdev),
start_year=self._start_year,
end_year=self._end_year)
return sim.get_simulated_value()
def reset(self):
self._annual_sum = self._initial_sum
def simulate_portfolio(initial_value,
annual_rate_of_return,
annual_payments,
mortgage,
start_year,
end_year,
num_simulations):
# Store the values and incomes for each simulation and each year.
values = []
net_incomes = []
# Loop over the number of simulations.
for _ in range(num_simulations):
curr_payments = annual_payments
for p in curr_payments:
p.reset()
# Store the values and incomes for all years in this simulation.
curr_values = [initial_value]
curr_net_incomes = []
# Loop over years.
for year in range(start_year, end_year, 1):
# Calculate current values.
new_income = 0
for p in curr_payments:
new_income += p.simulate_payment(year)
# Update payment value.
p.update_payment()
# Add mortgage payment to payments.
if (mortgage is None or year < mortgage.start_year_ or
year >= mortgage.start_year_ + mortgage.mortgage_term_years_):
mortgage_payment = 0.0
else:
mortgage_payment = mortgage.get_annual_payment()
new_income -= mortgage_payment
# Update value of assets.
ror = annual_rate_of_return.get_simulated_value()
if curr_values[-1] > 0:
new_value = (curr_values[-1] * ror) + new_income
else:
new_value = curr_values[-1] + new_income
# Update the incomes and values for one year in one simulation.
if len(curr_net_incomes) == 0:
curr_net_incomes.append(new_income)
curr_net_incomes.append(new_income)
curr_values.append(new_value)
# Update the set of all incomes and values.
net_incomes.append(curr_net_incomes)
values.append(curr_values)
return values, net_incomes
|
[
"numpy.random.normal"
] |
[((410, 495), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'self._parameter_mean', 'scale': 'self._parameter_stddev', 'size': '(1)'}), '(loc=self._parameter_mean, scale=self._parameter_stddev, size=1\n )\n', (426, 495), True, 'import numpy as np\n')]
|
import numpy as np
import keras.backend as K
from keras.layers import Layer
class LinearLayer(Layer):
""" linear regression score by using ids of user/item """
def __init__(self, num_user, num_item, **kwargs):
super(LinearLayer, self).__init__(**kwargs)
self.b_u = K.variable(np.zeros((num_user, 1)), name='{}_b_u'.format(self.name))
self.b_v = K.variable(np.zeros((num_item, 1)), name='{}_b_v'.format(self.name))
self.b_g = K.variable(0.0, name='{}_b_g'.format(self.name))
self.trainable_weights = [self.b_u, self.b_v, self.b_g]
def get_output_shape_for(self, input_shape):
return (None, 1)
def call(self, x, mask=None):
uid, vid = x[0], x[1]
# regression = self.b_u[uid] + self.b_v[vid] + self.b_g
regression = K.gather(self.b_u, uid) + K.gather(self.b_v, vid) + self.b_g
regression = K.reshape(regression, (-1, 1))
return regression
|
[
"keras.backend.reshape",
"numpy.zeros",
"keras.backend.gather"
] |
[((887, 917), 'keras.backend.reshape', 'K.reshape', (['regression', '(-1, 1)'], {}), '(regression, (-1, 1))\n', (896, 917), True, 'import keras.backend as K\n'), ((302, 325), 'numpy.zeros', 'np.zeros', (['(num_user, 1)'], {}), '((num_user, 1))\n', (310, 325), True, 'import numpy as np\n'), ((390, 413), 'numpy.zeros', 'np.zeros', (['(num_item, 1)'], {}), '((num_item, 1))\n', (398, 413), True, 'import numpy as np\n'), ((805, 828), 'keras.backend.gather', 'K.gather', (['self.b_u', 'uid'], {}), '(self.b_u, uid)\n', (813, 828), True, 'import keras.backend as K\n'), ((831, 854), 'keras.backend.gather', 'K.gather', (['self.b_v', 'vid'], {}), '(self.b_v, vid)\n', (839, 854), True, 'import keras.backend as K\n')]
|
# Copyright 2020 Amazon Technologies, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import copy
import itertools
import unittest
import byteps.mxnet as bps
import mxnet as mx
import mxnet.ndarray as nd
import numpy as np
from gluoncv.model_zoo import get_model
from mxnet import autograd, gluon
from numba import jit
from parameterized import parameterized
from tqdm import tqdm
from meta_test import MetaTest
from utils import bernoulli, fake_data
@jit(nopython=True)
def round_next_pow2(v):
v -= np.uint32(1)
v |= v >> np.uint32(1)
v |= v >> np.uint32(2)
v |= v >> np.uint32(4)
v |= v >> np.uint32(8)
v |= v >> np.uint32(16)
v += np.uint32(1)
return v
def dithering(x, k, state, partition='linear', norm="max"):
y = x.flatten()
if norm == "max":
scale = np.max(np.abs(y))
elif norm == "l2":
scale = np.linalg.norm(y.astype(np.float64), ord=2)
else:
raise ValueError("Unsupported normalization")
y /= scale
sign = np.sign(y)
y = np.abs(y)
# stocastic rounding
if partition == 'linear':
y *= k
low = np.floor(y)
p = y - low # whether to ceil
y = low + bernoulli(p, state)
y /= k
elif partition == "natural":
y *= 2**(k-1)
low = round_next_pow2((np.ceil(y).astype(np.uint32))) >> 1
length = copy.deepcopy(low)
length[length == 0] = 1
p = (y - low) / length
y = low + length * bernoulli(p, state)
y = y.astype(np.float32)
y /= 2**(k-1)
else:
raise ValueError("Unsupported partition")
y *= sign
y *= scale
return y.reshape(x.shape)
class DitheringTestCase(unittest.TestCase, metaclass=MetaTest):
@parameterized.expand(itertools.product([2, 4, 8], ["linear, natural"], ["max", "l2"], np.random.randint(0, 2020, size=3).tolist()))
def test_dithering(self, k, ptype, ntype, seed):
ctx = mx.gpu(0)
net = get_model("resnet18_v2")
net.initialize(mx.init.Xavier(), ctx=ctx)
net.summary(nd.ones((1, 3, 224, 224), ctx=ctx))
# hyper-params
batch_size = 32
optimizer_params = {'momentum': 0, 'wd': 0,
'learning_rate': 0.01}
compression_params = {
"compressor": "dithering",
"k": k,
"partition": ptype,
"normalize": ntype,
"seed": seed
}
print(compression_params)
trainer = bps.DistributedTrainer(net.collect_params(
), "sgd", optimizer_params, compression_params=compression_params)
loss_fn = gluon.loss.SoftmaxCrossEntropyLoss()
train_data = fake_data(batch_size=batch_size)
params = {}
rngs = {}
rngs_s = {}
for i, param in enumerate(trainer._params):
if param.grad_req != 'null':
params[i] = param._data[0].asnumpy()
rngs[i] = np.array([seed, seed], dtype=np.uint64)
rngs_s[i] = np.array([seed, seed], dtype=np.uint64)
for it, batch in tqdm(enumerate(train_data)):
data = batch[0].as_in_context(ctx)
label = batch[1].as_in_context(ctx)
with autograd.record():
output = net(data)
loss = loss_fn(output, label)
loss.backward()
gs = {}
xs = {}
for i, param in enumerate(trainer._params):
if param.grad_req != 'null':
gs[i] = param._grad[0].asnumpy()
xs[i] = param._data[0].asnumpy()
trainer.step(batch_size)
for i, param in enumerate(trainer._params):
if param.grad_req != "null":
g = gs[i] / (batch_size * bps.size())
c = dithering(g, k, rngs[i], ptype, ntype)
cs = dithering(c, k, rngs_s[i], ptype, ntype)
c = cs
params[i] -= optimizer_params["learning_rate"] * c
np_g = c.flatten()
mx_g = param._grad[0].asnumpy().flatten()
if not np.allclose(np_g, mx_g, atol=np.finfo(np.float32).eps):
diff = np.abs(np_g - mx_g)
print("np", np_g)
print("mx", mx_g)
print("diff", diff)
print("max diff", np.max(diff))
idx = np.nonzero(diff > 1e-5)
print("idx", idx, np_g[idx], mx_g[idx])
input()
cnt = 0
tot = 0
for i, param in enumerate(trainer._params):
if param.grad_req != "null":
x = param._data[0].asnumpy()
tot += len(x.flatten())
if not np.allclose(params[i], x, atol=np.finfo(np.float32).eps):
diff = np.abs(x.flatten() - params[i].flatten())
idx = np.where(diff > np.finfo(np.float32).eps)
cnt += len(idx[0])
assert cnt == 0, "false/tot=%d/%d=%f" % (cnt, tot, cnt/tot)
if __name__ == '__main__':
unittest.main()
|
[
"numpy.uint32",
"numpy.abs",
"numpy.floor",
"numpy.random.randint",
"unittest.main",
"gluoncv.model_zoo.get_model",
"numpy.finfo",
"numpy.max",
"mxnet.gpu",
"copy.deepcopy",
"mxnet.autograd.record",
"numpy.ceil",
"mxnet.gluon.loss.SoftmaxCrossEntropyLoss",
"mxnet.init.Xavier",
"utils.bernoulli",
"utils.fake_data",
"mxnet.ndarray.ones",
"numpy.nonzero",
"numba.jit",
"numpy.array",
"numpy.sign",
"byteps.mxnet.size"
] |
[((1062, 1080), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1065, 1080), False, 'from numba import jit\n'), ((1114, 1126), 'numpy.uint32', 'np.uint32', (['(1)'], {}), '(1)\n', (1123, 1126), True, 'import numpy as np\n'), ((1272, 1284), 'numpy.uint32', 'np.uint32', (['(1)'], {}), '(1)\n', (1281, 1284), True, 'import numpy as np\n'), ((1609, 1619), 'numpy.sign', 'np.sign', (['y'], {}), '(y)\n', (1616, 1619), True, 'import numpy as np\n'), ((1628, 1637), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (1634, 1637), True, 'import numpy as np\n'), ((5771, 5786), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5784, 5786), False, 'import unittest\n'), ((1141, 1153), 'numpy.uint32', 'np.uint32', (['(1)'], {}), '(1)\n', (1150, 1153), True, 'import numpy as np\n'), ((1168, 1180), 'numpy.uint32', 'np.uint32', (['(2)'], {}), '(2)\n', (1177, 1180), True, 'import numpy as np\n'), ((1195, 1207), 'numpy.uint32', 'np.uint32', (['(4)'], {}), '(4)\n', (1204, 1207), True, 'import numpy as np\n'), ((1222, 1234), 'numpy.uint32', 'np.uint32', (['(8)'], {}), '(8)\n', (1231, 1234), True, 'import numpy as np\n'), ((1249, 1262), 'numpy.uint32', 'np.uint32', (['(16)'], {}), '(16)\n', (1258, 1262), True, 'import numpy as np\n'), ((1723, 1734), 'numpy.floor', 'np.floor', (['y'], {}), '(y)\n', (1731, 1734), True, 'import numpy as np\n'), ((2540, 2549), 'mxnet.gpu', 'mx.gpu', (['(0)'], {}), '(0)\n', (2546, 2549), True, 'import mxnet as mx\n'), ((2564, 2588), 'gluoncv.model_zoo.get_model', 'get_model', (['"""resnet18_v2"""'], {}), "('resnet18_v2')\n", (2573, 2588), False, 'from gluoncv.model_zoo import get_model\n'), ((3226, 3262), 'mxnet.gluon.loss.SoftmaxCrossEntropyLoss', 'gluon.loss.SoftmaxCrossEntropyLoss', ([], {}), '()\n', (3260, 3262), False, 'from mxnet import autograd, gluon\n'), ((3285, 3317), 'utils.fake_data', 'fake_data', ([], {'batch_size': 'batch_size'}), '(batch_size=batch_size)\n', (3294, 3317), False, 'from utils import bernoulli, fake_data\n'), ((1425, 1434), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (1431, 1434), True, 'import numpy as np\n'), ((1792, 1811), 'utils.bernoulli', 'bernoulli', (['p', 'state'], {}), '(p, state)\n', (1801, 1811), False, 'from utils import bernoulli, fake_data\n'), ((1966, 1984), 'copy.deepcopy', 'copy.deepcopy', (['low'], {}), '(low)\n', (1979, 1984), False, 'import copy\n'), ((2612, 2628), 'mxnet.init.Xavier', 'mx.init.Xavier', ([], {}), '()\n', (2626, 2628), True, 'import mxnet as mx\n'), ((2659, 2693), 'mxnet.ndarray.ones', 'nd.ones', (['(1, 3, 224, 224)'], {'ctx': 'ctx'}), '((1, 3, 224, 224), ctx=ctx)\n', (2666, 2693), True, 'import mxnet.ndarray as nd\n'), ((3550, 3589), 'numpy.array', 'np.array', (['[seed, seed]'], {'dtype': 'np.uint64'}), '([seed, seed], dtype=np.uint64)\n', (3558, 3589), True, 'import numpy as np\n'), ((3618, 3657), 'numpy.array', 'np.array', (['[seed, seed]'], {'dtype': 'np.uint64'}), '([seed, seed], dtype=np.uint64)\n', (3626, 3657), True, 'import numpy as np\n'), ((3826, 3843), 'mxnet.autograd.record', 'autograd.record', ([], {}), '()\n', (3841, 3843), False, 'from mxnet import autograd, gluon\n'), ((2075, 2094), 'utils.bernoulli', 'bernoulli', (['p', 'state'], {}), '(p, state)\n', (2084, 2094), False, 'from utils import bernoulli, fake_data\n'), ((2427, 2461), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2020)'], {'size': '(3)'}), '(0, 2020, size=3)\n', (2444, 2461), True, 'import numpy as np\n'), ((4847, 4866), 'numpy.abs', 'np.abs', (['(np_g - mx_g)'], {}), '(np_g - mx_g)\n', (4853, 4866), True, 'import numpy as np\n'), ((5081, 5105), 'numpy.nonzero', 'np.nonzero', (['(diff > 1e-05)'], {}), '(diff > 1e-05)\n', (5091, 5105), True, 'import numpy as np\n'), ((1913, 1923), 'numpy.ceil', 'np.ceil', (['y'], {}), '(y)\n', (1920, 1923), True, 'import numpy as np\n'), ((4390, 4400), 'byteps.mxnet.size', 'bps.size', ([], {}), '()\n', (4398, 4400), True, 'import byteps.mxnet as bps\n'), ((5037, 5049), 'numpy.max', 'np.max', (['diff'], {}), '(diff)\n', (5043, 5049), True, 'import numpy as np\n'), ((5466, 5486), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (5474, 5486), True, 'import numpy as np\n'), ((5604, 5624), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (5612, 5624), True, 'import numpy as np\n'), ((4789, 4809), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (4797, 4809), True, 'import numpy as np\n')]
|
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
import sklearn
from sklearn import datasets
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.cluster import KMeans, AgglomerativeClustering
from sklearn.mixture import GaussianMixture
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.ensemble import RandomForestClassifier
def plot_pca(X, components=[1, 2], figsize=(8, 6),
color_vector=None, scale=False, title=None):
"""
Apply PCA to input X.
Args:
color_vector : each element corresponds to a row in X. Unique elements are colored with a different color.
Returns:
pca : object of sklearn.decomposition.PCA()
x_pca : pca matrix
fig : PCA plot figure handle
"""
if color_vector is not None:
assert len(X) == len(color_vector), 'len(df) and len(color_vector) must be the same size.'
n_colors = len(np.unique(color_vector))
colors = iter(cm.rainbow(np.linspace(0, 1, n_colors)))
X = pd.DataFrame(X)
# PCA
if scale:
xx = StandardScaler().fit_transform(X.values)
else:
xx = X.values
n_components = max(components)
pca = PCA(n_components=n_components)
x_pca = pca.fit_transform(xx)
pc0 = components[0] - 1
pc1 = components[1] - 1
# Start plotting
fig, ax = plt.subplots(figsize=figsize)
alpha = 0.7
if color_vector is not None:
for color in np.unique(color_vector):
idx = color_vector == color
c = next(colors)
ax.scatter(x_pca[idx, pc0], x_pca[idx, pc1], alpha=alpha,
marker='o', edgecolor=c, color=c,
label=f'{color}')
else:
ax.scatter(x_pca[:, pc0], x_pca[:, pc1], alpha=alpha,
marker='s', edgecolors=None, color='b')
ax.set_xlabel('PC' + str(components[0]))
ax.set_ylabel('PC' + str(components[1]))
ax.legend(loc='lower left', bbox_to_anchor=(1.01, 0.0), ncol=1, borderaxespad=0, frameon=True)
plt.grid(True)
if title:
ax.set_title(title)
print('Explained variance by PCA components [{}, {}]: [{:.5f}, {:.5f}]'.format(
components[0], components[1],
pca.explained_variance_ratio_[pc0],
pca.explained_variance_ratio_[pc1]))
return pca, x_pca
def load_cancer_data():
""" Return cancer dataset (unscaled).
Returns:
X, Y
"""
# Load data
from sklearn import datasets
data = datasets.load_breast_cancer()
# Get features and target
X = pd.DataFrame(data['data'], columns=data['feature_names'])
X = X[sorted(X.columns)]
Y = data['target']
return X, Y
def plot_kmeans_obj(X_sc, tot_clusters=10):
opt_obj_vec = []
for k in range(1, tot_clusters):
model = KMeans(n_clusters=k)
model.fit(X_sc)
opt_obj_vec.append(model.inertia_/X_sc.shape[0])
# Plot
k = np.arange(len(opt_obj_vec)) + 1
plt.figure(figsize=(8, 6))
plt.plot(k, opt_obj_vec, '--o')
plt.xlabel('Number of clusters (k)', fontsize=14)
plt.ylabel('Inertia', fontsize=14)
plt.grid(True)
return opt_obj_vec
def split_tr_te(X, Y, te_size=0.2):
from sklearn.model_selection import train_test_split
X = pd.DataFrame(X)
Y = pd.DataFrame(Y)
xtr, xte, ytr, yte = train_test_split(X, Y, test_size=te_size)
xtr.reset_index(drop=True, inplace=True)
xte.reset_index(drop=True, inplace=True)
return xtr, xte, ytr, yte
def chk_tissues(x, tissues):
return any([True if t in x else False for t in tissues])
def create_rna_data():
# Load data
rna_org = pd.read_csv('/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_rnaseq_data_lincs1000', sep='\t')
meta_org = pd.read_csv('/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_metadata_2018May.txt', sep='\t')
ctypes_org = pd.read_csv('/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_cancer_types', sep='\t')
print(rna_org.shape)
print(meta_org.shape)
print(ctypes_org.shape)
rna = rna_org.copy()
meta = meta_org.copy()
# Update rna df
rna.rename(columns={'Sample': 'sample'}, inplace=True)
rna.set_index('sample', inplace=True) # set dataframe index to sample (we will later merge dataframes on index)
rna.columns = ['GE_'+c for c in rna.columns] # add prefix 'GE_' to all gene expression columns
# Scale the features
rna_index, rna_cols = rna.index, rna.columns
rna = StandardScaler().fit_transform(rna)
rna = pd.DataFrame(rna, index=rna_index, columns=rna_cols)
# Update meta df
meta = meta.rename(
columns={'sample_name': 'sample', 'dataset': 'src',
'sample_category': 'category', 'sample_descr': 'descr',
'tumor_site_from_data_src': 'csite', 'tumor_type_from_data_src': 'ctype',
'simplified_tumor_site': 'simp_csite', 'simplified_tumor_type': 'simp_ctype'})
# Extract a subset of cols
meta = meta[['sample', 'src', 'csite', 'ctype', 'simp_csite', 'simp_ctype', 'category', 'descr']]
meta['src'] = meta['src'].map(lambda x: x.lower())
meta['csite'] = meta['csite'].map(lambda x: x.strip())
meta['ctype'] = meta['ctype'].map(lambda x: x.strip())
meta['src'] = meta['src'].map(lambda x: 'gdc' if x=='tcga' else x)
meta.set_index('sample', inplace=True) # add prefix 'GE_' to all gene expression columns
# Filter on source
sources = ['gdc']
rna = rna.loc[rna.index.map(lambda s: s.split('.')[0].lower() in sources), :]
print(rna.shape)
# Update rna and meta
on = 'sample'
df = pd.merge(meta, rna, how='inner', on=on)
col = 'csite'
df[col] = df[col].map(lambda x: x.split('/')[0])
# df[col].value_counts()
# GDC
tissues = ['breast', 'skin', 'lung', 'prostate']
df = df.loc[ df[col].map(lambda x: chk_tissues(x, tissues)), : ]
print(df['csite'].value_counts())
# Randomly sample a subset of samples to create a balanced dataset
sample_sz = 7
df_list = []
for i, t in enumerate(tissues):
print(t)
tmp = df[ df[col].isin([t]) ].sample(n=sample_sz, random_state=seed)
df_list.append(tmp)
df = pd.concat(df_list, axis=0)
df = df.sample(frac=1.0)
# Dump df
df = df.drop(columns=['simp_csite', 'simp_ctype', 'category', 'descr'])
df.to_csv('rna.csv')
def plot_hists(k_means_bins, y_bins, x_labels = ['Malignant', 'Benign']):
""" Specific function to plot histograms from bins.
matplotlib.org/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py
"""
x = np.arange(len(x_labels)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, y_bins, width, label='True label')
rects2 = ax.bar(x + width/2, k_means_bins, width, label='K-means')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Total count')
ax.set_title('Histogram')
ax.set_xticks(x)
ax.set_xticklabels(x_labels)
ax.set_ylim(0, 450)
ax.legend(loc='best')
def autolabel(rects):
""" Attach a text label above each bar in *rects*, displaying its height. """
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()
|
[
"pandas.DataFrame",
"matplotlib.pyplot.show",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"pandas.merge",
"sklearn.cluster.KMeans",
"sklearn.datasets.load_breast_cancer",
"matplotlib.pyplot.figure",
"sklearn.decomposition.PCA",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
"pandas.concat",
"numpy.unique",
"matplotlib.pyplot.grid"
] |
[((1256, 1271), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (1268, 1271), True, 'import pandas as pd\n'), ((1429, 1459), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'n_components'}), '(n_components=n_components)\n', (1432, 1459), False, 'from sklearn.decomposition import PCA\n'), ((1586, 1615), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (1598, 1615), True, 'import matplotlib.pyplot as plt\n'), ((2274, 2288), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2282, 2288), True, 'import matplotlib.pyplot as plt\n'), ((2728, 2757), 'sklearn.datasets.load_breast_cancer', 'datasets.load_breast_cancer', ([], {}), '()\n', (2755, 2757), False, 'from sklearn import datasets\n'), ((2797, 2854), 'pandas.DataFrame', 'pd.DataFrame', (["data['data']"], {'columns': "data['feature_names']"}), "(data['data'], columns=data['feature_names'])\n", (2809, 2854), True, 'import pandas as pd\n'), ((3216, 3242), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (3226, 3242), True, 'import matplotlib.pyplot as plt\n'), ((3247, 3278), 'matplotlib.pyplot.plot', 'plt.plot', (['k', 'opt_obj_vec', '"""--o"""'], {}), "(k, opt_obj_vec, '--o')\n", (3255, 3278), True, 'import matplotlib.pyplot as plt\n'), ((3283, 3332), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of clusters (k)"""'], {'fontsize': '(14)'}), "('Number of clusters (k)', fontsize=14)\n", (3293, 3332), True, 'import matplotlib.pyplot as plt\n'), ((3337, 3371), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Inertia"""'], {'fontsize': '(14)'}), "('Inertia', fontsize=14)\n", (3347, 3371), True, 'import matplotlib.pyplot as plt\n'), ((3376, 3390), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (3384, 3390), True, 'import matplotlib.pyplot as plt\n'), ((3526, 3541), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (3538, 3541), True, 'import pandas as pd\n'), ((3550, 3565), 'pandas.DataFrame', 'pd.DataFrame', (['Y'], {}), '(Y)\n', (3562, 3565), True, 'import pandas as pd\n'), ((3596, 3637), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': 'te_size'}), '(X, Y, test_size=te_size)\n', (3612, 3637), False, 'from sklearn.model_selection import train_test_split\n'), ((3910, 4024), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_rnaseq_data_lincs1000"""'], {'sep': '"""\t"""'}), "(\n '/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_rnaseq_data_lincs1000'\n , sep='\\t')\n", (3921, 4024), True, 'import pandas as pd\n'), ((4030, 4143), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_metadata_2018May.txt"""'], {'sep': '"""\t"""'}), "(\n '/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_metadata_2018May.txt'\n , sep='\\t')\n", (4041, 4143), True, 'import pandas as pd\n'), ((4151, 4255), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_cancer_types"""'], {'sep': '"""\t"""'}), "(\n '/Users/apartin/work/jdacs/Benchmarks/Data/Pilot1/combined_cancer_types',\n sep='\\t')\n", (4162, 4255), True, 'import pandas as pd\n'), ((4823, 4875), 'pandas.DataFrame', 'pd.DataFrame', (['rna'], {'index': 'rna_index', 'columns': 'rna_cols'}), '(rna, index=rna_index, columns=rna_cols)\n', (4835, 4875), True, 'import pandas as pd\n'), ((5931, 5970), 'pandas.merge', 'pd.merge', (['meta', 'rna'], {'how': '"""inner"""', 'on': 'on'}), "(meta, rna, how='inner', on=on)\n", (5939, 5970), True, 'import pandas as pd\n'), ((6534, 6560), 'pandas.concat', 'pd.concat', (['df_list'], {'axis': '(0)'}), '(df_list, axis=0)\n', (6543, 6560), True, 'import pandas as pd\n'), ((7087, 7101), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (7099, 7101), True, 'import matplotlib.pyplot as plt\n'), ((8023, 8033), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8031, 8033), True, 'import matplotlib.pyplot as plt\n'), ((1687, 1710), 'numpy.unique', 'np.unique', (['color_vector'], {}), '(color_vector)\n', (1696, 1710), True, 'import numpy as np\n'), ((3043, 3063), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'k'}), '(n_clusters=k)\n', (3049, 3063), False, 'from sklearn.cluster import KMeans, AgglomerativeClustering\n'), ((1159, 1182), 'numpy.unique', 'np.unique', (['color_vector'], {}), '(color_vector)\n', (1168, 1182), True, 'import numpy as np\n'), ((4777, 4793), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (4791, 4793), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\n'), ((1217, 1244), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_colors'], {}), '(0, 1, n_colors)\n', (1228, 1244), True, 'import numpy as np\n'), ((1310, 1326), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1324, 1326), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\n')]
|
import numpy as np
import pytz
from pandas._libs.tslibs import (
Resolution,
get_resolution,
)
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
def test_get_resolution_nano():
# don't return the fallback RESO_DAY
arr = np.array([1], dtype=np.int64)
res = get_resolution(arr)
assert res == Resolution.RESO_NS
def test_get_resolution_non_nano_data():
arr = np.array([1], dtype=np.int64)
res = get_resolution(arr, None, NpyDatetimeUnit.NPY_FR_us.value)
assert res == Resolution.RESO_US
res = get_resolution(arr, pytz.UTC, NpyDatetimeUnit.NPY_FR_us.value)
assert res == Resolution.RESO_US
|
[
"pandas._libs.tslibs.get_resolution",
"numpy.array"
] |
[((244, 273), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int64'}), '([1], dtype=np.int64)\n', (252, 273), True, 'import numpy as np\n'), ((284, 303), 'pandas._libs.tslibs.get_resolution', 'get_resolution', (['arr'], {}), '(arr)\n', (298, 303), False, 'from pandas._libs.tslibs import Resolution, get_resolution\n'), ((394, 423), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int64'}), '([1], dtype=np.int64)\n', (402, 423), True, 'import numpy as np\n'), ((434, 492), 'pandas._libs.tslibs.get_resolution', 'get_resolution', (['arr', 'None', 'NpyDatetimeUnit.NPY_FR_us.value'], {}), '(arr, None, NpyDatetimeUnit.NPY_FR_us.value)\n', (448, 492), False, 'from pandas._libs.tslibs import Resolution, get_resolution\n'), ((541, 603), 'pandas._libs.tslibs.get_resolution', 'get_resolution', (['arr', 'pytz.UTC', 'NpyDatetimeUnit.NPY_FR_us.value'], {}), '(arr, pytz.UTC, NpyDatetimeUnit.NPY_FR_us.value)\n', (555, 603), False, 'from pandas._libs.tslibs import Resolution, get_resolution\n')]
|
import sys
import argparse
from yolo import YOLO, detect_video
from PIL import Image
from keras.utils.generic_utils import Progbar
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import ImageDraw, ImageFont
def detect_sequence_imgs(yolo, list_images, output_dir, save_img=False):
# Prepare directory to save the results
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Load txt files with the paths of all the images
with open(list_images) as f:
lines = f.readlines()
# Prepare progress bar
steps = len(lines)
progbar = Progbar(target=steps)
# Iterate over each of the images
for i in range(0, steps):
# Load image
lines[i] = lines[i].replace("\n", "")
if not lines[i].endswith(('.jpg')):
lines[i] += '.jpg'
try:
img = Image.open(lines[i])
except:
print('Open Error! Try again!')
continue
else:
# Make predictions
predictions = yolo.detection_results(img, lines[i])
# Create dir if not exists
if not os.path.exists(output_dir):
os.mkdir(output_dir)
# Save the results on a txt (one txt per image)
results = open(os.path.join(output_dir, lines[i].replace("/", "__").replace('.jpg', ".txt")), 'w')
if save_img:
font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
size=np.floor(3e-2 * img.size[1] + 0.5).astype('int32'))
thickness = (img.size[0] + img.size[1]) // 300
draw = ImageDraw.Draw(img)
for j in range(0, predictions.shape[0]):
if predictions.shape[1] > 1:
label = predictions[j, 0].split()
left = predictions[j, 1]
top = predictions[j, 2]
right = predictions[j, 3]
bottom = predictions[j, 4]
print('\tClass = {}, Confidence = {}, Xmin = {}, Ymin = {}, Xmax = {}, Ymax = {}'.format(label[0],
label[1], left, top, right, bottom))
results.write(predictions[j, 0] + ' ' + left + ' ' + top + ' ' + right + ' ' + bottom + '\n')
if save_img:
left = int(left)
top = int(top)
right = int(right)
bottom = int(bottom)
label_size = draw.textsize(predictions[j, 0], font)
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
# My kingdom for a good redistributable image drawing library.
for k in range(thickness):
draw.rectangle([left + k, top + k, right - k, bottom - k], outline=(0, 255, 0))
draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=(0, 255, 0))
draw.text(text_origin, predictions[j, 0], fill=(0, 0, 0), font=font)
else:
results.write(predictions[j, 0])
results.close()
# Insert the results on the jpg
if save_img:
img.save(os.path.join(output_dir, lines[i].replace("/", "__").replace("jpg", "png")), 'PNG')
del draw
# Update progress bar
progbar.update(i+1), print('\t')
yolo.close_session()
def detect_img(yolo, image_path, output_dir='', gt='', save_img=False):
# Load image
try:
image= Image.open(image_path)
except:
print('Open Error! Try again!')
else:
# Make predictions
img_pred, predictions = yolo.detect_image(image)
# If gt is set, insert the gts on the image
if len(gt) > 0:
# Define font of the text of the labels and the thickness of the boxes
font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
thickness = (image.size[0] + image.size[1]) // 300
# Load gt
with open(gt) as g:
lines = g.readlines()
# Iterate over each bounding box
for i in range(0, len(lines)):
# Prepare to draw on the image
base = img_pred.convert('RGBA')
img_alpha = Image.new('RGBA', base.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(img_alpha, 'RGBA')
# Get label
lines[i] = lines[i].replace("\n", "")
line = lines[i].split()
label = line[0]
# Get the coordinates
left = float(line[1])
top = float(line[2])
right = float(line[3])
bottom = float(line[4])
# Prepare box for the label
label_size = draw.textsize(label, font)
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
# Iterate to draw the box more thick
for k in range(thickness):
draw.rectangle([left + k, top + k, right - k, bottom - k], outline=(255, 0, 0, 255))
# Draw the box of the labels
draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=(255, 0, 0, 64))
# Insert the text of the labels
draw.text(text_origin, label, fill=(0, 0, 0, 255), font=font)
img_pred = Image.alpha_composite(base, img_alpha)
del draw
# If output_dir is set, save the results on a txt and a jpg
if len(output_dir) > 0:
# Create dir if not exists
if not os.path.exists(output_dir):
os.mkdir(output_dir)
# Insert the results on the txt
results = open(output_dir + "/prediction.txt", 'w')
for j in range(0, predictions.shape[0]):
if predictions.shape[1] > 1:
results.write(predictions[j, 0] + ' ' + predictions[j, 1] + ' ' + predictions[j, 2] + ' '
+ predictions[j, 3] + ' ' + predictions[j, 4] + '\n')
else:
results.write(predictions[j, 0])
results.close()
# Insert the results on the jpg
if save_img:
img_pred.save(output_dir + "/prediction.png")
# Plot the result
plt.imshow(np.array(img_pred)), plt.show()
yolo.close_session()
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
FLAGS = None
if __name__ == '__main__':
# class YOLO defines the default value, so suppress any default here
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
'''
Command line options
'''
parser.add_argument(
'--model_path', type=str, dest='model_path',
help='path to model weight file, default ' + YOLO.get_defaults("model_path")
)
parser.add_argument(
'--anchors_path', type=str, dest='anchors_path',
help='path to anchor definitions, default ' + YOLO.get_defaults("anchors_path")
)
parser.add_argument(
'--classes_path', type=str, dest='classes_path',
help='path to class definitions, default ' + YOLO.get_defaults("classes_path")
)
parser.add_argument(
'--image_size', type=int, dest='image_size',
help='Size of the processed image(s), same for width and height,'
'default ({}, {})'.format(YOLO.get_defaults("model_image_size")[0],
YOLO.get_defaults("model_image_size")[1])
)
parser.add_argument(
'--score', type=float, dest='score', default=0.3,
help='confidence score threshold, default ' + str(YOLO.get_defaults("score"))
)
parser.add_argument(
'--iou', type=float, dest='iou', default=0.5,
help='IoU threshold, default ' + str(YOLO.get_defaults("iou"))
)
parser.add_argument(
'--gpu_num', type=int,
help='Number of GPU to use, default ' + str(YOLO.get_defaults("gpu_num"))
)
parser.add_argument(
'--image', default=False, action="store_true",
help='Image detection mode, will ignore all positional arguments'
)
'''
Command line positional arguments -- for video detection mode
'''
parser.add_argument(
"--input", nargs='?', type=str,required=False, default='./path2your_video',
help = "Video input path"
)
parser.add_argument(
"--output", nargs='?', type=str, default="",
help = "[Optional] Video output path"
)
parser.add_argument(
"--save_img", nargs='?', type=str2bool, default=False,
help="Save image with predictions or not"
)
# Only for single detections (single_image=True)
parser.add_argument(
"--gt", nargs='?', type=str, default="",
help="Path to txt file with the ground truth of the given image"
)
# Required for multiple detections (single_image=False)
parser.add_argument(
"--list_images", nargs='?', type=str, default="/media/nsp/62D49B40D49B157F/u/nsp/TFM_Natalia/PIROPO/Test/lista_img_test.txt",
help="Path to txt file listing the path of each of the images"
)
# Required for multiple detections (single_image=False)
parser.add_argument(
"--single_image", nargs='?', type=str, default="",
help="If you wish to detect one single image, indicate here its path"
)
parser.add_argument(
"--output_dir", nargs='?', type=str, default="/media/nsp/62D49B40D49B157F/u/nsp/TFM_Natalia/keras-yolo3/input/detection-results-trial10-hw38",
help="Path where a set of txt files (one per image) will be generated"
)
FLAGS = parser.parse_args()
if len(FLAGS.single_image) > 0:
detect_img(YOLO(**vars(FLAGS)), image_path=FLAGS.single_image, output_dir=FLAGS.output_dir, gt=FLAGS.gt, save_img=FLAGS.save_img)
else:
detect_sequence_imgs(YOLO(**vars(FLAGS)), list_images=FLAGS.list_images, output_dir=FLAGS.output_dir, save_img=FLAGS.save_img)
|
[
"os.mkdir",
"PIL.Image.new",
"keras.utils.generic_utils.Progbar",
"matplotlib.pyplot.show",
"os.makedirs",
"argparse.ArgumentParser",
"numpy.floor",
"os.path.exists",
"PIL.Image.open",
"PIL.Image.alpha_composite",
"numpy.array",
"yolo.YOLO.get_defaults",
"PIL.ImageDraw.Draw",
"argparse.ArgumentTypeError"
] |
[((626, 647), 'keras.utils.generic_utils.Progbar', 'Progbar', ([], {'target': 'steps'}), '(target=steps)\n', (633, 647), False, 'from keras.utils.generic_utils import Progbar\n'), ((7588, 7647), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'argument_default': 'argparse.SUPPRESS'}), '(argument_default=argparse.SUPPRESS)\n', (7611, 7647), False, 'import argparse\n'), ((374, 400), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (388, 400), False, 'import os\n'), ((411, 434), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (422, 434), False, 'import os\n'), ((3912, 3934), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (3922, 3934), False, 'from PIL import Image\n'), ((901, 921), 'PIL.Image.open', 'Image.open', (['lines[i]'], {}), '(lines[i])\n', (911, 921), False, 'from PIL import Image\n'), ((7112, 7122), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7120, 7122), True, 'import matplotlib.pyplot as plt\n'), ((7396, 7449), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Boolean value expected."""'], {}), "('Boolean value expected.')\n", (7422, 7449), False, 'import argparse\n'), ((1182, 1208), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (1196, 1208), False, 'import os\n'), ((1227, 1247), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (1235, 1247), False, 'import os\n'), ((1715, 1734), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (1729, 1734), False, 'from PIL import ImageDraw, ImageFont\n'), ((4805, 4853), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', 'base.size', '(255, 255, 255, 0)'], {}), "('RGBA', base.size, (255, 255, 255, 0))\n", (4814, 4853), False, 'from PIL import Image\n'), ((4878, 4911), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img_alpha', '"""RGBA"""'], {}), "(img_alpha, 'RGBA')\n", (4892, 4911), False, 'from PIL import ImageDraw, ImageFont\n'), ((6101, 6139), 'PIL.Image.alpha_composite', 'Image.alpha_composite', (['base', 'img_alpha'], {}), '(base, img_alpha)\n', (6122, 6139), False, 'from PIL import Image\n'), ((6332, 6358), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (6346, 6358), False, 'import os\n'), ((6377, 6397), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (6385, 6397), False, 'import os\n'), ((7091, 7109), 'numpy.array', 'np.array', (['img_pred'], {}), '(img_pred)\n', (7099, 7109), True, 'import numpy as np\n'), ((7826, 7857), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""model_path"""'], {}), "('model_path')\n", (7843, 7857), False, 'from yolo import YOLO, detect_video\n'), ((8006, 8039), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""anchors_path"""'], {}), "('anchors_path')\n", (8023, 8039), False, 'from yolo import YOLO, detect_video\n'), ((8187, 8220), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""classes_path"""'], {}), "('classes_path')\n", (8204, 8220), False, 'from yolo import YOLO, detect_video\n'), ((5456, 5493), 'numpy.array', 'np.array', (['[left, top - label_size[1]]'], {}), '([left, top - label_size[1]])\n', (5464, 5493), True, 'import numpy as np\n'), ((5552, 5577), 'numpy.array', 'np.array', (['[left, top + 1]'], {}), '([left, top + 1])\n', (5560, 5577), True, 'import numpy as np\n'), ((8426, 8463), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""model_image_size"""'], {}), "('model_image_size')\n", (8443, 8463), False, 'from yolo import YOLO, detect_video\n'), ((8509, 8546), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""model_image_size"""'], {}), "('model_image_size')\n", (8526, 8546), False, 'from yolo import YOLO, detect_video\n'), ((8704, 8730), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""score"""'], {}), "('score')\n", (8721, 8730), False, 'from yolo import YOLO, detect_video\n'), ((8868, 8892), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""iou"""'], {}), "('iou')\n", (8885, 8892), False, 'from yolo import YOLO, detect_video\n'), ((9014, 9042), 'yolo.YOLO.get_defaults', 'YOLO.get_defaults', (['"""gpu_num"""'], {}), "('gpu_num')\n", (9031, 9042), False, 'from yolo import YOLO, detect_video\n'), ((2769, 2806), 'numpy.array', 'np.array', (['[left, top - label_size[1]]'], {}), '([left, top - label_size[1]])\n', (2777, 2806), True, 'import numpy as np\n'), ((2881, 2906), 'numpy.array', 'np.array', (['[left, top + 1]'], {}), '([left, top + 1])\n', (2889, 2906), True, 'import numpy as np\n'), ((4370, 4406), 'numpy.floor', 'np.floor', (['(0.03 * image.size[1] + 0.5)'], {}), '(0.03 * image.size[1] + 0.5)\n', (4378, 4406), True, 'import numpy as np\n'), ((1575, 1609), 'numpy.floor', 'np.floor', (['(0.03 * img.size[1] + 0.5)'], {}), '(0.03 * img.size[1] + 0.5)\n', (1583, 1609), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
import os, sys
import numpy as np
import matplotlib.pylab as plt
from sklearn.manifold import TSNE
import json, pickle
def load_json_data(json_path):
fea_dict = json.load(open(json_path))
fea_category_dict = {}
for key in fea_dict.keys():
cat = key[:key.find('_')]
if cat not in fea_category_dict:
fea_category_dict[cat] = [fea_dict[key]]
else:
fea_category_dict[cat].append(fea_dict[key])
return fea_category_dict
def generate_data_label(feas):
Data = []
Label = []
for iter in range(0, 24):
if iter<22:
tn = len(feas[str(iter+1)])
for jter in range(tn):
temp = feas[str(iter+1)][jter]
Data.append(np.array(temp))
Label.append([iter])
elif iter==22:
tn = len(feas['X'])
for jter in range(tn):
temp = feas['X'][jter]
Data.append(np.array(temp))
Label.append([iter])
else:
tn = len(feas['Y'])
for jter in range(tn):
temp = feas['Y'][jter]
Data.append(np.array(temp))
Label.append([iter])
Data = np.array(Data)
Label = np.squeeze(Label)
return Data, Label
if __name__ == "__main__":
test_fea_path = "chromosome_test_feas.json"
test_feas = load_json_data(test_fea_path)
feas, labels = generate_data_label(test_feas)
y_data = labels
num_label = len(np.unique(y_data))
print("tsne...")
# # # original space
# ori_embed_feas = TSNE(n_components=2).fit_transform(feas)
# ori_vis_x = ori_embed_feas[:, 0]
# ori_vis_y = ori_embed_feas[:, 1]
# project space
lda_paras = pickle.load(open("lda_model.pkl", "rb"))
prj_feas = np.matmul(feas, lda_paras['ProjectMat'])
prj_embed_feas = TSNE(n_components=2).fit_transform(prj_feas)
prj_vis_x = prj_embed_feas[:, 0]
prj_vis_y = prj_embed_feas[:, 1]
# fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 3), dpi=300)
# ori = ax1.scatter(ori_vis_x, ori_vis_y, c=y_data, cmap=plt.cm.get_cmap("jet", num_label))
# plt.colorbar(ori, ax=ax1)
# ax1.set_title("Original chromosome feature embedding", fontsize=8)
# prj = ax2.scatter(prj_vis_x, prj_vis_y, c=y_data, cmap=plt.cm.get_cmap("jet", num_label))
# plt.colorbar(prj, ax=ax2)
# ax2.set_title("LDA projected feature embedding", fontsize=8)
fig, axes = plt.subplots(1, 1, figsize=(6, 6), dpi=300)
prj = axes.scatter(prj_vis_x, prj_vis_y, s=3, c=y_data, cmap=plt.cm.get_cmap("jet", num_label))
plt.colorbar(prj, ax=axes)
axes.set_title("LDA projected feature embedding", fontsize=8)
plt.show()
|
[
"matplotlib.pylab.colorbar",
"sklearn.manifold.TSNE",
"numpy.array",
"numpy.matmul",
"matplotlib.pylab.cm.get_cmap",
"numpy.squeeze",
"matplotlib.pylab.subplots",
"numpy.unique",
"matplotlib.pylab.show"
] |
[((1006, 1020), 'numpy.array', 'np.array', (['Data'], {}), '(Data)\n', (1014, 1020), True, 'import numpy as np\n'), ((1030, 1047), 'numpy.squeeze', 'np.squeeze', (['Label'], {}), '(Label)\n', (1040, 1047), True, 'import numpy as np\n'), ((1583, 1623), 'numpy.matmul', 'np.matmul', (['feas', "lda_paras['ProjectMat']"], {}), "(feas, lda_paras['ProjectMat'])\n", (1592, 1623), True, 'import numpy as np\n'), ((2246, 2289), 'matplotlib.pylab.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(6, 6)', 'dpi': '(300)'}), '(1, 1, figsize=(6, 6), dpi=300)\n', (2258, 2289), True, 'import matplotlib.pylab as plt\n'), ((2394, 2420), 'matplotlib.pylab.colorbar', 'plt.colorbar', (['prj'], {'ax': 'axes'}), '(prj, ax=axes)\n', (2406, 2420), True, 'import matplotlib.pylab as plt\n'), ((2492, 2502), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (2500, 2502), True, 'import matplotlib.pylab as plt\n'), ((1283, 1300), 'numpy.unique', 'np.unique', (['y_data'], {}), '(y_data)\n', (1292, 1300), True, 'import numpy as np\n'), ((1645, 1665), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)'}), '(n_components=2)\n', (1649, 1665), False, 'from sklearn.manifold import TSNE\n'), ((2355, 2388), 'matplotlib.pylab.cm.get_cmap', 'plt.cm.get_cmap', (['"""jet"""', 'num_label'], {}), "('jet', num_label)\n", (2370, 2388), True, 'import matplotlib.pylab as plt\n'), ((664, 678), 'numpy.array', 'np.array', (['temp'], {}), '(temp)\n', (672, 678), True, 'import numpy as np\n'), ((815, 829), 'numpy.array', 'np.array', (['temp'], {}), '(temp)\n', (823, 829), True, 'import numpy as np\n'), ((956, 970), 'numpy.array', 'np.array', (['temp'], {}), '(temp)\n', (964, 970), True, 'import numpy as np\n')]
|
import cv2 as cv
import numpy as np
def const_accel(dt = 1.0/30):
kf = cv.KalmanFilter(18, 6, 0)
state = np.zeros((18, 1), np.float32)
# Transition matrix position/orientation
tmp = np.eye(9, dtype=np.float32)
tmp[0:3, 3:6] = np.eye(3, dtype=np.float32) * dt
tmp[3:6, 6:9] = np.eye(3, dtype=np.float32) * dt
tmp[0:3, 6:9] = np.eye(3, dtype=np.float32) * dt * dt / 2
# Transition matrix
kf.transitionMatrix = np.concatenate((
np.concatenate((tmp, np.zeros((9, 9))), axis=1),
np.concatenate((np.zeros((9, 9)), tmp), axis=1)),
axis=0
)
# Measurement matrix
tmp = np.zeros((6, 18), dtype=np.float32)
tmp[0:3, 0:3] = np.eye(3, dtype=np.float32)
tmp[3:6, 9:12] = np.eye(3, dtype=np.float32)
kf.measurementMatrix = tmp
# Process/Measurement noise covariance & Error
kf.processNoiseCov = 1e-5 * np.eye(18, dtype=np.float32)
kf.measurementNoiseCov = 1e-4 * np.eye(6, dtype=np.float32)
kf.errorCovPost = np.eye(18, dtype=np.float32)
return kf
def const_vel(dt = 1.0/30):
kf = cv.KalmanFilter(12, 6, 0)
state = np.zeros((12, 1), np.float32)
# Transition matrix position/orientation
tmp = np.eye(9, dtype=np.float32)
tmp[0:3, 3:6] = np.eye(3, dtype=np.float32) * dt
# Transition matrix
kf.transitionMatrix = np.concatenate((
np.concatenate((tmp, np.zeros((6, 6))), axis=1),
np.concatenate((np.zeros((6, 6)), tmp), axis=1)),
axis=0
)
# Measurement matrix
tmp = np.zeros((6, 12), dtype=np.float32)
tmp[0:3, 0:3] = np.eye(3, dtype=np.float32)
tmp[3:6, 6:9] = np.eye(3, dtype=np.float32)
kf.measurementMatrix = tmp
# Process/Measurement noise covariance & Error
kf.processNoiseCov = 1e-5 * np.eye(18, dtype=np.float32)
kf.measurementNoiseCov = 1e-4 * np.eye(6, dtype=np.float32)
kf.errorCovPost = np.eye(18, dtype=np.float32)
return kf
filters = {
'const_accel': const_accel,
'const_vel': const_vel
}
|
[
"cv2.KalmanFilter",
"numpy.eye",
"numpy.zeros"
] |
[((77, 102), 'cv2.KalmanFilter', 'cv.KalmanFilter', (['(18)', '(6)', '(0)'], {}), '(18, 6, 0)\n', (92, 102), True, 'import cv2 as cv\n'), ((115, 144), 'numpy.zeros', 'np.zeros', (['(18, 1)', 'np.float32'], {}), '((18, 1), np.float32)\n', (123, 144), True, 'import numpy as np\n'), ((205, 232), 'numpy.eye', 'np.eye', (['(9)'], {'dtype': 'np.float32'}), '(9, dtype=np.float32)\n', (211, 232), True, 'import numpy as np\n'), ((651, 686), 'numpy.zeros', 'np.zeros', (['(6, 18)'], {'dtype': 'np.float32'}), '((6, 18), dtype=np.float32)\n', (659, 686), True, 'import numpy as np\n'), ((707, 734), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (713, 734), True, 'import numpy as np\n'), ((756, 783), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (762, 783), True, 'import numpy as np\n'), ((1018, 1046), 'numpy.eye', 'np.eye', (['(18)'], {'dtype': 'np.float32'}), '(18, dtype=np.float32)\n', (1024, 1046), True, 'import numpy as np\n'), ((1105, 1130), 'cv2.KalmanFilter', 'cv.KalmanFilter', (['(12)', '(6)', '(0)'], {}), '(12, 6, 0)\n', (1120, 1130), True, 'import cv2 as cv\n'), ((1143, 1172), 'numpy.zeros', 'np.zeros', (['(12, 1)', 'np.float32'], {}), '((12, 1), np.float32)\n', (1151, 1172), True, 'import numpy as np\n'), ((1233, 1260), 'numpy.eye', 'np.eye', (['(9)'], {'dtype': 'np.float32'}), '(9, dtype=np.float32)\n', (1239, 1260), True, 'import numpy as np\n'), ((1564, 1599), 'numpy.zeros', 'np.zeros', (['(6, 12)'], {'dtype': 'np.float32'}), '((6, 12), dtype=np.float32)\n', (1572, 1599), True, 'import numpy as np\n'), ((1620, 1647), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (1626, 1647), True, 'import numpy as np\n'), ((1668, 1695), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (1674, 1695), True, 'import numpy as np\n'), ((1930, 1958), 'numpy.eye', 'np.eye', (['(18)'], {'dtype': 'np.float32'}), '(18, dtype=np.float32)\n', (1936, 1958), True, 'import numpy as np\n'), ((253, 280), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (259, 280), True, 'import numpy as np\n'), ((306, 333), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (312, 333), True, 'import numpy as np\n'), ((903, 931), 'numpy.eye', 'np.eye', (['(18)'], {'dtype': 'np.float32'}), '(18, dtype=np.float32)\n', (909, 931), True, 'import numpy as np\n'), ((968, 995), 'numpy.eye', 'np.eye', (['(6)'], {'dtype': 'np.float32'}), '(6, dtype=np.float32)\n', (974, 995), True, 'import numpy as np\n'), ((1281, 1308), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (1287, 1308), True, 'import numpy as np\n'), ((1815, 1843), 'numpy.eye', 'np.eye', (['(18)'], {'dtype': 'np.float32'}), '(18, dtype=np.float32)\n', (1821, 1843), True, 'import numpy as np\n'), ((1880, 1907), 'numpy.eye', 'np.eye', (['(6)'], {'dtype': 'np.float32'}), '(6, dtype=np.float32)\n', (1886, 1907), True, 'import numpy as np\n'), ((359, 386), 'numpy.eye', 'np.eye', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (365, 386), True, 'import numpy as np\n'), ((502, 518), 'numpy.zeros', 'np.zeros', (['(9, 9)'], {}), '((9, 9))\n', (510, 518), True, 'import numpy as np\n'), ((555, 571), 'numpy.zeros', 'np.zeros', (['(9, 9)'], {}), '((9, 9))\n', (563, 571), True, 'import numpy as np\n'), ((1415, 1431), 'numpy.zeros', 'np.zeros', (['(6, 6)'], {}), '((6, 6))\n', (1423, 1431), True, 'import numpy as np\n'), ((1468, 1484), 'numpy.zeros', 'np.zeros', (['(6, 6)'], {}), '((6, 6))\n', (1476, 1484), True, 'import numpy as np\n')]
|
import numpy as np
import numpy.linalg as la
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
import sys
import SBW_util as util
from matplotlib.animation import FuncAnimation
eps_u = 0.001 # 0.01
eps_v = 0.001 # 0.001
gamma_u = 0.005# 0.05
zeta = 0.0
alpha_v = 0.1
beta_v = 0.1
eta_w = 10.0
def constr_lineqU(U, W, V, N, M, T):
'''
N: nb of x grid points (int)
T: current timestep (int)
U: discrete solution of u (np.array)
W: discrete solution of w (np.array)
V: discrete solution of v (np.array)
M: nb of time steps (int)
'''
h = 1.0/float(N)
k = 1.0/float(M)
#assert(U.shape == W.shape and W.shape == V.shape, 'Dim error')
#assert(U.shape[1] ==N and U.shape[0] == M, 'Dim error')
DT = 0
X_length = N
A2Ut = np.zeros((X_length, X_length))
A1Ut = np.zeros((X_length, X_length))
fU = np.zeros((X_length, ))
# BOUNDARY CONDITIONS
A2Ut[0,0], A2Ut[0, 1] = -1, 1 # left boundary
A2Ut[-1, -2], A2Ut[-1,-1] = -1, 1 # right boundary
A1Ut[0,0], A1Ut[0, 1] = -1, 1 # left boundary
A1Ut[-1, -2], A1Ut[-1,-1] = -1, 1 # right boundary
# A1 UM+1 = f - A2 UM
for i in range(1, X_length-1): # for each x in space do
A2Ut[i, i] = -1 - zeta*(-2*eps_u*k/(h**2)+ gamma_u*k/(h**2)*(W[T-DT, i+1]+W[T-DT, i-1]-2*W[T-DT, i])) # contribution of UN
A2Ut[i, i+1] = - zeta*(eps_u*k/(h**2)+gamma_u*k/(4*h**2)*(W[T-DT, i+1]-W[T-DT,i-1])) # contribution of UN-1
A2Ut[i, i-1] = - zeta*(eps_u*k/(h**2)-gamma_u*k/(4*h**2)*(W[T-DT, i+1]-W[T-DT,i-1]))
A1Ut[i,i] = 1 - (1-zeta)*(-2*eps_u*k/(h**2)+ gamma_u*k/(h**2)*(W[T-DT, i+1]+W[T-DT, i-1]-2*W[T-DT, i]))
A1Ut[i, i+1] = - (1-zeta)*(eps_u*k/(h**2)+gamma_u*k/(4*h**2)*(W[T-DT, i+1]-W[T-DT,i-1]))
A1Ut[i, i-1] = -(1-zeta)*(eps_u*k/(h**2)-gamma_u*k/(4*h**2)*(W[T-DT, i+1]-W[T-DT,i-1]))
dummy = A2Ut@U[T-1,:]
fU = fU - dummy
return A1Ut, fU, A2Ut
def constr_lineqV(U, W, V, N, M, T):
'''
N: nb of x grid points (int)
T: current timestep (int)
U: discrete solution of u (np.array)
W: discrete solution of w (np.array)
V: discrete solution of v (np.array)
M: nb of time steps (int)
'''
k = 1.0/float(M)
h = 1.0/float(N)
#k = 0.25*h**2*1.0/eps_v
#assert(U.shape == W.shape and W.shape == V.shape, 'Dim error')
#assert(U.shape[1]==N and U.shape[0] == M, 'Dim error')
X_length = N
A2Vt = np.zeros((X_length, X_length))
A1Vt = np.zeros((X_length, X_length))
fV = np.zeros((X_length, ))
# BOUNDARY CONDITIONS
A2Vt[0,0], A2Vt[0, 1] = -1.0, 1.0 # left boundary
A2Vt[-1, -2], A2Vt[-1,-1] = -1.0, 1.0 # right boundary
A1Vt[0,0], A1Vt[0, 1] = -1.0, 1.0 # left boundary
A1Vt[-1, -2], A1Vt[-1,-1] = -1.0, 1.0 # right boundary
# A1 VM+1 = f - A2 VM
for i in range(1, X_length-1): # for each x in space do
A1Vt[i, i] = 1 + (1-zeta)*2*eps_v*k/(h**2) + beta_v*(1-zeta)
A1Vt[i, i-1] = -(1-zeta)*eps_v*k/(h**2)
A1Vt[i, i+1] = -(1-zeta)*eps_v*k/(h**2)
A2Vt[i, i] = -1 + zeta*2*eps_v*k/(h**2) + beta_v*zeta
A2Vt[i, i-1] = -zeta*eps_v*k/(h**2)
A2Vt[i, i+1] = -zeta*eps_v*k/(h**2)
fV[i] = alpha_v*U[T-1, i]
dummy = A2Vt@V[T-1,:]
fV = fV - dummy
return A1Vt, fV, A2Vt
def constr_lineqW(U, W, V, N, M, T):
'''
N: nb of x grid points (int)
T: current timestep (int)
U: discrete solution of u (np.array)
W: discrete solution of w (np.array)
V: discrete solution of v (np.array)
M: nb of time steps (int)
'''
#k = 1.0/float(M)
h = 1.0/float(N)
k = 1.0/float(M)
#k = 0.25*h**2*1.0/eps_v
#assert(U.shape == W.shape and W.shape == V.shape, 'Dim error')
#assert(U.shape[1]==N and U.shape[0] == M, 'Dim error')
X_length = N
A2Wt = np.zeros((X_length, X_length))
A1Wt = np.zeros((X_length, X_length))
fW = np.zeros((X_length, ))
for i in range(0, X_length): # for each x in space do
A1Wt[i,i] = 1.0 + k*(1-zeta)*eta_w*V[T,i]
A2Wt[i,i] = -1.0 + k*zeta*eta_w*V[T,i]
dummy = A2Wt@W[T-1,:]
fW = fW - dummy
return A1Wt, fW, A2Wt
def SB_solver_1D(N, M, nb_sec):
print(M)
h = 1.0/float(N)
k = 1.0/float(M)
U = np.zeros((M*nb_sec,N))
W = np.zeros((M*nb_sec,N))
V = np.zeros((M*nb_sec,N))
epsilon = 0.01
# J = 0: SET INITIAL conditions
n0 = [np.exp(-((1.0*x)/N)**2/epsilon)*1.0 for x in range(N)]
f0 = [(1.0 - 0.25*np.exp(-((1.0*x)/N)**2/epsilon))*1.0 for x in range(N)]
m0 = [0.5*np.exp(-((1.0*x)/N)**2/epsilon) for x in range(N)]
U[0,:] = np.array(n0)
U[0,0], U[0,-1] = U[0,1], U[0,-2]
#V[0,:] = np.array(m0)
#V[0,0], V[0,-1] = V[0,1], V[0,-2]
W[0,:] = np.array(f0)
rhoU, rhoV, rhoW = [], [], []
# J = 1..M
for j in range(1, M*nb_sec): # for each time do
#print('_', end='')
AV, fV, BV = constr_lineqV(U, W, V, N, M, j) # use newer values of U already?
V_solve = la.solve(AV, fV)#, V_guess
V[j,:] = V_solve
AW, fW , BW = constr_lineqW(U, W, V, N, M, j)
W_solve = la.solve(AW, fW)
W[j,:] = W_solve
AU, fU, BU = constr_lineqU(U, W, V, N, M, j)
U_solve = la.solve(AU, fU)#, U_guess
U[j,:] = U_solve
return U, V, W, AU, BU, AV, BV, rhoU, rhoV, rhoW
compsol = True
N_tsol = 1024
nb_sec = 128
hsol = 1.0/float(N_tsol)
#ksol = 0.25*h**2 / max(eps_u,eps_v)
#M_tsol = int(1.0/k)
M_tsol=1024
ksol=1.0/float(M_tsol)
if compsol :
Usol, Vsol, Wsol, AUx, BUx, AVx, BVx, rhoUx, rhoVx, rhoWx = SB_solver_1D(N_tsol,M_tsol, nb_sec)
e=np.zeros(20)
for i in range (5, 9):
N_t=2**i
nb_sec = 128
M_t=2**i
k=1.0/float(M_tsol)
Tsol= M_tsol*nb_sec -1
T= M_t*nb_sec -1
K=M_tsol-1
# print(M_t,N_t)
Usolfit=np.zeros((M_t*nb_sec,N_t))
U, V, W, AUx, BUx, AVx, BVx, rhoUx, rhoVx, rhoWx = SB_solver_1D(N_t,M_t, nb_sec)
#print(np.size(Usolfit),np.size(U))
#for j in range(10) :
#Usolfit[j,:] =U[2**(M_t-i)*j,2**(6-i):]
e[i-1]= la.norm(U[T,:] - Usol[Tsol,::2**(K-i)])
# print(e)
xx = np.array(range(0,20))
fig = plt.figure(1)
plt.plot(xx, e)
|
[
"matplotlib.pyplot.plot",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.linalg.norm",
"numpy.exp",
"numpy.linalg.solve"
] |
[((5835, 5847), 'numpy.zeros', 'np.zeros', (['(20)'], {}), '(20)\n', (5843, 5847), True, 'import numpy as np\n'), ((6402, 6415), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (6412, 6415), True, 'from matplotlib import pyplot as plt\n'), ((6416, 6431), 'matplotlib.pyplot.plot', 'plt.plot', (['xx', 'e'], {}), '(xx, e)\n', (6424, 6431), True, 'from matplotlib import pyplot as plt\n'), ((856, 886), 'numpy.zeros', 'np.zeros', (['(X_length, X_length)'], {}), '((X_length, X_length))\n', (864, 886), True, 'import numpy as np\n'), ((898, 928), 'numpy.zeros', 'np.zeros', (['(X_length, X_length)'], {}), '((X_length, X_length))\n', (906, 928), True, 'import numpy as np\n'), ((939, 960), 'numpy.zeros', 'np.zeros', (['(X_length,)'], {}), '((X_length,))\n', (947, 960), True, 'import numpy as np\n'), ((2540, 2570), 'numpy.zeros', 'np.zeros', (['(X_length, X_length)'], {}), '((X_length, X_length))\n', (2548, 2570), True, 'import numpy as np\n'), ((2582, 2612), 'numpy.zeros', 'np.zeros', (['(X_length, X_length)'], {}), '((X_length, X_length))\n', (2590, 2612), True, 'import numpy as np\n'), ((2623, 2644), 'numpy.zeros', 'np.zeros', (['(X_length,)'], {}), '((X_length,))\n', (2631, 2644), True, 'import numpy as np\n'), ((3976, 4006), 'numpy.zeros', 'np.zeros', (['(X_length, X_length)'], {}), '((X_length, X_length))\n', (3984, 4006), True, 'import numpy as np\n'), ((4018, 4048), 'numpy.zeros', 'np.zeros', (['(X_length, X_length)'], {}), '((X_length, X_length))\n', (4026, 4048), True, 'import numpy as np\n'), ((4059, 4080), 'numpy.zeros', 'np.zeros', (['(X_length,)'], {}), '((X_length,))\n', (4067, 4080), True, 'import numpy as np\n'), ((4430, 4455), 'numpy.zeros', 'np.zeros', (['(M * nb_sec, N)'], {}), '((M * nb_sec, N))\n', (4438, 4455), True, 'import numpy as np\n'), ((4461, 4486), 'numpy.zeros', 'np.zeros', (['(M * nb_sec, N)'], {}), '((M * nb_sec, N))\n', (4469, 4486), True, 'import numpy as np\n'), ((4492, 4517), 'numpy.zeros', 'np.zeros', (['(M * nb_sec, N)'], {}), '((M * nb_sec, N))\n', (4500, 4517), True, 'import numpy as np\n'), ((4797, 4809), 'numpy.array', 'np.array', (['n0'], {}), '(n0)\n', (4805, 4809), True, 'import numpy as np\n'), ((4927, 4939), 'numpy.array', 'np.array', (['f0'], {}), '(f0)\n', (4935, 4939), True, 'import numpy as np\n'), ((6035, 6064), 'numpy.zeros', 'np.zeros', (['(M_t * nb_sec, N_t)'], {}), '((M_t * nb_sec, N_t))\n', (6043, 6064), True, 'import numpy as np\n'), ((6295, 6340), 'numpy.linalg.norm', 'la.norm', (['(U[T, :] - Usol[Tsol, ::2 ** (K - i)])'], {}), '(U[T, :] - Usol[Tsol, ::2 ** (K - i)])\n', (6302, 6340), True, 'import numpy.linalg as la\n'), ((5183, 5199), 'numpy.linalg.solve', 'la.solve', (['AV', 'fV'], {}), '(AV, fV)\n', (5191, 5199), True, 'import numpy.linalg as la\n'), ((5316, 5332), 'numpy.linalg.solve', 'la.solve', (['AW', 'fW'], {}), '(AW, fW)\n', (5324, 5332), True, 'import numpy.linalg as la\n'), ((5438, 5454), 'numpy.linalg.solve', 'la.solve', (['AU', 'fU'], {}), '(AU, fU)\n', (5446, 5454), True, 'import numpy.linalg as la\n'), ((4586, 4623), 'numpy.exp', 'np.exp', (['(-(1.0 * x / N) ** 2 / epsilon)'], {}), '(-(1.0 * x / N) ** 2 / epsilon)\n', (4592, 4623), True, 'import numpy as np\n'), ((4733, 4770), 'numpy.exp', 'np.exp', (['(-(1.0 * x / N) ** 2 / epsilon)'], {}), '(-(1.0 * x / N) ** 2 / epsilon)\n', (4739, 4770), True, 'import numpy as np\n'), ((4663, 4700), 'numpy.exp', 'np.exp', (['(-(1.0 * x / N) ** 2 / epsilon)'], {}), '(-(1.0 * x / N) ** 2 / epsilon)\n', (4669, 4700), True, 'import numpy as np\n')]
|
import numpy as np
def read_pairs(pairs_filename):
pairs = []
with open(pairs_filename, 'r') as f:
for line in f.readlines()[1:]:
print(line)
pair = line.strip().split()
print('--',pair)
pairs.append(pair)
return np.array(pairs)
read_pairs('ab_pairs_428.txt')
|
[
"numpy.array"
] |
[((292, 307), 'numpy.array', 'np.array', (['pairs'], {}), '(pairs)\n', (300, 307), True, 'import numpy as np\n')]
|
'''
data parameters
data: cora / dblp / arXiv / acm
split: train-test split used for the dataset
'''
data = "dblp"
split = 2
'''
model parameters
h: number of hidden dimensions
drop: hidden droput
relu: flag for relu non-linearity
'''
h = 1024
drop = 0.0
relu = False
'''
miscellaneous parameters
lr: learning rate
epochs: number of epochs
decay: weight decay
'''
lr = 0.001
epochs = 200
decay = 0.0005
'''
environmental parameters
gpu: gpu number (range: {0, 1, 2, 3, 4, 5, 6, 7})
seed: initial seed value
log: log on file (true) or print on console (false)
'''
gpu = 0
seed = 42
log = False
import argparse
def parse():
"""
add and parse arguments / hyperparameters
"""
p = argparse.ArgumentParser()
p = argparse.ArgumentParser(description="Inductive Vertex Embedding on Multi-Relational Ordered Hypergraphs")
def str2bool(v):
if isinstance(v, bool): return v
if v.lower() in ('no', 'false', 'f', 'n', '0'): return False
else: return True
p.add_argument('--data', type=str, default=data, help='data name (FB-AUTO)')
p.add_argument('--split', type=str, default=split, help='train-test split used for the dataset')
p.add_argument('--h', type=int, default=h, help='number of hidden dimensions')
p.add_argument('--drop', type=float, default=drop, help='hidden droput')
p.add_argument("--relu", default=relu, type=str2bool, help="flag for relu non-linearity")
p.add_argument('--lr', type=float, default=lr, help='learning rate')
p.add_argument('--epochs', type=int, default=epochs, help='number of epochs')
p.add_argument('--decay', type=float, default=decay, help='weight decay')
p.add_argument('--gpu', type=int, default=gpu, help='gpu number')
p.add_argument('--seed', type=int, default=seed, help='initial seed value')
p.add_argument("--log", default=log, type=str2bool, help="log on file (true) or print on console (false)")
p.add_argument('-f') # for jupyter default
return p.parse_args()
import os, inspect, logging
class Logger():
def __init__(self, args):
'''
Initialise logger
'''
# setup checkpoint directory
current = os.path.abspath(inspect.getfile(inspect.currentframe()))
Dir = os.path.join(os.path.split(os.path.split(current)[0])[0], "checkpoints")
self.log = args.log
# setup log file
if args.log:
if not os.path.exists(Dir): os.makedirs(Dir)
name = str(len(os.listdir(Dir)) + 1)
Dir = os.path.join(Dir, name)
if not os.path.exists(Dir): os.makedirs(Dir)
args.dir = Dir
# setup logging
logger = logging.getLogger(__name__)
file = os.path.join(Dir, name + ".log")
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", filename=file, level=logging.INFO)
self.logger = logger
def info(self, s):
if self.log: self.logger.info(s)
else: print(s)
import torch, numpy as np
def setup():
# parse arguments
args = parse()
args.logger = Logger(args)
D = vars(args)
# log configuration
l = ['']*(len(D)-1) + ['\n\n']
args.logger.info("Arguments are as follows")
for i, k in enumerate(D): args.logger.info(k + ": " + str(D[k]) + l[i])
# set seed
torch.manual_seed(args.seed)
np.random.seed(args.seed)
os.environ['PYTHONHASHSEED'] = str(args.seed)
# set device (gpu/cpu)
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
args.device = torch.device('cuda') if args.gpu != '-1' and torch.cuda.is_available() else torch.device('cpu')
return args
|
[
"numpy.random.seed",
"argparse.ArgumentParser",
"logging.basicConfig",
"os.makedirs",
"torch.manual_seed",
"os.path.exists",
"torch.cuda.is_available",
"torch.device",
"inspect.currentframe",
"os.path.split",
"os.path.join",
"os.listdir",
"logging.getLogger"
] |
[((704, 729), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (727, 729), False, 'import argparse\n'), ((738, 848), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Inductive Vertex Embedding on Multi-Relational Ordered Hypergraphs"""'}), "(description=\n 'Inductive Vertex Embedding on Multi-Relational Ordered Hypergraphs')\n", (761, 848), False, 'import argparse\n'), ((3416, 3444), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (3433, 3444), False, 'import torch, numpy as np\n'), ((3449, 3474), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (3463, 3474), True, 'import torch, numpy as np\n'), ((3687, 3707), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (3699, 3707), False, 'import torch, numpy as np\n'), ((3763, 3782), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3775, 3782), False, 'import torch, numpy as np\n'), ((2568, 2591), 'os.path.join', 'os.path.join', (['Dir', 'name'], {}), '(Dir, name)\n', (2580, 2591), False, 'import os, inspect, logging\n'), ((2726, 2753), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2743, 2753), False, 'import os, inspect, logging\n'), ((2786, 2818), 'os.path.join', 'os.path.join', (['Dir', "(name + '.log')"], {}), "(Dir, name + '.log')\n", (2798, 2818), False, 'import os, inspect, logging\n'), ((2831, 2943), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(message)s"""', 'filename': 'file', 'level': 'logging.INFO'}), "(format='%(asctime)s - %(levelname)s - %(message)s',\n filename=file, level=logging.INFO)\n", (2850, 2943), False, 'import os, inspect, logging\n'), ((3732, 3757), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3755, 3757), False, 'import torch, numpy as np\n'), ((2233, 2255), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (2253, 2255), False, 'import os, inspect, logging\n'), ((2450, 2469), 'os.path.exists', 'os.path.exists', (['Dir'], {}), '(Dir)\n', (2464, 2469), False, 'import os, inspect, logging\n'), ((2471, 2487), 'os.makedirs', 'os.makedirs', (['Dir'], {}), '(Dir)\n', (2482, 2487), False, 'import os, inspect, logging\n'), ((2611, 2630), 'os.path.exists', 'os.path.exists', (['Dir'], {}), '(Dir)\n', (2625, 2630), False, 'import os, inspect, logging\n'), ((2632, 2648), 'os.makedirs', 'os.makedirs', (['Dir'], {}), '(Dir)\n', (2643, 2648), False, 'import os, inspect, logging\n'), ((2299, 2321), 'os.path.split', 'os.path.split', (['current'], {}), '(current)\n', (2312, 2321), False, 'import os, inspect, logging\n'), ((2515, 2530), 'os.listdir', 'os.listdir', (['Dir'], {}), '(Dir)\n', (2525, 2530), False, 'import os, inspect, logging\n')]
|
''' Demonstrates linear regression with TensorFlow '''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
# Set constants
N = 1000
learning_rate = 0.1
batch_size = 40 # the size of the part of the entire dataset, we don't feed the entire dataset all at once, we divide it into parts
num_batches = 400
# Step 1: Generate input points
x = np.random.normal(size=N)
m_real = np.random.normal(loc=0.5, scale=0.2, size= N)
b_real = np.random.normal(loc=1.0, scale=0.2, size= N)
y = m_real*x + b_real
# Step 2: Create variables and placeholders
m= tf.Variable(tf.random_normal([]))
b= tf.Variable(tf.random_normal([]))
x_holder = tf.placeholder(tf.float32, shape=[batch_size])
y_holder = tf.placeholder(tf.float32, shape=[batch_size])
# Step 3: Define model and loss
model = m * x_holder + b
loss = tf.reduce_mean(tf.pow(model - y_holder, 2))
# Step 4: Create optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss)
# Step 5: Execute optimizer in a session
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(num_batches):
x_data = np.empty(batch_size)
y_data = np.empty(batch_size)
for i in range(batch_size):
index = np.random.randint(0, N)
x_data[i] = x[index]
y_data[i] = y[index]
sess.run(optimizer, feed_dict={x_holder: x_data, y_holder: y_data})
print("m = ", sess.run(m))
print("b = ", sess.run(b))
|
[
"tensorflow.global_variables_initializer",
"numpy.empty",
"tensorflow.Session",
"tensorflow.pow",
"tensorflow.placeholder",
"numpy.random.randint",
"tensorflow.random_normal",
"numpy.random.normal",
"tensorflow.train.GradientDescentOptimizer"
] |
[((443, 467), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'N'}), '(size=N)\n', (459, 467), True, 'import numpy as np\n'), ((477, 521), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.5)', 'scale': '(0.2)', 'size': 'N'}), '(loc=0.5, scale=0.2, size=N)\n', (493, 521), True, 'import numpy as np\n'), ((532, 576), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(1.0)', 'scale': '(0.2)', 'size': 'N'}), '(loc=1.0, scale=0.2, size=N)\n', (548, 576), True, 'import numpy as np\n'), ((731, 777), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[batch_size]'}), '(tf.float32, shape=[batch_size])\n', (745, 777), True, 'import tensorflow as tf\n'), ((789, 835), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[batch_size]'}), '(tf.float32, shape=[batch_size])\n', (803, 835), True, 'import tensorflow as tf\n'), ((660, 680), 'tensorflow.random_normal', 'tf.random_normal', (['[]'], {}), '([])\n', (676, 680), True, 'import tensorflow as tf\n'), ((697, 717), 'tensorflow.random_normal', 'tf.random_normal', (['[]'], {}), '([])\n', (713, 717), True, 'import tensorflow as tf\n'), ((915, 942), 'tensorflow.pow', 'tf.pow', (['(model - y_holder)', '(2)'], {}), '(model - y_holder, 2)\n', (921, 942), True, 'import tensorflow as tf\n'), ((1108, 1120), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1118, 1120), True, 'import tensorflow as tf\n'), ((983, 1045), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (1016, 1045), True, 'import tensorflow as tf\n'), ((1143, 1176), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1174, 1176), True, 'import tensorflow as tf\n'), ((1229, 1249), 'numpy.empty', 'np.empty', (['batch_size'], {}), '(batch_size)\n', (1237, 1249), True, 'import numpy as np\n'), ((1267, 1287), 'numpy.empty', 'np.empty', (['batch_size'], {}), '(batch_size)\n', (1275, 1287), True, 'import numpy as np\n'), ((1345, 1368), 'numpy.random.randint', 'np.random.randint', (['(0)', 'N'], {}), '(0, N)\n', (1362, 1368), True, 'import numpy as np\n')]
|
#
from typing import List
import sys
import json
import numpy as np
from fairseq import pybleu
def process_bpe_symbol(sentence: str, bpe_symbol: str):
if bpe_symbol is not None:
sentence = (sentence + ' ').replace(bpe_symbol, '').rstrip()
return sentence
# =====
# algorithm helper
# performing aligning by matching scores
# -- input is 2d matrix of matching scores [len_a1, len_a2], should be >=0, 0 means absolute no match
# -- the order is important for breaking ties for add_a1,match,add_a2: by default prefer add-a2 later
def align_matches(match_score_arr, order_scores=None):
DEFAULT_CODE = (0,1,2) # a1/match/a2
if order_scores is None:
order_scores = DEFAULT_CODE
assert np.all(match_score_arr>=0.)
len1, len2 = match_score_arr.shape
# recordings
record_best_scores = np.zeros((1+len1, 1+len2), dtype=np.float32) # best matching scores
# pointers for back-tracing & also prefer order: by default add a1(x+=1); match; add a2(y+=1)
record_best_codes = np.zeros((1+len1, 1+len2), dtype=np.int32)
record_best_codes[0,:] = 2 # add a2 at y
record_best_codes[:,0] = 0 # add a1 at x
record_best_codes[0,0] = -1 # never used
# loop: the looping order (ij or ji) does not matter
for i in range(len1):
ip1 = i + 1
for j in range(len2):
jp1 = j + 1
s_match = match_score_arr[i,j] + record_best_scores[i,j] # match one
s_a1 = record_best_scores[i,jp1] # add a1 on x
s_a2 = record_best_scores[ip1,j] # add a2 on y
ordered_selections = sorted(zip((s_a1, s_match, s_a2), order_scores, DEFAULT_CODE))
sel_score, _, sel_code = ordered_selections[-1] # max score
record_best_scores[ip1,jp1] = sel_score
record_best_codes[ip1,jp1] = sel_code
# backtracking for whole seq and aligning point
# results of idx matches
merge_to_a1, merge_to_a2 = [], [] # merge_idx -> a?_idx or None
a1_to_merge, a2_to_merge = [], [] # a?_idx -> merge_idx
back_i, back_j = len1, len2
cur_midx = -1
while back_i+back_j>0: # there are still remainings
code = record_best_codes[back_i, back_j]
if code == 0: # add a1[back_i-1]
back_i -= 1
merge_to_a1.append(back_i)
merge_to_a2.append(None)
a1_to_merge.append(cur_midx)
elif code == 1: # add matched a1[back_i-1],a2[back_j-1]
back_i -= 1
back_j -= 1
merge_to_a1.append(back_i)
merge_to_a2.append(back_j)
a1_to_merge.append(cur_midx)
a2_to_merge.append(cur_midx)
elif code == 2: # add a2[back_j-1]
back_j -= 1
merge_to_a1.append(None)
merge_to_a2.append(back_j)
a2_to_merge.append(cur_midx)
else:
raise NotImplementedError()
cur_midx -= 1
# reverse things
merge_to_a1.reverse()
merge_to_a2.reverse()
merge_len = len(merge_to_a1)
a1_to_merge = [merge_len+z for z in reversed(a1_to_merge)]
a2_to_merge = [merge_len+z for z in reversed(a2_to_merge)]
return merge_to_a1, merge_to_a2, a1_to_merge, a2_to_merge
# =====
# usually we want to match s2 to s1, thus hint is the start of s2 to s1
def align_seqs(s1, s2, hint_s2_on_s1_offset: float=None, hint_scale=0.1, match_f=(lambda x,y: float(x==y))):
# first compare each pair to get match scores
len1, len2 = len(s1), len(s2)
match_score_arr = np.asarray([match_f(x,y) for x in s1 for y in s2]).reshape((len1, len2))
if hint_s2_on_s1_offset is not None:
assert hint_s2_on_s1_offset>=0 and hint_s2_on_s1_offset<len(s1), "Outside range of s1"
posi_diff = np.arange(len1)[:, np.newaxis] - (np.arange(len2)+hint_s2_on_s1_offset)[np.newaxis, :]
hint_rewards = hint_scale * np.exp(-np.abs(posi_diff))
match_score_arr += (match_score_arr>0.).astype(np.float) * hint_rewards # only add if >0
# then get results
return align_matches(match_score_arr)
# =====
# special routine to merge a series of sequences (incrementally, left to right)
# input: seq_list is List[List[item]], K is merging range in each step
def merge_seqs(seq_list: List[List], K: int):
cur_seq = []
for s in seq_list:
if len(cur_seq) < K:
cur0, cur1 = [], cur_seq
else:
cur0, cur1 = cur_seq[:-K], cur_seq[-K:] # use the most recent K for merging
align_res = align_seqs(cur1, s)
# get the merged one
ma1, ma2 = align_res[:2]
cur2 = [(s[b] if a is None else cur1[a]) for a,b in zip(ma1, ma2)]
# finally concat
cur_seq = cur0 + cur2
return cur_seq
# ==
def test1():
# test
s1 = "pero las horas son fijadas por ' provincia ' , no por el gobierno central ...".split()
s2 = "pero las horas se establecen por provincia , no por ' gobierno central ' ...".split()
rets = align_seqs(s1, s2)
s_merge = [f"{s1[a] if a else ''}/{s2[b] if b else ''}" for a, b in zip(rets[0], rets[1])]
# breakpoint()
print(rets)
def test2():
SLEN = 20
PLEN = 10
WIN = 2
original_seq = list(range(SLEN))
center_seq = sorted(np.random.randint(0, SLEN, size=PLEN))
pieces = [(list(range(r-WIN, r)) + [r] + list(range(r+1, r+WIN+1))) for r in center_seq]
ret_seq = merge_seqs(pieces, K=5)
print(ret_seq, center_seq)
def main(filename, SEG=3, K=3):
scorer = pybleu.PyBleuScorer()
IGNORE_SET = ["<s>", "</s>"]
SEG = int(SEG) # SEG is used when reading raw inputs
K = int(K) # K is tunable for merging
pred_sens = []
cur_ref = ''
cur_hyp = ''
with open(filename) as f:
for line in f:
if line.startswith('ref:'):
if len(cur_ref) > 0:
pred_sens.append((cur_ref, cur_hyp))
cur_hyp = ''
cur_ref = line.split(':', 1)[1].strip()
elif line.startswith('hyp:'):
cur_hyp = ' '.join((cur_hyp, line.split(':', 1)[1].strip()))
results = []
with open('pred.txt', 'w') as predf, open('ref.txt', 'w') as reff:
for line in pred_sens:
ref, pred = line
try:
seq_list = json.loads(line) # each line is a json of List[List]
except:
raw_seq_list = pred.split()
seq_list = [raw_seq_list[i:i+SEG] for i in range(0, len(raw_seq_list), SEG)]
ret_seq = merge_seqs(seq_list, K)
final_seq = [""]
for r in ret_seq:
if r != final_seq[-1] and r not in IGNORE_SET:
final_seq.append(r)
ori_ref = process_bpe_symbol(ref.strip(), '@@ ')
reff.write(ori_ref + '\n')
ori_pred = process_bpe_symbol(' '.join(final_seq).strip(), '@@ ')
results.append((ori_ref, ori_pred))
predf.write(ori_pred + '\n')
ref, out = zip(*results)
print(scorer.score(ref, out))
if __name__ == '__main__':
# test1()
# test2()
main(*sys.argv[1:])
|
[
"numpy.abs",
"json.loads",
"numpy.zeros",
"numpy.random.randint",
"fairseq.pybleu.PyBleuScorer",
"numpy.arange",
"numpy.all"
] |
[((745, 775), 'numpy.all', 'np.all', (['(match_score_arr >= 0.0)'], {}), '(match_score_arr >= 0.0)\n', (751, 775), True, 'import numpy as np\n'), ((857, 905), 'numpy.zeros', 'np.zeros', (['(1 + len1, 1 + len2)'], {'dtype': 'np.float32'}), '((1 + len1, 1 + len2), dtype=np.float32)\n', (865, 905), True, 'import numpy as np\n'), ((1050, 1096), 'numpy.zeros', 'np.zeros', (['(1 + len1, 1 + len2)'], {'dtype': 'np.int32'}), '((1 + len1, 1 + len2), dtype=np.int32)\n', (1058, 1096), True, 'import numpy as np\n'), ((5599, 5620), 'fairseq.pybleu.PyBleuScorer', 'pybleu.PyBleuScorer', ([], {}), '()\n', (5618, 5620), False, 'from fairseq import pybleu\n'), ((5340, 5377), 'numpy.random.randint', 'np.random.randint', (['(0)', 'SLEN'], {'size': 'PLEN'}), '(0, SLEN, size=PLEN)\n', (5357, 5377), True, 'import numpy as np\n'), ((3824, 3839), 'numpy.arange', 'np.arange', (['len1'], {}), '(len1)\n', (3833, 3839), True, 'import numpy as np\n'), ((6442, 6458), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (6452, 6458), False, 'import json\n'), ((3858, 3873), 'numpy.arange', 'np.arange', (['len2'], {}), '(len2)\n', (3867, 3873), True, 'import numpy as np\n'), ((3956, 3973), 'numpy.abs', 'np.abs', (['posi_diff'], {}), '(posi_diff)\n', (3962, 3973), True, 'import numpy as np\n')]
|
import time
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split, KFold
from dogFunctions import genData, genBatch
def convBlock( X, trn, nFilters, kernelSize, bnm ):
'''A block consisting of a convolution, a poolingi, and a batch normalization layer.'''
heInit = tf.variance_scaling_initializer()
with tf.name_scope("ConvolutionBlock"):
conv = tf.layers.conv2d( X, filters = nFilters, kernel_size = kernelSize, strides = 1,
padding = "same", kernel_initializer = heInit )
pool = tf.layers.max_pooling2d( conv, pool_size = 2, strides = 2, padding = "valid",
name = "pool" )
bn = tf.layers.batch_normalization( pool, training = trn, momentum = bnm )
return tf.nn.elu( bn )
def inceptionBlock( X, trn, nPath1, nPath2_1, nPath2_2, nPath3_1, nPath3_2, nPath4, bnm ):
"""Creates an inception block with a residual (skip) connection."""
heInit = tf.variance_scaling_initializer()
m, h, w, c = X.get_shape().as_list()
with tf.name_scope( "inceptionBlock" ):
path1 = tf.layers.conv2d( X, filters = nPath1, kernel_size = 1, strides = 1,
padding = "same", activation = tf.nn.relu,
kernel_initializer = heInit )
in2 = tf.layers.conv2d( X, filters = nPath2_1, kernel_size = 1, strides = 1,
padding = "same", activation = tf.nn.elu,
kernel_initializer = heInit )
path2 = tf.layers.conv2d( in2, filters = nPath2_2, kernel_size = 3, strides = 1,
padding = "same", activation = tf.nn.elu,
kernel_initializer = heInit )
in3 = tf.layers.conv2d( X, filters = nPath3_1, kernel_size = 1, strides = 1,
padding = "same", activation = tf.nn.elu,
kernel_initializer = heInit )
path3 = tf.layers.conv2d( in3, filters = nPath3_2, kernel_size = 5, strides = 1,
padding = "same", activation = tf.nn.elu,
kernel_initializer = heInit )
in4 = tf.layers.max_pooling2d( X, pool_size = 2, strides = 1, padding = "same",
name = "p4.1" )
path4 = tf.layers.conv2d( in4, filters = nPath4, kernel_size = 1, strides = 1,
padding = "same", activation = tf.nn.elu,
kernel_initializer = heInit)
concat = tf.concat( [path1, path2, path3, path4], axis = 3 )
merge = tf.layers.conv2d( concat, filters = c, kernel_size = 1, strides = 1,
padding = "same", kernel_initializer = heInit )
bn = tf.layers.batch_normalization( merge + X, training = trn, momentum = bnm )
return tf.nn.elu( bn )
def dogClassifier( X, y, trn, alpha = 0.001, b1 = 0.9, b2 = 0.999, eps = 1e-08,
bnm = 0.99, dropProb = 0.5 ):
"""Creates all objects needed for training the dog classifier."""
heInit = tf.variance_scaling_initializer()
with tf.name_scope( "cnn" ):
conv1 = convBlock( X, trn, 8, 3, bnm )
incept1 = inceptionBlock( conv1, trn, 4, 2, 4, 2, 4, 4, bnm )
conv2 = convBlock( incept1, trn, 16, 3, bnm )
incept2_1 = inceptionBlock( conv2, trn, 8, 4, 8, 4, 8, 8, bnm )
incept2_2 = inceptionBlock( incept2_1, trn, 8, 4, 8, 4, 8, 8, bnm )
conv3 = convBlock( incept2_2, trn, 32, 3, bnm )
incept3_1 = inceptionBlock( conv3, trn, 16, 8, 16, 8, 16, 16, bnm )
incept3_2 = inceptionBlock( incept3_1, trn, 16, 8, 16, 8, 16, 16, bnm )
conv4 = convBlock( incept3_2, trn, 48, 3, bnm )
incept4_1 = inceptionBlock( conv4, trn, 24, 12, 24, 12, 24, 24, bnm )
incept4_2 = inceptionBlock( incept4_1, trn, 24, 12, 24, 12, 24, 24, bnm )
conv5 = convBlock( incept4_2, trn, 64, 3, bnm )
incept5_1 = inceptionBlock( conv5, trn, 32, 16, 32, 16, 32, 32, bnm )
incept5_2 = inceptionBlock( incept5_1, trn, 32, 16, 32, 16, 32, 32, bnm )
flat = tf.layers.flatten( incept5_2 )
dropout1 = tf.layers.dropout( flat, dropProb, training = trn )
fc1 = tf.layers.dense( dropout1, 1024, name = "fc1", kernel_initializer = heInit,
activation = tf.nn.elu )
dropout2 = tf.layers.dropout( fc1, dropProb, training = trn )
fc2 = tf.layers.dense( dropout2, 1024, name = "fc2", kernel_initializer = heInit,
activation = tf.nn.elu )
dropout3 = tf.layers.dropout( fc2, dropProb, training = trn )
logits = tf.layers.dense( dropout3, 120, name = "output", kernel_initializer = heInit )
predict = tf.nn.softmax( logits )
with tf.name_scope("loss"):
crossEnt = tf.nn.sparse_softmax_cross_entropy_with_logits( labels = y, logits = logits)
loss = tf.reduce_mean( crossEnt, name = "loss" )
with tf.name_scope("eval"):
correct = tf.nn.in_top_k(logits, y, 1)
accuracy = tf.reduce_mean( tf.cast(correct, tf.float32) )
with tf.name_scope("train"):
#opt = tf.train.MomentumOptimizer( learning_rate = alpha, momentum = b1,
# use_nesterov = False )
opt = tf.train.AdamOptimizer( learning_rate = alpha, beta1 = b1, beta2 = b2,
epsilon = eps )
training = opt.minimize( loss )
lossSummary = tf.summary.scalar("crossEntropy", loss)
with tf.name_scope("utility"):
init = tf.global_variables_initializer()
saver = tf.train.Saver()
return loss, training, accuracy, predict, lossSummary, init, saver
def batchEval( X, y, allX, allY, batchSize, function ):
count = 0
temp = 0
for start in range(0, len(allX) - 1, batchSize):
bX, bY = genData( allX[ start : start + batchSize ], allY, size = 200 )
n = len(bX)
count += n
temp += function.eval( feed_dict = { X : bX, y : bY } ) * n
return temp / count
def trainModel( trainX, valX, labels, params, saveModel = False , loadState = False,
histDtype = np.float32 ):
"""Trains the model. Loads a previously saved state if loadStat is True."""
imgSize = 200
parameters = params[ "params" ]
tf.reset_default_graph()
X = tf.placeholder(tf.float32, shape = (None, imgSize, imgSize, 3), name = "X")
y = tf.placeholder(tf.int32, shape = (None), name = "y")
trn = tf.placeholder_with_default( False, shape = (), name = "trn" )
loss, training, accuracy, predict, lossSummary, init, saver = dogClassifier( X, y, trn, **parameters )
extraOps = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
batchSize = params[ "batchSize" ]
maxBatch = 512
patience = 0
step = 0
startTime = time.time()
with tf.Session() as sess:
if ( loadState ):
saver.restore( sess, "./best/dogClass-best.ckpt" )
else:
init.run()
tls = [ histDtype( batchEval( X, y, trainX, labels, batchSize, loss ) ) ]
tas = [ histDtype( batchEval( X, y, trainX, labels, batchSize, accuracy ) ) ]
vls = [ histDtype( batchEval( X, y, valX, labels, batchSize, loss ) ) ]
vas = [ histDtype( batchEval( X, y, valX, labels, batchSize, accuracy ) ) ]
loVal = vls[0]
while ( batchSize <= maxBatch ):
for batchX, batchY in genBatch( trainX, labels, batchSize, imgSize = imgSize ):
sess.run( [training, extraOps], feed_dict = { X : batchX, y : batchY, trn : True } )
step += 1
if ( step % 25 == 0 ):
valLoss = batchEval( X, y, valX, labels, batchSize, loss )
valAcc = batchEval( X, y, valX, labels, batchSize, accuracy )
trainLoss = loss.eval( feed_dict = { X : batchX, y : batchY } )
trAcc = accuracy.eval( feed_dict = { X : batchX, y : batchY } )
tls.append( histDtype( trainLoss ) )
vls.append( histDtype( valLoss ) )
tas.append( histDtype( trAcc ) )
vas.append( histDtype( valAcc ) )
print( ("Step {0}:\n "\
"valLoss: {1:8.6f}, "\
"trainLoss: {2:8.6f}, "\
"trAcc: {3:5.4f}, "\
"valAcc: {4:5.4f}, "\
"patience: {5:>2d}").format( step, valLoss, trainLoss,
trAcc, valAcc, patience ) )
if ( valLoss < loVal ):
loVal = valLoss
patience = 0
if (saveModel):
saver.save( sess, "./best/dogClass-best.ckpt" )
elif ( step > 500 and valLoss >= loVal ):
patience += 1
if ( patience >= 10 ):
batchSize = 2 * batchSize
patience = 0
print( "\n\nbatchSize =", batchSize, "\n\n" )
endTime = time.time()
print( "Training time: {0:3.2f}h".format( (endTime - startTime) /3600.0 ) )
return ( np.array(loVal), np.array(tls), np.array(vls), np.array(tas), np.array(vas) )
|
[
"tensorflow.get_collection",
"tensorflow.reset_default_graph",
"tensorflow.layers.max_pooling2d",
"tensorflow.layers.batch_normalization",
"tensorflow.nn.softmax",
"tensorflow.nn.elu",
"tensorflow.placeholder_with_default",
"tensorflow.concat",
"tensorflow.placeholder",
"tensorflow.cast",
"dogFunctions.genData",
"tensorflow.name_scope",
"tensorflow.nn.in_top_k",
"tensorflow.summary.scalar",
"tensorflow.global_variables_initializer",
"tensorflow.train.Saver",
"tensorflow.layers.dropout",
"tensorflow.layers.flatten",
"tensorflow.reduce_mean",
"tensorflow.Session",
"tensorflow.layers.conv2d",
"dogFunctions.genBatch",
"tensorflow.variance_scaling_initializer",
"tensorflow.layers.dense",
"time.time",
"numpy.array",
"tensorflow.train.AdamOptimizer",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits"
] |
[((319, 352), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {}), '()\n', (350, 352), True, 'import tensorflow as tf\n'), ((1017, 1050), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {}), '()\n', (1048, 1050), True, 'import tensorflow as tf\n'), ((3236, 3269), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {}), '()\n', (3267, 3269), True, 'import tensorflow as tf\n'), ((6616, 6640), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (6638, 6640), True, 'import tensorflow as tf\n'), ((6650, 6721), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, imgSize, imgSize, 3)', 'name': '"""X"""'}), "(tf.float32, shape=(None, imgSize, imgSize, 3), name='X')\n", (6664, 6721), True, 'import tensorflow as tf\n'), ((6734, 6780), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': 'None', 'name': '"""y"""'}), "(tf.int32, shape=None, name='y')\n", (6748, 6780), True, 'import tensorflow as tf\n'), ((6797, 6853), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(False)'], {'shape': '()', 'name': '"""trn"""'}), "(False, shape=(), name='trn')\n", (6824, 6853), True, 'import tensorflow as tf\n'), ((6984, 7026), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), '(tf.GraphKeys.UPDATE_OPS)\n', (7001, 7026), True, 'import tensorflow as tf\n'), ((7133, 7144), 'time.time', 'time.time', ([], {}), '()\n', (7142, 7144), False, 'import time\n'), ((9541, 9552), 'time.time', 'time.time', ([], {}), '()\n', (9550, 9552), False, 'import time\n'), ((363, 396), 'tensorflow.name_scope', 'tf.name_scope', (['"""ConvolutionBlock"""'], {}), "('ConvolutionBlock')\n", (376, 396), True, 'import tensorflow as tf\n'), ((414, 533), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['X'], {'filters': 'nFilters', 'kernel_size': 'kernelSize', 'strides': '(1)', 'padding': '"""same"""', 'kernel_initializer': 'heInit'}), "(X, filters=nFilters, kernel_size=kernelSize, strides=1,\n padding='same', kernel_initializer=heInit)\n", (430, 533), True, 'import tensorflow as tf\n'), ((590, 678), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', (['conv'], {'pool_size': '(2)', 'strides': '(2)', 'padding': '"""valid"""', 'name': '"""pool"""'}), "(conv, pool_size=2, strides=2, padding='valid', name\n ='pool')\n", (613, 678), True, 'import tensorflow as tf\n'), ((737, 800), 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', (['pool'], {'training': 'trn', 'momentum': 'bnm'}), '(pool, training=trn, momentum=bnm)\n', (766, 800), True, 'import tensorflow as tf\n'), ((823, 836), 'tensorflow.nn.elu', 'tf.nn.elu', (['bn'], {}), '(bn)\n', (832, 836), True, 'import tensorflow as tf\n'), ((1103, 1134), 'tensorflow.name_scope', 'tf.name_scope', (['"""inceptionBlock"""'], {}), "('inceptionBlock')\n", (1116, 1134), True, 'import tensorflow as tf\n'), ((1154, 1286), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['X'], {'filters': 'nPath1', 'kernel_size': '(1)', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.relu', 'kernel_initializer': 'heInit'}), "(X, filters=nPath1, kernel_size=1, strides=1, padding=\n 'same', activation=tf.nn.relu, kernel_initializer=heInit)\n", (1170, 1286), True, 'import tensorflow as tf\n'), ((1381, 1514), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['X'], {'filters': 'nPath2_1', 'kernel_size': '(1)', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.elu', 'kernel_initializer': 'heInit'}), "(X, filters=nPath2_1, kernel_size=1, strides=1, padding=\n 'same', activation=tf.nn.elu, kernel_initializer=heInit)\n", (1397, 1514), True, 'import tensorflow as tf\n'), ((1610, 1745), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['in2'], {'filters': 'nPath2_2', 'kernel_size': '(3)', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.elu', 'kernel_initializer': 'heInit'}), "(in2, filters=nPath2_2, kernel_size=3, strides=1, padding=\n 'same', activation=tf.nn.elu, kernel_initializer=heInit)\n", (1626, 1745), True, 'import tensorflow as tf\n'), ((1840, 1973), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['X'], {'filters': 'nPath3_1', 'kernel_size': '(1)', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.elu', 'kernel_initializer': 'heInit'}), "(X, filters=nPath3_1, kernel_size=1, strides=1, padding=\n 'same', activation=tf.nn.elu, kernel_initializer=heInit)\n", (1856, 1973), True, 'import tensorflow as tf\n'), ((2069, 2204), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['in3'], {'filters': 'nPath3_2', 'kernel_size': '(5)', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.elu', 'kernel_initializer': 'heInit'}), "(in3, filters=nPath3_2, kernel_size=5, strides=1, padding=\n 'same', activation=tf.nn.elu, kernel_initializer=heInit)\n", (2085, 2204), True, 'import tensorflow as tf\n'), ((2299, 2378), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', (['X'], {'pool_size': '(2)', 'strides': '(1)', 'padding': '"""same"""', 'name': '"""p4.1"""'}), "(X, pool_size=2, strides=1, padding='same', name='p4.1')\n", (2322, 2378), True, 'import tensorflow as tf\n'), ((2442, 2575), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['in4'], {'filters': 'nPath4', 'kernel_size': '(1)', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.elu', 'kernel_initializer': 'heInit'}), "(in4, filters=nPath4, kernel_size=1, strides=1, padding=\n 'same', activation=tf.nn.elu, kernel_initializer=heInit)\n", (2458, 2575), True, 'import tensorflow as tf\n'), ((2670, 2717), 'tensorflow.concat', 'tf.concat', (['[path1, path2, path3, path4]'], {'axis': '(3)'}), '([path1, path2, path3, path4], axis=3)\n', (2679, 2717), True, 'import tensorflow as tf\n'), ((2739, 2848), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['concat'], {'filters': 'c', 'kernel_size': '(1)', 'strides': '(1)', 'padding': '"""same"""', 'kernel_initializer': 'heInit'}), "(concat, filters=c, kernel_size=1, strides=1, padding=\n 'same', kernel_initializer=heInit)\n", (2755, 2848), True, 'import tensorflow as tf\n'), ((2904, 2972), 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', (['(merge + X)'], {'training': 'trn', 'momentum': 'bnm'}), '(merge + X, training=trn, momentum=bnm)\n', (2933, 2972), True, 'import tensorflow as tf\n'), ((2995, 3008), 'tensorflow.nn.elu', 'tf.nn.elu', (['bn'], {}), '(bn)\n', (3004, 3008), True, 'import tensorflow as tf\n'), ((3280, 3300), 'tensorflow.name_scope', 'tf.name_scope', (['"""cnn"""'], {}), "('cnn')\n", (3293, 3300), True, 'import tensorflow as tf\n'), ((4320, 4348), 'tensorflow.layers.flatten', 'tf.layers.flatten', (['incept5_2'], {}), '(incept5_2)\n', (4337, 4348), True, 'import tensorflow as tf\n'), ((4371, 4418), 'tensorflow.layers.dropout', 'tf.layers.dropout', (['flat', 'dropProb'], {'training': 'trn'}), '(flat, dropProb, training=trn)\n', (4388, 4418), True, 'import tensorflow as tf\n'), ((4438, 4534), 'tensorflow.layers.dense', 'tf.layers.dense', (['dropout1', '(1024)'], {'name': '"""fc1"""', 'kernel_initializer': 'heInit', 'activation': 'tf.nn.elu'}), "(dropout1, 1024, name='fc1', kernel_initializer=heInit,\n activation=tf.nn.elu)\n", (4453, 4534), True, 'import tensorflow as tf\n'), ((4589, 4635), 'tensorflow.layers.dropout', 'tf.layers.dropout', (['fc1', 'dropProb'], {'training': 'trn'}), '(fc1, dropProb, training=trn)\n', (4606, 4635), True, 'import tensorflow as tf\n'), ((4655, 4751), 'tensorflow.layers.dense', 'tf.layers.dense', (['dropout2', '(1024)'], {'name': '"""fc2"""', 'kernel_initializer': 'heInit', 'activation': 'tf.nn.elu'}), "(dropout2, 1024, name='fc2', kernel_initializer=heInit,\n activation=tf.nn.elu)\n", (4670, 4751), True, 'import tensorflow as tf\n'), ((4806, 4852), 'tensorflow.layers.dropout', 'tf.layers.dropout', (['fc2', 'dropProb'], {'training': 'trn'}), '(fc2, dropProb, training=trn)\n', (4823, 4852), True, 'import tensorflow as tf\n'), ((4875, 4947), 'tensorflow.layers.dense', 'tf.layers.dense', (['dropout3', '(120)'], {'name': '"""output"""', 'kernel_initializer': 'heInit'}), "(dropout3, 120, name='output', kernel_initializer=heInit)\n", (4890, 4947), True, 'import tensorflow as tf\n'), ((4973, 4994), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (4986, 4994), True, 'import tensorflow as tf\n'), ((5007, 5028), 'tensorflow.name_scope', 'tf.name_scope', (['"""loss"""'], {}), "('loss')\n", (5020, 5028), True, 'import tensorflow as tf\n'), ((5049, 5120), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'y', 'logits': 'logits'}), '(labels=y, logits=logits)\n', (5095, 5120), True, 'import tensorflow as tf\n'), ((5141, 5178), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['crossEnt'], {'name': '"""loss"""'}), "(crossEnt, name='loss')\n", (5155, 5178), True, 'import tensorflow as tf\n'), ((5193, 5214), 'tensorflow.name_scope', 'tf.name_scope', (['"""eval"""'], {}), "('eval')\n", (5206, 5214), True, 'import tensorflow as tf\n'), ((5234, 5262), 'tensorflow.nn.in_top_k', 'tf.nn.in_top_k', (['logits', 'y', '(1)'], {}), '(logits, y, 1)\n', (5248, 5262), True, 'import tensorflow as tf\n'), ((5339, 5361), 'tensorflow.name_scope', 'tf.name_scope', (['"""train"""'], {}), "('train')\n", (5352, 5361), True, 'import tensorflow as tf\n'), ((5525, 5601), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'alpha', 'beta1': 'b1', 'beta2': 'b2', 'epsilon': 'eps'}), '(learning_rate=alpha, beta1=b1, beta2=b2, epsilon=eps)\n', (5547, 5601), True, 'import tensorflow as tf\n'), ((5714, 5753), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""crossEntropy"""', 'loss'], {}), "('crossEntropy', loss)\n", (5731, 5753), True, 'import tensorflow as tf\n'), ((5764, 5788), 'tensorflow.name_scope', 'tf.name_scope', (['"""utility"""'], {}), "('utility')\n", (5777, 5788), True, 'import tensorflow as tf\n'), ((5805, 5838), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (5836, 5838), True, 'import tensorflow as tf\n'), ((5855, 5871), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (5869, 5871), True, 'import tensorflow as tf\n'), ((6101, 6155), 'dogFunctions.genData', 'genData', (['allX[start:start + batchSize]', 'allY'], {'size': '(200)'}), '(allX[start:start + batchSize], allY, size=200)\n', (6108, 6155), False, 'from dogFunctions import genData, genBatch\n'), ((7155, 7167), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (7165, 7167), True, 'import tensorflow as tf\n'), ((9647, 9662), 'numpy.array', 'np.array', (['loVal'], {}), '(loVal)\n', (9655, 9662), True, 'import numpy as np\n'), ((9664, 9677), 'numpy.array', 'np.array', (['tls'], {}), '(tls)\n', (9672, 9677), True, 'import numpy as np\n'), ((9679, 9692), 'numpy.array', 'np.array', (['vls'], {}), '(vls)\n', (9687, 9692), True, 'import numpy as np\n'), ((9694, 9707), 'numpy.array', 'np.array', (['tas'], {}), '(tas)\n', (9702, 9707), True, 'import numpy as np\n'), ((9709, 9722), 'numpy.array', 'np.array', (['vas'], {}), '(vas)\n', (9717, 9722), True, 'import numpy as np\n'), ((5298, 5326), 'tensorflow.cast', 'tf.cast', (['correct', 'tf.float32'], {}), '(correct, tf.float32)\n', (5305, 5326), True, 'import tensorflow as tf\n'), ((7750, 7802), 'dogFunctions.genBatch', 'genBatch', (['trainX', 'labels', 'batchSize'], {'imgSize': 'imgSize'}), '(trainX, labels, batchSize, imgSize=imgSize)\n', (7758, 7802), False, 'from dogFunctions import genData, genBatch\n')]
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__all__ = ["Summary"]
import fitsio
import numpy as np
try:
import matplotlib.pyplot as pl
except ImportError:
pl = None
else:
from matplotlib.ticker import MaxNLocator
from matplotlib.backends.backend_pdf import PdfPages
from ..pipeline import Pipeline
class Summary(Pipeline):
query_parameters = dict(
summary_file=(None, True),
signals=([], False),
nboot=(400, False),
)
def __init__(self, *args, **kwargs):
if pl is None:
raise ImportError("matplotlib is required")
kwargs["cache"] = kwargs.pop("cache", False)
super(Summary, self).__init__(*args, **kwargs)
def get_result(self, query, parent_response):
from matplotlib import rcParams
rcParams["text.usetex"] = True
rcParams["font.size"] = 11.
epic = parent_response.epic
tpf = fitsio.read(parent_response.target_pixel_file)
lc_data = fitsio.read(query["light_curve_file"])
x = np.all(lc_data["flux"], axis=1)
i = np.arange(len(x))[np.isfinite(x)][-1]
# Get the light curve object.
lc = parent_response.model_light_curves[0]
fp_model = parent_response.fp_model
# Loop over signals, compute the mean model, and the centroid offsets.
print("Computing centroid offsets...")
off = np.empty(len(query["signals"]))
off_boot = np.empty((len(query["signals"]), query["nboot"]))
model = np.zeros_like(lc.time)
for i, row in enumerate(query["signals"]):
p, t0, d, tau = (row[k] for k in ["period", "t0", "depth",
"duration"])
hp = 0.5 * p
m = np.abs((lc.time - t0 + hp) % p - hp) < 0.5*tau
model[m] -= d
# Compute the centroid offsets.
off[i] = fp_model.compute_offsets(p, t0, tau)
for j in range(query["nboot"]):
x = np.random.uniform(0, p)
off_boot[i, j] = fp_model.compute_offsets(p, x, tau)
# Make the prediction.
t = lc.time
f = lc.flux - lc.predict(lc.flux - model)
# Dimensions.
full_h = 0.97 / 6
vspace_b, vspace_t = 0.2 * full_h, 0.1 * full_h
inner_h = full_h - vspace_t - vspace_b
full_w = 0.5
hspace_l, hspace_r = 0.15 * full_w, 0.05 * full_w
inner_w = full_w - hspace_l - hspace_r
label_dict = dict(xy=(0, 0), xycoords="axes fraction",
xytext=(6, 6), textcoords="offset points",
ha="left", va="bottom")
with PdfPages(query["summary_file"]) as pdf:
# Initialize the figure.
fig = pl.figure(figsize=(9, 12))
# Make a figure for every signal.
colors = "grb"
for ntransit, (row, color) in enumerate(zip(query["signals"],
colors)):
fig.clf()
# Plot the full light curve.
ax = pl.axes([hspace_l, 5. * full_h + vspace_b,
2*inner_w + hspace_l + hspace_r, inner_h])
ax.plot(t, f, ".k", rasterized=True)
ax.set_title((r"EPIC {0} \#{1} --- period: {2:.3f} d, "
"depth: {3:.3f} ppt").format(
epic.id,
ntransit + 1,
row["period"],
row["depth"],
))
# Plot the transit locations.
for mod, c in zip(query["signals"], colors):
p, t0 = (mod[k] for k in ["period", "t0"])
while True:
ax.axvline(t0, color=c, lw=1.5, alpha=0.5)
t0 += p
if t0 > t.max():
break
# Format the full light curve plot.
ax.set_xlim(t.min(), t.max())
ax.set_ylabel("rel. flux [ppt]")
ax.set_xlabel("time [days]")
ax.yaxis.set_major_locator(MaxNLocator(5))
ylim = ax.get_ylim()
# Compute the folded times.
p, t0, depth = (row[k] for k in ["period", "t0", "depth"])
hp = 0.5 * p
t_fold = (t - t0 + hp) % p - hp
# Plot the zoomed folded light curve.
ax = pl.axes([hspace_l, 4. * full_h + vspace_b, inner_w,
inner_h])
ax.plot(t_fold, f, ".k", rasterized=True)
ax.axvline(0, color=color, lw=1.5, alpha=0.5)
ax.annotate("phased (zoom)", **label_dict)
ax.set_xlim(-0.7, 0.7)
ax.set_ylim(ylim)
ax.set_ylabel("rel. flux [ppt]")
ax.set_xlabel("time since transit [days]")
ax.yaxis.set_major_locator(MaxNLocator(5))
# Plot the folded light curve.
ax = pl.axes([hspace_l, 3. * full_h + vspace_b, inner_w,
inner_h])
ax.plot(t_fold, f, ".k", rasterized=True)
ax.axvline(0, color=color, lw=1.5, alpha=0.5)
ax.annotate("phased", **label_dict)
ax.set_xlim(-1.7, 1.7)
ax.set_ylim(ylim)
ax.set_ylabel("rel. flux [ppt]")
ax.set_xlabel("time since transit [days]")
ax.yaxis.set_major_locator(MaxNLocator(5))
# Plot the secondary.
ax = pl.axes([hspace_l, 2. * full_h + vspace_b, inner_w,
inner_h])
t_fold_2 = (t - t0) % p - hp
ax.plot(t_fold_2, f, ".k", rasterized=True)
ax.axvline(0, color=color, lw=1.5, alpha=0.5)
ax.annotate("phased secondary", **label_dict)
ax.set_xlim(-1.7, 1.7)
ax.set_ylim(ylim)
ax.set_ylabel("rel. flux [ppt]")
ax.set_xlabel("time since secondary [days]")
ax.yaxis.set_major_locator(MaxNLocator(5))
# Plot the stacked transits.
ax = pl.axes([full_w + hspace_l, 2. * full_h + vspace_b,
inner_w,
3 * inner_h + 2 * vspace_b + 2 * vspace_t])
num = ((t - t0 - hp) // p).astype(int)
num -= min(num)
offset = 2 * depth
for n in set(num):
m = (num == n) & (np.abs(t_fold) < 1.7)
c = "rb"[n % 2]
ax.plot(t_fold[m], f[m] + offset * n, c)
ax.axhline(offset * n, color="k", linestyle="dashed")
ax.axvline(0, color="k", lw=1.5, alpha=0.5)
ax.set_yticklabels([])
ax.set_ylim(-offset, (max(num) + 0.5) * offset)
ax.set_xlim(-1.7, 1.7)
ax.set_xlabel("time since transit [days]")
# Plot the tpf.
ax = pl.axes([hspace_l, vspace_b, inner_w,
2 * inner_h + vspace_b + vspace_t])
img = tpf["FLUX"][i].T
limg = np.nan + np.zeros_like(img)
m = np.isfinite(img) & (img > 0)
limg[m] = np.log(img[m])
ax.imshow(-limg, cmap="gray", interpolation="nearest")
ax.annotate("log(frame)", **label_dict)
ax.set_xlim(-0.5, img.shape[1] - 0.5)
ax.set_ylim(-0.5, img.shape[0] - 0.5)
ax.set_xticklabels([])
ax.set_yticklabels([])
# Plot the centroid offsets.
ax = pl.axes([full_w + hspace_l, vspace_b + full_h, inner_w,
inner_h])
bins = np.linspace(0, off_boot[ntransit].max(), 12)
ax.hist(off_boot[ntransit], bins, histtype="step", color="k")
ax.axvline(off[ntransit], color=color, lw=1.5, alpha=0.5)
ax.set_yticklabels([])
ax.set_xlabel("centroid offset [pix]")
# Plot the even/odd depth.
ax = pl.axes([full_w + hspace_l, vspace_b, inner_w,
inner_h])
mu, std = fp_model.compute_odd_even(row["period"], row["t0"],
row["duration"])
ax.errorbar(mu, range(2), xerr=std, fmt="ok", capsize=0)
ax.set_yticklabels([])
ax.set_xlabel("even/odd depth [ppt]")
ax.set_ylim(-0.5, 1.5)
pdf.savefig(fig)
pl.close(fig)
return parent_response
|
[
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.random.uniform",
"numpy.zeros_like",
"numpy.abs",
"numpy.log",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.close",
"matplotlib.ticker.MaxNLocator",
"numpy.isfinite",
"fitsio.read",
"matplotlib.pyplot.figure",
"numpy.all"
] |
[((967, 1013), 'fitsio.read', 'fitsio.read', (['parent_response.target_pixel_file'], {}), '(parent_response.target_pixel_file)\n', (978, 1013), False, 'import fitsio\n'), ((1032, 1070), 'fitsio.read', 'fitsio.read', (["query['light_curve_file']"], {}), "(query['light_curve_file'])\n", (1043, 1070), False, 'import fitsio\n'), ((1083, 1114), 'numpy.all', 'np.all', (["lc_data['flux']"], {'axis': '(1)'}), "(lc_data['flux'], axis=1)\n", (1089, 1114), True, 'import numpy as np\n'), ((1558, 1580), 'numpy.zeros_like', 'np.zeros_like', (['lc.time'], {}), '(lc.time)\n', (1571, 1580), True, 'import numpy as np\n'), ((8852, 8865), 'matplotlib.pyplot.close', 'pl.close', (['fig'], {}), '(fig)\n', (8860, 8865), True, 'import matplotlib.pyplot as pl\n'), ((2713, 2744), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (["query['summary_file']"], {}), "(query['summary_file'])\n", (2721, 2744), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((2808, 2834), 'matplotlib.pyplot.figure', 'pl.figure', ([], {'figsize': '(9, 12)'}), '(figsize=(9, 12))\n', (2817, 2834), True, 'import matplotlib.pyplot as pl\n'), ((1145, 1159), 'numpy.isfinite', 'np.isfinite', (['x'], {}), '(x)\n', (1156, 1159), True, 'import numpy as np\n'), ((1803, 1839), 'numpy.abs', 'np.abs', (['((lc.time - t0 + hp) % p - hp)'], {}), '((lc.time - t0 + hp) % p - hp)\n', (1809, 1839), True, 'import numpy as np\n'), ((2043, 2066), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'p'], {}), '(0, p)\n', (2060, 2066), True, 'import numpy as np\n'), ((3142, 3234), 'matplotlib.pyplot.axes', 'pl.axes', (['[hspace_l, 5.0 * full_h + vspace_b, 2 * inner_w + hspace_l + hspace_r, inner_h]'], {}), '([hspace_l, 5.0 * full_h + vspace_b, 2 * inner_w + hspace_l +\n hspace_r, inner_h])\n', (3149, 3234), True, 'import matplotlib.pyplot as pl\n'), ((4589, 4651), 'matplotlib.pyplot.axes', 'pl.axes', (['[hspace_l, 4.0 * full_h + vspace_b, inner_w, inner_h]'], {}), '([hspace_l, 4.0 * full_h + vspace_b, inner_w, inner_h])\n', (4596, 4651), True, 'import matplotlib.pyplot as pl\n'), ((5169, 5231), 'matplotlib.pyplot.axes', 'pl.axes', (['[hspace_l, 3.0 * full_h + vspace_b, inner_w, inner_h]'], {}), '([hspace_l, 3.0 * full_h + vspace_b, inner_w, inner_h])\n', (5176, 5231), True, 'import matplotlib.pyplot as pl\n'), ((5733, 5795), 'matplotlib.pyplot.axes', 'pl.axes', (['[hspace_l, 2.0 * full_h + vspace_b, inner_w, inner_h]'], {}), '([hspace_l, 2.0 * full_h + vspace_b, inner_w, inner_h])\n', (5740, 5795), True, 'import matplotlib.pyplot as pl\n'), ((6363, 6472), 'matplotlib.pyplot.axes', 'pl.axes', (['[full_w + hspace_l, 2.0 * full_h + vspace_b, inner_w, 3 * inner_h + 2 *\n vspace_b + 2 * vspace_t]'], {}), '([full_w + hspace_l, 2.0 * full_h + vspace_b, inner_w, 3 * inner_h +\n 2 * vspace_b + 2 * vspace_t])\n', (6370, 6472), True, 'import matplotlib.pyplot as pl\n'), ((7231, 7304), 'matplotlib.pyplot.axes', 'pl.axes', (['[hspace_l, vspace_b, inner_w, 2 * inner_h + vspace_b + vspace_t]'], {}), '([hspace_l, vspace_b, inner_w, 2 * inner_h + vspace_b + vspace_t])\n', (7238, 7304), True, 'import matplotlib.pyplot as pl\n'), ((7500, 7514), 'numpy.log', 'np.log', (['img[m]'], {}), '(img[m])\n', (7506, 7514), True, 'import numpy as np\n'), ((7895, 7960), 'matplotlib.pyplot.axes', 'pl.axes', (['[full_w + hspace_l, vspace_b + full_h, inner_w, inner_h]'], {}), '([full_w + hspace_l, vspace_b + full_h, inner_w, inner_h])\n', (7902, 7960), True, 'import matplotlib.pyplot as pl\n'), ((8370, 8426), 'matplotlib.pyplot.axes', 'pl.axes', (['[full_w + hspace_l, vspace_b, inner_w, inner_h]'], {}), '([full_w + hspace_l, vspace_b, inner_w, inner_h])\n', (8377, 8426), True, 'import matplotlib.pyplot as pl\n'), ((4263, 4277), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', (['(5)'], {}), '(5)\n', (4274, 4277), False, 'from matplotlib.ticker import MaxNLocator\n'), ((5084, 5098), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', (['(5)'], {}), '(5)\n', (5095, 5098), False, 'from matplotlib.ticker import MaxNLocator\n'), ((5657, 5671), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', (['(5)'], {}), '(5)\n', (5668, 5671), False, 'from matplotlib.ticker import MaxNLocator\n'), ((6280, 6294), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', (['(5)'], {}), '(5)\n', (6291, 6294), False, 'from matplotlib.ticker import MaxNLocator\n'), ((7406, 7424), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (7419, 7424), True, 'import numpy as np\n'), ((7445, 7461), 'numpy.isfinite', 'np.isfinite', (['img'], {}), '(img)\n', (7456, 7461), True, 'import numpy as np\n'), ((6723, 6737), 'numpy.abs', 'np.abs', (['t_fold'], {}), '(t_fold)\n', (6729, 6737), True, 'import numpy as np\n')]
|
from typing import Dict, List, Tuple
from black import main
import matplotlib.pyplot as plt
import numpy as np
def _make_histogram(
reshaped_image: np.ndarray, threshold: float, bins: int = 5
) -> Tuple[List[int], np.ndarray]:
"""Fetch top colors from the histogram
Args:
reshaped_image (np.ndarray): Image reshaped to (N, 3)
n_colors (int, optional): Number of colors. Defaults to 2.
bins (int, optional): Number of bins for the histogram. Defaults to 5.
Returns:
Tuple[List[int], np.ndarray]: Unflatten indexes of top colors and all edges
"""
ranges = (
(np.min(reshaped_image[:, 0]), np.max(reshaped_image[:, 0])),
(np.min(reshaped_image[:, 1]), np.max(reshaped_image[:, 1])),
(np.min(reshaped_image[:, 2]), np.max(reshaped_image[:, 2])),
)
hist, edges = np.histogramdd(reshaped_image, bins=bins, range=ranges)
hist = hist / len(reshaped_image)
best_indexes = np.where(hist.flatten() > threshold)[0]
unflatten_indexes = [np.unravel_index(index, hist.shape) for index in best_indexes]
return unflatten_indexes, np.array(edges)
def _get_best_color_boundaries(
dimension_indexes: Tuple[int, int, int], edges: np.ndarray
) -> List[Tuple[float, float]]:
"""Compute boundaries for each dimension of a main color
Args:
dimension_indexes (int): Indexes of main color (R, G, B)
edges (np.ndarray): Edges from the histogram computation
Returns:
List[float, float]: List of the boundaries of the main color
"""
boundaries = []
for n, dimension_index in enumerate(dimension_indexes):
boundaries.append((edges[n, dimension_index], edges[n, dimension_index + 1]))
return boundaries
def _get_best_colors_boundaries(
indexes: List[Tuple[int, int, int]], edges: np.ndarray
) -> np.ndarray:
"""Compute boundaries of all main colors for all dimension
Args:
indexes (List[Tuple[int, int, int]]): List of color indexes (RGB)
edges (np.ndarray): Edges from the histogram computation
Returns:
np.ndarray: Boundaries of each colors shape (N, 3, 2)
"""
main_colors = []
for index in indexes:
main_colors.append(_get_best_color_boundaries(index, edges))
return np.array(main_colors)
def get_main_colors(
reshaped_image: np.ndarray, threshold: float, bins: int = 5
) -> np.ndarray:
"""Compute best colors
Args:
reshaped_image (np.ndarray): Reshaped image to (N, 3)
n_colors (int, optional): Number of main colors. Defaults to 2.
bins (int, optional): Bin size. Defaults to 5.
Returns:
np.ndarray: Main colors
"""
unflatten_indexes, edges = _make_histogram(reshaped_image, threshold, bins)
main_colors = _get_best_colors_boundaries(unflatten_indexes, edges)
return main_colors
def show_main_colors(main_colors: np.ndarray):
"""Plot main colors
Args:
main_colors (np.ndarray): Main colors
"""
_, axes = plt.subplots(1, len(main_colors), figsize=(15, 2))
for k in range(len(axes)):
axes[k].imshow([[np.mean(main_colors, axis=2)[k] / 256]])
axes[k].set_axis_off()
def compute_masks(main_colors: np.ndarray, image: np.ndarray) -> np.ndarray:
"""Compute masks for main_colors segmentation
Args:
main_colors (np.ndarray): Main colors
image (np.ndarray): Image
Returns:
np.ndarray: Masks
"""
masks = []
for main_color in main_colors:
condition = (image[..., 0] > main_color[0, 0]) & (
image[..., 0] < main_color[0, 1]
)
condition = (
condition
& (image[..., 1] > main_color[1, 0])
& (image[..., 1] < main_color[1, 1])
)
condition = (
condition
& (image[..., 2] > main_color[2, 0])
& (image[..., 2] < main_color[2, 1])
)
masks.append(condition)
return masks
def compute_distributions(
masks: np.ndarray, image: np.ndarray
) -> List[Dict[str, np.ndarray]]:
"""Compute distributions (mean, variance) for each main color
Args:
masks (np.ndarray): Masks of each main color
image (np.ndarray): Image
Returns:
List[Dict[str, np.ndarray]]: Distributions of main colors with
keys mu (for mean) and sigma2 (for variance)
"""
distributions = []
for mask in masks:
sub_image = image[mask]
distributions.append(
dict(
mu=np.mean(sub_image, axis=0),
sigma2=np.var(sub_image, axis=0),
size=len(sub_image),
)
)
return distributions
def show_mask(mask: np.ndarray, image: np.ndarray):
r = np.where(mask, image[..., 0], 255)[..., np.newaxis]
g = np.where(mask, image[..., 1], 255)[..., np.newaxis]
b = np.where(mask, image[..., 2], 255)[..., np.newaxis]
plt.imshow(np.concatenate([r, g, b], axis=-1))
def make_original_partition(image: np.ndarray, main_colors: np.ndarray) -> dict:
"""Generate an initial partition of using euclidian distance with main colors
Args:
image (np.ndarray): Image
main_colors (np.ndarray): Main colors boundaries
Returns:
dict: Initial partition
"""
partition = {k: set() for k in range(len(main_colors))}
reshaped_image = image.reshape(-1, 3)
for n in range(len(reshaped_image)):
pixel = reshaped_image[n]
distances = np.linalg.norm(pixel - np.mean(main_colors, 2), axis=1)
label = np.argmin(distances)
partition[label].add(str(n))
return partition
def segmentation(
image: np.ndarray, params: dict, verbose: bool = True, threshold: float = 0.1
) -> Tuple[List[Dict[str, np.ndarray]], dict]:
"""Run the original segmentation using histogram of colors
Args:
image (np.ndarray): Image
params (dict): Params with key bins (int)
verbose (bool, optional): Verbose. Defaults to True.
threshold (float, optional): Threshold. Defaults to 0.1.
Returns:
Tuple[List[Dict[str, np.ndarray]], dict]: Distributions of main colors
and original partition
"""
if verbose:
print("Computing main colors...")
reshaped_image = image.reshape((-1, 3))
main_colors = get_main_colors(
reshaped_image, bins=params["bins"], threshold=threshold
)
while len(main_colors) == 0:
threshold = threshold * 9 / 10
main_colors = get_main_colors(
reshaped_image, bins=params["bins"], threshold=threshold
)
masks = compute_masks(main_colors, image)
distributions = compute_distributions(masks, image)
original_partition = make_original_partition(image, main_colors)
return distributions, original_partition
|
[
"numpy.histogramdd",
"numpy.unravel_index",
"numpy.argmin",
"numpy.min",
"numpy.where",
"numpy.array",
"numpy.max",
"numpy.mean",
"numpy.var",
"numpy.concatenate"
] |
[((851, 906), 'numpy.histogramdd', 'np.histogramdd', (['reshaped_image'], {'bins': 'bins', 'range': 'ranges'}), '(reshaped_image, bins=bins, range=ranges)\n', (865, 906), True, 'import numpy as np\n'), ((2284, 2305), 'numpy.array', 'np.array', (['main_colors'], {}), '(main_colors)\n', (2292, 2305), True, 'import numpy as np\n'), ((1030, 1065), 'numpy.unravel_index', 'np.unravel_index', (['index', 'hist.shape'], {}), '(index, hist.shape)\n', (1046, 1065), True, 'import numpy as np\n'), ((1123, 1138), 'numpy.array', 'np.array', (['edges'], {}), '(edges)\n', (1131, 1138), True, 'import numpy as np\n'), ((4796, 4830), 'numpy.where', 'np.where', (['mask', 'image[..., 0]', '(255)'], {}), '(mask, image[..., 0], 255)\n', (4804, 4830), True, 'import numpy as np\n'), ((4856, 4890), 'numpy.where', 'np.where', (['mask', 'image[..., 1]', '(255)'], {}), '(mask, image[..., 1], 255)\n', (4864, 4890), True, 'import numpy as np\n'), ((4916, 4950), 'numpy.where', 'np.where', (['mask', 'image[..., 2]', '(255)'], {}), '(mask, image[..., 2], 255)\n', (4924, 4950), True, 'import numpy as np\n'), ((4983, 5017), 'numpy.concatenate', 'np.concatenate', (['[r, g, b]'], {'axis': '(-1)'}), '([r, g, b], axis=-1)\n', (4997, 5017), True, 'import numpy as np\n'), ((5609, 5629), 'numpy.argmin', 'np.argmin', (['distances'], {}), '(distances)\n', (5618, 5629), True, 'import numpy as np\n'), ((626, 654), 'numpy.min', 'np.min', (['reshaped_image[:, 0]'], {}), '(reshaped_image[:, 0])\n', (632, 654), True, 'import numpy as np\n'), ((656, 684), 'numpy.max', 'np.max', (['reshaped_image[:, 0]'], {}), '(reshaped_image[:, 0])\n', (662, 684), True, 'import numpy as np\n'), ((696, 724), 'numpy.min', 'np.min', (['reshaped_image[:, 1]'], {}), '(reshaped_image[:, 1])\n', (702, 724), True, 'import numpy as np\n'), ((726, 754), 'numpy.max', 'np.max', (['reshaped_image[:, 1]'], {}), '(reshaped_image[:, 1])\n', (732, 754), True, 'import numpy as np\n'), ((766, 794), 'numpy.min', 'np.min', (['reshaped_image[:, 2]'], {}), '(reshaped_image[:, 2])\n', (772, 794), True, 'import numpy as np\n'), ((796, 824), 'numpy.max', 'np.max', (['reshaped_image[:, 2]'], {}), '(reshaped_image[:, 2])\n', (802, 824), True, 'import numpy as np\n'), ((5560, 5583), 'numpy.mean', 'np.mean', (['main_colors', '(2)'], {}), '(main_colors, 2)\n', (5567, 5583), True, 'import numpy as np\n'), ((4570, 4596), 'numpy.mean', 'np.mean', (['sub_image'], {'axis': '(0)'}), '(sub_image, axis=0)\n', (4577, 4596), True, 'import numpy as np\n'), ((4621, 4646), 'numpy.var', 'np.var', (['sub_image'], {'axis': '(0)'}), '(sub_image, axis=0)\n', (4627, 4646), True, 'import numpy as np\n'), ((3125, 3153), 'numpy.mean', 'np.mean', (['main_colors'], {'axis': '(2)'}), '(main_colors, axis=2)\n', (3132, 3153), True, 'import numpy as np\n')]
|
import cv2
import numpy as np
img = cv2.imread("imori.jpg").astype(np.float32)
H,W,C=img.shape
#gray scale
b = img[:,:,0].copy()
g = img[:,:,1].copy()
r = img[:,:,2].copy()
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b #0.2126+0.7152+0.0722 = 1
gray = gray.astype(np.uint8)
#filtersize
filtersize=3
pad=filtersize//2
out=np.zeros((H+pad*2,W+pad*2,C),dtype=np.float)
out[pad:pad+H, pad:pad+W] = img.copy().astype(np.float)
#filter
temp=out.copy()
for y in range (H):
for x in range(W):
out[y+pad][x+pad]= np.max(temp[y:y+filtersize, x:x+filtersize])-np.min(temp[y:y+filtersize, x:x+filtersize])
out[out<0]=0
out[out>255]=255
out = out[pad:pad+H, pad:pad+W].astype(np.uint8)
cv2.imwrite("question13.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
[
"cv2.waitKey",
"cv2.imwrite",
"cv2.destroyAllWindows",
"numpy.zeros",
"cv2.imread",
"numpy.max",
"numpy.min",
"cv2.imshow"
] |
[((323, 378), 'numpy.zeros', 'np.zeros', (['(H + pad * 2, W + pad * 2, C)'], {'dtype': 'np.float'}), '((H + pad * 2, W + pad * 2, C), dtype=np.float)\n', (331, 378), True, 'import numpy as np\n'), ((695, 729), 'cv2.imwrite', 'cv2.imwrite', (['"""question13.jpg"""', 'out'], {}), "('question13.jpg', out)\n", (706, 729), False, 'import cv2\n'), ((730, 755), 'cv2.imshow', 'cv2.imshow', (['"""result"""', 'out'], {}), "('result', out)\n", (740, 755), False, 'import cv2\n'), ((756, 770), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (767, 770), False, 'import cv2\n'), ((771, 794), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (792, 794), False, 'import cv2\n'), ((36, 59), 'cv2.imread', 'cv2.imread', (['"""imori.jpg"""'], {}), "('imori.jpg')\n", (46, 59), False, 'import cv2\n'), ((524, 572), 'numpy.max', 'np.max', (['temp[y:y + filtersize, x:x + filtersize]'], {}), '(temp[y:y + filtersize, x:x + filtersize])\n', (530, 572), True, 'import numpy as np\n'), ((569, 617), 'numpy.min', 'np.min', (['temp[y:y + filtersize, x:x + filtersize]'], {}), '(temp[y:y + filtersize, x:x + filtersize])\n', (575, 617), True, 'import numpy as np\n')]
|
'''
interactive plot/ graphical user interface to select an area for segmentation, and appropriate thresholds.
'''
from matplotlib.widgets import PolygonSelector, Button,Slider
from matplotlib import path
from matplotlib.image import AxesImage
from matplotlib.backend_bases import MouseEvent
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import filedialog
import numpy as np
import warnings
import os
from segementation_bugs import *
def assert_mask(mask):
'''
hecks if mask exists.Tries to load from current working directory if it doesn't
and prints warning messages.
:param mask: np.darray representing the mask of the dish area
:return: the mask and a boolean if the the mask could be loaded
'''
if not isinstance(mask, np.ndarray):
print("no current mask for dish area found")
path_mask=os.path.join(os.getcwd(),"mask.npy")
if os.path.exists(path_mask): # checks if mask can be loaded from current directory
mask=np.load(path_mask)
print("load mask from "+ path_mask)
return mask,True
else:
warnings.warn("couldn't find current selection for the dish area"
"or load a mask file")
return 0, False
else:
return mask, True
def set_button(pos,disp_name,fun,font_size=10):
'''
helper function to set buttons, returns the axes object of the button and the widget
object
:param pos: x,y postion of buttom axes left corner and length and hight dx,dy as a list
:param disp_name: string of the button name
:param fun: function that is executed on button click
:return: ax_button: the axes of the button
button_widget: the button object
'''
ax_button = plt.axes(pos)
ax_button.xaxis.set_ticks_position('none')
ax_button.yaxis.set_ticks_position('none')
ax_button.set_xticks([])
ax_button.set_yticks([])
button_widget = Button(ax_button ,disp_name )
button_widget.on_clicked(fun)
button_widget.label.set_fontsize(font_size)
return ax_button,button_widget
def ask_file(event):
'''
opens a tk inter file browser. The selected file is loaded as an image to the window.
Additionally the filtered image is calculated immediately.
:param event:
:return:
'''
# opens dialog box for image selection
global fig, ax, image, pix, image_f, im, lasso2
root = tk.Tk()
root.withdraw() #
file_path = filedialog.askopenfile()
# loading the image
image = plt.imread(file_path.name)
# grey scale conversion, one could use some wights here
if len(image.shape) == 3:
#image=image[:,:,0]
image = np.mean(image, axis=2)
# filtering image
image_f=normalize(image,lb=0.1,ub=99.9) # normalization to a range from 0 to 1
image_f=gaussian(image_f,sigma=s1)-gaussian(image_f,sigma=s2) # difference of gaussian filtering
# displaying unfiltered image first
im=ax.imshow(image) # you can choose a diffrent color map here
fig.canvas.draw_idle() #plot update
# coordinate of the image, later needed for selction
pixx = np.arange(image.shape[0])
pixy = np.arange(image.shape[1])
xv, yv = np.meshgrid(pixy, pixx)
pix = np.vstack((xv.flatten(), yv.flatten())).T
# (re)initialize polygon selector
#lasso2.disconnect_events() seems to have some kind of bug...
lasso2 = PolygonSelector(ax, select_mask) # selector on bf image
def select_mask(verts):
'''
Constructs and displays the mask of the dish area from the nodes slected by the polygone selector.
:param verts: vertices from the polygone selector
:return:
'''
global mask,im_mask,mask_show,verts_out
if len(verts)==0:
return # workaround when deleting old mask
if not isinstance(pix,np.ndarray): #error handling if pix is not caclulated (e.g when no image is selected)
warnings.warn("could not find coordinates of an image\n"
"make sure to select and display an image file")
return
verts_out = verts # vertices of curve drawn by lasso selector
p = path.Path(verts)
#retrieving mask
ind = p.contains_points(pix, radius=1) # all points inside of the selected area
mask = np.reshape(np.array(ind), image.shape)
# displaying the mask overlayed on image
mask_show=np.zeros(mask.shape)+np.nan
mask_show[mask]=1
im_mask=ax.imshow(mask_show,alpha=0.2)
fig.canvas.draw_idle()
# deleting the selected mask with right click
def delete_mask(event):
'''
deletes the mask of the dish area or the mask for bug selection if you click with the right mouse button
:param event:
:return:
'''
global mask,im_mask,lasso2,mask_show,im_mask_bugs
# deleting mask of dish area if exists
if event.button==3 and event.inaxes==ax and isinstance(mask,np.ndarray) and isinstance(im_mask,AxesImage) : # only on right click, only if clicked in main axes
# chek if mask is already selected
mask=0 # reset mask
mask_show=0
im_mask.remove() # remove displaying mask
im_mask=0
lasso2._xs = []
lasso2._ys = []
lasso2._draw_polygon() # removes display of old verts
lasso2 = PolygonSelector(ax, select_mask) # reinitalizing the selector
fig.canvas.draw_idle() # plot update
#print('you pressed', event.button, event.xdata, event.ydata)
# deleting mask of bug segemetnation if exists
# only on right click, only if clicked in main axes or in slider axis
if event.button == 3 and isinstance(mask_bugs,np.ndarray) and isinstance(im_mask_bugs,AxesImage) and (event.inaxes==ax or event.inaxes == ax_slider):
im_mask_bugs.remove()#
im_mask_bugs=0
fig.canvas.draw_idle() # plotupdate
def save_mask(event):
'''
saves the mask to the currentworking directors as mask.npy.
:param event:
:return:
'''
## this will autmatically overide
file=os.path.join(os.getcwd(),"mask.npy")
np.save(file,mask)
print("mask saved to " + file)
### button to show filtering (could alos be done automatically
def show_filtered_image(event):
'''
shows the filtered image or the original image. If you press the button once, the
respectively other option appears on the button.
:param event:
:return:
'''
global sfi_button,im_f,im,im_mask,lasso2
# disconnects and stops the lassoselecto
lasso2.disconnect_events()
# showing the filtered image
if sfi_button.label.get_text()=="show filtered\nimage": # checks the text displayed on the button
im.remove()# removing unfiltered image
im_f=ax.imshow(image_f)# showning filterd image
lasso2 = PolygonSelector(ax, select_mask) # reinitalizing the selector
if isinstance(mask_show,np.ndarray): # showing mask if already selected
im_mask=ax.imshow(mask_show, alpha=0.2)
sfi_button.label.set_text("show unfiltered\nimage")
fig.canvas.draw_idle() # plot update
return
# showing the unfilterd image
if sfi_button.label.get_text()=="show unfiltered\nimage": # checks the text displayed on the button
im_f.remove() # removing unfiltered image
im = ax.imshow(image) # showing filterd image
lasso2 = PolygonSelector(ax, select_mask) # reinitalizing the selector
if isinstance(mask_show, np.ndarray): # showing mask if alaready selected
im_mask = ax.imshow(mask_show, alpha=0.2)
sfi_button.label.set_text("show filtered\nimage")
fig.canvas.draw_idle() # plot update
return
def update_segmentation(val): ## note also disables the polygone selctor
'''
Function to perform segmentation adn display the mask. This function is called when the threshold
slider or the show detections button is pressed.
:param val: value of the segmentation threshold
:return:
'''
global txt,ax,mask_bugs,mask,im_mask_bugs,im_mask,segmentation_factor
segmentation_factor=val
if not isinstance(pix, np.ndarray): # check if an image is selected
warnings.warn("could not find coordinates of an image\n"
"make sure to select and display an image file")
return
# checking if disk area mask is selected or can be loaded from the current working directory
mask,mask_bool=assert_mask(mask)
if not mask_bool:
return
# segmentation
mask_bugs,thresh=segementation_sd(image_f,f=segmentation_factor,mask_area=mask) #segemtnation with new values
#updating display
if isinstance(im_mask,AxesImage): # remove other mask from display
im_mask.remove()
im_mask=0
# clearing previous mask of bugs
if isinstance(im_mask_bugs,AxesImage):
im_mask_bugs.remove()
im_mask_bugs=0
# showing the new mask from segmentation
mask_bugs_show=np.zeros(mask_bugs.shape)+np.nan
mask_bugs_show[mask_bugs]=1
im_mask_bugs=ax.imshow(mask_bugs_show,alpha=0.7,cmap=cmap_mask)
# updating the text displaying the formula for the threshold
txt.remove()
txt=plt.text(0, 1.5,"thresh: %.2f=mean + %.2f * sd"%(np.round(thresh,2),np.round(val,2))
,transform = ax_slider_tresh.transAxes) ### get better text position
# disabeling the lassoselector
lasso2.set_visible(False)
lasso2.set_active(False)
fig.canvas.draw_idle() # plot update
def show_dections(event):
'''
showing the detections. Every bug is displayed as a dot. This function is called when the
"show detections" button is pressed or when the "min size" slider is used
:param event:
:return:
'''
global txt,ax,mask_bugs,mask,im_mask_bugs,im_mask,detections,minsize
#retreiving the value of minsize if the slider is used
if type(event)!=MouseEvent:
minsize=event
event_cp=event
if not isinstance(pix, np.ndarray): # check if image is selected
warnings.warn("could not find coordinates of an image\n"
"make sure to select and display an image file")
return
# checking if disk area mask is selected or can be loaded from the current working directory
mask,mask_bool=assert_mask(mask)
if not mask_bool:
return
# checking if segmentation has already been performed.
# if not segmentation is performed with the default or the latest selected value of the
# segmentation factor
if not isinstance(mask_bugs,AxesImage):
warnings.warn("clouldnt find mask from segmentation, performing segmentation"
"with factor %f"%segmentation_factor)
# segmentation
mask_bugs, thresh = segementation_sd(image_f, f=segmentation_factor, mask_area=mask) # segemtnation with new values
# updating segmentation mask
mask_bugs_show=np.zeros(mask_bugs.shape)+np.nan
mask_bugs_show[mask_bugs]=1
im_mask_bugs=ax.imshow(mask_bugs_show,alpha=0.7,cmap=cmap_mask)
# deleting previous detections:
if isinstance(detections,np.ndarray) or isinstance(detections,list):
for l in ax.lines:
l.remove()#removing all plotted points
for t in ax.texts [1:]:
t.remove() # removing all texts except an empty initial one
detections=0 #resetting detections list
# performing detection
detections,labels=detection(mask_bugs, min_size=minsize)
# dsiplaying the new detections with a dot and a number
offset=0.2 # text is moved a bit out of the way
for i,(x,y) in enumerate(detections):
ax.plot(y,x,"o",markersize=3)
ax.text(y,x,str(i))
# disabling the lassoselector
lasso2.set_visible(False)
lasso2.set_active(False)
fig.canvas.draw_idle()
# paramteres for filtering
s1=12
s2=5
##some preset or default values variables; don't change these
pix=0
mask=0
mask_show=0
im_mask=0
im_mask_bugs=0
mask_bugs=0
detections=0
segmentation_factor=5 # default value, you can change this
minsize=0 # default value, you can change this
# custom color map for showing the mask of segmentation
cmap_mask = LinearSegmentedColormap.from_list('mycmap', ["red","white"])
# initializing the interactive window
fig, ax = plt.subplots()
txt=plt.text(0.25,0.15,str("")) # text over sliding bar
plt.subplots_adjust(left=0.25, bottom=0.25)
# adding the open image button to the window
ax_file,file_select=set_button([0.02, 0.5, 0.17, 0.05],'open image',ask_file)
# initialyzing the polygone selector
lasso2 = PolygonSelector(ax, select_mask) #
## adds functionality to delete the mask of segemntation or the dish area on rioght mouse click
delete_mask_event = fig.canvas.mpl_connect('button_press_event', delete_mask)
# buttton so save the mask of the dish area
ax_save_changes,save_changes_button=set_button([0.02, 0.4, 0.17, 0.05],'save mask',save_mask)
# buttton to swithc between the filtered and unfiltered images
ax_sfi, sfi_button = set_button([0.02, 0.15, 0.17, 0.1], "show filtered\nimage",show_filtered_image)
# adding the slider for thresholding
ax_slider_tresh = plt.axes([0.25, 0.1, 0.65, 0.03]) # axis for the slider
slider1= Slider(ax_slider_tresh, 'threshold', 0.5, 30, valinit=5, valstep=0.01) # creates a slider object
slider1.on_changed(update_segmentation) # connects the slider to the segmentation function
# adding the "show detections button
ax_detections, detections_button = set_button([0.02, 0.3,0.17, 0.05], "show detections",show_dections)
# adding the slider for min_size
ax_slider_minsize = plt.axes([0.25, 0.05, 0.65, 0.03]) # axis for the slider
slider2= Slider(ax_slider_minsize, 'min size', 0, 200, valinit=50, valstep=1) # creates a slider object
slider2.on_changed(show_dections) # connects the slider to the show detections function
# showing the entire window
plt.show()
# todo:
# text position when segmenting is off
#bug:rectangel selector seems to get increasingly slower when image is switched multiple times
#(switching by loading new image or by displaying the filtered image
## sidenode, ther is also a "draw event, that might be nice....
# could add afunction to reactivate polygone selector (not really necessary)
|
[
"numpy.load",
"matplotlib.pyplot.axes",
"matplotlib.widgets.Slider",
"numpy.mean",
"numpy.arange",
"matplotlib.widgets.PolygonSelector",
"matplotlib.pyplot.imread",
"numpy.round",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.meshgrid",
"os.path.exists",
"tkinter.filedialog.askopenfile",
"matplotlib.pyplot.subplots",
"tkinter.Tk",
"numpy.save",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots_adjust",
"os.getcwd",
"numpy.zeros",
"matplotlib.widgets.Button",
"matplotlib.path.Path",
"numpy.array",
"warnings.warn"
] |
[((12274, 12335), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (['"""mycmap"""', "['red', 'white']"], {}), "('mycmap', ['red', 'white'])\n", (12307, 12335), False, 'from matplotlib.colors import LinearSegmentedColormap\n'), ((12384, 12398), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (12396, 12398), True, 'import matplotlib.pyplot as plt\n'), ((12455, 12498), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.25)', 'bottom': '(0.25)'}), '(left=0.25, bottom=0.25)\n', (12474, 12498), True, 'import matplotlib.pyplot as plt\n'), ((12670, 12702), 'matplotlib.widgets.PolygonSelector', 'PolygonSelector', (['ax', 'select_mask'], {}), '(ax, select_mask)\n', (12685, 12702), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((13240, 13273), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.25, 0.1, 0.65, 0.03]'], {}), '([0.25, 0.1, 0.65, 0.03])\n', (13248, 13273), True, 'import matplotlib.pyplot as plt\n'), ((13305, 13375), 'matplotlib.widgets.Slider', 'Slider', (['ax_slider_tresh', '"""threshold"""', '(0.5)', '(30)'], {'valinit': '(5)', 'valstep': '(0.01)'}), "(ax_slider_tresh, 'threshold', 0.5, 30, valinit=5, valstep=0.01)\n", (13311, 13375), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((13688, 13722), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.25, 0.05, 0.65, 0.03]'], {}), '([0.25, 0.05, 0.65, 0.03])\n', (13696, 13722), True, 'import matplotlib.pyplot as plt\n'), ((13754, 13822), 'matplotlib.widgets.Slider', 'Slider', (['ax_slider_minsize', '"""min size"""', '(0)', '(200)'], {'valinit': '(50)', 'valstep': '(1)'}), "(ax_slider_minsize, 'min size', 0, 200, valinit=50, valstep=1)\n", (13760, 13822), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((13966, 13976), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13974, 13976), True, 'import matplotlib.pyplot as plt\n'), ((1851, 1864), 'matplotlib.pyplot.axes', 'plt.axes', (['pos'], {}), '(pos)\n', (1859, 1864), True, 'import matplotlib.pyplot as plt\n'), ((2037, 2065), 'matplotlib.widgets.Button', 'Button', (['ax_button', 'disp_name'], {}), '(ax_button, disp_name)\n', (2043, 2065), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((2515, 2522), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (2520, 2522), True, 'import tkinter as tk\n'), ((2561, 2585), 'tkinter.filedialog.askopenfile', 'filedialog.askopenfile', ([], {}), '()\n', (2583, 2585), False, 'from tkinter import filedialog\n'), ((2622, 2648), 'matplotlib.pyplot.imread', 'plt.imread', (['file_path.name'], {}), '(file_path.name)\n', (2632, 2648), True, 'import matplotlib.pyplot as plt\n'), ((3232, 3257), 'numpy.arange', 'np.arange', (['image.shape[0]'], {}), '(image.shape[0])\n', (3241, 3257), True, 'import numpy as np\n'), ((3269, 3294), 'numpy.arange', 'np.arange', (['image.shape[1]'], {}), '(image.shape[1])\n', (3278, 3294), True, 'import numpy as np\n'), ((3308, 3331), 'numpy.meshgrid', 'np.meshgrid', (['pixy', 'pixx'], {}), '(pixy, pixx)\n', (3319, 3331), True, 'import numpy as np\n'), ((3503, 3535), 'matplotlib.widgets.PolygonSelector', 'PolygonSelector', (['ax', 'select_mask'], {}), '(ax, select_mask)\n', (3518, 3535), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((4226, 4242), 'matplotlib.path.Path', 'path.Path', (['verts'], {}), '(verts)\n', (4235, 4242), False, 'from matplotlib import path\n'), ((6141, 6160), 'numpy.save', 'np.save', (['file', 'mask'], {}), '(file, mask)\n', (6148, 6160), True, 'import numpy as np\n'), ((964, 989), 'os.path.exists', 'os.path.exists', (['path_mask'], {}), '(path_mask)\n', (978, 989), False, 'import os\n'), ((2783, 2805), 'numpy.mean', 'np.mean', (['image'], {'axis': '(2)'}), '(image, axis=2)\n', (2790, 2805), True, 'import numpy as np\n'), ((4012, 4127), 'warnings.warn', 'warnings.warn', (['"""could not find coordinates of an image\nmake sure to select and display an image file"""'], {}), '(\n """could not find coordinates of an image\nmake sure to select and display an image file"""\n )\n', (4025, 4127), False, 'import warnings\n'), ((4370, 4383), 'numpy.array', 'np.array', (['ind'], {}), '(ind)\n', (4378, 4383), True, 'import numpy as np\n'), ((4457, 4477), 'numpy.zeros', 'np.zeros', (['mask.shape'], {}), '(mask.shape)\n', (4465, 4477), True, 'import numpy as np\n'), ((5356, 5388), 'matplotlib.widgets.PolygonSelector', 'PolygonSelector', (['ax', 'select_mask'], {}), '(ax, select_mask)\n', (5371, 5388), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((6113, 6124), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6122, 6124), False, 'import os\n'), ((6862, 6894), 'matplotlib.widgets.PolygonSelector', 'PolygonSelector', (['ax', 'select_mask'], {}), '(ax, select_mask)\n', (6877, 6894), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((7440, 7472), 'matplotlib.widgets.PolygonSelector', 'PolygonSelector', (['ax', 'select_mask'], {}), '(ax, select_mask)\n', (7455, 7472), False, 'from matplotlib.widgets import PolygonSelector, Button, Slider\n'), ((8260, 8375), 'warnings.warn', 'warnings.warn', (['"""could not find coordinates of an image\nmake sure to select and display an image file"""'], {}), '(\n """could not find coordinates of an image\nmake sure to select and display an image file"""\n )\n', (8273, 8375), False, 'import warnings\n'), ((9044, 9069), 'numpy.zeros', 'np.zeros', (['mask_bugs.shape'], {}), '(mask_bugs.shape)\n', (9052, 9069), True, 'import numpy as np\n'), ((10100, 10215), 'warnings.warn', 'warnings.warn', (['"""could not find coordinates of an image\nmake sure to select and display an image file"""'], {}), '(\n """could not find coordinates of an image\nmake sure to select and display an image file"""\n )\n', (10113, 10215), False, 'import warnings\n'), ((10645, 10769), 'warnings.warn', 'warnings.warn', (["('clouldnt find mask from segmentation, performing segmentationwith factor %f'\n % segmentation_factor)"], {}), "(\n 'clouldnt find mask from segmentation, performing segmentationwith factor %f'\n % segmentation_factor)\n", (10658, 10769), False, 'import warnings\n'), ((929, 940), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (938, 940), False, 'import os\n'), ((1062, 1080), 'numpy.load', 'np.load', (['path_mask'], {}), '(path_mask)\n', (1069, 1080), True, 'import numpy as np\n'), ((1184, 1274), 'warnings.warn', 'warnings.warn', (['"""couldn\'t find current selection for the dish areaor load a mask file"""'], {}), '(\n "couldn\'t find current selection for the dish areaor load a mask file")\n', (1197, 1274), False, 'import warnings\n'), ((10991, 11016), 'numpy.zeros', 'np.zeros', (['mask_bugs.shape'], {}), '(mask_bugs.shape)\n', (10999, 11016), True, 'import numpy as np\n'), ((9317, 9336), 'numpy.round', 'np.round', (['thresh', '(2)'], {}), '(thresh, 2)\n', (9325, 9336), True, 'import numpy as np\n'), ((9336, 9352), 'numpy.round', 'np.round', (['val', '(2)'], {}), '(val, 2)\n', (9344, 9352), True, 'import numpy as np\n')]
|
from __future__ import division
import time
from Model import Road
from Model import Lane
import numpy as np
import cv2 as cv
from types import NoneType
import numpy as np
import moviepy.editor as mpy
import matplotlib.pyplot as plt
from ImageProcessing.PerspectiveWrapper import PerspectiveWrapper
import tensorflow as tf
from PIL import Image
from glob import glob
from tqdm import tqdm
from get_labels import get_labels
from get_model import get_model
from detect_peaks import detect_peaks
import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tensorflow as tf
from keras import backend as K
K.set_learning_phase(0)
# Set Memory allocation in tf/keras to Growth
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
config.inter_op_parallelism_threads = 4
config.intra_op_parallelism_threads = 4
config.allow_soft_placement = True
config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
sess = tf.compat.v1.Session(config=config)
K.set_session(sess)
class LaneDetectorCNN:
def __init__(self):
# General self.settings for network training and labels (do not change)
self.settings = dict()
self.settings['model'] = 'espnet'
self.settings['shape'] = (640, 480)
self.settings['random_flip'] = True
self.settings['random_crop'] = True
self.settings['epochs'] = 1000
self.settings['batch_size'] = 1
self.settings['learning_rate'] = 0.001
self.settings['weight_decay'] = 0.001
self.settings['labels'] = 'base'
self.settings['labels'] = get_labels(self.settings)
# self.settings for verbosity (with plots)
self.settings['verbose'] = False
# Setting to indicate whether to save input images one by one and create a movie afterwards
self.settings['save'] = False
# Load pretrained self.model
_, self.model, _ = get_model(self.settings)
print(os.getcwd())
self.model.load_weights('LaneDetectionOld/espnet_base_0.7669_0.7630.hdf5', by_name=True)
self.model._make_predict_function()
self.weights = self.model.get_weights()
weights_array = np.array(self.weights)
for i in range(len(self.weights)):
weights_array[i] = np.float16(weights_array[i])
self.weights = weights_array.tolist()
self.model.set_weights(self.weights)
# sess = tf.Session()
# sess.run(tf.global_variables_initializer())
# self.default_graph = tf.get_default_graph()
# self.default_graph.finalize()
def get_road(self, img):
lanes = self.get_lanes(img)
road = Road(lanes)
return road
def get_lanes(self, img):
return lanes
def detect_lanes(self, img):
image_w = img.shape[1]
image_h = img.shape[0]
# Load original image
image = np.array(img).astype(np.float32) / 255
# Resize it to network dimensions
image_small = cv.resize(image, (640, 480), interpolation=cv.INTER_LINEAR)
# with self.default_graph.as_default():
# Predict
image_pred_small = self.model.predict(np.expand_dims(image_small, axis=0), batch_size=len(image_small))[0]
# Resize prediction back to original size
image_pred = cv.resize(image_pred_small, (image_w, image_h), interpolation=cv.INTER_LINEAR)
# Get RGB image from label predictions
image_seg = y_label_to_rgb(self.settings, image_pred.argmax(axis=-1).astype(np.int))
# Transform image to flat representation
image_seg_flat = car_to_bird(image_seg)
# Extract lane markings
image_seg_flat_lane_markings = np.zeros((image_seg_flat.shape[:2]), dtype=np.uint8)
image_seg_flat_lane_markings[np.where((image_seg_flat == [255, 255, 255]).all(axis=2))] = [255]
# Extract road information
image_seg_flat_lane_edge_road = np.copy(image_seg_flat_lane_markings)
image_seg_flat_lane_edge_road[np.where((image_seg_flat == [128, 64, 128]).all(axis=2))] = [255]
image_seg_flat_lane_edge_road[np.where((image_seg_flat == [244, 35, 232]).all(axis=2))] = [255]
# Extract car/person information (in addition to road information)
image_seg_flat_lane_edge_car = np.copy(image_seg_flat_lane_edge_road)
image_seg_flat_lane_edge_car[np.where((image_seg_flat == [0, 0, 142]).all(axis=2))] = [255]
image_seg_flat_lane_edge_car[np.where((image_seg_flat == [128, 64, 128]).all(axis=2))] = [255]
# intersection edge detection between road-information and road-person-car information
image_seg_flat_lane_edge = np.zeros((image_seg_flat.shape[:2]), dtype=np.uint8)
image_seg_flat_lane_edge[(cv.Canny(image_seg_flat_lane_edge_road, 64, 192).astype(np.int) + cv.Canny(
image_seg_flat_lane_edge_car, 64, 192).astype(np.int)) > 255] = 255
# Combine intersection with extracted lane markings
image_seg_flat_lane = np.zeros((image_seg_flat.shape[:2]), dtype=np.uint8)
image_seg_flat_lane[image_seg_flat_lane_markings >= 255] = 255
# Since line below is commented out, only lane markings are checked as lane lines, and not road-sidewalk edges
# etc.
# image_seg_flat_lane[image_seg_flat_lane_edge >= 255] = 255
# Hough transformation to find straight lines in image_seg_flat_lane
image_flat_lines = np.zeros((image_seg_flat.shape[:2]), dtype=np.uint8)
lines = cv.HoughLinesP(image_seg_flat_lane, 6, np.pi / 130, 50, np.array([]), 10, 100)
if type(lines) != NoneType: # POOPOO ALERT
for line in lines:
for x1, y1, x2, y2 in line:
cv.line(image_flat_lines, (x1, y1), (x2, y2), 255, 1)
# # Detect peaks in bottom part (all except first 160px) of picture
# line_flat_peaks = (np.sum(image_flat_lines[0:, :], axis=0) / 255).astype(np.int32)
# peaks = detect_peaks(line_flat_peaks, mph=20, mpd=40, show=False).astype(np.int)
# # Find, for each peak, its lower/upper bound (based on when the line_flat_peaks returns 0)
# peaks_lower = np.zeros(len(peaks), dtype=np.int)
# peaks_upper = np.zeros(len(peaks), dtype=np.int)
# for j in range(len(peaks)):
# pos_left = np.where(line_flat_peaks[:peaks[j]] == 0)[0]
# if len(pos_left) > 0:
# peaks_lower[j] = pos_left[-1]
# else:
# peaks_lower[j] = 0
# pos_right = np.where(line_flat_peaks[peaks[j]:] == 0)[0]
# if len(pos_right) > 0:
# peaks_upper[j] = peaks[j] + pos_right[0]
# else:
# peaks_upper[j] = 640
# peaks = np.stack((peaks_lower, peaks, peaks_upper), axis=-1)
#
# # Split peaks in those lying left and right of the ego vehicle
# left_indexes = np.where(peaks[:, 1] < 320)[0]
# right_indexes = np.where(peaks[:, 1] >= 320)[0]
# # For all possible lane combinations see if they actually are a lane.
# lanes = []
# if len(left_indexes) > 0 and len(right_indexes) > 0:
# # Left Lanes
# for j in left_indexes[:-1]:
# left = peaks[left_indexes[j]]
# right = peaks[left_indexes[j + 1]]
# if (left[2] - left[0]) < 60 and (right[2] - right[0]) < 60:
# lane = StraightLane(left, right, 'left')
# if lane.get_confidence(image_seg_flat, image_flat_lines)[0] > 0.1:
# lanes.append(lane)
# # Center Lane
# left = peaks[left_indexes[-1]]
# right = peaks[right_indexes[0]]
# if (left[2] - left[0]) < 60 and (right[2] - right[0]) < 60:
# lane = StraightLane(left, right, 'center')
# if lane.get_confidence(image_seg_flat, image_flat_lines)[0] > 0.1:
# lanes.append(lane)
# # Right Lane
# for j in range(len(right_indexes[1:])):
# left = peaks[right_indexes[j]]
# right = peaks[right_indexes[j + 1]]
# if (left[2] - left[0]) < 60 and (right[2] - right[0]) < 60:
# lane = StraightLane(left, right, 'right')
# if lane.get_confidence(image_seg_flat, image_flat_lines)[0] > 0.1:
# lanes.append(lane)
#
# # Fill top/bottom values of lanes surrounded by two 'larger' lanes
# for j in range(1, len(lanes) - 1):
# top = (lanes[j - 1].top, lanes[j].top, lanes[j + 1].top)
# bottom = (lanes[j - 1].bottom, lanes[j].bottom, lanes[j + 1].bottom)
# if lanes[j - 1].right[1] == lanes[j].left[1] and lanes[j].right[1] == lanes[j + 1].left[1]:
# if np.max([lanes[j - 1].top, lanes[j + 1].top]) < lanes[j].top:
# lanes[j].top = np.max([lanes[j - 1].top, lanes[j + 1].top])
# if np.min([lanes[j - 1].bottom, lanes[j + 1].bottom]) > lanes[j].bottom:
# lanes[j].bottom = np.min([lanes[j - 1].bottom, lanes[j + 1].bottom])
#
# # Extract lane images (just for visualization - no further use)
# image_final_extracted = np.zeros(image_seg_flat.shape, dtype=np.uint8)
# image_final_created = np.zeros(image_seg_flat.shape, dtype=np.uint8)
# for lane in lanes:
# image_final_extracted[lane.top:lane.bottom + 1, lane.left[1]:lane.right[1], :] = lane.extract_image(
# image_seg_flat, image_flat_lines)[lane.top:lane.bottom + 1, lane.left[1]:lane.right[1], :]
# image_final_created[lane.top:lane.bottom + 1, lane.left[1] - 2:lane.right[1] + 3,
# :] = lane.create_image(
# image_seg_flat, image_flat_lines)[lane.top:lane.bottom + 1, lane.left[1] - 2:lane.right[1] + 3, :]
# Visualize results
if self.settings['verbose']:
plot_image(image, 1)
plot_image(image_small, 2)
plot_image(image_seg, 3)
plot_image(image_seg_flat, 4)
plot_image(image_seg_flat_lane_markings, 5)
plot_image(image_seg_flat_lane_edge_road, 6)
plot_image(image_seg_flat_lane_edge_car, 7)
plot_image(image_seg_flat_lane_edge, 8)
plot_image(image_seg_flat_lane, 9)
plot_image(image_flat_lines, 10)
plot_line(line_flat_peaks, 11)
plot_image(image_final_extracted, 12)
plot_image(image_final_created, 13)
# Save image process from input to detected lanes
if self.settings['save']:
image_flat = (car_to_bird(image) * 255).astype(np.uint8)
image = (image * 255).astype(np.uint8)
image_flat_lines = np.stack((image_flat_lines, image_flat_lines, image_flat_lines), axis=-1)
image_final = np.vstack((np.hstack((image, image_flat, image_flat_lines)),
np.hstack((image_seg, image_seg_flat, image_final_created))))
Image.fromarray(image_final).save(
'results/{}/{}.png'.format(num, str(i).rjust(len(str(len(img_paths))), '0')))
# # Create a clip with saved images
# if self.settings['save']:
# clip = mpy.ImageSequenceClip('results/{}'.format(num), fps=10)
# clip.write_videofile('results/{}.mp4'.format(num))
image_flat = (car_to_bird(image) * 255).astype(np.uint8)
image = (image * 255).astype(np.uint8)
image_flat_lines = np.stack((image_flat_lines, image_flat_lines, image_flat_lines), axis=-1)
image_final = np.vstack((np.hstack((image, image_flat, image_flat_lines)),
np.hstack((image_seg, image_seg_flat, image_flat_lines))))
return image_final, image_flat_lines
# Class for a single straight lane.
class StraightLane:
# Init
def __init__(self, left, right, name):
self.left = left
self.right = right
self.name = name
self.width = self.right[1] - self.left[1]
# Calculate top/bottom range of lane and extract road information from segmented flat image
def extract_image(self, full_image, line_image):
self.extracted_image = np.zeros(full_image.shape, dtype=np.uint8)
for rgb in [[128, 64, 128], [244, 35, 232], [255, 255, 255]]:
x, y = np.where((full_image[:, self.left[1]:self.right[1]] == rgb).all(axis=2))
self.extracted_image[x, y + self.left[1], :] = rgb
line_image = np.stack((line_image, line_image, line_image), axis=-1)
if 'left' in self.name:
self.top = np.where(np.sum(np.sum(line_image[:, self.left[0]:self.left[2], :], axis=2), axis=1) > 0)[0][0]
self.bottom = np.where(np.sum(np.sum(line_image[:, self.left[0]:self.left[2], :], axis=2), axis=1) > 0)[0][
-1]
elif 'right' in self.name:
self.top = np.where(np.sum(np.sum(line_image[:, self.right[0]:self.right[2], :], axis=2), axis=1) > 0)[0][0]
self.bottom = np.where(np.sum(np.sum(line_image[:, self.right[0]:self.right[2], :], axis=2), axis=1) > 0)[0][-1]
else:
self.top = np.where(np.sum(np.sum(line_image[:, self.left[0]:self.right[2], :], axis=2), axis=1) > 0)[0][0]
self.bottom = np.where(np.sum(np.sum(line_image[:, self.left[0]:self.right[2], :], axis=2), axis=1) > 0)[0][
-1]
return self.extracted_image
# Get type (road or sidewalk) and confidence value (how much of area of lane dimension is classified as
# road/sidewalk?)
def get_confidence(self, full_image, line_image):
if not hasattr(self, 'extracted_image'):
self.extract_image(full_image, line_image)
road_num = len(
np.where((full_image[self.top:self.bottom + 1, self.left[1]:self.right[1]] == [128, 64, 128]).all(axis=2))[
0])
sidewalk_num = len(
np.where((full_image[self.top:self.bottom + 1, self.left[1]:self.right[1]] == [244, 35, 232]).all(axis=2))[
0])
total_num = len(np.ravel(full_image[self.top:self.bottom + 1, self.left[1]:self.right[1], 0]))
if road_num >= sidewalk_num:
self.confidence = np.float(road_num / total_num)
self.confidence_name = 'road'
self.confidence_rgb = [128, 64, 128]
else:
self.confidence = sidewalk_num / total_num
self.confidence_name = 'sidewalk'
self.confidence_rgb = [244, 35, 232]
return (self.confidence, self.confidence_name, self.confidence_rgb)
# Create a visualization of this Lane
def create_image(self, full_image, line_image):
if not hasattr(self, 'extracted_image'):
self.extract_image(full_image, line_image)
if not hasattr(self, 'confidence_rgb'):
self.get_confidence(full_image, line_image)
self.created_image = np.zeros(self.extracted_image.shape, dtype=np.uint8)
self.created_image[self.top:self.bottom + 1, self.left[1]:self.right[1]] = self.confidence_rgb
cv.line(self.created_image, (self.left[1], self.top), (self.left[1], self.bottom), (255, 255, 255), 3)
cv.line(self.created_image, (self.right[1], self.top), (self.right[1], self.bottom), (255, 255, 255), 3)
return self.created_image
# Sort image paths by first 'padding' them with '_' (so that '12' does not gets sorted in between '119' and '121' by making it '_12')
def sort_paths(input_img_paths):
img_paths = []
for img_path in input_img_paths:
num = img_path.split('_')[-1].split('.')[0]
img_path = img_path.replace(str(num) + '.png', str(num).rjust(8, '!') + '.png')
img_paths.append(img_path)
img_paths.sort()
return img_paths
# Transform image from car to bird perspective
def car_to_bird(img):
pw = PerspectiveWrapper()
dst = pw.top_down(img)
return dst
# Convert label predictions to an RGB image
def y_label_to_rgb(settings, y_label):
y_rgb = np.zeros(y_label.shape + (3,), dtype=np.uint8)
for i in range(len(settings['labels'][0])):
name = tuple(settings['labels'][0].keys())[i]
rgb = settings['labels'][0][name]['rgb']
y_rgb[y_label == i + 1] = rgb
return y_rgb
# Plot image
def plot_image(image, fig_num):
plt.figure(fig_num)
plt.clf()
plt.imshow(image)
plt.pause(0.001)
# Plot line
def plot_line(line, fig_num):
plt.figure(fig_num)
plt.clf()
plt.plot(line)
plt.pause(0.001)
|
[
"numpy.sum",
"matplotlib.pyplot.clf",
"numpy.ravel",
"matplotlib.pyplot.figure",
"cv2.line",
"get_model.get_model",
"numpy.copy",
"matplotlib.pyplot.imshow",
"ImageProcessing.PerspectiveWrapper.PerspectiveWrapper",
"Model.Road",
"tensorflow.compat.v1.Session",
"matplotlib.pyplot.pause",
"cv2.resize",
"numpy.stack",
"numpy.float16",
"cv2.Canny",
"keras.backend.set_session",
"numpy.float",
"numpy.hstack",
"get_labels.get_labels",
"tensorflow.compat.v1.ConfigProto",
"matplotlib.pyplot.plot",
"os.getcwd",
"numpy.zeros",
"numpy.expand_dims",
"keras.backend.set_learning_phase",
"numpy.array",
"PIL.Image.fromarray"
] |
[((608, 631), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (628, 631), True, 'from keras import backend as K\n'), ((688, 714), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (712, 714), True, 'import tensorflow as tf\n'), ((959, 994), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'config': 'config'}), '(config=config)\n', (979, 994), True, 'import tensorflow as tf\n'), ((995, 1014), 'keras.backend.set_session', 'K.set_session', (['sess'], {}), '(sess)\n', (1008, 1014), True, 'from keras import backend as K\n'), ((15981, 16001), 'ImageProcessing.PerspectiveWrapper.PerspectiveWrapper', 'PerspectiveWrapper', ([], {}), '()\n', (15999, 16001), False, 'from ImageProcessing.PerspectiveWrapper import PerspectiveWrapper\n'), ((16141, 16187), 'numpy.zeros', 'np.zeros', (['(y_label.shape + (3,))'], {'dtype': 'np.uint8'}), '(y_label.shape + (3,), dtype=np.uint8)\n', (16149, 16187), True, 'import numpy as np\n'), ((16445, 16464), 'matplotlib.pyplot.figure', 'plt.figure', (['fig_num'], {}), '(fig_num)\n', (16455, 16464), True, 'import matplotlib.pyplot as plt\n'), ((16469, 16478), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (16476, 16478), True, 'import matplotlib.pyplot as plt\n'), ((16483, 16500), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (16493, 16500), True, 'import matplotlib.pyplot as plt\n'), ((16505, 16521), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.001)'], {}), '(0.001)\n', (16514, 16521), True, 'import matplotlib.pyplot as plt\n'), ((16570, 16589), 'matplotlib.pyplot.figure', 'plt.figure', (['fig_num'], {}), '(fig_num)\n', (16580, 16589), True, 'import matplotlib.pyplot as plt\n'), ((16594, 16603), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (16601, 16603), True, 'import matplotlib.pyplot as plt\n'), ((16608, 16622), 'matplotlib.pyplot.plot', 'plt.plot', (['line'], {}), '(line)\n', (16616, 16622), True, 'import matplotlib.pyplot as plt\n'), ((16627, 16643), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.001)'], {}), '(0.001)\n', (16636, 16643), True, 'import matplotlib.pyplot as plt\n'), ((1596, 1621), 'get_labels.get_labels', 'get_labels', (['self.settings'], {}), '(self.settings)\n', (1606, 1621), False, 'from get_labels import get_labels\n'), ((1918, 1942), 'get_model.get_model', 'get_model', (['self.settings'], {}), '(self.settings)\n', (1927, 1942), False, 'from get_model import get_model\n'), ((2183, 2205), 'numpy.array', 'np.array', (['self.weights'], {}), '(self.weights)\n', (2191, 2205), True, 'import numpy as np\n'), ((2659, 2670), 'Model.Road', 'Road', (['lanes'], {}), '(lanes)\n', (2663, 2670), False, 'from Model import Road\n'), ((2991, 3050), 'cv2.resize', 'cv.resize', (['image', '(640, 480)'], {'interpolation': 'cv.INTER_LINEAR'}), '(image, (640, 480), interpolation=cv.INTER_LINEAR)\n', (3000, 3050), True, 'import cv2 as cv\n'), ((3305, 3383), 'cv2.resize', 'cv.resize', (['image_pred_small', '(image_w, image_h)'], {'interpolation': 'cv.INTER_LINEAR'}), '(image_pred_small, (image_w, image_h), interpolation=cv.INTER_LINEAR)\n', (3314, 3383), True, 'import cv2 as cv\n'), ((3695, 3745), 'numpy.zeros', 'np.zeros', (['image_seg_flat.shape[:2]'], {'dtype': 'np.uint8'}), '(image_seg_flat.shape[:2], dtype=np.uint8)\n', (3703, 3745), True, 'import numpy as np\n'), ((3928, 3965), 'numpy.copy', 'np.copy', (['image_seg_flat_lane_markings'], {}), '(image_seg_flat_lane_markings)\n', (3935, 3965), True, 'import numpy as np\n'), ((4289, 4327), 'numpy.copy', 'np.copy', (['image_seg_flat_lane_edge_road'], {}), '(image_seg_flat_lane_edge_road)\n', (4296, 4327), True, 'import numpy as np\n'), ((4662, 4712), 'numpy.zeros', 'np.zeros', (['image_seg_flat.shape[:2]'], {'dtype': 'np.uint8'}), '(image_seg_flat.shape[:2], dtype=np.uint8)\n', (4670, 4712), True, 'import numpy as np\n'), ((4996, 5046), 'numpy.zeros', 'np.zeros', (['image_seg_flat.shape[:2]'], {'dtype': 'np.uint8'}), '(image_seg_flat.shape[:2], dtype=np.uint8)\n', (5004, 5046), True, 'import numpy as np\n'), ((5427, 5477), 'numpy.zeros', 'np.zeros', (['image_seg_flat.shape[:2]'], {'dtype': 'np.uint8'}), '(image_seg_flat.shape[:2], dtype=np.uint8)\n', (5435, 5477), True, 'import numpy as np\n'), ((11616, 11689), 'numpy.stack', 'np.stack', (['(image_flat_lines, image_flat_lines, image_flat_lines)'], {'axis': '(-1)'}), '((image_flat_lines, image_flat_lines, image_flat_lines), axis=-1)\n', (11624, 11689), True, 'import numpy as np\n'), ((12332, 12374), 'numpy.zeros', 'np.zeros', (['full_image.shape'], {'dtype': 'np.uint8'}), '(full_image.shape, dtype=np.uint8)\n', (12340, 12374), True, 'import numpy as np\n'), ((12621, 12676), 'numpy.stack', 'np.stack', (['(line_image, line_image, line_image)'], {'axis': '(-1)'}), '((line_image, line_image, line_image), axis=-1)\n', (12629, 12676), True, 'import numpy as np\n'), ((15045, 15097), 'numpy.zeros', 'np.zeros', (['self.extracted_image.shape'], {'dtype': 'np.uint8'}), '(self.extracted_image.shape, dtype=np.uint8)\n', (15053, 15097), True, 'import numpy as np\n'), ((15209, 15316), 'cv2.line', 'cv.line', (['self.created_image', '(self.left[1], self.top)', '(self.left[1], self.bottom)', '(255, 255, 255)', '(3)'], {}), '(self.created_image, (self.left[1], self.top), (self.left[1], self.\n bottom), (255, 255, 255), 3)\n', (15216, 15316), True, 'import cv2 as cv\n'), ((15320, 15429), 'cv2.line', 'cv.line', (['self.created_image', '(self.right[1], self.top)', '(self.right[1], self.bottom)', '(255, 255, 255)', '(3)'], {}), '(self.created_image, (self.right[1], self.top), (self.right[1], self\n .bottom), (255, 255, 255), 3)\n', (15327, 15429), True, 'import cv2 as cv\n'), ((1957, 1968), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1966, 1968), False, 'import os\n'), ((2280, 2308), 'numpy.float16', 'np.float16', (['weights_array[i]'], {}), '(weights_array[i])\n', (2290, 2308), True, 'import numpy as np\n'), ((5552, 5564), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5560, 5564), True, 'import numpy as np\n'), ((10853, 10926), 'numpy.stack', 'np.stack', (['(image_flat_lines, image_flat_lines, image_flat_lines)'], {'axis': '(-1)'}), '((image_flat_lines, image_flat_lines, image_flat_lines), axis=-1)\n', (10861, 10926), True, 'import numpy as np\n'), ((14205, 14282), 'numpy.ravel', 'np.ravel', (['full_image[self.top:self.bottom + 1, self.left[1]:self.right[1], 0]'], {}), '(full_image[self.top:self.bottom + 1, self.left[1]:self.right[1], 0])\n', (14213, 14282), True, 'import numpy as np\n'), ((14351, 14381), 'numpy.float', 'np.float', (['(road_num / total_num)'], {}), '(road_num / total_num)\n', (14359, 14381), True, 'import numpy as np\n'), ((3164, 3199), 'numpy.expand_dims', 'np.expand_dims', (['image_small'], {'axis': '(0)'}), '(image_small, axis=0)\n', (3178, 3199), True, 'import numpy as np\n'), ((11723, 11771), 'numpy.hstack', 'np.hstack', (['(image, image_flat, image_flat_lines)'], {}), '((image, image_flat, image_flat_lines))\n', (11732, 11771), True, 'import numpy as np\n'), ((11806, 11862), 'numpy.hstack', 'np.hstack', (['(image_seg, image_seg_flat, image_flat_lines)'], {}), '((image_seg, image_seg_flat, image_flat_lines))\n', (11815, 11862), True, 'import numpy as np\n'), ((2887, 2900), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (2895, 2900), True, 'import numpy as np\n'), ((5723, 5776), 'cv2.line', 'cv.line', (['image_flat_lines', '(x1, y1)', '(x2, y2)', '(255)', '(1)'], {}), '(image_flat_lines, (x1, y1), (x2, y2), 255, 1)\n', (5730, 5776), True, 'import cv2 as cv\n'), ((10964, 11012), 'numpy.hstack', 'np.hstack', (['(image, image_flat, image_flat_lines)'], {}), '((image, image_flat, image_flat_lines))\n', (10973, 11012), True, 'import numpy as np\n'), ((11050, 11109), 'numpy.hstack', 'np.hstack', (['(image_seg, image_seg_flat, image_final_created)'], {}), '((image_seg, image_seg_flat, image_final_created))\n', (11059, 11109), True, 'import numpy as np\n'), ((11124, 11152), 'PIL.Image.fromarray', 'Image.fromarray', (['image_final'], {}), '(image_final)\n', (11139, 11152), False, 'from PIL import Image\n'), ((4749, 4797), 'cv2.Canny', 'cv.Canny', (['image_seg_flat_lane_edge_road', '(64)', '(192)'], {}), '(image_seg_flat_lane_edge_road, 64, 192)\n', (4757, 4797), True, 'import cv2 as cv\n'), ((4815, 4862), 'cv2.Canny', 'cv.Canny', (['image_seg_flat_lane_edge_car', '(64)', '(192)'], {}), '(image_seg_flat_lane_edge_car, 64, 192)\n', (4823, 4862), True, 'import cv2 as cv\n'), ((12748, 12807), 'numpy.sum', 'np.sum', (['line_image[:, self.left[0]:self.left[2], :]'], {'axis': '(2)'}), '(line_image[:, self.left[0]:self.left[2], :], axis=2)\n', (12754, 12807), True, 'import numpy as np\n'), ((12870, 12929), 'numpy.sum', 'np.sum', (['line_image[:, self.left[0]:self.left[2], :]'], {'axis': '(2)'}), '(line_image[:, self.left[0]:self.left[2], :], axis=2)\n', (12876, 12929), True, 'import numpy as np\n'), ((13042, 13103), 'numpy.sum', 'np.sum', (['line_image[:, self.right[0]:self.right[2], :]'], {'axis': '(2)'}), '(line_image[:, self.right[0]:self.right[2], :], axis=2)\n', (13048, 13103), True, 'import numpy as np\n'), ((13166, 13227), 'numpy.sum', 'np.sum', (['line_image[:, self.right[0]:self.right[2], :]'], {'axis': '(2)'}), '(line_image[:, self.right[0]:self.right[2], :], axis=2)\n', (13172, 13227), True, 'import numpy as np\n'), ((13302, 13362), 'numpy.sum', 'np.sum', (['line_image[:, self.left[0]:self.right[2], :]'], {'axis': '(2)'}), '(line_image[:, self.left[0]:self.right[2], :], axis=2)\n', (13308, 13362), True, 'import numpy as np\n'), ((13425, 13485), 'numpy.sum', 'np.sum', (['line_image[:, self.left[0]:self.right[2], :]'], {'axis': '(2)'}), '(line_image[:, self.left[0]:self.right[2], :], axis=2)\n', (13431, 13485), True, 'import numpy as np\n')]
|
from easyhmm import sparsehmm, hmm
import numpy as np
obsProbList = np.array(((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, 0.0), (1/3, 1/3, 1/3), (0.75, 0.25, 0.0)), dtype = np.float32)
obsProbList = np.concatenate((obsProbList, obsProbList[::-1], obsProbList))
obsProbList += 1e-5
obsProbList /= np.sum(obsProbList, axis=1).reshape(obsProbList.shape[0], 1)
initStateProb = np.ones(3, dtype = np.float32) / 3
transProb = np.array((1/3, 1/3, 1/3, 1/3, 1/3, 1/3, 0, 0.5, 0.5), dtype = np.float32)
vd = hmm.ViterbiDecoder(3)
vd.initialize(obsProbList[0], initStateProb)
vd.feed(obsProbList[1:], transProb)
print("NormalHMM:", vd.readDecodedPath())
|
[
"numpy.sum",
"easyhmm.hmm.ViterbiDecoder",
"numpy.ones",
"numpy.array",
"numpy.concatenate"
] |
[((72, 217), 'numpy.array', 'np.array', (['((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, 0.0), (1 /\n 3, 1 / 3, 1 / 3), (0.75, 0.25, 0.0))'], {'dtype': 'np.float32'}), '(((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, \n 0.0), (1 / 3, 1 / 3, 1 / 3), (0.75, 0.25, 0.0)), dtype=np.float32)\n', (80, 217), True, 'import numpy as np\n'), ((224, 285), 'numpy.concatenate', 'np.concatenate', (['(obsProbList, obsProbList[::-1], obsProbList)'], {}), '((obsProbList, obsProbList[::-1], obsProbList))\n', (238, 285), True, 'import numpy as np\n'), ((451, 539), 'numpy.array', 'np.array', (['(1 / 3, 1 / 3, 1 / 3, 1 / 3, 1 / 3, 1 / 3, 0, 0.5, 0.5)'], {'dtype': 'np.float32'}), '((1 / 3, 1 / 3, 1 / 3, 1 / 3, 1 / 3, 1 / 3, 0, 0.5, 0.5), dtype=np.\n float32)\n', (459, 539), True, 'import numpy as np\n'), ((533, 554), 'easyhmm.hmm.ViterbiDecoder', 'hmm.ViterbiDecoder', (['(3)'], {}), '(3)\n', (551, 554), False, 'from easyhmm import sparsehmm, hmm\n'), ((403, 431), 'numpy.ones', 'np.ones', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (410, 431), True, 'import numpy as np\n'), ((323, 350), 'numpy.sum', 'np.sum', (['obsProbList'], {'axis': '(1)'}), '(obsProbList, axis=1)\n', (329, 350), True, 'import numpy as np\n')]
|
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from magnebot import Arm
from magnebot.paths import IK_ORIENTATIONS_RIGHT_PATH, IK_ORIENTATIONS_LEFT_PATH, IK_POSITIONS_PATH
from magnebot.ik.orientation import ORIENTATIONS
"""
Visualize the pre-calculated IK orientation solutions as colorized vertical slices.
Each position is a circle on the image. Each image is a region at a given y value.
Each position is colorized to indicate the orientation mode + target orientation solution.
These images are saved to: `doc/images/ik`
"""
if __name__ == "__main__":
ik_images_directory = Path("../doc/images/ik")
# This color palette is used to colorize each orientation.
# Source: https://github.com/onivim/oni/blob/master/extensions/theme-onedark/colors/onedark.vim
colors = [(171, 178, 191), (224, 108, 117), (190, 80, 70), (152, 195, 121), (229, 192, 123), (209, 154, 102),
(97, 175, 239), (198, 120, 221), (86, 182, 194), (99, 109, 131)]
# Draw a colorized legend for the orientation images.
font_path = "fonts/inconsolata/Inconsolata_Expanded-Regular.ttf"
legend_font = ImageFont.truetype(font_path, 14)
legend = Image.new('RGB', (128, 220))
draw = ImageDraw.Draw(legend)
y = 8
x = 8
draw.text((x, y), "Key:", font=legend_font, anchor="mb", fill=(171, 178, 191))
y += 24
x += 8
for color, o in zip(colors, ORIENTATIONS):
draw.text((x, y), str(o), font=legend_font, anchor="mb", fill=color)
y += 18
# Save the color legend.
legend.save(str(ik_images_directory.joinpath("legend.jpg")))
# Load the positions.
positions = np.load(str(IK_POSITIONS_PATH.resolve()))
# The width of the image in pixels.
d = 256
# The radius of each circle.
r = 12
# Make images for each arm.
for arm, path in zip([Arm.left, Arm.right], [IK_ORIENTATIONS_LEFT_PATH, IK_ORIENTATIONS_RIGHT_PATH]):
orientations = np.load(str(path.resolve()))
directory = ik_images_directory.joinpath(arm.name)
# Get vertical slices of the point cloud.
for y in np.arange(0, 1.6, step=0.1):
image = Image.new('RGB', (d, 300))
draw = ImageDraw.Draw(image)
x = 0
# Draw the title text.
header_font = ImageFont.truetype(font_path, 18)
header = f"y = {round(y, 1)}"
header_size = header_font.getsize(header)
header_x = int((d / 2) - (header_size[0] / 2))
header_y = 8
draw.text((header_x, header_y), header, font=header_font, anchor="mg", fill=(171, 178, 191))
for p, o in zip(positions, orientations):
# Only include positions with the correct y value.
if o < -0.01 or np.abs(y - p[1]) > 0.01:
continue
# Convert the position to image coordinates.
x = d * (1 - ((1 - p[0]) / 2)) - 6
# Add a little padding to position this below the header text.
z = d * (1 - ((1 - p[2]) / 2)) + 30
# Draw a circle to mark the position. Colorize the orientation.
draw.rectangle((x, z, x + r, z + r), fill=colors[o], outline=colors[o])
# Save the image.
image.save(str(directory.joinpath(f"{round(y, 1)}.jpg").resolve()))
|
[
"PIL.Image.new",
"numpy.abs",
"PIL.ImageFont.truetype",
"pathlib.Path",
"numpy.arange",
"magnebot.paths.IK_POSITIONS_PATH.resolve",
"PIL.ImageDraw.Draw"
] |
[((627, 651), 'pathlib.Path', 'Path', (['"""../doc/images/ik"""'], {}), "('../doc/images/ik')\n", (631, 651), False, 'from pathlib import Path\n'), ((1153, 1186), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_path', '(14)'], {}), '(font_path, 14)\n', (1171, 1186), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1200, 1228), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(128, 220)'], {}), "('RGB', (128, 220))\n", (1209, 1228), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1240, 1262), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['legend'], {}), '(legend)\n', (1254, 1262), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2120, 2147), 'numpy.arange', 'np.arange', (['(0)', '(1.6)'], {'step': '(0.1)'}), '(0, 1.6, step=0.1)\n', (2129, 2147), True, 'import numpy as np\n'), ((1678, 1705), 'magnebot.paths.IK_POSITIONS_PATH.resolve', 'IK_POSITIONS_PATH.resolve', ([], {}), '()\n', (1703, 1705), False, 'from magnebot.paths import IK_ORIENTATIONS_RIGHT_PATH, IK_ORIENTATIONS_LEFT_PATH, IK_POSITIONS_PATH\n'), ((2169, 2195), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(d, 300)'], {}), "('RGB', (d, 300))\n", (2178, 2195), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2215, 2236), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['image'], {}), '(image)\n', (2229, 2236), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2316, 2349), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_path', '(18)'], {}), '(font_path, 18)\n', (2334, 2349), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2788, 2804), 'numpy.abs', 'np.abs', (['(y - p[1])'], {}), '(y - p[1])\n', (2794, 2804), True, 'import numpy as np\n')]
|
import os
from searcher.es_search import SearchResults_ES
from searcher.corpus_manager import CorpusManager
#from searcher.models import QueryRequest, VisRequest
#from searcher.query_handler import QueryHandler
from searcher.corpus_manager import CorpusManager
from searcher.nlp_model_manager import NLPModelManager
from searcher.formatted_data_manager import FormattedDataManager
import pandas as pd
import numpy as np
import tqdm
import gensim
from gensim.models import CoherenceModel
STORAGE_PATH = "eval_data/lda_hyperparams/"
class ModelEvaluation:
def __init__(self, query_obj):
self.query_obj = query_obj
self.dictionary = CorpusManager(self.query_obj)
self.corpus = None
self.raw_corpus = None
self.df = None
self.raw_doc_iter = SearchResults_ES(self.query_obj['database'], qry_obj=self.query_obj, rand=self.query_obj["rand"], cleaned=True)
self.doc_iter = None
def run_eval(self):
if self.query_obj['method'] == "special":
#unimpemented
return
else:
self.run_lda_coherence()
def single_lda_run(self, topics=None, a=0.91, b=.1, seed=100, savefile=None):
ntopics = self.query_obj['num_topics'] if topics == None else topics
if self.corpus == None:
self.dictionary.create_ngrams()
self.dictionary.create_dict()
self.corpus = []
self.raw_corpus = []
self.doc_iter = SearchResults_ES(self.query_obj['database'], qry_obj=self.query_obj, rand=self.query_obj["rand"], tokenized=True, cm=self.dictionary)
for x in self.raw_doc_iter:
self.raw_corpus.append(x)
for x in self.doc_iter:
self.corpus.append(x)
lda_model = gensim.models.LdaModel(
corpus=self.corpus,
id2word=self.dictionary.dct,
num_topics=ntopics,
random_state=seed,
chunksize=100,
passes=5,
alpha=a,
eta=b,
eval_every=5,
per_word_topics=True)
topics = lda_model.show_topics(num_topics=ntopics, num_words=10, formatted=True)
print("model alpha:{} beta:{} topics:{}".format(a, b, ntopics))
print(topics)
if savefile:
lda_model.save(STORAGE_PATH + savefile)
else:
lda_model.save(STORAGE_PATH + 'test_model')
perp = lda_model.log_perplexity(self.corpus)
coherence_model_lda = CoherenceModel(model=lda_model, texts=self.raw_corpus, dictionary=self.dictionary.dct, coherence='c_v')
with np.errstate(invalid='ignore'):
lda_score = coherence_model_lda.get_coherence()
print(lda_score)
print(perp)
return [lda_score, perp]
def run_lda_coherence(self, min_topics=15, max_topics=40, step_size=5, test=False):
if self.corpus == None:
self.dictionary.create_ngrams()
self.dictionary.create_dict()
self.corpus = []
self.raw_corpus = []
self.doc_iter = SearchResults_ES(self.query_obj['database'], qry_obj=self.query_obj, rand=self.query_obj["rand"], tokenized=True, cm=self.dictionary)
self.raw_doc_iter = SearchResults_ES(self.query_obj['database'], qry_obj=self.query_obj, rand=self.query_obj["rand"], cleaned=True, cm=self.dictionary)
for x in self.raw_doc_iter:
self.raw_corpus.append(x)
for x in self.doc_iter:
self.corpus.append(x)
print("CORPUS")
print(self.corpus)
print("RAW_CORPUS")
print(self.raw_corpus)
step_size = step_size
topics_range = range(min_topics, max_topics, step_size)
# Alpha parameter
alpha = list(np.arange(0.01, 1, 0.3))
alpha.append('symmetric')
alpha.append('asymmetric')
# Beta parameter
beta = list(np.arange(0.01, 1, 0.3))
beta.append('symmetric')
beta.append('auto')
if test == True:
alpha = [0.31]
beta = [0.91]
id2word = self.dictionary
corpus_sets = [""]
corpus_title = ['100% Corpus']
model_results = {'Validation_Set': [],
'Topics': [],
'Alpha': [],
'Beta': [],
'Coherence': [],
'Perplexity' : []
}
total_count = len(alpha) * len(beta) * ((max_topics - min_topics) / step_size)
print(total_count)
if 1 == 1:
pbar = tqdm.tqdm(total=total_count)
# iterate through validation corpuses
for i in range(len(corpus_sets)):
# iterate through number of topics
for k in topics_range:
# iterate through alpha values
for a in alpha:
# iterare through beta values
for b in beta:
# get the coherence score for the given parameters
count = 0
cv = self.single_lda_run(topics=k, a=a, b=b)
model_results['Validation_Set'].append(corpus_title[i])
model_results['Topics'].append(k)
model_results['Alpha'].append(a)
model_results['Beta'].append(b)
model_results['Coherence'].append(cv[0])
model_results['Perplexity'].append(cv[1])
pbar.update(1)
self.df = pd.DataFrame(model_results)
pbar.close()
return
def write_eval(self, writefile=None):
if writefile:
self.df.to_csv(writefile, index=False)
else:
return self.df
if __name__ == '__main__':
"""test_qry_obj = {'start': '1809', 'end': '2017', 'f_start': '-1', 'f_end': '-1', 'qry': '', 'maximum_hits': '10', 'method': 'multilevel_lda', 'stop_words': '', 'replacement': '', 'phrases': '', 'level_select': 'article', 'num_topics': 10, 'passes': '20', 'database': 'CaseLaw_v2', 'journal': 'all', 'jurisdiction_select': 'all', 'auth_s': '', 'family_select': 'both', 'min_occurrence': '-1', 'max_occurrence': '-1', 'doc_count': '500', 'ngrams' : False, 'model_name' : 'test', 'rand' : True}
"""
test_qry_obj = {'start': 'year', 'end': 'year', 'f_start': '-1', 'f_end': '-1', 'qry': 'apple OR banana', 'maximum_hits': '100', 'method': 'multilevel_lda', 'stop_words': '', 'replacement': '', 'phrases': '', 'level_select': 'article', 'num_topics': 10, 'passes': '20', 'database': 'Pubmed', 'journal': 'all', 'jurisdiction_select': 'all', 'auth_s': '', 'family_select': 'both', 'min_occurrence': '-1', 'max_occurrence': '-1', 'doc_count': '10', 'ngrams' : True, 'model_name' : 'test', 'rand' : False}
me = ModelEvaluation(test_qry_obj)
me.run_lda_coherence(test=True)
me.write_eval(STORAGE_PATH + "test_pubmed_eval.csv")
|
[
"pandas.DataFrame",
"tqdm.tqdm",
"numpy.errstate",
"searcher.es_search.SearchResults_ES",
"gensim.models.LdaModel",
"numpy.arange",
"searcher.corpus_manager.CorpusManager",
"gensim.models.CoherenceModel"
] |
[((637, 666), 'searcher.corpus_manager.CorpusManager', 'CorpusManager', (['self.query_obj'], {}), '(self.query_obj)\n', (650, 666), False, 'from searcher.corpus_manager import CorpusManager\n'), ((752, 868), 'searcher.es_search.SearchResults_ES', 'SearchResults_ES', (["self.query_obj['database']"], {'qry_obj': 'self.query_obj', 'rand': "self.query_obj['rand']", 'cleaned': '(True)'}), "(self.query_obj['database'], qry_obj=self.query_obj, rand=\n self.query_obj['rand'], cleaned=True)\n", (768, 868), False, 'from searcher.es_search import SearchResults_ES\n'), ((1587, 1782), 'gensim.models.LdaModel', 'gensim.models.LdaModel', ([], {'corpus': 'self.corpus', 'id2word': 'self.dictionary.dct', 'num_topics': 'ntopics', 'random_state': 'seed', 'chunksize': '(100)', 'passes': '(5)', 'alpha': 'a', 'eta': 'b', 'eval_every': '(5)', 'per_word_topics': '(True)'}), '(corpus=self.corpus, id2word=self.dictionary.dct,\n num_topics=ntopics, random_state=seed, chunksize=100, passes=5, alpha=a,\n eta=b, eval_every=5, per_word_topics=True)\n', (1609, 1782), False, 'import gensim\n'), ((2158, 2266), 'gensim.models.CoherenceModel', 'CoherenceModel', ([], {'model': 'lda_model', 'texts': 'self.raw_corpus', 'dictionary': 'self.dictionary.dct', 'coherence': '"""c_v"""'}), "(model=lda_model, texts=self.raw_corpus, dictionary=self.\n dictionary.dct, coherence='c_v')\n", (2172, 2266), False, 'from gensim.models import CoherenceModel\n'), ((4608, 4635), 'pandas.DataFrame', 'pd.DataFrame', (['model_results'], {}), '(model_results)\n', (4620, 4635), True, 'import pandas as pd\n'), ((1325, 1463), 'searcher.es_search.SearchResults_ES', 'SearchResults_ES', (["self.query_obj['database']"], {'qry_obj': 'self.query_obj', 'rand': "self.query_obj['rand']", 'tokenized': '(True)', 'cm': 'self.dictionary'}), "(self.query_obj['database'], qry_obj=self.query_obj, rand=\n self.query_obj['rand'], tokenized=True, cm=self.dictionary)\n", (1341, 1463), False, 'from searcher.es_search import SearchResults_ES\n'), ((2269, 2298), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (2280, 2298), True, 'import numpy as np\n'), ((2658, 2796), 'searcher.es_search.SearchResults_ES', 'SearchResults_ES', (["self.query_obj['database']"], {'qry_obj': 'self.query_obj', 'rand': "self.query_obj['rand']", 'tokenized': '(True)', 'cm': 'self.dictionary'}), "(self.query_obj['database'], qry_obj=self.query_obj, rand=\n self.query_obj['rand'], tokenized=True, cm=self.dictionary)\n", (2674, 2796), False, 'from searcher.es_search import SearchResults_ES\n'), ((2816, 2952), 'searcher.es_search.SearchResults_ES', 'SearchResults_ES', (["self.query_obj['database']"], {'qry_obj': 'self.query_obj', 'rand': "self.query_obj['rand']", 'cleaned': '(True)', 'cm': 'self.dictionary'}), "(self.query_obj['database'], qry_obj=self.query_obj, rand=\n self.query_obj['rand'], cleaned=True, cm=self.dictionary)\n", (2832, 2952), False, 'from searcher.es_search import SearchResults_ES\n'), ((3269, 3292), 'numpy.arange', 'np.arange', (['(0.01)', '(1)', '(0.3)'], {}), '(0.01, 1, 0.3)\n', (3278, 3292), True, 'import numpy as np\n'), ((3384, 3407), 'numpy.arange', 'np.arange', (['(0.01)', '(1)', '(0.3)'], {}), '(0.01, 1, 0.3)\n', (3393, 3407), True, 'import numpy as np\n'), ((3880, 3908), 'tqdm.tqdm', 'tqdm.tqdm', ([], {'total': 'total_count'}), '(total=total_count)\n', (3889, 3908), False, 'import tqdm\n')]
|
import numpy as np
from PulseGenerator import Pulse
# physical constants
planck = 4.13566751691e-15 # ev s
hbarfs = planck * 1e15 / (2 * np.pi) #ev fs
ev_nm = 1239.842
opt_t = np.linspace(900,1100,10)/hbarfs
def build_fitness_function(
nbins=30,
tl_duration=19.0,
e_carrier=2.22,
e_shaper=0.3,
total_duration=1000.0,
avgtimes=[1200.0],):
# Load necessary quantites
es = np.load("operators/es.npy")
fcf_e = np.load("operators/fcf_e.npy")
Pce = np.load("operators/Pce.npy")
Pte = np.load("operators/Pte.npy")
# Ultrafast laser parameters
width_tl = tl_duration/hbarfs
width_total = total_duration/hbarfs
w0 = e_carrier
elow = e_carrier - e_shaper/2.0
ehigh = e_carrier + e_shaper/2.0
de = (ehigh - elow)/nbins
opt_times = np.array(avgtimes)/hbarfs
def make_shaped_pulse(veci, veca):
intensities = veci
angles = veca
intensities[intensities<0] = 0.0
intensities[intensities>1] = 1.0
intensities[angles<0] = 0.0
intensities[angles>2*np.pi] = 2 * np.pi
amplitudes = np.sqrt(intensities) * np.exp(1j * angles)
gp = Pulse(elow, de, amplitudes, width_tl, width_total, w0=w0)
return gp
def prop_with_pulse(gp, times):
preps = gp.get_preps(times,es)
for i in range(len(es)):
preps[i,:] *= np.exp(-1j * es[i] * times) * fcf_e[i] * (-1.0/1j)
pt = np.array([psi.T.conj().dot(Pte).dot(psi) for psi in preps.T]).real
pc = np.array([psi.T.conj().dot(Pce).dot(psi) for psi in preps.T]).real
return pt, pc
def evaluate(veci,veca):
g = make_shaped_pulse(veci,veca)
pt, pc = prop_with_pulse(g, opt_times)
return np.sum(pt)/np.sum(pc + pt)
return evaluate
if __name__ == "__main__":
# Build a fitness function that represents shaped pulse control of
# cis-trans isomerization of retinal in bacteriorhodopsin. The paremeters
# below are those used in the paper:
# https://aip.scitation.org/doi/abs/10.1063/1.5003389
# nbins is the number of pixels on the pulse shaper. The final fitness
# function has nbins x 2 dimensions:
# - nbins values between 0 and 1 that give the transparency of the shaper
# at that pixel.
#- nbins angles (periodic, 0 to 2 pi radians) that give the delay applied
# by the shaper at that pixel.
# Values outside those bounds are truncated.
# Parameters
# -------------------------------------------------------------------------
# nbins: number of controllable elements on the pulse shaper
# tl_duration: duration of the seed pulse to the shaper, in fs.
# e_carrier: carrier energy of the seed pulse, in eV.
# e_shaper: bandwidth of the shaper, in eV.
# total_duration: soft limit on the total pulse length, in fs.
# avgtimes: time points at which the isomer ratio is computed and averaged
# to obtain the final fitness ("control interval").
fitness = build_fitness_function(
nbins=30,
tl_duration=19.0,
e_carrier=2.22,
e_shaper=0.3,
total_duration=1000.0,
avgtimes=np.linspace(900,1100,10))
# evaluate some pulses
values = [fitness(np.random.rand(30), 2 * np.pi * np.random.rand(30))
for k in range(6)]
|
[
"numpy.load",
"numpy.sum",
"PulseGenerator.Pulse",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"numpy.random.rand",
"numpy.sqrt"
] |
[((177, 203), 'numpy.linspace', 'np.linspace', (['(900)', '(1100)', '(10)'], {}), '(900, 1100, 10)\n', (188, 203), True, 'import numpy as np\n'), ((429, 456), 'numpy.load', 'np.load', (['"""operators/es.npy"""'], {}), "('operators/es.npy')\n", (436, 456), True, 'import numpy as np\n'), ((469, 499), 'numpy.load', 'np.load', (['"""operators/fcf_e.npy"""'], {}), "('operators/fcf_e.npy')\n", (476, 499), True, 'import numpy as np\n'), ((510, 538), 'numpy.load', 'np.load', (['"""operators/Pce.npy"""'], {}), "('operators/Pce.npy')\n", (517, 538), True, 'import numpy as np\n'), ((549, 577), 'numpy.load', 'np.load', (['"""operators/Pte.npy"""'], {}), "('operators/Pte.npy')\n", (556, 577), True, 'import numpy as np\n'), ((825, 843), 'numpy.array', 'np.array', (['avgtimes'], {}), '(avgtimes)\n', (833, 843), True, 'import numpy as np\n'), ((1186, 1243), 'PulseGenerator.Pulse', 'Pulse', (['elow', 'de', 'amplitudes', 'width_tl', 'width_total'], {'w0': 'w0'}), '(elow, de, amplitudes, width_tl, width_total, w0=w0)\n', (1191, 1243), False, 'from PulseGenerator import Pulse\n'), ((1130, 1150), 'numpy.sqrt', 'np.sqrt', (['intensities'], {}), '(intensities)\n', (1137, 1150), True, 'import numpy as np\n'), ((1153, 1174), 'numpy.exp', 'np.exp', (['(1.0j * angles)'], {}), '(1.0j * angles)\n', (1159, 1174), True, 'import numpy as np\n'), ((1764, 1774), 'numpy.sum', 'np.sum', (['pt'], {}), '(pt)\n', (1770, 1774), True, 'import numpy as np\n'), ((1775, 1790), 'numpy.sum', 'np.sum', (['(pc + pt)'], {}), '(pc + pt)\n', (1781, 1790), True, 'import numpy as np\n'), ((3199, 3225), 'numpy.linspace', 'np.linspace', (['(900)', '(1100)', '(10)'], {}), '(900, 1100, 10)\n', (3210, 3225), True, 'import numpy as np\n'), ((3276, 3294), 'numpy.random.rand', 'np.random.rand', (['(30)'], {}), '(30)\n', (3290, 3294), True, 'import numpy as np\n'), ((3308, 3326), 'numpy.random.rand', 'np.random.rand', (['(30)'], {}), '(30)\n', (3322, 3326), True, 'import numpy as np\n'), ((1397, 1426), 'numpy.exp', 'np.exp', (['(-1.0j * es[i] * times)'], {}), '(-1.0j * es[i] * times)\n', (1403, 1426), True, 'import numpy as np\n')]
|
import os, sys
import argparse
import numpy as np
import gzip
# image processing
from PIL import Image
import cv2
from ipfml import utils
from ipfml.processing import transform, segmentation
import matplotlib.pyplot as plt
from estimators import estimate, estimators_list
data_output = 'data/generated'
def write_progress(progress):
barWidth = 180
output_str = "["
pos = barWidth * progress
for i in range(barWidth):
if i < pos:
output_str = output_str + "="
elif i == pos:
output_str = output_str + ">"
else:
output_str = output_str + " "
output_str = output_str + "] " + str(int(progress * 100.0)) + " %\r"
print(output_str)
sys.stdout.write("\033[F")
def main():
parser = argparse.ArgumentParser(description="Check complexity of each zone of scene using estimator during rendering")
parser.add_argument('--folder', type=str, help='folder where scenes with png scene file are stored')
parser.add_argument('--estimators', type=str, help='list of estimators', default='l_mean,l_variance')
parser.add_argument('--output', type=str, help='output data filename', required=True)
args = parser.parse_args()
p_folder = args.folder
p_estimators = [ i.strip() for i in args.estimators.split(',') ]
p_output = args.output
print(p_estimators)
folders = [ f for f in os.listdir(p_folder) if 'min_max' not in f ]
n_zones = 16
if not os.path.exists(data_output):
os.makedirs(data_output)
datafile = open(os.path.join(data_output, p_output), 'w')
for i, scene in enumerate(sorted(folders)):
zones = []
zones_indices = np.arange(n_zones)
for _ in zones_indices:
zones.append([])
scene_folder = os.path.join(p_folder, scene)
# get all images and extract estimator for each blocks
images = sorted([ i for i in os.listdir(scene_folder) if '.png' in i ])
# get reference image
img_path = os.path.join(scene_folder, images[0])
img_arr = np.array(Image.open(img_path))
blocks = segmentation.divide_in_blocks(img_arr, (200, 200))
for index, b in enumerate(blocks):
# extract data and write into file
x = []
for estimator in p_estimators:
estimated = estimate(estimator, b)
if not isinstance(estimated, np.float64):
for v in estimated:
x.append(v)
else:
x.append(estimated)
line = scene + ';' + img_path + ';' + str(index) + ';'
for v in x:
line += str(v) + ';'
line += '\n'
datafile.write(line)
write_progress((i * n_zones + index + 1) / (float(len(folders)) * float(n_zones)))
datafile.close()
if __name__ == "__main__":
main()
|
[
"sys.stdout.write",
"os.makedirs",
"argparse.ArgumentParser",
"estimators.estimate",
"os.path.exists",
"ipfml.processing.segmentation.divide_in_blocks",
"PIL.Image.open",
"numpy.arange",
"os.path.join",
"os.listdir"
] |
[((720, 746), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[F"""'], {}), "('\\x1b[F')\n", (736, 746), False, 'import os, sys\n'), ((775, 890), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Check complexity of each zone of scene using estimator during rendering"""'}), "(description=\n 'Check complexity of each zone of scene using estimator during rendering')\n", (798, 890), False, 'import argparse\n'), ((1471, 1498), 'os.path.exists', 'os.path.exists', (['data_output'], {}), '(data_output)\n', (1485, 1498), False, 'import os, sys\n'), ((1508, 1532), 'os.makedirs', 'os.makedirs', (['data_output'], {}), '(data_output)\n', (1519, 1532), False, 'import os, sys\n'), ((1554, 1589), 'os.path.join', 'os.path.join', (['data_output', 'p_output'], {}), '(data_output, p_output)\n', (1566, 1589), False, 'import os, sys\n'), ((1689, 1707), 'numpy.arange', 'np.arange', (['n_zones'], {}), '(n_zones)\n', (1698, 1707), True, 'import numpy as np\n'), ((1806, 1835), 'os.path.join', 'os.path.join', (['p_folder', 'scene'], {}), '(p_folder, scene)\n', (1818, 1835), False, 'import os, sys\n'), ((2030, 2067), 'os.path.join', 'os.path.join', (['scene_folder', 'images[0]'], {}), '(scene_folder, images[0])\n', (2042, 2067), False, 'import os, sys\n'), ((2136, 2186), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['img_arr', '(200, 200)'], {}), '(img_arr, (200, 200))\n', (2165, 2186), False, 'from ipfml.processing import transform, segmentation\n'), ((1396, 1416), 'os.listdir', 'os.listdir', (['p_folder'], {}), '(p_folder)\n', (1406, 1416), False, 'import os, sys\n'), ((2096, 2116), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (2106, 2116), False, 'from PIL import Image\n'), ((2390, 2412), 'estimators.estimate', 'estimate', (['estimator', 'b'], {}), '(estimator, b)\n', (2398, 2412), False, 'from estimators import estimate, estimators_list\n'), ((1937, 1961), 'os.listdir', 'os.listdir', (['scene_folder'], {}), '(scene_folder)\n', (1947, 1961), False, 'import os, sys\n')]
|
import csv
import json
import multiprocessing as mp
import os
import random
import signal
import string
import sys
import traceback
from datetime import datetime, timedelta
from itertools import repeat
import nest_asyncio
import numpy as np
from cate.core import DATA_STORE_REGISTRY, ds
from cate.core.ds import DataAccessError
nest_asyncio.apply()
# header for CSV report
header_row = ['ECV-Name', 'Dataset-ID', 'supported', 'open(1)', 'open_bbox(2)', 'cache(3)', 'map(4)', 'comment']
results_csv = f'test_cci_data_support_{datetime.date(datetime.now())}.csv'
# Not supported vector data:
vector_data = ['esacci.ICESHEETS.mon.IND.GMB.GRACE-instrument.GRACE.VARIOUS.1-3.greenland_gmb_time_series',
'esacci.ICESHEETS.unspecified.Unspecified.CFL.multi-sensor.multi-platform.UNSPECIFIED.v3-0.greenland',
'esacci.ICESHEETS.unspecified.Unspecified.GLL.multi-sensor.multi-platform.UNSPECIFIED.v1-3.greenland',
'esacci.ICESHEETS.yr.Unspecified.GMB.GRACE-instrument.GRACE.UNSPECIFIED.1-2.greenland_gmb_timeseries',
'esacci.ICESHEETS.yr.Unspecified.GMB.GRACE-instrument.GRACE.UNSPECIFIED.1-4.greenland_gmb_time_series',
'esacci.ICESHEETS.yr.Unspecified.GMB.GRACE-instrument.GRACE.UNSPECIFIED.1-5.greenland_gmb_time_series']
# time out in order to cancel datasets which are taking longer than a certain time
TIMEOUT_TIME = 120
class TimeOutException(Exception):
pass
def alarm_handler(signum, frame):
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] ALARM signal received')
raise TimeOutException(f'Time out after {TIMEOUT_TIME} seconds.')
# Utility functions
def append_dict_as_row(file_name, dict_of_elem, field_names):
# Open file in append mode
with open(file_name, 'a+', newline='') as write_obj:
# Create a writer object from csv module
dict_writer = csv.DictWriter(write_obj, fieldnames=field_names)
# Add dictionary as wor in the csv
dict_writer.writerow(dict_of_elem)
write_obj.close()
def update_csv(results_csv, header_row, results_for_dataset_collection):
if not os.path.isfile(results_csv):
with open(results_csv, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(header_row)
append_dict_as_row(results_csv, results_for_dataset_collection, header_row)
def get_region(dataset):
bbox_maxx = dataset.meta_info['bbox_maxx']
bbox_minx = dataset.meta_info['bbox_minx']
bbox_maxy = dataset.meta_info['bbox_maxy']
bbox_miny = dataset.meta_info['bbox_miny']
indx = random.uniform(float(bbox_minx), float(bbox_maxx))
indy = random.uniform(float(bbox_miny), float(bbox_maxy))
if indx == float(bbox_maxx):
if indx > 0:
indx = indx - 1
else:
indx = indx + 1
if indy == float(bbox_maxy):
if indy > 0:
indy = indy - 1
else:
indy = indy + 1
if indx == float(bbox_minx):
indx = indx + 1
if indy == float(bbox_miny):
indy = indy + 1
region = [float("{:.1f}".format(indx)), float("{:.1f}".format(indy)), float(
"{:.1f}".format((indx + 0.1))), float("{:.1f}".format((indy + 0.1)))]
return region
def check_for_processing(cube, summary_row, time_range):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(TIMEOUT_TIME)
try:
try:
var = list(cube.data_vars)[0]
except IndexError:
summary_row['open_bbox(2)'] = 'no'
comment_1 = f'Failed at getting first variable from list {list(cube.data_vars)}: {sys.exc_info()[:2]}'
return summary_row, comment_1
try:
np.sum(cube[var])
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] The requested time range is {time_range}. '
f'The cubes actual first time stamp is {cube.time.min()} '
f'and last {cube.time.max()}.')
summary_row['open_bbox(2)'] = 'yes'
comment_1 = ''
except:
summary_row['open_bbox(2)'] = 'no'
comment_1 = f'Failed executing np.sum(cube[{var}]): {sys.exc_info()[:2]}'
except TimeOutException:
summary_row['open_bbox(2)'] = 'no'
comment_1 = sys.exc_info()[:2]
signal.alarm(0)
return summary_row, comment_1
def check_write_to_disc(summary_row, comment_2, data_source, time_range, variables, region, lds):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(TIMEOUT_TIME)
if comment_2 is not None:
return summary_row, comment_2
rand_string = f"test{random.choice(string.ascii_lowercase)}{random.choice(string.octdigits)}" # needed when tests run in parallel
try:
data_source.make_local(rand_string, time_range=time_range, var_names=variables, region=region)
local_ds = ds.open_dataset(f'local.{rand_string}')
local_ds.close()
summary_row['cache(3)'] = 'yes'
comment_2 = ''
except DataAccessError:
summary_row['cache(3)'] = 'no'
comment_2 = f'local.{rand_string}: Failed saving to disc with: {sys.exc_info()[:2]}'
except TimeOutException:
summary_row['cache(3)'] = 'no'
comment_2 = sys.exc_info()[:2]
except:
summary_row['cache(3)'] = 'no'
comment_2 = f'Failed saving to disc with: {sys.exc_info()[:2]}'
lds.remove_data_source(f"local.{rand_string}")
signal.alarm(0)
return summary_row, comment_2
def check_for_visualization(cube, summary_row, variables):
var_with_lat_lon_right_order = []
vars = []
comment_3 = None
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(TIMEOUT_TIME)
try:
for var in cube.data_vars:
vars.append(var)
if cube[var].dims[-2:] == ('lat', 'lon'):
if len(cube.lat.shape) == 1 and len(cube.lon.shape) == 1:
if cube.lat.size > 0 and cube.lon.size > 0:
var_with_lat_lon_right_order.append(var)
else:
comment_3 = f'cube.lat.size: {cube.lat.size}, cube.lon.size: {cube.lon.size}.'
else:
comment_3 = f'cube.lat.shape: {cube.lat.shape}, cube.lon.shape: {cube.lon.shape}.'
else:
comment_3 = f'Last two dimensions of variable {var}: {cube[var].dims[-2:]}.'
if len(var_with_lat_lon_right_order) > 0:
summary_row['map(4)'] = 'yes'
comment_3 = ''
else:
summary_row['map(4)'] = 'no'
if len(vars) == 0:
comment_3 = f'Dataset has none of the requested variables: {variables}.'
if comment_3 is None:
comment_3 = f'None of variables: {vars} has lat and lon in correct order.'
except TimeOutException:
summary_row['map(4)'] = 'no'
comment_3 = sys.exc_info()[:2]
signal.alarm(0)
return summary_row, comment_3
def check_for_support(data_id):
if 'sinusoidal' in data_id:
supported = False
reason = f"There is no support for sinusoidal datasets, please use the equivalent dataset with 'geographic' in" \
f" the dataset_id."
elif 'L2P' in data_id:
supported = False
reason = f"There is no support for L2P datasets, because problems are expected."
elif 'esacci.FIRE.mon.L3S' in data_id:
supported = False
reason = f"There is no support for FIRE L3S datasets, because problems are expected."
elif 'esacci.SEALEVEL.satellite-orbit-frequency.L1' in data_id:
supported = False
reason = f"There is no support for SEALEVEL satellite-orbit-frequency datasets, because problems are expected."
elif data_id in vector_data:
supported = False
reason = f"There is no support for vector data."
else:
supported = True
reason = None
return supported, reason
def _all_tests_no(summary_row, comment_1, open_wo_subset_only=False):
summary_row['open_bbox(2)'] = 'no'
summary_row['cache(3)'] = 'no'
summary_row['map(4)'] = 'no'
if open_wo_subset_only:
summary_row['open(1)'] = 'yes'
summary_row['comment'] = f'(1) Dataset can open without spatial subset only; (2) {comment_1}'
else:
summary_row['open(1)'] = 'no'
summary_row['comment'] = f'{comment_1}'
update_csv(results_csv, header_row, summary_row)
def test_open_ds(data, store, lds):
comment_1 = None
comment_2 = None
comment_3 = None
open_wo_subset_only = False
data_id = data.id
summary_row = {'ECV-Name': data_id.split('.')[1], 'Dataset-ID': data_id}
supported, reason = check_for_support(data_id)
if not supported:
summary_row['supported'] = 'no'
comment_1 = reason
_all_tests_no(summary_row, comment_1)
return
else:
summary_row['supported'] = 'yes'
try:
data_source = store.query(ds_id=data_id)[0]
except:
comment_1 = f'Failed getting data description while executing ' \
f'store.query(ds_id={data_id})[0] with: {sys.exc_info()[:2]}'
_all_tests_no(summary_row, comment_1)
return
data_source.update_file_list()
if len(data_source._file_list) == 0:
comment_1 = f'Has no file list.'
_all_tests_no(summary_row, comment_1)
return
region = get_region(data_source)
try:
time_range = tuple(
t.strftime('%Y-%m-%d') for t in [data_source._file_list[0][1], data_source._file_list[1][2]])
except IndexError:
try:
time_range = tuple(
t.strftime('%Y-%m-%d') for t in [data_source._file_list[0][1], data_source._file_list[0][2]])
except:
time_range = None
except:
time_range = None
var_list = []
s_not_to_be_in_var = ['longitude', 'latitude', 'lat', 'lon',
'bounds', 'bnds', 'date', 'Longitude', 'Latitude']
if len(data_source.meta_info['variables']) > 3:
while len(var_list) < 1:
for var in random.choices(data_source.meta_info['variables'], k=2):
if not (any(s_part in var['name'] for s_part in s_not_to_be_in_var)) and var[
'name'] not in var_list:
var_list.append(var['name'])
else:
for var in data_source.meta_info['variables']:
if not (any(s_part in var['name'] for s_part in s_not_to_be_in_var)) and var[
'name'] not in var_list:
var_list.append(var['name'])
try:
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Opening cube for data_id {data_id} with {var_list} '
f'and time range {time_range}.')
cube = data_source.open_dataset(time_range=time_range, var_names=var_list)
vars_in_cube = []
for var in var_list:
if var in cube.data_vars:
vars_in_cube.append(var)
if len(vars_in_cube) == 0:
comment_1 = f'Requested variables {var_list} for subset are not in dataset.'
_all_tests_no(summary_row, comment_1, open_wo_subset_only)
return
summary_row['open(1)'] = 'yes'
open_wo_subset_only = True
except:
traceback_file_url = generate_traceback_file(data_id, time_range, var_list, None)
_all_tests_no(summary_row, traceback_file_url, open_wo_subset_only)
return
try:
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Opening cube for data_id {data_id} with {var_list} '
f'and region {region} and time range {time_range}.')
cube = data_source.open_dataset(time_range=time_range, var_names=var_list, region=region)
summary_row['open(1)'] = 'yes'
open_wo_subset_only = False
except ValueError:
track = traceback.format_exc()
if 'Can not select a region outside dataset boundaries.' in track:
try:
region = '141.6, -18.7, 141.7, -18.6'
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Opening cube for data_id {data_id} with '
f'{var_list} and region {region}.')
cube = data_source.open_dataset(time_range=time_range, var_names=var_list, region=region)
open_wo_subset_only = False
except:
traceback_file_url = generate_traceback_file(data_id, time_range, var_list, region)
_all_tests_no(summary_row, traceback_file_url, open_wo_subset_only)
return
else:
traceback_file_url = generate_traceback_file(data_id, time_range, var_list, region)
_all_tests_no(summary_row, traceback_file_url, open_wo_subset_only)
return
except IndexError:
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Index error happening at stage 2. for {data_id}')
traceback_file_url = generate_traceback_file(data_id, time_range, var_list, region)
_all_tests_no(summary_row, traceback_file_url, open_wo_subset_only)
return
except:
track = traceback.format_exc()
if 'does not seem to have any datasets in given time range' in track:
try:
time_range = (time_range[0], time_range[1] + timedelta(days=4))
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Opening cube for data_id {data_id} '
f'with {var_list}.')
cube = data_source.open_dataset(time_range=time_range, var_names=var_list, region=region)
open_wo_subset_only = False
except IndexError:
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Index error happening at stage 3. '
f'for {data_id}')
traceback_file_url = generate_traceback_file(data_id, time_range, var_list, region)
_all_tests_no(summary_row, traceback_file_url, open_wo_subset_only)
return
except:
traceback_file_url = generate_traceback_file(data_id, time_range, var_list, region)
_all_tests_no(summary_row, traceback_file_url, open_wo_subset_only)
return
else:
traceback_file_url = generate_traceback_file(data_id, time_range, var_list, region)
_all_tests_no(summary_row, traceback_file_url, open_wo_subset_only)
return
vars_in_cube = []
for var in var_list:
if var in cube.data_vars:
vars_in_cube.append(var)
if len(vars_in_cube) == 0:
comment_1 = f'Requested variables {var_list} for subset are not in dataset.'
_all_tests_no(summary_row, comment_1, open_wo_subset_only)
return
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Checking cube for data_id {data_id} for processing.')
summary_row, comment_1 = check_for_processing(cube, summary_row, time_range)
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Checking cube for data_id {data_id} for visualization.')
summary_row, comment_3 = check_for_visualization(cube, summary_row, var_list)
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Closing cube for data_id {data_id}')
cube.close()
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Checking cube {data_id} for writing to disk.')
summary_row, comment_2 = check_write_to_disc(summary_row, comment_2, data_source, time_range, var_list, region, lds)
if comment_1 and (comment_1 == comment_3):
summary_row['comment'] = f'{comment_1}'
else:
if comment_1:
if comment_1 == comment_2 == comment_3:
summary_row['comment'] = f'{comment_1}'
else:
comment_1 = f'(1) {comment_1}; '
if comment_2:
comment_2 = f'(2) {comment_2}; '
if comment_3:
comment_3 = f'(3) {comment_3}; '
summary_row['comment'] = f'{comment_1} {comment_2} {comment_3}'
update_csv(results_csv, header_row, summary_row)
def generate_traceback_file(data_id, time_range, var_list, region):
dir_for_traceback = f'error_traceback/{datetime.date(datetime.now())}'
if not os.path.exists(dir_for_traceback):
os.mkdir(dir_for_traceback)
traceback_file = f'{dir_for_traceback}/{data_id}.txt'
with open(traceback_file, 'a') as trace_f:
trace_f.write(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Request: \n'
f'data_source.open_dataset(time_range={time_range}, var_names={var_list}, region={region})\n')
trace_f.write('\n')
trace_f.write(traceback.format_exc())
traceback_file_url = f'https://github.com/CCI-Tools/cate-e2e/blob/master/testing-cci-datasets/{traceback_file}'
return traceback_file_url
def sort_csv(input_csv, output_csv):
with open(input_csv, 'r', newline='') as f_input:
csv_input = csv.DictReader(f_input)
data = sorted(csv_input, key=lambda row: (row['Dataset-ID']))
with open(output_csv, 'w', newline='') as f_output:
csv_output = csv.DictWriter(f_output, fieldnames=csv_input.fieldnames)
csv_output.writeheader()
csv_output.writerows(data)
# creating summary csv
def read_all_result_rows(path, header_row):
test_data_sets_list = []
with open(path) as csvfile:
reader = csv.DictReader(csvfile, fieldnames=header_row, delimiter=',')
firstline = True
for row in reader:
if firstline: # skip first line
firstline = False
continue
test_data_sets_list.append(row)
return test_data_sets_list
def get_list_of_ecvs(data_sets):
ecvs = []
for dataset in data_sets:
if dataset['ECV-Name'] in ecvs:
continue
else:
ecvs.append(dataset['ECV-Name'])
ecvs.append('ALL_ECVS')
return ecvs
def count_success_fail(data_sets, ecv):
supported = 0
not_supported = 0
open_success = 0
open_fail = 0
open_bbox_success = 0
open_bbox_fail = 0
cache_success = 0
cache_fail = 0
visualize_success = 0
visualize_fail = 0
if 'ALL_ECVS' not in ecv:
for dataset in data_sets:
if ecv in dataset['ECV-Name']:
if 'yes' in dataset['supported']:
supported += 1
if 'yes' in dataset['open(1)']:
open_success += 1
else:
open_fail += 1
if 'yes' in dataset['open_bbox(2)']:
open_bbox_success += 1
else:
open_bbox_fail += 1
if 'yes' in dataset['cache(3)']:
cache_success += 1
else:
cache_fail += 1
if 'yes' in dataset['map(4)']:
visualize_success += 1
else:
visualize_fail += 1
else:
not_supported += 1
total_number_of_datasets = sum([supported, not_supported])
else:
for dataset in data_sets:
if 'yes' in dataset['supported']:
supported += 1
if 'yes' in dataset['open(1)']:
open_success += 1
else:
open_fail += 1
if 'yes' in dataset['open_bbox(2)']:
open_bbox_success += 1
else:
open_bbox_fail += 1
if 'yes' in dataset['cache(3)']:
cache_success += 1
else:
cache_fail += 1
if 'yes' in dataset['map(4)']:
visualize_success += 1
else:
visualize_fail += 1
else:
not_supported += 1
total_number_of_datasets = len(data_sets)
supported_percentage = 100 * supported / total_number_of_datasets
open_success_percentage = 100 * open_success / (total_number_of_datasets - not_supported)
open_bbox_success_percentage = 100 * open_bbox_success / (total_number_of_datasets - not_supported)
visualize_success_percentage = 100 * visualize_success / (total_number_of_datasets - not_supported)
cache_success_percentage = 100 * cache_success / (total_number_of_datasets - not_supported)
summary_row_new = {'ecv': ecv,
'supported': supported,
'open_success': open_success,
'open_fail': open_bbox_fail,
'open_bbox_success': open_bbox_success,
'open_bbox_fail': open_fail,
'cache_success': cache_success,
'cache_fail': cache_fail,
'visualize_success': visualize_success,
'visualize_fail': visualize_fail,
'supported_percentage': supported_percentage,
'open_success_percentage': open_success_percentage,
'open_bbox_success_percentage': open_bbox_success_percentage,
'visualize_success_percentage': visualize_success_percentage,
'cache_success_percentage': cache_success_percentage,
'total_number_of_datasets': total_number_of_datasets
}
return summary_row_new
def create_list_of_failed(test_data_sets, failed_csv, header_row):
for dataset in test_data_sets:
if dataset['supported'] == 'yes' and (dataset['open(1)'] == 'no' or
dataset['open_bbox(2)'] == 'no' or
dataset['cache(3)'] == 'no' or
dataset['map(4)'] == 'no'):
update_csv(failed_csv, header_row, dataset)
def create_dict_of_ids_with_verification_flags(data_sets):
dict_with_verify_flags = {}
for dataset in data_sets:
verify_flags = []
if 'yes' in dataset['open(1)']:
verify_flags.append('open')
if 'yes' in dataset['open_bbox(2)']:
verify_flags.append('open_bbox')
if 'yes' in dataset['cache(3)']:
verify_flags.append('cache')
if 'yes' in dataset['map(4)']:
verify_flags.append('map')
dict_with_verify_flags[dataset['Dataset-ID']] = {'verification_flags': verify_flags}
return dict_with_verify_flags
def main():
store = DATA_STORE_REGISTRY.get_data_store('esa_cci_odp_os')
data_sets = store.query()
lds = DATA_STORE_REGISTRY.get_data_store('local')
start_time = datetime.now()
with mp.Pool(mp.cpu_count() - 1, maxtasksperchild=1) as pool:
pool.starmap(test_open_ds, zip(data_sets, repeat(store), repeat(lds)))
pool.close()
pool.join()
sort_csv(results_csv, f'sorted_{results_csv}')
test_data_sets = read_all_result_rows(f'sorted_{results_csv}', header_row)
ecvs = get_list_of_ecvs(test_data_sets)
failed_csv = f'failed_{results_csv}'
create_list_of_failed(test_data_sets, failed_csv, header_row)
sort_csv(failed_csv, f'sorted_{failed_csv}')
with open(results_csv, 'r', newline='') as f_input:
csv_input = csv.DictReader(f_input)
data = sorted(csv_input, key=lambda row: (row['Dataset-ID']))
with open(f'sorted_{results_csv}', 'w', newline='') as f_output:
csv_output = csv.DictWriter(f_output, fieldnames=csv_input.fieldnames)
csv_output.writeheader()
csv_output.writerows(data)
summary_csv = f'summary_sorted_{results_csv}'
header_summary = ['ecv', 'supported', 'open_success', 'open_fail', 'open_bbox_success', 'open_bbox_fail',
'cache_success', 'cache_fail', 'visualize_success',
'visualize_fail', 'supported_percentage', 'open_success_percentage',
'open_bbox_success_percentage',
'cache_success_percentage',
'visualize_success_percentage', 'total_number_of_datasets']
for ecv in ecvs:
results_summary_row = count_success_fail(test_data_sets, ecv)
update_csv(summary_csv, header_summary, results_summary_row)
dict_with_verify_flags = create_dict_of_ids_with_verification_flags(test_data_sets)
with open(f'DrsID_verification_flags_{datetime.date(datetime.now())}.json', 'w') as f:
json.dump(dict_with_verify_flags, f, indent=4)
if os.path.exists(results_csv):
os.remove(results_csv)
else:
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] The file {results_csv} does not exist.')
if os.path.exists(failed_csv):
os.remove(failed_csv)
else:
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] The file {failed_csv} does not exist.')
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Test run finished on {datetime.date(datetime.now())}.')
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Test run took {datetime.now() - start_time}')
if __name__ == '__main__':
main()
|
[
"os.mkdir",
"os.remove",
"numpy.sum",
"random.choices",
"os.path.isfile",
"sys.exc_info",
"csv.DictWriter",
"multiprocessing.cpu_count",
"cate.core.ds.open_dataset",
"os.path.exists",
"datetime.timedelta",
"traceback.format_exc",
"cate.core.DATA_STORE_REGISTRY.get_data_store",
"signal.alarm",
"nest_asyncio.apply",
"datetime.datetime.now",
"json.dump",
"csv.writer",
"csv.DictReader",
"signal.signal",
"itertools.repeat",
"random.choice"
] |
[((330, 350), 'nest_asyncio.apply', 'nest_asyncio.apply', ([], {}), '()\n', (348, 350), False, 'import nest_asyncio\n'), ((3313, 3357), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'alarm_handler'], {}), '(signal.SIGALRM, alarm_handler)\n', (3326, 3357), False, 'import signal\n'), ((3362, 3388), 'signal.alarm', 'signal.alarm', (['TIMEOUT_TIME'], {}), '(TIMEOUT_TIME)\n', (3374, 3388), False, 'import signal\n'), ((4306, 4321), 'signal.alarm', 'signal.alarm', (['(0)'], {}), '(0)\n', (4318, 4321), False, 'import signal\n'), ((4461, 4505), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'alarm_handler'], {}), '(signal.SIGALRM, alarm_handler)\n', (4474, 4505), False, 'import signal\n'), ((4510, 4536), 'signal.alarm', 'signal.alarm', (['TIMEOUT_TIME'], {}), '(TIMEOUT_TIME)\n', (4522, 4536), False, 'import signal\n'), ((5445, 5460), 'signal.alarm', 'signal.alarm', (['(0)'], {}), '(0)\n', (5457, 5460), False, 'import signal\n'), ((5634, 5678), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'alarm_handler'], {}), '(signal.SIGALRM, alarm_handler)\n', (5647, 5678), False, 'import signal\n'), ((5683, 5709), 'signal.alarm', 'signal.alarm', (['TIMEOUT_TIME'], {}), '(TIMEOUT_TIME)\n', (5695, 5709), False, 'import signal\n'), ((6934, 6949), 'signal.alarm', 'signal.alarm', (['(0)'], {}), '(0)\n', (6946, 6949), False, 'import signal\n'), ((22645, 22697), 'cate.core.DATA_STORE_REGISTRY.get_data_store', 'DATA_STORE_REGISTRY.get_data_store', (['"""esa_cci_odp_os"""'], {}), "('esa_cci_odp_os')\n", (22679, 22697), False, 'from cate.core import DATA_STORE_REGISTRY, ds\n'), ((22738, 22781), 'cate.core.DATA_STORE_REGISTRY.get_data_store', 'DATA_STORE_REGISTRY.get_data_store', (['"""local"""'], {}), "('local')\n", (22772, 22781), False, 'from cate.core import DATA_STORE_REGISTRY, ds\n'), ((22800, 22814), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (22812, 22814), False, 'from datetime import datetime, timedelta\n'), ((24638, 24665), 'os.path.exists', 'os.path.exists', (['results_csv'], {}), '(results_csv)\n', (24652, 24665), False, 'import os\n'), ((24822, 24848), 'os.path.exists', 'os.path.exists', (['failed_csv'], {}), '(failed_csv)\n', (24836, 24848), False, 'import os\n'), ((1879, 1928), 'csv.DictWriter', 'csv.DictWriter', (['write_obj'], {'fieldnames': 'field_names'}), '(write_obj, fieldnames=field_names)\n', (1893, 1928), False, 'import csv\n'), ((2127, 2154), 'os.path.isfile', 'os.path.isfile', (['results_csv'], {}), '(results_csv)\n', (2141, 2154), False, 'import os\n'), ((4872, 4911), 'cate.core.ds.open_dataset', 'ds.open_dataset', (['f"""local.{rand_string}"""'], {}), "(f'local.{rand_string}')\n", (4887, 4911), False, 'from cate.core import DATA_STORE_REGISTRY, ds\n'), ((16262, 16295), 'os.path.exists', 'os.path.exists', (['dir_for_traceback'], {}), '(dir_for_traceback)\n', (16276, 16295), False, 'import os\n'), ((16305, 16332), 'os.mkdir', 'os.mkdir', (['dir_for_traceback'], {}), '(dir_for_traceback)\n', (16313, 16332), False, 'import os\n'), ((16974, 16997), 'csv.DictReader', 'csv.DictReader', (['f_input'], {}), '(f_input)\n', (16988, 16997), False, 'import csv\n'), ((17146, 17203), 'csv.DictWriter', 'csv.DictWriter', (['f_output'], {'fieldnames': 'csv_input.fieldnames'}), '(f_output, fieldnames=csv_input.fieldnames)\n', (17160, 17203), False, 'import csv\n'), ((17419, 17480), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {'fieldnames': 'header_row', 'delimiter': '""","""'}), "(csvfile, fieldnames=header_row, delimiter=',')\n", (17433, 17480), False, 'import csv\n'), ((23410, 23433), 'csv.DictReader', 'csv.DictReader', (['f_input'], {}), '(f_input)\n', (23424, 23433), False, 'import csv\n'), ((23595, 23652), 'csv.DictWriter', 'csv.DictWriter', (['f_output'], {'fieldnames': 'csv_input.fieldnames'}), '(f_output, fieldnames=csv_input.fieldnames)\n', (23609, 23652), False, 'import csv\n'), ((24583, 24629), 'json.dump', 'json.dump', (['dict_with_verify_flags', 'f'], {'indent': '(4)'}), '(dict_with_verify_flags, f, indent=4)\n', (24592, 24629), False, 'import json\n'), ((24675, 24697), 'os.remove', 'os.remove', (['results_csv'], {}), '(results_csv)\n', (24684, 24697), False, 'import os\n'), ((24858, 24879), 'os.remove', 'os.remove', (['failed_csv'], {}), '(failed_csv)\n', (24867, 24879), False, 'import os\n'), ((543, 557), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (555, 557), False, 'from datetime import datetime, timedelta\n'), ((2234, 2250), 'csv.writer', 'csv.writer', (['file'], {}), '(file)\n', (2244, 2250), False, 'import csv\n'), ((3709, 3726), 'numpy.sum', 'np.sum', (['cube[var]'], {}), '(cube[var])\n', (3715, 3726), True, 'import numpy as np\n'), ((4631, 4668), 'random.choice', 'random.choice', (['string.ascii_lowercase'], {}), '(string.ascii_lowercase)\n', (4644, 4668), False, 'import random\n'), ((4670, 4701), 'random.choice', 'random.choice', (['string.octdigits'], {}), '(string.octdigits)\n', (4683, 4701), False, 'import random\n'), ((10120, 10175), 'random.choices', 'random.choices', (["data_source.meta_info['variables']"], {'k': '(2)'}), "(data_source.meta_info['variables'], k=2)\n", (10134, 10175), False, 'import random\n'), ((11885, 11907), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (11905, 11907), False, 'import traceback\n'), ((13162, 13184), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (13182, 13184), False, 'import traceback\n'), ((16691, 16713), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (16711, 16713), False, 'import traceback\n'), ((4283, 4297), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (4295, 4297), False, 'import sys\n'), ((5248, 5262), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (5260, 5262), False, 'import sys\n'), ((6911, 6925), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (6923, 6925), False, 'import sys\n'), ((16233, 16247), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (16245, 16247), False, 'from datetime import datetime, timedelta\n'), ((22832, 22846), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (22844, 22846), True, 'import multiprocessing as mp\n'), ((22931, 22944), 'itertools.repeat', 'repeat', (['store'], {}), '(store)\n', (22937, 22944), False, 'from itertools import repeat\n'), ((22946, 22957), 'itertools.repeat', 'repeat', (['lds'], {}), '(lds)\n', (22952, 22957), False, 'from itertools import repeat\n'), ((25093, 25107), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (25105, 25107), False, 'from datetime import datetime, timedelta\n'), ((25189, 25203), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (25201, 25203), False, 'from datetime import datetime, timedelta\n'), ((1494, 1508), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1506, 1508), False, 'from datetime import datetime, timedelta\n'), ((5139, 5153), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (5151, 5153), False, 'import sys\n'), ((5369, 5383), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (5381, 5383), False, 'import sys\n'), ((9148, 9162), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (9160, 9162), False, 'import sys\n'), ((14818, 14832), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (14830, 14832), False, 'from datetime import datetime, timedelta\n'), ((15014, 15028), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (15026, 15028), False, 'from datetime import datetime, timedelta\n'), ((15214, 15228), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (15226, 15228), False, 'from datetime import datetime, timedelta\n'), ((15329, 15343), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (15341, 15343), False, 'from datetime import datetime, timedelta\n'), ((24540, 24554), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (24552, 24554), False, 'from datetime import datetime, timedelta\n'), ((25010, 25024), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (25022, 25024), False, 'from datetime import datetime, timedelta\n'), ((25127, 25141), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (25139, 25141), False, 'from datetime import datetime, timedelta\n'), ((3621, 3635), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (3633, 3635), False, 'import sys\n'), ((4170, 4184), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (4182, 4184), False, 'import sys\n'), ((10634, 10648), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (10646, 10648), False, 'from datetime import datetime, timedelta\n'), ((11506, 11520), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (11518, 11520), False, 'from datetime import datetime, timedelta\n'), ((13341, 13358), 'datetime.timedelta', 'timedelta', ([], {'days': '(4)'}), '(days=4)\n', (13350, 13358), False, 'from datetime import datetime, timedelta\n'), ((16464, 16478), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (16476, 16478), False, 'from datetime import datetime, timedelta\n'), ((24726, 24740), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (24738, 24740), False, 'from datetime import datetime, timedelta\n'), ((24908, 24922), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (24920, 24922), False, 'from datetime import datetime, timedelta\n'), ((3749, 3763), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3761, 3763), False, 'from datetime import datetime, timedelta\n'), ((12854, 12868), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (12866, 12868), False, 'from datetime import datetime, timedelta\n'), ((12080, 12094), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (12092, 12094), False, 'from datetime import datetime, timedelta\n'), ((13386, 13400), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (13398, 13400), False, 'from datetime import datetime, timedelta\n'), ((13720, 13734), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (13732, 13734), False, 'from datetime import datetime, timedelta\n')]
|
import numpy as np
import pandas as pd
from perceptron import MLP
import seaborn as sns
import matplotlib.pyplot as plt
if __name__ == "__main__":
# create a dataset to train and test a network
x_train = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
y_train = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
# create a Multilayer Perceptron with one hidden layer
mlp = MLP(4, [2], 4, bias=False)
# train network
x = mlp.train(x_train, y_train, 1, 0.2, verbose=True)
# plot a MSE for each outputs and avg output
mlp.plot_mse('example_plot')
# plot activations on hidden layer each training session
list_epochs = [i+1 for i in range(1000)]
df_hidden = pd.DataFrame(mlp.hidden_activates, columns=['1 neuron', '2 neuron'])
df_epoch = pd.DataFrame(list_epochs, columns=['epochs'])
df = pd.concat([df_epoch, df_hidden], axis=1)
plt.clf()
sns.lineplot(x='epochs', y='value', hue='variable',
data=pd.melt(df, ['epochs']),legend=False)
plt.legend(title = "Hidden_layer")
plt.savefig('hidden.png')
# get first prediction
x_test = np.array([1, 0, 0, 0])
outputs = mlp.predict(x_test)
print("Network believes that is equal to {}".format(outputs))
x_test = np.array([0, 1, 0, 0])
# get second prediction
outputs = mlp.predict(x_test)
print("Network believes that is equal to {}".format(outputs))
x_test = np.array([0, 0, 1, 0])
# get third prediction
outputs = mlp.predict(x_test)
print("Network believes that is equal to {}".format(outputs))
x_test = np.array([0, 0, 0, 1])
# get fourth prediction
outputs = mlp.predict(x_test)
print("Network believes that is equal to {}".format(outputs))
|
[
"pandas.DataFrame",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.legend",
"numpy.array",
"pandas.melt",
"perceptron.MLP",
"pandas.concat",
"matplotlib.pyplot.savefig"
] |
[((219, 285), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n', (227, 285), True, 'import numpy as np\n'), ((300, 366), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n', (308, 366), True, 'import numpy as np\n'), ((437, 463), 'perceptron.MLP', 'MLP', (['(4)', '[2]', '(4)'], {'bias': '(False)'}), '(4, [2], 4, bias=False)\n', (440, 463), False, 'from perceptron import MLP\n'), ((748, 816), 'pandas.DataFrame', 'pd.DataFrame', (['mlp.hidden_activates'], {'columns': "['1 neuron', '2 neuron']"}), "(mlp.hidden_activates, columns=['1 neuron', '2 neuron'])\n", (760, 816), True, 'import pandas as pd\n'), ((832, 877), 'pandas.DataFrame', 'pd.DataFrame', (['list_epochs'], {'columns': "['epochs']"}), "(list_epochs, columns=['epochs'])\n", (844, 877), True, 'import pandas as pd\n'), ((887, 927), 'pandas.concat', 'pd.concat', (['[df_epoch, df_hidden]'], {'axis': '(1)'}), '([df_epoch, df_hidden], axis=1)\n', (896, 927), True, 'import pandas as pd\n'), ((932, 941), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (939, 941), True, 'import matplotlib.pyplot as plt\n'), ((1059, 1091), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""Hidden_layer"""'}), "(title='Hidden_layer')\n", (1069, 1091), True, 'import matplotlib.pyplot as plt\n'), ((1098, 1123), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""hidden.png"""'], {}), "('hidden.png')\n", (1109, 1123), True, 'import matplotlib.pyplot as plt\n'), ((1169, 1191), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (1177, 1191), True, 'import numpy as np\n'), ((1305, 1327), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (1313, 1327), True, 'import numpy as np\n'), ((1470, 1492), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '([0, 0, 1, 0])\n', (1478, 1492), True, 'import numpy as np\n'), ((1634, 1656), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (1642, 1656), True, 'import numpy as np\n'), ((1017, 1040), 'pandas.melt', 'pd.melt', (['df', "['epochs']"], {}), "(df, ['epochs'])\n", (1024, 1040), True, 'import pandas as pd\n')]
|
from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7
# Importing the base class
from co_simulation_base_io import CoSimulationBaseIO
# Other imports
import numpy as np
import co_simulation_tools as cs_tools
def Create(solvers, solver_name, level):
return SDoFIO(solvers, solver_name, level)
class SDoFIO(CoSimulationBaseIO):
def ImportData(self, data_settings, from_client):
data_name = data_settings["data_name"]
io_settings = data_settings["io_settings"]
data_array = np.array([])
cs_tools.ImportArrayFromSolver(from_client, data_name, data_array)
sdof_solver = self.solvers[self.solver_name]
sdof_data_settings = sdof_solver.GetDataDefinition(data_settings["data_name"])
value = sum(data_array)
if "io_options" in io_settings:
if "swap_sign" in io_settings["io_options"]:
value *= -1.0
data_identifier = sdof_data_settings["data_identifier"]
sdof_solver.SetData(data_identifier, value)
def ExportData(self, data_settings, to_client):
sdof_solver = self.solvers[self.solver_name]
sdof_data_settings = sdof_solver.GetDataDefinition(data_settings["data_name"])
sdof_data_settings["data_name"] = data_settings["data_name"]
if not sdof_data_settings["data_format"] == "scalar_value":
raise Exception('SDoFIO can only handle scalar values')
sdof_solver = self.solvers[self.solver_name]
data_identifier = sdof_data_settings["data_identifier"]
x = sdof_solver.GetData(data_identifier)
sdof_data_settings["scalar_value"] = x
to_client.ImportData(sdof_data_settings, to_client)
|
[
"co_simulation_tools.ImportArrayFromSolver",
"numpy.array"
] |
[((586, 598), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (594, 598), True, 'import numpy as np\n'), ((607, 673), 'co_simulation_tools.ImportArrayFromSolver', 'cs_tools.ImportArrayFromSolver', (['from_client', 'data_name', 'data_array'], {}), '(from_client, data_name, data_array)\n', (637, 673), True, 'import co_simulation_tools as cs_tools\n')]
|
import copy
import itertools
import seaborn as sns
import glob
import os
import math
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import imutils
import numpy as np
from pre_processing import Pre_Processing
import cv2
import scipy.special
import time
import matplotlib
vehicle_info = "vehicle_info"
class Car():
def __init__(self):
self.car_length, self.car_width, self.center_of_vehicles = list(), list(), list()
self.vehicles = dict()
self.vehicles["red"] = dict()
self.vehicles["blue"] = dict()
self.pre_process = Pre_Processing()
self.car_length = None
self.car_width = None
self.car_length_sim = None
self.height = None
self.width = None
self.show_image = None
self.output_folder = None
self.process_number = None
def getCarDimensions(self):
""" Return car length and car width"""
return (self.car_length, self.car_width)
def getImageDimensions(self):
""" Return heigth and width"""
return (self.height, self.width)
def edgesofTheCar(self, box_points, width_of_car):
# rect_points = list()
points_on_vehicle = box_points.tolist()
advance_points = list()
points_on_width = list()
x = list(range(4))
y = list(range(1,4))
y.append(0)
nodes_coverage = list(zip(x,y))
for i,j in nodes_coverage:
# print(box_points, box_points[i][0])
ed_edges = np.sqrt(np.square(np.array(box_points[j][0]) - np.array(box_points[i][0])) + np.square(np.array(box_points[j][1]) - np.array(box_points[i][1])))
# print("\n width_of_car ", width_of_car)
# print("ed edges of the car ", ed_edges)
if(ed_edges > width_of_car * 1.1):
""" We need to find three points on the side of a vehicle """
mid_point = [(int(box_points[i][0]) + int(box_points[j][0])) // 2, (int(box_points[i][1]) + int(box_points[j][1])) // 2]
mid_point_1 = [(int(mid_point[0]) + int(box_points[i][0])) // 2, (int(mid_point[1]) + int(box_points[i][1])) // 2]
mid_point_2 = [(int(mid_point[0]) + int(box_points[j][0])) // 2, (int(mid_point[1]) + int(box_points[j][1])) // 2]
advance_points.extend([mid_point_1, mid_point_2])
else:
mid_point = [(int(box_points[i][0]) + int(box_points[j][0])) // 2, (int(box_points[i][1]) + int(box_points[j][1])) // 2]
points_on_width.append(mid_point)
# rect_points.append(mid_point)
points_on_vehicle.append(mid_point)
# last_midpoint_point = [(int(box_points[0][0]) + int(box_points[-1][0])) // 2, (int(box_points[0][1]) + int(box_points[-1][1])) // 2]
# points_on_vehicle.append(last_midpoint_point)
points_on_vehicle.extend(advance_points)
return points_on_vehicle, points_on_width
def extractVehicleContoursFromMask(self):
for vehicle_color in self.vehicles:
contours, hierarchy = cv2.findContours(self.vehicles[vehicle_color]["mask"].copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
self.vehicles[vehicle_color]["contour"] = contours
# print(len(self.vehicles[vehicle_color]["contour"]), hierarchy)
self.vehicles[vehicle_color].pop('mask', None)
def geometricOperationOnVehicle(self, image, time_efficiency):
""" Finds number of things related to the vehicles:
1. min_area_rect (OBB == Object Oriented Bounding Box)(returns the center, (width, height), angle)
2. center_of_car (center of vehicle in image)
3. angle_of_rect (orientation of rectangle in image)
4. vehicle_nodes (8 points on vehicle including box_points)
5. car_length
6. car_width
Args:
vehicles ([dictionary]): [information about vehicles]
"""
c_length, c_width, center_of_vehicles = list(), list(), list()
vehicle_info = "vehicle_info"
t0 = time.time()
print("\n------- Vehicle Extraction Pipeline ------")
print("\n------- Extracting Geometric Information of vehicles ------")
for vehicle_color in self.vehicles:
print("\n{} Vehicle \n".format(str.capitalize((vehicle_color))))
self.vehicles[vehicle_color][vehicle_info] = dict()
count_id = 0
for i, contour in enumerate(self.vehicles[vehicle_color]["contour"]):
# print ("Vehicle {} # {}, Shape = {}, Area = {}, Arc_Length = {} ".format(vehicle_color, i, contour.shape,
# cv2.contourArea(contour), cv2.arcLength(contour, closed=False)))
print ("Vehicle {} # {}, Area = {}, Arc_Length = {} ".format(vehicle_color, i,
cv2.contourArea(contour), cv2.arcLength(contour, closed=False)))
if cv2.contourArea(contour) > 60:
self.vehicles[vehicle_color][vehicle_info][str(count_id)] = dict()
self.vehicles[vehicle_color]["dimensions"] = dict()
M = cv2.moments(contour)
# self.vehicles[vehicle_color]["moments"] = M
# print("Moments of contour are = ", M)
# mid_x = M["m10"] / M["m00"]
# mid_y = M["m01"] / M["m00"]
# self.vehicles["blue"]["center_of_car"] = (mid_x, mid_y)
# print("vehicles center_of_car = ", self.vehicles["blue"]["center_of_car"])
x, y, width, height = cv2.boundingRect(contour)
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
img = cv2.polylines(image.copy(), [box], True, (0,255,0), 2)
temp_img = cv2.rectangle(image.copy(), (x,y), (x + width, y + height), (0,204,255), 2)
# temp_img = cv2.line(image.copy(), tuple([box[1][0], box[1][1]]), tuple([box[2][0], box[2][1]]), (128,128,128), 3)
# cv2.circle(img, tuple([int(rect[0][0]), int(rect[0][1])]), 5, (204, 0, 204), -1)
### cv2.norm(box[0] - box[1], cv2.NORM_L2)
## square_root((x2-x1)**2 + (y2-y1)**2)
dist_p_12 = math.sqrt(math.pow(int(round(box[0][0])) - int(round(box[1][0])), 2) + math.pow(int(round(box[0][1])) - int(round(box[1][1])), 2))
## square_root((x3-x2)**2 + (y3-y2)**2)
dist_p_23 = math.sqrt(math.pow(int(round(box[1][0])) - int(round(box[2][0])), 2) + math.pow(int(round(box[1][1])) - int(round(box[2][1])), 2))
c_length.append(max(dist_p_12, dist_p_23))
c_width.append(min(dist_p_12, dist_p_23))
center_of_vehicles.append((int(rect[0][0]), int(rect[0][1])))
vehicle_nodes, nodes_on_width = self.edgesofTheCar(box, min(dist_p_12, dist_p_23))
vehicle_center = ((box[0][0] + box[1][0] + box[2][0] + box[3][0]) / len(box),
(box[0][1] + box[1][1] + box[2][1] + box[3][1]) / len(box))
# cv2.circle(img, tuple([int(vehicle_center[0]), int(vehicle_center[1])]), 8, (0, 255, 255), -1)
# print(edgesofTheCar(box))
# print("vehicle_nodes array", np.array(vehicle_nodes))
self.vehicles[vehicle_color][vehicle_info][str(count_id)]["bounding_rect"] = cv2.boundingRect(contour)
self.vehicles[vehicle_color][vehicle_info][str(count_id)]["min_area_rect"] = rect
self.vehicles[vehicle_color][vehicle_info][str(count_id)]["center_of_car"] = (rect[0][0], rect[0][1]) # vehicle_center # /int(rect[0][0], int(rect[0][1]))
self.vehicles[vehicle_color][vehicle_info][str(count_id)]["angle_of_rect"] = rect[2]
self.vehicles[vehicle_color][vehicle_info][str(count_id)]["vehicle_nodes"] = vehicle_nodes
self.vehicles[vehicle_color][vehicle_info][str(count_id)]["nodes_on_width"] = nodes_on_width
""" Corner Points and Nodes of Vehicles """
# cv2.rectangle(img, (x, y),(x + width, y + height), (255, 255, 0), -1)
cv2.circle(img, tuple([int(vehicle_nodes[0][0]), int(vehicle_nodes[0][1])]), 5, (255, 255, 0), -1) ## Light Sky blue , Node 0
cv2.circle(img, tuple([int(vehicle_nodes[1][0]), int(vehicle_nodes[1][1])]), 5, (127, 0, 255), -1) ## Lipstic Pink , Node 1
cv2.circle(img, tuple([int(vehicle_nodes[2][0]), int(vehicle_nodes[2][1])]), 5, (255, 51, 153), -1) ## Purple color , Node 2
cv2.circle(img, tuple([int(vehicle_nodes[3][0]), int(vehicle_nodes[3][1])]), 5, (255, 0, 0), -1) ## Dark Blue , Node 3
cv2.circle(img, tuple([int(vehicle_nodes[4][0]), int(vehicle_nodes[4][1])]), 5, (50, 255, 255), -1) ## Yellow , Node 4 (Mid_0_1)
cv2.circle(img, tuple([int(vehicle_nodes[5][0]), int(vehicle_nodes[5][1])]), 5, (50, 255, 255), -1) ## Yellow , Node 5 (Mid_1_2)
cv2.circle(img, tuple([int(vehicle_nodes[6][0]), int(vehicle_nodes[6][1])]), 5, (50, 255, 255), -1) ## Yellow , Node 6 (Mid_2_3)
cv2.circle(img, tuple([int(vehicle_nodes[7][0]), int(vehicle_nodes[7][1])]), 5, (50, 255, 255), -1) ## Yellow , Node 7 (Mid_3_4)
cv2.circle(img, tuple([int(vehicle_nodes[8][0]), int(vehicle_nodes[8][1])]), 5, (0, 255, 0), -1) ## Green , Node 8 (Mid_4_1)
cv2.circle(img, tuple([int(vehicle_nodes[9][0]), int(vehicle_nodes[9][1])]), 5, (0, 255, 0), -1) ## Green , Node 9 (Mid_4_2)
cv2.circle(img, tuple([int(vehicle_nodes[10][0]), int(vehicle_nodes[10][1])]), 5, (0, 255, 0), -1) ## Green , Node 10 (Mid_7_3)
cv2.circle(img, tuple([int(vehicle_nodes[11][0]), int(vehicle_nodes[11][1])]), 5, (0, 255, 0), -1) ## Green , Node 11 (Mid_7_4)
count_id += 1
# print("vehicles center_of_car = {} \n".format(self.vehicles[vehicle_color][vehicle_info][str(count_id)]["center_of_car"]))
# if self.show_image:
# self.pre_process.showImage(" Axis Aligned Bounding Boxes Vs Oriented Bounding Boxes", np.hstack([temp_img, img]))
self.vehicles[vehicle_color].pop("contour", None)
# c_length.sort()
# c_width.sort()
# self.car_length = round(sum(c_length))
# self.car_width = round(c_width)
self.car_length = sum(c_length) / len(c_length)
self.car_width = sum(c_width) / len(c_length)
# self.car_length = round(min(c_length)) # round(max(c_length)),, default -> round(max(c_length))
# self.car_width = round(max(c_width))
for vehicle_color in self.vehicles:
self.vehicles[vehicle_color]["dimensions"]["car_length"] = self.car_length
self.vehicles[vehicle_color]["dimensions"]["car_length_sim"] = self.car_length_sim
self.vehicles[vehicle_color]["dimensions"]["car_width"] = self.car_width
t1 = time.time()
print("\n---- Dimensions of Vehicles -------\n")
print("car_length = ", self.car_length)
print("car_width = ", self.car_width)
if self.show_image:
self.pre_process.showImage("Axis Aligned Bounding Boxes Vs Oriented Bounding Boxes", np.hstack([temp_img, img]), time=800)
cv2.imwrite(self.output_folder + "{}_AABB_OBB.jpg".format(self.process_number), np.hstack([temp_img, img]))
self.process_number += 1
time_efficiency["calc_vehicle_nodes"] = t1-t0
# print("total time taken", t1-t0)
def extractingCrashPoint(self, image, time_efficiency):
""" Distance calculation between vehicles nodes and extracting the crash point """
t0 = time.time()
nodes_of_vehicles = [self.vehicles[vehicle_color]["vehicle_info"][str(v_id)]["vehicle_nodes"]
for vehicle_color in self.vehicles for v_id in self.vehicles[vehicle_color]["vehicle_info"]]
crash_ed_cal = list()
for vehicle1_nodes, vehicle2_nodes in itertools.combinations(nodes_of_vehicles, 2):
point_dist = list()
crash_img = image.copy()
for point_1 in vehicle1_nodes:
cv2.circle(crash_img, tuple(point_1), radius=3,
color=(0, 255, 0), thickness=-1)
for point_2 in vehicle2_nodes:
cv2.circle(crash_img, tuple(point_2), radius=3,
color=(255, 0, 0), thickness=-1)
crash_ed = cv2.norm(np.array(point_1) -
np.array(point_2), cv2.NORM_L2)
# print("crash_ed", crash_ed)
point_dist.append([crash_ed, point_1, point_2])
# print("point_dist", point_dist)
# cv2.imshow("crash point analyzation", crash_img)
# cv2.waitKey(50)
# cv2.destroyAllWindows()
# cv2.imshow("crash point analyzation", crash_img)
# cv2.waitKey(0)
crash_ed_cal.append(min(point_dist))
# print("crash euclidean distance calculation for the two vehicles", crash_ed_cal)
min_dist = min(crash_ed_cal)
crash_point = [(int(round(min_dist[1][0])) + int(round(min_dist[2][0]))) // 2,
(int(round(min_dist[1][1])) + int(round(min_dist[2][1]))) // 2]
for vehicle_color in self.vehicles:
self.vehicles[vehicle_color]["crash_point"] = dict()
self.vehicles[vehicle_color]["crash_point"]["coordinates"] = crash_point
self.vehicles[vehicle_color]["crash_point"]["dist_to_vehicle"] = min_dist[0]
t1 = time.time()
cv2.circle(crash_img, tuple(crash_point), 8, (0, 128, 255), -1)
# print("crash point = ", tuple(crash_point))
cv2.imwrite(self.output_folder + "{}_crash_point_visualization.jpg".format(self.process_number), crash_img)
self.process_number += 1
if self.show_image:
self.pre_process.showImage("crash point visualization", crash_img, time=800)
time_efficiency["calc_crash_pt"] = t1-t0
# print("total time taken", t1-t0)
return crash_point
def extractTriangle(self, image, time_efficiency):
"""
Triangle Extraction
"""
t0 = time.time()
for vehicle_color in self.vehicles:
for vehicle_id in self.vehicles[vehicle_color]['vehicle_info']:
test = np.zeros_like(image)
test_image = image #.copy()
x, y, w, h = self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]["bounding_rect"]
box_points = self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]["vehicle_nodes"][:4]
# ROI = image[y:y+h, x:x+w]
roi = cv2.fillPoly(test, np.array([box_points]), (255, 255, 255))
roi = cv2.bitwise_and(test_image, test_image, mask=roi[:,:,0])
# cv2.imshow("ROI", roi)
roi = cv2.bitwise_not(roi)
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.blur(gray, (3, 3), 0)
# cv2.threshold(blur, 10, 255, cv2.THRESH_BINARY)
_, thresh = cv2.threshold(blur, 15, 255, cv2.THRESH_BINARY)
thresh = cv2.bitwise_not(thresh)
# if self.show_image:
# cv2.imshow("gray", gray)
# cv2.imshow("blur", blur)
# cv2.imshow("thresh", thresh)
# cv2.imshow("after applying NOT ", thresh)
# cv2.waitKey(400)
# # kernel = np.zeros((4,4), np.uint8)
# # dilate = cv2.dilate(thresh, kernel)
# # dilate = cv2.bitwise_not(dilate)
# # rect_kernel = cv2.getStructuringElement( cv2.MORPH_RECT,(5,5))
# # dilate = cv2.dilate(thresh, rect_kernel )
cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnt = max(cnts, key=cv2.contourArea)
# print("number of selected contours", len(cnts))
# print("")
# print("contour shape ", cnt.shape)
# # peri = cv2.arcLength(contour, True)
# # approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
# # # if the shape is a triangle, it will have 3 vertices
# # print("len(approx)", len(approx))
# # if len(approx) == 3:
# # print("triangle")
rect = cv2.minAreaRect(cnt)
# print("mid values", tuple([int(rect[0][0]), int(rect[0][1])]))
# cv2.circle(img, tuple(self.vehicles[vehicle_color]["crash_point"]["coordinates"]), 5, (0, 128, 255), -1)
cv2.circle(test_image, (int(rect[0][0]), int(rect[0][1])), 2, (255, 128, 0), -1 )
self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]["triangle_position"] = tuple([int(rect[0][0]), int(rect[0][1])])
t1 = time.time()
cv2.destroyAllWindows()
cv2.imwrite(self.output_folder + "{}_triangle_extraction.jpg".format(self.process_number), test_image)
self.process_number += 1
time_efficiency["tri_ext"] = t1-t0
# print("total time taken", t1-t0)
def pointNearNodes(self, nodes, point):
distances = np.sqrt(np.square(nodes[:, 0] - point[0]) + np.square(nodes[:, 1] - point[1]))
distances = distances.reshape(distances.shape[0], -1)
dist_nodes = np.hstack((distances, nodes))
near_nodes = dist_nodes[dist_nodes[:, 0].argsort()]
return near_nodes
def extractingAnglesForVehicles(self, image, time_efficiency):
t0 = time.time()
print("\n-------- Extracting Angle of Vehicles -------\n")
for vehicle_color in self.vehicles:
print("{} Vehicle".format(str.capitalize(vehicle_color)))
for vehicle_id in self.vehicles[vehicle_color]["vehicle_info"]:
points_along_width = np.asarray(self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["nodes_on_width"], np.int32)
box = self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["vehicle_nodes"][:4]
triangle_position = np.asarray(self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["triangle_position"], np.int32)
nodes_near_triangle = self.pointNearNodes(points_along_width, triangle_position)
nodes_near_triangle = nodes_near_triangle[:,1:]
point_1 = nodes_near_triangle[1]
point_2 = nodes_near_triangle[0]
x = [round(point_1[0]), round(point_2[0])]
y = [round(point_1[1]), round(point_2[1])]
dy = y[1] - y[0]
dx = x[1] - x[0]
rads = math.atan2(dy,dx)
angle_of_vehicle = math.degrees(rads)
## Extrapolation based on the angle extracted
length = 25
extrap_point_x = int(round(point_2[0] + length * 1.1 * math.cos(angle_of_vehicle * np.pi / 180.0)))
extrap_point_y = int(round(point_2[1] + length * 1.1 * math.sin(angle_of_vehicle * np.pi / 180.0)))
cv2.line(image, tuple( [int(point_2[0]), int(point_2[1])]), tuple([extrap_point_x, extrap_point_y]), (255, 255, 0), 2) # (0, 100, 255)
### Orientation vehicle based on angle computed using position of the triangle
angle_of_vehicle = (-angle_of_vehicle if angle_of_vehicle < 0 else ( -angle_of_vehicle + 360 ))
print("V{}, Angle = {} ".format(vehicle_id, angle_of_vehicle))
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["angle_of_car"] = angle_of_vehicle
# cv2.polylines(image, np.array([box]), True, (36, 255, 12), 3)
# cv2.imshow("Angles For Vehicles", image)
# cv2.waitKey(0)
t1 = time.time()
if self.show_image:
self.pre_process.showImage("Angles For Vehicles", image, time=800)
cv2.imwrite(self.output_folder + "{}_angles_for_vehicles.jpg".format(self.process_number), image)
self.process_number += 1
time_efficiency["angle_cal"] = t1-t0
# print("total time taken", t1-t0)
def settingVehiclesInfo(self, v_color, vehicle_dist_pivot):
del self.vehicles[v_color]["vehicle_info"]
self.vehicles[v_color]["vehicle_info"] = dict()
print("\n Arranging the snapshots for {} vehicle in order".format(v_color))
for v_id in range(len(vehicle_dist_pivot)):
# print("vehicle number =", v_id)
self.vehicles[v_color]["vehicle_info"][str(v_id)] = vehicle_dist_pivot[int(v_id)][2]
def extractVehicleProjectedSide(self, v_color, side):
orient_count = 0
side_name = side[0]
side_value = np.array(side[1])
oriented_vehicles = list()
for v_id in self.vehicles[v_color]["vehicle_info"]:
# print(v_id, "angle of the car ", round(vehicles[v_color]["vehicle_info"][v_id]["angle_of_car"]))
veh_angle = self.vehicles[v_color]["vehicle_info"][v_id]["angle_of_car"]
points_along_width = np.asarray(self.vehicles[v_color]["vehicle_info"][v_id]["nodes_on_width"], np.int32)
triangle_position = np.asarray(self.vehicles[v_color]["vehicle_info"][v_id]["triangle_position"], np.int32)
nodes_near_triangle = self.pointNearNodes(points_along_width, triangle_position)
nodes_near_triangle = nodes_near_triangle[:, 1:]
front_point = nodes_near_triangle[0]
dx = side_value[:, 0] - front_point[0]
dy = side_value[:, 1] - front_point[1]
projected_angles = np.arctan2(dy, dx)
projected_angles = projected_angles * 180 / np.pi
side_results = [-round(angle) if angle < 0 else (-round(angle) + 360) for angle in projected_angles ]
# print(side_results)
# print("vehicle's angle exist on the projected side", side_name, "= ", round(veh_angle) in side_results)
if round(veh_angle) in side_results:
print("V{} is oriented towards the projected side = {}".format(v_id, side_name))
oriented_vehicles.append(v_id)
orient_count += 1
return orient_count, oriented_vehicles
def extractLeastDistanceVehicle(self, v_color):
side_dist_calc = list()
### Least distant vehicle from the frame of the image
for v_id in self.vehicles[v_color]["vehicle_info"]:
waypoint_of_vehicle = self.vehicles[v_color]["vehicle_info"][v_id]["center_of_car"]
Dy_min = cv2.norm(np.array(waypoint_of_vehicle) - np.array([waypoint_of_vehicle[0], 0]), cv2.NORM_L2) ## Top
Dx_min = cv2.norm(np.array(waypoint_of_vehicle) - np.array([0, waypoint_of_vehicle[1]]), cv2.NORM_L2) ## Left
Dy_max = cv2.norm(np.array(waypoint_of_vehicle) - np.array([waypoint_of_vehicle[0], self.height]), cv2.NORM_L2) ## Bottom
Dx_max = cv2.norm(np.array(waypoint_of_vehicle) - np.array([self.width, waypoint_of_vehicle[1]]), cv2.NORM_L2) ## Right
self.vehicles[v_color]["vehicle_info"][v_id]["distance_from_boundary"] = min([(Dy_min, "top"), (Dx_min, "left"), (Dy_max, "bottom"), (Dx_max, "right")])
side_dist_calc.append(self.vehicles[v_color]["vehicle_info"][v_id]["distance_from_boundary"])
print("V{}, min distance from sketch boundary = {}".format(v_id , self.vehicles[v_color]["vehicle_info"][v_id]["distance_from_boundary"]))
print("V{} has the least distance from sketch boundary".format(side_dist_calc.index(min(side_dist_calc))))
least_distant = str(side_dist_calc.index(min(side_dist_calc)))
self.vehicles[v_color]["least_distant_vehicle"] = self.vehicles[v_color]["vehicle_info"][least_distant]
return least_distant, side_dist_calc
def sideDistances(self, v_color, v_id, projected_side):
waypoint_of_vehicle = self.vehicles[v_color]["vehicle_info"][v_id]["center_of_car"]
if projected_side == "TOP":
dist = cv2.norm(np.array(waypoint_of_vehicle) - np.array([waypoint_of_vehicle[0], 0]), cv2.NORM_L2) ## Top
elif projected_side == "LEFT":
dist = cv2.norm(np.array(waypoint_of_vehicle) - np.array([0, waypoint_of_vehicle[1]]), cv2.NORM_L2) ## Left
elif projected_side == "BOTTOM":
dist = cv2.norm(np.array(waypoint_of_vehicle) - np.array([waypoint_of_vehicle[0], self.height]), cv2.NORM_L2) ## Bottom
elif projected_side == "RIGHT":
dist = cv2.norm(np.array(waypoint_of_vehicle) - np.array([self.width, waypoint_of_vehicle[1]]), cv2.NORM_L2) ## Right
else:
None
return dist
def distanceFromInitialVehicle(self, v_color, initial_vehicle):
dist_from_pivot = list()
for v_id in self.vehicles[v_color]["vehicle_info"]:
init_vehicle_center = initial_vehicle[2]['center_of_car']
vehicle_center = self.vehicles[v_color]["vehicle_info"][v_id]["center_of_car"]
# print("initial vehicle center", init_vehicle_center)
# print("vehicle_center", vehicle_center)
dist = cv2.norm(np.array(vehicle_center) - np.array(init_vehicle_center), cv2.NORM_L2)
dist_from_pivot.append([dist, v_id, self.vehicles[v_color]["vehicle_info"][v_id]])
dist_from_pivot = np.array(dist_from_pivot)
dist_from_pivot = dist_from_pivot[dist_from_pivot[:, 0].argsort()].tolist()
return dist_from_pivot
def extractSideDistanceOfVehicles(self, v_color, projected_side, orien_veh_ids):
project_dist = list()
dist_from_pivot = list()
if orien_veh_ids:
for v_id in self.vehicles[v_color]["vehicle_info"].keys():
dist = self.sideDistances(v_color, v_id, projected_side)
project_dist.append([dist, v_id, self.vehicles[v_color]["vehicle_info"][v_id]])
project_dist = np.array(project_dist)
initial_vehicle = project_dist[project_dist[:, 0].argsort()][-1]
dist_from_pivot = self.distanceFromInitialVehicle(v_color, initial_vehicle)
else:
for v_id in self.vehicles[v_color]["vehicle_info"]:
dist = self.sideDistances(v_color, v_id, projected_side)
dist_from_pivot.append([dist, v_id, self.vehicles[v_color]["vehicle_info"][v_id]])
return dist_from_pivot
def generateSequenceOfMovements(self, image, time_efficiency):
""" Extracting the sequence of movements of vehicles and aligning them from start to crash point and beyond """
h, w = image.shape[:2]
range_w = list(range(0, w))
range_h = list(range(0, h))
## The frame of the image is splitted into section and used to create a point of reference to calculate the sequence of movement
h_top = [0] * len(range_w)
TOP = list(zip(range_w, h_top))
h_bottom = [h] * len(range_w)
BOTTOM = list(zip(range_w, h_bottom))
w_left = [0] * len(range_h)
LEFT = list(zip(w_left, range_h))
w_right = [w] * len(range_h)
RIGHT = list(zip(w_right, range_h))
enviro_frame = {"TOP": TOP,
"BOTTOM": BOTTOM,
"LEFT": LEFT,
"RIGHT": RIGHT}
t0 = time.time()
print("\n--------- Extracting the Sequence of Movements of vehicles ----------")
for v_color in self.vehicles:
vehicle_dist_pivot = list()
print("\n------ {} Vehicle -----".format(str.capitalize(v_color)))
### Least distant vehicle from the frame of the image
least_distant, side_dist_calc = self.extractLeastDistanceVehicle(v_color)
# print("side_dist_calc", side_dist_calc)
vehicles_projection = list()
for side in enviro_frame.items():
orient_count, oriented_vehicles = self.extractVehicleProjectedSide(v_color, side)
vehicles_projection.append([orient_count, side[0], oriented_vehicles])
vehicles_projection = np.array(vehicles_projection)
veh_proj_counts = vehicles_projection[vehicles_projection[:, 0].argsort()][-2:]
## last vehicles projected side snapshot count is greater than the second last vehicle, if not then switch to distance based calculation.
if veh_proj_counts[-1][0] > veh_proj_counts[-2][0]:
veh_proj_side = vehicles_projection[vehicles_projection[:, 0].argsort()][-1][1]
print("Final Projected Side = ", veh_proj_side)
print("oriented vehicles", vehicles_projection)
# proj_dist_veh = np.array(self.extractSideDistanceOfVehicles(
# v_color, veh_proj_side, vehicles_projection[vehicles_projection[:, 0].argsort()][-1][2]))
proj_dist_veh = np.array(self.extractSideDistanceOfVehicles(v_color, veh_proj_side, True))
else:
veh_proj_side = str.upper(self.vehicles[v_color]["vehicle_info"][least_distant]["distance_from_boundary"][1])
proj_dist_veh = np.array(self.extractSideDistanceOfVehicles(v_color, veh_proj_side, False))
proj_dist_veh = proj_dist_veh[proj_dist_veh[:, 0].argsort()] #[::-1]
print([proj_dist_veh[:,:2]])
print("Starting Vehicle Index (ID) = ", proj_dist_veh[0][1])
start_veh_id = proj_dist_veh[0][1] # proj_dist_veh[-1][1]
self.vehicles[v_color]["initial_vehicle"] = self.vehicles[v_color]["vehicle_info"][start_veh_id]
init_veh_center = self.vehicles[v_color]["initial_vehicle"]['center_of_car']
cv2.circle(image, (int(init_veh_center[0]), int(init_veh_center[1]) ), radius=5, color=(255, 255, 0), thickness=-1)
self.settingVehiclesInfo(v_color, proj_dist_veh.tolist())
# print(proj_dist_veh)
t1 = time.time()
### Annotating the boxpoints and the arranging the sequences
for vehicle_color in self.vehicles:
for i, vehicle_id in enumerate(self.vehicles[vehicle_color]["vehicle_info"]):
box = self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["vehicle_nodes"][:4]
# print("angle of the car ", self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["angle_of_car"])
center_x, center_y = ((box[0][0] + box[1][0] + box[2][0] + box[3][0]) // 4, (box[0][1] + box[1][1] + box[2][1] + box[3][1]) // 4)
# cv2.circle(image, (center_x, center_y), radius = 12 - 2*i , color = (255, 255, 0), thickness = -1)
cv2.putText(image, str(i), (center_x - 5, center_y - 5), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 0), 2)
cv2.polylines(image, np.array([box]), True, (0, 255, 255), 2)
if self.show_image:
self.pre_process.showImage("Sequence of Movements", image, time=600)
# cv2.imshow("Sequence of Movements", image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
cv2.imwrite(self.output_folder + "{}_sequence_of_movements.jpg".format(self.process_number), image)
self.process_number += 1
time_efficiency["seq_movement"] = t1-t0
# print("total time taken", t1-t0)
def extractCrashImpactNodes(self, image, time_efficiency):
""" Twelve box-point crash impact model for locating the crash point on the vehicle and the point of deformation"""
t0 = time.time()
# print("\n--------- Extracting The Crash Impact Nodes Of vehicles----------\n")
for vehicle_color in self.vehicles:
for vehicle_id in self.vehicles[vehicle_color]["vehicle_info"]:
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"] = dict()
angle = self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["angle_of_car"]
# print("vehicle color",vehicle_color, "vehicle_id", vehicle_id)
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["crashed"] = False
### Using the angle and the position of triangle to localize longest and shortest sides of the vehicles
pivot_node = np.asarray(self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["vehicle_nodes"][0], np.float32)
vehicle_box_points = np.asarray(self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["vehicle_nodes"][:4], np.float32)
vehicle_side_points = np.asarray(self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["vehicle_nodes"][4:8], np.float32)
vehicle_extreme_points = np.asarray(self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["vehicle_nodes"][8:], np.float32)
triangle_position = np.asarray(self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["triangle_position"], np.float32)
front_nodes = self.pointNearNodes(vehicle_box_points, triangle_position)[:2]
front_nodes = front_nodes[:,1:]
front_side = self.pointNearNodes(front_nodes, pivot_node)
front_side = front_side[:,1:]
interval_one = list(range(0, 91)) + list(range(271, 361))
interval_two = list(range(91, 271))
if (round(angle) in interval_one):
front_left = front_side[1] ### longer_side ... Left_side
front_right = front_side[0] ### shorter_side ... Right_side
# print("angle greater than 270 and less than 90", angle)
elif (round(angle) in interval_two):
front_left = front_side[0] ### shorter_side ... Left_side
front_right = front_side[1] ### longer_side ... Right_side
# print("angle less than 270 and greater than 90", angle)
else:
None
# if (270 <= angle or angle <= 90):
# front_left = front_side[1] ### longer_side ... Left_side
# front_right = front_side[0] ### shorter_side ... Right_side
# print("angle greater than 270 and less than 90", angle)
# # print("front side", front_side)
# # print("front_left nodes", front_left)
# # print("front_right nodes", front_right)
# elif (270 > angle or angle >= 91):
# front_left = front_side[0] ### longer_side ... Left_side
# front_right = front_side[1] ### shorter_side ... Right_side
# print("angle less than 270 and greater than 90", angle)
# # print("front side", front_side)
# # print("front_left nodes", front_left)
# # print("front_right nodes", front_right)
# cv2.circle(image, tuple([int(front_left[0]), int(front_left[1])]), 8, (255, 255, 0), -1)
# cv2.circle(image, tuple([int(front_right[0]), int(front_right[1])]), 8, (0, 255, 255), -1)
vehicle_corners = self.pointNearNodes(vehicle_box_points, front_left)[1:]
vehicle_corners = vehicle_corners[:,1:]
rear_left = vehicle_corners[1]
rear_right = vehicle_corners[2]
vehicle_sides = self.pointNearNodes(vehicle_side_points, front_left)
vehicle_sides = vehicle_sides[:,1:]
front_mid = vehicle_sides[0]
left_mid = vehicle_sides[1]
right_mid = vehicle_sides[2]
rear_mid = vehicle_sides[3]
vehicle_extremes = self.pointNearNodes(vehicle_extreme_points, front_left)
vehicle_extremes = vehicle_extremes[:,1:]
front_left_mid = vehicle_extremes[0]
front_right_mid = vehicle_extremes[1]
rear_left_mid = vehicle_extremes[2]
rear_right_mid = vehicle_extremes[3]
cv2.circle(image, tuple([int(front_left[0]), int(front_left[1])]), 9, (128, 128, 256), -1)
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["front_left"] = front_left.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["front_left_mid"] = front_left_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["left_mid"] = left_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["rear_left_mid"] = rear_left_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["rear_left"] = rear_left.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["rear_mid"] = rear_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["rear_right"] = rear_right.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["rear_right_mid"] = rear_right_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["right_mid"] = right_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["front_right_mid"] = front_right_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["front_right"] = front_right.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]["front_mid"] = front_mid.tolist()
self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes_array"] = [["front_left", front_left.tolist()],
["front_left_mid", front_left_mid.tolist()],
["left_mid", left_mid.tolist()],
["rear_left_mid", rear_left_mid.tolist()],
["rear_left", rear_left.tolist()],
["rear_mid", rear_mid.tolist()],
["rear_right", rear_right.tolist()],
["rear_right_mid", rear_right_mid.tolist()],
["right_mid", right_mid.tolist()],
["front_right_mid", front_right_mid.tolist()],
["front_right", front_right.tolist()],
["front_mid", front_mid.tolist()]]
t1 = time.time()
for vehicle_color in self.vehicles:
for vehicle_id in self.vehicles[vehicle_color]["vehicle_info"]:
for oriented_node in self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"]:
point = self.vehicles[vehicle_color]["vehicle_info"][vehicle_id]["oriented_nodes"][oriented_node]
cv2.circle(image, tuple([int(point[0]), int(point[1])]), 4, (0, 255, 0), -1)
if self.show_image:
cv2.imshow("vehicle sides", image)
cv2.waitKey(15)
if self.show_image:
self.pre_process.showImage("vehicle sides", image, time=800)
cv2.destroyAllWindows()
cv2.imwrite(self.output_folder + "{}_twelve_point_model_sides.jpg".format(self.process_number), image)
self.process_number += 1
time_efficiency["oriented_nodes"] = t1-t0
# print("time taken = ", t1-t0)
def extractCrashPointOnVehicle(self, impact_image, time_efficiency, external, external_impact_points, crash_impact_locations):
""" Crash Impact of the Individual Vehicles """
# impact_points = list()
t0 = time.time()
for i, vehicle_color in enumerate(self.vehicles):
print("\n------- Proposed Crash Impact Point on the {} Vehicle ------".format(str.capitalize(vehicle_color)))
self.vehicles[vehicle_color]["impact_point_details"] = dict()
min_dist = self.vehicles[vehicle_color]["crash_point"]["dist_to_vehicle"]
impact_points = {0 : "front_left", 1: "front_left_mid", 2: "left_mid",
3: "rear_left_mid", 4: "rear_left", 5: "rear_mid",
6: "rear_right", 7: "rear_right_mid", 8: "right_mid",
9 : "front_right_mid", 10: "front_right", 11: "front_mid"}
for vehicle_vid in list(self.vehicles[vehicle_color]["vehicle_info"]): #[-2:]:
oriented_nodes_array = np.array(self.vehicles[vehicle_color]["vehicle_info"][vehicle_vid]["oriented_nodes_array"], dtype=object)
crash_point = self.vehicles[vehicle_color]["crash_point"]["coordinates"]
oriented_nodes_label = np.arange(0, len(oriented_nodes_array[:, 0].tolist()))
oriented_nodes_label = oriented_nodes_label.reshape(oriented_nodes_label.shape[0], -1)
oriented_nodes_values = np.asarray(oriented_nodes_array[:, 1].tolist())
edist_crash_nodes = np.sqrt(((oriented_nodes_values[:, 0] - crash_point[0]) ** 2 + (oriented_nodes_values[:, 1] - crash_point[1]) ** 2))
edist_crash_nodes = edist_crash_nodes.reshape(edist_crash_nodes.shape[0], -1)
edist_crash_nodes = np.hstack([edist_crash_nodes, oriented_nodes_label])
first_impact_side, second_impact_side = edist_crash_nodes[edist_crash_nodes[:, 0].argsort()][:2]
if float(first_impact_side[0]) <= min_dist:
vehicle_impact_side = impact_points[int(first_impact_side[1])]
second_impact_side = impact_points[int(second_impact_side[1])]
vehicle_side_coord = oriented_nodes_values[int(first_impact_side[1])]
# print("\n")
# print(str.capitalize(vehicle_color), "Vehicle")
print("Snapshot of vehicle = ", vehicle_vid)
print("Minimum distance from crash point to vehicle = {} pixels".format(min_dist))
print("Vehicle impact side internal annotation = ", vehicle_impact_side)
print("Vehicle second nearest impact side = ", second_impact_side)
### Adjustment to the internal annotator sides
if vehicle_impact_side == 'front_left_mid':
if second_impact_side == "front_left":
vehicle_impact_side = "front_left"
else:
vehicle_impact_side = "left_mid"
elif vehicle_impact_side == 'rear_left_mid':
if second_impact_side == "rear_left":
vehicle_impact_side = "rear_left"
else:
vehicle_impact_side = "left_mid"
elif vehicle_impact_side == 'rear_right_mid':
if second_impact_side == "rear_right":
vehicle_impact_side = "rear_right"
else:
vehicle_impact_side = "right_mid"
elif vehicle_impact_side == 'front_right_mid':
if second_impact_side == "front_right":
vehicle_impact_side = "front_right"
else:
vehicle_impact_side = "right_mid"
else:
None
self.vehicles[vehicle_color]["impact_point_details"]["snapshot"] = vehicle_vid
self.vehicles[vehicle_color]["impact_point_details"]["internal_impact_side"] = vehicle_impact_side
if external:
self.vehicles[vehicle_color]["impact_point_details"]["external_impact_side"] = external_impact_points[vehicle_color]
print("Vehicle impact side external validity = ", external_impact_points[vehicle_color])
self.vehicles[vehicle_color]["impact_point_details"]["side_coordinates"] = vehicle_side_coord.tolist()
self.vehicles[vehicle_color]["impact_point_details"]["reference_deformations"] = crash_impact_locations[vehicle_impact_side]
self.vehicles[vehicle_color]["vehicle_info"][vehicle_vid]["crashed"] = True
# impact_points.append([vehicle_color, vehicle_vid, vehicle_side, vehicle_side_coord])
print("Vehicle impact side internal adjusted = ", vehicle_impact_side)
print("Vehicle side coordinates = ", vehicle_side_coord)
print("Possible reference deformation group = ", self.vehicles[vehicle_color]["impact_point_details"]["reference_deformations"])
color = [(0, 255, 255), (255, 255, 0), (51, 255, 128), (128, 55, 160)]
cv2.circle(impact_image, tuple([int(vehicle_side_coord[0]), int(vehicle_side_coord[1])]), 6, color[i], -1)
# cv2.imshow("impact point on the vehicles", impact_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
t1 = time.time()
if self.show_image:
self.pre_process.showImage("impact point on the vehicles", impact_image, time=800)
cv2.imwrite(self.output_folder + "{}_crash_point_on_vehicles.jpg".format(self.process_number), impact_image)
self.process_number += 1
time_efficiency["skt_veh_impact"] = t1-t0
# print("\ntime taken", t1-t0)
def setColorBoundary(self, red_boundary, blue_boundary):
self.pre_process.red_car_boundary = red_boundary
self.pre_process.blue_car_boundary = blue_boundary
def extractVehicleInformation(self, image_path, time_efficiency, show_image, output_folder, external, external_impact_points, crash_impact_locations, car_length_sim):
image = self.pre_process.readImage(image_path=image_path)
print("Image Dimensions", image.shape[:2])
self.height, self.width = image.shape[:2]
self.car_length_sim = car_length_sim
self.show_image = show_image
self.output_folder = os.path.join(output_folder, "car/")
if not os.path.exists(self.output_folder):
os.makedirs(self.output_folder)
# self.output_folder = os.path.join(output_folder, "car/")
self.process_number = 0
""" Resize the image """
# image = self.pre_process.resize(image=image)
# print("Image Dimensions after resizing", image.shape[:2])
""" Get Mask for the Image dimension """
mask = self.pre_process.getMask(image=image)
self.pre_process.showImage('image original', image, time=800)
""" Transform image HSV colorspace and threshold the image"""
hsv = self.pre_process.changeColorSpace(image, cv2.COLOR_BGR2HSV)
mask_r, mask_b = self.pre_process.getMaskWithRange(image=hsv)
result_r = self.pre_process.bitwiseAndOperation(image=image, mask=mask_r)
result_b = self.pre_process.bitwiseAndOperation(image=image, mask=mask_b)
mask_result_r = np.hstack([cv2.merge([mask_r, mask_r, mask_r]), result_r])
mask_result_b = np.hstack([cv2.merge([mask_b, mask_b, mask_b]), result_b])
blend_masks_r_b = self.pre_process.bitwiseOrOperation(mask_b, mask_r)
blend_masks_res = self.pre_process.bitwiseOrOperation(result_b, result_r)
""" Blurring the masks of the red and blue cars """
mask_r_blur = self.pre_process.blurImage(mask_r, (5, 5), 0) # (5, 5)
mask_b_blur = self.pre_process.blurImage(mask_b, (3, 3), 0) # (3, 3)
""" Morphological Operations """
opening_r = self.pre_process.applyMorphologicalOperation(
image=mask_r_blur, kernel_window=(5, 5), morph_operation=cv2.MORPH_OPEN)
opening_b = self.pre_process.applyMorphologicalOperation(
image=mask_b_blur, kernel_window=(5, 5), morph_operation=cv2.MORPH_OPEN)
time_efficiency["preprocess"] = 0.0
""" Print or show images on screen"""
# self.pre_process.showImage('mask and result for red car', mask_result_r)
# self.pre_process.showImage('mask and result for blue car', mask_result_b)
# self.pre_process.showImage("masks blue and red car", blend_masks_r_b)
# self.pre_process.showImage('result blue and red car', blend_masks_res)
# self.pre_process.showImage("Opening Operation on Red and Blue Cars", np.hstack([opening_b, opening_r]))
""" Plot Images"""
# self.pre_process.plotFigure(image=mask_result_r, cmap="brg", title="Red Car")
# self.pre_process.plotFigure(image=mask_result_b, cmap="brg", title="Blue Car")
# self.pre_process.plotFigure(image=blend_masks_r_b, cmap="brg", title="masks blue and red car")
# self.pre_process.plotFigure(image=blend_masks_res, cmap="brg", title="result blue and red car")
# self.pre_process.plotFigure(image=np.hstack([opening_b, opening_r]), cmap="brg", title="Opening Operation on Red and Blue Cars")
""" Saving the figure"""
cv2.imwrite(self.output_folder + "{}_mask_result_r.jpg".format(self.process_number), mask_result_r)
cv2.imwrite(self.output_folder + "{}_mask_result_b.jpg".format(self.process_number), mask_result_b)
self.process_number += 1
cv2.imwrite(self.output_folder + "{}_blend_masks_r_b.jpg".format(self.process_number), blend_masks_r_b)
cv2.imwrite(self.output_folder + "{}_blend_masks_res.jpg".format(self.process_number), blend_masks_res)
self.process_number += 1
cv2.imwrite(self.output_folder + "{}_opening_morph.jpg".format(self.process_number), np.hstack([opening_b, opening_r]))
self.process_number += 1
self.vehicles["red"]["mask"] = opening_r
self.vehicles["blue"]["mask"] = opening_b
self.extractVehicleContoursFromMask()
self.geometricOperationOnVehicle(image.copy(), time_efficiency)
crash_point = self.extractingCrashPoint(image.copy(), time_efficiency)
self.extractTriangle(image.copy(), time_efficiency)
self.extractingAnglesForVehicles(image.copy(), time_efficiency)
self.generateSequenceOfMovements(image.copy(), time_efficiency)
self.extractCrashImpactNodes(image.copy(), time_efficiency)
self.extractCrashPointOnVehicle(image.copy(), time_efficiency, external, external_impact_points, crash_impact_locations)
return self.vehicles, time_efficiency
|
[
"numpy.arctan2",
"cv2.bitwise_and",
"math.atan2",
"cv2.arcLength",
"cv2.boxPoints",
"cv2.minAreaRect",
"cv2.imshow",
"os.path.join",
"cv2.contourArea",
"numpy.zeros_like",
"cv2.cvtColor",
"os.path.exists",
"math.cos",
"pre_processing.Pre_Processing",
"cv2.destroyAllWindows",
"cv2.boundingRect",
"cv2.bitwise_not",
"numpy.int0",
"cv2.waitKey",
"numpy.asarray",
"numpy.square",
"math.sin",
"numpy.hstack",
"itertools.combinations",
"cv2.merge",
"math.degrees",
"os.makedirs",
"cv2.threshold",
"cv2.moments",
"cv2.blur",
"time.time",
"numpy.array",
"cv2.findContours",
"numpy.sqrt"
] |
[((592, 608), 'pre_processing.Pre_Processing', 'Pre_Processing', ([], {}), '()\n', (606, 608), False, 'from pre_processing import Pre_Processing\n'), ((4137, 4148), 'time.time', 'time.time', ([], {}), '()\n', (4146, 4148), False, 'import time\n'), ((11776, 11787), 'time.time', 'time.time', ([], {}), '()\n', (11785, 11787), False, 'import time\n'), ((12543, 12554), 'time.time', 'time.time', ([], {}), '()\n', (12552, 12554), False, 'import time\n'), ((12865, 12909), 'itertools.combinations', 'itertools.combinations', (['nodes_of_vehicles', '(2)'], {}), '(nodes_of_vehicles, 2)\n', (12887, 12909), False, 'import itertools\n'), ((14525, 14536), 'time.time', 'time.time', ([], {}), '()\n', (14534, 14536), False, 'import time\n'), ((15189, 15200), 'time.time', 'time.time', ([], {}), '()\n', (15198, 15200), False, 'import time\n'), ((17970, 17981), 'time.time', 'time.time', ([], {}), '()\n', (17979, 17981), False, 'import time\n'), ((17990, 18013), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (18011, 18013), False, 'import cv2\n'), ((18489, 18518), 'numpy.hstack', 'np.hstack', (['(distances, nodes)'], {}), '((distances, nodes))\n', (18498, 18518), True, 'import numpy as np\n'), ((18686, 18697), 'time.time', 'time.time', ([], {}), '()\n', (18695, 18697), False, 'import time\n'), ((20968, 20979), 'time.time', 'time.time', ([], {}), '()\n', (20977, 20979), False, 'import time\n'), ((21920, 21937), 'numpy.array', 'np.array', (['side[1]'], {}), '(side[1])\n', (21928, 21937), True, 'import numpy as np\n'), ((26594, 26619), 'numpy.array', 'np.array', (['dist_from_pivot'], {}), '(dist_from_pivot)\n', (26602, 26619), True, 'import numpy as np\n'), ((28604, 28615), 'time.time', 'time.time', ([], {}), '()\n', (28613, 28615), False, 'import time\n'), ((31282, 31293), 'time.time', 'time.time', ([], {}), '()\n', (31291, 31293), False, 'import time\n'), ((32889, 32900), 'time.time', 'time.time', ([], {}), '()\n', (32898, 32900), False, 'import time\n'), ((40940, 40951), 'time.time', 'time.time', ([], {}), '()\n', (40949, 40951), False, 'import time\n'), ((41658, 41681), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (41679, 41681), False, 'import cv2\n'), ((42169, 42180), 'time.time', 'time.time', ([], {}), '()\n', (42178, 42180), False, 'import time\n'), ((47813, 47824), 'time.time', 'time.time', ([], {}), '()\n', (47822, 47824), False, 'import time\n'), ((48845, 48880), 'os.path.join', 'os.path.join', (['output_folder', '"""car/"""'], {}), "(output_folder, 'car/')\n", (48857, 48880), False, 'import os\n'), ((12210, 12236), 'numpy.hstack', 'np.hstack', (['[temp_img, img]'], {}), '([temp_img, img])\n', (12219, 12236), True, 'import numpy as np\n'), ((22271, 22359), 'numpy.asarray', 'np.asarray', (["self.vehicles[v_color]['vehicle_info'][v_id]['nodes_on_width']", 'np.int32'], {}), "(self.vehicles[v_color]['vehicle_info'][v_id]['nodes_on_width'],\n np.int32)\n", (22281, 22359), True, 'import numpy as np\n'), ((22389, 22481), 'numpy.asarray', 'np.asarray', (["self.vehicles[v_color]['vehicle_info'][v_id]['triangle_position']", 'np.int32'], {}), "(self.vehicles[v_color]['vehicle_info'][v_id]['triangle_position'\n ], np.int32)\n", (22399, 22481), True, 'import numpy as np\n'), ((22829, 22847), 'numpy.arctan2', 'np.arctan2', (['dy', 'dx'], {}), '(dy, dx)\n', (22839, 22847), True, 'import numpy as np\n'), ((27183, 27205), 'numpy.array', 'np.array', (['project_dist'], {}), '(project_dist)\n', (27191, 27205), True, 'import numpy as np\n'), ((29392, 29421), 'numpy.array', 'np.array', (['vehicles_projection'], {}), '(vehicles_projection)\n', (29400, 29421), True, 'import numpy as np\n'), ((48896, 48930), 'os.path.exists', 'os.path.exists', (['self.output_folder'], {}), '(self.output_folder)\n', (48910, 48930), False, 'import os\n'), ((48944, 48975), 'os.makedirs', 'os.makedirs', (['self.output_folder'], {}), '(self.output_folder)\n', (48955, 48975), False, 'import os\n'), ((52451, 52484), 'numpy.hstack', 'np.hstack', (['[opening_b, opening_r]'], {}), '([opening_b, opening_r])\n', (52460, 52484), True, 'import numpy as np\n'), ((12083, 12109), 'numpy.hstack', 'np.hstack', (['[temp_img, img]'], {}), '([temp_img, img])\n', (12092, 12109), True, 'import numpy as np\n'), ((15344, 15364), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (15357, 15364), True, 'import numpy as np\n'), ((15768, 15826), 'cv2.bitwise_and', 'cv2.bitwise_and', (['test_image', 'test_image'], {'mask': 'roi[:, :, 0]'}), '(test_image, test_image, mask=roi[:, :, 0])\n', (15783, 15826), False, 'import cv2\n'), ((15888, 15908), 'cv2.bitwise_not', 'cv2.bitwise_not', (['roi'], {}), '(roi)\n', (15903, 15908), False, 'import cv2\n'), ((15932, 15969), 'cv2.cvtColor', 'cv2.cvtColor', (['roi', 'cv2.COLOR_BGR2GRAY'], {}), '(roi, cv2.COLOR_BGR2GRAY)\n', (15944, 15969), False, 'import cv2\n'), ((15993, 16018), 'cv2.blur', 'cv2.blur', (['gray', '(3, 3)', '(0)'], {}), '(gray, (3, 3), 0)\n', (16001, 16018), False, 'import cv2\n'), ((16113, 16160), 'cv2.threshold', 'cv2.threshold', (['blur', '(15)', '(255)', 'cv2.THRESH_BINARY'], {}), '(blur, 15, 255, cv2.THRESH_BINARY)\n', (16126, 16160), False, 'import cv2\n'), ((16186, 16209), 'cv2.bitwise_not', 'cv2.bitwise_not', (['thresh'], {}), '(thresh)\n', (16201, 16209), False, 'import cv2\n'), ((16848, 16914), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_NONE'], {}), '(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n', (16864, 16914), False, 'import cv2\n'), ((17479, 17499), 'cv2.minAreaRect', 'cv2.minAreaRect', (['cnt'], {}), '(cnt)\n', (17494, 17499), False, 'import cv2\n'), ((18335, 18368), 'numpy.square', 'np.square', (['(nodes[:, 0] - point[0])'], {}), '(nodes[:, 0] - point[0])\n', (18344, 18368), True, 'import numpy as np\n'), ((18371, 18404), 'numpy.square', 'np.square', (['(nodes[:, 1] - point[1])'], {}), '(nodes[:, 1] - point[1])\n', (18380, 18404), True, 'import numpy as np\n'), ((18992, 19093), 'numpy.asarray', 'np.asarray', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]['nodes_on_width']", 'np.int32'], {}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_id][\n 'nodes_on_width'], np.int32)\n", (19002, 19093), True, 'import numpy as np\n'), ((19225, 19329), 'numpy.asarray', 'np.asarray', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]['triangle_position']", 'np.int32'], {}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_id][\n 'triangle_position'], np.int32)\n", (19235, 19329), True, 'import numpy as np\n'), ((19811, 19829), 'math.atan2', 'math.atan2', (['dy', 'dx'], {}), '(dy, dx)\n', (19821, 19829), False, 'import math\n'), ((19864, 19882), 'math.degrees', 'math.degrees', (['rads'], {}), '(rads)\n', (19876, 19882), False, 'import math\n'), ((33631, 33736), 'numpy.asarray', 'np.asarray', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]['vehicle_nodes'][0]", 'np.float32'], {}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_id][\n 'vehicle_nodes'][0], np.float32)\n", (33641, 33736), True, 'import numpy as np\n'), ((33769, 33875), 'numpy.asarray', 'np.asarray', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]['vehicle_nodes'][:4]", 'np.float32'], {}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_id][\n 'vehicle_nodes'][:4], np.float32)\n", (33779, 33875), True, 'import numpy as np\n'), ((33909, 34016), 'numpy.asarray', 'np.asarray', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]['vehicle_nodes'][4:8]", 'np.float32'], {}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_id][\n 'vehicle_nodes'][4:8], np.float32)\n", (33919, 34016), True, 'import numpy as np\n'), ((34053, 34159), 'numpy.asarray', 'np.asarray', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]['vehicle_nodes'][8:]", 'np.float32'], {}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_id][\n 'vehicle_nodes'][8:], np.float32)\n", (34063, 34159), True, 'import numpy as np\n'), ((34192, 34298), 'numpy.asarray', 'np.asarray', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_id]['triangle_position']", 'np.float32'], {}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_id][\n 'triangle_position'], np.float32)\n", (34202, 34298), True, 'import numpy as np\n'), ((43001, 43111), 'numpy.array', 'np.array', (["self.vehicles[vehicle_color]['vehicle_info'][vehicle_vid][\n 'oriented_nodes_array']"], {'dtype': 'object'}), "(self.vehicles[vehicle_color]['vehicle_info'][vehicle_vid][\n 'oriented_nodes_array'], dtype=object)\n", (43009, 43111), True, 'import numpy as np\n'), ((43560, 43679), 'numpy.sqrt', 'np.sqrt', (['((oriented_nodes_values[:, 0] - crash_point[0]) ** 2 + (\n oriented_nodes_values[:, 1] - crash_point[1]) ** 2)'], {}), '((oriented_nodes_values[:, 0] - crash_point[0]) ** 2 + (\n oriented_nodes_values[:, 1] - crash_point[1]) ** 2)\n', (43567, 43679), True, 'import numpy as np\n'), ((43820, 43872), 'numpy.hstack', 'np.hstack', (['[edist_crash_nodes, oriented_nodes_label]'], {}), '([edist_crash_nodes, oriented_nodes_label])\n', (43829, 43872), True, 'import numpy as np\n'), ((49853, 49888), 'cv2.merge', 'cv2.merge', (['[mask_r, mask_r, mask_r]'], {}), '([mask_r, mask_r, mask_r])\n', (49862, 49888), False, 'import cv2\n'), ((49936, 49971), 'cv2.merge', 'cv2.merge', (['[mask_b, mask_b, mask_b]'], {}), '([mask_b, mask_b, mask_b])\n', (49945, 49971), False, 'import cv2\n'), ((5159, 5183), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (5174, 5183), False, 'import cv2\n'), ((5374, 5394), 'cv2.moments', 'cv2.moments', (['contour'], {}), '(contour)\n', (5385, 5394), False, 'import cv2\n'), ((5840, 5865), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (5856, 5865), False, 'import cv2\n'), ((5893, 5917), 'cv2.minAreaRect', 'cv2.minAreaRect', (['contour'], {}), '(contour)\n', (5908, 5917), False, 'import cv2\n'), ((5945, 5964), 'cv2.boxPoints', 'cv2.boxPoints', (['rect'], {}), '(rect)\n', (5958, 5964), False, 'import cv2\n'), ((5991, 6003), 'numpy.int0', 'np.int0', (['box'], {}), '(box)\n', (5998, 6003), True, 'import numpy as np\n'), ((7851, 7876), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (7867, 7876), False, 'import cv2\n'), ((15705, 15727), 'numpy.array', 'np.array', (['[box_points]'], {}), '([box_points])\n', (15713, 15727), True, 'import numpy as np\n'), ((23787, 23816), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (23795, 23816), True, 'import numpy as np\n'), ((23819, 23856), 'numpy.array', 'np.array', (['[waypoint_of_vehicle[0], 0]'], {}), '([waypoint_of_vehicle[0], 0])\n', (23827, 23856), True, 'import numpy as np\n'), ((23910, 23939), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (23918, 23939), True, 'import numpy as np\n'), ((23942, 23979), 'numpy.array', 'np.array', (['[0, waypoint_of_vehicle[1]]'], {}), '([0, waypoint_of_vehicle[1]])\n', (23950, 23979), True, 'import numpy as np\n'), ((24033, 24062), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (24041, 24062), True, 'import numpy as np\n'), ((24065, 24112), 'numpy.array', 'np.array', (['[waypoint_of_vehicle[0], self.height]'], {}), '([waypoint_of_vehicle[0], self.height])\n', (24073, 24112), True, 'import numpy as np\n'), ((24168, 24197), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (24176, 24197), True, 'import numpy as np\n'), ((24200, 24246), 'numpy.array', 'np.array', (['[self.width, waypoint_of_vehicle[1]]'], {}), '([self.width, waypoint_of_vehicle[1]])\n', (24208, 24246), True, 'import numpy as np\n'), ((25265, 25294), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (25273, 25294), True, 'import numpy as np\n'), ((25297, 25334), 'numpy.array', 'np.array', (['[waypoint_of_vehicle[0], 0]'], {}), '([waypoint_of_vehicle[0], 0])\n', (25305, 25334), True, 'import numpy as np\n'), ((26402, 26426), 'numpy.array', 'np.array', (['vehicle_center'], {}), '(vehicle_center)\n', (26410, 26426), True, 'import numpy as np\n'), ((26429, 26458), 'numpy.array', 'np.array', (['init_vehicle_center'], {}), '(init_vehicle_center)\n', (26437, 26458), True, 'import numpy as np\n'), ((32133, 32148), 'numpy.array', 'np.array', (['[box]'], {}), '([box])\n', (32141, 32148), True, 'import numpy as np\n'), ((5057, 5081), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (5072, 5081), False, 'import cv2\n'), ((5083, 5119), 'cv2.arcLength', 'cv2.arcLength', (['contour'], {'closed': '(False)'}), '(contour, closed=False)\n', (5096, 5119), False, 'import cv2\n'), ((25425, 25454), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (25433, 25454), True, 'import numpy as np\n'), ((25457, 25494), 'numpy.array', 'np.array', (['[0, waypoint_of_vehicle[1]]'], {}), '([0, waypoint_of_vehicle[1]])\n', (25465, 25494), True, 'import numpy as np\n'), ((41465, 41499), 'cv2.imshow', 'cv2.imshow', (['"""vehicle sides"""', 'image'], {}), "('vehicle sides', image)\n", (41475, 41499), False, 'import cv2\n'), ((41524, 41539), 'cv2.waitKey', 'cv2.waitKey', (['(15)'], {}), '(15)\n', (41535, 41539), False, 'import cv2\n'), ((1587, 1613), 'numpy.array', 'np.array', (['box_points[j][0]'], {}), '(box_points[j][0])\n', (1595, 1613), True, 'import numpy as np\n'), ((1616, 1642), 'numpy.array', 'np.array', (['box_points[i][0]'], {}), '(box_points[i][0])\n', (1624, 1642), True, 'import numpy as np\n'), ((1656, 1682), 'numpy.array', 'np.array', (['box_points[j][1]'], {}), '(box_points[j][1])\n', (1664, 1682), True, 'import numpy as np\n'), ((1685, 1711), 'numpy.array', 'np.array', (['box_points[i][1]'], {}), '(box_points[i][1])\n', (1693, 1711), True, 'import numpy as np\n'), ((13361, 13378), 'numpy.array', 'np.array', (['point_1'], {}), '(point_1)\n', (13369, 13378), True, 'import numpy as np\n'), ((13421, 13438), 'numpy.array', 'np.array', (['point_2'], {}), '(point_2)\n', (13429, 13438), True, 'import numpy as np\n'), ((25587, 25616), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (25595, 25616), True, 'import numpy as np\n'), ((25619, 25666), 'numpy.array', 'np.array', (['[waypoint_of_vehicle[0], self.height]'], {}), '([waypoint_of_vehicle[0], self.height])\n', (25627, 25666), True, 'import numpy as np\n'), ((20063, 20105), 'math.cos', 'math.cos', (['(angle_of_vehicle * np.pi / 180.0)'], {}), '(angle_of_vehicle * np.pi / 180.0)\n', (20071, 20105), False, 'import math\n'), ((20180, 20222), 'math.sin', 'math.sin', (['(angle_of_vehicle * np.pi / 180.0)'], {}), '(angle_of_vehicle * np.pi / 180.0)\n', (20188, 20222), False, 'import math\n'), ((25760, 25789), 'numpy.array', 'np.array', (['waypoint_of_vehicle'], {}), '(waypoint_of_vehicle)\n', (25768, 25789), True, 'import numpy as np\n'), ((25792, 25838), 'numpy.array', 'np.array', (['[self.width, waypoint_of_vehicle[1]]'], {}), '([self.width, waypoint_of_vehicle[1]])\n', (25800, 25838), True, 'import numpy as np\n')]
|
import numpy as np
import math
class Aligner:
def __init__(self,coordFile):
self.coordFile=coordFile
self._natoms=0
self._symbols=[]
self._resids = []
self._atomids = []
self._resnames = []
self._x=[]
self._y=[]
self._z=[]
self.read()
def read(self):
fileHandler=open(self.coordFile,"r")
lines=fileHandler.readlines()
for line in lines:
if line.startswith('HETATM') or line.startswith('ATOM'):
self._atomids.append(int(line[6:11]))
self._symbols.append(line[12:16])
self._resnames.append(line[17:20])
self._resids.append(int(line[22:26]))
self._x.append(float(line[30:38]))
self._y.append(float(line[38:46]))
self._z.append(float(line[46:54]))
self._natoms +=1
fileHandler.close()
def align(self,iatom= None,jatom = None,target_dir= None):
if not iatom or not jatom:
iatom,jatom = self.findMoleculeAxis()
if not target_dir:
target_dir = [0.0, 0.0, 1.0]
coords=np.zeros((3,self._natoms),dtype=float)
coords[0,:]=self._x
coords[1,:]=self._y
coords[2,:]=self._z
vec1=[
coords[0,iatom-1] - coords[0,jatom-1],
coords[1,iatom-1] - coords[1,jatom-1],
coords[2,iatom-1] - coords[2,jatom-1]
]
coords=do_align(vec1,target_dir,coords)
self._x = list(coords[0,:])
self._y = list(coords[1,:])
self._z = list(coords[2,:])
def write(self,outfile = 'out.pdb'):
filehandler = open(outfile,'w')
for i in range(self._natoms):
filehandler.write('%-6s%5d %-4s %3s %4d %8.3f%8.3f%8.3f\n'%
(
'ATOM',
self._atomids[i],
self._symbols[i],
self._resnames[i],
self._resids[i],
self._x[i],self._y[i],self._z[i]
)
)
filehandler.close()
def moveTo(self,transPos,atomID = None):
'''
tranPos: coordinate of target point, where COM or atomID will
be moved
'''
if atomID:
xref = self.x[atomID-1]
yref = self.y[atomID-1]
zref = self.z[atomID-1]
else:
xcom = sum(self._x)/self._natoms
ycom = sum(self._y)/self._natoms
zcom = sum(self._z)/self._natoms
xref = xcom; yref = ycom; zref = zcom
for i in range(self._natoms):
self._x[i] = self._x[i] - xref + transPos[0]
self._y[i] = self._y[i] - yref + transPos[1]
self._z[i] = self._z[i] - zref + transPos[2]
def moveBy(self, transVector):
for i in range(self.natoms):
self.x[i] += transVector[0]
self.y[i] += transVector[1]
self.z[i] += transVector[2]
def findMoleculeAxis(self):
pairs = []
dist = []
for i in range(self._natoms-1):
for j in range(i+1,self._natoms):
dx = self._x[i] - self._x[j]
dy = self._y[i] - self._y[j]
dz = self._z[i] - self._z[j]
dist.append(dx**2 + dy**2 + dz**2)
pairs.append((i,j))
argmax = np.argmax(dist)
return pairs[argmax][0] + 1, pairs[argmax][1] + 1
def merge(self,other):
self._natoms += other._natoms
self._symbols += other._symbols
self._resids += [resid+self._resids[-1] for resid in other._resids]
self._atomids += [atomid+self._atomids[-1] for atomid in other._atomids]
self._resnames += other._resnames
self._x += other._x
self._y += other._y
self._z += other._z
@property
def x(self):
return self._x
@property
def y(self):
return self._y
@property
def z(self):
return self._z
@property
def natoms(self):
return self._natoms
@property
def symbols(self):
return self._symbols
@property
def resnames(self):
return self._resnames
@property
def atomids(self):
return self._atomids
def getAlignMatrix(v,c):
'''
https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
'''
alignMat=np.zeros((3,3),dtype=float)
iMat=np.zeros((3,3),dtype=float)
vx=np.zeros((3,3),dtype=float)
iMat[0,0]=1.0
iMat[1,1]=1.0
iMat[2,2]=1.0
vx[0,0]=0.0
vx[0,1]=-v[2]
vx[0,2]=v[1]
vx[1,0]=v[2]
vx[1,1]=0.0
vx[1,2]=-v[0]
vx[2,0]=-v[1]
vx[2,1]=v[0]
vx[2,2]=0.0
factor=1.0/(1.0+c)
alignMat=iMat + vx + np.matmul(vx,vx) * factor
return alignMat
def getRotMatrix(rotAxis,angle):
rotMat=np.zeros((3,3),dtype=float)
angle = angle * 0.0174533 # degree to radian
cos = math.cosine(angle)
sin = math.sine(anlge)
_cos_ = 1 - cos
u = rotAxis / np.linalg.norm(u)
ux = u[0]; uy = u[1]; uz = u[2]
uxy = ux * uy
uyz = uy * uz
uzx = uz * ux
uxx = ux * ux
uyy = uy * uy
uzz = uz * uz
rotMat[0,0] = cos + (uxx * _cos_)
rotMat[0,1] = (uxy * _cos_) - (uz * sin)
rotMat[0,2] = (uzx * _cos_) + (uy * sin)
rotMat[1,0] = (uxy * _cos_) + (uz * sin)
rotMat[1,1] = cos + (uyy * _cos_)
rotMat[1,2] = (uyz * _cos_) - (ux * sin)
rotMat[2,0] = (uzx * _cos_) - (uy * sin)
rotMat[2,1] = (uyz * _cos_) + (ux * sin)
rotMat[2,2] = cos + (uzz*_cos_)
return rotMat
def do_align(u,v,coords):
u=u/np.linalg.norm(u)
v=v/np.linalg.norm(v)
normal=np.cross(u,v)
c=np.dot(u,v)
if abs(abs(c)-1)<10e-10: # if vectors are antiparallel
coords= coords * -1
return coords
alignMat=getAlignMatrix(normal,c)
coords=np.matmul(alignMat,coords)
return(coords)
# m0 =Aligner('hemcel.pdb')
# m0.align(5,294,[0,0,1])
# m0.moveTo([10,0,0])
# # molecule0.write('out0.pdb')
# m1 = Aligner('cellulose_2.pdb')
# m1.align(2,246,[0,0,1])
# m1.moveTo([0,0,0])
# m0.merge(m1)
# m0.write('out-merged.pdb')
|
[
"numpy.argmax",
"numpy.cross",
"numpy.zeros",
"math.cosine",
"math.sine",
"numpy.linalg.norm",
"numpy.matmul",
"numpy.dot"
] |
[((4770, 4799), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'float'}), '((3, 3), dtype=float)\n', (4778, 4799), True, 'import numpy as np\n'), ((4807, 4836), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'float'}), '((3, 3), dtype=float)\n', (4815, 4836), True, 'import numpy as np\n'), ((4842, 4871), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'float'}), '((3, 3), dtype=float)\n', (4850, 4871), True, 'import numpy as np\n'), ((5237, 5266), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'float'}), '((3, 3), dtype=float)\n', (5245, 5266), True, 'import numpy as np\n'), ((5332, 5350), 'math.cosine', 'math.cosine', (['angle'], {}), '(angle)\n', (5343, 5350), False, 'import math\n'), ((5361, 5377), 'math.sine', 'math.sine', (['anlge'], {}), '(anlge)\n', (5370, 5377), False, 'import math\n'), ((6116, 6130), 'numpy.cross', 'np.cross', (['u', 'v'], {}), '(u, v)\n', (6124, 6130), True, 'import numpy as np\n'), ((6136, 6148), 'numpy.dot', 'np.dot', (['u', 'v'], {}), '(u, v)\n', (6142, 6148), True, 'import numpy as np\n'), ((6318, 6345), 'numpy.matmul', 'np.matmul', (['alignMat', 'coords'], {}), '(alignMat, coords)\n', (6327, 6345), True, 'import numpy as np\n'), ((1237, 1277), 'numpy.zeros', 'np.zeros', (['(3, self._natoms)'], {'dtype': 'float'}), '((3, self._natoms), dtype=float)\n', (1245, 1277), True, 'import numpy as np\n'), ((3621, 3636), 'numpy.argmax', 'np.argmax', (['dist'], {}), '(dist)\n', (3630, 3636), True, 'import numpy as np\n'), ((5422, 5439), 'numpy.linalg.norm', 'np.linalg.norm', (['u'], {}), '(u)\n', (5436, 5439), True, 'import numpy as np\n'), ((6059, 6076), 'numpy.linalg.norm', 'np.linalg.norm', (['u'], {}), '(u)\n', (6073, 6076), True, 'import numpy as np\n'), ((6085, 6102), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (6099, 6102), True, 'import numpy as np\n'), ((5138, 5155), 'numpy.matmul', 'np.matmul', (['vx', 'vx'], {}), '(vx, vx)\n', (5147, 5155), True, 'import numpy as np\n')]
|
import logging
from pathlib import Path
from typing import BinaryIO, Callable, Dict, Iterable, NewType, Union, IO
import numpy
from absl import flags
from cv2.cv2 import IMREAD_COLOR, imdecode, cvtColor, COLOR_RGB2BGR
from injector import Binder, Module, inject, singleton
import ffmpeg
import subprocess
from rep0st.db.post import Post, Type
log = logging.getLogger(__name__)
FLAGS = flags.FLAGS
flags.DEFINE_string('rep0st_media_path', '',
'Path to media directory used by rep0st to save media.')
_MediaDirectory = NewType('_MediaDirectory', Path)
def _readline(stream: IO[bytes]) -> Union[None, str]:
out_bytes = bytes()
c = stream.read(1)
if not c:
return None
while c != b'\n':
out_bytes += c
c = stream.read(1)
return out_bytes.decode('ascii').strip()
class _MediaFlagModule(Module):
def configure(self, binder: Binder) -> None:
media_path = Path(FLAGS.rep0st_media_path)
if FLAGS.rep0st_media_path == '' or not media_path.is_dir():
raise NotADirectoryError(
'rep0st_media_path has to be set to an existing directory.')
binder.bind(_MediaDirectory, to=media_path)
class DecodeMediaServiceModule(Module):
def configure(self, binder: Binder):
binder.bind(DecodeMediaService)
@singleton
class DecodeMediaService:
def _decode_image(self, data: numpy.ndarray) -> numpy.ndarray:
try:
img = imdecode(data, IMREAD_COLOR)
if img is None:
raise ImageDecodeException("Could not decode image")
return img
except:
raise ImageDecodeException("Could not decode image")
def decode_image_from_buffer(self, data: bytes) -> Iterable[numpy.ndarray]:
try:
data = numpy.frombuffer(data, dtype=numpy.uint8)
except (IOError, OSError) as e:
raise NoMediaFoundException('Could not data from buffer') from e
yield self._decode_image(data)
def decode_image_from_file(self, file: BinaryIO) -> Iterable[numpy.ndarray]:
try:
data = numpy.fromfile(file, dtype=numpy.uint8)
except (IOError, OSError) as e:
raise NoMediaFoundException(
f'Could not read data from file {file}') from e
yield self._decode_image(data)
def decode_video_from_file(self, file: BinaryIO) -> Iterable[numpy.ndarray]:
cmd = ffmpeg.input(
'pipe:',
vsync=0,
skip_frame='nokey',
hide_banner=None,
threads=1,
loglevel='error').output(
'pipe:', vcodec='ppm', format='rawvideo')
proc = subprocess.Popen(
cmd.compile(),
stdin=file,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
while True:
format = _readline(proc.stdout)
if not format:
break
if format != 'P6':
raise NotImplementedError(
'frames returned by ffmpeg cannot be decoded due to an unsupported format'
)
width, height = [int(x) for x in _readline(proc.stdout).split(' ')]
max_value = int(_readline(proc.stdout))
if max_value != 255:
raise NotImplementedError(f'max_value has to be 255, it is {max_value}')
in_bytes = proc.stdout.read(width * height * 3)
if not in_bytes:
raise BufferError('could not read the full frame')
in_frame = numpy.frombuffer(in_bytes,
numpy.uint8).reshape([height, width, 3])
in_frame = cvtColor(in_frame, COLOR_RGB2BGR)
yield in_frame
retcode = proc.wait(timeout=1)
if retcode != 0:
err = proc.stderr.read().decode('utf-8')
raise SyntaxError(err)
class ReadMediaServiceModule(Module):
def configure(self, binder: Binder):
binder.install(DecodeMediaServiceModule)
binder.install(_MediaFlagModule)
binder.bind(ReadMediaService)
class NoMediaFoundException(Exception):
pass
class ImageDecodeException(Exception):
pass
@singleton
class ReadMediaService:
media_dir: Path
decode_media_service: DecodeMediaService
decoders: Dict[Type, Callable[[Iterable[numpy.ndarray]], BinaryIO]]
@inject
def __init__(self, media_dir: _MediaDirectory,
decode_media_service: DecodeMediaService):
self.media_dir = media_dir
self.decode_media_service = decode_media_service
self.decoders = {
Type.IMAGE: self.decode_media_service.decode_image_from_file,
Type.VIDEO: self.decode_media_service.decode_video_from_file,
}
def get_images(self, post: Post) -> Iterable[numpy.ndarray]:
media_file = self.media_dir / post.image
if post.fullsize:
fullsize_media_file = self.media_dir / 'full' / post.fullsize
if not fullsize_media_file.is_file():
log.error(
f'Fullsize image for {post.id} not found at {fullsize_media_file.absolute()}. Falling back to resized image'
)
else:
log.debug(f'Using fullsize image {fullsize_media_file.absolute()}')
media_file = fullsize_media_file
if post.type not in self.decoders:
raise NotImplementedError(
f'Decoder needed for {post} for type {post.type} is not implemented')
try:
with media_file.open("rb") as f:
for image in self.decoders[post.type](f):
yield image
except (IOError, OSError) as e:
raise NoMediaFoundException(
f'Could not read images for post {post.id} from file {media_file.absolute()}'
) from e
|
[
"numpy.fromfile",
"numpy.frombuffer",
"absl.flags.DEFINE_string",
"pathlib.Path",
"cv2.cv2.imdecode",
"ffmpeg.input",
"typing.NewType",
"cv2.cv2.cvtColor",
"logging.getLogger"
] |
[((351, 378), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (368, 378), False, 'import logging\n'), ((399, 504), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""rep0st_media_path"""', '""""""', '"""Path to media directory used by rep0st to save media."""'], {}), "('rep0st_media_path', '',\n 'Path to media directory used by rep0st to save media.')\n", (418, 504), False, 'from absl import flags\n'), ((539, 571), 'typing.NewType', 'NewType', (['"""_MediaDirectory"""', 'Path'], {}), "('_MediaDirectory', Path)\n", (546, 571), False, 'from typing import BinaryIO, Callable, Dict, Iterable, NewType, Union, IO\n'), ((903, 932), 'pathlib.Path', 'Path', (['FLAGS.rep0st_media_path'], {}), '(FLAGS.rep0st_media_path)\n', (907, 932), False, 'from pathlib import Path\n'), ((1393, 1421), 'cv2.cv2.imdecode', 'imdecode', (['data', 'IMREAD_COLOR'], {}), '(data, IMREAD_COLOR)\n', (1401, 1421), False, 'from cv2.cv2 import IMREAD_COLOR, imdecode, cvtColor, COLOR_RGB2BGR\n'), ((1694, 1735), 'numpy.frombuffer', 'numpy.frombuffer', (['data'], {'dtype': 'numpy.uint8'}), '(data, dtype=numpy.uint8)\n', (1710, 1735), False, 'import numpy\n'), ((1980, 2019), 'numpy.fromfile', 'numpy.fromfile', (['file'], {'dtype': 'numpy.uint8'}), '(file, dtype=numpy.uint8)\n', (1994, 2019), False, 'import numpy\n'), ((3367, 3400), 'cv2.cv2.cvtColor', 'cvtColor', (['in_frame', 'COLOR_RGB2BGR'], {}), '(in_frame, COLOR_RGB2BGR)\n', (3375, 3400), False, 'from cv2.cv2 import IMREAD_COLOR, imdecode, cvtColor, COLOR_RGB2BGR\n'), ((2274, 2375), 'ffmpeg.input', 'ffmpeg.input', (['"""pipe:"""'], {'vsync': '(0)', 'skip_frame': '"""nokey"""', 'hide_banner': 'None', 'threads': '(1)', 'loglevel': '"""error"""'}), "('pipe:', vsync=0, skip_frame='nokey', hide_banner=None,\n threads=1, loglevel='error')\n", (2286, 2375), False, 'import ffmpeg\n'), ((3248, 3287), 'numpy.frombuffer', 'numpy.frombuffer', (['in_bytes', 'numpy.uint8'], {}), '(in_bytes, numpy.uint8)\n', (3264, 3287), False, 'import numpy\n')]
|
# MIT License
# xlr8
# Copyright (c) 2022 Ethereal AI
#
# 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 scipy.sparse as sp
from scipy import linalg
from scipy.sparse.linalg import svds
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array, check_random_state
from sklearn.utils.extmath import (randomized_range_finder, safe_sparse_dot,
svd_flip)
from sklearn.utils.sparsefuncs import mean_variance_axis
__all__ = ["TruncatedSVD"]
class TruncatedSVD(TransformerMixin, BaseEstimator):
"""Dimensionality reduction using truncated SVD (aka LSA).
This transformer performs linear dimensionality reduction by means of
truncated singular value decomposition (SVD). Contrary to PCA, this
estimator does not center the data before computing the singular value
decomposition. This means it can work with sparse matrices
efficiently.
In particular, truncated SVD works on term count/tf-idf matrices as
returned by the vectorizers in :mod:`sklearn.feature_extraction.text`. In
that context, it is known as latent semantic analysis (LSA).
This estimator supports two algorithms: a fast randomized SVD solver, and
a "naive" algorithm that uses ARPACK as an eigensolver on `X * X.T` or
`X.T * X`, whichever is more efficient.
Read more in the :ref:`User Guide <LSA>`.
Parameters
----------
n_components : int, default=2
Desired dimensionality of output data.
Must be strictly less than the number of features.
The default value is useful for visualisation. For LSA, a value of
100 is recommended.
n_iter : int, default=5
Number of iterations for randomized SVD solver. Not used by ARPACK. The
default is larger than the default in
:func:`~sklearn.utils.extmath.randomized_svd` to handle sparse
matrices that may have large slowly decaying spectrum.
random_state : int, RandomState instance or None, default=None
Used during randomized svd. Pass an int for reproducible results across
multiple function calls.
See :term:`Glossary <random_state>`.
tol : float, default=0.0
Tolerance for ARPACK. 0 means machine precision. Ignored by randomized
SVD solver.
Attributes
----------
components_ : ndarray of shape (n_components, n_features)
The right singular vectors of the input data.
explained_variance_ : ndarray of shape (n_components,)
The variance of the training samples transformed by a projection to
each component.
explained_variance_ratio_ : ndarray of shape (n_components,)
Percentage of variance explained by each of the selected components.
singular_values_ : ndarray od shape (n_components,)
The singular values corresponding to each of the selected components.
The singular values are equal to the 2-norms of the ``n_components``
variables in the lower-dimensional space.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
DictionaryLearning : Find a dictionary that sparsely encodes data.
FactorAnalysis : A simple linear generative model with
Gaussian latent variables.
IncrementalPCA : Incremental principal components analysis.
KernelPCA : Kernel Principal component analysis.
NMF : Non-Negative Matrix Factorization.
PCA : Principal component analysis.
Notes
-----
SVD suffers from a problem called "sign indeterminacy", which means the
sign of the ``components_`` and the output from transform depend on the
algorithm and random state. To work around this, fit instances of this
class to data once, then keep the instance around to do transformations.
References
----------
Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions
Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf
Examples
--------
>>> from sklearn.decomposition import TruncatedSVD
>>> from scipy.sparse import csr_matrix
>>> import numpy as np
>>> np.random.seed(0)
>>> X_dense = np.random.rand(100, 100)
>>> X_dense[:, 2 * np.arange(50)] = 0
>>> X = csr_matrix(X_dense)
>>> svd = TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> svd.fit(X)
TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> print(svd.explained_variance_ratio_)
[0.0157... 0.0512... 0.0499... 0.0479... 0.0453...]
>>> print(svd.explained_variance_ratio_.sum())
0.2102...
>>> print(svd.singular_values_)
[35.2410... 4.5981... 4.5420... 4.4486... 4.3288...]
"""
def __init__(
self,
n_components=2,
*,
n_oversamples=10,
n_iter=5,
random_state=None,
tol=0.0,
):
self.n_components = n_components
self.n_oversamples = n_oversamples
self.n_iter = n_iter
self.random_state = random_state
self.tol = tol
def randomized_svd(
self,
M,
n_components,
*,
n_oversamples=10,
n_iter="auto",
power_iteration_normalizer="auto",
transpose="auto",
flip_sign=True,
random_state="warn",
):
"""Computes a truncated randomized SVD.
This method solves the fixed-rank approximation problem described in the
Halko et al paper (problem (1.5), p5).
Parameters
----------
M : {ndarray, sparse matrix}
Matrix to decompose.
n_components : int
Number of singular values and vectors to extract.
n_oversamples : int, default=10
Additional number of random vectors to sample the range of M so as
to ensure proper conditioning. The total number of random vectors
used to find the range of M is n_components + n_oversamples. Smaller
number can improve speed but can negatively impact the quality of
approximation of singular vectors and singular values. Users might wish
to increase this parameter up to `2*k - n_components` where k is the
effective rank, for large matrices, noisy problems, matrices with
slowly decaying spectrums, or to increase precision accuracy. See Halko
et al (pages 5, 23 and 26).
n_iter : int or 'auto', default='auto'
Number of power iterations. It can be used to deal with very noisy
problems. When 'auto', it is set to 4, unless `n_components` is small
(< .1 * min(X.shape)) in which case `n_iter` is set to 7.
This improves precision with few components. Note that in general
users should rather increase `n_oversamples` before increasing `n_iter`
as the principle of the randomized method is to avoid usage of these
more costly power iterations steps. When `n_components` is equal
or greater to the effective matrix rank and the spectrum does not
present a slow decay, `n_iter=0` or `1` should even work fine in theory
(see Halko et al paper, page 9).
.. versionchanged:: 0.18
power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
Whether the power iterations are normalized with step-by-step
QR factorization (the slowest but most accurate), 'none'
(the fastest but numerically unstable when `n_iter` is large, e.g.
typically 5 or larger), or 'LU' factorization (numerically stable
but can lose slightly in accuracy). The 'auto' mode applies no
normalization if `n_iter` <= 2 and switches to LU otherwise.
.. versionadded:: 0.18
transpose : bool or 'auto', default='auto'
Whether the algorithm should be applied to M.T instead of M. The
result should approximately be the same. The 'auto' mode will
trigger the transposition if M.shape[1] > M.shape[0] since this
implementation of randomized SVD tend to be a little faster in that
case.
.. versionchanged:: 0.18
flip_sign : bool, default=True
The output of a singular value decomposition is only unique up to a
permutation of the signs of the singular vectors. If `flip_sign` is
set to `True`, the sign ambiguity is resolved by making the largest
loadings for each component in the left singular vectors positive.
random_state : int, RandomState instance or None, default='warn'
The seed of the pseudo random number generator to use when
shuffling the data, i.e. getting the random vectors to initialize
the algorithm. Pass an int for reproducible results across multiple
function calls. See :term:`Glossary <random_state>`.
.. versionchanged:: 1.2
The previous behavior (`random_state=0`) is deprecated, and
from v1.2 the default value will be `random_state=None`. Set
the value of `random_state` explicitly to suppress the deprecation
warning.
Notes
-----
This algorithm finds a (usually very good) approximate truncated
singular value decomposition using randomization to speed up the
computations. It is particularly fast on large matrices on which
you wish to extract only a small number of components. In order to
obtain further speed up, `n_iter` can be set <=2 (at the cost of
loss of precision). To increase the precision it is recommended to
increase `n_oversamples`, up to `2*k-n_components` where k is the
effective rank. Usually, `n_components` is chosen to be greater than k
so increasing `n_oversamples` up to `n_components` should be enough.
References
----------
* Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions (Algorithm 4.3)
Halko, et al., 2009 https://arxiv.org/abs/0909.4061
* A randomized algorithm for the decomposition of matrices
<NAME>, <NAME> and <NAME>
* An implementation of a randomized algorithm for principal component
analysis
<NAME> et al. 2014
"""
if random_state == "warn":
random_state = 0
random_state = check_random_state(random_state)
n_random = n_components + n_oversamples
n_samples, n_features = M.shape
if transpose == "auto":
transpose = n_samples < n_features
if transpose:
# this implementation is a bit faster with smaller shape[1]
M = M.T
Q = randomized_range_finder(
M,
size=n_random,
n_iter=n_iter,
power_iteration_normalizer=power_iteration_normalizer,
random_state=random_state,
)
# project M to the (k + p) dimensional space using the basis vectors
B = safe_sparse_dot(Q.T, M)
# compute the SVD on the thin matrix: (k + p) wide
Uhat, s, Vt = linalg.svd(
B, full_matrices=False, check_finite=False, overwrite_a=True
)
del B
U = np.dot(Q, Uhat)
if flip_sign:
if not transpose:
U, Vt = svd_flip(U, Vt)
else:
# In case of transpose u_based_decision=false
# to actually flip based on u and not v.
U, Vt = svd_flip(U, Vt, u_based_decision=False)
if transpose:
# transpose back the results according to the input convention
return Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T
else:
return U[:, :n_components], s[:n_components], Vt[:n_components, :]
def fit(self, X, y=None):
"""Fit model on training data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
self : object
Returns the transformer object.
"""
self.fit_transform(X)
return self
def fit_transform(self, X, y=None):
"""Fit model to X and perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
X_new : ndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
"""
# X = self._validate_data(X, accept_sparse=["csr", "csc"], ensure_min_features=2)
random_state = check_random_state(self.random_state)
k = self.n_components
n_features = X.shape[1]
if k >= n_features:
raise ValueError(
"n_components must be < n_features; got %d >= %d" % (k, n_features)
)
U, Sigma, VT = self.randomized_svd(
X,
self.n_components,
n_oversamples=self.n_oversamples,
power_iteration_normalizer="none",
n_iter=self.n_iter,
random_state=random_state,
)
self.components_ = VT
# As a result of the SVD approximation error on X ~ U @ Sigma @ V.T,
# X @ V is not the same as U @ Sigma
X_transformed = safe_sparse_dot(X, self.components_.T)
return X_transformed
def transform(self, X):
"""Perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
New data.
Returns
-------
X_new : ndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
"""
# X = self._validate_data(X, accept_sparse=["csr", "csc"], reset=False)
return safe_sparse_dot(X, self.components_.T)
def _more_tags(self):
return {"preserves_dtype": [np.float64, np.float32]}
|
[
"sklearn.utils.check_random_state",
"sklearn.utils.extmath.randomized_range_finder",
"scipy.linalg.svd",
"sklearn.utils.extmath.svd_flip",
"sklearn.utils.extmath.safe_sparse_dot",
"numpy.dot"
] |
[((11843, 11875), 'sklearn.utils.check_random_state', 'check_random_state', (['random_state'], {}), '(random_state)\n', (11861, 11875), False, 'from sklearn.utils import check_array, check_random_state\n'), ((12171, 12318), 'sklearn.utils.extmath.randomized_range_finder', 'randomized_range_finder', (['M'], {'size': 'n_random', 'n_iter': 'n_iter', 'power_iteration_normalizer': 'power_iteration_normalizer', 'random_state': 'random_state'}), '(M, size=n_random, n_iter=n_iter,\n power_iteration_normalizer=power_iteration_normalizer, random_state=\n random_state)\n', (12194, 12318), False, 'from sklearn.utils.extmath import randomized_range_finder, safe_sparse_dot, svd_flip\n'), ((12471, 12494), 'sklearn.utils.extmath.safe_sparse_dot', 'safe_sparse_dot', (['Q.T', 'M'], {}), '(Q.T, M)\n', (12486, 12494), False, 'from sklearn.utils.extmath import randomized_range_finder, safe_sparse_dot, svd_flip\n'), ((12577, 12649), 'scipy.linalg.svd', 'linalg.svd', (['B'], {'full_matrices': '(False)', 'check_finite': '(False)', 'overwrite_a': '(True)'}), '(B, full_matrices=False, check_finite=False, overwrite_a=True)\n', (12587, 12649), False, 'from scipy import linalg\n'), ((12699, 12714), 'numpy.dot', 'np.dot', (['Q', 'Uhat'], {}), '(Q, Uhat)\n', (12705, 12714), True, 'import numpy as np\n'), ((14372, 14409), 'sklearn.utils.check_random_state', 'check_random_state', (['self.random_state'], {}), '(self.random_state)\n', (14390, 14409), False, 'from sklearn.utils import check_array, check_random_state\n'), ((15071, 15109), 'sklearn.utils.extmath.safe_sparse_dot', 'safe_sparse_dot', (['X', 'self.components_.T'], {}), '(X, self.components_.T)\n', (15086, 15109), False, 'from sklearn.utils.extmath import randomized_range_finder, safe_sparse_dot, svd_flip\n'), ((15621, 15659), 'sklearn.utils.extmath.safe_sparse_dot', 'safe_sparse_dot', (['X', 'self.components_.T'], {}), '(X, self.components_.T)\n', (15636, 15659), False, 'from sklearn.utils.extmath import randomized_range_finder, safe_sparse_dot, svd_flip\n'), ((12792, 12807), 'sklearn.utils.extmath.svd_flip', 'svd_flip', (['U', 'Vt'], {}), '(U, Vt)\n', (12800, 12807), False, 'from sklearn.utils.extmath import randomized_range_finder, safe_sparse_dot, svd_flip\n'), ((12969, 13008), 'sklearn.utils.extmath.svd_flip', 'svd_flip', (['U', 'Vt'], {'u_based_decision': '(False)'}), '(U, Vt, u_based_decision=False)\n', (12977, 13008), False, 'from sklearn.utils.extmath import randomized_range_finder, safe_sparse_dot, svd_flip\n')]
|
#!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Project: Project4
@File : app.py
@Author : <NAME>
@Time : 2021/12/3
"""
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
from surprise import KNNBasic, Reader, Dataset
import warnings
warnings.filterwarnings("ignore")
def get_top_10(new_rate):
new_rate = pd.DataFrame({'movieID': movieID, 'rate': new_rate})
new_rate['iid'] = new_rate['movieID'].map(lambda x: trainset.to_inner_iid(x))
iid_to_rate = {iid: rate for iid, rate in zip(new_rate['iid'], new_rate['rate'])}
est_rate = []
for mid, iid, rate in zip(new_rate['movieID'], new_rate['iid'], new_rate['rate']):
if rate != 0:
est_rate.append(-1)
continue
nei_rate = []
nei_weight = []
kneighbors = algo.get_neighbors(iid, 20)
for nei in kneighbors:
r = iid_to_rate[nei]
if r == 0:
continue
nei_rate.append(r)
nei_weight.append(algo.sim[iid, nei])
if len(nei_rate) == 0:
est_rate.append(movie_avg[mid])
else:
est_rate.append(np.average(nei_rate, weights=nei_weight))
new_rate['est_rate'] = est_rate
top10 = new_rate.sort_values(['est_rate'], ascending=False)[:10]['movieID'].tolist()
return top10
def get_movie_src(id):
src = "https://liangfgithub.github.io/MovieImages/{}.jpg?raw=true"
return src.format(id)
def get_image_oneline(id_list, rank=None):
children = []
if rank is None:
for id in id_list:
ch = html.Div(style={'width': '18%', 'display': 'inline-block', "margin-right": "15px"}, children=[
html.Img(src=get_movie_src(id), style={"margin-bottom": "15px"}),
html.Div(movieid_to_name[id])
])
children.append(ch)
else:
for id, rk in zip(id_list, rank):
ch = html.Div(style={'width': '18%', 'display': 'inline-block', "margin-right": "15px"}, children=[
html.H3('Top {}'.format(rk)),
html.Img(src=get_movie_src(id), style={"margin-bottom": "15px"}),
html.Div(movieid_to_name[id])
])
children.append(ch)
return html.Div(style={'textAlign': 'center', 'align-items': 'center'}, children=children)
def get_image(id_list, rank=None):
children = []
if rank is None:
for i in range(0, len(id_list) - 2, 5):
five_list = id_list[i:i+5]
children.append(get_image_oneline(five_list))
children.append(html.Hr(style={"margin-bottom": "25px", "margin-top": "25px"}))
return html.Div(style={'textAlign': 'center', 'align-items': 'center'}, children=children)
else:
for i in range(0, len(id_list) - 2, 5):
five_list = id_list[i:i+5]
children.append(get_image_oneline(five_list, rank[i:i+5]))
children.append(html.Hr(style={"margin-bottom": "25px", "margin-top": "25px"}))
return html.Div(style={'textAlign': 'center', 'align-items': 'center'}, children=children)
def get_image_oneline_radio(id_list):
children = []
for id in id_list:
ch = html.Div(style={'width': '18%', 'display': 'inline-block', "margin-right": "15px"}, children=[
html.Img(src=get_movie_src(id), style={"margin-bottom": "15px"}),
html.Div(movieid_to_name[id], style={"margin-bottom": "15px"}),
dcc.RadioItems(
id='rating_input_{}'.format(id),
options=[{'label': str(i), 'value': str(i)} for i in range(1, 6)],
value=None,
labelStyle={'display': 'inline-block'}
)
])
children.append(ch)
return html.Div(style={'textAlign': 'center', 'align-items': 'center'}, children=children)
def get_image_radio(id_list):
children = []
for i in range(0, len(id_list) - 2, 5):
five_list = id_list[i:i+5]
children.append(get_image_oneline_radio(five_list))
children.append(html.Hr(style={"margin-bottom": "30px", "margin-top": "30px"}))
return html.Div(style={'textAlign': 'center', 'align-items': 'center', "margin-top": "15px",
"maxHeight": "650px", "overflow": "scroll"}, children=children)
tabs_styles = {
'height': '44px'
}
tab_style = {
'borderBottom': '1px solid #d6d6d6',
'padding': '6px',
'fontWeight': 'bold'
}
tab_selected_style = {
'borderTop': '1px solid #d6d6d6',
'borderBottom': '1px solid #d6d6d6',
'backgroundColor': '#119DFF',
'color': 'white',
'padding': '6px'
}
button_style = {'background-color': '#228B22',
'font-size': '20px',
'color': 'white',
'height': '60px',
'width': '250px'}
myurl = "https://liangfgithub.github.io/MovieData/"
ratings = pd.read_csv(myurl + 'ratings.dat?raw=true', header=None, sep=':').dropna(axis=1)
ratings.columns = ['UserID', 'MovieID', 'Rating', 'Timestamp']
ratings.drop(['Timestamp'], axis=1, inplace=True)
movies = pd.read_csv(myurl + 'movies.dat?raw=true', header=None, sep='::', encoding='latin1')
movies.columns = ['MovieID', 'Title', 'Genres']
movieid_to_name = {}
for key, value in zip(movies['MovieID'], movies['Title']):
movieid_to_name[key] = value
movies['Genres'] = movies['Genres'].map(lambda s: s.split('|'))
genre_list = ["Action", "Adventure", "Animation",
"Children's", "Comedy", "Crime",
"Documentary", "Drama", "Fantasy",
"Film-Noir", "Horror", "Musical",
"Mystery", "Romance", "Sci-Fi",
"Thriller", "War", "Western"]
movieID = np.sort(ratings['MovieID'].unique()).tolist()
id_displaying = movieID[:50]
states = [State('rating_input_{}'.format(id), 'value') for id in id_displaying]
for g in genre_list:
movies[g] = movies['Genres'].map(lambda x: 1 if g in x else 0)
movie_pop = ratings.groupby(['MovieID'])['Rating'].agg(['mean', 'count']).reset_index()
genre_popular_10 = pd.DataFrame()
# geren_highrate_10 = pd.DataFrame()
for genre in genre_list:
movie_spe_genre = movies.loc[movies[genre] == 1, ['MovieID', 'Title']]
movie_spe_genre = pd.merge(movie_spe_genre, movie_pop, on='MovieID')
# movie_spe_genre.sort_values(['count'], ascending=False)[:10]['MovieID'].values.tolist()
most_popular_10 = movie_spe_genre.sort_values(['count'], ascending=False)[:10]['MovieID'].values.tolist()
# high_rated_10 = movie_spe_genre[movie_spe_genre['count'] >= 10]
# high_rated_10 = high_rated_10.sort_values(['mean'], ascending=False)[:10]['MovieID'].values.tolist()
genre_popular_10[genre] = most_popular_10
# geren_highrate_10[genre] = high_rated_10
# model
# A reader is still needed but only the rating_scale param is requiered.
reader = Reader(rating_scale=(1, 5))
# The columns must correspond to user id, item id and ratings (in that order).
data = Dataset.load_from_df(ratings[['UserID', 'MovieID', 'Rating']], reader)
sim_options = {'name': 'cosine',
'user_based': False}
trainset = data.build_full_trainset()
algo = KNNBasic(k=20, min_k=1, sim_options=sim_options)
algo.fit(trainset)
movie_avg = {i: avg for i, avg in zip(movie_pop['MovieID'], movie_pop['mean'])}
def get_movie_src(idx):
src = "https://liangfgithub.github.io/MovieImages/{}.jpg?raw=true"
return src.format(idx)
def get_sys1_output():
children = [
html.H2('Please select your favorite genre'),
html.Div(style={'width': '100%', 'display': 'flex', 'align-items': 'center', 'justify-content': 'center'},
children=[
dcc.Dropdown(
id='genre_dropdown',
options=[{'label': g, 'value': g} for g in genre_list],
placeholder="Select a Genre",
clearable=False,
style={'width': '350px', "margin-bottom": "15px"}
)
]),
html.Button('Get Recommendations', id='genre_button',
n_clicks=0, style = button_style),
html.Hr(style={"margin-bottom": "25px", "margin-top": "25px"}),
html.Div(style={'width': '100%', 'display': 'inline'}, children=[
html.H2('Movies you might like'),
html.Div(id='genre_output', children=None)
])
]
return html.Div(children=children)
def get_sys2_output():
children = [
html.H2('Please rate some movies then click the button', style={"margin-bottom": "15px"}),
html.H2('Wait for about 10 seconds then scroll to the bottom to see the recommendations', style={"margin-bottom": "15px"}),
html.Button('Get Recommendations', id='rating_button',
n_clicks=0, style=button_style),
get_image_radio(id_displaying),
html.Hr(style={"margin-bottom": "25px", "margin-top": "25px"}),
html.Div(style={'width': '100%', 'display': 'inline'}, children=[
html.H2('Movies you might like'),
html.Div(id='rating_output', children=None)
])
]
return html.Div(children=children)
app = dash.Dash(__name__, suppress_callback_exceptions=True)
app.layout = html.Div(style={'textAlign': 'center', 'align-items': 'center'}, children=[
dcc.Tabs(id='system_tab', value='tab_1', children=[
dcc.Tab(label='System1: Recommender by Genre', value='tab_1', style=tab_style, selected_style=tab_selected_style),
dcc.Tab(label='System2: Recommender by Rating', value='tab_2', style=tab_style, selected_style=tab_selected_style),
], style=tabs_styles),
html.Div(id='sys_output', children=None)
])
# tab callback
@app.callback(
Output('sys_output', 'children'),
Input('system_tab', 'value'))
def update_sys_out(system):
if system == 'tab_1':
return get_sys1_output()
else:
return get_sys2_output()
@app.callback(Output('genre_output', 'children'),
Input('genre_button', 'n_clicks'),
State('genre_dropdown', 'value'), prevent_initial_call=True)
def update_output(n_clicks, genre):
return [get_image(genre_popular_10[genre].values.tolist())]
@app.callback(Output("rating_output", "children"),
Input('rating_button', 'n_clicks'),
states, prevent_initial_call=True)
def update_rating_output(n_clicks, *rates):
new_rate = []
for rate in rates:
if rate is None:
new_rate.append(0)
else:
new_rate.append(int(rate))
new_rate = new_rate + [0] * (len(movieID) - len(new_rate))
recommend_id = get_top_10(new_rate)
return [get_image(recommend_id, rank=[i+1 for i in range(10)])]
if __name__ == '__main__':
# style={"maxHeight": "250px", "overflow": "scroll"}
app.run_server(debug=False)
|
[
"pandas.DataFrame",
"dash.html.H2",
"dash.Dash",
"numpy.average",
"surprise.Dataset.load_from_df",
"pandas.read_csv",
"surprise.Reader",
"warnings.filterwarnings",
"dash.html.Div",
"pandas.merge",
"dash.dependencies.State",
"dash.html.Button",
"dash.dcc.Tab",
"dash.dependencies.Input",
"dash.dcc.Dropdown",
"surprise.KNNBasic",
"dash.html.Hr",
"dash.dependencies.Output"
] |
[((335, 368), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (358, 368), False, 'import warnings\n'), ((5181, 5270), 'pandas.read_csv', 'pd.read_csv', (["(myurl + 'movies.dat?raw=true')"], {'header': 'None', 'sep': '"""::"""', 'encoding': '"""latin1"""'}), "(myurl + 'movies.dat?raw=true', header=None, sep='::', encoding=\n 'latin1')\n", (5192, 5270), True, 'import pandas as pd\n'), ((6144, 6158), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6156, 6158), True, 'import pandas as pd\n'), ((6936, 6963), 'surprise.Reader', 'Reader', ([], {'rating_scale': '(1, 5)'}), '(rating_scale=(1, 5))\n', (6942, 6963), False, 'from surprise import KNNBasic, Reader, Dataset\n'), ((7050, 7120), 'surprise.Dataset.load_from_df', 'Dataset.load_from_df', (["ratings[['UserID', 'MovieID', 'Rating']]", 'reader'], {}), "(ratings[['UserID', 'MovieID', 'Rating']], reader)\n", (7070, 7120), False, 'from surprise import KNNBasic, Reader, Dataset\n'), ((7235, 7283), 'surprise.KNNBasic', 'KNNBasic', ([], {'k': '(20)', 'min_k': '(1)', 'sim_options': 'sim_options'}), '(k=20, min_k=1, sim_options=sim_options)\n', (7243, 7283), False, 'from surprise import KNNBasic, Reader, Dataset\n'), ((9284, 9338), 'dash.Dash', 'dash.Dash', (['__name__'], {'suppress_callback_exceptions': '(True)'}), '(__name__, suppress_callback_exceptions=True)\n', (9293, 9338), False, 'import dash\n'), ((411, 463), 'pandas.DataFrame', 'pd.DataFrame', (["{'movieID': movieID, 'rate': new_rate}"], {}), "({'movieID': movieID, 'rate': new_rate})\n", (423, 463), True, 'import pandas as pd\n'), ((2341, 2429), 'dash.html.Div', 'html.Div', ([], {'style': "{'textAlign': 'center', 'align-items': 'center'}", 'children': 'children'}), "(style={'textAlign': 'center', 'align-items': 'center'}, children=\n children)\n", (2349, 2429), False, 'from dash import html\n'), ((3852, 3940), 'dash.html.Div', 'html.Div', ([], {'style': "{'textAlign': 'center', 'align-items': 'center'}", 'children': 'children'}), "(style={'textAlign': 'center', 'align-items': 'center'}, children=\n children)\n", (3860, 3940), False, 'from dash import html\n'), ((4224, 4381), 'dash.html.Div', 'html.Div', ([], {'style': "{'textAlign': 'center', 'align-items': 'center', 'margin-top': '15px',\n 'maxHeight': '650px', 'overflow': 'scroll'}", 'children': 'children'}), "(style={'textAlign': 'center', 'align-items': 'center',\n 'margin-top': '15px', 'maxHeight': '650px', 'overflow': 'scroll'},\n children=children)\n", (4232, 4381), False, 'from dash import html\n'), ((6319, 6369), 'pandas.merge', 'pd.merge', (['movie_spe_genre', 'movie_pop'], {'on': '"""MovieID"""'}), "(movie_spe_genre, movie_pop, on='MovieID')\n", (6327, 6369), True, 'import pandas as pd\n'), ((8517, 8544), 'dash.html.Div', 'html.Div', ([], {'children': 'children'}), '(children=children)\n', (8525, 8544), False, 'from dash import html\n'), ((9249, 9276), 'dash.html.Div', 'html.Div', ([], {'children': 'children'}), '(children=children)\n', (9257, 9276), False, 'from dash import html\n'), ((9857, 9889), 'dash.dependencies.Output', 'Output', (['"""sys_output"""', '"""children"""'], {}), "('sys_output', 'children')\n", (9863, 9889), False, 'from dash.dependencies import Input, Output, State\n'), ((9895, 9923), 'dash.dependencies.Input', 'Input', (['"""system_tab"""', '"""value"""'], {}), "('system_tab', 'value')\n", (9900, 9923), False, 'from dash.dependencies import Input, Output, State\n'), ((10070, 10104), 'dash.dependencies.Output', 'Output', (['"""genre_output"""', '"""children"""'], {}), "('genre_output', 'children')\n", (10076, 10104), False, 'from dash.dependencies import Input, Output, State\n'), ((10120, 10153), 'dash.dependencies.Input', 'Input', (['"""genre_button"""', '"""n_clicks"""'], {}), "('genre_button', 'n_clicks')\n", (10125, 10153), False, 'from dash.dependencies import Input, Output, State\n'), ((10169, 10201), 'dash.dependencies.State', 'State', (['"""genre_dropdown"""', '"""value"""'], {}), "('genre_dropdown', 'value')\n", (10174, 10201), False, 'from dash.dependencies import Input, Output, State\n'), ((10345, 10380), 'dash.dependencies.Output', 'Output', (['"""rating_output"""', '"""children"""'], {}), "('rating_output', 'children')\n", (10351, 10380), False, 'from dash.dependencies import Input, Output, State\n'), ((10396, 10430), 'dash.dependencies.Input', 'Input', (['"""rating_button"""', '"""n_clicks"""'], {}), "('rating_button', 'n_clicks')\n", (10401, 10430), False, 'from dash.dependencies import Input, Output, State\n'), ((2753, 2841), 'dash.html.Div', 'html.Div', ([], {'style': "{'textAlign': 'center', 'align-items': 'center'}", 'children': 'children'}), "(style={'textAlign': 'center', 'align-items': 'center'}, children=\n children)\n", (2761, 2841), False, 'from dash import html\n'), ((3113, 3201), 'dash.html.Div', 'html.Div', ([], {'style': "{'textAlign': 'center', 'align-items': 'center'}", 'children': 'children'}), "(style={'textAlign': 'center', 'align-items': 'center'}, children=\n children)\n", (3121, 3201), False, 'from dash import html\n'), ((4978, 5043), 'pandas.read_csv', 'pd.read_csv', (["(myurl + 'ratings.dat?raw=true')"], {'header': 'None', 'sep': '""":"""'}), "(myurl + 'ratings.dat?raw=true', header=None, sep=':')\n", (4989, 5043), True, 'import pandas as pd\n'), ((7556, 7600), 'dash.html.H2', 'html.H2', (['"""Please select your favorite genre"""'], {}), "('Please select your favorite genre')\n", (7563, 7600), False, 'from dash import html\n'), ((8132, 8222), 'dash.html.Button', 'html.Button', (['"""Get Recommendations"""'], {'id': '"""genre_button"""', 'n_clicks': '(0)', 'style': 'button_style'}), "('Get Recommendations', id='genre_button', n_clicks=0, style=\n button_style)\n", (8143, 8222), False, 'from dash import html\n'), ((8249, 8311), 'dash.html.Hr', 'html.Hr', ([], {'style': "{'margin-bottom': '25px', 'margin-top': '25px'}"}), "(style={'margin-bottom': '25px', 'margin-top': '25px'})\n", (8256, 8311), False, 'from dash import html\n'), ((8594, 8688), 'dash.html.H2', 'html.H2', (['"""Please rate some movies then click the button"""'], {'style': "{'margin-bottom': '15px'}"}), "('Please rate some movies then click the button', style={\n 'margin-bottom': '15px'})\n", (8601, 8688), False, 'from dash import html\n'), ((8693, 8825), 'dash.html.H2', 'html.H2', (['"""Wait for about 10 seconds then scroll to the bottom to see the recommendations"""'], {'style': "{'margin-bottom': '15px'}"}), "(\n 'Wait for about 10 seconds then scroll to the bottom to see the recommendations'\n , style={'margin-bottom': '15px'})\n", (8700, 8825), False, 'from dash import html\n'), ((8825, 8916), 'dash.html.Button', 'html.Button', (['"""Get Recommendations"""'], {'id': '"""rating_button"""', 'n_clicks': '(0)', 'style': 'button_style'}), "('Get Recommendations', id='rating_button', n_clicks=0, style=\n button_style)\n", (8836, 8916), False, 'from dash import html\n'), ((8981, 9043), 'dash.html.Hr', 'html.Hr', ([], {'style': "{'margin-bottom': '25px', 'margin-top': '25px'}"}), "(style={'margin-bottom': '25px', 'margin-top': '25px'})\n", (8988, 9043), False, 'from dash import html\n'), ((4149, 4211), 'dash.html.Hr', 'html.Hr', ([], {'style': "{'margin-bottom': '30px', 'margin-top': '30px'}"}), "(style={'margin-bottom': '30px', 'margin-top': '30px'})\n", (4156, 4211), False, 'from dash import html\n'), ((9777, 9817), 'dash.html.Div', 'html.Div', ([], {'id': '"""sys_output"""', 'children': 'None'}), "(id='sys_output', children=None)\n", (9785, 9817), False, 'from dash import html\n'), ((1218, 1258), 'numpy.average', 'np.average', (['nei_rate'], {'weights': 'nei_weight'}), '(nei_rate, weights=nei_weight)\n', (1228, 1258), True, 'import numpy as np\n'), ((2674, 2736), 'dash.html.Hr', 'html.Hr', ([], {'style': "{'margin-bottom': '25px', 'margin-top': '25px'}"}), "(style={'margin-bottom': '25px', 'margin-top': '25px'})\n", (2681, 2736), False, 'from dash import html\n'), ((3034, 3096), 'dash.html.Hr', 'html.Hr', ([], {'style': "{'margin-bottom': '25px', 'margin-top': '25px'}"}), "(style={'margin-bottom': '25px', 'margin-top': '25px'})\n", (3041, 3096), False, 'from dash import html\n'), ((3479, 3541), 'dash.html.Div', 'html.Div', (['movieid_to_name[id]'], {'style': "{'margin-bottom': '15px'}"}), "(movieid_to_name[id], style={'margin-bottom': '15px'})\n", (3487, 3541), False, 'from dash import html\n'), ((7766, 7962), 'dash.dcc.Dropdown', 'dcc.Dropdown', ([], {'id': '"""genre_dropdown"""', 'options': "[{'label': g, 'value': g} for g in genre_list]", 'placeholder': '"""Select a Genre"""', 'clearable': '(False)', 'style': "{'width': '350px', 'margin-bottom': '15px'}"}), "(id='genre_dropdown', options=[{'label': g, 'value': g} for g in\n genre_list], placeholder='Select a Genre', clearable=False, style={\n 'width': '350px', 'margin-bottom': '15px'})\n", (7778, 7962), False, 'from dash import dcc\n'), ((8400, 8432), 'dash.html.H2', 'html.H2', (['"""Movies you might like"""'], {}), "('Movies you might like')\n", (8407, 8432), False, 'from dash import html\n'), ((8446, 8488), 'dash.html.Div', 'html.Div', ([], {'id': '"""genre_output"""', 'children': 'None'}), "(id='genre_output', children=None)\n", (8454, 8488), False, 'from dash import html\n'), ((9131, 9163), 'dash.html.H2', 'html.H2', (['"""Movies you might like"""'], {}), "('Movies you might like')\n", (9138, 9163), False, 'from dash import html\n'), ((9177, 9220), 'dash.html.Div', 'html.Div', ([], {'id': '"""rating_output"""', 'children': 'None'}), "(id='rating_output', children=None)\n", (9185, 9220), False, 'from dash import html\n'), ((1853, 1882), 'dash.html.Div', 'html.Div', (['movieid_to_name[id]'], {}), '(movieid_to_name[id])\n', (1861, 1882), False, 'from dash import html\n'), ((2253, 2282), 'dash.html.Div', 'html.Div', (['movieid_to_name[id]'], {}), '(movieid_to_name[id])\n', (2261, 2282), False, 'from dash import html\n'), ((9498, 9616), 'dash.dcc.Tab', 'dcc.Tab', ([], {'label': '"""System1: Recommender by Genre"""', 'value': '"""tab_1"""', 'style': 'tab_style', 'selected_style': 'tab_selected_style'}), "(label='System1: Recommender by Genre', value='tab_1', style=\n tab_style, selected_style=tab_selected_style)\n", (9505, 9616), False, 'from dash import dcc\n'), ((9625, 9744), 'dash.dcc.Tab', 'dcc.Tab', ([], {'label': '"""System2: Recommender by Rating"""', 'value': '"""tab_2"""', 'style': 'tab_style', 'selected_style': 'tab_selected_style'}), "(label='System2: Recommender by Rating', value='tab_2', style=\n tab_style, selected_style=tab_selected_style)\n", (9632, 9744), False, 'from dash import dcc\n')]
|
from OSIM.Simulation.NetToComp import NetToComp
from OSIM.Modeling.CircuitSystemEquations import CircuitSystemEquations
from OSIM.Simulation.CircuitAnalysis.CircuitAnalyser import CircuitAnalyser
import numpy as np
seq = CircuitSystemEquations(NetToComp('GilberMixerEasy.net').getComponents())
ca = CircuitAnalyser(seq)
mag = ca.getGain("V1","Q1C",180e9)
print("gain")
print(mag)
ca.printDCOp(["vCurMirror","Q7IT","Q6C","RFPlus","Q1C"])
#imp1_180 = ca.getImpedanceAt("V1",180e9)
#imp3_180 = ca.getImpedanceAt("V3",180e9)
#imp4_18 = ca.getImpedanceAt("V4",18e9)
#imp5_18 = ca.getImpedanceAt("V5",18e9)
#print("IMP1_180 @180G: %s"%str(imp1_180))
#print("IMP3_180 @180G: %s"%str(imp3_180))
#print("IMP4_18 @18G: %s"%str((imp4_18)))
#print("IMP5_18 @18G: %s"%str(imp5_18))
#print(imp6)
#v1 = seq.getCompByName("V1").setInnerImpedance(imp[0])
#seq.getCompByName("V3").setInnerImpedance(imp[0])
#print(v1.getInnerImpedance())
#ca.plot_smith(ca.getSPAnalysis_linx(175e9,185e9,1e9,["V3"]))
#ca.plot_lin(ca.getACAnalysis_linx("V1",["Q1C"],170e9,190e9,1e9)[0])
res = ca.getTrans(0,1e-10,1e-13,["Q3C","Q1C","LOPlus","RFPlus"])
#mag = ca.getGain("V1","Q1C",180e9)
#print(mag)
# how to get a diff-Signal
out = np.zeros((2,res[0].shape[1]),dtype = np.float64)
for i in range(res[0].shape[1]):
out[0][i] = (res[0])[0][i]
out[1][i] = (res[0])[1][i] - (res[0])[2][i]
ca.plot_lin([out,["diffout"],"transient"])
print("Max %G "%np.amax(out[1][:]))
toFile = open("Gilbert_out_OSIM.csv", 'w')
for i in range (res[0].shape[1]):
t = str((res[0])[0][i])
plot = str(out[1][i])
wline = "".join((t,",",plot,"\n"))
toFile.write(wline)
toFile.close()
ca.plot_lin(res)
|
[
"numpy.zeros",
"OSIM.Simulation.NetToComp.NetToComp",
"OSIM.Simulation.CircuitAnalysis.CircuitAnalyser.CircuitAnalyser",
"numpy.amax"
] |
[((300, 320), 'OSIM.Simulation.CircuitAnalysis.CircuitAnalyser.CircuitAnalyser', 'CircuitAnalyser', (['seq'], {}), '(seq)\n', (315, 320), False, 'from OSIM.Simulation.CircuitAnalysis.CircuitAnalyser import CircuitAnalyser\n'), ((1206, 1254), 'numpy.zeros', 'np.zeros', (['(2, res[0].shape[1])'], {'dtype': 'np.float64'}), '((2, res[0].shape[1]), dtype=np.float64)\n', (1214, 1254), True, 'import numpy as np\n'), ((1427, 1445), 'numpy.amax', 'np.amax', (['out[1][:]'], {}), '(out[1][:])\n', (1434, 1445), True, 'import numpy as np\n'), ((245, 277), 'OSIM.Simulation.NetToComp.NetToComp', 'NetToComp', (['"""GilberMixerEasy.net"""'], {}), "('GilberMixerEasy.net')\n", (254, 277), False, 'from OSIM.Simulation.NetToComp import NetToComp\n')]
|
import numpy as np
def get_fuel_v1(mass):
return int(np.floor(mass / 3) - 2)
def get_fuel_v2(mass):
fuel = int(np.floor(mass / 3) - 2)
if fuel <= 0:
return 0
else:
return fuel + get_fuel_v2(fuel)
def load_inputs(filename):
with open(filename) as f:
return [int(line.strip()) for line in f]
module_masses = load_inputs("input.txt")
module_fuels = map(get_fuel_v2, module_masses)
total = sum(module_fuels)
print("Total: ", total)
|
[
"numpy.floor"
] |
[((58, 76), 'numpy.floor', 'np.floor', (['(mass / 3)'], {}), '(mass / 3)\n', (66, 76), True, 'import numpy as np\n'), ((121, 139), 'numpy.floor', 'np.floor', (['(mass / 3)'], {}), '(mass / 3)\n', (129, 139), True, 'import numpy as np\n')]
|
import os
import sys
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import optotrak.calibrationcore as cc
from utils.logger import *
#import analysis.delayedfeedback.database as db
#import analysis.delayedfeedback.datalayer as dtl
import analysis.delayedfeedback.analyze_delayedfeedback as adf
datapath = "../../../data/delayedfeedback"
procpath = "../../../processed/delayedfeedback"
def read_optotrak_offline_trajectory(blockpath):
opto_filename = os.path.join(os.path.dirname(__file__), blockpath, "REC-001.OPTO.npy")
data = np.load(opto_filename).astype(float)
data[np.abs(data) > 1.0e6] = np.NAN
return data
def read_optotrak_odau(blockpath):
odau_filename = os.path.join(os.path.dirname(__file__), blockpath, "REC-001.ODAU.npy")
data = np.load(odau_filename).astype(float)
return data
def read_online_trajectory(blockpath):
nplogfilename = os.path.join(os.path.dirname(__file__), blockpath + "/datarecorder.pkl")
print("Reading {}".format(nplogfilename))
nplog = NPLog.from_file(nplogfilename)
#print("Arrays logged: {}".format(nplog.get_names()))
t, data = nplog.stack("realtimedata")
framenumbers = np.squeeze(np.array([record.framenr for record in data]))
trajectory = np.squeeze(np.array([record.data for record in data]))
trajectory[np.abs(trajectory) > 1.0e6] = np.NAN
x = np.arange(framenumbers[0], framenumbers[-1], 1)
tr = np.stack([np.interp(x, framenumbers, trajectory[:, 0]),
np.interp(x, framenumbers, trajectory[:, 1]),
np.interp(x, framenumbers, trajectory[:, 2]),], axis=-1)
t = np.interp(x, framenumbers, t)
frametimes = np.squeeze(np.array([record.timestamp for record in data]))
frametimes = np.interp(x, framenumbers, frametimes)
# Best linear fit of frametimes to remove jitter
n = len(frametimes)
r = np.vstack([range(n), np.ones(n)])
ab = frametimes.dot(np.linalg.pinv(r))
tfit = ab.dot(r)
return tfit, tr
def realign(data1, data2):
n = 10000
sh = 0
r = np.ones([n, 4])
r[:, :3] = data1[sh:sh+n]
sh = 0
d = np.ones([n, 4])
d[:, :3] = data2[sh:sh+n]
x = np.dot(r.T, np.linalg.pinv(d.T))
r = r[:, :3]
d = np.dot(x, d.T).T[:, :3]
d = np.ones([data2.shape[0], 4])
d[:, :3] = data2
data2 = np.dot(x, d.T).T[:, :3]
return data2
def list_dirs(dirpath):
return [os.path.join(dirpath, o) for o in os.listdir(dirpath) if os.path.isdir(os.path.join(dirpath,o))]
def list_dirs_tree(dirpath):
return [x[0] for x in os.walk(dirpath)][1:]
def ensure_dir_exists(dirpath):
if not os.path.exists(dirpath):
os.makedirs(dirpath)
def iterate_all_blocks(callback):
subjectpathes = list_dirs(datapath)
for subjectpath in subjectpathes:
print("Session path \"{}\"".format(subjectpath))
blockpaths = list_dirs(subjectpath)
for blockpath in blockpaths:
print("Block path \"{}\"".format(blockpath))
callback(blockpath)
def recover_dropped_frames(blockpath):
savepath = blockpath.replace(datapath, procpath)
savepath = os.path.join(os.path.dirname(__file__), savepath)
if not os.path.exists(os.path.join(savepath, "optical.npy")):
print("Reading block {}".format(blockpath))
exit()
t, data = read_online_trajectory(blockpath)
print("Recovered shape: {}".format(data.shape))
print("Saving to: {}".format(savepath))
ensure_dir_exists(savepath)
np.save(os.path.join(savepath, "timestamps.npy"), t)
np.save(os.path.join(savepath, "optical.npy"), data)
def project_to_screen(blockpath):
recover_dropped_frames(blockpath)
savepath = blockpath.replace(datapath, procpath)
savepath = os.path.join(os.path.dirname(__file__), savepath)
if not os.path.exists(os.path.join(savepath, "screen_trajectory.npy")):
calibration = cc.ProjectionCalibration()
calibration.load_from_file(os.path.join(datapath, "projection_calibration.pkl"))
trajectory = np.load(os.path.join(savepath, "optical.npy"))
screen_data = calibration.apply_calibration(trajectory)
np.save(os.path.join(savepath, "screen_trajectory.npy"), screen_data)
def read_restored_trajectory(blockpath):
recover_dropped_frames(blockpath)
#print("Reading OPTO block {}".format(blockpath))
savepath = blockpath.replace(datapath, procpath)
savepath = os.path.join(os.path.dirname(__file__), savepath)
timestamps = np.load(os.path.join(savepath, "timestamps.npy"))
trajectory = np.load(os.path.join(savepath, "optical.npy"))
return timestamps, trajectory
def read_projected_to_screen(blockpath):
project_to_screen(blockpath)
#print("Reading projected to screen data block {}".format(blockpath))
savepath = blockpath.replace(datapath, procpath)
savepath = os.path.join(os.path.dirname(__file__), savepath)
timestamps = np.load(os.path.join(savepath, "timestamps.npy"))
trajectory = np.load(os.path.join(savepath, "screen_trajectory.npy"))
return timestamps, trajectory
def read_sync_EMG(blockpath):
#print("Reading ODAU block {}".format(blockpath))
data = read_optotrak_odau(blockpath)
#print(data.shape)
sync = data[:, 0]
emg = data[:, 1:]
return sync, emg
def filter_EMG(emg, fnyq=0.5 * 1200, fcut=15):
b, a = signal.butter(2, fcut*1.25/fnyq)
y = signal.filtfilt(b, a, np.abs(emg), axis=0, padlen=150)
return y
def filter_trajectory(x, fnyq=0.5 * 120, fcut=15):
b, a = signal.butter(2, fcut*1.25/fnyq)
y = signal.filtfilt(b, a, x, axis=0, padlen=150)
return y
def plot_EMG(emg, filtered):
plt.plot(emg)
plt.plot(filtered)
plt.plot(np.arange(len(filtered))[::10], filtered[::10])
plt.show()
return
def plot_EMG_FFT(x):
NFFT = 1024 # the length of the windowing segments
Fs = 1200 #int(1.0 / dt) # the sampling frequency
fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(np.abs(x))
Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
# The `specgram` method returns 4 objects. They are:
# - Pxx: the periodogram
# - freqs: the frequency vector
# - bins: the centers of the time bins
# - im: the matplotlib.image.AxesImage instance representing the data in the plot
plt.show()
#np.save(os.path.join(savepath, "EMG.npy"), data)
def block_processor_filter_emg(blockpath):
sync, emg = read_sync_EMG(blockpath)
#emg = emg[:20000]
filtered = filter_EMG(emg, fcut=1)[::10] # every 10-th
t, trajectory = read_restored_trajectory(blockpath)
print(filtered.shape, trajectory.shape)
velocity = np.diff(trajectory, axis=0)
acceleration = np.diff(velocity, axis=0)
n = len(acceleration)
print(n, filtered.shape, trajectory.shape)
if np.abs(len(filtered) - len(trajectory)) > 5:
return
nx = 4
lag = 45
xy = np.hstack([filtered[:n-lag], trajectory[lag:n], velocity[lag:n], acceleration[lag:n]])
#xy = np.hstack([filtered[:n], trajectory[:n], velocity[:n], acceleration[:n]])
# Remove NaNs
invalid = np.any(np.isnan(xy), axis=1)
xy = xy[np.logical_not(invalid)]
# Center the data
xy_mean = np.nanmean(xy, axis=0)
cxy = xy - xy_mean
# Whiten the data
w = 1.0 / np.sqrt(np.sum(cxy**2, axis=0)/len(cxy))
wxy = w * cxy
# Cross-correlation
a, b = wxy[:, :nx], wxy[:, nx:]
for i in range(a.shape[1]):
for j in range(b.shape[1]):
cc = np.abs(signal.correlate(a[:, i], b[:, j]))
t = len(cc)
t0 = int(t/2)
lag = np.argmax(cc)-t0
print(i, j, lag)
plt.plot(range(-t0, t-t0), cc)
plt.show()
# Covariance matrix
wxytwxy = np.dot(wxy.T, wxy)/len(wxy)
plt.imshow(wxytwxy)
plt.show()
# Decode trajectory from EMG
cov_xy = wxytwxy[:nx, nx:]
cov_yx = wxytwxy[nx:, :nx]
cov_xx = wxytwxy[:nx, :nx]
print(wxytwxy.shape, cov_xy.shape)
ystar = np.dot(cov_yx, np.linalg.inv(cov_xx)).dot(wxy[:, :nx].T).T
print(ystar.shape)
n = 2000
plt.plot(ystar[:n, :3] + [0, 5, 10])
plt.plot(wxy[:n, nx:nx+3] + [0, 5, 10])
plt.show()
plt.plot(wxy[:, nx+1], wxy[:, nx+2])
plt.plot(ystar[:, 1], ystar[:, 2])
plt.show()
#exit()
#plot_EMG(emg, 10*filtered)
#exit()
def block_processor_optmial_filter(blockpath):
sync, emg = read_sync_EMG(blockpath)
nemg = emg.shape[-1]
t, trajectory = read_restored_trajectory(blockpath)
velocity = np.diff(trajectory, axis=0)
acceleration = np.diff(velocity, axis=0)
#velocity = filter_trajectory(velocity, fcut=30) # returns all NaNs
#acceleration = filter_trajectory(acceleration) # returns all NaNs
filtertype = "blocksum"
if filtertype == "blocksum":
# Block sum filer
emg = np.abs(emg)
emg = np.reshape(emg, newshape=(len(trajectory), emg.shape[-1], -1))
emg = np.sum(emg, axis=-1)
elif filtertype == "lowpass":
emg = filter_EMG(emg, fcut=50)[::10] # every 10-th
#plt.plot(emg[:2000])
#plt.show()
# Low-pass filter
n = len(acceleration)
if np.abs(len(emg) - len(trajectory)) > 5:
return
minlag = -60
maxlag = -10
x = np.vstack([emg[-minlag+lag:n+lag, i] for i in range(emg.shape[-1]) for lag in range(minlag, maxlag)]).T
#x = np.hstack([emg[-minlag+lag:n+lag] for lag in range(minlag, maxlag)])
y = np.hstack([trajectory[-minlag:n], velocity[-minlag:n], acceleration[-minlag:n]])
xy = np.hstack([x, y])
# Remove NaNs
invalid = np.any(np.isnan(xy), axis=1)
ninvalid = np.count_nonzero(invalid)
print("Invalid samples: {}% ({} of {})".format(100*ninvalid/len(xy), ninvalid, len(xy)))
xy = xy[np.logical_not(invalid)]
# Center the data
xy_mean = np.nanmean(xy, axis=0)
cxy = xy - xy_mean
# Whiten the data
w = 1.0 / np.sqrt(np.sum(cxy**2, axis=0)/len(cxy))
wxy = w * cxy
nx = x.shape[1]
print("Regressor size: {}".format(nx))
# Covariance matrix
wxytwxy = np.dot(wxy.T, wxy)/len(wxy)
#plt.imshow(wxytwxy)
#plt.title("Covariance matrix")
#plt.show()
# Decode trajectory from EMG
cov_xy = wxytwxy[:nx, nx:]
cov_yx = wxytwxy[nx:, :nx]
cov_xx = wxytwxy[:nx, :nx]
cov_yy = wxytwxy[nx:, nx:]
# PCA
E, V = np.linalg.eigh(cxy.T.dot(cxy)[:4, :4]/len(cxy))
print("EMG eigenvalues: {}".format(E/np.max(E)))
# Optimal decoder
decoder = np.dot(cov_yx, np.linalg.inv(cov_xx))
decoder_covar = cov_yy - np.dot(cov_yx, np.linalg.inv(cov_xx).dot(cov_xy))
#print(decoder.shape)
#plt.imshow(decoder)
#plt.show()
for i in range(0, 3):
for iemg in range(nemg):
plt.subplot(3, nemg, iemg + nemg*i+1)
plt.plot(decoder[i*3:(i+1)*3, iemg*nx/nemg:(iemg+1)*nx/nemg].T)
plt.title("Ch {}, {}".format(iemg, ["position", "velocity", "acceleration"][i]))
plt.show()
ystar = decoder.dot(wxy[:, :nx].T).T
n = 20000
for f, feat in zip(range(0, 3), ["position", "velocity", "acceleration"]):
fig = plt.figure()
fig.suptitle(feat)
for i, coorname in zip(range(0, 3), ["x", "y", "z"]): # coordinates
plt.subplot(3, 1, i+1)
k = f*3 + i
yi = ystar[:n, k]
ei = decoder_covar[k, k]
plt.fill_between(range(len(yi)), yi-ei, yi+ei, alpha=0.2, linewidth=1)
plt.plot(yi, linewidth=1)
plt.plot(wxy[:n, nx+k], linewidth=1)
plt.title(coorname)
plt.show()
if __name__ == "__main__":
# Recover the missing frames
iterate_all_blocks(recover_dropped_frames)
iterate_all_blocks(project_to_screen)
#exit()
# Filter the EMG
iterate_all_blocks(block_processor_optmial_filter)
exit()
datapath = "../../../data/delayedfeedback"
procpath = "../../../processed/delayedfeedback"
subjectpathes = list_dirs(datapath)
for subjectpath in subjectpathes:
print("Session path \"{}\"".format(subjectpath))
blockpaths = list_dirs(subjectpath)
for blockpath in blockpaths:
print("Block path \"{}\"".format(blockpath))
savepath = blockpath.replace(datapath, procpath)
if not os.path.exists(savepath):
print("Reading block {}".format(blockpath))
t, data = read_online_trajectory(blockpath)
print("Recovered shape: {}".format(data.shape))
print("Saving to: {}".format(savepath))
ensure_dir_exists(savepath)
np.save(os.path.join(savepath, "timestamps.npy"), t)
np.save(os.path.join(savepath, "optical.npy"), data)
|
[
"matplotlib.pyplot.title",
"numpy.load",
"numpy.abs",
"numpy.sum",
"numpy.argmax",
"os.walk",
"numpy.ones",
"numpy.isnan",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.interp",
"os.path.join",
"numpy.linalg.pinv",
"numpy.nanmean",
"matplotlib.pyplot.imshow",
"os.path.dirname",
"numpy.logical_not",
"os.path.exists",
"numpy.max",
"matplotlib.pyplot.subplots",
"scipy.signal.butter",
"matplotlib.pyplot.show",
"scipy.signal.correlate",
"numpy.hstack",
"numpy.linalg.inv",
"numpy.dot",
"os.listdir",
"matplotlib.pyplot.subplot",
"numpy.count_nonzero",
"os.makedirs",
"scipy.signal.filtfilt",
"matplotlib.pyplot.plot",
"optotrak.calibrationcore.ProjectionCalibration",
"numpy.diff",
"numpy.array"
] |
[((1394, 1441), 'numpy.arange', 'np.arange', (['framenumbers[0]', 'framenumbers[-1]', '(1)'], {}), '(framenumbers[0], framenumbers[-1], 1)\n', (1403, 1441), True, 'import numpy as np\n'), ((1659, 1688), 'numpy.interp', 'np.interp', (['x', 'framenumbers', 't'], {}), '(x, framenumbers, t)\n', (1668, 1688), True, 'import numpy as np\n'), ((1784, 1822), 'numpy.interp', 'np.interp', (['x', 'framenumbers', 'frametimes'], {}), '(x, framenumbers, frametimes)\n', (1793, 1822), True, 'import numpy as np\n'), ((2115, 2130), 'numpy.ones', 'np.ones', (['[n, 4]'], {}), '([n, 4])\n', (2122, 2130), True, 'import numpy as np\n'), ((2185, 2200), 'numpy.ones', 'np.ones', (['[n, 4]'], {}), '([n, 4])\n', (2192, 2200), True, 'import numpy as np\n'), ((2340, 2368), 'numpy.ones', 'np.ones', (['[data2.shape[0], 4]'], {}), '([data2.shape[0], 4])\n', (2347, 2368), True, 'import numpy as np\n'), ((5470, 5506), 'scipy.signal.butter', 'signal.butter', (['(2)', '(fcut * 1.25 / fnyq)'], {}), '(2, fcut * 1.25 / fnyq)\n', (5483, 5506), False, 'from scipy import signal\n'), ((5648, 5684), 'scipy.signal.butter', 'signal.butter', (['(2)', '(fcut * 1.25 / fnyq)'], {}), '(2, fcut * 1.25 / fnyq)\n', (5661, 5684), False, 'from scipy import signal\n'), ((5689, 5733), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'x'], {'axis': '(0)', 'padlen': '(150)'}), '(b, a, x, axis=0, padlen=150)\n', (5704, 5733), False, 'from scipy import signal\n'), ((5782, 5795), 'matplotlib.pyplot.plot', 'plt.plot', (['emg'], {}), '(emg)\n', (5790, 5795), True, 'import matplotlib.pyplot as plt\n'), ((5800, 5818), 'matplotlib.pyplot.plot', 'plt.plot', (['filtered'], {}), '(filtered)\n', (5808, 5818), True, 'import matplotlib.pyplot as plt\n'), ((5884, 5894), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5892, 5894), True, 'import matplotlib.pyplot as plt\n'), ((6062, 6083), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)'}), '(nrows=2)\n', (6074, 6083), True, 'import matplotlib.pyplot as plt\n'), ((6438, 6448), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6446, 6448), True, 'import matplotlib.pyplot as plt\n'), ((6788, 6815), 'numpy.diff', 'np.diff', (['trajectory'], {'axis': '(0)'}), '(trajectory, axis=0)\n', (6795, 6815), True, 'import numpy as np\n'), ((6835, 6860), 'numpy.diff', 'np.diff', (['velocity'], {'axis': '(0)'}), '(velocity, axis=0)\n', (6842, 6860), True, 'import numpy as np\n'), ((7034, 7126), 'numpy.hstack', 'np.hstack', (['[filtered[:n - lag], trajectory[lag:n], velocity[lag:n], acceleration[lag:n]]'], {}), '([filtered[:n - lag], trajectory[lag:n], velocity[lag:n],\n acceleration[lag:n]])\n', (7043, 7126), True, 'import numpy as np\n'), ((7346, 7368), 'numpy.nanmean', 'np.nanmean', (['xy'], {'axis': '(0)'}), '(xy, axis=0)\n', (7356, 7368), True, 'import numpy as np\n'), ((7834, 7844), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7842, 7844), True, 'import matplotlib.pyplot as plt\n'), ((7916, 7935), 'matplotlib.pyplot.imshow', 'plt.imshow', (['wxytwxy'], {}), '(wxytwxy)\n', (7926, 7935), True, 'import matplotlib.pyplot as plt\n'), ((7940, 7950), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7948, 7950), True, 'import matplotlib.pyplot as plt\n'), ((8233, 8269), 'matplotlib.pyplot.plot', 'plt.plot', (['(ystar[:n, :3] + [0, 5, 10])'], {}), '(ystar[:n, :3] + [0, 5, 10])\n', (8241, 8269), True, 'import matplotlib.pyplot as plt\n'), ((8274, 8315), 'matplotlib.pyplot.plot', 'plt.plot', (['(wxy[:n, nx:nx + 3] + [0, 5, 10])'], {}), '(wxy[:n, nx:nx + 3] + [0, 5, 10])\n', (8282, 8315), True, 'import matplotlib.pyplot as plt\n'), ((8318, 8328), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8326, 8328), True, 'import matplotlib.pyplot as plt\n'), ((8334, 8374), 'matplotlib.pyplot.plot', 'plt.plot', (['wxy[:, nx + 1]', 'wxy[:, nx + 2]'], {}), '(wxy[:, nx + 1], wxy[:, nx + 2])\n', (8342, 8374), True, 'import matplotlib.pyplot as plt\n'), ((8375, 8409), 'matplotlib.pyplot.plot', 'plt.plot', (['ystar[:, 1]', 'ystar[:, 2]'], {}), '(ystar[:, 1], ystar[:, 2])\n', (8383, 8409), True, 'import matplotlib.pyplot as plt\n'), ((8414, 8424), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8422, 8424), True, 'import matplotlib.pyplot as plt\n'), ((8673, 8700), 'numpy.diff', 'np.diff', (['trajectory'], {'axis': '(0)'}), '(trajectory, axis=0)\n', (8680, 8700), True, 'import numpy as np\n'), ((8720, 8745), 'numpy.diff', 'np.diff', (['velocity'], {'axis': '(0)'}), '(velocity, axis=0)\n', (8727, 8745), True, 'import numpy as np\n'), ((9623, 9708), 'numpy.hstack', 'np.hstack', (['[trajectory[-minlag:n], velocity[-minlag:n], acceleration[-minlag:n]]'], {}), '([trajectory[-minlag:n], velocity[-minlag:n], acceleration[-minlag:n]]\n )\n', (9632, 9708), True, 'import numpy as np\n'), ((9713, 9730), 'numpy.hstack', 'np.hstack', (['[x, y]'], {}), '([x, y])\n', (9722, 9730), True, 'import numpy as np\n'), ((9812, 9837), 'numpy.count_nonzero', 'np.count_nonzero', (['invalid'], {}), '(invalid)\n', (9828, 9837), True, 'import numpy as np\n'), ((10009, 10031), 'numpy.nanmean', 'np.nanmean', (['xy'], {'axis': '(0)'}), '(xy, axis=0)\n', (10019, 10031), True, 'import numpy as np\n'), ((11169, 11179), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11177, 11179), True, 'import matplotlib.pyplot as plt\n'), ((502, 527), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (517, 527), False, 'import os\n'), ((734, 759), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (749, 759), False, 'import os\n'), ((934, 959), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (949, 959), False, 'import os\n'), ((1213, 1258), 'numpy.array', 'np.array', (['[record.framenr for record in data]'], {}), '([record.framenr for record in data])\n', (1221, 1258), True, 'import numpy as np\n'), ((1289, 1331), 'numpy.array', 'np.array', (['[record.data for record in data]'], {}), '([record.data for record in data])\n', (1297, 1331), True, 'import numpy as np\n'), ((1718, 1765), 'numpy.array', 'np.array', (['[record.timestamp for record in data]'], {}), '([record.timestamp for record in data])\n', (1726, 1765), True, 'import numpy as np\n'), ((1975, 1992), 'numpy.linalg.pinv', 'np.linalg.pinv', (['r'], {}), '(r)\n', (1989, 1992), True, 'import numpy as np\n'), ((2252, 2271), 'numpy.linalg.pinv', 'np.linalg.pinv', (['d.T'], {}), '(d.T)\n', (2266, 2271), True, 'import numpy as np\n'), ((2482, 2506), 'os.path.join', 'os.path.join', (['dirpath', 'o'], {}), '(dirpath, o)\n', (2494, 2506), False, 'import os\n'), ((2706, 2729), 'os.path.exists', 'os.path.exists', (['dirpath'], {}), '(dirpath)\n', (2720, 2729), False, 'import os\n'), ((2739, 2759), 'os.makedirs', 'os.makedirs', (['dirpath'], {}), '(dirpath)\n', (2750, 2759), False, 'import os\n'), ((3225, 3250), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3240, 3250), False, 'import os\n'), ((3865, 3890), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3880, 3890), False, 'import os\n'), ((4000, 4026), 'optotrak.calibrationcore.ProjectionCalibration', 'cc.ProjectionCalibration', ([], {}), '()\n', (4024, 4026), True, 'import optotrak.calibrationcore as cc\n'), ((4550, 4575), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4565, 4575), False, 'import os\n'), ((4612, 4652), 'os.path.join', 'os.path.join', (['savepath', '"""timestamps.npy"""'], {}), "(savepath, 'timestamps.npy')\n", (4624, 4652), False, 'import os\n'), ((4679, 4716), 'os.path.join', 'os.path.join', (['savepath', '"""optical.npy"""'], {}), "(savepath, 'optical.npy')\n", (4691, 4716), False, 'import os\n'), ((4983, 5008), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4998, 5008), False, 'import os\n'), ((5045, 5085), 'os.path.join', 'os.path.join', (['savepath', '"""timestamps.npy"""'], {}), "(savepath, 'timestamps.npy')\n", (5057, 5085), False, 'import os\n'), ((5112, 5159), 'os.path.join', 'os.path.join', (['savepath', '"""screen_trajectory.npy"""'], {}), "(savepath, 'screen_trajectory.npy')\n", (5124, 5159), False, 'import os\n'), ((5533, 5544), 'numpy.abs', 'np.abs', (['emg'], {}), '(emg)\n', (5539, 5544), True, 'import numpy as np\n'), ((6097, 6106), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (6103, 6106), True, 'import numpy as np\n'), ((7246, 7258), 'numpy.isnan', 'np.isnan', (['xy'], {}), '(xy)\n', (7254, 7258), True, 'import numpy as np\n'), ((7280, 7303), 'numpy.logical_not', 'np.logical_not', (['invalid'], {}), '(invalid)\n', (7294, 7303), True, 'import numpy as np\n'), ((7884, 7902), 'numpy.dot', 'np.dot', (['wxy.T', 'wxy'], {}), '(wxy.T, wxy)\n', (7890, 7902), True, 'import numpy as np\n'), ((9003, 9014), 'numpy.abs', 'np.abs', (['emg'], {}), '(emg)\n', (9009, 9014), True, 'import numpy as np\n'), ((9106, 9126), 'numpy.sum', 'np.sum', (['emg'], {'axis': '(-1)'}), '(emg, axis=-1)\n', (9112, 9126), True, 'import numpy as np\n'), ((9775, 9787), 'numpy.isnan', 'np.isnan', (['xy'], {}), '(xy)\n', (9783, 9787), True, 'import numpy as np\n'), ((9943, 9966), 'numpy.logical_not', 'np.logical_not', (['invalid'], {}), '(invalid)\n', (9957, 9966), True, 'import numpy as np\n'), ((10262, 10280), 'numpy.dot', 'np.dot', (['wxy.T', 'wxy'], {}), '(wxy.T, wxy)\n', (10268, 10280), True, 'import numpy as np\n'), ((10713, 10734), 'numpy.linalg.inv', 'np.linalg.inv', (['cov_xx'], {}), '(cov_xx)\n', (10726, 10734), True, 'import numpy as np\n'), ((11338, 11350), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (11348, 11350), True, 'import matplotlib.pyplot as plt\n'), ((11793, 11803), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11801, 11803), True, 'import matplotlib.pyplot as plt\n'), ((571, 593), 'numpy.load', 'np.load', (['opto_filename'], {}), '(opto_filename)\n', (578, 593), True, 'import numpy as np\n'), ((617, 629), 'numpy.abs', 'np.abs', (['data'], {}), '(data)\n', (623, 629), True, 'import numpy as np\n'), ((803, 825), 'numpy.load', 'np.load', (['odau_filename'], {}), '(odau_filename)\n', (810, 825), True, 'import numpy as np\n'), ((1348, 1366), 'numpy.abs', 'np.abs', (['trajectory'], {}), '(trajectory)\n', (1354, 1366), True, 'import numpy as np\n'), ((1462, 1506), 'numpy.interp', 'np.interp', (['x', 'framenumbers', 'trajectory[:, 0]'], {}), '(x, framenumbers, trajectory[:, 0])\n', (1471, 1506), True, 'import numpy as np\n'), ((1528, 1572), 'numpy.interp', 'np.interp', (['x', 'framenumbers', 'trajectory[:, 1]'], {}), '(x, framenumbers, trajectory[:, 1])\n', (1537, 1572), True, 'import numpy as np\n'), ((1594, 1638), 'numpy.interp', 'np.interp', (['x', 'framenumbers', 'trajectory[:, 2]'], {}), '(x, framenumbers, trajectory[:, 2])\n', (1603, 1638), True, 'import numpy as np\n'), ((1938, 1948), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (1945, 1948), True, 'import numpy as np\n'), ((2303, 2317), 'numpy.dot', 'np.dot', (['x', 'd.T'], {}), '(x, d.T)\n', (2309, 2317), True, 'import numpy as np\n'), ((2402, 2416), 'numpy.dot', 'np.dot', (['x', 'd.T'], {}), '(x, d.T)\n', (2408, 2416), True, 'import numpy as np\n'), ((2516, 2535), 'os.listdir', 'os.listdir', (['dirpath'], {}), '(dirpath)\n', (2526, 2535), False, 'import os\n'), ((3288, 3325), 'os.path.join', 'os.path.join', (['savepath', '"""optical.npy"""'], {}), "(savepath, 'optical.npy')\n", (3300, 3325), False, 'import os\n'), ((3604, 3644), 'os.path.join', 'os.path.join', (['savepath', '"""timestamps.npy"""'], {}), "(savepath, 'timestamps.npy')\n", (3616, 3644), False, 'import os\n'), ((3665, 3702), 'os.path.join', 'os.path.join', (['savepath', '"""optical.npy"""'], {}), "(savepath, 'optical.npy')\n", (3677, 3702), False, 'import os\n'), ((3928, 3975), 'os.path.join', 'os.path.join', (['savepath', '"""screen_trajectory.npy"""'], {}), "(savepath, 'screen_trajectory.npy')\n", (3940, 3975), False, 'import os\n'), ((4062, 4114), 'os.path.join', 'os.path.join', (['datapath', '"""projection_calibration.pkl"""'], {}), "(datapath, 'projection_calibration.pkl')\n", (4074, 4114), False, 'import os\n'), ((4145, 4182), 'os.path.join', 'os.path.join', (['savepath', '"""optical.npy"""'], {}), "(savepath, 'optical.npy')\n", (4157, 4182), False, 'import os\n'), ((4264, 4311), 'os.path.join', 'os.path.join', (['savepath', '"""screen_trajectory.npy"""'], {}), "(savepath, 'screen_trajectory.npy')\n", (4276, 4311), False, 'import os\n'), ((10958, 10999), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', 'nemg', '(iemg + nemg * i + 1)'], {}), '(3, nemg, iemg + nemg * i + 1)\n', (10969, 10999), True, 'import matplotlib.pyplot as plt\n'), ((11008, 11087), 'matplotlib.pyplot.plot', 'plt.plot', (['decoder[i * 3:(i + 1) * 3, iemg * nx / nemg:(iemg + 1) * nx / nemg].T'], {}), '(decoder[i * 3:(i + 1) * 3, iemg * nx / nemg:(iemg + 1) * nx / nemg].T)\n', (11016, 11087), True, 'import matplotlib.pyplot as plt\n'), ((11467, 11491), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(i + 1)'], {}), '(3, 1, i + 1)\n', (11478, 11491), True, 'import matplotlib.pyplot as plt\n'), ((11677, 11702), 'matplotlib.pyplot.plot', 'plt.plot', (['yi'], {'linewidth': '(1)'}), '(yi, linewidth=1)\n', (11685, 11702), True, 'import matplotlib.pyplot as plt\n'), ((11715, 11753), 'matplotlib.pyplot.plot', 'plt.plot', (['wxy[:n, nx + k]'], {'linewidth': '(1)'}), '(wxy[:n, nx + k], linewidth=1)\n', (11723, 11753), True, 'import matplotlib.pyplot as plt\n'), ((11764, 11783), 'matplotlib.pyplot.title', 'plt.title', (['coorname'], {}), '(coorname)\n', (11773, 11783), True, 'import matplotlib.pyplot as plt\n'), ((2553, 2577), 'os.path.join', 'os.path.join', (['dirpath', 'o'], {}), '(dirpath, o)\n', (2565, 2577), False, 'import os\n'), ((2639, 2655), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (2646, 2655), False, 'import os\n'), ((7441, 7465), 'numpy.sum', 'np.sum', (['(cxy ** 2)'], {'axis': '(0)'}), '(cxy ** 2, axis=0)\n', (7447, 7465), True, 'import numpy as np\n'), ((7645, 7679), 'scipy.signal.correlate', 'signal.correlate', (['a[:, i]', 'b[:, j]'], {}), '(a[:, i], b[:, j])\n', (7661, 7679), False, 'from scipy import signal\n'), ((7749, 7762), 'numpy.argmax', 'np.argmax', (['cc'], {}), '(cc)\n', (7758, 7762), True, 'import numpy as np\n'), ((10104, 10128), 'numpy.sum', 'np.sum', (['(cxy ** 2)'], {'axis': '(0)'}), '(cxy ** 2, axis=0)\n', (10110, 10128), True, 'import numpy as np\n'), ((10645, 10654), 'numpy.max', 'np.max', (['E'], {}), '(E)\n', (10651, 10654), True, 'import numpy as np\n'), ((12520, 12544), 'os.path.exists', 'os.path.exists', (['savepath'], {}), '(savepath)\n', (12534, 12544), False, 'import os\n'), ((8148, 8169), 'numpy.linalg.inv', 'np.linalg.inv', (['cov_xx'], {}), '(cov_xx)\n', (8161, 8169), True, 'import numpy as np\n'), ((10780, 10801), 'numpy.linalg.inv', 'np.linalg.inv', (['cov_xx'], {}), '(cov_xx)\n', (10793, 10801), True, 'import numpy as np\n'), ((12859, 12899), 'os.path.join', 'os.path.join', (['savepath', '"""timestamps.npy"""'], {}), "(savepath, 'timestamps.npy')\n", (12871, 12899), False, 'import os\n'), ((12928, 12965), 'os.path.join', 'os.path.join', (['savepath', '"""optical.npy"""'], {}), "(savepath, 'optical.npy')\n", (12940, 12965), False, 'import os\n')]
|
import numpy as np
import time
from keras.callbacks import TensorBoard, ModelCheckpoint
from keras.models import Model, Input, load_model
from keras.layers.core import Activation
from keras.layers.core import Dense, Dropout
from keras.layers import concatenate
from keras.initializers import he_normal
from DataGenerator import DataGenerator
class MLP:
"""
Creates an MLP that predicts side advantage in a given chess position.
This class compiles a keras model, as well as evaluates pre-existing models.
To create training data, see stockfish_eval.py
"""
def __init__(self,
model_name,
pretrained_weights,
epochs=200,
batch_size=128,
activation_func='relu',
dropout=0.2,
num_classes=2):
np.random.seed(42)
self.model_filename = model_name + '.model'
self.model_name = model_name
self.pretrained_weights = pretrained_weights
self.epochs = epochs
self.batch_size = batch_size
self.activation_func = activation_func
self.dropout = dropout
self.num_classes = num_classes
self.model = None
def train_with_datagen(self):
tensorboard = TensorBoard(log_dir="logs\\{}{}".format(self.model_name, time.time()))
epoch_path = str(self.model_name) + '-{epoch:02d}.model'
checkpoint = ModelCheckpoint(epoch_path, period=4)
# training_boards = list(np.load('known_scores(2.7).npy').item().items())
# val_boards = list(np.load('test_set(166438)_old.npy').item().items())
training_boards = list(np.load('train(18000000)_new.npy').item().items())
val_boards = list(np.load('test(2000000)_new.npy').item().items())
# training_boards = list(np.load('expanded_train(3600000).npy').item().items())
# val_boards = list(np.load('expanded_test(400000).npy').item().items())
# training_boards = list(np.load('train_set(5000000)_FICS.npy').item().items())
# val_boards = list(np.load('test_set(500000)_FICS.npy').item().items())
if self.num_classes > 0:
print('Ternary classification')
training_generator = DataGenerator(training_boards, batch_size=128, categorical=True)
validation_generator = DataGenerator(val_boards, batch_size=128, categorical=True)
self.ternary_classifier()
else:
training_generator = DataGenerator(training_boards, batch_size=128)
validation_generator = DataGenerator(val_boards, batch_size=128)
self.regression_with_encoder()
self.model.fit_generator(generator=training_generator,
validation_data=validation_generator,
use_multiprocessing=True,
workers=2,
epochs=32,
verbose=True,
callbacks=[tensorboard, checkpoint])
# Classify White Win / Black Win / Draw states
def ternary_classifier(self):
board_input = Input(shape=((64 * 12) + 7,), name='board_input')
x = Dense(1024)(board_input)
x = Activation(activation=self.activation_func)(x)
x = Dropout(rate=self.dropout)(x)
x = Dense(512)(x)
x = Activation(activation=self.activation_func)(x)
x = Dropout(rate=self.dropout)(x)
x = Dense(256)(x)
x = Activation(activation=self.activation_func)(x)
x = Dropout(rate=self.dropout)(x)
main_output = Dense(3, name='main_output')(x)
main_output = Activation(activation='softmax')(main_output)
self.model = Model(inputs=[board_input], outputs=[main_output])
self.model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Classify White Win/Black Win states
def binary_classifier(self):
board_input = Input(shape=((64 * 12) + 3,), name='board_input')
x = Dense(1024)(board_input)
x = Activation(activation=self.activation_func)(x)
x = Dropout(self.dropout)(x)
x = Dense(512)(x)
x = Activation(activation=self.activation_func)(x)
x = Dropout(self.dropout)(x)
x = Dense(256)(x)
x = Activation(activation=self.activation_func)(x)
x = Dropout(self.dropout)(x)
main_output = Dense(1, name='main_output')(x)
main_output = Activation(activation='sigmoid')(main_output)
self.model = Model(inputs=[board_input], outputs=[main_output])
self.model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
def regression(self):
board_input = Input(shape=((64 * 12) + 7,), name='board_input')
x = Dense(2048)(board_input)
x = Activation(activation=self.activation_func)(x)
x = Dropout(self.dropout)(x)
x = Dense(2048)(x)
x = Activation(activation=self.activation_func)(x)
x = Dropout(self.dropout)(x)
x = Dense(2048)(x)
x = Activation(activation=self.activation_func)(x)
x = Dropout(self.dropout)(x)
main_output = Dense(1, name='main_output')(x)
main_output = Activation(activation='tanh')(main_output)
self.model = Model(inputs=[board_input], outputs=[main_output])
self.model.compile(optimizer='adam',
loss='mean_squared_error',
metrics=['mse'])
def regression_with_encoder(self):
encoder = load_model('encoder_new_relu-06.model')
# encoder_model = Model(inputs=encoder.input, outputs=encoder.get_layer('activation_3').output)
board_input = Input(shape=((64 * 12) + 7,), name='board_input')
encoded = Dense(512, name='encoder_1', weights=encoder.get_layer('encoder_1').get_weights())(board_input)
encoded = Activation(activation='relu', name='act1')(encoded)
encoded = Dense(256, name='encoder_2', weights=encoder.get_layer('encoder_2').get_weights())(encoded)
encoded = Activation(activation='relu', name='act2')(encoded)
encoded = Dense(128, name='encoder_3', weights=encoder.get_layer('encoder_3').get_weights())(encoded)
encoded = Activation(activation='relu', name='act3')(encoded)
x = Dense(2048, name='eval_1')(board_input)
x = Activation(activation=self.activation_func, name='act4')(x)
x = Dropout(self.dropout, name='drop1')(x)
x = Dense(2048, name='eval_2')(x)
x = Activation(activation=self.activation_func, name='act5')(x)
x = Dropout(self.dropout, name='drop2')(x)
x = Dense(2048, name='eval_3')(x)
x = Activation(activation=self.activation_func, name='act6')(x)
x = Dropout(self.dropout, name='drop3')(x)
main_output = Dense(1, name='evaluation')(x)
main_output = Activation(activation='tanh', name='final_output')(main_output)
self.model = Model(inputs=[board_input], outputs=[main_output])
self.model.compile(optimizer='adam',
loss='mean_squared_error',
metrics=['mse'])
print(self.model.summary())
if __name__ == '__main__':
NN_regression_encoder = MLP('regression_18mill', num_classes=0,
activation_func='relu', pretrained_weights=None, dropout=0.25)
NN_regression_encoder.train_with_datagen()
|
[
"keras.models.load_model",
"keras.layers.core.Dense",
"numpy.load",
"numpy.random.seed",
"keras.callbacks.ModelCheckpoint",
"keras.layers.core.Activation",
"keras.models.Input",
"keras.models.Model",
"time.time",
"DataGenerator.DataGenerator",
"keras.layers.core.Dropout"
] |
[((844, 862), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (858, 862), True, 'import numpy as np\n'), ((1429, 1466), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['epoch_path'], {'period': '(4)'}), '(epoch_path, period=4)\n', (1444, 1466), False, 'from keras.callbacks import TensorBoard, ModelCheckpoint\n'), ((3156, 3203), 'keras.models.Input', 'Input', ([], {'shape': '(64 * 12 + 7,)', 'name': '"""board_input"""'}), "(shape=(64 * 12 + 7,), name='board_input')\n", (3161, 3203), False, 'from keras.models import Model, Input, load_model\n'), ((3746, 3796), 'keras.models.Model', 'Model', ([], {'inputs': '[board_input]', 'outputs': '[main_output]'}), '(inputs=[board_input], outputs=[main_output])\n', (3751, 3796), False, 'from keras.models import Model, Input, load_model\n'), ((4056, 4103), 'keras.models.Input', 'Input', ([], {'shape': '(64 * 12 + 3,)', 'name': '"""board_input"""'}), "(shape=(64 * 12 + 3,), name='board_input')\n", (4061, 4103), False, 'from keras.models import Model, Input, load_model\n'), ((4631, 4681), 'keras.models.Model', 'Model', ([], {'inputs': '[board_input]', 'outputs': '[main_output]'}), '(inputs=[board_input], outputs=[main_output])\n', (4636, 4681), False, 'from keras.models import Model, Input, load_model\n'), ((4881, 4928), 'keras.models.Input', 'Input', ([], {'shape': '(64 * 12 + 7,)', 'name': '"""board_input"""'}), "(shape=(64 * 12 + 7,), name='board_input')\n", (4886, 4928), False, 'from keras.models import Model, Input, load_model\n'), ((5456, 5506), 'keras.models.Model', 'Model', ([], {'inputs': '[board_input]', 'outputs': '[main_output]'}), '(inputs=[board_input], outputs=[main_output])\n', (5461, 5506), False, 'from keras.models import Model, Input, load_model\n'), ((5709, 5748), 'keras.models.load_model', 'load_model', (['"""encoder_new_relu-06.model"""'], {}), "('encoder_new_relu-06.model')\n", (5719, 5748), False, 'from keras.models import Model, Input, load_model\n'), ((5875, 5922), 'keras.models.Input', 'Input', ([], {'shape': '(64 * 12 + 7,)', 'name': '"""board_input"""'}), "(shape=(64 * 12 + 7,), name='board_input')\n", (5880, 5922), False, 'from keras.models import Model, Input, load_model\n'), ((7158, 7208), 'keras.models.Model', 'Model', ([], {'inputs': '[board_input]', 'outputs': '[main_output]'}), '(inputs=[board_input], outputs=[main_output])\n', (7163, 7208), False, 'from keras.models import Model, Input, load_model\n'), ((2237, 2301), 'DataGenerator.DataGenerator', 'DataGenerator', (['training_boards'], {'batch_size': '(128)', 'categorical': '(True)'}), '(training_boards, batch_size=128, categorical=True)\n', (2250, 2301), False, 'from DataGenerator import DataGenerator\n'), ((2337, 2396), 'DataGenerator.DataGenerator', 'DataGenerator', (['val_boards'], {'batch_size': '(128)', 'categorical': '(True)'}), '(val_boards, batch_size=128, categorical=True)\n', (2350, 2396), False, 'from DataGenerator import DataGenerator\n'), ((2482, 2528), 'DataGenerator.DataGenerator', 'DataGenerator', (['training_boards'], {'batch_size': '(128)'}), '(training_boards, batch_size=128)\n', (2495, 2528), False, 'from DataGenerator import DataGenerator\n'), ((2564, 2605), 'DataGenerator.DataGenerator', 'DataGenerator', (['val_boards'], {'batch_size': '(128)'}), '(val_boards, batch_size=128)\n', (2577, 2605), False, 'from DataGenerator import DataGenerator\n'), ((3219, 3230), 'keras.layers.core.Dense', 'Dense', (['(1024)'], {}), '(1024)\n', (3224, 3230), False, 'from keras.layers.core import Dense, Dropout\n'), ((3256, 3299), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (3266, 3299), False, 'from keras.layers.core import Activation\n'), ((3315, 3341), 'keras.layers.core.Dropout', 'Dropout', ([], {'rate': 'self.dropout'}), '(rate=self.dropout)\n', (3322, 3341), False, 'from keras.layers.core import Dense, Dropout\n'), ((3358, 3368), 'keras.layers.core.Dense', 'Dense', (['(512)'], {}), '(512)\n', (3363, 3368), False, 'from keras.layers.core import Dense, Dropout\n'), ((3384, 3427), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (3394, 3427), False, 'from keras.layers.core import Activation\n'), ((3443, 3469), 'keras.layers.core.Dropout', 'Dropout', ([], {'rate': 'self.dropout'}), '(rate=self.dropout)\n', (3450, 3469), False, 'from keras.layers.core import Dense, Dropout\n'), ((3486, 3496), 'keras.layers.core.Dense', 'Dense', (['(256)'], {}), '(256)\n', (3491, 3496), False, 'from keras.layers.core import Dense, Dropout\n'), ((3512, 3555), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (3522, 3555), False, 'from keras.layers.core import Activation\n'), ((3571, 3597), 'keras.layers.core.Dropout', 'Dropout', ([], {'rate': 'self.dropout'}), '(rate=self.dropout)\n', (3578, 3597), False, 'from keras.layers.core import Dense, Dropout\n'), ((3624, 3652), 'keras.layers.core.Dense', 'Dense', (['(3)'], {'name': '"""main_output"""'}), "(3, name='main_output')\n", (3629, 3652), False, 'from keras.layers.core import Dense, Dropout\n'), ((3678, 3710), 'keras.layers.core.Activation', 'Activation', ([], {'activation': '"""softmax"""'}), "(activation='softmax')\n", (3688, 3710), False, 'from keras.layers.core import Activation\n'), ((4119, 4130), 'keras.layers.core.Dense', 'Dense', (['(1024)'], {}), '(1024)\n', (4124, 4130), False, 'from keras.layers.core import Dense, Dropout\n'), ((4156, 4199), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (4166, 4199), False, 'from keras.layers.core import Activation\n'), ((4215, 4236), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {}), '(self.dropout)\n', (4222, 4236), False, 'from keras.layers.core import Dense, Dropout\n'), ((4253, 4263), 'keras.layers.core.Dense', 'Dense', (['(512)'], {}), '(512)\n', (4258, 4263), False, 'from keras.layers.core import Dense, Dropout\n'), ((4279, 4322), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (4289, 4322), False, 'from keras.layers.core import Activation\n'), ((4338, 4359), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {}), '(self.dropout)\n', (4345, 4359), False, 'from keras.layers.core import Dense, Dropout\n'), ((4376, 4386), 'keras.layers.core.Dense', 'Dense', (['(256)'], {}), '(256)\n', (4381, 4386), False, 'from keras.layers.core import Dense, Dropout\n'), ((4402, 4445), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (4412, 4445), False, 'from keras.layers.core import Activation\n'), ((4461, 4482), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {}), '(self.dropout)\n', (4468, 4482), False, 'from keras.layers.core import Dense, Dropout\n'), ((4509, 4537), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'name': '"""main_output"""'}), "(1, name='main_output')\n", (4514, 4537), False, 'from keras.layers.core import Dense, Dropout\n'), ((4563, 4595), 'keras.layers.core.Activation', 'Activation', ([], {'activation': '"""sigmoid"""'}), "(activation='sigmoid')\n", (4573, 4595), False, 'from keras.layers.core import Activation\n'), ((4944, 4955), 'keras.layers.core.Dense', 'Dense', (['(2048)'], {}), '(2048)\n', (4949, 4955), False, 'from keras.layers.core import Dense, Dropout\n'), ((4981, 5024), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (4991, 5024), False, 'from keras.layers.core import Activation\n'), ((5040, 5061), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {}), '(self.dropout)\n', (5047, 5061), False, 'from keras.layers.core import Dense, Dropout\n'), ((5078, 5089), 'keras.layers.core.Dense', 'Dense', (['(2048)'], {}), '(2048)\n', (5083, 5089), False, 'from keras.layers.core import Dense, Dropout\n'), ((5105, 5148), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (5115, 5148), False, 'from keras.layers.core import Activation\n'), ((5164, 5185), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {}), '(self.dropout)\n', (5171, 5185), False, 'from keras.layers.core import Dense, Dropout\n'), ((5202, 5213), 'keras.layers.core.Dense', 'Dense', (['(2048)'], {}), '(2048)\n', (5207, 5213), False, 'from keras.layers.core import Dense, Dropout\n'), ((5229, 5272), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func'}), '(activation=self.activation_func)\n', (5239, 5272), False, 'from keras.layers.core import Activation\n'), ((5288, 5309), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {}), '(self.dropout)\n', (5295, 5309), False, 'from keras.layers.core import Dense, Dropout\n'), ((5336, 5364), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'name': '"""main_output"""'}), "(1, name='main_output')\n", (5341, 5364), False, 'from keras.layers.core import Dense, Dropout\n'), ((5391, 5420), 'keras.layers.core.Activation', 'Activation', ([], {'activation': '"""tanh"""'}), "(activation='tanh')\n", (5401, 5420), False, 'from keras.layers.core import Activation\n'), ((6058, 6100), 'keras.layers.core.Activation', 'Activation', ([], {'activation': '"""relu"""', 'name': '"""act1"""'}), "(activation='relu', name='act1')\n", (6068, 6100), False, 'from keras.layers.core import Activation\n'), ((6247, 6289), 'keras.layers.core.Activation', 'Activation', ([], {'activation': '"""relu"""', 'name': '"""act2"""'}), "(activation='relu', name='act2')\n", (6257, 6289), False, 'from keras.layers.core import Activation\n'), ((6436, 6478), 'keras.layers.core.Activation', 'Activation', ([], {'activation': '"""relu"""', 'name': '"""act3"""'}), "(activation='relu', name='act3')\n", (6446, 6478), False, 'from keras.layers.core import Activation\n'), ((6501, 6527), 'keras.layers.core.Dense', 'Dense', (['(2048)'], {'name': '"""eval_1"""'}), "(2048, name='eval_1')\n", (6506, 6527), False, 'from keras.layers.core import Dense, Dropout\n'), ((6553, 6609), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func', 'name': '"""act4"""'}), "(activation=self.activation_func, name='act4')\n", (6563, 6609), False, 'from keras.layers.core import Activation\n'), ((6625, 6660), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {'name': '"""drop1"""'}), "(self.dropout, name='drop1')\n", (6632, 6660), False, 'from keras.layers.core import Dense, Dropout\n'), ((6677, 6703), 'keras.layers.core.Dense', 'Dense', (['(2048)'], {'name': '"""eval_2"""'}), "(2048, name='eval_2')\n", (6682, 6703), False, 'from keras.layers.core import Dense, Dropout\n'), ((6719, 6775), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func', 'name': '"""act5"""'}), "(activation=self.activation_func, name='act5')\n", (6729, 6775), False, 'from keras.layers.core import Activation\n'), ((6791, 6826), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {'name': '"""drop2"""'}), "(self.dropout, name='drop2')\n", (6798, 6826), False, 'from keras.layers.core import Dense, Dropout\n'), ((6843, 6869), 'keras.layers.core.Dense', 'Dense', (['(2048)'], {'name': '"""eval_3"""'}), "(2048, name='eval_3')\n", (6848, 6869), False, 'from keras.layers.core import Dense, Dropout\n'), ((6885, 6941), 'keras.layers.core.Activation', 'Activation', ([], {'activation': 'self.activation_func', 'name': '"""act6"""'}), "(activation=self.activation_func, name='act6')\n", (6895, 6941), False, 'from keras.layers.core import Activation\n'), ((6957, 6992), 'keras.layers.core.Dropout', 'Dropout', (['self.dropout'], {'name': '"""drop3"""'}), "(self.dropout, name='drop3')\n", (6964, 6992), False, 'from keras.layers.core import Dense, Dropout\n'), ((7019, 7046), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'name': '"""evaluation"""'}), "(1, name='evaluation')\n", (7024, 7046), False, 'from keras.layers.core import Dense, Dropout\n'), ((7072, 7122), 'keras.layers.core.Activation', 'Activation', ([], {'activation': '"""tanh"""', 'name': '"""final_output"""'}), "(activation='tanh', name='final_output')\n", (7082, 7122), False, 'from keras.layers.core import Activation\n'), ((1329, 1340), 'time.time', 'time.time', ([], {}), '()\n', (1338, 1340), False, 'import time\n'), ((1661, 1695), 'numpy.load', 'np.load', (['"""train(18000000)_new.npy"""'], {}), "('train(18000000)_new.npy')\n", (1668, 1695), True, 'import numpy as np\n'), ((1738, 1770), 'numpy.load', 'np.load', (['"""test(2000000)_new.npy"""'], {}), "('test(2000000)_new.npy')\n", (1745, 1770), True, 'import numpy as np\n')]
|
""" Testing driver LatinHypercubeDriver."""
import unittest
from random import seed
from types import GeneratorType
import numpy as np
from openmdao.api import IndepVarComp, Group, Problem, Component
from openmdao.test.paraboloid import Paraboloid
from openmdao.test.util import assert_rel_error
from openmdao.drivers.latinhypercube_driver import LatinHypercubeDriver, OptimizedLatinHypercubeDriver
from openmdao.drivers.latinhypercube_driver import _is_latin_hypercube, _rand_latin_hypercube, _mmlhs, _LHC_Individual
class TestLatinHypercubeDriver(unittest.TestCase):
def setUp(self):
self.seed()
self.hypercube_sizes = ((3, 1), (5, 5), (20, 8))
def seed(self):
# seedval = None
self.seedval = 1
seed(self.seedval)
np.random.seed(self.seedval)
def test_rand_latin_hypercube(self):
for n, k in self.hypercube_sizes:
test_lhc = _rand_latin_hypercube(n, k)
self.assertTrue(_is_latin_hypercube(test_lhc))
def _test_mmlhs_latin(self, n, k):
p = 1
population = 3
generations = 6
test_lhc = _rand_latin_hypercube(n, k)
best_lhc = _LHC_Individual(test_lhc, 1, p)
mmphi_initial = best_lhc.mmphi()
for q in (1, 2, 5, 10, 20, 50, 100):
lhc_start = _LHC_Individual(test_lhc, q, p)
lhc_opt = _mmlhs(lhc_start, population, generations)
if lhc_opt.mmphi() < best_lhc.mmphi():
best_lhc = lhc_opt
self.assertTrue(
best_lhc.mmphi() < mmphi_initial,
"'_mmlhs' didn't yield lower phi. Seed was {}".format(self.seedval))
def test_mmlhs_latin(self):
for n, k in self.hypercube_sizes:
self._test_mmlhs_latin(n, k)
def test_algorithm_coverage_lhc(self):
prob = Problem()
root = prob.root = Group()
root.add('p1', IndepVarComp('x', 50.0), promotes=['*'])
root.add('p2', IndepVarComp('y', 50.0), promotes=['*'])
root.add('comp', Paraboloid(), promotes=['*'])
prob.driver = LatinHypercubeDriver(100)
prob.driver.add_desvar('x', lower=-50.0, upper=50.0)
prob.driver.add_desvar('y', lower=-50.0, upper=50.0)
prob.driver.add_objective('f_xy')
prob.setup(check=False)
runList = prob.driver._build_runlist()
prob.run()
# Ensure generated run list is a generator
self.assertTrue(
(type(runList) == GeneratorType),
"_build_runlist did not return a generator.")
# Add run list to dictionaries
xDict = []
yDict = []
countRuns = 0
for inputLine in runList:
countRuns += 1
x, y = dict(inputLine).values()
xDict.append(np.floor(x))
yDict.append(np.floor(y))
# Assert we had the correct number of runs
self.assertTrue(
countRuns == 100,
"Incorrect number of runs generated.")
# Assert all input values in range [-50,50]
valuesInRange = True
for value in xDict + yDict:
if value < (-50) or value > 49:
valuesInRange = False
self.assertTrue(
valuesInRange,
"One of the input values was outside the given range.")
# Assert a single input in each interval [n,n+1] for n = [-50,49]
self.assertTrue(
len(xDict) == 100,
"One of the intervals wasn't covered.")
self.assertTrue(
len(yDict) == 100,
"One of the intervals wasn't covered.")
def test_algorithm_coverage_olhc(self):
prob = Problem()
root = prob.root = Group()
root.add('p1', IndepVarComp('x', 50.0), promotes=['*'])
root.add('p2', IndepVarComp('y', 50.0), promotes=['*'])
root.add('comp', Paraboloid(), promotes=['*'])
prob.driver = OptimizedLatinHypercubeDriver(100, population=5)
prob.driver.add_desvar('x', lower=-50.0, upper=50.0)
prob.driver.add_desvar('y', lower=-50.0, upper=50.0)
prob.driver.add_objective('f_xy')
prob.setup(check=False)
runList = prob.driver._build_runlist()
prob.run()
# Ensure generated run list is a generator
self.assertTrue(
(type(runList) == GeneratorType),
"_build_runlist did not return a generator.")
# Add run list to dictionaries
xDict = []
yDict = []
countRuns = 0
for inputLine in runList:
countRuns += 1
x, y = dict(inputLine).values()
xDict.append(np.floor(x))
yDict.append(np.floor(y))
# Assert we had the correct number of runs
self.assertTrue(
countRuns == 100,
"Incorrect number of runs generated.")
# Assert all input values in range [-50,50]
valuesInRange = True
for value in xDict + yDict:
if value < (-50) or value > 49:
valuesInRange = False
self.assertTrue(
valuesInRange,
"One of the input values was outside the given range.")
# Assert a single input in each interval [n,n+1] for n = [-50,49]
self.assertTrue(
len(xDict) == 100,
"One of the intervals wasn't covered.")
self.assertTrue(
len(yDict) == 100,
"One of the intervals wasn't covered.")
'''
def test_seed_works(self):
'''
class ParaboloidArray(Component):
""" Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 """
def __init__(self):
super(ParaboloidArray, self).__init__()
self.add_param('X', val=np.array([0., 0.]))
self.add_output('f_xy', val=0.0)
self._history = []
def solve_nonlinear(self, params, unknowns, resids):
"""f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3
"""
x = params['X'][0]
y = params['X'][1]
self._history.append((x, y))
unknowns['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0
class TestLatinHypercubeDriverArray(unittest.TestCase):
def test_rand_latin_hypercube(self):
top = Problem()
root = top.root = Group()
root.add('p1', IndepVarComp('X', np.array([50., 50.])), promotes=['*'])
root.add('comp', ParaboloidArray(), promotes=['*'])
top.driver = OptimizedLatinHypercubeDriver(num_samples=4, seed=0, population=20,
generations=4, norm_method=2)
top.driver.add_desvar('X', lower=np.array([-50., -50.]), upper=np.array([50., 50.]))
top.driver.add_objective('f_xy')
top.setup(check=False)
top.run()
results = top.root.comp._history
#assert_rel_error(self, results[0][0], -11.279662, 1e-4)
#assert_rel_error(self, results[0][1], -32.120265, 1e-4)
#assert_rel_error(self, results[1][0], 40.069084, 1e-4)
#assert_rel_error(self, results[1][1], -11.377920, 1e-4)
#assert_rel_error(self, results[2][0], 10.5913699, 1e-4)
#assert_rel_error(self, results[2][1], 41.147352826, 1e-4)
#assert_rel_error(self, results[3][0], -39.06031971, 1e-4)
#assert_rel_error(self, results[3][1], 22.29432501, 1e-4)
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"openmdao.api.IndepVarComp",
"numpy.random.seed",
"openmdao.api.Problem",
"openmdao.drivers.latinhypercube_driver.LatinHypercubeDriver",
"numpy.floor",
"openmdao.drivers.latinhypercube_driver._rand_latin_hypercube",
"random.seed",
"openmdao.drivers.latinhypercube_driver._mmlhs",
"openmdao.drivers.latinhypercube_driver._LHC_Individual",
"openmdao.drivers.latinhypercube_driver.OptimizedLatinHypercubeDriver",
"openmdao.api.Group",
"openmdao.drivers.latinhypercube_driver._is_latin_hypercube",
"numpy.array",
"openmdao.test.paraboloid.Paraboloid"
] |
[((7420, 7435), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7433, 7435), False, 'import unittest\n'), ((753, 771), 'random.seed', 'seed', (['self.seedval'], {}), '(self.seedval)\n', (757, 771), False, 'from random import seed\n'), ((780, 808), 'numpy.random.seed', 'np.random.seed', (['self.seedval'], {}), '(self.seedval)\n', (794, 808), True, 'import numpy as np\n'), ((1125, 1152), 'openmdao.drivers.latinhypercube_driver._rand_latin_hypercube', '_rand_latin_hypercube', (['n', 'k'], {}), '(n, k)\n', (1146, 1152), False, 'from openmdao.drivers.latinhypercube_driver import _is_latin_hypercube, _rand_latin_hypercube, _mmlhs, _LHC_Individual\n'), ((1172, 1203), 'openmdao.drivers.latinhypercube_driver._LHC_Individual', '_LHC_Individual', (['test_lhc', '(1)', 'p'], {}), '(test_lhc, 1, p)\n', (1187, 1203), False, 'from openmdao.drivers.latinhypercube_driver import _is_latin_hypercube, _rand_latin_hypercube, _mmlhs, _LHC_Individual\n'), ((1834, 1843), 'openmdao.api.Problem', 'Problem', ([], {}), '()\n', (1841, 1843), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((1871, 1878), 'openmdao.api.Group', 'Group', ([], {}), '()\n', (1876, 1878), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((2086, 2111), 'openmdao.drivers.latinhypercube_driver.LatinHypercubeDriver', 'LatinHypercubeDriver', (['(100)'], {}), '(100)\n', (2106, 2111), False, 'from openmdao.drivers.latinhypercube_driver import LatinHypercubeDriver, OptimizedLatinHypercubeDriver\n'), ((3709, 3718), 'openmdao.api.Problem', 'Problem', ([], {}), '()\n', (3716, 3718), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((3746, 3753), 'openmdao.api.Group', 'Group', ([], {}), '()\n', (3751, 3753), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((3961, 4009), 'openmdao.drivers.latinhypercube_driver.OptimizedLatinHypercubeDriver', 'OptimizedLatinHypercubeDriver', (['(100)'], {'population': '(5)'}), '(100, population=5)\n', (3990, 4009), False, 'from openmdao.drivers.latinhypercube_driver import LatinHypercubeDriver, OptimizedLatinHypercubeDriver\n'), ((6280, 6289), 'openmdao.api.Problem', 'Problem', ([], {}), '()\n', (6287, 6289), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((6316, 6323), 'openmdao.api.Group', 'Group', ([], {}), '()\n', (6321, 6323), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((6488, 6589), 'openmdao.drivers.latinhypercube_driver.OptimizedLatinHypercubeDriver', 'OptimizedLatinHypercubeDriver', ([], {'num_samples': '(4)', 'seed': '(0)', 'population': '(20)', 'generations': '(4)', 'norm_method': '(2)'}), '(num_samples=4, seed=0, population=20,\n generations=4, norm_method=2)\n', (6517, 6589), False, 'from openmdao.drivers.latinhypercube_driver import LatinHypercubeDriver, OptimizedLatinHypercubeDriver\n'), ((916, 943), 'openmdao.drivers.latinhypercube_driver._rand_latin_hypercube', '_rand_latin_hypercube', (['n', 'k'], {}), '(n, k)\n', (937, 943), False, 'from openmdao.drivers.latinhypercube_driver import _is_latin_hypercube, _rand_latin_hypercube, _mmlhs, _LHC_Individual\n'), ((1314, 1345), 'openmdao.drivers.latinhypercube_driver._LHC_Individual', '_LHC_Individual', (['test_lhc', 'q', 'p'], {}), '(test_lhc, q, p)\n', (1329, 1345), False, 'from openmdao.drivers.latinhypercube_driver import _is_latin_hypercube, _rand_latin_hypercube, _mmlhs, _LHC_Individual\n'), ((1368, 1410), 'openmdao.drivers.latinhypercube_driver._mmlhs', '_mmlhs', (['lhc_start', 'population', 'generations'], {}), '(lhc_start, population, generations)\n', (1374, 1410), False, 'from openmdao.drivers.latinhypercube_driver import _is_latin_hypercube, _rand_latin_hypercube, _mmlhs, _LHC_Individual\n'), ((1903, 1926), 'openmdao.api.IndepVarComp', 'IndepVarComp', (['"""x"""', '(50.0)'], {}), "('x', 50.0)\n", (1915, 1926), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((1967, 1990), 'openmdao.api.IndepVarComp', 'IndepVarComp', (['"""y"""', '(50.0)'], {}), "('y', 50.0)\n", (1979, 1990), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((2033, 2045), 'openmdao.test.paraboloid.Paraboloid', 'Paraboloid', ([], {}), '()\n', (2043, 2045), False, 'from openmdao.test.paraboloid import Paraboloid\n'), ((3778, 3801), 'openmdao.api.IndepVarComp', 'IndepVarComp', (['"""x"""', '(50.0)'], {}), "('x', 50.0)\n", (3790, 3801), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((3842, 3865), 'openmdao.api.IndepVarComp', 'IndepVarComp', (['"""y"""', '(50.0)'], {}), "('y', 50.0)\n", (3854, 3865), False, 'from openmdao.api import IndepVarComp, Group, Problem, Component\n'), ((3908, 3920), 'openmdao.test.paraboloid.Paraboloid', 'Paraboloid', ([], {}), '()\n', (3918, 3920), False, 'from openmdao.test.paraboloid import Paraboloid\n'), ((973, 1002), 'openmdao.drivers.latinhypercube_driver._is_latin_hypercube', '_is_latin_hypercube', (['test_lhc'], {}), '(test_lhc)\n', (992, 1002), False, 'from openmdao.drivers.latinhypercube_driver import _is_latin_hypercube, _rand_latin_hypercube, _mmlhs, _LHC_Individual\n'), ((2796, 2807), 'numpy.floor', 'np.floor', (['x'], {}), '(x)\n', (2804, 2807), True, 'import numpy as np\n'), ((2834, 2845), 'numpy.floor', 'np.floor', (['y'], {}), '(y)\n', (2842, 2845), True, 'import numpy as np\n'), ((4693, 4704), 'numpy.floor', 'np.floor', (['x'], {}), '(x)\n', (4701, 4704), True, 'import numpy as np\n'), ((4731, 4742), 'numpy.floor', 'np.floor', (['y'], {}), '(y)\n', (4739, 4742), True, 'import numpy as np\n'), ((5805, 5825), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (5813, 5825), True, 'import numpy as np\n'), ((6366, 6388), 'numpy.array', 'np.array', (['[50.0, 50.0]'], {}), '([50.0, 50.0])\n', (6374, 6388), True, 'import numpy as np\n'), ((6678, 6702), 'numpy.array', 'np.array', (['[-50.0, -50.0]'], {}), '([-50.0, -50.0])\n', (6686, 6702), True, 'import numpy as np\n'), ((6708, 6730), 'numpy.array', 'np.array', (['[50.0, 50.0]'], {}), '([50.0, 50.0])\n', (6716, 6730), True, 'import numpy as np\n')]
|
from matplotlib import pyplot as plt
from matplotlib import rcParams
import numpy as np
import pickle
import copy as cp
import gs2_plotting as gplot
from plot_phi2_vs_time import plot_phi2_ky_vs_t
def my_single_task(ifile,run,myin,myout,mygrids,mytime,myfields,stitching=False):
# Compute and save to dat file
if not run.only_plot:
# OB 140918 ~ mygrids.ny = naky. Before, ny was defined as mygrids.ny, but I have changed it to ny specified in the input file, so we have both.
# (Same for x, and I replaced all further ny,nx that should have been naky and nakx, respectively)
spec_names = []
for ispec in range(myout['nspec']):
spec_names.append(myin['species_parameters_'+str(ispec+1)]['type'])
qflx = get_dict_item('es_heat_flux',myout)
vflx = get_dict_item('es_mom_flux',myout)
if myout['es_heat_flux_present'] and myout['es_mom_flux_present']:
# avoid divide by zero with qflx
# in this case, set pi/Q = 0
dum = np.copy(qflx)
zerotest = dum==0
dum[zerotest] = vflx[zerotest]*100000
pioq = np.copy(np.divide(vflx,dum))
else:
pioq = np.arange(1,dtype=float)
# need to multiply this by rhoc/(g_exb*rmaj**2)
#prandtl = np.copy(vflx[:,0]*tprim[0]/(qflx[:,0]*q)
(pflx_kxky,pflx_kxky_tavg) = get_dict_item('es_part_flux_by_mode', myout, mygrids=mygrids, mytime=mytime)
(qflx_kxky,qflx_kxky_tavg) = get_dict_item('es_heat_flux_by_mode', myout, mygrids=mygrids, mytime=mytime)
(vflx_kxky,vflx_kxky_tavg) = get_dict_item('es_mom_flux_by_mode', myout, mygrids=mygrids, mytime=mytime)
(pflx_vpth, pflx_vpth_tavg) = get_dict_item('es_part_sym', myout, mygrids=mygrids, mytime=mytime)
(qflx_vpth, qflx_vpth_tavg) = get_dict_item('es_heat_sym', myout, mygrids=mygrids, mytime=mytime)
(vflx_vpth, vflx_vpth_tavg) = get_dict_item('es_mom_sym', myout, mygrids=mygrids, mytime=mytime)
(phi2_kxky,phi2_kxky_tavg) = get_dict_item('phi2_by_mode', myout, mygrids=mygrids, mytime=mytime)
# Save computed quantities OB 140918 ~ added tri,kap to saved dat.
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.fluxes.dat'
mydict = {'pflx':get_dict_item('es_part_flux',myout),'qflx':qflx,'vflx':vflx,'xchange':get_dict_item('es_energy_exchange',myout),
'pflx_kxky':pflx_kxky,'qflx_kxky':qflx_kxky,'vflx_kxky':vflx_kxky,
'pflx_kxky_tavg':pflx_kxky_tavg,'qflx_kxky_tavg':qflx_kxky_tavg,'vflx_kxky_tavg':vflx_kxky_tavg,
'pflx_vpth_tavg':pflx_vpth_tavg,'qflx_vpth_tavg':qflx_vpth_tavg,'vflx_vpth_tavg':vflx_vpth_tavg,
'pioq':pioq,'nvpa':mygrids.nvpa,'ntheta':mygrids.ntheta,'nx':myin['kt_grids_box_parameters']['nx'],'ny':myin['kt_grids_box_parameters']['ny'],
'nxmid':mygrids.nxmid,'islin':get_boolean(myin, 'nonlinear_terms_knobs', 'nonlinear_mode', 'off'),
'nspec':myout['nspec'],'spec_names':spec_names,
'naky':mygrids.ny,'nakx':mygrids.nx,'kx':mygrids.kx,'ky':mygrids.ky,'time':mytime.time,'time_steady':mytime.time_steady,'it_min':mytime.it_min,'it_max':mytime.it_max,
'phi2_avg':myfields.phi2_avg,'phi2_by_ky':get_dict_item('phi2_by_ky', myout),'has_flowshear':get_boolean(myin, 'dist_fn_knobs', 'g_exb', 0., negate = True),
'phi2_kxky_tavg':phi2_kxky_tavg,'phi2_kxky':phi2_kxky,
'tri':myin['theta_grid_parameters']['tri'],'kap':myin['theta_grid_parameters']['akappa']}
with open(datfile_name,'wb') as datfile:
pickle.dump(mydict,datfile)
# Save time obj
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.time.dat'
with open(datfile_name,'wb') as datfile:
pickle.dump(mytime,datfile)
# Save grid obj
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.grids.dat'
with open(datfile_name,'wb') as datfile:
pickle.dump(mygrids,datfile)
# Read from dat files
else:
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.fluxes.dat'
with open(datfile_name,'rb') as datfile:
mydict = pickle.load(datfile)
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.time.dat'
with open(datfile_name,'rb') as datfile:
mytime = pickle.load(datfile)
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.grids.dat'
with open(datfile_name,'rb') as datfile:
mygrids = pickle.load(datfile)
if not run.no_plot and not stitching: # plot fluxes for this single file
plot_fluxes(ifile,run,mytime,mydict)
# OB 140918 ~ Gets boolean properties and defaults if not in input file.
# myin is the input file dictionary.
# namelist is the namelist within the input file.
# item is the item within the namelist.
# if myin[namelist][item] == matches, return
# if negate, then == changes to !=
# default is what is returned if the desired key could not be found
def get_boolean(myin, namelist, item, matches, negate = False, default = False):
try:
return (myin[namelist][item] != matches and negate) or (myin[namelist][item] == matches and not negate)
except:
# Could not find key in list.
return default
# OB 140918 ~ Clean up the long list of if "XYZ_present" above with this function
# name is the key in myout that belongs to the data of interest.
# For kx_ky and vpar_theta quantities, we use mytime and mygrids.
# Note that if the key is not present, the passed arrays do not have the correct dims.
# This will likely lead to crashes if they are used later, so before use we should probably always check if _present.
def get_dict_item(name, myout, mygrids=None, mytime=None):
if "by_mode" in name:
if myout[name+'_present']:
ndims = myout[name].ndim
lslice, rslice = [slice(None)] * ndims, [slice(None)] * ndims
lslice[ndims-1] = slice(0,mygrids.nxmid)
rslice[ndims-1] = slice(mygrids.nxmid,mygrids.nx)
value_kxky = np.concatenate((myout[name][tuple(rslice)],myout[name][tuple(lslice)]),axis=ndims-1)
return (value_kxky,mytime.timeavg(value_kxky))
else:
return (((np.arange(1,dtype=float)),np.arange(1,dtype=float)))
elif "sym" in name: # TODO OB ~ N.B. not yet tested since I didn't have an out.nc file that contained "XYZ_sym" data
if myout[name+'_present']:
return (myout[name],mytime.timeavg(myout[name]))
else:
return (((np.arange(1,dtype=float)),np.arange(1,dtype=float)))
else:
if myout[name+"_present"]:
value = myout[name]
else:
value = np.arange(1,dtype=float)
return value
# OB ~ function to plot a heatmap of heat flux vs triangularity and elongation.
def trikap(run):
# Only execute if plotting
if run.no_plot:
return
print("Plotting scan of triangularity vs elongation...")
Nfile = len(run.fnames)
# Init arrays of data used in scan.
full_fluxes = [dict() for ifile in range(Nfile)]
full_time = [dict() for ifile in range(Nfile)]
# Initialize fluxes and grids from .dat files.
for ifile in range(Nfile):
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.fluxes.dat'
with open(datfile_name,'rb') as datfile:
full_fluxes[ifile] = pickle.load(datfile)
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.time.dat'
with open(datfile_name,'rb') as datfile:
full_time[ifile] = pickle.load(datfile)
# Uses nspec from first file. Will quit if not constant between files.
nspec = full_fluxes[0]['nspec']
print("Number of species " + str(nspec))
tri,kap = np.zeros(Nfile),np.zeros(Nfile)
for ifile in range(Nfile):
tri[ifile] = full_fluxes[ifile]['tri']
kap[ifile] = full_fluxes[ifile]['kap']
if full_fluxes[ifile]['nspec'] != nspec:
quit("Number of species varies between files - exiting")
tris = sorted(list(set(tri)))
kaps = sorted(list(set(kap)))
print("Triangularity values: " + str(tris))
print("Elongation values: " + str(kaps))
if len(tris) * len(kaps) != Nfile:
quit("Too few files added to populate the scan - exiting")
qflx = np.zeros((len(tris), len(kaps), nspec))
for itri in range(len(tris)):
for ikap in range(len(kaps)):
for ifile in range(Nfile):
if tri[ifile] == tris[itri] and kap[ifile] == kaps[ikap]:
for ispec in range(nspec):
qflx[itri,ikap,ispec] = full_time[ifile].timeavg(full_fluxes[ifile]['qflx'][:,ispec])
spec_names = full_fluxes[0]['spec_names']
pdflist = []
tmp_pdf_id=0
for ispec in range(nspec):
print("Plotting for species: " + spec_names[ispec])
gplot.plot_2d(qflx[:,:,ispec],tris,kaps,np.min(qflx[:,:,ispec]),np.max(qflx[:,:,ispec]),cmp='Reds',xlab='$\delta$',ylab='$\kappa$',title='$Q_{GS2}$: ' + spec_names[ispec])
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run)
pdflist.append(tmp_pdfname)
tmp_pdf_id += 1
merged_pdfname = 'tri_kap_scan'
gplot.merge_pdfs(pdflist, merged_pdfname, run)
def stitching_fluxes(run):
# Only executed if we want to plot the data
if run.no_plot:
return
Nfile = len(run.fnames)
full_fluxes = [dict() for ifile in range(Nfile)]
full_time = [dict() for ifile in range(Nfile)]
full_grids = [dict() for ifile in range(Nfile)]
# Reading .dat file for each run
# and calc how long the stitched array will be
Nt_tot = 0
for ifile in range(Nfile):
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.fluxes.dat'
with open(datfile_name,'rb') as datfile:
full_fluxes[ifile] = pickle.load(datfile)
datfile_name = run.work_dir + run.dirs[ifile] + run.out_dir + run.files[ifile] + '.time.dat'
with open(datfile_name,'rb') as datfile:
full_time[ifile] = pickle.load(datfile)
Nt_tot += full_fluxes[ifile]['pflx'].shape[0]
if ifile > 0:
Nt_tot -= 1 # removing duplicate at restart point
# A lot of stuff is the same for all runs
islin = full_fluxes[0]['islin']
has_flowshear = full_fluxes[0]['has_flowshear']
twin = full_time[0].twin
nspec = full_fluxes[0]['nspec']
spec_names = full_fluxes[0]['spec_names']
nx = full_fluxes[0]['nx']
ny = full_fluxes[0]['ny']
naky = full_fluxes[0]['naky']
nakx = full_fluxes[0]['nakx']
kx = full_fluxes[0]['kx']
ky = full_fluxes[0]['ky']
datfile_name = run.work_dir + run.dirs[0] + run.out_dir + run.files[0] + '.grids.dat'
with open(datfile_name,'rb') as datfile:
my_grids = pickle.load(datfile)
# Stitching the arrays together
stitch_my_time = cp.deepcopy(full_time[0])
stitch_my_time.ntime = Nt_tot
stitch_my_time.time = np.zeros(Nt_tot)
stitch_pflx = np.zeros((Nt_tot,nspec))
stitch_qflx = np.zeros((Nt_tot,nspec))
stitch_vflx = np.zeros((Nt_tot,nspec))
stitch_pioq = np.zeros((Nt_tot,nspec))
stitch_pflx_kxky = np.zeros((Nt_tot,nspec,naky,nakx))
stitch_qflx_kxky = np.zeros((Nt_tot,nspec,naky,nakx))
stitch_vflx_kxky = np.zeros((Nt_tot,nspec,naky,nakx))
stitch_pflx_kxky_tavg = np.zeros((nspec,naky,nakx))
stitch_qflx_kxky_tavg = np.zeros((nspec,naky,nakx))
stitch_vflx_kxky_tavg = np.zeros((nspec,naky,nakx))
stitch_phi2_avg = np.zeros(Nt_tot)
stitch_phi2_by_ky = np.zeros((Nt_tot,naky))
stitch_phi2_kxky = np.zeros((Nt_tot,naky,nakx))
stitch_phi2_kxky_tavg = np.zeros((naky,nakx))
it_tot = 0
for ifile in range(Nfile):
if ifile == 0:
it_range = range(full_time[0].ntime)
else:
it_range = range(1,full_time[ifile].ntime) # excluding duplicate when restarting
for it in it_range:
stitch_my_time.time[it_tot] = full_time[ifile].time[it]
for ispec in range(nspec):
stitch_pflx[it_tot,ispec] = full_fluxes[ifile]['pflx'][it,ispec]
stitch_qflx[it_tot,ispec] = full_fluxes[ifile]['qflx'][it,ispec]
stitch_vflx[it_tot,ispec] = full_fluxes[ifile]['vflx'][it,ispec]
stitch_pioq[it_tot,ispec] = full_fluxes[ifile]['pioq'][it,ispec]
for ikx in range(nakx):
for iky in range(naky):
stitch_pflx_kxky[it_tot,ispec,iky,ikx] = full_fluxes[ifile]['pflx_kxky'][it,ispec,iky,ikx]
stitch_qflx_kxky[it_tot,ispec,iky,ikx] = full_fluxes[ifile]['qflx_kxky'][it,ispec,iky,ikx]
stitch_vflx_kxky[it_tot,ispec,iky,ikx] = full_fluxes[ifile]['vflx_kxky'][it,ispec,iky,ikx]
for ikx in range(nakx):
for iky in range(naky):
stitch_phi2_kxky[it_tot,iky,ikx] = full_fluxes[ifile]['phi2_kxky'][it,iky,ikx]
stitch_phi2_avg[it_tot] = full_fluxes[ifile]['phi2_avg'][it]
stitch_phi2_by_ky[it_tot,:] = full_fluxes[ifile]['phi2_by_ky'][it,:]
it_tot += 1
stitch_my_time.it_min = int(np.ceil((1.0-twin)*stitch_my_time.ntime))
stitch_my_time.it_max = stitch_my_time.ntime-1
stitch_my_time.time_steady = stitch_my_time.time[stitch_my_time.it_min:stitch_my_time.it_max]
stitch_my_time.ntime_steady = stitch_my_time.time_steady.size
# Computing time averaged versions of stitched fluxes vs (kx,ky) OB 140918 ~ New timeavg doesn't need us to explicitly loop over.
stitch_phi2_kxky_tavg = stitch_my_time.timeavg(stitch_phi2_kxky)
stitch_pflx_kxky_tavg = stitch_my_time.timeavg(stitch_pflx_kxky)
stitch_qflx_kxky_tavg = stitch_my_time.timeavg(stitch_qflx_kxky)
stitch_vflx_kxky_tavg = stitch_my_time.timeavg(stitch_vflx_kxky)
# Plotting the stitched fluxes
ifile = None
stitch_dict = {'pflx':stitch_pflx,'qflx':stitch_qflx,'vflx':stitch_vflx,'pioq':stitch_pioq,
'nx':nx,'ny':ny,'islin':islin,'has_flowshear':has_flowshear,'nspec':nspec,'spec_names':spec_names,
'naky':naky,'nakx':nakx,'kx':kx,'ky':ky,'phi2_avg':stitch_phi2_avg,'phi2_by_ky':stitch_phi2_by_ky,
'pflx_kxky_tavg':stitch_pflx_kxky_tavg,'qflx_kxky_tavg':stitch_qflx_kxky_tavg,
'vflx_kxky_tavg':stitch_vflx_kxky_tavg,'phi2_kxky_tavg':stitch_phi2_kxky_tavg}
plot_fluxes(ifile,run,stitch_my_time,stitch_dict)
def plot_fluxes(ifile,run,mytime,mydict):
islin = mydict['islin']
has_flowshear = mydict['has_flowshear']
# t grid
time = mytime.time
time_steady = mytime.time_steady
it_min = mytime.it_min
it_max = mytime.it_max
# k grids
nx = mydict['nx']
ny = mydict['ny']
naky = mydict['naky']
nakx = mydict['nakx']
kx = mydict['kx']
ky = mydict['ky']
# species
nspec = mydict['nspec']
spec_names = mydict['spec_names']
# fluxes vs t
pflx = mydict['pflx']
qflx = mydict['qflx']
vflx = mydict['vflx']
pioq = mydict['pioq']
# fluxes vs (kx,ky)
pflx_kxky_tavg = mydict['pflx_kxky_tavg']
qflx_kxky_tavg = mydict['qflx_kxky_tavg']
vflx_kxky_tavg = mydict['vflx_kxky_tavg']
# potential
phi2_avg = mydict['phi2_avg']
phi2_by_ky = mydict['phi2_by_ky']
phi2_kxky_tavg = mydict['phi2_kxky_tavg']
print()
print(">>> producing plots of fluxes vs time...")
print("-- plotting avg(phi2)")
write_fluxes_vs_t = False
tmp_pdf_id = 1
pdflist = []
if phi2_avg is not None:
title = '$\\langle|\phi^{2}|\\rangle_{\\theta,k_x,k_y}$'
if islin:
title = '$\ln$'+title
gplot.plot_1d(time,np.log(phi2_avg),'$t (a/v_{t})$',title)
else:
gplot.plot_1d(time,phi2_avg,'$t (a/v_{t})$',title)
plt.grid(True)
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
print("-- plotting particle flux")
if pflx is not None:
title = '$\Gamma_{GS2}$'
plot_flux_vs_t(islin,nspec,spec_names,mytime,pflx,title)
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
print("-- plotting heat flux")
if qflx is not None:
title = '$Q_{GS2}$'
plot_flux_vs_t(islin,nspec,spec_names,mytime,qflx,title)
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
print("-- plotting momentum flux")
if vflx is not None:
title = '$\Pi_{GS2}$'
plot_flux_vs_t(islin,nspec,spec_names,mytime,vflx,title,)
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
#if myout['es_energy_exchange_present']:
# title = 'energy exchange'
# gplot.plot_1d(mytime.time,self.xchange,"$t (v_t/a)$",title)
# write_fluxes_vs_t = True
# tmp_pdfname = 'tmp'+str(tmp_pdf_id)
# gplot.save_plot(tmp_pdfname, run, ifile)
# pdflist.append(tmp_pdfname)
# tmp_pdf_id = tmp_pdf_id+1
print("-- plotting momentum/heat flux ratio")
if pioq is not None:
title = '$\Pi_{GS2}/Q_{GS2}$'
for idx in range(nspec):
plt.plot(mytime.time_steady,pioq[it_min:it_max,idx],label=spec_names[idx])
plt.title(title)
plt.xlabel('$t (a/v_t)$')
plt.legend()
plt.grid(True)
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
print("-- plotting phi2 by ky")
if phi2_by_ky is not None:
title = '$\\langle|\phi^{2}|\\rangle_{\\theta,k_x}$'
# Create list of colors
cmap = plt.get_cmap('nipy_spectral')
my_colors = [cmap(i) for i in np.linspace(0,1,naky-1)]
if islin:
title = '$\\ln$' + title
plt.semilogy(time, np.log(phi2_by_ky[:,0]),label='ky = '+'{:5.3f}'.format(ky[0]),linestyle='dashed',color='black')
for iky in range(1,naky) :
plt.semilogy(time, np.log(phi2_by_ky[:,iky]),label='ky = '+'{:5.3f}'.format(ky[iky]),color=my_colors[iky-1])
else:
plt.plot(time, phi2_by_ky[:,0],label='ky = '+'{:5.3f}'.format(ky[0]),linestyle='dashed',color='black')
for iky in range(1,naky) :
plt.semilogy(time, phi2_by_ky[:,iky],label='ky = '+'{:5.3f}'.format(ky[iky]),color=my_colors[iky-1])
plt.xlabel('$t (a/v_t)$')
plt.title(title)
plt.legend(prop={'size': 11}, ncol=6)
plt.grid(True)
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
if naky>4:
tmp_pdf_id = tmp_pdf_id+1
title = '$\\langle|\phi^{2}|\\rangle_{\\theta,k_x}$ for low $k_y$'
#plt.figure(figsize=(8,8)) # NDCDEL
if islin:
title = '$\\ln$' + title
plt.semilogy(time, np.log(phi2_by_ky[:,0]),label='ky = '+'{:5.3f}'.format(ky[0]),linestyle='dashed',color='black')
for iky in range(1,5) :
plt.semilogy(time, np.log(phi2_by_ky[:,iky]),label='ky = '+'{:5.3f}'.format(ky[iky]),color=my_colors[iky-1])
else:
plt.plot(time[:], phi2_by_ky[:,0],label='ky = '+'{:5.3f}'.format(ky[0]),linestyle='dashed',color='black')
#for iky in range(1,4) :# NDCDEL
for iky in range(1,5) :
plt.semilogy(time[:], phi2_by_ky[:,iky],label='ky = '+'{:5.3f}'.format(ky[iky]),color=my_colors[iky-1])
#plt.xlabel('$t$') # NDCDEL
plt.xlabel('$t (a/v_t)$')
#plt.ylabel('$\\langle|\phi^{2}|\\rangle_{\\theta,k_x}$') # NDCDEL
plt.title(title)
plt.legend()
plt.grid(True)
# NDCDEL
#axes = plt.gca()
#axes.set_xlim([0,500])
#plt.savefig('terrific.pdf')
# endNDCDEL
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
title = '$\\langle|\phi^{2}|\\rangle_{\\theta,k_x}$ for high $k_y$'
if islin:
title = '$\\ln$' + title
for iky in range(naky-5,naky) :
plt.semilogy(time, np.log(phi2_by_ky[:,iky]),label='ky = '+'{:5.3f}'.format(ky[iky]),color=my_colors[iky-1])
else:
for iky in range(naky-5,naky) :
plt.semilogy(time, phi2_by_ky[:,iky],label='ky = '+'{:5.3f}'.format(ky[iky]),color=my_colors[iky-1])
plt.xlabel('$t (a/v_t)$')
plt.title(title)
plt.legend()
plt.grid(True)
write_fluxes_vs_t = True
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
if write_fluxes_vs_t:
merged_pdfname = 'fluxes_vs_t'
if ifile==None: # This is the case when we stitch fluxes together
merged_pdfname += '_'+run.scan_name
gplot.merge_pdfs(pdflist, merged_pdfname, run, ifile)
print('complete')
print()
print('producing plots of fluxes vs (kx,ky)...', end='')
write_fluxes_vs_kxky = False
tmp_pdf_id = 1
pdflist = []
# Plot phi2 averaged over t and theta, vs (kx,ky)
plot_phi2_vs_kxky(kx,ky,phi2_kxky_tavg,has_flowshear)
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id += 1
if pflx_kxky_tavg is not None:
title = '$\Gamma_{GS2}$'
for ispec in range(nspec):
plot_flux_vs_kxky(ispec,spec_names,kx,ky,pflx_kxky_tavg,title,has_flowshear)
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
write_fluxes_vs_kxky = True
if qflx_kxky_tavg is not None:
title = '$Q_{GS2}$'
for ispec in range(nspec):
plot_flux_vs_kxky(ispec,spec_names,kx,ky,qflx_kxky_tavg,title,has_flowshear)
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
write_fluxes_vs_kxky = True
if vflx_kxky_tavg is not None:
title = '$\Pi_{GS2}$'
for ispec in range(nspec):
plot_flux_vs_kxky(ispec,spec_names,kx,ky,vflx_kxky_tavg,title,has_flowshear)
tmp_pdfname = 'tmp'+str(tmp_pdf_id)
gplot.save_plot(tmp_pdfname, run, ifile)
pdflist.append(tmp_pdfname)
tmp_pdf_id = tmp_pdf_id+1
write_fluxes_vs_kxky = True
if write_fluxes_vs_kxky:
merged_pdfname = 'fluxes_vs_kxky'
if ifile==None: # This is the case when we stitch fluxes together
merged_pdfname += '_'+run.scan_name
gplot.merge_pdfs(pdflist, merged_pdfname, run, ifile)
print('complete')
#print()
#print('producing plots of fluxes vs (vpa,theta)...',end='')
#write_vpathetasym = False
#tmp_pdf_id = 1
#pdflist = []
#if pflx_vpth_tavg is not None and mygrids.vpa is not None:
# title = '$\Gamma_{GS2}$'
# plot_flux_vs_vpth(mygrids,pflx_vpth_tavg,title)
# write_vpathetasym = True
# tmp_pdfname = 'tmp'+str(tmp_pdf_id)
# gplot.save_plot(tmp_pdfname, run, ifile)
# pdflist.append(tmp_pdfname)
# tmp_pdf_id = tmp_pdf_id+1
#if qflx_vpth_tavg is not None and mygrids.vpa is not None:
# title = '$Q_{GS2}$'
# plot_flux_vs_vpth(mygrids,qflx_vpth_tavg,title)
# write_vpathetasym = True
# tmp_pdfname = 'tmp'+str(tmp_pdf_id)
# gplot.save_plot(tmp_pdfname, run, ifile)
# pdflist.append(tmp_pdfname)
# tmp_pdf_id = tmp_pdf_id+1
#if vflx_vpth_tavg is not None and mygrids.vpa is not None:
# title = '$\Pi_{GS2}$'
# plot_flux_vs_vpth(mygrids,vflx_vpth_tavg,title)
# write_vpathetasym = True
# tmp_pdfname = 'tmp'+str(tmp_pdf_id)
# gplot.save_plot(tmp_pdfname, run, ifile)
# pdflist.append(tmp_pdfname)
# tmp_pdf_id = tmp_pdf_id+1
#if write_vpathetasym:
# merged_pdfname = 'fluxes_vs_vpa_theta'
# gplot.merge_pdfs(pdflist, merged_pdfname, run, ifile)
#print('complete')
def plot_flux_vs_t(islin,nspec,spec_names,mytime,flx,title,):
fig=plt.figure(figsize=(12,8))
dum = np.empty(mytime.ntime_steady)
if islin:
title = '$\\ln($' + title + '$)$'
# generate a curve for each species
# on the same plot
# plot time-traces for each species
for idx in range(nspec):
# get the time-averaged flux
if islin:
plt.plot(mytime.time,np.log(flx[:,idx]),label=spec_names[idx])
else:
plt.plot(mytime.time,flx[:,idx],label=spec_names[idx])
# plot time-averages
for idx in range(nspec):
if islin:
flxavg = mytime.timeavg(np.log(np.absolute(flx[:,idx])))
dum.fill(flxavg)
else:
flxavg = mytime.timeavg(flx[:,idx])
dum.fill(flxavg)
plt.plot(mytime.time_steady,dum,'--')
print('flux avg for '+spec_names[idx]+': '+str(flxavg))
plt.xlabel('$t (a/v_t)$')
plt.xlim([mytime.time[0],mytime.time[-1]])
plt.title(title)
plt.legend()
plt.grid(True)
return fig
def plot_flux_vs_kxky(ispec,spec_names,kx,ky,flx,title,has_flowshear):
from gs2_plotting import plot_2d
if has_flowshear:
xlab = '$\\bar{k}_{x}\\rho_i$'
else:
xlab = '$k_{x}\\rho_i$'
ylab = '$k_{y}\\rho_i$'
cmap = 'Blues' # 'Reds','Blues'
z = flx[ispec,:,:] # OB 140918 ~ Don't take absolute value of fluxes.
z_min, z_max = 0.0, z.max()
title = 'Contributions to ' + title
if ispec > 1:
title += ' (impurity ' + str(ispec-1) + ')'
else:
title += ' (' + spec_names[ispec] + 's)'
fig = plot_2d(np.transpose(z),kx,ky,z_min,z_max,xlab,ylab,title,cmap)
return fig
def plot_phi2_vs_kxky(kx,ky,phi2,has_flowshear):
from gs2_plotting import plot_2d
title = '$\\langle\\vert\\hat{\\varphi}_k\\vert ^2\\rangle_{t,\\theta}$'
title += ' $\\forall$ $k_y > 0$'
if has_flowshear:
xlab = '$\\bar{k}_{x}\\rho_i$'
else:
xlab = '$k_{x}\\rho_i$'
ylab = '$k_{y}\\rho_i$'
cmap = 'RdBu'# 'RdBu_r','Blues'
z = phi2[1:,:] # taking out zonal modes because they are much larger
z_min, z_max = z.min(), z.max()
use_logcolor = True
fig = plot_2d(np.transpose(z),kx,ky[1:],z_min,z_max,xlab,ylab,title,cmap,use_logcolor)
return fig
def plot_flux_vs_vpth(mygrids,flx,title):
from gs2_plotting import plot_2d
xlab = '$\\theta$'
ylab = '$v_{\parallel}$'
cmap = 'RdBu'
for idx in range(flx.shape[0]):
z = flx[idx,:,:]
z_min, z_max = z.min(), z.max()
fig = plot_2d(z,mygrids.theta,mygrids.vpa,z_min,z_max,xlab,ylab,title+' (is= '+str(idx+1)+')',cmap)
return fig
|
[
"matplotlib.pyplot.title",
"numpy.absolute",
"pickle.dump",
"numpy.empty",
"matplotlib.pyplot.figure",
"pickle.load",
"numpy.arange",
"gs2_plotting.plot_1d",
"numpy.copy",
"numpy.transpose",
"numpy.max",
"numpy.linspace",
"numpy.divide",
"copy.deepcopy",
"numpy.ceil",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.legend",
"numpy.min",
"gs2_plotting.save_plot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlim",
"gs2_plotting.merge_pdfs",
"matplotlib.pyplot.plot",
"numpy.log",
"numpy.zeros",
"matplotlib.pyplot.xlabel"
] |
[((9739, 9785), 'gs2_plotting.merge_pdfs', 'gplot.merge_pdfs', (['pdflist', 'merged_pdfname', 'run'], {}), '(pdflist, merged_pdfname, run)\n', (9755, 9785), True, 'import gs2_plotting as gplot\n'), ((11442, 11467), 'copy.deepcopy', 'cp.deepcopy', (['full_time[0]'], {}), '(full_time[0])\n', (11453, 11467), True, 'import copy as cp\n'), ((11528, 11544), 'numpy.zeros', 'np.zeros', (['Nt_tot'], {}), '(Nt_tot)\n', (11536, 11544), True, 'import numpy as np\n'), ((11564, 11589), 'numpy.zeros', 'np.zeros', (['(Nt_tot, nspec)'], {}), '((Nt_tot, nspec))\n', (11572, 11589), True, 'import numpy as np\n'), ((11607, 11632), 'numpy.zeros', 'np.zeros', (['(Nt_tot, nspec)'], {}), '((Nt_tot, nspec))\n', (11615, 11632), True, 'import numpy as np\n'), ((11650, 11675), 'numpy.zeros', 'np.zeros', (['(Nt_tot, nspec)'], {}), '((Nt_tot, nspec))\n', (11658, 11675), True, 'import numpy as np\n'), ((11693, 11718), 'numpy.zeros', 'np.zeros', (['(Nt_tot, nspec)'], {}), '((Nt_tot, nspec))\n', (11701, 11718), True, 'import numpy as np\n'), ((11746, 11783), 'numpy.zeros', 'np.zeros', (['(Nt_tot, nspec, naky, nakx)'], {}), '((Nt_tot, nspec, naky, nakx))\n', (11754, 11783), True, 'import numpy as np\n'), ((11804, 11841), 'numpy.zeros', 'np.zeros', (['(Nt_tot, nspec, naky, nakx)'], {}), '((Nt_tot, nspec, naky, nakx))\n', (11812, 11841), True, 'import numpy as np\n'), ((11862, 11899), 'numpy.zeros', 'np.zeros', (['(Nt_tot, nspec, naky, nakx)'], {}), '((Nt_tot, nspec, naky, nakx))\n', (11870, 11899), True, 'import numpy as np\n'), ((11925, 11954), 'numpy.zeros', 'np.zeros', (['(nspec, naky, nakx)'], {}), '((nspec, naky, nakx))\n', (11933, 11954), True, 'import numpy as np\n'), ((11981, 12010), 'numpy.zeros', 'np.zeros', (['(nspec, naky, nakx)'], {}), '((nspec, naky, nakx))\n', (11989, 12010), True, 'import numpy as np\n'), ((12037, 12066), 'numpy.zeros', 'np.zeros', (['(nspec, naky, nakx)'], {}), '((nspec, naky, nakx))\n', (12045, 12066), True, 'import numpy as np\n'), ((12088, 12104), 'numpy.zeros', 'np.zeros', (['Nt_tot'], {}), '(Nt_tot)\n', (12096, 12104), True, 'import numpy as np\n'), ((12129, 12153), 'numpy.zeros', 'np.zeros', (['(Nt_tot, naky)'], {}), '((Nt_tot, naky))\n', (12137, 12153), True, 'import numpy as np\n'), ((12176, 12206), 'numpy.zeros', 'np.zeros', (['(Nt_tot, naky, nakx)'], {}), '((Nt_tot, naky, nakx))\n', (12184, 12206), True, 'import numpy as np\n'), ((12233, 12255), 'numpy.zeros', 'np.zeros', (['(naky, nakx)'], {}), '((naky, nakx))\n', (12241, 12255), True, 'import numpy as np\n'), ((22706, 22746), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (22721, 22746), True, 'import gs2_plotting as gplot\n'), ((25738, 25765), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (25748, 25765), True, 'from matplotlib import pyplot as plt\n'), ((25775, 25804), 'numpy.empty', 'np.empty', (['mytime.ntime_steady'], {}), '(mytime.ntime_steady)\n', (25783, 25804), True, 'import numpy as np\n'), ((26590, 26615), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t (a/v_t)$"""'], {}), "('$t (a/v_t)$')\n", (26600, 26615), True, 'from matplotlib import pyplot as plt\n'), ((26620, 26663), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[mytime.time[0], mytime.time[-1]]'], {}), '([mytime.time[0], mytime.time[-1]])\n', (26628, 26663), True, 'from matplotlib import pyplot as plt\n'), ((26667, 26683), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (26676, 26683), True, 'from matplotlib import pyplot as plt\n'), ((26688, 26700), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (26698, 26700), True, 'from matplotlib import pyplot as plt\n'), ((26705, 26719), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (26713, 26719), True, 'from matplotlib import pyplot as plt\n'), ((8257, 8272), 'numpy.zeros', 'np.zeros', (['Nfile'], {}), '(Nfile)\n', (8265, 8272), True, 'import numpy as np\n'), ((8273, 8288), 'numpy.zeros', 'np.zeros', (['Nfile'], {}), '(Nfile)\n', (8281, 8288), True, 'import numpy as np\n'), ((9604, 9637), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run'], {}), '(tmp_pdfname, run)\n', (9619, 9637), True, 'import gs2_plotting as gplot\n'), ((11363, 11383), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (11374, 11383), False, 'import pickle\n'), ((13802, 13846), 'numpy.ceil', 'np.ceil', (['((1.0 - twin) * stitch_my_time.ntime)'], {}), '((1.0 - twin) * stitch_my_time.ntime)\n', (13809, 13846), True, 'import numpy as np\n'), ((16457, 16471), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (16465, 16471), True, 'from matplotlib import pyplot as plt\n'), ((16557, 16597), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (16572, 16597), True, 'import gs2_plotting as gplot\n'), ((16915, 16955), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (16930, 16955), True, 'import gs2_plotting as gplot\n'), ((17264, 17304), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (17279, 17304), True, 'import gs2_plotting as gplot\n'), ((17620, 17660), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (17635, 17660), True, 'import gs2_plotting as gplot\n'), ((18322, 18338), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (18331, 18338), True, 'from matplotlib import pyplot as plt\n'), ((18347, 18372), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t (a/v_t)$"""'], {}), "('$t (a/v_t)$')\n", (18357, 18372), True, 'from matplotlib import pyplot as plt\n'), ((18381, 18393), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (18391, 18393), True, 'from matplotlib import pyplot as plt\n'), ((18402, 18416), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (18410, 18416), True, 'from matplotlib import pyplot as plt\n'), ((18502, 18542), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (18517, 18542), True, 'import gs2_plotting as gplot\n'), ((18788, 18817), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""nipy_spectral"""'], {}), "('nipy_spectral')\n", (18800, 18817), True, 'from matplotlib import pyplot as plt\n'), ((19520, 19545), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t (a/v_t)$"""'], {}), "('$t (a/v_t)$')\n", (19530, 19545), True, 'from matplotlib import pyplot as plt\n'), ((19554, 19570), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (19563, 19570), True, 'from matplotlib import pyplot as plt\n'), ((19579, 19616), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'prop': "{'size': 11}", 'ncol': '(6)'}), "(prop={'size': 11}, ncol=6)\n", (19589, 19616), True, 'from matplotlib import pyplot as plt\n'), ((19626, 19640), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (19634, 19640), True, 'from matplotlib import pyplot as plt\n'), ((19726, 19766), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (19741, 19766), True, 'import gs2_plotting as gplot\n'), ((22324, 22377), 'gs2_plotting.merge_pdfs', 'gplot.merge_pdfs', (['pdflist', 'merged_pdfname', 'run', 'ifile'], {}), '(pdflist, merged_pdfname, run, ifile)\n', (22340, 22377), True, 'import gs2_plotting as gplot\n'), ((24215, 24268), 'gs2_plotting.merge_pdfs', 'gplot.merge_pdfs', (['pdflist', 'merged_pdfname', 'run', 'ifile'], {}), '(pdflist, merged_pdfname, run, ifile)\n', (24231, 24268), True, 'import gs2_plotting as gplot\n'), ((26483, 26522), 'matplotlib.pyplot.plot', 'plt.plot', (['mytime.time_steady', 'dum', '"""--"""'], {}), "(mytime.time_steady, dum, '--')\n", (26491, 26522), True, 'from matplotlib import pyplot as plt\n'), ((27314, 27329), 'numpy.transpose', 'np.transpose', (['z'], {}), '(z)\n', (27326, 27329), True, 'import numpy as np\n'), ((27913, 27928), 'numpy.transpose', 'np.transpose', (['z'], {}), '(z)\n', (27925, 27928), True, 'import numpy as np\n'), ((1070, 1083), 'numpy.copy', 'np.copy', (['qflx'], {}), '(qflx)\n', (1077, 1083), True, 'import numpy as np\n'), ((1245, 1270), 'numpy.arange', 'np.arange', (['(1)'], {'dtype': 'float'}), '(1, dtype=float)\n', (1254, 1270), True, 'import numpy as np\n'), ((3743, 3771), 'pickle.dump', 'pickle.dump', (['mydict', 'datfile'], {}), '(mydict, datfile)\n', (3754, 3771), False, 'import pickle\n'), ((3958, 3986), 'pickle.dump', 'pickle.dump', (['mytime', 'datfile'], {}), '(mytime, datfile)\n', (3969, 3986), False, 'import pickle\n'), ((4174, 4203), 'pickle.dump', 'pickle.dump', (['mygrids', 'datfile'], {}), '(mygrids, datfile)\n', (4185, 4203), False, 'import pickle\n'), ((4431, 4451), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (4442, 4451), False, 'import pickle\n'), ((4624, 4644), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (4635, 4644), False, 'import pickle\n'), ((4819, 4839), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (4830, 4839), False, 'import pickle\n'), ((7861, 7881), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (7872, 7881), False, 'import pickle\n'), ((8065, 8085), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (8076, 8085), False, 'import pickle\n'), ((9419, 9444), 'numpy.min', 'np.min', (['qflx[:, :, ispec]'], {}), '(qflx[:, :, ispec])\n', (9425, 9444), True, 'import numpy as np\n'), ((9443, 9468), 'numpy.max', 'np.max', (['qflx[:, :, ispec]'], {}), '(qflx[:, :, ispec])\n', (9449, 9468), True, 'import numpy as np\n'), ((10408, 10428), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (10419, 10428), False, 'import pickle\n'), ((10612, 10632), 'pickle.load', 'pickle.load', (['datfile'], {}), '(datfile)\n', (10623, 10632), False, 'import pickle\n'), ((16398, 16451), 'gs2_plotting.plot_1d', 'gplot.plot_1d', (['time', 'phi2_avg', '"""$t (a/v_{t})$"""', 'title'], {}), "(time, phi2_avg, '$t (a/v_{t})$', title)\n", (16411, 16451), True, 'import gs2_plotting as gplot\n'), ((18239, 18316), 'matplotlib.pyplot.plot', 'plt.plot', (['mytime.time_steady', 'pioq[it_min:it_max, idx]'], {'label': 'spec_names[idx]'}), '(mytime.time_steady, pioq[it_min:it_max, idx], label=spec_names[idx])\n', (18247, 18316), True, 'from matplotlib import pyplot as plt\n'), ((20769, 20794), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t (a/v_t)$"""'], {}), "('$t (a/v_t)$')\n", (20779, 20794), True, 'from matplotlib import pyplot as plt\n'), ((20886, 20902), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (20895, 20902), True, 'from matplotlib import pyplot as plt\n'), ((20915, 20927), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20925, 20927), True, 'from matplotlib import pyplot as plt\n'), ((20940, 20954), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (20948, 20954), True, 'from matplotlib import pyplot as plt\n'), ((21204, 21244), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (21219, 21244), True, 'import gs2_plotting as gplot\n'), ((21843, 21868), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t (a/v_t)$"""'], {}), "('$t (a/v_t)$')\n", (21853, 21868), True, 'from matplotlib import pyplot as plt\n'), ((21881, 21897), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (21890, 21897), True, 'from matplotlib import pyplot as plt\n'), ((21910, 21922), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (21920, 21922), True, 'from matplotlib import pyplot as plt\n'), ((21935, 21949), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (21943, 21949), True, 'from matplotlib import pyplot as plt\n'), ((22047, 22087), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (22062, 22087), True, 'import gs2_plotting as gplot\n'), ((23052, 23092), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (23067, 23092), True, 'import gs2_plotting as gplot\n'), ((23454, 23494), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (23469, 23494), True, 'import gs2_plotting as gplot\n'), ((23858, 23898), 'gs2_plotting.save_plot', 'gplot.save_plot', (['tmp_pdfname', 'run', 'ifile'], {}), '(tmp_pdfname, run, ifile)\n', (23873, 23898), True, 'import gs2_plotting as gplot\n'), ((26154, 26211), 'matplotlib.pyplot.plot', 'plt.plot', (['mytime.time', 'flx[:, idx]'], {'label': 'spec_names[idx]'}), '(mytime.time, flx[:, idx], label=spec_names[idx])\n', (26162, 26211), True, 'from matplotlib import pyplot as plt\n'), ((1191, 1211), 'numpy.divide', 'np.divide', (['vflx', 'dum'], {}), '(vflx, dum)\n', (1200, 1211), True, 'import numpy as np\n'), ((6623, 6648), 'numpy.arange', 'np.arange', (['(1)'], {'dtype': 'float'}), '(1, dtype=float)\n', (6632, 6648), True, 'import numpy as np\n'), ((6649, 6674), 'numpy.arange', 'np.arange', (['(1)'], {'dtype': 'float'}), '(1, dtype=float)\n', (6658, 6674), True, 'import numpy as np\n'), ((7142, 7167), 'numpy.arange', 'np.arange', (['(1)'], {'dtype': 'float'}), '(1, dtype=float)\n', (7151, 7167), True, 'import numpy as np\n'), ((16332, 16348), 'numpy.log', 'np.log', (['phi2_avg'], {}), '(phi2_avg)\n', (16338, 16348), True, 'import numpy as np\n'), ((18856, 18883), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(naky - 1)'], {}), '(0, 1, naky - 1)\n', (18867, 18883), True, 'import numpy as np\n'), ((18967, 18991), 'numpy.log', 'np.log', (['phi2_by_ky[:, 0]'], {}), '(phi2_by_ky[:, 0])\n', (18973, 18991), True, 'import numpy as np\n'), ((26086, 26105), 'numpy.log', 'np.log', (['flx[:, idx]'], {}), '(flx[:, idx])\n', (26092, 26105), True, 'import numpy as np\n'), ((6978, 7003), 'numpy.arange', 'np.arange', (['(1)'], {'dtype': 'float'}), '(1, dtype=float)\n', (6987, 7003), True, 'import numpy as np\n'), ((7004, 7029), 'numpy.arange', 'np.arange', (['(1)'], {'dtype': 'float'}), '(1, dtype=float)\n', (7013, 7029), True, 'import numpy as np\n'), ((19137, 19163), 'numpy.log', 'np.log', (['phi2_by_ky[:, iky]'], {}), '(phi2_by_ky[:, iky])\n', (19143, 19163), True, 'import numpy as np\n'), ((20099, 20123), 'numpy.log', 'np.log', (['phi2_by_ky[:, 0]'], {}), '(phi2_by_ky[:, 0])\n', (20105, 20123), True, 'import numpy as np\n'), ((26329, 26353), 'numpy.absolute', 'np.absolute', (['flx[:, idx]'], {}), '(flx[:, idx])\n', (26340, 26353), True, 'import numpy as np\n'), ((20274, 20300), 'numpy.log', 'np.log', (['phi2_by_ky[:, iky]'], {}), '(phi2_by_ky[:, iky])\n', (20280, 20300), True, 'import numpy as np\n'), ((21554, 21580), 'numpy.log', 'np.log', (['phi2_by_ky[:, iky]'], {}), '(phi2_by_ky[:, iky])\n', (21560, 21580), True, 'import numpy as np\n')]
|
# code for a local TFlite (Tensor Flow Lite) test, assuming an env where tflite is installed, see instructions below
"""
sample zipped test env should be available here:
https://github.com/lineality/tensorflow_lite_in_aws_lambda_function
to use pre-made-zipped tflite env for python 3.8:
$ unzip env.zip
$ source env/bin/activate
(env) $ python3 local_tflite_test.py
Note: you can install python3.8 separately if your default is something else.
"""
"""
To install the tensorflow lite package (follow official tensorfow docs)
use:
pip3 install --extra-index-url https://google-coral.github.io/py-repo/ tflite_runtime
# instruction code to create python env (for uploading to AWS):
# only tflite_runtime is needed, numpy is included with tflite
$ python3 -m venv env; source env/bin/activate
$ pip install --upgrade pip
$ pip3 install --extra-index-url https://google-coral.github.io/py-repo/ tflite_runtime
$ pip freeze > requirements.txt
# drill down to -> env/lib/python3.8/sitepackages
# this makes the main zip file
$ zip -r9 ../../../../function.zip .
# make a lambda_function.py file
# later update this with real code
$ touch lambda_function.py
# In project-root folder:
# add .py file to your zip file
$ zip -g ./function.zip -r lambda_function.py
# to update the .py file (depending on OS)
# edit file in the ziped archive
# or re-add a new .py to replace the old by repeating the same step from above
$ zip -g ./function.zip -r lambda_function.py
"""
"""
Workflow:
1. get user_input
2. S3: Connect to S3 (Make resource and client)
3. download zip file from S3
4. extract zip and put in /tmp/
5. load model
6. make prediction
7. clear /tmp/
8. export result
"""
"""
Sample Ouput:
{
"statusCode": 200,
"about": "output_of_Tensorflow_ML_model",
"body": -0.07657486200332642
}
"""
"""
Sample input:
{
"s3_file_name": "model.tflite",
"s3_bucket_name": "api-sample-bucket1",
"user_input_for_X": 3.04
}
"""
# import librarires
import tflite_runtime.interpreter as tflite
from tflite_runtime.interpreter import Interpreter
import pathlib # not needed?
import numpy as np # not needed?
import glob # for directory file search
#from zipfile import ZipFile # Optional
def run_model():
# set up TF interpreter (point at .tflite model)
interpreter = Interpreter('model.tflite')
# for terminal
print("Model Loaded Successfully.")
###############
# Set up Model
###############
# set up interpreter
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# X: input data
X_raw_input = [[0.37094948,0.37094948,0.37094948,0.37094948]]
## for testing
#X_raw_input = [[0.37094948]]
# formatting: convert raw input number to an numpy array
input_data = np.asarray(X_raw_input, dtype=np.float32)
# y: using model, produce predicted y from X input
interpreter.set_tensor(input_details[0]['index'], input_data)
# Start interpreter
interpreter.invoke()
##################
# Make Prediction
##################
# Make Prediction
tflite_prediction_results = interpreter.get_tensor(output_details[0]['index'])
# for terminal
print("Prediction: y =", tflite_prediction_results)
############################
# process and format output
############################
"""
- remove brackets (remove from matrix/array), isolate just the number
- make type -> float
"""
tflite_prediction_results = tflite_prediction_results[0]
tflite_prediction_results = float( tflite_prediction_results[0] )
###############
# Final Output
###############
status_code = 200
output = tflite_prediction_results
return {
'statusCode': status_code,
'about': "output_of_Tensorflow_ML_model",
'body': output
}
run_model()
|
[
"numpy.asarray",
"tflite_runtime.interpreter.Interpreter"
] |
[((2302, 2329), 'tflite_runtime.interpreter.Interpreter', 'Interpreter', (['"""model.tflite"""'], {}), "('model.tflite')\n", (2313, 2329), False, 'from tflite_runtime.interpreter import Interpreter\n'), ((2876, 2917), 'numpy.asarray', 'np.asarray', (['X_raw_input'], {'dtype': 'np.float32'}), '(X_raw_input, dtype=np.float32)\n', (2886, 2917), True, 'import numpy as np\n')]
|
# this is the python implementation for the credit risk project
import os
import numpy as np
import pandas as pd
import re
from math import sqrt
import time
import string
import matplotlib
import matplotlib.pyplot as plt
import nltk
import sklearn
from sklearn import preprocessing
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.model_selection import RepeatedKFold
from sklearn.model_selection import cross_val_score
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.metrics.pairwise import cosine_distances
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.inspection import permutation_importance
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
# set environment
os.chdir(r'C:\Users\wmwms\OneDrive - George Mason University\Academics\2020Fall\CS584\HW2')
os.getcwd()
# load data
train_data = pd.read_csv(r"data\1600106342_882043_train.csv", header = 0)#, nrows = 2000)
test_data = pd.read_csv(r"data\1600106342_8864183_test.csv", header = 0)#, nrows = 1000)
test_data.head
# explore
#train_data.head
#train_data.iloc[0]
#test_data.head
#test_data.iloc[0]
#train_data.dtypes
#train_data.describe()
#test_data.describe()
#train_data.isnull().sum()
#test_data.isnull().sum()
train_data.cov()
train_data.corr()
#%matplotlib inline
#train_data.boxplot()
#pd.plotting.parallel_coordinates(train_data,'credit')
# check y value distribution
train_data['credit'].value_counts()
# make train data balanced
temp_train_data = train_data[train_data['credit']==0]
temp_train_data_1 = train_data[train_data['credit']==1]
temp_train_data.shape
temp_train_data_1.shape
# balanced data has F1 score 0.64
#train_data = temp_train_data.sample(n = 7841, replace = False).append(temp_train_data_1)
#train_data.shape
# increse 0 counts to 2x, F1 score 0.66
train_data = temp_train_data.sample(n = 7841*2, replace = False).append(temp_train_data_1)
train_data.shape
# increse 0 counts to 3x, F1 score 0.65
#train_data = temp_train_data.sample(n = 7841*3, replace = False).append(temp_train_data_1)
#train_data.shape
# data pre-processing
X_train = train_data.copy()
X_train = X_train.iloc[:,0:12]
Y_train = train_data['credit']
X_train.shape
Y_train.shape
X_test = test_data.copy()
X_test.shape
# convert string to numeric
from sklearn.preprocessing import LabelEncoder
lb_make = LabelEncoder()
X_train.groupby('F10')['F10'].nunique()
X_train["F10cat"] = lb_make.fit_transform(X_train["F10"])
X_train[["F10","F10cat"]].dtypes
X_train.groupby('F10cat')['F10cat'].nunique()
X_train['F10cat'].head
del X_train['F10']
X_train.head
lb_make = LabelEncoder()
X_train.groupby('F11')['F11'].nunique()
X_train["F11cat"] = lb_make.fit_transform(X_train["F11"])
X_train[["F11","F11cat"]].dtypes
X_train.groupby('F11cat')['F11cat'].nunique()
X_train['F11cat'].head
del X_train['F11']
del X_train['id']
X_train.head
lb_make = LabelEncoder()
X_test.groupby('F10')['F10'].nunique()
X_test["F10cat"] = lb_make.fit_transform(X_test["F10"])
X_test[["F10","F10cat"]].dtypes
X_test.groupby('F10cat')['F10cat'].nunique()
X_test['F10cat'].head
del X_test['F10']
X_test.head
lb_make = LabelEncoder()
X_test.groupby('F11')['F11'].nunique()
X_test["F11cat"] = lb_make.fit_transform(X_test["F11"])
X_test[["F11","F11cat"]].dtypes
X_test.groupby('F11cat')['F11cat'].nunique()
X_test['F11cat'].head
del X_test['F11']
del X_test['id']
X_test.head
new_test_data = X_test
Y_test = pd.DataFrame([0] * len(X_test.index))
# delete column(s)
del X_train['F3']
del X_test['F3']
new_test_data.shape
X_train.shape
Y_train.shape
X_test.shape
Y_test.shape
new_data_train = X_test
new_data_test = Y_test
X_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size = 0.33, shuffle = True)
# data standardization
X_train = preprocessing.scale(X_train)
X_test = preprocessing.scale(X_test)
# data normalization
#X_train = preprocessing.normalize(X_train)
#X_test = preprocessing.normalize(X_test)
pd.DataFrame(X_train).cov()
pd.DataFrame(X_train).corr()
###################################################################################
# preliminary models
# Decision Trees
# F1: 0.58
'''
from sklearn import tree
X_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size=0.8, random_state=1)
maxdepths = [2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50]
trainAcc = np.zeros(len(maxdepths))
testAcc = np.zeros(len(maxdepths))
index = 0
for depth in maxdepths:
clf = tree.DecisionTreeClassifier(max_depth=depth)
clf = clf.fit(X_train, Y_train)
Y_predTrain = clf.predict(X_train)
Y_predTest = clf.predict(X_test)
trainAcc[index] = accuracy_score(Y_train, Y_predTrain)
testAcc[index] = accuracy_score(Y_test, Y_predTest)
index += 1
plt.plot(maxdepths,trainAcc,'ro-',maxdepths,testAcc,'bv--')
plt.legend(['Training Accuracy','Test Accuracy'])
plt.xlabel('Max depth')
plt.ylabel('Accuracy')
'''
###################################################################################
'''
# KNN
# F1: 0.64
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
%matplotlib inline
numNeighbors = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
trainAcc = []
testAcc = []
for k in numNeighbors:
clf = KNeighborsClassifier(n_neighbors=k, metric='minkowski', p=2)
clf.fit(X_train, Y_train)
Y_predTrain = clf.predict(X_train)
Y_predTest = clf.predict(X_test)
trainAcc.append(accuracy_score(Y_train, Y_predTrain))
testAcc.append(accuracy_score(Y_test, Y_predTest))
plt.plot(numNeighbors, trainAcc, 'ro-', numNeighbors, testAcc,'bv--')
plt.legend(['Training Accuracy','Test Accuracy'])
plt.xlabel('Number of neighbors')
plt.ylabel('Accuracy')
'''
###################################################################################
# RandomForest
# F1: 0.64 with balanced data
from sklearn import ensemble
from sklearn.tree import DecisionTreeClassifier
numBaseClassifiers = 500
maxdepth = 10
trainAcc = []
testAcc = []
new_test_data.head
clf = ensemble.RandomForestClassifier(n_estimators=numBaseClassifiers)
clf.fit(X_train, Y_train)
Y_predTrain = clf.predict(X_train)
#Y_predTest = clf.predict(new_test_data)
#trainAcc.append(accuracy_score(Y_train, Y_predTrain))
#testAcc.append(accuracy_score(Y_test, Y_predTest))
#trainAcc
#testAcc
#Y_predTest
###################################################################################
# cross validation
# cv = KFold(n_splits = 10, random_state = 1, shuffle = True)
cv = RepeatedKFold(n_splits = 10, n_repeats = 3, random_state = 1)
scores = cross_val_score(clf,X_train, Y_train, scoring = 'accuracy', cv = cv, n_jobs = -1)
print('Accuracy: %.3f (%.3f)' % (np.mean(scores), np.std(scores)))
# F1 score
F1 = f1_score(Y_train,Y_predTrain, average = 'weighted')
print('F1 score: %.3f' % F1)
# feature importance
# found F3 to be of great importance yet its variance is large
importances = clf.feature_importances_
std = np.std([tree.feature_importances_ for tree in clf.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
print("Feature ranking:")
for f in range(X_train.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
plt.figure()
plt.title("Feature importances")
plt.bar(range(X_train.shape[1]), importances[indices],
color="r", yerr=std[indices], align="center")
plt.xticks(range(X_train.shape[1]), indices)
plt.xlim([-1, X_train.shape[1]])
plt.show()
###################################################################################
# prediction
Y_predTest = clf.predict(new_test_data)
# output
sub = pd.DataFrame(Y_predTest)
#sub = sub[0:]
submission = open("submission.txt","w")
submission.write(sub.to_string(index = False))
submission.close()
###################################################################################
|
[
"sklearn.ensemble.RandomForestClassifier",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"pandas.DataFrame",
"matplotlib.pyplot.show",
"sklearn.preprocessing.scale",
"os.getcwd",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"sklearn.model_selection.cross_val_score",
"numpy.std",
"sklearn.preprocessing.LabelEncoder",
"numpy.argsort",
"sklearn.metrics.f1_score",
"matplotlib.pyplot.figure",
"numpy.mean",
"sklearn.model_selection.RepeatedKFold",
"os.chdir"
] |
[((1085, 1192), 'os.chdir', 'os.chdir', (['"""C:\\\\Users\\\\wmwms\\\\OneDrive - George Mason University\\\\Academics\\\\2020Fall\\\\CS584\\\\HW2"""'], {}), "(\n 'C:\\\\Users\\\\wmwms\\\\OneDrive - George Mason University\\\\Academics\\\\2020Fall\\\\CS584\\\\HW2'\n )\n", (1093, 1192), False, 'import os\n'), ((1177, 1188), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1186, 1188), False, 'import os\n'), ((1215, 1273), 'pandas.read_csv', 'pd.read_csv', (['"""data\\\\1600106342_882043_train.csv"""'], {'header': '(0)'}), "('data\\\\1600106342_882043_train.csv', header=0)\n", (1226, 1273), True, 'import pandas as pd\n'), ((1305, 1363), 'pandas.read_csv', 'pd.read_csv', (['"""data\\\\1600106342_8864183_test.csv"""'], {'header': '(0)'}), "('data\\\\1600106342_8864183_test.csv', header=0)\n", (1316, 1363), True, 'import pandas as pd\n'), ((2693, 2707), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (2705, 2707), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((2951, 2965), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (2963, 2965), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((3227, 3241), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (3239, 3241), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((3477, 3491), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (3489, 3491), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((4017, 4081), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_train', 'Y_train'], {'test_size': '(0.33)', 'shuffle': '(True)'}), '(X_train, Y_train, test_size=0.33, shuffle=True)\n', (4033, 4081), False, 'from sklearn.model_selection import train_test_split\n'), ((4120, 4148), 'sklearn.preprocessing.scale', 'preprocessing.scale', (['X_train'], {}), '(X_train)\n', (4139, 4148), False, 'from sklearn import preprocessing\n'), ((4158, 4185), 'sklearn.preprocessing.scale', 'preprocessing.scale', (['X_test'], {}), '(X_test)\n', (4177, 4185), False, 'from sklearn import preprocessing\n'), ((6336, 6400), 'sklearn.ensemble.RandomForestClassifier', 'ensemble.RandomForestClassifier', ([], {'n_estimators': 'numBaseClassifiers'}), '(n_estimators=numBaseClassifiers)\n', (6367, 6400), False, 'from sklearn import ensemble\n'), ((6814, 6869), 'sklearn.model_selection.RepeatedKFold', 'RepeatedKFold', ([], {'n_splits': '(10)', 'n_repeats': '(3)', 'random_state': '(1)'}), '(n_splits=10, n_repeats=3, random_state=1)\n', (6827, 6869), False, 'from sklearn.model_selection import RepeatedKFold\n'), ((6885, 6961), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['clf', 'X_train', 'Y_train'], {'scoring': '"""accuracy"""', 'cv': 'cv', 'n_jobs': '(-1)'}), "(clf, X_train, Y_train, scoring='accuracy', cv=cv, n_jobs=-1)\n", (6900, 6961), False, 'from sklearn.model_selection import cross_val_score\n'), ((7051, 7101), 'sklearn.metrics.f1_score', 'f1_score', (['Y_train', 'Y_predTrain'], {'average': '"""weighted"""'}), "(Y_train, Y_predTrain, average='weighted')\n", (7059, 7101), False, 'from sklearn.metrics import f1_score\n'), ((7262, 7333), 'numpy.std', 'np.std', (['[tree.feature_importances_ for tree in clf.estimators_]'], {'axis': '(0)'}), '([tree.feature_importances_ for tree in clf.estimators_], axis=0)\n', (7268, 7333), True, 'import numpy as np\n'), ((7530, 7542), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7540, 7542), True, 'import matplotlib.pyplot as plt\n'), ((7543, 7575), 'matplotlib.pyplot.title', 'plt.title', (['"""Feature importances"""'], {}), "('Feature importances')\n", (7552, 7575), True, 'import matplotlib.pyplot as plt\n'), ((7730, 7762), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-1, X_train.shape[1]]'], {}), '([-1, X_train.shape[1]])\n', (7738, 7762), True, 'import matplotlib.pyplot as plt\n'), ((7763, 7773), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7771, 7773), True, 'import matplotlib.pyplot as plt\n'), ((7929, 7953), 'pandas.DataFrame', 'pd.DataFrame', (['Y_predTest'], {}), '(Y_predTest)\n', (7941, 7953), True, 'import pandas as pd\n'), ((7357, 7380), 'numpy.argsort', 'np.argsort', (['importances'], {}), '(importances)\n', (7367, 7380), True, 'import numpy as np\n'), ((4295, 4316), 'pandas.DataFrame', 'pd.DataFrame', (['X_train'], {}), '(X_train)\n', (4307, 4316), True, 'import pandas as pd\n'), ((4323, 4344), 'pandas.DataFrame', 'pd.DataFrame', (['X_train'], {}), '(X_train)\n', (4335, 4344), True, 'import pandas as pd\n'), ((7000, 7015), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (7007, 7015), True, 'import numpy as np\n'), ((7017, 7031), 'numpy.std', 'np.std', (['scores'], {}), '(scores)\n', (7023, 7031), True, 'import numpy as np\n')]
|
from ._functions import pdist
import numpy as np
def smote(minority_data_points, k=1):
'''
SMOTE (Synthetic Minority Oversampling TEchnique).
Used to generate more data points for minority class or imbalanced learning.
Parameters
----------
minority_data_points : numpy.array
Inputs or data points corresponding to the minority class.
k : int
Number of neighbors to consider.
Returns
-------
new_points : numpy.array
New generated data points (Excluding data points passed to the
function). :code:`k*minority_data_points.shape[0]` points will be
generated.
'''
npoints = minority_data_points.shape[0]
nfeatures = minority_data_points.shape[1]
# Calculate distance between each point and evry other point
distances = pdist(minority_data_points, minority_data_points)
# Get indices of closest k neigbours for each point
indices = np.argsort(distances, axis=1)[:, 1:k+1]
# Get the closest k neighbours for each point
neighbours = minority_data_points[indices].squeeze()
neighbours = neighbours.reshape(k*npoints, nfeatures)
# Calculate diffrence between points and k neighbours
minority_data_points_dups = minority_data_points[np.tile(np.arange(npoints).reshape(npoints, 1), k)]
minority_data_points_dups = minority_data_points_dups.reshape(k*npoints, nfeatures)
diff = neighbours - minority_data_points_dups
# Create new data points
random_floats = np.random.uniform(0, 1, (npoints*k))
new_points = minority_data_points_dups + (diff.T*random_floats).T
return new_points
|
[
"numpy.argsort",
"numpy.random.uniform",
"numpy.arange"
] |
[((1508, 1544), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(npoints * k)'], {}), '(0, 1, npoints * k)\n', (1525, 1544), True, 'import numpy as np\n'), ((950, 979), 'numpy.argsort', 'np.argsort', (['distances'], {'axis': '(1)'}), '(distances, axis=1)\n', (960, 979), True, 'import numpy as np\n'), ((1276, 1294), 'numpy.arange', 'np.arange', (['npoints'], {}), '(npoints)\n', (1285, 1294), True, 'import numpy as np\n')]
|
import numpy as np
import argparse
import glob
import amrex_plot_tools as amrex
if __name__ == "__main__":
import pylab as plt
rkey, ikey = amrex.get_particle_keys()
t = []
fee = []
fexR = []
fexI = []
fxx = []
pupt = []
files = sorted(glob.glob("plt[0-9][0-9][0-9][0-9][0-9]"))
print(files[0], files[-1])
for f in files:
plotfile = f #"plt"+str(i).zfill(5)
idata, rdata = amrex.read_particle_data(plotfile, ptype="neutrinos")
p = rdata[0]
t.append(p[rkey["time"]])
fee.append(p[rkey["f00_Re"]])
fexR.append(p[rkey["f01_Re"]])
fexI.append(p[rkey["f01_Im"]])
fxx.append(p[rkey["f11_Re"]])
pupt.append(p[rkey["pupt"]])
fee = np.array(fee)
fexR = np.array(fexR)
fexI = np.array(fexI)
fxx = np.array(fxx)
t = np.array(t)
print(t)
fig = plt.gcf()
fig.set_size_inches(8, 8)
plt.plot(t, fee, 'b-',linewidth=0.5,label="f00_Re")
plt.plot(t, fexR, 'g-',linewidth=0.5,label="f01_Re")
plt.plot(t, fexI, 'r-',linewidth=0.5,label="f01_Im")
plt.plot(t, fxx, 'k-',linewidth=0.5,label="f11_Re")
x = fexR
y = fexI
z = 0.5*(fee-fxx)
plt.plot(t, np.sqrt(x**2+y**2+z**2),linewidth=0.5,label="radius")
plt.grid()
plt.legend()
ax = plt.gca()
ax.set_xlabel(r'$t$ (s)')
ax.set_ylabel(r'$f$')
plt.savefig('single_neutrino.png')
|
[
"pylab.grid",
"pylab.savefig",
"numpy.array",
"amrex_plot_tools.get_particle_keys",
"glob.glob",
"pylab.gcf",
"pylab.gca",
"amrex_plot_tools.read_particle_data",
"pylab.legend",
"pylab.plot",
"numpy.sqrt"
] |
[((150, 175), 'amrex_plot_tools.get_particle_keys', 'amrex.get_particle_keys', ([], {}), '()\n', (173, 175), True, 'import amrex_plot_tools as amrex\n'), ((762, 775), 'numpy.array', 'np.array', (['fee'], {}), '(fee)\n', (770, 775), True, 'import numpy as np\n'), ((787, 801), 'numpy.array', 'np.array', (['fexR'], {}), '(fexR)\n', (795, 801), True, 'import numpy as np\n'), ((813, 827), 'numpy.array', 'np.array', (['fexI'], {}), '(fexI)\n', (821, 827), True, 'import numpy as np\n'), ((838, 851), 'numpy.array', 'np.array', (['fxx'], {}), '(fxx)\n', (846, 851), True, 'import numpy as np\n'), ((860, 871), 'numpy.array', 'np.array', (['t'], {}), '(t)\n', (868, 871), True, 'import numpy as np\n'), ((896, 905), 'pylab.gcf', 'plt.gcf', ([], {}), '()\n', (903, 905), True, 'import pylab as plt\n'), ((941, 994), 'pylab.plot', 'plt.plot', (['t', 'fee', '"""b-"""'], {'linewidth': '(0.5)', 'label': '"""f00_Re"""'}), "(t, fee, 'b-', linewidth=0.5, label='f00_Re')\n", (949, 994), True, 'import pylab as plt\n'), ((997, 1051), 'pylab.plot', 'plt.plot', (['t', 'fexR', '"""g-"""'], {'linewidth': '(0.5)', 'label': '"""f01_Re"""'}), "(t, fexR, 'g-', linewidth=0.5, label='f01_Re')\n", (1005, 1051), True, 'import pylab as plt\n'), ((1054, 1108), 'pylab.plot', 'plt.plot', (['t', 'fexI', '"""r-"""'], {'linewidth': '(0.5)', 'label': '"""f01_Im"""'}), "(t, fexI, 'r-', linewidth=0.5, label='f01_Im')\n", (1062, 1108), True, 'import pylab as plt\n'), ((1111, 1164), 'pylab.plot', 'plt.plot', (['t', 'fxx', '"""k-"""'], {'linewidth': '(0.5)', 'label': '"""f11_Re"""'}), "(t, fxx, 'k-', linewidth=0.5, label='f11_Re')\n", (1119, 1164), True, 'import pylab as plt\n'), ((1291, 1301), 'pylab.grid', 'plt.grid', ([], {}), '()\n', (1299, 1301), True, 'import pylab as plt\n'), ((1306, 1318), 'pylab.legend', 'plt.legend', ([], {}), '()\n', (1316, 1318), True, 'import pylab as plt\n'), ((1328, 1337), 'pylab.gca', 'plt.gca', ([], {}), '()\n', (1335, 1337), True, 'import pylab as plt\n'), ((1398, 1432), 'pylab.savefig', 'plt.savefig', (['"""single_neutrino.png"""'], {}), "('single_neutrino.png')\n", (1409, 1432), True, 'import pylab as plt\n'), ((276, 317), 'glob.glob', 'glob.glob', (['"""plt[0-9][0-9][0-9][0-9][0-9]"""'], {}), "('plt[0-9][0-9][0-9][0-9][0-9]')\n", (285, 317), False, 'import glob\n'), ((451, 504), 'amrex_plot_tools.read_particle_data', 'amrex.read_particle_data', (['plotfile'], {'ptype': '"""neutrinos"""'}), "(plotfile, ptype='neutrinos')\n", (475, 504), True, 'import amrex_plot_tools as amrex\n'), ((1228, 1261), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (1235, 1261), True, 'import numpy as np\n')]
|
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import numpy as np
def hill_slopes(rule, transactions):
"""Visualize rule as hill slopes.
**Reference:** <NAME>. et al. (2020). Visualization of Numerical Association Rules by Hill Slopes.
In: <NAME>., <NAME>., <NAME>., <NAME>. (eds) Intelligent Data Engineering and Automated Learning – IDEAL 2020.
IDEAL 2020. Lecture Notes in Computer Science(), vol 12489. Springer, Cham. https://doi.org/10.1007/978-3-030-62362-3_10
Args:
rule (Rule): Association rule to visualize.
transactions (pandas.DataFrame): Transactions as a DataFrame.
Returns:
tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]: Figure and Axes of plot.
"""
features = rule.antecedent + rule.consequent
num_features = len(features)
support = np.empty(num_features)
max_index = -1
max_support = -1
match_x = None
x_count = 0
for i, f in enumerate(features):
if f.dtype != 'cat':
match = (transactions[f.name] <= f.max_val) & (transactions[f.name] >= f.min_val)
else:
match = transactions[f.name] == f.categories[0]
supp_count = match.sum()
supp = supp_count / len(transactions)
support[i] = supp
if supp >= max_support:
max_support = supp
max_index = i
match_x = match
x_count = supp_count
confidence = np.empty(num_features)
for i, y in enumerate(features):
if i == max_index:
confidence[i] = 2
continue
if y.dtype != 'cat':
match_y = (transactions[y.name] <= y.max_val) & (transactions[y.name] >= y.min_val)
else:
match_y = transactions[y.name] == y.categories[0]
supp_count = (match_x & match_y).sum()
confidence[i] = supp_count / x_count
indices = np.argsort(confidence)[::-1]
confidence = confidence[indices]
confidence[0] = max_support
support = support[indices]
length = np.sqrt(support ** 2 + confidence ** 2)
position = np.empty(num_features)
position[0] = length[0] / 2
for i, ln in enumerate(length[1:]):
position[i + 1] = position[i] + length[i] / 2 + confidence[i + 1] + ln / 2
s = (length + support + confidence) / 2
a = s * (s - length) * (s - support) * (s - confidence)
if np.all(a >= 0):
a = np.sqrt(a)
height = 2 * a / length
x = np.sqrt(support ** 2 - height ** 2)
vec = np.concatenate((-length / 2, -length / 2 + x, length / 2))
vec = (vec.reshape(3, num_features) + position).T.reshape(len(vec))
height = np.concatenate((height, np.zeros(len(vec) - num_features)))
height = np.reshape(height, (3, num_features)).T.reshape(len(vec))
height = np.concatenate((np.zeros(1), height))[:len(vec)]
fig, ax = _ribbon(vec, height)
ax.set_ylabel('Location')
ax.set_yticks(range(num_features + 1))
ax.set_yticklabels(range(num_features + 1))
ax.set_zlabel('Height')
ax.view_init(30, 240)
return fig, ax
def _ribbon(x, z, width=0.5):
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
xi = np.linspace(x[:-1], x[1:], num=100, axis=1).flatten()
zi = np.interp(xi, x, z)
xx = np.column_stack((-np.ones(len(zi)), np.ones(len(zi)))) * width + 1
yy = np.column_stack((xi, xi))
zz = np.column_stack((zi, zi))
scalar_map = ScalarMappable(Normalize(vmin=0, vmax=zi.max()))
colors = scalar_map.to_rgba(zz)
ax.plot_surface(xx, yy, zz, rstride=1, cstride=1, facecolors=colors)
fig.colorbar(scalar_map, shrink=0.5, aspect=10)
return fig, ax
|
[
"numpy.concatenate",
"numpy.empty",
"numpy.zeros",
"numpy.argsort",
"numpy.reshape",
"numpy.linspace",
"numpy.column_stack",
"numpy.interp",
"matplotlib.pyplot.subplots",
"numpy.all",
"numpy.sqrt"
] |
[((893, 915), 'numpy.empty', 'np.empty', (['num_features'], {}), '(num_features)\n', (901, 915), True, 'import numpy as np\n'), ((1499, 1521), 'numpy.empty', 'np.empty', (['num_features'], {}), '(num_features)\n', (1507, 1521), True, 'import numpy as np\n'), ((2088, 2127), 'numpy.sqrt', 'np.sqrt', (['(support ** 2 + confidence ** 2)'], {}), '(support ** 2 + confidence ** 2)\n', (2095, 2127), True, 'import numpy as np\n'), ((2143, 2165), 'numpy.empty', 'np.empty', (['num_features'], {}), '(num_features)\n', (2151, 2165), True, 'import numpy as np\n'), ((2434, 2448), 'numpy.all', 'np.all', (['(a >= 0)'], {}), '(a >= 0)\n', (2440, 2448), True, 'import numpy as np\n'), ((3226, 3271), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'subplot_kw': "{'projection': '3d'}"}), "(subplot_kw={'projection': '3d'})\n", (3238, 3271), True, 'import matplotlib.pyplot as plt\n'), ((3345, 3364), 'numpy.interp', 'np.interp', (['xi', 'x', 'z'], {}), '(xi, x, z)\n', (3354, 3364), True, 'import numpy as np\n'), ((3451, 3476), 'numpy.column_stack', 'np.column_stack', (['(xi, xi)'], {}), '((xi, xi))\n', (3466, 3476), True, 'import numpy as np\n'), ((3486, 3511), 'numpy.column_stack', 'np.column_stack', (['(zi, zi)'], {}), '((zi, zi))\n', (3501, 3511), True, 'import numpy as np\n'), ((1945, 1967), 'numpy.argsort', 'np.argsort', (['confidence'], {}), '(confidence)\n', (1955, 1967), True, 'import numpy as np\n'), ((2462, 2472), 'numpy.sqrt', 'np.sqrt', (['a'], {}), '(a)\n', (2469, 2472), True, 'import numpy as np\n'), ((2517, 2552), 'numpy.sqrt', 'np.sqrt', (['(support ** 2 - height ** 2)'], {}), '(support ** 2 - height ** 2)\n', (2524, 2552), True, 'import numpy as np\n'), ((2568, 2626), 'numpy.concatenate', 'np.concatenate', (['(-length / 2, -length / 2 + x, length / 2)'], {}), '((-length / 2, -length / 2 + x, length / 2))\n', (2582, 2626), True, 'import numpy as np\n'), ((3282, 3325), 'numpy.linspace', 'np.linspace', (['x[:-1]', 'x[1:]'], {'num': '(100)', 'axis': '(1)'}), '(x[:-1], x[1:], num=100, axis=1)\n', (3293, 3325), True, 'import numpy as np\n'), ((2798, 2835), 'numpy.reshape', 'np.reshape', (['height', '(3, num_features)'], {}), '(height, (3, num_features))\n', (2808, 2835), True, 'import numpy as np\n'), ((2889, 2900), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (2897, 2900), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
# @Time : 2020/12/12
# @Author : <NAME>
# @GitHub : https://github.com/lartpang
from functools import wraps
import numpy as np
import torch
def reduce_score(score: torch.Tensor, mean_on_loss: bool = True):
if mean_on_loss:
loss = (1 - score).mean()
else:
loss = 1 - score.mean()
return loss
def reduce_loss(loss: torch.Tensor, reduction: str = "mean") -> torch.Tensor:
"""
:param loss: loss tensor
:param reduction: mean, sum, or none
"""
if reduction == "mean":
loss = loss.mean()
elif reduction == "sum":
loss = loss.sum()
elif reduction == "none":
pass
else:
raise NotImplementedError
return loss
def check_args(func):
"""
Decorator that checks the validity of the parameters.
"""
@wraps(func)
def wrapper(logits, gts=None, **kwargs):
if logits.ndim != 4:
raise ValueError(
f"Only support N,C,H,W logits, but get {logits.shape} and {logits.type()}"
)
if gts is not None:
if gts.ndim != 4 or gts.shape[1] != 1:
raise ValueError(f"Only support N,1,H,W gts, but get {gts.shape} and {gts.type()}")
if logits.shape[0] != gts.shape[0] or logits.shape[2:] != gts.shape[2:]:
raise ValueError(
f"Logits {logits.shape} and gts {gts.shape} must have the same size."
)
if not 1 <= logits.shape[1] <= gts.max():
raise ValueError(
"The num_classes of logits is not compatible with the one of gts."
)
return func(logits, gts, **kwargs)
return wrapper
def cal_sparse_coef(curr_iter, num_iter, method="linear", extra_args=None):
if extra_args is None:
extra_args = {}
def _linear(curr_iter, milestones=(0.3, 0.7), coef_range=(0, 1)):
min_point, max_point = min(milestones), max(milestones)
min_coef, max_coef = min(coef_range), max(coef_range)
if curr_iter < (num_iter * min_point):
coef = min_coef
elif curr_iter > (num_iter * max_point):
coef = max_coef
else:
ratio = (max_coef - min_coef) / (num_iter * (max_point - min_point))
coef = ratio * (curr_iter - num_iter * min_point)
return coef
def _cos(curr_iter, coef_range=(0, 1)):
min_coef, max_coef = min(coef_range), max(coef_range)
normalized_coef = (1 - np.cos(curr_iter / num_iter * np.pi)) / 2
coef = normalized_coef * (max_coef - min_coef) + min_coef
return coef
def _constant(curr_iter, constant=1.0):
return constant
_funcs = dict(
linear=_linear,
cos=_cos,
constant=_constant,
)
coef = _funcs[method](curr_iter, **extra_args)
return coef
|
[
"numpy.cos",
"functools.wraps"
] |
[((835, 846), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (840, 846), False, 'from functools import wraps\n'), ((2511, 2547), 'numpy.cos', 'np.cos', (['(curr_iter / num_iter * np.pi)'], {}), '(curr_iter / num_iter * np.pi)\n', (2517, 2547), True, 'import numpy as np\n')]
|
# import unittest
from pandas import DataFrame
from pandas.tools.describe import value_range
import numpy as np
def test_value_range():
df = DataFrame(np.random.randn(5, 5))
df.ix[0, 2] = -5
df.ix[2, 0] = 5
res = value_range(df)
assert(res['Minimum'] == -5)
assert(res['Maximum'] == 5)
df.ix[0, 1] = np.NaN
assert(res['Minimum'] == -5)
assert(res['Maximum'] == 5)
|
[
"numpy.random.randn",
"pandas.tools.describe.value_range"
] |
[((234, 249), 'pandas.tools.describe.value_range', 'value_range', (['df'], {}), '(df)\n', (245, 249), False, 'from pandas.tools.describe import value_range\n'), ((159, 180), 'numpy.random.randn', 'np.random.randn', (['(5)', '(5)'], {}), '(5, 5)\n', (174, 180), True, 'import numpy as np\n')]
|
# Training to a set of multiple objects (e.g. ShapeNet or DTU)
# tensorboard logs available in logs/<expname>
import imp
import sys
import os
from unittest.mock import patch
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
)
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src"))
)
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "train"))
)
import warnings
import trainlib
from model import make_model, loss
from render import NeRFRenderer
from data import get_split_dataset
import util
import numpy as np
import torch.nn.functional as F
import torch
import tqdm
from dotmap import DotMap
from data.AppearanceDataset import AppearanceDataset
from random import randint
from torchvision.transforms.functional_tensor import crop
def extra_args(parser):
parser.add_argument(
"--batch_size", "-B", type=int, default=4, help="Object batch size ('SB')"
)
parser.add_argument(
"--nviews",
"-V",
type=str,
default="1",
help="Number of source views (multiview); put multiple (space delim) to pick randomly per batch ('NV')",
)
parser.add_argument(
"--freeze_enc",
action="store_true",
default=None,
help="Freeze encoder weights and only train MLP",
)
parser.add_argument(
"--no_bbox_step",
type=int,
default=100000,
help="Step to stop using bbox sampling",
)
parser.add_argument(
"--fixed_test",
action="store_true",
default=None,
help="Freeze encoder weights and only train MLP",
)
parser.add_argument(
"--dset_ind", "-ID", type=int, default=0, help="Index of scene to be modified in dataset"
)
parser.add_argument(
"--appdir", "-DA", type=str, default=None, help="Appearance Dataset directory"
)
parser.add_argument(
"--appearance_format",
"-FA",
type=str,
default=None,
help="Appearance format, eth3d (only for now)",
)
parser.add_argument(
"--app_ind", "-IA", type=int, default=0, help="Index of image to be used for appearance harmonization"
)
parser.add_argument(
"--load_app_encoder",
action="store_true",
default=None,
help="Load an appearance encoder's weights",
)
parser.add_argument(
"--freeze_app_enc",
action="store_true",
default=None,
help="Freeze appearance encoder weights and only train MLP",
)
parser.add_argument(
"--app_enc_off",
action="store_true",
default=None,
help="Train without appearance encoder enhancements",
)
parser.add_argument(
"--freeze_f1",
action="store_true",
default=None,
help="Freeze first multi-view network weights and only train later MLP",
)
parser.add_argument(
"--refencdir", "-DRE", type=str, default=None, help="Reference encoder directory (used for loss)"
)
parser.add_argument(
"--patch_dim", "-P", type=int, default=128, help="The H and W dimension of image patches (power of 2)"
)
parser.add_argument(
"--subpatch_factor", "-PS", type=int, default=1, help="patch_dim / subpatch_factor * 2 = subpatches rendered and composed (power of 2)"
)
parser.add_argument(
"--vis_step_off",
action="store_true",
default=None,
help="Skip the visualization steps of our scene",
)
return parser
args, conf = util.args.parse_args(extra_args, training=True, default_ray_batch_size=128)
device = util.get_cuda(args.gpu_id[0])
app_size = None
app_size_h = conf.get_int("data.app_data.img_size_h", None)
app_size_w = conf.get_int("data.app_data.img_size_w", None)
if (app_size_h is not None and app_size_w is not None):
app_size = (app_size_h, app_size_w)
dset, val_dset, _ = get_split_dataset(args.dataset_format, args.datadir)
if not args.app_enc_off:
dset_app = AppearanceDataset(args.appdir, "train", image_size=app_size, img_ind=args.app_ind)
print(
"dset z_near {}, z_far {}, lindisp {}".format(dset.z_near, dset.z_far, dset.lindisp)
)
net = make_model(
conf["model"],
app_enc_on = not args.app_enc_off,
stop_encoder_grad=args.freeze_enc,
stop_app_encoder_grad=args.freeze_app_enc,
stop_f1_grad=args.freeze_f1
).to(device=device)
if args.freeze_enc:
print("Encoder frozen")
net.encoder.eval()
if args.app_enc_off:
print("Appearance encoder OFF (training normally)")
else:
print("Appearance encoder on")
if args.freeze_app_enc:
print("Appearance encoder weights frozen")
net.app_encoder.eval()
renderer = NeRFRenderer.from_conf(conf["renderer"], lindisp=dset.lindisp,).to(
device=device
)
# Parallize
render_par = renderer.bind_parallel(net, args.gpu_id).eval()
nviews = list(map(int, args.nviews.split()))
class PixelNeRF_ATrainer(trainlib.Trainer):
def __init__(self):
super().__init__(net, dset, val_dset, args, conf["train"], device=device)
self.renderer_state_path = "%s/%s/_renderer" % (
self.args.checkpoints_path,
self.args.name,
)
self.lambda_coarse = conf.get_float("loss.lambda_coarse")
self.lambda_fine = conf.get_float("loss.lambda_fine", 1.0)
print(
"lambda coarse {} and fine {}".format(self.lambda_coarse, self.lambda_fine)
)
self.rgb_coarse_crit = loss.get_rgb_loss(conf["loss.rgb"], True)
if "rgb_fine" in conf["loss"]:
print("using fine loss")
fine_loss_conf = conf["loss.rgb_fine"]
self.rgb_fine_crit = loss.get_rgb_loss(fine_loss_conf, False)
# Loss configuration for appearance specific losses
self.lambda_density_coarse = conf.get_float("loss.lambda_density_coarse")
self.lambda_density_fine = conf.get_float("loss.lambda_density_fine")
self.lambda_ref_coarse = conf.get_float("loss.lambda_ref_coarse")
self.lambda_ref_fine = conf.get_float("loss.lambda_ref_fine")
print("lambda coarse density {}, fine density {}, reference coarse {}, and reference fine {}".format(
self.lambda_density_coarse,
self.lambda_density_fine,
self.lambda_ref_coarse,
self.lambda_ref_fine
))
density_loss_conf = conf["loss.density"]
self.density_app_crit = loss.get_density_loss(density_loss_conf)
self.ref_app_crit = loss.ReferenceColorLoss(conf, args.refencdir).to(device=device)
if args.resume:
if os.path.exists(self.renderer_state_path):
renderer.load_state_dict(
torch.load(self.renderer_state_path, map_location=device)
)
self.z_near = dset.z_near
self.z_far = dset.z_far
self.use_bbox = args.no_bbox_step > 0
# Premeptively our dataset as we train on a single scene
self.nerf_data = dset[args.dset_ind]
SB = args.batch_size
NV, _, H, W = self.nerf_data["images"].shape
self.nerf_data["images"] = self.nerf_data["images"].unsqueeze(0).expand(SB, NV, 3, H, W)
self.nerf_data["poses"] = self.nerf_data["poses"].unsqueeze(0).expand(SB, NV, 4, 4)
self.nerf_data["focal"] = self.nerf_data["focal"].unsqueeze(0).expand(SB, 2)
self.nerf_data["c"] = self.nerf_data["c"].unsqueeze(0).expand(SB, 2)
# Decide whether you're training with or without the appearance encoder
self.app_enc_on = not args.app_enc_off
self.calc_losses = self.calc_losses_app if self.app_enc_on else self.calc_losses_no_app
# If we are, that means we're using a background and patch loss
if self.app_enc_on:
self.appearance_img = dset_app[args.app_ind]["images"].unsqueeze(0).to(device=device)
self.patch_dim = args.patch_dim
self.subpatch_factor = args.subpatch_factor
self.ssh_dim = (256, 256) # Original processing resolution of SHH Encoder
else:
self.appearance_img = None
# Choose whether to skip visualizing our scene every epoch
self.vis_step_on = not args.vis_step_off
def post_batch(self, epoch, batch):
renderer.sched_step(args.batch_size)
def extra_save_state(self):
torch.save(renderer.state_dict(), self.renderer_state_path)
def choose_views(self, data):
all_images = data["images"].to(device=device) # (SB, NV, 3, H, W)
all_poses = data["poses"].to(device=device) # (SB, NV, 4, 4)
SB, NV, _, _, _ = all_images.shape
curr_nviews = nviews[torch.randint(0, len(nviews), ()).item()]
if curr_nviews == 1:
image_ord = torch.randint(0, NV, (SB, 1)).to(device=device)
else:
image_ord = torch.empty((SB, curr_nviews), dtype=torch.long).to(device=device)
for obj_idx in range(SB):
if curr_nviews > 1:
# Somewhat inefficient, don't know better way
image_ord[obj_idx] = torch.from_numpy(
np.random.choice(NV, curr_nviews, replace=False)
)
src_images = util.batched_index_select_nd(
all_images, image_ord
) # (SB, NS, 3, H, W)
src_poses = util.batched_index_select_nd(all_poses, image_ord) # (SB, NS, 4, 4)
return src_images, src_poses
def encode_chosen_views(self, data, src_images, src_poses):
all_focals = data["focal"] # (SB)
all_c = data.get("c") # (SB)
net.encode(
src_images,
src_poses,
all_focals.to(device=device),
c=all_c.to(device=device) if all_c is not None else None,
)
def rand_rays(self, data, is_train=True, global_step=0):
if "images" not in data:
return {}
all_images = data["images"].to(device=device) # (SB, NV, 3, H, W)
SB, NV, _, H, W = all_images.shape
all_poses = data["poses"].to(device=device) # (SB, NV, 4, 4)
all_bboxes = data.get("bbox") # (SB, NV, 4) cmin rmin cmax rmax
all_focals = data["focal"] # (SB)
if self.use_bbox and global_step >= args.no_bbox_step:
self.use_bbox = False
print(">>> Stopped using bbox sampling @ iter", global_step)
if not is_train or not self.use_bbox:
all_bboxes = None
all_rgb_gt = []
all_rays = []
for obj_idx in range(SB):
if all_bboxes is not None:
bboxes = all_bboxes[obj_idx]
images = all_images[obj_idx] # (NV, 3, H, W)
poses = all_poses[obj_idx] # (NV, 4, 4)
focal = all_focals[obj_idx]
c = None
if "c" in data:
c = data["c"][obj_idx]
images_0to1 = images * 0.5 + 0.5
cam_rays = util.gen_rays(
poses, W, H, focal, self.z_near, self.z_far, c=c
) # (NV, H, W, 8)
rgb_gt_all = images_0to1
rgb_gt_all = (
rgb_gt_all.permute(0, 2, 3, 1).contiguous().reshape(-1, 3)
) # (NV, H, W, 3)
if all_bboxes is not None:
pix = util.bbox_sample(bboxes, args.ray_batch_size)
pix_inds = pix[..., 0] * H * W + pix[..., 1] * W + pix[..., 2]
else:
pix_inds = torch.randint(0, NV * H * W, (args.ray_batch_size,))
rgb_gt = rgb_gt_all[pix_inds] # (ray_batch_size, 3)
rays = cam_rays.view(-1, cam_rays.shape[-1])[pix_inds].to(
device=device
) # (ray_batch_size, 8)
all_rgb_gt.append(rgb_gt)
all_rays.append(rays)
all_rgb_gt = torch.stack(all_rgb_gt) # (SB, ray_batch_size, 3)
all_rays = torch.stack(all_rays) # (SB, ray_batch_size, 8)
all_bboxes = all_poses = all_images = None
return all_rays, all_rgb_gt
def patch_rays(self, data):
if "images" not in data:
return {}
all_images = data["images"].to(device=device) # (SB, NV, 3, H, W)
SB, NV, _, H, W = all_images.shape
all_poses = data["poses"].to(device=device) # (SB, NV, 4, 4)
all_focals = data["focal"] # (SB)
all_rgb_gt = []
all_rays = []
for obj_idx in range(SB):
images = all_images[obj_idx] # (NV, 3, H, W)
poses = all_poses[obj_idx] # (NV, 4, 4)
focal = all_focals[obj_idx]
c = None
if "c" in data:
c = data["c"][obj_idx]
images_0to1 = images * 0.5 + 0.5
cam_rays = util.gen_rays(
poses, W, H, focal, self.z_near, self.z_far, c=c
).permute(0, 3, 1, 2)
rgb_gt_all = images_0to1
rgb_gt_all = (
rgb_gt_all.permute(0, 2, 3, 1).contiguous().reshape(-1, 3)
).reshape(NV, 3, H, W)
P = self.patch_dim
i = randint(0, H - P)
j = randint(0, W - P)
rgb_gt = crop(rgb_gt_all, i, j, P, P)
rays = crop(cam_rays, i, j, P, P)
all_rgb_gt.append(rgb_gt)
all_rays.append(rays)
all_rgb_gt = torch.stack(all_rgb_gt) # (SB, ray_batch_size, 3)
all_rays = torch.stack(all_rays) # (SB, ray_batch_size, 8)
image_ord = torch.randint(0, NV, (SB, 1)).to(device=device)
all_rays = util.batched_index_select_nd(all_rays, image_ord)
all_rgb_gt = util.batched_index_select_nd(all_rgb_gt, image_ord).reshape(SB, -1, 3)
all_poses = all_images = None
return all_rays, all_rgb_gt
def encode_back_patch(self):
P = self.patch_dim
back_patch = util.get_random_patch(self.appearance_img, P, P)
back_patch = F.interpolate(back_patch, size=self.ssh_dim, mode="area")
self.ref_app_crit.encode_targets(back_patch)
def reg_pass(self, all_rays):
return DotMap(render_par(all_rays, want_weights=True, app_pass=False))
def app_pass(self, app_imgs, all_rays):
# Appearance encoder encoding
net.app_encoder.encode(app_imgs)
render_dict = DotMap(render_par(all_rays, want_weights=True, app_pass=True))
return render_dict
def nerf_loss(self, render_dict, all_rgb_gt, loss_dict):
# Compute our standard PixelNeRF loss
coarse = render_dict.coarse
fine = render_dict.fine
using_fine = len(fine) > 0
rgb_loss = self.rgb_coarse_crit(coarse.rgb, all_rgb_gt) * self.lambda_coarse
loss_dict["rc"] = rgb_loss.item()
if using_fine:
fine_loss = self.rgb_fine_crit(fine.rgb, all_rgb_gt) * self.lambda_fine
rgb_loss += fine_loss
loss_dict["rf"] = fine_loss.item()
return rgb_loss
def depth_loss(self, app_render_dict, reg_render_dict, loss_dict):
coarse_reg = reg_render_dict.coarse
fine_reg = reg_render_dict.fine
coarse_app = app_render_dict.coarse
fine_app = app_render_dict.fine
using_fine_app = len(fine_app) > 0
density_app_loss = self.density_app_crit(coarse_reg.depth.detach(), coarse_app.depth) * self.lambda_density_coarse
loss_dict["dc"] = density_app_loss.item()
if using_fine_app:
density_app_loss_fine = self.density_app_crit(fine_reg.depth.detach(), fine_app.depth) * self.lambda_density_fine
density_app_loss += density_app_loss_fine
loss_dict["df"] = density_app_loss_fine.item()
return density_app_loss
def app_loss(self, src_images, subpatch_dicts, loss_dict):
SB, _, D, H, W = src_images.shape
P = self.patch_dim
# Going to assume fine network is here. If its an issue, change later.
coarse_app_rgb, fine_app_rgb = util.recompose_subpatch_render_dicts_rgb(subpatch_dicts, SB, P, self.subpatch_factor)
app_rgb_coarse = util.ssh_normalization(coarse_app_rgb)
app_rgb_coarse = F.interpolate(app_rgb_coarse, size=self.ssh_dim, mode="area")
ref_app_loss = self.ref_app_crit(app_rgb_coarse) * self.lambda_ref_coarse
loss_dict["rec"] = ref_app_loss.item()
app_rgb_fine = util.ssh_normalization(fine_app_rgb)
app_rgb_fine = F.interpolate(app_rgb_fine, size=self.ssh_dim, mode="area")
ref_app_loss_fine = self.ref_app_crit(app_rgb_fine) * self.lambda_ref_fine
ref_app_loss += ref_app_loss_fine
loss_dict["ref"] = ref_app_loss.item()
return ref_app_loss
def calc_losses_no_app(self, data, app_data, is_train=True, global_step=0):
# Establish the views we'll be using to train
src_images, src_poses = self.choose_views(data)
# Encode our chosen views
self.encode_chosen_views(data, src_images, src_poses)
# Choose our standard randomly-smapled rays for our regular pass
nerf_rays, nerf_rays_gt = self.rand_rays(data, is_train, global_step)
# Render out our scene with our ground truth model
reg_render_dict = self.reg_pass(nerf_rays)
loss_dict = {}
# Compute our standard NeRF losses and losses associated with appearance encoder
loss = self.nerf_loss(reg_render_dict, nerf_rays_gt, loss_dict)
if is_train:
loss.backward()
loss_dict["t"] = loss.item()
return loss_dict
def calc_losses_app(self, data, app_data, is_train=True, global_step=0):
# Establish the views we'll be using to train
src_images, src_poses = self.choose_views(data)
# Encode our chosen views
self.encode_chosen_views(data, src_images, src_poses)
# Choose our standard randomly-smapled rays for our regular pass
nerf_rays, nerf_rays_gt = self.rand_rays(data, is_train, global_step)
# Render out our scene with our ground truth model
reg_render_dict = self.reg_pass(nerf_rays)
# Encode a random patch from the background image
self.encode_back_patch()
# Render out our scene using appearance encoding and trainable F2
app_render_dict = self.app_pass(app_data, nerf_rays)
loss_dict = {}
# Compute our standard NeRF losses and losses associated with appearance encoder
nerf_loss = self.nerf_loss(app_render_dict, nerf_rays_gt, loss_dict)
# Compute our density loss using the depthmap from our ground truth
depth_loss = self.depth_loss(app_render_dict, reg_render_dict, loss_dict)
reg_render_dict = app_render_dict = None
# Choose rays corresponding to an image patch at our disposal
patch_rays, _ = self.patch_rays(data)
# Decompose this patch into smaller subpatches
subpatch_rays = util.decompose_to_subpatches(patch_rays, self.subpatch_factor)
# Render out these subpatches
subpatch_dicts = []
for i in range(self.subpatch_factor):
row = []
for j in range(self.subpatch_factor):
row.append(self.app_pass(app_data, subpatch_rays[i][j]))
subpatch_dicts.append(row)
# Compute our appearance loss using our appearance encoder and these subpatches
app_loss = self.app_loss(src_images, subpatch_dicts, loss_dict)
# Compute our standard NeRF loss
loss = nerf_loss + depth_loss + app_loss
if is_train:
loss.backward()
loss_dict["t"] = loss.item()
return loss_dict
def train_step(self, data, app_data, global_step):
return self.calc_losses(data, app_data, is_train=True, global_step=global_step)
def eval_step(self, data, app_data, global_step):
renderer.eval()
losses = self.calc_losses(data, app_data, is_train=False, global_step=global_step)
renderer.train()
return losses
def vis_step(self, data, global_step, idx=None):
if "images" not in data:
return {}
if idx is None:
batch_idx = np.random.randint(0, data["images"].shape[0])
else:
print(idx)
batch_idx = idx
images = data["images"][batch_idx].to(device=device) # (NV, 3, H, W)
if self.app_enc_on:
app_images = self.appearance_img
poses = data["poses"][batch_idx].to(device=device) # (NV, 4, 4)
focal = data["focal"][batch_idx : batch_idx + 1] # (1)
c = data.get("c")
if c is not None:
c = c[batch_idx : batch_idx + 1] # (1)
NV, _, H, W = images.shape
cam_rays = util.gen_rays(
poses, W, H, focal, self.z_near, self.z_far, c=c
) # (NV, H, W, 8)
images_0to1 = images * 0.5 + 0.5 # (NV, 3, H, W)
curr_nviews = nviews[torch.randint(0, len(nviews), (1,)).item()]
views_src = np.sort(np.random.choice(NV, curr_nviews, replace=False))
view_dest = np.random.randint(0, NV - curr_nviews)
for vs in range(curr_nviews):
view_dest += view_dest >= views_src[vs]
views_src = torch.from_numpy(views_src)
# set renderer net to eval mode
renderer.eval()
source_views = (
images_0to1[views_src]
.permute(0, 2, 3, 1)
.cpu()
.numpy()
.reshape(-1, H, W, 3)
)
gt = images_0to1[view_dest].permute(1, 2, 0).cpu().numpy().reshape(H, W, 3)
with torch.no_grad():
test_rays = cam_rays[view_dest] # (H, W, 8)
test_images = images[views_src] # (NS, 3, H, W)
net.encode(
test_images.unsqueeze(0),
poses[views_src].unsqueeze(0),
focal.to(device=device),
c=c.to(device=device) if c is not None else None,
)
if self.app_enc_on:
net.app_encoder.encode(app_images)
test_rays = test_rays.reshape(1, H * W, -1)
render_dict = DotMap(render_par(test_rays, want_weights=True))
coarse = render_dict.coarse
fine = render_dict.fine
using_fine = len(fine) > 0
alpha_coarse_np = coarse.weights[0].sum(dim=-1).cpu().numpy().reshape(H, W)
rgb_coarse_np = coarse.rgb[0].cpu().numpy().reshape(H, W, 3)
depth_coarse_np = coarse.depth[0].cpu().numpy().reshape(H, W)
if using_fine:
alpha_fine_np = fine.weights[0].sum(dim=1).cpu().numpy().reshape(H, W)
depth_fine_np = fine.depth[0].cpu().numpy().reshape(H, W)
rgb_fine_np = fine.rgb[0].cpu().numpy().reshape(H, W, 3)
print("c rgb min {} max {}".format(rgb_coarse_np.min(), rgb_coarse_np.max()))
print(
"c alpha min {}, max {}".format(
alpha_coarse_np.min(), alpha_coarse_np.max()
)
)
alpha_coarse_cmap = util.cmap(alpha_coarse_np) / 255
depth_coarse_cmap = util.cmap(depth_coarse_np) / 255
vis_list = [
*source_views,
gt,
depth_coarse_cmap,
rgb_coarse_np,
alpha_coarse_cmap,
]
if self.app_enc_on:
app_images_0to1 = app_images * 0.5 + 0.5 # (NV, 3, H, W)
Wa = app_images.shape[-1]
app_gt = app_images_0to1[batch_idx].permute(1, 2, 0).cpu().numpy().reshape(H, Wa, 3)
vis_list.append(app_gt)
vis_coarse = np.hstack(vis_list)
vis = vis_coarse
if using_fine:
print("f rgb min {} max {}".format(rgb_fine_np.min(), rgb_fine_np.max()))
print(
"f alpha min {}, max {}".format(
alpha_fine_np.min(), alpha_fine_np.max()
)
)
depth_fine_cmap = util.cmap(depth_fine_np) / 255
alpha_fine_cmap = util.cmap(alpha_fine_np) / 255
vis_list = [
*source_views,
gt,
depth_fine_cmap,
rgb_fine_np,
alpha_fine_cmap,
]
if self.app_enc_on:
vis_list.append(app_gt)
vis_fine = np.hstack(vis_list)
vis = np.vstack((vis_coarse, vis_fine))
rgb_psnr = rgb_fine_np
else:
rgb_psnr = rgb_coarse_np
psnr = util.psnr(rgb_psnr, gt)
vals = {"psnr": psnr}
print("psnr", psnr)
# set the renderer network back to train mode
renderer.train()
return vis, vals
def start(self):
def fmt_loss_str(losses):
return "loss " + (" ".join(k + ":" + str(losses[k]) for k in losses))
step_id = self.start_iter_id
progress = tqdm.tqdm(bar_format="[{rate_fmt}] ")
for epoch in range(self.num_epochs):
self.writer.add_scalar(
"lr", self.optim.param_groups[0]["lr"], global_step=step_id
)
batch = 0
for _ in range(self.num_epoch_repeats):
losses = self.train_step(self.nerf_data, self.appearance_img, global_step=step_id)
loss_str = fmt_loss_str(losses)
if batch % self.print_interval == 0:
print(
"E",
epoch,
"B",
batch,
loss_str,
" lr",
self.optim.param_groups[0]["lr"],
)
if batch % self.eval_interval == 0:
self.net.eval()
with torch.no_grad():
test_losses = self.eval_step(self.nerf_data, self.appearance_img, global_step=step_id)
self.net.train()
test_loss_str = fmt_loss_str(test_losses)
self.writer.add_scalars("train", losses, global_step=step_id)
self.writer.add_scalars(
"test", test_losses, global_step=step_id
)
print("*** Eval:", "E", epoch, "B", batch, test_loss_str, " lr")
if batch % self.save_interval == 0 and (epoch > 0 or batch > 0):
print("saving")
if self.managed_weight_saving:
self.net.save_weights(self.args)
else:
torch.save(
self.net.state_dict(), self.default_net_state_path
)
torch.save(self.optim.state_dict(), self.optim_state_path)
if self.lr_scheduler is not None:
torch.save(
self.lr_scheduler.state_dict(), self.lrsched_state_path
)
torch.save({"iter": step_id + 1}, self.iter_state_path)
self.extra_save_state()
if self.vis_step_on and batch % self.vis_interval == 0:
print("generating visualization")
# Render out the scene
self.net.eval()
with torch.no_grad():
vis, vis_vals = self.vis_step(
self.nerf_data, global_step=step_id
)
if vis_vals is not None:
self.writer.add_scalars(
"vis", vis_vals, global_step=step_id
)
self.net.train()
if vis is not None:
import imageio
vis_u8 = (vis * 255).astype(np.uint8)
imageio.imwrite(
os.path.join(
self.visual_path,
"{:04}_{:04}_vis.png".format(epoch, batch),
),
vis_u8,
)
if (
batch == self.num_total_batches - 1
or batch % self.accu_grad == self.accu_grad - 1
):
# torch.nn.utils.clip_grad_norm_(net.parameters(), 0.5)
self.optim.step()
self.optim.zero_grad()
self.post_batch(epoch, batch)
step_id += 1
batch += 1
progress.update(1)
if self.lr_scheduler is not None:
self.lr_scheduler.step()
trainer = PixelNeRF_ATrainer()
trainer.start()
|
[
"torch.empty",
"numpy.random.randint",
"util.get_cuda",
"util.decompose_to_subpatches",
"torch.no_grad",
"util.gen_rays",
"data.get_split_dataset",
"random.randint",
"os.path.dirname",
"render.NeRFRenderer.from_conf",
"os.path.exists",
"torch.load",
"util.args.parse_args",
"model.loss.item",
"util.recompose_subpatch_render_dicts_rgb",
"util.get_random_patch",
"numpy.random.choice",
"data.AppearanceDataset.AppearanceDataset",
"tqdm.tqdm",
"model.loss.ReferenceColorLoss",
"torch.randint",
"util.ssh_normalization",
"util.psnr",
"numpy.hstack",
"model.loss.get_density_loss",
"model.make_model",
"model.loss.backward",
"util.cmap",
"numpy.vstack",
"torch.from_numpy",
"util.batched_index_select_nd",
"util.bbox_sample",
"torch.stack",
"model.loss.get_rgb_loss",
"torch.save",
"torch.nn.functional.interpolate",
"torchvision.transforms.functional_tensor.crop"
] |
[((3595, 3670), 'util.args.parse_args', 'util.args.parse_args', (['extra_args'], {'training': '(True)', 'default_ray_batch_size': '(128)'}), '(extra_args, training=True, default_ray_batch_size=128)\n', (3615, 3670), False, 'import util\n'), ((3680, 3709), 'util.get_cuda', 'util.get_cuda', (['args.gpu_id[0]'], {}), '(args.gpu_id[0])\n', (3693, 3709), False, 'import util\n'), ((3964, 4016), 'data.get_split_dataset', 'get_split_dataset', (['args.dataset_format', 'args.datadir'], {}), '(args.dataset_format, args.datadir)\n', (3981, 4016), False, 'from data import get_split_dataset\n'), ((4057, 4144), 'data.AppearanceDataset.AppearanceDataset', 'AppearanceDataset', (['args.appdir', '"""train"""'], {'image_size': 'app_size', 'img_ind': 'args.app_ind'}), "(args.appdir, 'train', image_size=app_size, img_ind=args.\n app_ind)\n", (4074, 4144), False, 'from data.AppearanceDataset import AppearanceDataset\n'), ((4245, 4419), 'model.make_model', 'make_model', (["conf['model']"], {'app_enc_on': '(not args.app_enc_off)', 'stop_encoder_grad': 'args.freeze_enc', 'stop_app_encoder_grad': 'args.freeze_app_enc', 'stop_f1_grad': 'args.freeze_f1'}), "(conf['model'], app_enc_on=not args.app_enc_off,\n stop_encoder_grad=args.freeze_enc, stop_app_encoder_grad=args.\n freeze_app_enc, stop_f1_grad=args.freeze_f1)\n", (4255, 4419), False, 'from model import make_model, loss\n'), ((4756, 4818), 'render.NeRFRenderer.from_conf', 'NeRFRenderer.from_conf', (["conf['renderer']"], {'lindisp': 'dset.lindisp'}), "(conf['renderer'], lindisp=dset.lindisp)\n", (4778, 4818), False, 'from render import NeRFRenderer\n'), ((5527, 5568), 'model.loss.get_rgb_loss', 'loss.get_rgb_loss', (["conf['loss.rgb']", '(True)'], {}), "(conf['loss.rgb'], True)\n", (5544, 5568), False, 'from model import make_model, loss\n'), ((6484, 6524), 'model.loss.get_density_loss', 'loss.get_density_loss', (['density_loss_conf'], {}), '(density_loss_conf)\n', (6505, 6524), False, 'from model import make_model, loss\n'), ((9288, 9339), 'util.batched_index_select_nd', 'util.batched_index_select_nd', (['all_images', 'image_ord'], {}), '(all_images, image_ord)\n', (9316, 9339), False, 'import util\n'), ((9403, 9453), 'util.batched_index_select_nd', 'util.batched_index_select_nd', (['all_poses', 'image_ord'], {}), '(all_poses, image_ord)\n', (9431, 9453), False, 'import util\n'), ((11856, 11879), 'torch.stack', 'torch.stack', (['all_rgb_gt'], {}), '(all_rgb_gt)\n', (11867, 11879), False, 'import torch\n'), ((11926, 11947), 'torch.stack', 'torch.stack', (['all_rays'], {}), '(all_rays)\n', (11937, 11947), False, 'import torch\n'), ((13354, 13377), 'torch.stack', 'torch.stack', (['all_rgb_gt'], {}), '(all_rgb_gt)\n', (13365, 13377), False, 'import torch\n'), ((13424, 13445), 'torch.stack', 'torch.stack', (['all_rays'], {}), '(all_rays)\n', (13435, 13445), False, 'import torch\n'), ((13561, 13610), 'util.batched_index_select_nd', 'util.batched_index_select_nd', (['all_rays', 'image_ord'], {}), '(all_rays, image_ord)\n', (13589, 13610), False, 'import util\n'), ((13861, 13909), 'util.get_random_patch', 'util.get_random_patch', (['self.appearance_img', 'P', 'P'], {}), '(self.appearance_img, P, P)\n', (13882, 13909), False, 'import util\n'), ((13931, 13988), 'torch.nn.functional.interpolate', 'F.interpolate', (['back_patch'], {'size': 'self.ssh_dim', 'mode': '"""area"""'}), "(back_patch, size=self.ssh_dim, mode='area')\n", (13944, 13988), True, 'import torch.nn.functional as F\n'), ((15970, 16060), 'util.recompose_subpatch_render_dicts_rgb', 'util.recompose_subpatch_render_dicts_rgb', (['subpatch_dicts', 'SB', 'P', 'self.subpatch_factor'], {}), '(subpatch_dicts, SB, P, self.\n subpatch_factor)\n', (16010, 16060), False, 'import util\n'), ((16082, 16120), 'util.ssh_normalization', 'util.ssh_normalization', (['coarse_app_rgb'], {}), '(coarse_app_rgb)\n', (16104, 16120), False, 'import util\n'), ((16146, 16207), 'torch.nn.functional.interpolate', 'F.interpolate', (['app_rgb_coarse'], {'size': 'self.ssh_dim', 'mode': '"""area"""'}), "(app_rgb_coarse, size=self.ssh_dim, mode='area')\n", (16159, 16207), True, 'import torch.nn.functional as F\n'), ((16361, 16397), 'util.ssh_normalization', 'util.ssh_normalization', (['fine_app_rgb'], {}), '(fine_app_rgb)\n', (16383, 16397), False, 'import util\n'), ((16421, 16480), 'torch.nn.functional.interpolate', 'F.interpolate', (['app_rgb_fine'], {'size': 'self.ssh_dim', 'mode': '"""area"""'}), "(app_rgb_fine, size=self.ssh_dim, mode='area')\n", (16434, 16480), True, 'import torch.nn.functional as F\n'), ((17501, 17512), 'model.loss.item', 'loss.item', ([], {}), '()\n', (17510, 17512), False, 'from model import make_model, loss\n'), ((18919, 18981), 'util.decompose_to_subpatches', 'util.decompose_to_subpatches', (['patch_rays', 'self.subpatch_factor'], {}), '(patch_rays, self.subpatch_factor)\n', (18947, 18981), False, 'import util\n'), ((19604, 19615), 'model.loss.item', 'loss.item', ([], {}), '()\n', (19613, 19615), False, 'from model import make_model, loss\n'), ((20718, 20781), 'util.gen_rays', 'util.gen_rays', (['poses', 'W', 'H', 'focal', 'self.z_near', 'self.z_far'], {'c': 'c'}), '(poses, W, H, focal, self.z_near, self.z_far, c=c)\n', (20731, 20781), False, 'import util\n'), ((21051, 21089), 'numpy.random.randint', 'np.random.randint', (['(0)', '(NV - curr_nviews)'], {}), '(0, NV - curr_nviews)\n', (21068, 21089), True, 'import numpy as np\n'), ((21200, 21227), 'torch.from_numpy', 'torch.from_numpy', (['views_src'], {}), '(views_src)\n', (21216, 21227), False, 'import torch\n'), ((23574, 23593), 'numpy.hstack', 'np.hstack', (['vis_list'], {}), '(vis_list)\n', (23583, 23593), True, 'import numpy as np\n'), ((24468, 24491), 'util.psnr', 'util.psnr', (['rgb_psnr', 'gt'], {}), '(rgb_psnr, gt)\n', (24477, 24491), False, 'import util\n'), ((24851, 24888), 'tqdm.tqdm', 'tqdm.tqdm', ([], {'bar_format': '"""[{rate_fmt}] """'}), "(bar_format='[{rate_fmt}] ')\n", (24860, 24888), False, 'import tqdm\n'), ((229, 254), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (244, 254), False, 'import os\n'), ((318, 343), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (333, 343), False, 'import os\n'), ((414, 439), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (429, 439), False, 'import os\n'), ((5729, 5769), 'model.loss.get_rgb_loss', 'loss.get_rgb_loss', (['fine_loss_conf', '(False)'], {}), '(fine_loss_conf, False)\n', (5746, 5769), False, 'from model import make_model, loss\n'), ((6657, 6697), 'os.path.exists', 'os.path.exists', (['self.renderer_state_path'], {}), '(self.renderer_state_path)\n', (6671, 6697), False, 'import os\n'), ((10991, 11054), 'util.gen_rays', 'util.gen_rays', (['poses', 'W', 'H', 'focal', 'self.z_near', 'self.z_far'], {'c': 'c'}), '(poses, W, H, focal, self.z_near, self.z_far, c=c)\n', (11004, 11054), False, 'import util\n'), ((13110, 13127), 'random.randint', 'randint', (['(0)', '(H - P)'], {}), '(0, H - P)\n', (13117, 13127), False, 'from random import randint\n'), ((13144, 13161), 'random.randint', 'randint', (['(0)', '(W - P)'], {}), '(0, W - P)\n', (13151, 13161), False, 'from random import randint\n'), ((13184, 13212), 'torchvision.transforms.functional_tensor.crop', 'crop', (['rgb_gt_all', 'i', 'j', 'P', 'P'], {}), '(rgb_gt_all, i, j, P, P)\n', (13188, 13212), False, 'from torchvision.transforms.functional_tensor import crop\n'), ((13232, 13258), 'torchvision.transforms.functional_tensor.crop', 'crop', (['cam_rays', 'i', 'j', 'P', 'P'], {}), '(cam_rays, i, j, P, P)\n', (13236, 13258), False, 'from torchvision.transforms.functional_tensor import crop\n'), ((17460, 17475), 'model.loss.backward', 'loss.backward', ([], {}), '()\n', (17473, 17475), False, 'from model import make_model, loss\n'), ((19563, 19578), 'model.loss.backward', 'loss.backward', ([], {}), '()\n', (19576, 19578), False, 'from model import make_model, loss\n'), ((20161, 20206), 'numpy.random.randint', 'np.random.randint', (['(0)', "data['images'].shape[0]"], {}), "(0, data['images'].shape[0])\n", (20178, 20206), True, 'import numpy as np\n'), ((20981, 21029), 'numpy.random.choice', 'np.random.choice', (['NV', 'curr_nviews'], {'replace': '(False)'}), '(NV, curr_nviews, replace=False)\n', (20997, 21029), True, 'import numpy as np\n'), ((21568, 21583), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (21581, 21583), False, 'import torch\n'), ((23025, 23051), 'util.cmap', 'util.cmap', (['alpha_coarse_np'], {}), '(alpha_coarse_np)\n', (23034, 23051), False, 'import util\n'), ((23086, 23112), 'util.cmap', 'util.cmap', (['depth_coarse_np'], {}), '(depth_coarse_np)\n', (23095, 23112), False, 'import util\n'), ((24294, 24313), 'numpy.hstack', 'np.hstack', (['vis_list'], {}), '(vis_list)\n', (24303, 24313), True, 'import numpy as np\n'), ((24332, 24365), 'numpy.vstack', 'np.vstack', (['(vis_coarse, vis_fine)'], {}), '((vis_coarse, vis_fine))\n', (24341, 24365), True, 'import numpy as np\n'), ((6553, 6598), 'model.loss.ReferenceColorLoss', 'loss.ReferenceColorLoss', (['conf', 'args.refencdir'], {}), '(conf, args.refencdir)\n', (6576, 6598), False, 'from model import make_model, loss\n'), ((11334, 11379), 'util.bbox_sample', 'util.bbox_sample', (['bboxes', 'args.ray_batch_size'], {}), '(bboxes, args.ray_batch_size)\n', (11350, 11379), False, 'import util\n'), ((11504, 11556), 'torch.randint', 'torch.randint', (['(0)', '(NV * H * W)', '(args.ray_batch_size,)'], {}), '(0, NV * H * W, (args.ray_batch_size,))\n', (11517, 11556), False, 'import torch\n'), ((13494, 13523), 'torch.randint', 'torch.randint', (['(0)', 'NV', '(SB, 1)'], {}), '(0, NV, (SB, 1))\n', (13507, 13523), False, 'import torch\n'), ((13632, 13683), 'util.batched_index_select_nd', 'util.batched_index_select_nd', (['all_rgb_gt', 'image_ord'], {}), '(all_rgb_gt, image_ord)\n', (13660, 13683), False, 'import util\n'), ((23920, 23944), 'util.cmap', 'util.cmap', (['depth_fine_np'], {}), '(depth_fine_np)\n', (23929, 23944), False, 'import util\n'), ((23981, 24005), 'util.cmap', 'util.cmap', (['alpha_fine_np'], {}), '(alpha_fine_np)\n', (23990, 24005), False, 'import util\n'), ((6761, 6818), 'torch.load', 'torch.load', (['self.renderer_state_path'], {'map_location': 'device'}), '(self.renderer_state_path, map_location=device)\n', (6771, 6818), False, 'import torch\n'), ((8826, 8855), 'torch.randint', 'torch.randint', (['(0)', 'NV', '(SB, 1)'], {}), '(0, NV, (SB, 1))\n', (8839, 8855), False, 'import torch\n'), ((8912, 8960), 'torch.empty', 'torch.empty', (['(SB, curr_nviews)'], {'dtype': 'torch.long'}), '((SB, curr_nviews), dtype=torch.long)\n', (8923, 8960), False, 'import torch\n'), ((9191, 9239), 'numpy.random.choice', 'np.random.choice', (['NV', 'curr_nviews'], {'replace': '(False)'}), '(NV, curr_nviews, replace=False)\n', (9207, 9239), True, 'import numpy as np\n'), ((12774, 12837), 'util.gen_rays', 'util.gen_rays', (['poses', 'W', 'H', 'focal', 'self.z_near', 'self.z_far'], {'c': 'c'}), '(poses, W, H, focal, self.z_near, self.z_far, c=c)\n', (12787, 12837), False, 'import util\n'), ((26959, 27014), 'torch.save', 'torch.save', (["{'iter': step_id + 1}", 'self.iter_state_path'], {}), "({'iter': step_id + 1}, self.iter_state_path)\n", (26969, 27014), False, 'import torch\n'), ((25741, 25756), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (25754, 25756), False, 'import torch\n'), ((27311, 27326), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (27324, 27326), False, 'import torch\n')]
|
"""The example:
- creates waveform file from two i_data and q_data vectors
- sends the file to the SGT100A instrument
- activates the waveform
You have the option of auto-scaling the samples to the full range with the parameter 'auto_scale'
"""
import numpy as np
from RsSgt import *
RsSgt.assert_minimum_version('4.70.1')
sgt = RsSgt('TCPIP::10.214.1.57::HISLIP')
print(sgt.utilities.idn_string)
sgt.utilities.reset()
pc_wv_file = r'c:\temp\arbFileExample.wv'
instr_wv_file = '/var/user/InstrDemoFile.wv'
# Creating the I/Q vectors as lists: i_data / q_data
# Samples clock
clock_freq = 600e6
# wave clock
wave_freq = 120e6
# Scale factor - change it to less or more that 1 if you want to see the autoscaling capability of the create_waveform_file...() methods
scale_factor = 0.8
time_vector = np.arange(0, 50 / wave_freq, 1 / clock_freq)
# I-component an Q-component data
i_data = np.cos(2 * np.pi * wave_freq * time_vector) * scale_factor
q_data = np.sin(2 * np.pi * wave_freq * time_vector) * scale_factor
# Take those samples and create a wv file, send it to the instrument with the name instr_wv_file (not auto-scaled)
result = sgt.arb_files.create_waveform_file_from_samples(i_data, q_data, pc_wv_file, clock_freq=100E6, auto_scale=False, comment='Created from I/Q vectors')
sgt.arb_files.send_waveform_file_to_instrument(pc_wv_file, instr_wv_file)
# Selecting the waveform and load it in the ARB
sgt.source.bb.arbitrary.waveform.set_select(instr_wv_file)
sgt.source.frequency.fixed.set_value(1.1E9)
sgt.source.power.level.immediate.set_amplitude(-11.1)
# Turning on the ARB baseband
sgt.source.bb.arbitrary.set_state(True)
# Turning on the RF out state
sgt.output.state.set_value(True)
sgt.close()
|
[
"numpy.sin",
"numpy.arange",
"numpy.cos"
] |
[((803, 847), 'numpy.arange', 'np.arange', (['(0)', '(50 / wave_freq)', '(1 / clock_freq)'], {}), '(0, 50 / wave_freq, 1 / clock_freq)\n', (812, 847), True, 'import numpy as np\n'), ((891, 934), 'numpy.cos', 'np.cos', (['(2 * np.pi * wave_freq * time_vector)'], {}), '(2 * np.pi * wave_freq * time_vector)\n', (897, 934), True, 'import numpy as np\n'), ((959, 1002), 'numpy.sin', 'np.sin', (['(2 * np.pi * wave_freq * time_vector)'], {}), '(2 * np.pi * wave_freq * time_vector)\n', (965, 1002), True, 'import numpy as np\n')]
|
# Copyright (c) 2020, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import random
import numpy as np
from ai_economist.foundation.base.registrar import Registry
class BaseAgent:
"""Base class for Agent classes.
Instances of Agent classes are created for each agent in the environment. Agent
instances are stateful, capturing location, inventory, endogenous variables,
and any additional state fields created by environment components during
construction (see BaseComponent.get_additional_state_fields in base_component.py).
They also provide a simple API for getting/setting actions for each of their
registered action subspaces (which depend on the components used to build
the environment).
Args:
idx (int or str): Index that uniquely identifies the agent object amongst the
other agent objects registered in its environment.
multi_action_mode (bool): Whether to allow the agent to take one action for
each of its registered action subspaces each timestep (if True),
or to limit the agent to take only one action each timestep (if False).
"""
name = ""
def __init__(self, idx=None, multi_action_mode=None):
assert self.name
if idx is None:
idx = 0
if multi_action_mode is None:
multi_action_mode = False
if isinstance(idx, str):
self._idx = idx
else:
self._idx = int(idx)
self.multi_action_mode = bool(multi_action_mode)
self.single_action_map = (
{}
) # Used to convert single-action-mode actions to the general format
self.action = dict()
self.action_dim = dict()
self._action_names = []
self._multi_action_dict = {}
self._unique_actions = 0
self._total_actions = 0
self.state = dict(loc=[0, 0], inventory={}, escrow={}, endogenous={})
self._registered_inventory = False
self._registered_endogenous = False
self._registered_components = False
self._noop_action_dict = dict()
# Special flag to allow logic for multi-action-mode agents
# that are not given any actions.
self._passive_multi_action_agent = False
# If this gets set to true, we can make masks faster
self._one_component_single_action = False
self._premask = None
@property
def idx(self):
"""Index used to identify this agent. Must be unique within the environment."""
return self._idx
def register_inventory(self, resources):
"""Used during environment construction to populate inventory/escrow fields."""
assert not self._registered_inventory
for entity_name in resources:
self.inventory[entity_name] = 0
self.escrow[entity_name] = 0
self._registered_inventory = True
def register_endogenous(self, endogenous):
"""Used during environment construction to populate endogenous state fields."""
assert not self._registered_endogenous
for entity_name in endogenous:
self.endogenous[entity_name] = 0
self._registered_endogenous = True
def _incorporate_component(self, action_name, n):
extra_n = (
1 if self.multi_action_mode else 0
) # Each sub-action has a NO-OP in multi action mode)
self.action[action_name] = 0
self.action_dim[action_name] = n + extra_n
self._action_names.append(action_name)
self._multi_action_dict[action_name] = False
self._unique_actions += 1
if self.multi_action_mode:
self._total_actions += n + extra_n
else:
for action_n in range(1, n + 1):
self._total_actions += 1
self.single_action_map[int(self._total_actions)] = [
action_name,
action_n,
]
def register_components(self, components):
"""Used during environment construction to set up state/action spaces."""
assert not self._registered_components
for component in components:
n = component.get_n_actions(self.name)
if n is None:
continue
# Most components will have a single action-per-agent, so n is an int
if isinstance(n, int):
if n == 0:
continue
self._incorporate_component(component.name, n)
# They can also internally handle multiple actions-per-agent,
# so n is an tuple or list
elif isinstance(n, (tuple, list)):
for action_sub_name, n_ in n:
if n_ == 0:
continue
if "." in action_sub_name:
raise NameError(
"Sub-action {} of component {} "
"is illegally named.".format(
action_sub_name, component.name
)
)
self._incorporate_component(
"{}.{}".format(component.name, action_sub_name), n_
)
# If that's not what we got something is funky.
else:
raise TypeError(
"Received unexpected type ({}) from {}.get_n_actions('{}')".format(
type(n), component.name, self.name
)
)
for k, v in component.get_additional_state_fields(self.name).items():
self.state[k] = v
# Currently no actions are available to this agent. Give it a placeholder.
if len(self.action) == 0 and self.multi_action_mode:
self._incorporate_component("PassiveAgentPlaceholder", 0)
self._passive_multi_action_agent = True
elif len(self.action) == 1 and not self.multi_action_mode:
self._one_component_single_action = True
self._premask = np.ones(1 + self._total_actions, dtype=np.float32)
self._registered_components = True
self._noop_action_dict = {k: v * 0 for k, v in self.action.items()}
verbose = False
if verbose:
print(self.name, self.idx, "constructed action map:")
for k, v in self.single_action_map.items():
print("single action map:", k, v)
for k, v in self.action.items():
print("action:", k, v)
for k, v in self.action_dim.items():
print("action_dim:", k, v)
@property
def action_spaces(self):
"""
if self.multi_action_mode == True:
Returns an integer array with length equal to the number of action
subspaces that the agent registered. The i'th element of the array
indicates the number of actions associated with the i'th action subspace.
In multi_action_mode, each subspace includes a NO-OP.
Note: self._action_names describes which action subspace each element of
the array refers to.
Example:
>> self.multi_action_mode
True
>> self.action_spaces
[2, 5]
>> self._action_names
["Build", "Gather"]
# [1 Build action + Build NO-OP, 4 Gather actions + Gather NO-OP]
if self.multi_action_mode == False:
Returns a single integer equal to the total number of actions that the
agent can take.
Example:
>> self.multi_action_mode
False
>> self.action_spaces
6
>> self._action_names
["Build", "Gather"]
# 1 NO-OP + 1 Build action + 4 Gather actions.
"""
if self.multi_action_mode:
action_dims = []
for m in self._action_names:
action_dims.append(np.array(self.action_dim[m]).reshape(-1))
return np.concatenate(action_dims).astype(np.int32)
n_actions = 1 # (NO-OP)
for m in self._action_names:
n_actions += self.action_dim[m]
return n_actions
@property
def loc(self):
"""2D list of [row, col] representing agent's location in the environment."""
return self.state["loc"]
@property
def endogenous(self):
"""Dictionary representing endogenous quantities (i.e. "Labor").
Example:
>> self.endogenous
{"Labor": 30.25}
"""
return self.state["endogenous"]
@property
def inventory(self):
"""Dictionary representing quantities of resources in agent's inventory.
Example:
>> self.inventory
{"Wood": 3, "Stone": 20, "Coin": 1002.83}
"""
return self.state["inventory"]
@property
def escrow(self):
"""Dictionary representing quantities of resources in agent's escrow.
https://en.wikipedia.org/wiki/Escrow
Escrow is used to manage any portion of the agent's inventory that is
reserved for a particular purpose. Typically, something enters escrow as part
of a contractual arrangement to disburse that something when another
condition is met. An example is found in the ContinuousDoubleAuction
Component class (see ../components/continuous_double_auction.py). When an
agent creates an order to sell a unit of Wood, for example, the component
moves one unit of Wood from the agent's inventory to its escrow. If another
agent buys the Wood, it is moved from escrow to the other agent's inventory. By
placing the Wood in escrow, it prevents the first agent from using it for
something else (i.e. building a house).
Notes:
The inventory and escrow share the same keys. An agent's endowment refers
to the total quantity it has in its inventory and escrow.
Escrow is provided to simplify inventory management but its intended
semantics are not enforced directly. It is up to Component classes to
enforce these semantics.
Example:
>> self.inventory
{"Wood": 0, "Stone": 1, "Coin": 3}
"""
return self.state["escrow"]
def inventory_to_escrow(self, resource, amount):
"""Move some amount of a resource from agent inventory to agent escrow.
Amount transferred is capped to the amount of resource in agent inventory.
Args:
resource (str): The name of the resource to move (i.e. "Wood", "Coin").
amount (float): The amount to be moved from inventory to escrow. Must be
positive.
Returns:
Amount of resource actually transferred. Will be less than amount argument
if amount argument exceeded the amount of resource in the inventory.
Calculated as:
transferred = np.minimum(self.state["inventory"][resource], amount)
"""
assert amount >= 0
transferred = float(np.minimum(self.state["inventory"][resource], amount))
self.state["inventory"][resource] -= transferred
self.state["escrow"][resource] += transferred
return float(transferred)
def escrow_to_inventory(self, resource, amount):
"""Move some amount of a resource from agent escrow to agent inventory.
Amount transferred is capped to the amount of resource in agent escrow.
Args:
resource (str): The name of the resource to move (i.e. "Wood", "Coin").
amount (float): The amount to be moved from escrow to inventory. Must be
positive.
Returns:
Amount of resource actually transferred. Will be less than amount argument
if amount argument exceeded the amount of resource in escrow.
Calculated as:
transferred = np.minimum(self.state["escrow"][resource], amount)
"""
assert amount >= 0
transferred = float(np.minimum(self.state["escrow"][resource], amount))
self.state["escrow"][resource] -= transferred
self.state["inventory"][resource] += transferred
return float(transferred)
def total_endowment(self, resource):
"""Get the combined inventory+escrow endowment of resource.
Args:
resource (str): Name of the resource
Returns:
The amount of resource in the agents inventory and escrow.
"""
return self.inventory[resource] + self.escrow[resource]
def reset_actions(self, component=None):
"""Reset all actions to the NO-OP action (the 0'th action index).
If component is specified, only reset action(s) for that component.
"""
if not component:
self.action.update(self._noop_action_dict)
else:
for k, v in self.action.items():
if "." in component:
if k.lower() == component.lower():
self.action[k] = v * 0
else:
base_component = k.split(".")[0]
if base_component.lower() == component.lower():
self.action[k] = v * 0
def has_component(self, component_name):
"""Returns True if the agent has component_name as a registered subaction."""
return bool(component_name in self.action)
def get_random_action(self):
"""
Select a component at random and randomly choose one of its actions (other
than NO-OP).
"""
random_component = random.choice(self._action_names)
component_action = random.choice(
list(range(1, self.action_dim[random_component]))
)
return {random_component: component_action}
def get_component_action(self, component_name, sub_action_name=None):
"""
Return the action(s) taken for component_name component, or None if the
agent does not use that component.
"""
if sub_action_name is not None:
return self.action.get(component_name + "." + sub_action_name, None)
matching_names = [
m for m in self._action_names if m.split(".")[0] == component_name
]
if len(matching_names) == 0:
return None
if len(matching_names) == 1:
return self.action.get(matching_names[0], None)
return [self.action.get(m, None) for m in matching_names]
def set_component_action(self, component_name, action):
"""Set the action(s) taken for component_name component."""
if component_name not in self.action:
raise KeyError(
"Agent {} of type {} does not have {} registered as a subaction".format(
self.idx, self.name, component_name
)
)
if self._multi_action_dict[component_name]:
self.action[component_name] = np.array(action, dtype=np.int32)
else:
self.action[component_name] = int(action)
def populate_random_actions(self):
"""Fill the action buffer with random actions. This is for testing."""
for component, d in self.action_dim.items():
if isinstance(d, int):
self.set_component_action(component, np.random.randint(0, d))
else:
d_array = np.array(d)
self.set_component_action(
component, np.floor(np.random.rand(*d_array.shape) * d_array)
)
def parse_actions(self, actions):
"""Parse the actions array to fill each component's action buffers."""
if self.multi_action_mode:
assert len(actions) == self._unique_actions
if len(actions) == 1:
self.set_component_action(self._action_names[0], actions[0])
else:
for action_name, action in zip(self._action_names, actions):
self.set_component_action(action_name, int(action))
# Single action mode
else:
# Action was supplied as an index of a specific subaction.
# No need to do any lookup.
if isinstance(actions, dict):
if len(actions) == 0:
return
assert len(actions) == 1
action_name = list(actions.keys())[0]
action = list(actions.values())[0]
if action == 0:
return
self.set_component_action(action_name, action)
# Action was supplied as an index into the full set of combined actions
else:
action = int(actions)
# Universal NO-OP
if action == 0:
return
action_name, action = self.single_action_map.get(action)
self.set_component_action(action_name, action)
def flatten_masks(self, mask_dict):
"""Convert a dictionary of component action masks into a single mask vector."""
if self._one_component_single_action:
self._premask[1:] = mask_dict[self._action_names[0]]
return self._premask
no_op_mask = [1]
if self._passive_multi_action_agent:
return np.array(no_op_mask).astype(np.float32)
list_of_masks = []
if not self.multi_action_mode:
list_of_masks.append(no_op_mask)
for m in self._action_names:
if m not in mask_dict:
raise KeyError("No mask provided for {} (agent {})".format(m, self.idx))
if self.multi_action_mode:
list_of_masks.append(no_op_mask)
list_of_masks.append(mask_dict[m])
return np.concatenate(list_of_masks).astype(np.float32)
agent_registry = Registry(BaseAgent)
"""The registry for Agent classes.
This creates a registry object for Agent classes. This registry requires that all
added classes are subclasses of BaseAgent. To make an Agent class available through
the registry, decorate the class definition with @agent_registry.add.
Example:
from ai_economist.foundation.base.base_agent import BaseAgent, agent_registry
@agent_registry.add
class ExampleAgent(BaseAgent):
name = "Example"
pass
assert agent_registry.has("Example")
AgentClass = agent_registry.get("Example")
agent = AgentClass(...)
assert isinstance(agent, ExampleAgent)
Notes:
The foundation package exposes the agent registry as: foundation.agents
An Agent class that is defined and registered following the above example will
only be visible in foundation.agents if defined/registered in a file that is
imported in ../agents/__init__.py.
"""
|
[
"numpy.minimum",
"ai_economist.foundation.base.registrar.Registry",
"numpy.ones",
"random.choice",
"numpy.random.randint",
"numpy.array",
"numpy.random.rand",
"numpy.concatenate"
] |
[((18196, 18215), 'ai_economist.foundation.base.registrar.Registry', 'Registry', (['BaseAgent'], {}), '(BaseAgent)\n', (18204, 18215), False, 'from ai_economist.foundation.base.registrar import Registry\n'), ((13972, 14005), 'random.choice', 'random.choice', (['self._action_names'], {}), '(self._action_names)\n', (13985, 14005), False, 'import random\n'), ((11394, 11447), 'numpy.minimum', 'np.minimum', (["self.state['inventory'][resource]", 'amount'], {}), "(self.state['inventory'][resource], amount)\n", (11404, 11447), True, 'import numpy as np\n'), ((12385, 12435), 'numpy.minimum', 'np.minimum', (["self.state['escrow'][resource]", 'amount'], {}), "(self.state['escrow'][resource], amount)\n", (12395, 12435), True, 'import numpy as np\n'), ((15329, 15361), 'numpy.array', 'np.array', (['action'], {'dtype': 'np.int32'}), '(action, dtype=np.int32)\n', (15337, 15361), True, 'import numpy as np\n'), ((6232, 6282), 'numpy.ones', 'np.ones', (['(1 + self._total_actions)'], {'dtype': 'np.float32'}), '(1 + self._total_actions, dtype=np.float32)\n', (6239, 6282), True, 'import numpy as np\n'), ((15759, 15770), 'numpy.array', 'np.array', (['d'], {}), '(d)\n', (15767, 15770), True, 'import numpy as np\n'), ((18128, 18157), 'numpy.concatenate', 'np.concatenate', (['list_of_masks'], {}), '(list_of_masks)\n', (18142, 18157), True, 'import numpy as np\n'), ((8274, 8301), 'numpy.concatenate', 'np.concatenate', (['action_dims'], {}), '(action_dims)\n', (8288, 8301), True, 'import numpy as np\n'), ((15690, 15713), 'numpy.random.randint', 'np.random.randint', (['(0)', 'd'], {}), '(0, d)\n', (15707, 15713), True, 'import numpy as np\n'), ((17665, 17685), 'numpy.array', 'np.array', (['no_op_mask'], {}), '(no_op_mask)\n', (17673, 17685), True, 'import numpy as np\n'), ((8213, 8241), 'numpy.array', 'np.array', (['self.action_dim[m]'], {}), '(self.action_dim[m])\n', (8221, 8241), True, 'import numpy as np\n'), ((15854, 15884), 'numpy.random.rand', 'np.random.rand', (['*d_array.shape'], {}), '(*d_array.shape)\n', (15868, 15884), True, 'import numpy as np\n')]
|
from modeldata import from_downloaded as modeldata_from_downloaded
import log
from utilities import get_ncfiles_in_dir,get_variable_name,get_variable_name_reverse
from utilities import convert_time_to_datetime,get_n_months,get_l_time_range,add_month_to_timestamp
from netCDF4 import Dataset
from datetime import datetime,timedelta
import numpy as np
import os
def variables_at_depth(input_dir,output_dir,model_name,
i_times=[0],i_depths=[0],
variables=['u','v','mld','salinity','temp','sea_ice_cover'],
filename_format='%Y%m%d',log_file='edt/extract_depth.log'):
filenames = get_ncfiles_in_dir(input_dir)
for filename in filenames:
netcdf = Dataset(input_dir+filename)
modeldata = modeldata_from_downloaded(netcdf,variables,model_name,i_times=i_times,i_depths=i_depths)
output_path = modeldata.get_output_path(output_dir,filename_format=filename_format)
if os.path.exists(output_path):
log.info(log_file,f'File already exists, skipping: {output_path}')
netcdf.close()
continue
log.info(log_file,f'Extracting depth layers {str(i_depths)} and saving to file: {output_path}')
_ = modeldata.write_to_netcdf(output_dir,filename_format=filename_format)
netcdf.close()
def monthly_files(input_path,output_dir,model_name,log_file='edt/extract_monthly.log'):
netcdf = Dataset(input_path)
# keep original variables: find general name from model specific name
model_variables = list(set(netcdf.variables.keys())-set(netcdf.dimensions.keys()))
variables = []
for model_variable in model_variables:
variables.append(get_variable_name_reverse(model_name,model_variable))
time_var = get_variable_name(model_name,'time')
time = convert_time_to_datetime(netcdf[time_var][:],netcdf[time_var].units)
n_months = get_n_months(time[0],time[-1])
date0 = datetime(time[0].year,time[0].month,1)
for i in range(n_months):
start_date = add_month_to_timestamp(date0,i)
end_date = add_month_to_timestamp(date0,i+1)-timedelta(days=1)
l_times = get_l_time_range(time,start_date,end_date)
i_times = np.where(l_times)[0]
modeldata = modeldata_from_downloaded(netcdf,variables,model_name,i_times=i_times)
output_path = modeldata.get_output_path(output_dir,filename_format='%Y%m')
if os.path.exists(output_path):
log.info(log_file,f'File already exists, skipping: {output_path}')
continue
log.info(log_file,f'Writing monthly data to file: {output_path}')
_ = modeldata.write_to_netcdf(output_dir,filename_format='%Y%m')
netcdf.close()
|
[
"netCDF4.Dataset",
"utilities.get_variable_name",
"utilities.get_variable_name_reverse",
"utilities.add_month_to_timestamp",
"utilities.get_ncfiles_in_dir",
"utilities.convert_time_to_datetime",
"utilities.get_l_time_range",
"os.path.exists",
"datetime.datetime",
"modeldata.from_downloaded",
"log.info",
"numpy.where",
"utilities.get_n_months",
"datetime.timedelta"
] |
[((653, 682), 'utilities.get_ncfiles_in_dir', 'get_ncfiles_in_dir', (['input_dir'], {}), '(input_dir)\n', (671, 682), False, 'from utilities import get_ncfiles_in_dir, get_variable_name, get_variable_name_reverse\n'), ((1438, 1457), 'netCDF4.Dataset', 'Dataset', (['input_path'], {}), '(input_path)\n', (1445, 1457), False, 'from netCDF4 import Dataset\n'), ((1775, 1812), 'utilities.get_variable_name', 'get_variable_name', (['model_name', '"""time"""'], {}), "(model_name, 'time')\n", (1792, 1812), False, 'from utilities import get_ncfiles_in_dir, get_variable_name, get_variable_name_reverse\n'), ((1823, 1892), 'utilities.convert_time_to_datetime', 'convert_time_to_datetime', (['netcdf[time_var][:]', 'netcdf[time_var].units'], {}), '(netcdf[time_var][:], netcdf[time_var].units)\n', (1847, 1892), False, 'from utilities import convert_time_to_datetime, get_n_months, get_l_time_range, add_month_to_timestamp\n'), ((1907, 1938), 'utilities.get_n_months', 'get_n_months', (['time[0]', 'time[-1]'], {}), '(time[0], time[-1])\n', (1919, 1938), False, 'from utilities import convert_time_to_datetime, get_n_months, get_l_time_range, add_month_to_timestamp\n'), ((1950, 1990), 'datetime.datetime', 'datetime', (['time[0].year', 'time[0].month', '(1)'], {}), '(time[0].year, time[0].month, 1)\n', (1958, 1990), False, 'from datetime import datetime, timedelta\n'), ((731, 760), 'netCDF4.Dataset', 'Dataset', (['(input_dir + filename)'], {}), '(input_dir + filename)\n', (738, 760), False, 'from netCDF4 import Dataset\n'), ((779, 875), 'modeldata.from_downloaded', 'modeldata_from_downloaded', (['netcdf', 'variables', 'model_name'], {'i_times': 'i_times', 'i_depths': 'i_depths'}), '(netcdf, variables, model_name, i_times=i_times,\n i_depths=i_depths)\n', (804, 875), True, 'from modeldata import from_downloaded as modeldata_from_downloaded\n'), ((971, 998), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (985, 998), False, 'import os\n'), ((2040, 2072), 'utilities.add_month_to_timestamp', 'add_month_to_timestamp', (['date0', 'i'], {}), '(date0, i)\n', (2062, 2072), False, 'from utilities import convert_time_to_datetime, get_n_months, get_l_time_range, add_month_to_timestamp\n'), ((2161, 2205), 'utilities.get_l_time_range', 'get_l_time_range', (['time', 'start_date', 'end_date'], {}), '(time, start_date, end_date)\n', (2177, 2205), False, 'from utilities import convert_time_to_datetime, get_n_months, get_l_time_range, add_month_to_timestamp\n'), ((2263, 2336), 'modeldata.from_downloaded', 'modeldata_from_downloaded', (['netcdf', 'variables', 'model_name'], {'i_times': 'i_times'}), '(netcdf, variables, model_name, i_times=i_times)\n', (2288, 2336), True, 'from modeldata import from_downloaded as modeldata_from_downloaded\n'), ((2428, 2455), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (2442, 2455), False, 'import os\n'), ((2565, 2631), 'log.info', 'log.info', (['log_file', 'f"""Writing monthly data to file: {output_path}"""'], {}), "(log_file, f'Writing monthly data to file: {output_path}')\n", (2573, 2631), False, 'import log\n'), ((1012, 1079), 'log.info', 'log.info', (['log_file', 'f"""File already exists, skipping: {output_path}"""'], {}), "(log_file, f'File already exists, skipping: {output_path}')\n", (1020, 1079), False, 'import log\n'), ((1706, 1759), 'utilities.get_variable_name_reverse', 'get_variable_name_reverse', (['model_name', 'model_variable'], {}), '(model_name, model_variable)\n', (1731, 1759), False, 'from utilities import get_ncfiles_in_dir, get_variable_name, get_variable_name_reverse\n'), ((2091, 2127), 'utilities.add_month_to_timestamp', 'add_month_to_timestamp', (['date0', '(i + 1)'], {}), '(date0, i + 1)\n', (2113, 2127), False, 'from utilities import convert_time_to_datetime, get_n_months, get_l_time_range, add_month_to_timestamp\n'), ((2125, 2142), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (2134, 2142), False, 'from datetime import datetime, timedelta\n'), ((2222, 2239), 'numpy.where', 'np.where', (['l_times'], {}), '(l_times)\n', (2230, 2239), True, 'import numpy as np\n'), ((2469, 2536), 'log.info', 'log.info', (['log_file', 'f"""File already exists, skipping: {output_path}"""'], {}), "(log_file, f'File already exists, skipping: {output_path}')\n", (2477, 2536), False, 'import log\n')]
|
import math
from pandas import DataFrame
import numpy as np
from __init__fuzzy import *
def experiment(sliding_number=3, hidden_node=15):
dat_nn = np.asarray(scaler.fit_transform(dat))
X_train_size = int(len(dat_nn)*0.7)
sliding = np.array(list(SlidingWindow(dat_nn, sliding_number)))
X_train_nn = sliding[:X_train_size]
y_train_nn = dat_nn[sliding_number:X_train_size+sliding_number].reshape(-1,1)
X_test_nn = sliding[X_train_size:]
y_test_nn = dat_nn[X_train_size+sliding_number-1:].reshape(-1,1)
y_actual_test = dat[X_train_size+sliding_number-1:].tolist()
estimator = KerasRegressor(learning_rate=0.01, hidden_nodes=[hidden_node], steps=5000, optimize='Adam')
estimator.fit(X_train_nn, y_train_nn)
y_pred = scaler.inverse_transform(estimator.predict(X_test_nn))
score_mape = mean_absolute_error(y_pred, y_actual_test)
score_rmse = math.sqrt(mean_squared_error(y_pred,y_actual_test))
np.savez('model_saved/BPNN_%s_%s' % (sliding_number, score_mape), y_pred=y_pred, y_true=y_actual_test)
return sliding_number, score_rmse, score_mape
result = [[experiment(sliding_number=i) for i in np.arange(2,6)] for j in np.arange(10)]
#np.savez("BPNN_epochs",result=result)
results = DataFrame(np.array(result).reshape(-1,3), columns=["sliding_number","rmse","mae"])
results.to_csv('experiment_logs/bpnn_experiment.csv')
|
[
"numpy.array",
"numpy.savez",
"numpy.arange"
] |
[((948, 1055), 'numpy.savez', 'np.savez', (["('model_saved/BPNN_%s_%s' % (sliding_number, score_mape))"], {'y_pred': 'y_pred', 'y_true': 'y_actual_test'}), "('model_saved/BPNN_%s_%s' % (sliding_number, score_mape), y_pred=\n y_pred, y_true=y_actual_test)\n", (956, 1055), True, 'import numpy as np\n'), ((1176, 1189), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (1185, 1189), True, 'import numpy as np\n'), ((1151, 1166), 'numpy.arange', 'np.arange', (['(2)', '(6)'], {}), '(2, 6)\n', (1160, 1166), True, 'import numpy as np\n'), ((1250, 1266), 'numpy.array', 'np.array', (['result'], {}), '(result)\n', (1258, 1266), True, 'import numpy as np\n')]
|
# -*- encoding:utf-8 -*-
from __future__ import print_function
import os, codecs, re
import random
import numpy as np
from datetime import datetime
from collections import defaultdict, Counter
from nltk.stem.porter import PorterStemmer
import reader
from utils import AGENT_FIRST_THRESHOLD, AGENT_SECOND_THRESHOLD, VISITOR_FIRST_THRESHOLD, VISITOR_SECOND_THRESHOLD
BASE_DIR = 'data'
THREAD_PATH = os.path.join(BASE_DIR,'chat_sequences.txt')
UTTERANCE_LENGTH_PATH = os.path.join(BASE_DIR,'utt_length.txt')
NULL_TOKEN = "X"
def encode_time_bucket(interval, speaker):
if speaker == "Agent":
if interval < AGENT_FIRST_THRESHOLD:
return "AGENT_TIME_1"
elif interval < AGENT_SECOND_THRESHOLD:
return "AGENT_TIME_2"
else:
return "AGENT_TIME_3"
elif speaker == "Visitor":
if interval < VISITOR_FIRST_THRESHOLD:
return "VISITOR_TIME_1"
elif interval < VISITOR_SECOND_THRESHOLD:
return "VISITOR_TIME_2"
else:
return "VISITOR_TIME_3"
def load_target_sessions(threshold):
s_set=[]
with open(UTTERANCE_LENGTH_PATH, 'rt') as f:
for line in f:
data=line.strip().split()
sid=data[0]
ulen=int(data[1])
if ulen < threshold:
continue
s_set.append(sid)
return s_set
def load_topn_words(sessions, N):
word_lists = []
for w_list in sessions.values():
word_lists.extend(w_list)
c = Counter(word_lists)
word_lists = dict(c.most_common(N)).keys()
return word_lists
def make_session_text():
session_set = load_target_sessions(threshold=4)
fsession_agent = codecs.open(reader.AGENT_SESSION_PATH, 'w', encoding='utf-8')
fsession_visitor = codecs.open(reader.VISITOR_SESSION_PATH, 'w', encoding='utf-8')
with codecs.open(THREAD_PATH, 'r', encoding='utf-8') as f:
f.next()
current_id = 'EXID'
prev_utt_dt = None
prev_speaker = None
agent_text_list = []
visitor_text_list = []
for idx, line in enumerate(f):
if idx % 1000 == 0:
print("Reading {}th line".format(idx))
data = line.strip().split('|')
session_id = data[0]
if session_id not in session_set or len(data) != 6:
continue
speaker = data[2]
type = data[4]
# 2013-10-01T00:02:47+00:00
current_utt_dt = datetime.strptime(data[5][:19], '%Y-%m-%dT%H:%M:%S')
if session_id != current_id and current_id != 'EXID':
current_id = session_id
num_agent_words = len(agent_text_list)
num_visitor_words = len(visitor_text_list)
# save agent sessions
print(current_id, file=fsession_agent, end=' ')
for ix in range(num_agent_words-1):
print(agent_text_list[ix], file=fsession_agent, end=' ')
print(agent_text_list[-1], file=fsession_agent)
agent_text_list[:] = []
# save visitor sessions
print(current_id, file=fsession_visitor, end=' ')
for ix in range(num_visitor_words-1):
print(visitor_text_list[ix], file=fsession_visitor, end=' ')
print(visitor_text_list[-1], file=fsession_visitor)
visitor_text_list[:] = []
prev_utt_dt = None
elif session_id != current_id and current_id == 'EXID':
current_id = session_id
elif session_id == current_id:
pass
else:
print("Unexpected errors on reading threads")
exit()
if type == 'URL':
text = 'URLLINK'
tokens = [text]
else:
text = data[3].strip().lower()
text = re.sub(r'<a href>.*<\a>', 'HTMLLINK', text)
text = re.sub(r'http://[\w./]+', 'URLLINK', text)
tokens = [re.sub(r'\W+', '', t) for t in re.split(r'\s+', text)]
tokens = [t for t in tokens if t != ""]
if prev_utt_dt is not None and prev_speaker != speaker:
time_bucket = encode_time(prev_utt_dt, current_utt_dt, speaker)
agent_text_list.append(time_bucket)
visitor_text_list.append(time_bucket)
if speaker == "Agent":
for t in tokens:
agent_text_list.append(t)
visitor_text_list.append(NULL_TOKEN)
elif speaker == "Visitor":
for t in tokens:
agent_text_list.append(NULL_TOKEN)
visitor_text_list.append(t)
else:
print("Probably errors on data. line num:{}".format(idx))
exit()
prev_speaker = speaker
prev_utt_dt = current_utt_dt
# For the last session
num_agent_words = len(agent_text_list)
num_visitor_words = len(visitor_text_list)
# save agent sessions
print(current_id, file=fsession_agent, end=' ')
for ix in range(num_agent_words - 1):
print(agent_text_list[ix], file=fsession_agent, end=' ')
print(agent_text_list[-1], file=fsession_agent)
agent_text_list[:] = []
# save visitor sessions
print(current_id, file=fsession_visitor, end=' ')
for ix in range(num_visitor_words - 1):
print(visitor_text_list[ix], file=fsession_visitor, end=' ')
print(visitor_text_list[-1], file=fsession_visitor)
visitor_text_list[:] = []
fsession_agent.close()
fsession_visitor.close()
def make_stemmed_text():
# Create p_stemmer of class PorterStemmer
p_stemmer = PorterStemmer()
print('Stemming agent sessions.')
fout_agent = codecs.open(reader.AGENT_PRE_PATH, 'w', encoding='utf-8')
with codecs.open(reader.AGENT_NOPRE_PATH, 'r', encoding='utf-8') as fsession_agent:
for idx, line in enumerate(fsession_agent):
if idx % 1000 == 0:
print("Reading {}th line".format(idx))
data = line.strip().split()
session_id = data[0]
words = data[1:]
num_words = len(words)
print(session_id, file=fout_agent, end=' ')
for ix in range(num_words-1):
w = words[ix]
if 'AGENT_' in w or 'VISITOR_' in w:
print(w, file=fout_agent, end=' ')
else:
print(p_stemmer.stem(w), file=fout_agent, end=' ')
print(p_stemmer.stem(words[-1]), file=fout_agent)
fout_agent.close()
print('Stemming visitor sessions.')
fout_visitor = codecs.open(reader.VISITOR_PRE_PATH, 'w', encoding='utf-8')
with codecs.open(reader.VISITOR_NOPRE_PATH, 'r', encoding='utf-8') as fsession_visitor:
for idx, line in enumerate(fsession_visitor):
if idx % 1000 == 0:
print("Reading {}th line".format(idx))
data = line.strip().split()
session_id = data[0]
words = data[1:]
num_words = len(words)
print(session_id, file=fout_visitor, end=' ')
for ix in range(num_words - 1):
w = words[ix]
if 'AGENT_' in w or 'VISITOR_' in w:
print(w, file=fout_visitor, end=' ')
else:
print(p_stemmer.stem(w), file=fout_visitor, end=' ')
print(p_stemmer.stem(words[-1]), file=fout_visitor)
fout_visitor.close()
def transform_label(session_label):
for sid, label in session_label.items():
if label == "Very Dissatisfied" or label == "Dissatisfied":
# 1 if satisfaction shows negativity
label_int = 1
else:
label_int = 0
session_label[sid] = label_int
return session_label
def transform_sequence(sequences, word_indices):
new_sequences = defaultdict(list)
for sid, sequence in sequences.items():
for s_ix, w in enumerate(sequence):
if w not in word_indices:
index = word_indices[NULL_TOKEN]
else:
index = word_indices[w]
new_sequences[sid].append(index)
return new_sequences
def transform_sequence_using_topn(sequences, word_indices, wv, top_words):
new_sequences = defaultdict(list)
candidate_matching = {}
for sid, sequence in sequences.items():
for s_ix, w in enumerate(sequence):
if w not in word_indices:
index = word_indices[NULL_TOKEN]
elif w not in top_words:
if w in candidate_matching:
index = word_indices[candidate_matching[w]]
else:
candidate, _ = wv.most_similar(positive=[w], topn=1)[0]
candidate_matching[w] = candidate
if candidate in word_indices:
index = word_indices[candidate]
else:
index = word_indices[NULL_TOKEN]
else:
index = word_indices[w]
new_sequences[sid].append(index)
return new_sequences
def transform_labeled_data_listform(sequences, labels):
sids = sequences.keys()
X, y = [], []
for sid in sids:
seq = sequences[sid]
label = labels[sid]
X.append(seq)
y.append(label)
return X, y
def filter_labeled_data(sequences, labels):
seq_keys = set(sequences.keys())
label_keys = set(labels.keys())
common_keys = seq_keys & label_keys
new_sequences = {}
new_labels = {}
for k in common_keys:
new_sequences[k] = sequences[k]
new_labels[k] = labels[k]
return new_sequences, new_labels
def random_oversampling(X, y, seed):
random.seed(seed)
satisfaction_counter = Counter(y)
(major_label, major_cnt), (minor_label, minor_cnt) = satisfaction_counter.most_common(2)
minor_indices = [i for i, x in enumerate(y) if x == minor_label]
all_indices = [i for i in range(0, len(y))]
for i in range(major_cnt / minor_cnt - 2):
all_indices.extend(minor_indices)
rest_cnt = major_cnt % minor_cnt
all_indices.extend(random.sample(minor_indices, rest_cnt))
new_X = [X[i] for i in all_indices]
new_y = [y[i] for i in all_indices]
return new_X, new_y
def get_wordvectors_from_keyedvectors(keyedVectors, seed):
vocab_list_wo_NULL = keyedVectors.vocab.keys()
embedding_dim = keyedVectors.syn0.shape[1]
if NULL_TOKEN in vocab_list_wo_NULL:
vocab_list_wo_NULL.remove(NULL_TOKEN)
vocab_list = [NULL_TOKEN] + vocab_list_wo_NULL # X should be located at 0
word_indices = {}
for vocab_index in range(1, len(vocab_list)):
w = vocab_list[vocab_index]
word_indices[w] = vocab_index
# index for out-of-vocabulary words
np.random.seed(seed)
word_indices[NULL_TOKEN] = 0
vocab_size = len(word_indices)
embedding_matrix = np.zeros((vocab_size, embedding_dim), dtype=np.float32)
# Out-of-vocabulary word is zero-vector
embedding_matrix[0] = np.random.random(size=keyedVectors.syn0.shape[1]) / 5 - 0.1
for word in vocab_list_wo_NULL:
i = word_indices[word]
embedding_vector = keyedVectors.word_vec(word)
embedding_matrix[i] = embedding_vector
return vocab_size, embedding_dim, word_indices, embedding_matrix
if __name__ == '__main__':
make_session_text()
make_stemmed_text()
|
[
"numpy.random.seed",
"codecs.open",
"re.split",
"random.sample",
"nltk.stem.porter.PorterStemmer",
"numpy.zeros",
"collections.defaultdict",
"datetime.datetime.strptime",
"numpy.random.random",
"random.seed",
"collections.Counter",
"os.path.join",
"re.sub"
] |
[((414, 458), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""chat_sequences.txt"""'], {}), "(BASE_DIR, 'chat_sequences.txt')\n", (426, 458), False, 'import os, codecs, re\n'), ((483, 523), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""utt_length.txt"""'], {}), "(BASE_DIR, 'utt_length.txt')\n", (495, 523), False, 'import os, codecs, re\n'), ((1577, 1596), 'collections.Counter', 'Counter', (['word_lists'], {}), '(word_lists)\n', (1584, 1596), False, 'from collections import defaultdict, Counter\n'), ((1779, 1840), 'codecs.open', 'codecs.open', (['reader.AGENT_SESSION_PATH', '"""w"""'], {'encoding': '"""utf-8"""'}), "(reader.AGENT_SESSION_PATH, 'w', encoding='utf-8')\n", (1790, 1840), False, 'import os, codecs, re\n'), ((1865, 1928), 'codecs.open', 'codecs.open', (['reader.VISITOR_SESSION_PATH', '"""w"""'], {'encoding': '"""utf-8"""'}), "(reader.VISITOR_SESSION_PATH, 'w', encoding='utf-8')\n", (1876, 1928), False, 'import os, codecs, re\n'), ((6039, 6054), 'nltk.stem.porter.PorterStemmer', 'PorterStemmer', ([], {}), '()\n', (6052, 6054), False, 'from nltk.stem.porter import PorterStemmer\n'), ((6114, 6171), 'codecs.open', 'codecs.open', (['reader.AGENT_PRE_PATH', '"""w"""'], {'encoding': '"""utf-8"""'}), "(reader.AGENT_PRE_PATH, 'w', encoding='utf-8')\n", (6125, 6171), False, 'import os, codecs, re\n'), ((7036, 7095), 'codecs.open', 'codecs.open', (['reader.VISITOR_PRE_PATH', '"""w"""'], {'encoding': '"""utf-8"""'}), "(reader.VISITOR_PRE_PATH, 'w', encoding='utf-8')\n", (7047, 7095), False, 'import os, codecs, re\n'), ((8336, 8353), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (8347, 8353), False, 'from collections import defaultdict, Counter\n'), ((8772, 8789), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (8783, 8789), False, 'from collections import defaultdict, Counter\n'), ((10289, 10306), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (10300, 10306), False, 'import random\n'), ((10335, 10345), 'collections.Counter', 'Counter', (['y'], {}), '(y)\n', (10342, 10345), False, 'from collections import defaultdict, Counter\n'), ((11399, 11419), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (11413, 11419), True, 'import numpy as np\n'), ((11516, 11571), 'numpy.zeros', 'np.zeros', (['(vocab_size, embedding_dim)'], {'dtype': 'np.float32'}), '((vocab_size, embedding_dim), dtype=np.float32)\n', (11524, 11571), True, 'import numpy as np\n'), ((1941, 1988), 'codecs.open', 'codecs.open', (['THREAD_PATH', '"""r"""'], {'encoding': '"""utf-8"""'}), "(THREAD_PATH, 'r', encoding='utf-8')\n", (1952, 1988), False, 'import os, codecs, re\n'), ((6182, 6241), 'codecs.open', 'codecs.open', (['reader.AGENT_NOPRE_PATH', '"""r"""'], {'encoding': '"""utf-8"""'}), "(reader.AGENT_NOPRE_PATH, 'r', encoding='utf-8')\n", (6193, 6241), False, 'import os, codecs, re\n'), ((7106, 7167), 'codecs.open', 'codecs.open', (['reader.VISITOR_NOPRE_PATH', '"""r"""'], {'encoding': '"""utf-8"""'}), "(reader.VISITOR_NOPRE_PATH, 'r', encoding='utf-8')\n", (7117, 7167), False, 'import os, codecs, re\n'), ((10712, 10750), 'random.sample', 'random.sample', (['minor_indices', 'rest_cnt'], {}), '(minor_indices, rest_cnt)\n', (10725, 10750), False, 'import random\n'), ((2593, 2645), 'datetime.datetime.strptime', 'datetime.strptime', (['data[5][:19]', '"""%Y-%m-%dT%H:%M:%S"""'], {}), "(data[5][:19], '%Y-%m-%dT%H:%M:%S')\n", (2610, 2645), False, 'from datetime import datetime\n'), ((11644, 11693), 'numpy.random.random', 'np.random.random', ([], {'size': 'keyedVectors.syn0.shape[1]'}), '(size=keyedVectors.syn0.shape[1])\n', (11660, 11693), True, 'import numpy as np\n'), ((4081, 4124), 're.sub', 're.sub', (['"""<a href>.*<\\\\a>"""', '"""HTMLLINK"""', 'text'], {}), "('<a href>.*<\\\\a>', 'HTMLLINK', text)\n", (4087, 4124), False, 'import os, codecs, re\n'), ((4149, 4191), 're.sub', 're.sub', (['"""http://[\\\\w./]+"""', '"""URLLINK"""', 'text'], {}), "('http://[\\\\w./]+', 'URLLINK', text)\n", (4155, 4191), False, 'import os, codecs, re\n'), ((4219, 4240), 're.sub', 're.sub', (['"""\\\\W+"""', '""""""', 't'], {}), "('\\\\W+', '', t)\n", (4225, 4240), False, 'import os, codecs, re\n'), ((4250, 4272), 're.split', 're.split', (['"""\\\\s+"""', 'text'], {}), "('\\\\s+', text)\n", (4258, 4272), False, 'import os, codecs, re\n')]
|
"""
Script to get all the tiles from available scenes, aoi and date range for Planetscope or Skysat
Author: @developmentseed
Run:
python3 get_planet_tiles.py --geojson=supersites.geojson \
--api_key=xxxxx \
--collections=PSScene3Band \
--start_date=2020,1,1 \
--end_date=2020,1,10 \
--cloud_cover=0.05 \
--zoom=16 \
--out_tex=test.txt
"""
import os
import sys
import requests
from requests.auth import HTTPBasicAuth
import numpy as np
import json
import requests
import mercantile
import numpy as np
import argparse
from datetime import date
from planet import api
client = api.ClientV1()
def stats(geometry, collections, start_date, end_date, cc, PL_API_KEY):
"""Retrieve Stats
----
Args:
collections: ['PSOrthoTile', 'REOrthoTile', 'PSScene3Band', 'PSScene4Band', 'SkySatScene']
geometry: geojson for the sites
start_date: "2020-04-01T00:00:00.000Z"
end_date: same format as start_date
cc: cloud cover in 0.05 (5%)
"""
# filter for items the overlap with our chosen geometry
geometry_filter = {
"type": "GeometryFilter",
"field_name": "geometry",
"config": geometry
}
# filter images acquired in a certain date range
date_range_filter = {
"type": "DateRangeFilter",
"field_name": "acquired",
"config": {
"gte": start_date,
"lte": end_date
}
}
# filter any images which are more than 50% clouds
cloud_cover_filter = {
"type": "RangeFilter",
"field_name": "cloud_cover",
"config": {
"lte": cc
}
}
config = {
"type": "AndFilter",
"config": [geometry_filter, cloud_cover_filter, date_range_filter]
}
# Stats API request object
stats_endpoint_request = {
"interval": "day", "item_types": collections, "filter": config
}
# build a filter for the AOI
query = api.filters.and_filter(
api.filters.geom_filter(geometry),
api.filters.range_filter('cloud_cover', gt=0),
api.filters.range_filter('cloud_cover', lt=float(cc)),
api.filters.date_range("acquired", gte=start_date, lte=end_date)
)
# we are requesting <collect type> imagery
item_types = collections
request = api.filters.build_search_request(query, item_types)
# this will cause an exception if there are any API related errors
results = client.quick_search(request)
return results.get()
def search(geometry, collections, start_date, end_date, cc, PL_API_KEY
):
"""Search for Data."""
print('PL_API_KEY: ', PL_API_KEY)
print('geometry: ', geometry)
print('collections: ', collections)
print('start_date, end_date: ', start_date, end_date)
print('cc: ', cc)
# filter for items the overlap with our chosen geometry
geometry_filter = {
"type": "GeometryFilter",
"field_name": "geometry",
"config": geometry
}
# filter images acquired in a certain date range
date_range_filter = {
"type": "DateRangeFilter",
"field_name": "acquired",
"config": {
"gte": start_date,
"lte":end_date
}
}
# filter any images which are more than 50% clouds
cloud_cover_filter = {
"type": "RangeFilter",
"field_name": "cloud_cover",
"config": {
"lte": cc
}
}
config = {
"type": "AndFilter",
"config": [geometry_filter, cloud_cover_filter, date_range_filter]
}
# Stats API request object
stats_endpoint_request = {
"interval": "day",
"item_types": collections,
"filter": config
}
# fire off the POST request #'https://api.planet.com/data/v1/quick-search',
result = requests.post('https://api.planet.com/data/v1/quick-search',
auth=HTTPBasicAuth(PL_API_KEY, ''), json=stats_endpoint_request)
# build a filter for the AOI
query = api.filters.and_filter(
api.filters.geom_filter(geometry),
api.filters.range_filter('cloud_cover', gt=0),
api.filters.range_filter('cloud_cover', lt=float(cc)),
api.filters.date_range("acquired", gte=start_date, lte=end_date)
)
# we are requesting <collect type> imagery
item_types = collections
request = api.filters.build_search_request(query, item_types)
# this will cause an exception if there are any API related errors
results = client.quick_search(request)
return results.get()
def get_scene_ids_aoi(site_aois, start_date, end_date, cc, collections, api_key):
"""get scene ids
"""
results = {feat["properties"]["label"] : stats(feat["geometry"], collections, start_date, end_date, cc, api_key)
for feat in site_aois["features"]}
results_PS = {feat["properties"]["label"] : search(feat["geometry"], collections, start_date, end_date, cc, api_key)
for feat in site_aois["features"]}
results_PS = {feat["properties"]["label"] : search(feat["geometry"], collections, start_date, end_date, cc, api_key)
for feat in site_aois["features"]}
aois_scene_ids = [{
aoi: [[f['id'], f['geometry']['coordinates']]for f in results_PS[aoi]['features']]
} for aoi in results_PS.keys()]
print(f"Total of {collections} scenes per sites")
for k, r in results.items():
print(k)
im = r.get("buckets", [])
total = sum([f["count"] for f in im])
print(total)
print("---")
return aois_scene_ids
def revert_coordinates(coordinates):
"""convert coordinates to bbox
Args:
coordinates(list): geometry coordiantes of the aoi
Return:
bbox(list): [xmin, ymin, xmax, ymax]
"""
coordinates = np.asarray(coordinates)
lats = coordinates[:,:,1]
lons = coordinates[:,:,0]
bbox = [lons.min(), lats.min(), lons.max(), lats.max()]
return bbox
def tile_indices(bbox, ZOOM_LEVEL):
"""get mercantile bounds
Args:
bbox(list): [xmin, ymin, xmax, ymax] of the aoi
ZOOM_LEVEL(int): zoom level, e.g. 16
Returns:
tile_bounds (list): tile bounds of AOI
"""
start_x, start_y, _ = mercantile.tile(bbox[0], bbox[3], ZOOM_LEVEL)
end_x, end_y, _ = mercantile.tile(bbox[2], bbox[1], ZOOM_LEVEL)
tile_bounds = [[start_x, end_x], [start_y, end_y]]
return tile_bounds
def get_tile_xy(geojson, start_date, end_date, cc, collections, ZOOM_LEVEL, api_key):
"""get tile range for pss scenes
Args:
geojson (geojson): polygons of the AOIs;
start_date(iso date): date in iso format, e.g. "2020-04-01T00:00:00.000Z"
end_date(iso date): date in iso format, e.g. "2020-04-03T00:00:00.000Z"
cc(float): cloud cover, e.g. 0.05;
collections(list): planet image products, e.g.['PSOrthoTile','PSScene3Band','SkySatScene']
"""
scene_tiles_range = []
aoi_scene_coverage = get_scene_ids_aoi(geojson, start_date, end_date,
cc, collections, api_key)
for aoi in aoi_scene_coverage:
for item in aoi.values():
for scene_id, coor in item:
bbox = revert_coordinates(coor)
tiles = tile_indices(bbox, ZOOM_LEVEL)
scene_tiles_range.append([scene_id, tiles])
return scene_tiles_range
def get_tiles(tile_rangs):
"""get each scene id and the tile x y bounds
Args:
tile_rangs(list): save scene id and x y bounds
###########tile_range#######
#[['20200529_003832_100d', [[53910, 53961], [24896, 24921]]]]#
Returns:
tile_xyz(list): a list contains scene id, x, y, z.
###########################
"""
tile_xyz = []
for item in tile_rangs:
for x_bound in range(item[1][0][0], item[1][0][1] + 1):
for y_bound in range(item[1][1][0], item[1][1][1]):
tile_xyz.append(f'{item[0]}-{x_bound}-{y_bound}-16')
return tile_xyz
def write_txt(tile_file, out_tex):
"""write tile in format of 'pss_scene_id-x-y-z' to a txt file
"""
with open(out_tex, 'w') as out:
for tile in tile_file:
out.write(tile)
out.write('\n')
def main(geojson, api_key, collections, start_date, end_date, cloud_cover, zoom, out_tex):
"""get all the tiles
"""
with open(geojson, 'r') as geo:
geojson = json.load(geo)
collections = [collections]
year_s, mon_s, day_s = start_date.split(',')
year_e, mon_e, day_e = end_date.split(',')
start_date = f'{date(int(year_s), int(mon_s), int(day_s))}T00:00:00.000Z'
end_date = f'{date(int(year_e), int(mon_e), int(day_e))}T00:00:00.000Z'
zoom = int(zoom)
print("#"*40)
print(f'start date is {start_date} and end date is {end_date}\n')
tile_range = get_tile_xy(geojson, start_date, end_date, float(cloud_cover), collections,
int(zoom), api_key)
tiles_pss_aois = get_tiles(tile_range)
print(f'total output tiles are {len(tiles_pss_aois)}\n')
write_txt(tiles_pss_aois, out_tex)
print(f'write all the tiles in {out_tex} at current directory \n')
print("#"*40)
def parse_arg(args):
desc = "get_planet_tiles"
dhf = argparse.RawTextHelpFormatter
parse0 = argparse.ArgumentParser(description= desc, formatter_class=dhf)
parse0.add_argument('--geojson', help="aoi API endpoit in https://")
parse0.add_argument('--api_key', help="planet api key")
parse0.add_argument('--collections', help="Planet product as a list")
parse0.add_argument('--start_date', help="start date in format of: year, month, day")
parse0.add_argument('--end_date', help="start date in format of: year, month, day")
parse0.add_argument('--cloud_cover', help='cloud cover in float, e.g. 0.05 for under 5%')
parse0.add_argument('--zoom', help='OSM zoom level, e.g. 16')
parse0.add_argument('--out_tex', help='txt name to save all the output tiles')
return vars(parse0.parse_args(args))
def cli():
args = parse_arg(sys.argv[1:])
main(**args)
if __name__ == "__main__":
cli()
|
[
"json.load",
"argparse.ArgumentParser",
"numpy.asarray",
"planet.api.filters.geom_filter",
"planet.api.filters.date_range",
"planet.api.filters.range_filter",
"requests.auth.HTTPBasicAuth",
"planet.api.filters.build_search_request",
"mercantile.tile",
"planet.api.ClientV1"
] |
[((666, 680), 'planet.api.ClientV1', 'api.ClientV1', ([], {}), '()\n', (678, 680), False, 'from planet import api\n'), ((2330, 2381), 'planet.api.filters.build_search_request', 'api.filters.build_search_request', (['query', 'item_types'], {}), '(query, item_types)\n', (2362, 2381), False, 'from planet import api\n'), ((4324, 4375), 'planet.api.filters.build_search_request', 'api.filters.build_search_request', (['query', 'item_types'], {}), '(query, item_types)\n', (4356, 4375), False, 'from planet import api\n'), ((5775, 5798), 'numpy.asarray', 'np.asarray', (['coordinates'], {}), '(coordinates)\n', (5785, 5798), True, 'import numpy as np\n'), ((6207, 6252), 'mercantile.tile', 'mercantile.tile', (['bbox[0]', 'bbox[3]', 'ZOOM_LEVEL'], {}), '(bbox[0], bbox[3], ZOOM_LEVEL)\n', (6222, 6252), False, 'import mercantile\n'), ((6275, 6320), 'mercantile.tile', 'mercantile.tile', (['bbox[2]', 'bbox[1]', 'ZOOM_LEVEL'], {}), '(bbox[2], bbox[1], ZOOM_LEVEL)\n', (6290, 6320), False, 'import mercantile\n'), ((9267, 9329), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc', 'formatter_class': 'dhf'}), '(description=desc, formatter_class=dhf)\n', (9290, 9329), False, 'import argparse\n'), ((2012, 2045), 'planet.api.filters.geom_filter', 'api.filters.geom_filter', (['geometry'], {}), '(geometry)\n', (2035, 2045), False, 'from planet import api\n'), ((2053, 2098), 'planet.api.filters.range_filter', 'api.filters.range_filter', (['"""cloud_cover"""'], {'gt': '(0)'}), "('cloud_cover', gt=0)\n", (2077, 2098), False, 'from planet import api\n'), ((2167, 2231), 'planet.api.filters.date_range', 'api.filters.date_range', (['"""acquired"""'], {'gte': 'start_date', 'lte': 'end_date'}), "('acquired', gte=start_date, lte=end_date)\n", (2189, 2231), False, 'from planet import api\n'), ((4006, 4039), 'planet.api.filters.geom_filter', 'api.filters.geom_filter', (['geometry'], {}), '(geometry)\n', (4029, 4039), False, 'from planet import api\n'), ((4047, 4092), 'planet.api.filters.range_filter', 'api.filters.range_filter', (['"""cloud_cover"""'], {'gt': '(0)'}), "('cloud_cover', gt=0)\n", (4071, 4092), False, 'from planet import api\n'), ((4161, 4225), 'planet.api.filters.date_range', 'api.filters.date_range', (['"""acquired"""'], {'gte': 'start_date', 'lte': 'end_date'}), "('acquired', gte=start_date, lte=end_date)\n", (4183, 4225), False, 'from planet import api\n'), ((8382, 8396), 'json.load', 'json.load', (['geo'], {}), '(geo)\n', (8391, 8396), False, 'import json\n'), ((3870, 3899), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['PL_API_KEY', '""""""'], {}), "(PL_API_KEY, '')\n", (3883, 3899), False, 'from requests.auth import HTTPBasicAuth\n')]
|
import numpy as np
# transfer functions
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# derivative of sigmoid
def dsigmoid(y):
return np.multiply(y, (1.0 - y))
def tanh(x):
return np.tanh(x)
# derivative for tanh sigmoid
def dtanh(y):
return 1 - np.multiply(y, y)
|
[
"numpy.exp",
"numpy.multiply",
"numpy.tanh"
] |
[((144, 167), 'numpy.multiply', 'np.multiply', (['y', '(1.0 - y)'], {}), '(y, 1.0 - y)\n', (155, 167), True, 'import numpy as np\n'), ((196, 206), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (203, 206), True, 'import numpy as np\n'), ((268, 285), 'numpy.multiply', 'np.multiply', (['y', 'y'], {}), '(y, y)\n', (279, 285), True, 'import numpy as np\n'), ((78, 88), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (84, 88), True, 'import numpy as np\n')]
|
#!/usr/local/bin/python3
# solver2021.py : 2021 Sliding tile puzzle solver
#
# Code by: <NAME> (hatha), <NAME> (aagond)
#
# Based on skeleton code by D. Crandall & B551 Staff, September 2021
#
#References used are as follows:
#1. https://www.quora.com/How-do-I-create-a-nested-list-from-a-flat-one-in-Python to create list of lists in compact manner
#2. a) Test code given by CSCI B551 team for Left,right, up, down, Icc, Ic, Occ, Oc moves.
#2. b) for tweaking given code using a different approach.
#3. To find coordinates of elements in a nested list, I referred https://stackoverflow.com/questions/53319487/finding-the-index-of-elements-in-nested-list?rq=1
import sys
import numpy as np
import copy
from queue import PriorityQueue
ROWS=5
COLS=5
def printable_board(board):
return [ ('%3d ')*COLS % board[j:(j+COLS)] for j in range(0, ROWS*COLS, COLS) ]
def heuristic_used(board):
#Split the board and took corners, vertices of inner ring and the center most element.
groups=[1,5,21,25,13,8,12,18,14]
"""
groups is a combination of following 3 subgroups
1 _ _ _ 5 _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ 8 _ _
_ _ _ _ _ _ _ 13 _ _ _ 12 _14 _
_ _ _ _ _ _ _ _ _ _ _ _ 18 _ _
21 _ _ _ 25 _ _ _ _ _ _ _ _ _ _
Corners of the goal state Center most element of goal state Vertices of Inner ring
Subgroup 1 Subgroup 2 Subgroup 3
"""
# Tupled coordinates of selected groups of goal state
goal_coord=[(0,0),(0,4),(4,0),(4,4),(2,2),(1,2),(2,1),(3,2),(2,3)]
coordinates=[]
#Below section stores coordinates of selected group from current state in a list: coordinates
for tile in groups:
for ind, row in enumerate(board):
if tile in row:
coordinates.append((ind,row.index(tile)))
min_dist_list=[]
#Below part finds the shortest Manhattan distance to it's goal state
for i in range(len(goal_coord)):
dist1= abs(goal_coord[i][0]-coordinates[i][0])+abs(goal_coord[i][1]-coordinates[i][1])
dist2= ROWS-abs(goal_coord[i][0]-coordinates[i][0])+abs(goal_coord[i][1]-coordinates[i][1])
dist3= abs(goal_coord[i][0]-coordinates[i][0])+COLS-abs(goal_coord[i][1]-coordinates[i][1])
dist4= ROWS-abs(goal_coord[i][0]-coordinates[i][0]) +COLS-abs(goal_coord[1][0]-coordinates[i][1])
min_dist_list.append(min(dist1,dist2,dist3,dist4))
#Returns Max of manhattan of subgroup1 + Middle element + Max of manhattan of subgroup3
return max(min_dist_list[:3])+ min_dist_list[4]+ max(min_dist_list[5:])
def move_right(board, row):
boardR=copy.deepcopy(board)
boardR[row] = boardR[row][-1:] + boardR[row][:-1]
return boardR
def move_left(board, row):
#"""Move the given row to one position left"""
#print('Row : ', row, '\nBoard L :', board[row])
boardL=copy.deepcopy(board)
boardL[row] = boardL[row][1:] + boardL[row][:1]
return boardL
def rotate_right(board,row,residual):
board[row] = [board[row][0]] +[residual] + board[row][1:]
#print(' Rotate\n:' ,(board))
residual=board[row].pop()
return residual
def rotate_left(board,row,residual):
board[row] = board[row][:-1] + [residual] + [board[row][-1]]
residual=board[row].pop(0)
return residual
def move_clockwise(board):
"""Move the outer ring clockwise"""
boardC=copy.deepcopy(board)
boardC[0]=[boardC[1][0]]+boardC[0]
#print(boardC)
residual=boardC[0].pop()
#print(residual)
boardC=transpose_board(boardC)
#print(np.array(boardC))
residual=rotate_right(boardC,-1,residual)
#print(residual)
boardC=transpose_board(boardC)
residual=rotate_left(boardC,-1,residual)
boardC=transpose_board(boardC)
residual=rotate_left(boardC,0,residual)
boardC=transpose_board(boardC)
return boardC
def move_cclockwise(board):
"""Move the outer ring counter-clockwise"""
boardCC=copy.deepcopy(board)
boardCC[0]=boardCC[0]+[boardCC[1][-1]]
residual=boardCC[0].pop(0)
boardCC=transpose_board(boardCC)
residual=rotate_right(boardCC,0,residual)
boardCC=transpose_board(boardCC)
residual=rotate_right(boardCC,-1,residual)
boardCC=transpose_board(boardCC)
residual=rotate_left(boardCC,-1,residual)
boardCC=transpose_board(boardCC)
return boardCC
def transpose_board(board):
"""Transpose the board --> change row to column"""
boardT=copy.deepcopy(board)
return [list(col) for col in zip(*boardT)]
# return a list of possible successor states
def successors(current_state):
next_state = []
for i in range(ROWS):
boardL = move_left(current_state,i)
boardR = move_right(current_state,i)
boardU = transpose_board(move_left(transpose_board(current_state), i))
boardD = transpose_board(move_right(transpose_board(current_state), i))
next_state.append([boardL, "L"+ str(i+1)])
next_state.append([boardR, "R"+ str(i+1)])
next_state.append([boardU, "U"+str(i+1)])
next_state.append([boardD, "D"+str(i+1)])
boardOC = move_clockwise(current_state)
next_state.append([boardOC, "Oc"])
boardOCC = move_cclockwise(current_state)
next_state.append([boardOCC, "Occ"])
boardIC=np.array(current_state)
inner_board=boardIC[1:-1,1:-1].tolist()
inner_board = move_clockwise(inner_board)
boardIC[1:-1,1:-1]=np.array(inner_board)
boardIC=boardIC.tolist()
next_state.append([boardIC, "Ic"])
boardICC=np.array(current_state)
inner_board=boardICC[1:-1,1:-1].tolist()
inner_board = move_cclockwise(inner_board)
boardICC[1:-1,1:-1]=np.array(inner_board)
boardICC=boardICC.tolist()
next_state.append([boardICC, "Icc"])
return next_state
# check if we've reached the goal
def is_goal(current_state):
goal_state= [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]
return current_state == goal_state
def solve(initial_board):
initial_board_list= list(initial_board)
#Referred below to find non-clunky way of creating nested list from list
#https://www.quora.com/How-do-I-create-a-nested-list-from-a-flat-one-in-Python
original_board = [initial_board_list[i:i + ROWS] for i in range(0, len(initial_board_list), ROWS)]
fringe = PriorityQueue()
fringe.put((0,original_board,'',0))
already_visited=[]
already_visited.append(original_board)
while fringe :
cost_heuristic , current_state, route_taken, count_steps =fringe.get()
steps = count_steps+1 #Increase the cost after every move
if is_goal(current_state):
route_taken=route_taken.split(",")
route_taken.pop() #Remove last comma
return route_taken
for state_move in successors(current_state):
next_state, moves = state_move[0], state_move[1]
if next_state not in already_visited:
already_visited.append(next_state)
fringe.put((heuristic_used(next_state)+steps,next_state, route_taken+moves+",", steps))
return [] #In case no steps needed/fringe empty
#Please don't modify anything below this line
if __name__ == "__main__":
if(len(sys.argv) != 2):
raise(Exception("Error: expected a board filename"))
start_state = []
with open(sys.argv[1], 'r') as file:
for line in file:
start_state += [ int(i) for i in line.split() ]
if len(start_state) != ROWS*COLS:
raise(Exception("Error: couldn't parse start state file"))
print("Start state: \n" +"\n".join(printable_board(tuple(start_state))))
print("Solving...")
route = solve(tuple(start_state))
print("Solution found in " + str(len(route)) + " moves:" + "\n" + " ".join(route))
|
[
"queue.PriorityQueue",
"copy.deepcopy",
"numpy.array"
] |
[((2976, 2996), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (2989, 2996), False, 'import copy\n'), ((3220, 3240), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (3233, 3240), False, 'import copy\n'), ((3738, 3758), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (3751, 3758), False, 'import copy\n'), ((4299, 4319), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (4312, 4319), False, 'import copy\n'), ((4791, 4811), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (4804, 4811), False, 'import copy\n'), ((5624, 5647), 'numpy.array', 'np.array', (['current_state'], {}), '(current_state)\n', (5632, 5647), True, 'import numpy as np\n'), ((5761, 5782), 'numpy.array', 'np.array', (['inner_board'], {}), '(inner_board)\n', (5769, 5782), True, 'import numpy as np\n'), ((5869, 5892), 'numpy.array', 'np.array', (['current_state'], {}), '(current_state)\n', (5877, 5892), True, 'import numpy as np\n'), ((6009, 6030), 'numpy.array', 'np.array', (['inner_board'], {}), '(inner_board)\n', (6017, 6030), True, 'import numpy as np\n'), ((6707, 6722), 'queue.PriorityQueue', 'PriorityQueue', ([], {}), '()\n', (6720, 6722), False, 'from queue import PriorityQueue\n')]
|
#!/usr/bin/env python3
import LinearResponseVariationalBayes as vb
import LinearResponseVariationalBayes.SparseObjectives as obj_lib
import LinearResponseVariationalBayes.OptimizationUtils as opt_lib
import autograd.numpy as np
import numpy.testing as np_test
import unittest
class QuadraticModel(object):
def __init__(self, dim):
self.dim = dim
self.param = vb.VectorParam('theta', size=dim)
vec = np.linspace(0.1, 0.3, num=dim)
self.matrix = np.outer(vec, vec) + np.eye(dim)
self.vec = vec
self.objective = obj_lib.Objective(self.param, self.get_objective)
def get_objective(self):
theta = self.param.get()
objective = 0.5 * theta.T @ self.matrix @ theta + self.vec @ theta
return objective
# Testing functions that use the fact that the optimum has a closed form.
def get_true_optimum_theta(self):
theta = -1 * np.linalg.solve(self.matrix, self.vec)
return theta
def get_true_optimum(self):
# ...in the free parameterization.
theta = self.get_true_optimum_theta()
self.param.set_vector(theta)
return self.param.get_free()
class TestOptimizationUtils(unittest.TestCase):
def test_optimzation_utils(self):
model = QuadraticModel(3)
init_x = np.zeros(model.dim)
opt_x, opt_result = opt_lib.minimize_objective_bfgs(
model.objective, init_x, precondition=False)
np_test.assert_array_almost_equal(
model.get_true_optimum(), opt_result.x)
np_test.assert_array_almost_equal(
model.get_true_optimum(), opt_x)
opt_x, opt_result = opt_lib.minimize_objective_trust_ncg(
model.objective, init_x, precondition=False)
np_test.assert_array_almost_equal(
model.get_true_optimum(), opt_result.x)
np_test.assert_array_almost_equal(
model.get_true_optimum(), opt_x)
hessian, inv_hess_sqrt, hessian_corrected = \
opt_lib.set_objective_preconditioner(model.objective, init_x)
np_test.assert_array_almost_equal(model.matrix, hessian)
opt_x, opt_result = opt_lib.minimize_objective_bfgs(
model.objective, init_x, precondition=True)
np_test.assert_array_almost_equal(model.get_true_optimum(), opt_x)
opt_x, opt_result = opt_lib.minimize_objective_trust_ncg(
model.objective, init_x, precondition=True)
np_test.assert_array_almost_equal(model.get_true_optimum(), opt_x)
def test_repeated_optimization(self):
model = QuadraticModel(3)
init_x = np.zeros(model.dim)
def initial_optimization(x):
new_x = np.random.random(len(x))
return new_x, new_x
def take_gradient_step(x):
grad = model.objective.fun_free_grad(x)
return x - 0.5 * grad, x
opt_x, converged, x_conv, f_conv, grad_conv, obj_opt, opt_results = \
opt_lib.repeatedly_optimize(
model.objective,
take_gradient_step,
init_x,
initial_optimization_fun=initial_optimization,
keep_intermediate_optimizations=True,
max_iter=1000)
np_test.assert_array_almost_equal(
model.get_true_optimum(), opt_x, decimal=4)
class TestMatrixSquareRoot(unittest.TestCase):
def test_sym_matrix_inv_sqrt(self):
a_vec = np.array([1, 2, 3])
b_vec = np.array([0, 1, 3])
c_vec = np.array([0, 3, 3])
# a_vec = a_vec /np.linalg.norm(a_vec)
# b_vec = b_vec /np.linalg.norm(b_vec)
# c_vec = c_vec / np.linalg.norm(c_vec)
a = np.outer(a_vec, a_vec) + \
np.outer(b_vec, b_vec) + \
np.outer(c_vec, c_vec)
# Test with no eigenvalue trimming
a_inv_sqrt, a_corrected = opt_lib.get_sym_matrix_inv_sqrt(a)
np_test.assert_array_almost_equal(
np.linalg.inv(a), a_inv_sqrt @ a_inv_sqrt.T)
np_test.assert_array_almost_equal(a, a_corrected)
# Check the eigenvalue trimming.
eig_val, eig_vec = np.linalg.eigh(a)
min_ev = eig_val[0] + 0.5 * (eig_val[1] - eig_val[0])
max_ev = eig_val[2] - 0.5 * (eig_val[2] - eig_val[1])
a_inv_sqrt, a_corrected = opt_lib.get_sym_matrix_inv_sqrt(
a, ev_min=min_ev)
eig_val_test, _ = np.linalg.eigh(np.linalg.inv(a_inv_sqrt @ a_inv_sqrt.T))
np_test.assert_array_almost_equal(min_ev, eig_val_test[0])
np_test.assert_array_almost_equal(eig_val[1:2], eig_val_test[1:2])
a_inv_sqrt, a_corrected = opt_lib.get_sym_matrix_inv_sqrt(
a, ev_max=max_ev)
eig_val_test, _ = np.linalg.eigh(np.linalg.inv(a_inv_sqrt @ a_inv_sqrt.T))
np_test.assert_array_almost_equal(max_ev, eig_val_test[2])
np_test.assert_array_almost_equal(eig_val[0:1], eig_val_test[0:1])
a_inv_sqrt, a_corrected = opt_lib.get_sym_matrix_inv_sqrt(
a, ev_min=min_ev, ev_max=max_ev)
eig_val_test, _ = np.linalg.eigh(np.linalg.inv(a_inv_sqrt @ a_inv_sqrt.T))
np_test.assert_array_almost_equal(min_ev, eig_val_test[0])
np_test.assert_array_almost_equal(max_ev, eig_val_test[2])
np_test.assert_array_almost_equal(eig_val[1], eig_val_test[1])
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_trust_ncg",
"LinearResponseVariationalBayes.OptimizationUtils.get_sym_matrix_inv_sqrt",
"LinearResponseVariationalBayes.OptimizationUtils.repeatedly_optimize",
"LinearResponseVariationalBayes.SparseObjectives.Objective",
"autograd.numpy.linalg.eigh",
"autograd.numpy.outer",
"autograd.numpy.eye",
"autograd.numpy.linalg.solve",
"autograd.numpy.array",
"autograd.numpy.zeros",
"autograd.numpy.linspace",
"autograd.numpy.linalg.inv",
"LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_bfgs",
"numpy.testing.assert_array_almost_equal",
"LinearResponseVariationalBayes.VectorParam",
"LinearResponseVariationalBayes.OptimizationUtils.set_objective_preconditioner"
] |
[((5354, 5369), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5367, 5369), False, 'import unittest\n'), ((381, 414), 'LinearResponseVariationalBayes.VectorParam', 'vb.VectorParam', (['"""theta"""'], {'size': 'dim'}), "('theta', size=dim)\n", (395, 414), True, 'import LinearResponseVariationalBayes as vb\n'), ((430, 460), 'autograd.numpy.linspace', 'np.linspace', (['(0.1)', '(0.3)'], {'num': 'dim'}), '(0.1, 0.3, num=dim)\n', (441, 460), True, 'import autograd.numpy as np\n'), ((565, 614), 'LinearResponseVariationalBayes.SparseObjectives.Objective', 'obj_lib.Objective', (['self.param', 'self.get_objective'], {}), '(self.param, self.get_objective)\n', (582, 614), True, 'import LinearResponseVariationalBayes.SparseObjectives as obj_lib\n'), ((1311, 1330), 'autograd.numpy.zeros', 'np.zeros', (['model.dim'], {}), '(model.dim)\n', (1319, 1330), True, 'import autograd.numpy as np\n'), ((1360, 1436), 'LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_bfgs', 'opt_lib.minimize_objective_bfgs', (['model.objective', 'init_x'], {'precondition': '(False)'}), '(model.objective, init_x, precondition=False)\n', (1391, 1436), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((1662, 1748), 'LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_trust_ncg', 'opt_lib.minimize_objective_trust_ncg', (['model.objective', 'init_x'], {'precondition': '(False)'}), '(model.objective, init_x, precondition=\n False)\n', (1698, 1748), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((2007, 2068), 'LinearResponseVariationalBayes.OptimizationUtils.set_objective_preconditioner', 'opt_lib.set_objective_preconditioner', (['model.objective', 'init_x'], {}), '(model.objective, init_x)\n', (2043, 2068), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((2077, 2133), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['model.matrix', 'hessian'], {}), '(model.matrix, hessian)\n', (2110, 2133), True, 'import numpy.testing as np_test\n'), ((2163, 2238), 'LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_bfgs', 'opt_lib.minimize_objective_bfgs', (['model.objective', 'init_x'], {'precondition': '(True)'}), '(model.objective, init_x, precondition=True)\n', (2194, 2238), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((2356, 2441), 'LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_trust_ncg', 'opt_lib.minimize_objective_trust_ncg', (['model.objective', 'init_x'], {'precondition': '(True)'}), '(model.objective, init_x, precondition=True\n )\n', (2392, 2441), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((2619, 2638), 'autograd.numpy.zeros', 'np.zeros', (['model.dim'], {}), '(model.dim)\n', (2627, 2638), True, 'import autograd.numpy as np\n'), ((2970, 3150), 'LinearResponseVariationalBayes.OptimizationUtils.repeatedly_optimize', 'opt_lib.repeatedly_optimize', (['model.objective', 'take_gradient_step', 'init_x'], {'initial_optimization_fun': 'initial_optimization', 'keep_intermediate_optimizations': '(True)', 'max_iter': '(1000)'}), '(model.objective, take_gradient_step, init_x,\n initial_optimization_fun=initial_optimization,\n keep_intermediate_optimizations=True, max_iter=1000)\n', (2997, 3150), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((3445, 3464), 'autograd.numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (3453, 3464), True, 'import autograd.numpy as np\n'), ((3481, 3500), 'autograd.numpy.array', 'np.array', (['[0, 1, 3]'], {}), '([0, 1, 3])\n', (3489, 3500), True, 'import autograd.numpy as np\n'), ((3517, 3536), 'autograd.numpy.array', 'np.array', (['[0, 3, 3]'], {}), '([0, 3, 3])\n', (3525, 3536), True, 'import autograd.numpy as np\n'), ((3870, 3904), 'LinearResponseVariationalBayes.OptimizationUtils.get_sym_matrix_inv_sqrt', 'opt_lib.get_sym_matrix_inv_sqrt', (['a'], {}), '(a)\n', (3901, 3904), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((4013, 4062), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['a', 'a_corrected'], {}), '(a, a_corrected)\n', (4046, 4062), True, 'import numpy.testing as np_test\n'), ((4132, 4149), 'autograd.numpy.linalg.eigh', 'np.linalg.eigh', (['a'], {}), '(a)\n', (4146, 4149), True, 'import autograd.numpy as np\n'), ((4309, 4358), 'LinearResponseVariationalBayes.OptimizationUtils.get_sym_matrix_inv_sqrt', 'opt_lib.get_sym_matrix_inv_sqrt', (['a'], {'ev_min': 'min_ev'}), '(a, ev_min=min_ev)\n', (4340, 4358), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((4463, 4521), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['min_ev', 'eig_val_test[0]'], {}), '(min_ev, eig_val_test[0])\n', (4496, 4521), True, 'import numpy.testing as np_test\n'), ((4530, 4596), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['eig_val[1:2]', 'eig_val_test[1:2]'], {}), '(eig_val[1:2], eig_val_test[1:2])\n', (4563, 4596), True, 'import numpy.testing as np_test\n'), ((4632, 4681), 'LinearResponseVariationalBayes.OptimizationUtils.get_sym_matrix_inv_sqrt', 'opt_lib.get_sym_matrix_inv_sqrt', (['a'], {'ev_max': 'max_ev'}), '(a, ev_max=max_ev)\n', (4663, 4681), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((4786, 4844), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['max_ev', 'eig_val_test[2]'], {}), '(max_ev, eig_val_test[2])\n', (4819, 4844), True, 'import numpy.testing as np_test\n'), ((4853, 4919), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['eig_val[0:1]', 'eig_val_test[0:1]'], {}), '(eig_val[0:1], eig_val_test[0:1])\n', (4886, 4919), True, 'import numpy.testing as np_test\n'), ((4955, 5019), 'LinearResponseVariationalBayes.OptimizationUtils.get_sym_matrix_inv_sqrt', 'opt_lib.get_sym_matrix_inv_sqrt', (['a'], {'ev_min': 'min_ev', 'ev_max': 'max_ev'}), '(a, ev_min=min_ev, ev_max=max_ev)\n', (4986, 5019), True, 'import LinearResponseVariationalBayes.OptimizationUtils as opt_lib\n'), ((5124, 5182), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['min_ev', 'eig_val_test[0]'], {}), '(min_ev, eig_val_test[0])\n', (5157, 5182), True, 'import numpy.testing as np_test\n'), ((5191, 5249), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['max_ev', 'eig_val_test[2]'], {}), '(max_ev, eig_val_test[2])\n', (5224, 5249), True, 'import numpy.testing as np_test\n'), ((5258, 5320), 'numpy.testing.assert_array_almost_equal', 'np_test.assert_array_almost_equal', (['eig_val[1]', 'eig_val_test[1]'], {}), '(eig_val[1], eig_val_test[1])\n', (5291, 5320), True, 'import numpy.testing as np_test\n'), ((483, 501), 'autograd.numpy.outer', 'np.outer', (['vec', 'vec'], {}), '(vec, vec)\n', (491, 501), True, 'import autograd.numpy as np\n'), ((504, 515), 'autograd.numpy.eye', 'np.eye', (['dim'], {}), '(dim)\n', (510, 515), True, 'import autograd.numpy as np\n'), ((916, 954), 'autograd.numpy.linalg.solve', 'np.linalg.solve', (['self.matrix', 'self.vec'], {}), '(self.matrix, self.vec)\n', (931, 954), True, 'import autograd.numpy as np\n'), ((3769, 3791), 'autograd.numpy.outer', 'np.outer', (['c_vec', 'c_vec'], {}), '(c_vec, c_vec)\n', (3777, 3791), True, 'import autograd.numpy as np\n'), ((3960, 3976), 'autograd.numpy.linalg.inv', 'np.linalg.inv', (['a'], {}), '(a)\n', (3973, 3976), True, 'import autograd.numpy as np\n'), ((4413, 4453), 'autograd.numpy.linalg.inv', 'np.linalg.inv', (['(a_inv_sqrt @ a_inv_sqrt.T)'], {}), '(a_inv_sqrt @ a_inv_sqrt.T)\n', (4426, 4453), True, 'import autograd.numpy as np\n'), ((4736, 4776), 'autograd.numpy.linalg.inv', 'np.linalg.inv', (['(a_inv_sqrt @ a_inv_sqrt.T)'], {}), '(a_inv_sqrt @ a_inv_sqrt.T)\n', (4749, 4776), True, 'import autograd.numpy as np\n'), ((5074, 5114), 'autograd.numpy.linalg.inv', 'np.linalg.inv', (['(a_inv_sqrt @ a_inv_sqrt.T)'], {}), '(a_inv_sqrt @ a_inv_sqrt.T)\n', (5087, 5114), True, 'import autograd.numpy as np\n'), ((3691, 3713), 'autograd.numpy.outer', 'np.outer', (['a_vec', 'a_vec'], {}), '(a_vec, a_vec)\n', (3699, 3713), True, 'import autograd.numpy as np\n'), ((3730, 3752), 'autograd.numpy.outer', 'np.outer', (['b_vec', 'b_vec'], {}), '(b_vec, b_vec)\n', (3738, 3752), True, 'import autograd.numpy as np\n')]
|
from MyAIGuide.data import GoogleFitDataTCX, DATA_DIR, get_google_fit_steps, collect_activities_from_dir, get_google_fit_activities
import pandas as pd
import numpy as np
TEST_PARTICIPANT = DATA_DIR / 'Participant2Anonymized'
TCX_FILE = "2018-11-05T16_46_19-05_00_PT17M6S_Marche à pied.tcx"
TCX_DIR = DATA_DIR / "Participant1" / "GoogleFitData" / "smartphone1" / "Activités"
TEST_TCX = TCX_DIR / TCX_FILE
i = pd.date_range("2015-11-19", periods=1550, freq="1D")
sLength = len(i)
empty = pd.Series(np.zeros(sLength)).values
d = {
"steps": empty,
"denivelation": empty,
"kneePain": empty,
"handsAndFingerPain": empty,
"foreheadAndEyesPain": empty,
"forearmElbowPain": empty,
"aroundEyesPain": empty,
"shoulderNeckPain": empty,
"movesSteps": empty,
"googlefitSteps": empty,
"elevation_gain": empty,
"elevation_loss": empty,
"calories": empty,
}
data = pd.DataFrame(data=d, index=i)
def test_get_google_fit_steps():
new_data = get_google_fit_steps(fname=TEST_PARTICIPANT, data=data)
assert isinstance(new_data, pd.DataFrame)
assert sum(new_data["googlefitSteps"]) > 0
def test_google_fit_data_tcx():
instance = GoogleFitDataTCX(TEST_TCX)
def test_collect_activities_from_dir():
df = collect_activities_from_dir(TCX_DIR)
assert "calories", "elevation_gain" in df
assert "dateTime", "elevation_loss" in df
def test_get_google_fit_activities():
new_data = get_google_fit_activities(fname=TCX_DIR, data=data)
assert isinstance(new_data, pd.DataFrame)
assert sum(new_data["elevation_gain"]) > 0
assert sum(new_data["elevation_loss"]) > 0
assert sum(new_data["calories"]) > 0
|
[
"pandas.DataFrame",
"MyAIGuide.data.GoogleFitDataTCX",
"pandas.date_range",
"numpy.zeros",
"MyAIGuide.data.get_google_fit_steps",
"MyAIGuide.data.collect_activities_from_dir",
"MyAIGuide.data.get_google_fit_activities"
] |
[((412, 464), 'pandas.date_range', 'pd.date_range', (['"""2015-11-19"""'], {'periods': '(1550)', 'freq': '"""1D"""'}), "('2015-11-19', periods=1550, freq='1D')\n", (425, 464), True, 'import pandas as pd\n'), ((904, 933), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd', 'index': 'i'}), '(data=d, index=i)\n', (916, 933), True, 'import pandas as pd\n'), ((984, 1039), 'MyAIGuide.data.get_google_fit_steps', 'get_google_fit_steps', ([], {'fname': 'TEST_PARTICIPANT', 'data': 'data'}), '(fname=TEST_PARTICIPANT, data=data)\n', (1004, 1039), False, 'from MyAIGuide.data import GoogleFitDataTCX, DATA_DIR, get_google_fit_steps, collect_activities_from_dir, get_google_fit_activities\n'), ((1182, 1208), 'MyAIGuide.data.GoogleFitDataTCX', 'GoogleFitDataTCX', (['TEST_TCX'], {}), '(TEST_TCX)\n', (1198, 1208), False, 'from MyAIGuide.data import GoogleFitDataTCX, DATA_DIR, get_google_fit_steps, collect_activities_from_dir, get_google_fit_activities\n'), ((1260, 1296), 'MyAIGuide.data.collect_activities_from_dir', 'collect_activities_from_dir', (['TCX_DIR'], {}), '(TCX_DIR)\n', (1287, 1296), False, 'from MyAIGuide.data import GoogleFitDataTCX, DATA_DIR, get_google_fit_steps, collect_activities_from_dir, get_google_fit_activities\n'), ((1444, 1495), 'MyAIGuide.data.get_google_fit_activities', 'get_google_fit_activities', ([], {'fname': 'TCX_DIR', 'data': 'data'}), '(fname=TCX_DIR, data=data)\n', (1469, 1495), False, 'from MyAIGuide.data import GoogleFitDataTCX, DATA_DIR, get_google_fit_steps, collect_activities_from_dir, get_google_fit_activities\n'), ((500, 517), 'numpy.zeros', 'np.zeros', (['sLength'], {}), '(sLength)\n', (508, 517), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
import numpy as np
from functools import partial
class TailBoost:
def __init__(self, urm):
self.weights = list()
self.urm = urm
self.__create_weights()
self.update_scores = partial(np.vectorize(lambda weight, score: score * weight), self.weights)
def __create_weights(self):
num_users = self.urm.shape[0]
num_items = self.urm.shape[1]
item_popularity = self.urm.sum(axis=0).squeeze()
for item_id in range(num_items):
m_j = item_popularity[0, item_id] # WARNING: THIS CAN BE 0!!!
if m_j == 0:
m_j = 1
self.weights.append(np.log(num_users / m_j))
self.weights = np.array(self.weights)
|
[
"numpy.array",
"numpy.log",
"numpy.vectorize"
] |
[((726, 748), 'numpy.array', 'np.array', (['self.weights'], {}), '(self.weights)\n', (734, 748), True, 'import numpy as np\n'), ((244, 294), 'numpy.vectorize', 'np.vectorize', (['(lambda weight, score: score * weight)'], {}), '(lambda weight, score: score * weight)\n', (256, 294), True, 'import numpy as np\n'), ((678, 701), 'numpy.log', 'np.log', (['(num_users / m_j)'], {}), '(num_users / m_j)\n', (684, 701), True, 'import numpy as np\n')]
|
import numpy as np
import matplotlib.pyplot as plt
from signals.fourier import fourier
from signals.analysis import ClimbingAgent
def test_fourier():
fs = 100
length = 100.0
n = fs * length
x = np.linspace(0., length, n)
y = np.sin(10. * 2. * np.pi * x)
y += 0.75 * np.sin(20. * 2. * np.pi * x)
y += 0.5 * np.sin(30. * 2. * np.pi * x)
y += 0.25 * np.sin(40. * 2. * np.pi * x)
xf, yf = fourier(y, fs)
plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.subplot(2, 1, 2)
plt.plot(xf, yf)
plt.show()
def test_agent():
values = [1, 2, 3, 2, 1]
delta = 2
agent = ClimbingAgent(values, 4, delta, 1)
print([i for i in agent.range()])
print([i for i in agent.range(True)])
agent.climb()
print([i for i in agent.range()])
print([i for i in agent.range(True)])
print([i for i in range(delta, 15, delta * 2 + 1)])
if __name__ == "__main__":
# test_fourier()
test_agent()
|
[
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"signals.analysis.ClimbingAgent",
"numpy.sin",
"signals.fourier.fourier",
"numpy.linspace"
] |
[((214, 241), 'numpy.linspace', 'np.linspace', (['(0.0)', 'length', 'n'], {}), '(0.0, length, n)\n', (225, 241), True, 'import numpy as np\n'), ((249, 279), 'numpy.sin', 'np.sin', (['(10.0 * 2.0 * np.pi * x)'], {}), '(10.0 * 2.0 * np.pi * x)\n', (255, 279), True, 'import numpy as np\n'), ((425, 439), 'signals.fourier.fourier', 'fourier', (['y', 'fs'], {}), '(y, fs)\n', (432, 439), False, 'from signals.fourier import fourier\n'), ((445, 465), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (456, 465), True, 'import matplotlib.pyplot as plt\n'), ((470, 484), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (478, 484), True, 'import matplotlib.pyplot as plt\n'), ((489, 509), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (500, 509), True, 'import matplotlib.pyplot as plt\n'), ((514, 530), 'matplotlib.pyplot.plot', 'plt.plot', (['xf', 'yf'], {}), '(xf, yf)\n', (522, 530), True, 'import matplotlib.pyplot as plt\n'), ((535, 545), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (543, 545), True, 'import matplotlib.pyplot as plt\n'), ((621, 655), 'signals.analysis.ClimbingAgent', 'ClimbingAgent', (['values', '(4)', 'delta', '(1)'], {}), '(values, 4, delta, 1)\n', (634, 655), False, 'from signals.analysis import ClimbingAgent\n'), ((294, 324), 'numpy.sin', 'np.sin', (['(20.0 * 2.0 * np.pi * x)'], {}), '(20.0 * 2.0 * np.pi * x)\n', (300, 324), True, 'import numpy as np\n'), ((338, 368), 'numpy.sin', 'np.sin', (['(30.0 * 2.0 * np.pi * x)'], {}), '(30.0 * 2.0 * np.pi * x)\n', (344, 368), True, 'import numpy as np\n'), ((383, 413), 'numpy.sin', 'np.sin', (['(40.0 * 2.0 * np.pi * x)'], {}), '(40.0 * 2.0 * np.pi * x)\n', (389, 413), True, 'import numpy as np\n')]
|
import numpy as np
'''
Label any new implementation of von-Zeipel cylinders in another spacetime
by prefixing VZC, followed by the id of the spacetime.
'''
class VZCBase():
def __init__(self, l, r0, r_range=(2, 18),
num=10000, verbose=True):
self.r_in, self.r_out = r_range
self.num = num
self.r = np.linspace(self.r_in, self.r_out,
num=self.num, endpoint=True)
self.verbose = verbose
self.l = l
self.r0 = r0
def compute_theta(self):
raise NotImplementedError()
def horizon(self, theta):
raise NotImplementedError()
def get_r(self):
return self.r
def get_r0(self):
return self.r0
def set_r0(self, r_new):
self.r0 = r_new
|
[
"numpy.linspace"
] |
[((345, 408), 'numpy.linspace', 'np.linspace', (['self.r_in', 'self.r_out'], {'num': 'self.num', 'endpoint': '(True)'}), '(self.r_in, self.r_out, num=self.num, endpoint=True)\n', (356, 408), True, 'import numpy as np\n')]
|
# Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
def _string_lists(alphabet=None):
return st.lists(
elements=st.text(alphabet=alphabet, average_size=3),
min_size=0,
max_size=3)
class TestStringOps(hu.HypothesisTestCase):
@given(strings=_string_lists())
def test_string_prefix(self, strings):
length = 3
# although we are utf-8 encoding below to avoid python exceptions,
# StringPrefix op deals with byte-length prefixes, which may produce
# an invalid utf-8 string. The goal here is just to avoid python
# complaining about the unicode -> str conversion.
strings = np.array(
[a.encode('utf-8') for a in strings], dtype=np.object
)
def string_prefix_ref(strings):
return (
np.array([a[:length] for a in strings], dtype=object),
)
op = core.CreateOperator(
'StringPrefix',
['strings'],
['stripped'],
length=length)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_prefix_ref)
@given(strings=_string_lists())
def test_string_suffix(self, strings):
length = 3
strings = np.array(
[a.encode('utf-8') for a in strings], dtype=np.object
)
def string_suffix_ref(strings):
return (
np.array([a[-length:] for a in strings], dtype=object),
)
op = core.CreateOperator(
'StringSuffix',
['strings'],
['stripped'],
length=length)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_suffix_ref)
@given(strings=st.text(alphabet=['a', 'b'], average_size=3))
def test_string_starts_with(self, strings):
prefix = 'a'
strings = np.array(
[str(a) for a in strings], dtype=np.object
)
def string_starts_with_ref(strings):
return (
np.array([a.startswith(prefix) for a in strings], dtype=bool),
)
op = core.CreateOperator(
'StringStartsWith',
['strings'],
['bools'],
prefix=prefix)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_starts_with_ref)
@given(strings=st.text(alphabet=['a', 'b'], average_size=3))
def test_string_ends_with(self, strings):
suffix = 'a'
strings = np.array(
[str(a) for a in strings], dtype=np.object
)
def string_ends_with_ref(strings):
return (
np.array([a.endswith(suffix) for a in strings], dtype=bool),
)
op = core.CreateOperator(
'StringEndsWith',
['strings'],
['bools'],
suffix=suffix)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_ends_with_ref)
if __name__ == "__main__":
import unittest
unittest.main()
|
[
"unittest.main",
"caffe2.python.core.CreateOperator",
"hypothesis.strategies.text",
"numpy.array"
] |
[((4080, 4095), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4093, 4095), False, 'import unittest\n'), ((1833, 1910), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""StringPrefix"""', "['strings']", "['stripped']"], {'length': 'length'}), "('StringPrefix', ['strings'], ['stripped'], length=length)\n", (1852, 1910), False, 'from caffe2.python import core\n'), ((2454, 2531), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""StringSuffix"""', "['strings']", "['stripped']"], {'length': 'length'}), "('StringSuffix', ['strings'], ['stripped'], length=length)\n", (2473, 2531), False, 'from caffe2.python import core\n'), ((3112, 3190), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""StringStartsWith"""', "['strings']", "['bools']"], {'prefix': 'prefix'}), "('StringStartsWith', ['strings'], ['bools'], prefix=prefix)\n", (3131, 3190), False, 'from caffe2.python import core\n'), ((3770, 3846), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""StringEndsWith"""', "['strings']", "['bools']"], {'suffix': 'suffix'}), "('StringEndsWith', ['strings'], ['bools'], suffix=suffix)\n", (3789, 3846), False, 'from caffe2.python import core\n'), ((1056, 1098), 'hypothesis.strategies.text', 'st.text', ([], {'alphabet': 'alphabet', 'average_size': '(3)'}), '(alphabet=alphabet, average_size=3)\n', (1063, 1098), True, 'import hypothesis.strategies as st\n'), ((2730, 2774), 'hypothesis.strategies.text', 'st.text', ([], {'alphabet': "['a', 'b']", 'average_size': '(3)'}), "(alphabet=['a', 'b'], average_size=3)\n", (2737, 2774), True, 'import hypothesis.strategies as st\n'), ((3394, 3438), 'hypothesis.strategies.text', 'st.text', ([], {'alphabet': "['a', 'b']", 'average_size': '(3)'}), "(alphabet=['a', 'b'], average_size=3)\n", (3401, 3438), True, 'import hypothesis.strategies as st\n'), ((1750, 1803), 'numpy.array', 'np.array', (['[a[:length] for a in strings]'], {'dtype': 'object'}), '([a[:length] for a in strings], dtype=object)\n', (1758, 1803), True, 'import numpy as np\n'), ((2370, 2424), 'numpy.array', 'np.array', (['[a[-length:] for a in strings]'], {'dtype': 'object'}), '([a[-length:] for a in strings], dtype=object)\n', (2378, 2424), True, 'import numpy as np\n')]
|
import numpy as np
from . import compute_max_angle
def gensk97(N):
# See http://dx.doi.org/10.1016/j.jsb.2006.06.002 and references therein
N = int(N)
h = -1.0 + (2.0/(N-1))*np.arange(0,N)
theta = np.arccos(h)
phi_base = np.zeros_like(theta)
phi_base[1:(N-1)] = ((3.6/np.sqrt(N))/np.sqrt(1 - h[1:(N-1)]**2))
phi = np.cumsum(phi_base)
phi[0] = 0
phi[N-1] = 0
stheta = np.sin(theta)
dirs = np.vstack([np.cos(phi)*stheta, np.sin(phi)*stheta, np.cos(theta)]).T
return dirs
class SK97Quadrature:
@staticmethod
def compute_degree(N,rad,usFactor):
ang = compute_max_angle(N,rad,usFactor)
return SK97Quadrature.get_degree(ang)
@staticmethod
def get_degree(maxAngle):
degree = np.ceil((3.6/maxAngle)**2)
cmaxAng = 3.6/np.sqrt(degree)
return degree, cmaxAng
@staticmethod
def get_quad_points(degree,sym = None):
verts = gensk97(degree)
p = np.array(verts)
w = (4.0*np.pi/len(verts)) * np.ones(len(verts))
if sym is None:
return p, w
else:
validPs = sym.in_asymunit(p)
return p[validPs], w[validPs] * (np.sum(w) / np.sum(w[validPs]))
|
[
"numpy.zeros_like",
"numpy.sum",
"numpy.ceil",
"numpy.cumsum",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.cos",
"numpy.arccos",
"numpy.sqrt"
] |
[((214, 226), 'numpy.arccos', 'np.arccos', (['h'], {}), '(h)\n', (223, 226), True, 'import numpy as np\n'), ((242, 262), 'numpy.zeros_like', 'np.zeros_like', (['theta'], {}), '(theta)\n', (255, 262), True, 'import numpy as np\n'), ((343, 362), 'numpy.cumsum', 'np.cumsum', (['phi_base'], {}), '(phi_base)\n', (352, 362), True, 'import numpy as np\n'), ((409, 422), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (415, 422), True, 'import numpy as np\n'), ((305, 333), 'numpy.sqrt', 'np.sqrt', (['(1 - h[1:N - 1] ** 2)'], {}), '(1 - h[1:N - 1] ** 2)\n', (312, 333), True, 'import numpy as np\n'), ((761, 791), 'numpy.ceil', 'np.ceil', (['((3.6 / maxAngle) ** 2)'], {}), '((3.6 / maxAngle) ** 2)\n', (768, 791), True, 'import numpy as np\n'), ((965, 980), 'numpy.array', 'np.array', (['verts'], {}), '(verts)\n', (973, 980), True, 'import numpy as np\n'), ((187, 202), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (196, 202), True, 'import numpy as np\n'), ((293, 303), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (300, 303), True, 'import numpy as np\n'), ((810, 825), 'numpy.sqrt', 'np.sqrt', (['degree'], {}), '(degree)\n', (817, 825), True, 'import numpy as np\n'), ((485, 498), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (491, 498), True, 'import numpy as np\n'), ((445, 456), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (451, 456), True, 'import numpy as np\n'), ((465, 476), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (471, 476), True, 'import numpy as np\n'), ((1187, 1196), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (1193, 1196), True, 'import numpy as np\n'), ((1199, 1217), 'numpy.sum', 'np.sum', (['w[validPs]'], {}), '(w[validPs])\n', (1205, 1217), True, 'import numpy as np\n')]
|
# Python Script to initialize a Peripheral Architecture:
# Developed by <NAME> as part of the Piranhas Toolkit
# Questions & bugs: <EMAIL>
import numpy as np
from piranhas import *
import math
# Run Intialization Parameters:
param = param_init_all()
scale = param.scale
fovea = param.fovea
e0_in_deg = param.e0_in_deg
visual_field_radius_in_deg = param.visual_field_radius_in_deg
deg_per_pixel = param.deg_per_pixel
# Get Peripheral Architecture Parameters
# Given the scale, compute the N_e and N_theta parameters.
# You can also uncomment this line and input any values for N_e and N_theta.
# Please refer to Freeman & Simoncelli, 2011 to check what values of scale
# are biologically plausible for V1 and V2 receptive field sizes.
N_param = get_pooling_parameters(scale,e0_in_deg,visual_field_radius_in_deg,deg_per_pixel)
N_e = N_param[0]
N_theta = N_param[1]
#visual flag?
visual = 0
# The peripheral_regions data structure allows you to do anything you want with the pooling regions.
peripheral_filters = generate_pooling_regios_vector_smooth(deg_per_pixel,N_e,N_theta,visual_field_radius_in_deg,fovea,e0_in_deg,visual)
##################################
# Compute Peripheral Mask Stream #
##################################
# size might have changed after removing peripheral regions inside fovea
param_check = np.shape(peripheral_filters.regions)
N_theta = param_check[0]
N_e = param_check[1]
peri_height = param_check[2]
peri_width = param_check[3]
select_mask_stream = np.empty((N_theta*N_e,peri_height,peri_width),dtype=object)
select_mask_label = np.zeros((peri_height,peri_width))
for z in range(1,N_theta*N_e):
i1 = np.mod(z,N_theta)
if i1==0:
i1 = N_theta
j1 = np.round(np.floor((z-0.1)/N_theta)+1)
select_mask_stream[z-1,:,:] = np.squeeze(peripheral_filters.regions[i1-1,j1-1,:,:])
select_loc = np.where(select_mask_stream[z-1,:,:]>0)
select_mask_label[select_loc[0],select_loc[1]] = z-1
###################
# Get Foveal Mask #
###################
dist_mask = np.empty(N_theta)
for i in range(0,N_theta):
point_vector = np.empty(np.shape(peripheral_filters.offsets_r[i][0])[0])
for j in range(0,np.shape(peripheral_filters.offsets_r[i][0])[0]):
#Compute L2 norm (euclidean distance from center of fixation)
point_buff = np.linalg.norm([peripheral_filters.offsets_r[i][0][j],peripheral_filters.offsets_c[i][0][j]])
point_vector[j] = abs(point_buff)
dist_mask[i] = min(point_vector)
del point_vector
# Compute Foveal Radius
foveal_radius = np.ceil(np.mean(dist_mask))
foveal_radius_px = foveal_radius
foveal_radius_deg = foveal_radius * deg_per_pixel
foveal_mask = np.zeros((peri_height,peri_width))
mid_point_w = np.round(peri_width/2)
mid_point_h = np.round(peri_height/2)
for i in range(0,peri_width):
for j in range(0,peri_height):
if np.sqrt(pow( i-mid_point_w,2) + pow(j-mid_point_h,2)) <= foveal_radius:
foveal_mask[j][i] = 1
######################
# Create Filter bank #
######################
# To do.
# We have to add the gabor filter bank here.
visual_mask = 0
####################################
# Create list of Foveal_parameters #
####################################
foveal_param = foveal_param_init_all()
foveal_param.N_theta = N_theta;
foveal_param.N_e = N_e;
#foveal_param.wave_num = wave_num;
#foveal_param.orien = orien;
foveal_param.peri_height = peri_height;
foveal_param.peri_width = peri_width;
foveal_param.select_mask_stream = select_mask_stream;
foveal_param.select_mask_label = select_mask_label;
foveal_param.foveal_mask = foveal_mask;
foveal_param.foveal_radius_px = foveal_radius_px;
foveal_param.foveal_radius_deg = foveal_radius_deg;
#foveal_param.filter_bank = filter_bank;
#foveal_param.filter_bank_stream = filter_bank_stream;
foveal_param.peripheral_filters = peripheral_filters;
foveal_param.visual_mask = visual_mask;
foveal_param.deg_per_pixel = deg_per_pixel;
foveal_param.monitor.pixel_res_width = param.pixel_res_width;
foveal_param.monitor.pixel_res_height = param.pixel_res_height;
foveal_param.monitor.mon_width = param.mon_width;
foveal_param.monitor.mon_height = param.mon_height;
foveal_param.monitor.view_dist = param.view_dist;
|
[
"numpy.empty",
"numpy.floor",
"numpy.zeros",
"numpy.mod",
"numpy.shape",
"numpy.where",
"numpy.mean",
"numpy.linalg.norm",
"numpy.squeeze",
"numpy.round"
] |
[((1329, 1365), 'numpy.shape', 'np.shape', (['peripheral_filters.regions'], {}), '(peripheral_filters.regions)\n', (1337, 1365), True, 'import numpy as np\n'), ((1492, 1556), 'numpy.empty', 'np.empty', (['(N_theta * N_e, peri_height, peri_width)'], {'dtype': 'object'}), '((N_theta * N_e, peri_height, peri_width), dtype=object)\n', (1500, 1556), True, 'import numpy as np\n'), ((1572, 1607), 'numpy.zeros', 'np.zeros', (['(peri_height, peri_width)'], {}), '((peri_height, peri_width))\n', (1580, 1607), True, 'import numpy as np\n'), ((2004, 2021), 'numpy.empty', 'np.empty', (['N_theta'], {}), '(N_theta)\n', (2012, 2021), True, 'import numpy as np\n'), ((2621, 2656), 'numpy.zeros', 'np.zeros', (['(peri_height, peri_width)'], {}), '((peri_height, peri_width))\n', (2629, 2656), True, 'import numpy as np\n'), ((2671, 2695), 'numpy.round', 'np.round', (['(peri_width / 2)'], {}), '(peri_width / 2)\n', (2679, 2695), True, 'import numpy as np\n'), ((2708, 2733), 'numpy.round', 'np.round', (['(peri_height / 2)'], {}), '(peri_height / 2)\n', (2716, 2733), True, 'import numpy as np\n'), ((1645, 1663), 'numpy.mod', 'np.mod', (['z', 'N_theta'], {}), '(z, N_theta)\n', (1651, 1663), True, 'import numpy as np\n'), ((1766, 1826), 'numpy.squeeze', 'np.squeeze', (['peripheral_filters.regions[i1 - 1, j1 - 1, :, :]'], {}), '(peripheral_filters.regions[i1 - 1, j1 - 1, :, :])\n', (1776, 1826), True, 'import numpy as np\n'), ((1836, 1881), 'numpy.where', 'np.where', (['(select_mask_stream[z - 1, :, :] > 0)'], {}), '(select_mask_stream[z - 1, :, :] > 0)\n', (1844, 1881), True, 'import numpy as np\n'), ((2501, 2519), 'numpy.mean', 'np.mean', (['dist_mask'], {}), '(dist_mask)\n', (2508, 2519), True, 'import numpy as np\n'), ((2270, 2369), 'numpy.linalg.norm', 'np.linalg.norm', (['[peripheral_filters.offsets_r[i][0][j], peripheral_filters.offsets_c[i][0][j]]'], {}), '([peripheral_filters.offsets_r[i][0][j], peripheral_filters.\n offsets_c[i][0][j]])\n', (2284, 2369), True, 'import numpy as np\n'), ((1706, 1735), 'numpy.floor', 'np.floor', (['((z - 0.1) / N_theta)'], {}), '((z - 0.1) / N_theta)\n', (1714, 1735), True, 'import numpy as np\n'), ((2074, 2118), 'numpy.shape', 'np.shape', (['peripheral_filters.offsets_r[i][0]'], {}), '(peripheral_filters.offsets_r[i][0])\n', (2082, 2118), True, 'import numpy as np\n'), ((2141, 2185), 'numpy.shape', 'np.shape', (['peripheral_filters.offsets_r[i][0]'], {}), '(peripheral_filters.offsets_r[i][0])\n', (2149, 2185), True, 'import numpy as np\n')]
|
#!/usr/bin/python
import os
import sys
import numpy
import datetime
import re
# Probability of correctness
fq_prob_list = [0.725,
0.9134,
0.936204542,
0.949544344,
0.959009084,
0.966350507,
0.972348887,
0.977420444,
0.981813627,
0.985688689,
0.98915505,
0.992290754,
0.995153429,
0.997786834,
0.999999999]
fq_char_list = [str(unichr(min(int(33 - 10 * numpy.math.log10(1 -p)), 73))) for p in fq_prob_list]
NUM_FQ_CHAR = len(fq_char_list) - 1
def log_print(print_str):
os.system("echo '" + str(print_str) + "'")
################################################################################
# Separate the path to a file from the filename (filepath -> path,filename)
def GetPathAndName(pathfilename):
ls=pathfilename.split('/')
filename=ls[-1]
if len(ls)==1:
return '',filename
path='/'.join(ls[0:-1])+'/'
return path, filename
# Compute the complementary sequence from a base sequence
def compleseq(seq):
newseq=""
for base in seq:
if base=="A":
base="T"
elif base=="C":
base="G"
elif base=="G":
base="C"
elif base=="T":
base="A"
elif base=="-":
base="-"
elif base=="a":
base="t"
elif base=="c":
base="g"
elif base=="g":
base="c"
elif base=="t":
base="a"
newseq=base+newseq
return newseq
def lower_mismatch_bowtie(SR_seq,mismatch):
if mismatch == ['']:
return SR_seq
SR_seq_list = list(SR_seq)
for c in mismatch:
pos = int(c.split(':')[0])
SR_seq_list[pos] = SR_seq_list[pos].lower()
return ''.join(SR_seq_list)
# Turn a cps repetition count list into a complete list (insert 1 for things which aren't repeated)
def expandidx_list(line):
L_p_seq_ls = []
ls = line.strip().split('\t')
if (len(ls)<2):
L_ls=[]
p_ls=[]
else:
p_ls = ls[0].split(',')
L_ls = ls[1].split(',')
temp_p=-1
i=0
for p in p_ls:
L_p_seq_ls.extend( [onestr]*(int(p)-temp_p-1))
L_p_seq_ls.append(L_ls[i])
temp_p=int(p)
i+=1
return L_p_seq_ls
################################################################################
# Compute majority sequence from the candidates
def optimize_seq(temp_candidate_ls):
result = ""
max_n = 0
temp_candidate_set = set(temp_candidate_ls)
for temp_candidate in temp_candidate_set:
if temp_candidate!='' :
n = temp_candidate_ls.count(temp_candidate)
if n > max_n:
result = temp_candidate
max_n =n
return[ result, max_n ]
################################################################################
# Uncompress a cps back to the original sequence
def uncompress_seq(temp_SR_idx_seq_list,seq):
result = ""
i=0
for s in seq:
result=result+s*int(temp_SR_idx_seq_list[i])
i+=1
return result
def Convertord(SR_idx_seq_list):
result = ''
for s in SR_idx_seq_list:
result = result + chr(int(s)+48)
return result
################################################################################
if len(sys.argv) >= 2:
LR_SR_mapping_filename = sys.argv[1]
LR_readname_filename = sys.argv[2]
else:
log_print("usage :./correct_nonredundant.py LR_SR.map.aa_tmp LR.fa.readname")
log_print("usage : python correct_nonredundant.py LR_SR.map.aa_tmp LR.fa.readname")
sys.exit(1)
LR_read_name_list = [""]
readname_file = open(LR_readname_filename,'r')
i = 0
# Load all the long read names
for line in readname_file:
i = i + 1
fields = line.strip().split()
read_int = int(fields[0])
for j in range(i - read_int):
# Fill in missing readname entries
LR_read_name_list.append("")
LR_read_name_list.append(fields[1])
path,filename = GetPathAndName(LR_SR_mapping_filename)
tmp = open(LR_SR_mapping_filename,'r')
full_read_file=open(path + 'full_'+ filename,'w')
corrected_read_file=open(path + 'corrected_'+ filename,'w')
corrected_read_fq_file=open(path + 'corrected_'+ filename +'.fq','w')
uncorrected_read_file = open(path + 'uncorrected_'+ filename,'w')
zerostr="0"
onestr="1"
t0 = datetime.datetime.now()
# For each long read, perform correction
for tmp_line in tmp:
# Separate the tmp line into it's components
tmp_ls = tmp_line.split('yue')
LR_seq = tmp_ls[0]
LR_idx_seq = tmp_ls[1]
SR_ls_ls = tmp_ls[2].split(';')
read_name = tmp_ls[3]
read_int = int(read_name[0:])
if tmp_ls[2] == '':
log_print(read_name + "\tno alignment")
continue
ls_SR_seq = tmp_ls[4].split('kinfai')
ls_SR_idx_seq = tmp_ls[5].split('kinfai')
start_pt_ls = []
NSR_ls = []
mismatch_ls = []
indel_pt_set_ls = []
insert_pt_ls_ls = []
del_pt_list = []
del_pt_set=set()
crt_pt_ls = set()
crt_pt_dict={}
all_seq_idx_list=[]
all_del_seq_list=[]
temp_all_seq_idx=[]
LR_seq = LR_seq.strip()+'ZX'*25 # extend the long read with ZX in order to handle short reads which go past the end of the long read
L_LR_seq = len(LR_seq)
a=L_LR_seq-1
LR_idx_seq_ls = LR_idx_seq.strip().split('\t')
if len(LR_idx_seq_ls) > 1:
p_ls = LR_idx_seq_ls[0].strip().split(',')
else:
p_ls=[]
crt_pt_ls.update(set(numpy.array(p_ls,dtype='int')))
crt_pt_ls.update(set(range(a-50,a) ))
#########################################################################################################
end_pt_ls = []
i=0
# For each short read mapped to this long read
coverage_list = [0] * L_LR_seq
for SR in SR_ls_ls:
SR_ls = SR.split(',')
pos = int(SR_ls[1])
pos -=1
if pos<0:
i+=1
continue
start_pt_ls.append(pos)
SR_seq = ls_SR_seq[i]
L =len(SR_seq.strip())
NSR_ls.append(SR_ls[0])
mismatch= SR_ls[2]
insert_pt_set= set()
temp_del_dt= {}
indel_pt_set =set()
# If there's a mismatch (of any kind) between the SR and LR
if not mismatch == '':
mismatch_pos_ls = map(int, re.findall(r'\d+',mismatch))
mismatch_type_ls = re.findall('>|\+|-', mismatch)
mismatch_seq_ls = re.findall('\w+', mismatch)
j=0
# For all of the mismatches
for mismatch_type in mismatch_type_ls:
# Convert the CIGAR information into an internal representation by position
if mismatch_type == '+':
del_pt = mismatch_pos_ls[j] + pos
del_pt_set.add(del_pt)
temp_del_dt[mismatch_pos_ls[j]] = mismatch_seq_ls[2*j+1]
indel_pt_set.add(mismatch_pos_ls[j])
L -= len(mismatch_seq_ls[2*j+1])
elif mismatch_type == '-':
L_insert = len(mismatch_seq_ls[2*j+1])
L += L_insert
if L_insert>1:
log_print("warning inert >2 bp")
insert_pt_set.add(mismatch_pos_ls[j])
indel_pt_set.add(mismatch_pos_ls[j])
else:
p_ls.append(mismatch_pos_ls[j])
j+=1
# Compute coverage information (percentage of LR covered by SR)
end_pt_ls.append(pos + L - 1)
n_rep = int(SR_ls[0].split('_')[1])
coverage_list[pos : (pos + L)] = [(coverage_list[k] + n_rep) for k in range(pos, pos + L)]
insert_pt_ls_ls.append(insert_pt_set)
del_pt_list.append(temp_del_dt)
indel_pt_set_ls.append(indel_pt_set)
i+=1
start_pt =min(start_pt_ls)
########################################################################################################
if start_pt_ls == []:
log_print(read_name)
log_print("no alignments, empty")
continue
#########################################################################################################
# Clip the 3 and 5 prime ends of the long read, which are uncovered by short reads
temp_LR_idx_seq_list = expandidx_list(LR_idx_seq)
temp_LR_idx_seq_list.extend( [onestr]*( len(LR_seq) - len(temp_LR_idx_seq_list)) ) # handle the ZX stuff
#max_start_pt100 = 100 + max(start_pt_ls)
end_pt = max(end_pt_ls)+1
five_end_seq = uncompress_seq(temp_LR_idx_seq_list[0:(start_pt+1)], LR_seq[0:(start_pt+1)]) # Note: the end and start pos of SRs are not used for correction
three_end_seq=""
if ((end_pt-1) < (len(LR_seq)-50)):
three_end_seq = uncompress_seq(temp_LR_idx_seq_list[(end_pt-1):(len(LR_seq)-50)], LR_seq[(end_pt-1):(len(LR_seq)-50)])
temp_LR_seq = LR_seq[start_pt:end_pt].strip()
coverage_list = [ fq_char_list[min( coverage_list[i], NUM_FQ_CHAR)] for i in range(start_pt, end_pt)]
L_temp_LR_seq = len(temp_LR_seq)
temp_LR_idx_seq_list = temp_LR_idx_seq_list[start_pt:end_pt]
temp_LR_idx_seq_list.extend( [onestr]*( L_temp_LR_seq - len(temp_LR_idx_seq_list)) )
uncorrected_read_file.write('>' + LR_read_name_list[read_int] +'\n')
# Note: the end and start pos of SRs are not used for correction
L_temp_LR_idx_seq_list = len(temp_LR_idx_seq_list)
uncorrected_read_file.write(uncompress_seq(temp_LR_idx_seq_list[1:(L_temp_LR_idx_seq_list-1)], temp_LR_seq[1:(L_temp_LR_idx_seq_list-1)]).replace('X','').replace('Z','') +'\n')
#########################################################################################################
i=0
# Iterate over the short reads, make the short read as long as the long read (TODO: HOLY SCHAMOLY!)
for NSR in NSR_ls:
insert_pt_set = insert_pt_ls_ls[i]
temp_del_dt = del_pt_list[i]
indel_pt_set = indel_pt_set_ls[i]
len_space = start_pt_ls[i]
SR_seq = ls_SR_seq[i]
SR_idx_seq = ls_SR_idx_seq[i]
i+=1
n_rep = int(NSR.split('_')[1])
ls = SR_idx_seq.strip().split('\t')
if len(ls)==0:
p_ls=[]
else:
p_ls = ls[0].split(',')
SR_idx_seq_list = expandidx_list(SR_idx_seq)
SR_idx_seq_list.extend([onestr]*(len(SR_seq)-len(SR_idx_seq_list)))
if NSR[0]=='-':
SR_seq = compleseq(SR_seq)
SR_idx_seq_list = SR_idx_seq_list[::-1]
SR_seq_list=list(SR_seq)
SR_idx_seq_list[0]=zerostr
SR_idx_seq_list[-1]= zerostr
SR_del_seq_list = ['=']*len(SR_seq_list) # Equals sign is used to indicate a deletion
deleted_idx_list=[]
indel_pt_ls = list(indel_pt_set)
indel_pt_ls.sort()
# Go over all the indel points for this short read and rewrite them to use the long read position
for pt in indel_pt_ls:
if pt in insert_pt_set:
SR_seq_list.insert(pt-1,'-')
SR_idx_seq_list.insert(pt-1,onestr)
SR_del_seq_list.insert(pt-1,'=')
if temp_del_dt.has_key(pt):
L=len(temp_del_dt[pt])
pt-=1
del SR_seq_list[pt:pt+L]
del SR_del_seq_list[pt:pt+L]
SR_del_seq_list[pt-1] = uncompress_seq(SR_idx_seq_list[pt:pt+L], temp_del_dt[pt+1])
del SR_idx_seq_list[pt:pt+L]
SR_del_seq = ''.join(SR_del_seq_list)
###############
(I_ls,) = numpy.nonzero(numpy.array(SR_idx_seq_list,dtype='int')>1)
I_ls = len_space + I_ls
crt_pt_ls.update(set(I_ls))
#############DISPLAY#######################################
# Add everything we can learn from this SR into the master correction list
crt_pt_ls.update( set(numpy.array(list(insert_pt_set),dtype='int')+len_space-1) )
SR_idx_seq = Convertord(SR_idx_seq_list)
SR_seq = ''.join(SR_seq_list)
############FILL UP LEFT SIDE############################
temp_SR_seq = zerostr*(len_space-start_pt) + SR_seq
temp_SR_idx_seq = zerostr*(len_space-start_pt) + SR_idx_seq
temp_SR_del_seq = zerostr*(len_space-start_pt) + SR_del_seq
temp = numpy.copy(SR_seq_list)
SR_seq_list = [zerostr]*(len_space-start_pt)
SR_seq_list.extend(temp)
temp = numpy.copy(SR_idx_seq_list)
SR_idx_seq_list =[zerostr]*(len_space-start_pt)
SR_idx_seq_list.extend(temp)
temp = numpy.copy(SR_del_seq_list)
SR_del_seq_list =[zerostr]*(len_space-start_pt)
SR_del_seq_list.extend(temp)
############FILL UP RIGHT SIDE############################
temp_SR_seq = temp_SR_seq + zerostr*(L_temp_LR_seq - len(temp_SR_seq))
temp_SR_idx_seq = temp_SR_idx_seq + zerostr*(L_temp_LR_seq - len(temp_SR_idx_seq))
temp_SR_del_seq = temp_SR_del_seq + zerostr*(L_temp_LR_seq - len(temp_SR_del_seq))
SR_seq_list.extend( [zerostr]*(L_temp_LR_seq - len(SR_seq_list)))
SR_idx_seq_list.extend([zerostr]*(L_temp_LR_seq - len(SR_idx_seq_list)))
SR_del_seq_list.extend([zerostr]*(L_temp_LR_seq - len(SR_del_seq_list)))
###############
all_seq_idx_list.append([SR_seq_list, SR_idx_seq_list, n_rep])
all_del_seq_list.append([SR_del_seq_list, n_rep])
#########################################################################################################
# Sort the correction points based on position
crt_pt_sorted_array = numpy.array(numpy.sort(list(crt_pt_ls)))
temp_index_ls = numpy.searchsorted(crt_pt_sorted_array,[start_pt,end_pt])
crt_repos_ls = crt_pt_sorted_array[temp_index_ls[0]:temp_index_ls[1]] - start_pt
temp_LR_seq_list = list(temp_LR_seq)
i = 0
# Compute coverage information for the long read
for x in temp_LR_seq_list:
n = int(temp_LR_idx_seq_list[i])
temp_LR_seq_list[i] = x*n
coverage_list[i] = coverage_list[i] * n
i+=1
# Make the corrections (+,>,HC)
for crt_repos in crt_repos_ls:
temp_candidate_ls = []
# For each SR
for temp_SR_seq_idx_list in all_seq_idx_list: # list(list(list()))
x = temp_SR_seq_idx_list[0][crt_repos] # base
n = int(temp_SR_seq_idx_list[1][crt_repos]) # repeat of the base
n_rep =int( temp_SR_seq_idx_list[2]) # repeat of the short read
pre_x = temp_SR_seq_idx_list[0][max(0,crt_repos-1)]
post_x = temp_SR_seq_idx_list[0][min(len(temp_SR_seq_idx_list[0])-1, crt_repos+1)]
if n>0 and x!='N' and pre_x!='N' and post_x!='N':
temp_candidate_ls.extend([x*n]*n_rep)
[optimal_seq, n_max] = optimize_seq(temp_candidate_ls)
if optimal_seq!='':
if optimal_seq=='-':
optimal_seq=''
temp_LR_seq_list[crt_repos] = optimal_seq
coverage_list[crt_repos] = fq_char_list[min( n_max, NUM_FQ_CHAR)] * len(optimal_seq)
#########################################################################################################
coverage_L = len(temp_LR_seq_list)
#########################################################################################################
del_pt_sorted_array = numpy.array(numpy.sort(list(del_pt_set)))
temp_del_index_ls = numpy.searchsorted(del_pt_sorted_array,[start_pt-1,end_pt])
del_repos_ls = del_pt_sorted_array[temp_del_index_ls[0]:temp_index_ls[1]] - start_pt -2
Npredel=0
# Make the corrections (-)
for del_repos in del_repos_ls:
temp_candidate_ls = []
# For each SR
for SR_del_seq_list_ls in all_del_seq_list:
SR_del_seq_list = SR_del_seq_list_ls[0]
n_rep = SR_del_seq_list_ls[1]
if not SR_del_seq_list[del_repos] == '0':
temp_candidate_ls.extend([SR_del_seq_list[del_repos]]*n_rep)
[optimal_seq, n_max] = optimize_seq(temp_candidate_ls)
if optimal_seq!='' and optimal_seq!='=':
del_repos_Npredel_1 = del_repos+Npredel+1
temp_LR_seq_list.insert(del_repos_Npredel_1, optimal_seq)
coverage_list.insert(del_repos_Npredel_1, fq_char_list[min( n_max, NUM_FQ_CHAR)] * len(optimal_seq))
coverage_L +=1
Npredel+=1
#########################################################################################################
final_seq = ''.join(temp_LR_seq_list[1:(coverage_L-1)]) # create the corrected long read, Note: the end and start pos of SRs are not used for correction
coverage_seq = ''.join(coverage_list[1:(coverage_L-1)]) # Coverage data, turns into quality in the output fastq
#########################################################################################################
full_read_file.write('>' + LR_read_name_list[read_int]+'\n')
full_read_file.write(five_end_seq + final_seq.replace('X','').replace('Z','') + three_end_seq + '\n')
corrected_seq = final_seq.replace('X','').replace('Z','')
coverage = 1. * sum((cvrg != fq_char_list[0]) for cvrg in coverage_seq) / len(corrected_seq)
corrected_read_file.write('>' + LR_read_name_list[read_int] + '|' + "{0:.2f}".format(round(coverage, 2)) + '\n')
corrected_read_file.write(corrected_seq + '\n')
corrected_read_fq_file.write('@' + LR_read_name_list[read_int] + '|' + "{0:.2f}".format(round(coverage, 2)) + '\n')
corrected_read_fq_file.write(corrected_seq + '\n')
corrected_read_fq_file.write('+\n')
corrected_read_fq_file.write(coverage_seq.replace('X','').replace('Z','') + '\n')
tmp.close()
full_read_file.close()
corrected_read_file.close()
corrected_read_fq_file.close()
uncorrected_read_file.close()
log_print(datetime.datetime.now()-t0)
|
[
"numpy.copy",
"numpy.searchsorted",
"re.findall",
"numpy.array",
"numpy.math.log10",
"datetime.datetime.now",
"sys.exit"
] |
[((4481, 4504), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4502, 4504), False, 'import datetime\n'), ((3719, 3730), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3727, 3730), False, 'import sys\n'), ((13758, 13817), 'numpy.searchsorted', 'numpy.searchsorted', (['crt_pt_sorted_array', '[start_pt, end_pt]'], {}), '(crt_pt_sorted_array, [start_pt, end_pt])\n', (13776, 13817), False, 'import numpy\n'), ((15528, 15591), 'numpy.searchsorted', 'numpy.searchsorted', (['del_pt_sorted_array', '[start_pt - 1, end_pt]'], {}), '(del_pt_sorted_array, [start_pt - 1, end_pt])\n', (15546, 15591), False, 'import numpy\n'), ((12422, 12445), 'numpy.copy', 'numpy.copy', (['SR_seq_list'], {}), '(SR_seq_list)\n', (12432, 12445), False, 'import numpy\n'), ((12548, 12575), 'numpy.copy', 'numpy.copy', (['SR_idx_seq_list'], {}), '(SR_idx_seq_list)\n', (12558, 12575), False, 'import numpy\n'), ((12685, 12712), 'numpy.copy', 'numpy.copy', (['SR_del_seq_list'], {}), '(SR_del_seq_list)\n', (12695, 12712), False, 'import numpy\n'), ((17931, 17954), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (17952, 17954), False, 'import datetime\n'), ((5617, 5647), 'numpy.array', 'numpy.array', (['p_ls'], {'dtype': '"""int"""'}), "(p_ls, dtype='int')\n", (5628, 5647), False, 'import numpy\n'), ((6500, 6531), 're.findall', 're.findall', (['""">|\\\\+|-"""', 'mismatch'], {}), "('>|\\\\+|-', mismatch)\n", (6510, 6531), False, 'import re\n'), ((6561, 6589), 're.findall', 're.findall', (['"""\\\\w+"""', 'mismatch'], {}), "('\\\\w+', mismatch)\n", (6571, 6589), False, 'import re\n'), ((6440, 6468), 're.findall', 're.findall', (['"""\\\\d+"""', 'mismatch'], {}), "('\\\\d+', mismatch)\n", (6450, 6468), False, 'import re\n'), ((11716, 11757), 'numpy.array', 'numpy.array', (['SR_idx_seq_list'], {'dtype': '"""int"""'}), "(SR_idx_seq_list, dtype='int')\n", (11727, 11757), False, 'import numpy\n'), ((576, 599), 'numpy.math.log10', 'numpy.math.log10', (['(1 - p)'], {}), '(1 - p)\n', (592, 599), False, 'import numpy\n')]
|
import os
import json
import argparse
import sys
import numpy as np
from logger import Logger
from pathlib import Path
from joblib import Parallel, delayed
from modeling.model import KuramotoSystem, plot_interaction
from plotting.animate import Animator
from plotting.plot_solution import PlotSetup
CONFIG_NAME = 'config', 'json'
PHASES_NAME = 'oscillators', 'npy'
NOTES_NAME = 'notes', 'txt'
TIME_NAME = 'time', 'npy'
LOG_NAME = 'log', 'txt'
def model(config, fmt: (str, PlotSetup) = 'simulation'):
"""Prepare and run a cortical sheet simulation based on the passed config dictionary"""
nodes_side = config['sqrt_nodes']
time = config['time']
gain_ratio = config['gain_ratio']
torus = True
# Init model
gain = gain_ratio*nodes_side**2
kuramoto = KuramotoSystem(
(nodes_side, nodes_side),
config['system'],
gain,
boundary=torus
)
# Run Model
time_eval = np.linspace(0, time, config['frames'])
try:
solution = kuramoto.solve(
(0, time),
config['ODE_method'], # too stiff for 'RK45', use 'LSODA',‘BDF’,'Radau'
config['continuous_soln'],
time_eval,
config['max_delta_t'],
config['zero_ics'],
)
osc_state = solution.y.reshape((nodes_side, nodes_side, solution.t.shape[0]))
time = solution.t
msg = solution.message
except Exception as e:
print('Integration failed!')
osc_state = None
time = None
msg = f'{e}'
if config['save_numpy']:
fmt = save_data(fmt, config, osc_state, time, msg)
return osc_state, time, fmt
def save_data(fmt, config, osc_state=None, time=None, solver_notes=None):
"""Load the result of a simulation run to the target directory"""
import subprocess
git_hash = subprocess.check_output(["git", "describe", "--always"]).strip()
git_url = subprocess.check_output(["git", "config", "--get", "remote.origin.url"]).strip()
solver_notes += f'\n\nCode used for this run:\n' \
f' git url: {git_url}\n' \
f' commit hash: {git_hash}'
fmt = fmt if hasattr(fmt, 'file_name') else PlotSetup(label=fmt)
print(f'Saving to {fmt.directory}')
with open(fmt.file_name(*CONFIG_NAME), 'w') as f:
json.dump(config, f, indent=2)
with open(fmt.file_name(*NOTES_NAME), 'w') as f:
if solver_notes:
f.write(solver_notes)
if osc_state is not None:
np.save(fmt.file_name(*PHASES_NAME), osc_state)
if time is not None:
np.save(fmt.file_name(*TIME_NAME), time)
return fmt
def load_data(data_folder):
"""Load the data (result of a simulation run) from the target directory"""
fmt = PlotSetup(base_folder=data_folder, readonly=True)
with open(fmt.file_name(*CONFIG_NAME)) as f:
config = json.load(f)
osc_state = np.load(fmt.file_name(*PHASES_NAME))
time = np.load(fmt.file_name(*TIME_NAME))
return config, osc_state, time, fmt
def plot(config=None, osc_states=None, time=None, data_folder=None, fmt=None, cleanup=True):
"""Plot a gif of the phase evolution over time for the given data, optionally loaded from disk"""
# No data provided explicitly, need to load from the passed folder
if data_folder is not None and (config is None or osc_states is None or time is None):
config, osc_states, time, fmt = load_data(data_folder)
# Insufficient info provided, we don't know what to plot!
elif data_folder is None and (config is None or osc_states is None or time is None):
raise KeyError('Both the data_folder and the data contents were left blank!')
vid = Animator(config, fmt)
vid.animate(osc_states, time, cleanup=cleanup)
plot_interaction(config['sqrt_nodes'], config['system'], config['gain_ratio'], out_fmt=fmt)
def run(config_set: str = 'local_sync', config_file: str = 'model_config.json', base_path='plots', do_plot=True):
"""Run a model based on the passed config file and immediately plot the results"""
path_fmt = PlotSetup(base_path, config_set)
sys.stdout = Logger(path_fmt.file_name(*LOG_NAME))
with open(Path(config_file).resolve()) as f:
var = json.load(f)
config = var[config_set]
oscillator_state, time, path_fmt = model(config, path_fmt)
if do_plot:
plot(config=config, osc_states=oscillator_state, time=time, fmt=path_fmt)
def sweep(var_name, start, stop, steps, n_jobs=-2,
config_set='gain_sweep', config_file: str = 'model_config.json', base_path='plots'):
with open(Path(config_file).resolve()) as f:
var = json.load(f)
base_config = var[config_set]
conf_str = json.dumps(base_config)
var_key = '"<sweep-var>"'
if var_key not in conf_str:
raise KeyError('The swept config set must have the target variable replaced by \'"<sweep-var>"\'')
base_fmt = PlotSetup(base_folder=base_path, label=f'{config_set}_sweep')
var_values = np.linspace(start, stop, steps, endpoint=True)
all_configs = []
file_fmts = []
for value in var_values:
str_here = conf_str.replace(var_key, str(round(value, 4)))
config = json.loads(str_here)
fmt = PlotSetup(base_folder=base_fmt.directory, label=f'{var_name}={value:.2f}')
all_configs.append(config)
file_fmts.append(fmt)
Parallel(n_jobs=n_jobs, verbose=20)(
delayed(model)(all_configs[i], file_fmts[i])
for i in range(len(all_configs))
)
def main():
"""Function to run"""
parser = argparse.ArgumentParser(description='Select model_config scenario & path (optional):')
parser.add_argument('--set', metavar='scenario | variable set',
type=str, nargs='?',
help='model_config.json key like global_sync',
default='test_set')
parser.add_argument('--path', metavar='directory to config.json',
type=str, nargs='?',
help='model_config.json path, default is pwd',
default='model_config.json')
parser.add_argument('--out', metavar='output directory',
type=str, nargs='?',
help='base path to output raw data and plots',
default='plots')
parser.add_argument('--plot', action='store_true',
help='Whether to plot the results right away')
parser.add_argument('--sweep', action='store_true',
help='Whether to plot the results right away')
parser.add_argument('--var', metavar='variable',
type=str, nargs='?',
help='Name of variable being swept',
default='Var')
parser.add_argument('--start', metavar='sweep start',
type=float, nargs='?',
help='Start value of the sweep variable',
default=0.0)
parser.add_argument('--stop', metavar='sweep stop',
type=float, nargs='?',
help='End value of the sweep variable, included',
default=1.0)
parser.add_argument('--steps', metavar='num steps',
type=int, nargs='?',
help='Number of steps in the sweep',
default=10)
parser.add_argument('--jobs', metavar='num jobs',
type=int, nargs='?',
help='Number of parallel jobs to run',
default=-2)
args = parser.parse_args()
if args.sweep:
sweep(args.var, args.start, args.stop, args.steps, args.jobs, args.set, args.path, args.out)
else:
run(args.set, args.path, base_path=args.out, do_plot=args.plot)
if __name__ == '__main__':
main()
|
[
"json.dump",
"json.load",
"argparse.ArgumentParser",
"json.loads",
"subprocess.check_output",
"plotting.animate.Animator",
"json.dumps",
"modeling.model.KuramotoSystem",
"pathlib.Path",
"numpy.linspace",
"joblib.Parallel",
"plotting.plot_solution.PlotSetup",
"joblib.delayed",
"modeling.model.plot_interaction"
] |
[((788, 873), 'modeling.model.KuramotoSystem', 'KuramotoSystem', (['(nodes_side, nodes_side)', "config['system']", 'gain'], {'boundary': 'torus'}), "((nodes_side, nodes_side), config['system'], gain, boundary=torus\n )\n", (802, 873), False, 'from modeling.model import KuramotoSystem, plot_interaction\n'), ((940, 978), 'numpy.linspace', 'np.linspace', (['(0)', 'time', "config['frames']"], {}), "(0, time, config['frames'])\n", (951, 978), True, 'import numpy as np\n'), ((2776, 2825), 'plotting.plot_solution.PlotSetup', 'PlotSetup', ([], {'base_folder': 'data_folder', 'readonly': '(True)'}), '(base_folder=data_folder, readonly=True)\n', (2785, 2825), False, 'from plotting.plot_solution import PlotSetup\n'), ((3717, 3738), 'plotting.animate.Animator', 'Animator', (['config', 'fmt'], {}), '(config, fmt)\n', (3725, 3738), False, 'from plotting.animate import Animator\n'), ((3795, 3891), 'modeling.model.plot_interaction', 'plot_interaction', (["config['sqrt_nodes']", "config['system']", "config['gain_ratio']"], {'out_fmt': 'fmt'}), "(config['sqrt_nodes'], config['system'], config[\n 'gain_ratio'], out_fmt=fmt)\n", (3811, 3891), False, 'from modeling.model import KuramotoSystem, plot_interaction\n'), ((4106, 4138), 'plotting.plot_solution.PlotSetup', 'PlotSetup', (['base_path', 'config_set'], {}), '(base_path, config_set)\n', (4115, 4138), False, 'from plotting.plot_solution import PlotSetup\n'), ((4735, 4758), 'json.dumps', 'json.dumps', (['base_config'], {}), '(base_config)\n', (4745, 4758), False, 'import json\n'), ((4945, 5006), 'plotting.plot_solution.PlotSetup', 'PlotSetup', ([], {'base_folder': 'base_path', 'label': 'f"""{config_set}_sweep"""'}), "(base_folder=base_path, label=f'{config_set}_sweep')\n", (4954, 5006), False, 'from plotting.plot_solution import PlotSetup\n'), ((5025, 5071), 'numpy.linspace', 'np.linspace', (['start', 'stop', 'steps'], {'endpoint': '(True)'}), '(start, stop, steps, endpoint=True)\n', (5036, 5071), True, 'import numpy as np\n'), ((5596, 5687), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Select model_config scenario & path (optional):"""'}), "(description=\n 'Select model_config scenario & path (optional):')\n", (5619, 5687), False, 'import argparse\n'), ((2214, 2234), 'plotting.plot_solution.PlotSetup', 'PlotSetup', ([], {'label': 'fmt'}), '(label=fmt)\n', (2223, 2234), False, 'from plotting.plot_solution import PlotSetup\n'), ((2338, 2368), 'json.dump', 'json.dump', (['config', 'f'], {'indent': '(2)'}), '(config, f, indent=2)\n', (2347, 2368), False, 'import json\n'), ((2892, 2904), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2901, 2904), False, 'import json\n'), ((4258, 4270), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4267, 4270), False, 'import json\n'), ((4673, 4685), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4682, 4685), False, 'import json\n'), ((5225, 5245), 'json.loads', 'json.loads', (['str_here'], {}), '(str_here)\n', (5235, 5245), False, 'import json\n'), ((5260, 5334), 'plotting.plot_solution.PlotSetup', 'PlotSetup', ([], {'base_folder': 'base_fmt.directory', 'label': 'f"""{var_name}={value:.2f}"""'}), "(base_folder=base_fmt.directory, label=f'{var_name}={value:.2f}')\n", (5269, 5334), False, 'from plotting.plot_solution import PlotSetup\n'), ((5406, 5441), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'n_jobs', 'verbose': '(20)'}), '(n_jobs=n_jobs, verbose=20)\n', (5414, 5441), False, 'from joblib import Parallel, delayed\n'), ((1849, 1905), 'subprocess.check_output', 'subprocess.check_output', (["['git', 'describe', '--always']"], {}), "(['git', 'describe', '--always'])\n", (1872, 1905), False, 'import subprocess\n'), ((1928, 2000), 'subprocess.check_output', 'subprocess.check_output', (["['git', 'config', '--get', 'remote.origin.url']"], {}), "(['git', 'config', '--get', 'remote.origin.url'])\n", (1951, 2000), False, 'import subprocess\n'), ((5451, 5465), 'joblib.delayed', 'delayed', (['model'], {}), '(model)\n', (5458, 5465), False, 'from joblib import Parallel, delayed\n'), ((4209, 4226), 'pathlib.Path', 'Path', (['config_file'], {}), '(config_file)\n', (4213, 4226), False, 'from pathlib import Path\n'), ((4624, 4641), 'pathlib.Path', 'Path', (['config_file'], {}), '(config_file)\n', (4628, 4641), False, 'from pathlib import Path\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:Description: Larva segmentation
:Authors: (c) <NAME> <<EMAIL>>
:Date: 2020-08-120
"""
import os
import cv2 as cv
import numpy as np
# from scipy.io import loadmat
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from glob import iglob
# import json
#class NumpyDataEncoder(json.JSONEncoder):
# """JSON serializer of numpy types"""
# def default(self, obj):
# if isinstance(obj, np.integer):
# return int(obj)
# elif isinstance(obj, np.floating):
# return float(obj)
# elif isinstance(obj, np.ndarray):
# return obj.tolist()
# return super(NumpyDataEncoder, self).default(obj)
if __name__ == '__main__':
parser = ArgumentParser(description='Larva segmentation.',
formatter_class=ArgumentDefaultsHelpFormatter, conflict_handler='resolve')
parser.add_argument("-d", "--outp-dir", default=None,
help='Output directory. The input directory is used by default.')
parser.add_argument('input', metavar='INPUT', nargs='+',
help='Wildcards of input video files to be processed')
args = parser.parse_args()
# # Load annotations
# 0 area
# 1 perimeter
# 2 spine length
# 3 fluorescence
# 4 frame number
# 5 larval number (identity)
# 6 x coordinate
# 7 y coordinate
# B7Larva1 .. B7Larva4: array[array]]
# anno = loadmat('v44_v45/B7L.mat')
# Prepare output directory
if args.outp_dir and not os.path.exists(args.outp_dir):
os.makedirs(args.outp_dir)
nfiles = 0
for wlc in args.input:
for ifname in iglob(wlc):
nfiles += 1
print('Processing {} ...'.format(ifname))
#with open(ifname, 'rb') as finp:
cap = cv.VideoCapture(ifname)
fps = cap.get(cv.CAP_PROP_FPS)
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
#ofname = oa.path.split(ifname)[1]
ofname = os.path.join(args.outp_dir, 'v4_v5_f.05_clahe32.avi')
print(' fps: {}, size: {}x{}\n\toutput: {}'.format(fps, width, height, ofname))
# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
# Define the fps to be equal to 10. Also frame size is passed.
# FMP4, MJPG, XVID
#fourcc = cv.VideoWriter_fourcc(*'MJPG')
out = cv.VideoWriter(ofname, cv.VideoWriter_fourcc(*'XVID'), fps, (width, height))
if not cap:
exit(1)
title = os.path.split(ifname)[1]
#cv.namedWindow(title, cv.WINDOW_NORMAL)
#wWnd = 1600
#rfont = width / wWnd
#cv.resizeWindow(title, wWnd, int(height / rfont))
#rfont = max(1, rfont)
nframe = 0
while cap.isOpened():
# Capture frame-by-frame
ret, frame = cap.read()
if not ret:
assert frame is None
break
nframe += 1
#_, _, w, _ = cv.getWindowImageRect(title)
#rfont = max(1, width / w)
#cv.putText(frame,'Recording ...',
# (20, 20 + int(24 * rfont)), # bottomLeftCornerOfText
# cv.FONT_HERSHEY_SIMPLEX,
# rfont, # Font size
# (7, 7, 255), # Color
# 1 + round(rfont)) # Line thickness, px
cv.imshow(title, frame)
# Convert to grayscale
gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
# Apply CLAHE (Contrast Limited Adaptive Histogram Equalization)
clahe = cv.createCLAHE(clipLimit=32.0, tileGridSize=(8,8)) # clipLimit=40 / 255 Threshold for contrast limiting.
gray = clahe.apply(gray)
# Adaprive optimal thresholds: THRESH_OTSU, THRESH_TRIANGLE
ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU) # THRESH_TRIANGLE
cv.imshow(title + '_thresh', thresh)
# cv.imshow(title + '_gray', frame)
# Noise removal
kernel = np.ones((3, 3), np.uint8) # 3, 3
opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=2) # orig: 2
# opening = cv.dilate(thresh, kernel, iterations=2) # 3
cv.imshow(title + '_opening', opening)
# opening = thresh
# # Background identification
sure_bg = cv.dilate(opening, kernel, iterations=3) # orig: 3
# #sure_bg = cv.morphologyEx(opening, cv.MORPH_OPEN, kernel, iterations=2) # 2
# cv.imshow(title + '_bg', sure_bg)
# # sure_bg = opening
# Foreground identification
dist_transform = cv.distanceTransform(opening, cv.DIST_L2, 5) # 5 or 3
ret, sure_fg = cv.threshold(dist_transform, 0.05 * dist_transform.max(), 255, 0) # 0.7 [0.5 - deliv]]
# Remaining areas
sure_fg = np.uint8(sure_fg)
unknown = cv.subtract(sure_bg, sure_fg)
# cv.imshow(title + '_unknown', unknown)
# Marker labelling
ret, markers = cv.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers + 1
# Mark the region of unknown with zero
markers[unknown == 255] = 0
# Apply watershed
markers = cv.watershed(frame, markers)
frame[markers == -1] = [255,0,0]
cv.imshow(title + '_gray', frame)
# Save output video
out.write(frame)
#cv.imwrite("frame%d.jpg" % count, frame)
# Wait 10 ms for a 'q' to exit or capture the next frame
key = cv.waitKey(10) & 0xFF
# Quit: escape, e or q
if key in (27, ord('e'), ord('q')):
break
# Pause: Spacebar or p
elif key in (32, ord('p')):
cv.waitKey(-1)
cap.release()
out.release()
cv.destroyAllWindows() # destroy all opened windows
|
[
"argparse.ArgumentParser",
"cv2.VideoWriter_fourcc",
"numpy.ones",
"glob.iglob",
"cv2.imshow",
"os.path.join",
"cv2.subtract",
"cv2.dilate",
"cv2.cvtColor",
"os.path.exists",
"cv2.connectedComponents",
"cv2.destroyAllWindows",
"numpy.uint8",
"cv2.waitKey",
"cv2.morphologyEx",
"cv2.createCLAHE",
"cv2.distanceTransform",
"os.makedirs",
"cv2.threshold",
"cv2.watershed",
"cv2.VideoCapture",
"os.path.split"
] |
[((698, 827), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Larva segmentation."""', 'formatter_class': 'ArgumentDefaultsHelpFormatter', 'conflict_handler': '"""resolve"""'}), "(description='Larva segmentation.', formatter_class=\n ArgumentDefaultsHelpFormatter, conflict_handler='resolve')\n", (712, 827), False, 'from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n'), ((1439, 1465), 'os.makedirs', 'os.makedirs', (['args.outp_dir'], {}), '(args.outp_dir)\n', (1450, 1465), False, 'import os\n'), ((1519, 1529), 'glob.iglob', 'iglob', (['wlc'], {}), '(wlc)\n', (1524, 1529), False, 'from glob import iglob\n'), ((1406, 1435), 'os.path.exists', 'os.path.exists', (['args.outp_dir'], {}), '(args.outp_dir)\n', (1420, 1435), False, 'import os\n'), ((1637, 1660), 'cv2.VideoCapture', 'cv.VideoCapture', (['ifname'], {}), '(ifname)\n', (1652, 1660), True, 'import cv2 as cv\n'), ((1845, 1898), 'os.path.join', 'os.path.join', (['args.outp_dir', '"""v4_v5_f.05_clahe32.avi"""'], {}), "(args.outp_dir, 'v4_v5_f.05_clahe32.avi')\n", (1857, 1898), False, 'import os\n'), ((5231, 5253), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (5251, 5253), True, 'import cv2 as cv\n'), ((2240, 2270), 'cv2.VideoWriter_fourcc', 'cv.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (2261, 2270), True, 'import cv2 as cv\n'), ((2332, 2353), 'os.path.split', 'os.path.split', (['ifname'], {}), '(ifname)\n', (2345, 2353), False, 'import os\n'), ((2999, 3022), 'cv2.imshow', 'cv.imshow', (['title', 'frame'], {}), '(title, frame)\n', (3008, 3022), True, 'import cv2 as cv\n'), ((3061, 3098), 'cv2.cvtColor', 'cv.cvtColor', (['frame', 'cv.COLOR_BGR2GRAY'], {}), '(frame, cv.COLOR_BGR2GRAY)\n', (3072, 3098), True, 'import cv2 as cv\n'), ((3179, 3230), 'cv2.createCLAHE', 'cv.createCLAHE', ([], {'clipLimit': '(32.0)', 'tileGridSize': '(8, 8)'}), '(clipLimit=32.0, tileGridSize=(8, 8))\n', (3193, 3230), True, 'import cv2 as cv\n'), ((3397, 3462), 'cv2.threshold', 'cv.threshold', (['gray', '(0)', '(255)', '(cv.THRESH_BINARY_INV + cv.THRESH_OTSU)'], {}), '(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)\n', (3409, 3462), True, 'import cv2 as cv\n'), ((3486, 3522), 'cv2.imshow', 'cv.imshow', (["(title + '_thresh')", 'thresh'], {}), "(title + '_thresh', thresh)\n", (3495, 3522), True, 'import cv2 as cv\n'), ((3597, 3622), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.uint8'], {}), '((3, 3), np.uint8)\n', (3604, 3622), True, 'import numpy as np\n'), ((3646, 3706), 'cv2.morphologyEx', 'cv.morphologyEx', (['thresh', 'cv.MORPH_OPEN', 'kernel'], {'iterations': '(2)'}), '(thresh, cv.MORPH_OPEN, kernel, iterations=2)\n', (3661, 3706), True, 'import cv2 as cv\n'), ((3781, 3819), 'cv2.imshow', 'cv.imshow', (["(title + '_opening')", 'opening'], {}), "(title + '_opening', opening)\n", (3790, 3819), True, 'import cv2 as cv\n'), ((3891, 3931), 'cv2.dilate', 'cv.dilate', (['opening', 'kernel'], {'iterations': '(3)'}), '(opening, kernel, iterations=3)\n', (3900, 3931), True, 'import cv2 as cv\n'), ((4144, 4188), 'cv2.distanceTransform', 'cv.distanceTransform', (['opening', 'cv.DIST_L2', '(5)'], {}), '(opening, cv.DIST_L2, 5)\n', (4164, 4188), True, 'import cv2 as cv\n'), ((4342, 4359), 'numpy.uint8', 'np.uint8', (['sure_fg'], {}), '(sure_fg)\n', (4350, 4359), True, 'import numpy as np\n'), ((4374, 4403), 'cv2.subtract', 'cv.subtract', (['sure_bg', 'sure_fg'], {}), '(sure_bg, sure_fg)\n', (4385, 4403), True, 'import cv2 as cv\n'), ((4496, 4527), 'cv2.connectedComponents', 'cv.connectedComponents', (['sure_fg'], {}), '(sure_fg)\n', (4518, 4527), True, 'import cv2 as cv\n'), ((4733, 4761), 'cv2.watershed', 'cv.watershed', (['frame', 'markers'], {}), '(frame, markers)\n', (4745, 4761), True, 'import cv2 as cv\n'), ((4803, 4836), 'cv2.imshow', 'cv.imshow', (["(title + '_gray')", 'frame'], {}), "(title + '_gray', frame)\n", (4812, 4836), True, 'import cv2 as cv\n'), ((5009, 5023), 'cv2.waitKey', 'cv.waitKey', (['(10)'], {}), '(10)\n', (5019, 5023), True, 'import cv2 as cv\n'), ((5173, 5187), 'cv2.waitKey', 'cv.waitKey', (['(-1)'], {}), '(-1)\n', (5183, 5187), True, 'import cv2 as cv\n')]
|
"""
Adapted from https://github.com/leoxiaobin/deep-high-resolution-net.pytorch
Original licence: Copyright (c) Microsoft, under the MIT License.
"""
from abc import ABC, abstractmethod
import copy
import random
import cv2
import numpy as np
from albumentations import (
Compose,
Normalize,
)
import tensorflow as tf
from ..transforms import (
get_affine_transform,
affine_transform,
fliplr_joints,
half_body_transform,
)
class BaseDataset(ABC):
def __init__(self, config, root: str, image_set: str, is_train: str):
self.num_joints = 0
self.is_train = is_train
self.root = root
self.image_set = image_set
self.scale_factor = config.dataset.scale_factor
self.rotation_factor = config.dataset.rot_factor
self.flip = config.dataset.flip
self.half_body_prob = config.dataset.half_body_prob
self.half_body_num_joints = config.dataset.half_body_num_joints
self.color_rgb = config.dataset.color_rgb
self.input_w = config.model.input_width
self.input_h = config.model.input_height
self.output_w = config.model.output_width
self.output_h = config.model.output_height
self.aspect_ratio = self.input_w * 1.0 / self.input_h
self.sigma = config.model.sigma
self.transform = Compose([
Normalize(
mean=config.model.mean,
std=config.model.std),
])
self.flip_pairs = None
self.upper_body_ids = None
self.lower_body_ids = None
self.db = []
self.output_types = {
'inputs': tf.float32,
'target': tf.float32,
'target_weight': tf.float32,
'image_file': tf.string,
'file_name': tf.string,
'joints': tf.float32,
'joints_visible': tf.float32,
'center': tf.float32,
'scale': tf.float32,
'rotation': tf.float32,
'score': tf.float32,
}
@abstractmethod
def _get_db(self):
raise NotImplementedError
@abstractmethod
def evaluate(self, preds, output_dir, all_boxes, img_path):
raise NotImplementedError
def __len__(self):
return len(self.db)
def __getitem__(self, idx):
db_rec = copy.deepcopy(self.db[idx])
image_file = db_rec['image']
file_name = db_rec['file_name'] if 'file_name' in db_rec else ''
img = cv2.imread(
image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
if img is None:
raise ValueError('Fail to read {}'.format(image_file))
if self.color_rgb:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
joints = db_rec['joints_3d']
joints_visible = db_rec['joints_3d_visible']
c = db_rec['center']
s = db_rec['scale']
score = db_rec['score'] if 'score' in db_rec else 1
r = 0
# augmentation
if self.is_train:
if (np.sum(joints_visible[:, 0]) > self.half_body_num_joints
and np.random.rand() < self.half_body_prob):
c_half_body, s_half_body = half_body_transform(
joints,
joints_visible,
self.num_joints,
self.upper_body_ids,
self.aspect_ratio)
if c_half_body is not None and s_half_body is not None:
c = c_half_body
s = s_half_body
sf = self.scale_factor
rf = self.rotation_factor
s = s * np.clip(np.random.randn() * sf + 1, 1 - sf, 1 + sf)
r = np.clip(np.random.randn() * rf, -rf * 2, rf * 2) \
if random.random() <= 0.6 else 0
if self.flip and random.random() <= 0.5:
img = img[:, ::-1, :]
joints, joints_visible = fliplr_joints(
joints, joints_visible, img.shape[1], self.flip_pairs)
c[0] = img.shape[1] - c[0] - 1
trans = get_affine_transform(c, s, r, (self.input_w, self.input_h))
img = cv2.warpAffine(
img,
trans,
(self.input_w, self.input_h),
flags=cv2.INTER_LINEAR)
if self.transform:
img = self.transform(image=img)['image']
for i in range(self.num_joints):
if joints_visible[i, 0] > 0.0:
joints[i, 0:2] = affine_transform(joints[i, 0:2], trans)
target, target_weight = self._generate_target(joints, joints_visible)
return {
'inputs': img,
'target': target,
'target_weight': target_weight,
'image_file': image_file,
'file_name': file_name,
'joints': joints,
'joints_visible': joints_visible,
'center': c,
'scale': s,
'rotation': r,
'score': score
}
def generator(self):
"""Generator for `tf.data.Dataset.from_generator`.
"""
indices = list(range(len(self)))
if self.is_train:
random.shuffle(indices)
for idx in indices:
yield self[idx]
def _generate_target(self, joints: np.ndarray, joints_visible: np.ndarray):
"""Generate target map.
Args:
joints : [num_joints, 3]
joints_visible: [num_joints, 3]
Returns:
target: [self.output_height, self.output_width, num_joints]
target_weight: 1: visible, 0: invisible
"""
target_weight = np.ones((self.num_joints, 1), dtype=np.float32)
target_weight[:, 0] = joints_visible[:, 0]
target = np.zeros(
(self.output_h, self.output_w, self.num_joints),
dtype=np.float32)
tmp_size = self.sigma * 3
for joint_id in range(self.num_joints):
heatmap_vis = joints_visible[joint_id, 0]
target_weight[joint_id] = heatmap_vis
feat_stride = [
self.input_w / self.output_w,
self.input_h / self.output_h,
]
mu_x = joints[joint_id][0] / feat_stride[0]
mu_y = joints[joint_id][1] / feat_stride[1]
# Check that any part of the gaussian is in-bounds
ul = [mu_x - tmp_size, mu_y - tmp_size]
br = [mu_x + tmp_size + 1, mu_y + tmp_size + 1]
if (ul[0] >= self.output_w or
ul[1] >= self.output_h or
br[0] < 0 or
br[1] < 0):
target_weight[joint_id] = 0
if target_weight[joint_id] == 0:
continue
x = np.arange(0, self.output_w, 1, np.float32)
y = np.arange(0, self.output_h, 1, np.float32)
y = y[:, None]
if target_weight[joint_id] > 0.5:
target[..., joint_id] = np.exp(
-((x - mu_x) ** 2 + (y - mu_y) ** 2) / (2 * self.sigma ** 2))
return target, target_weight
|
[
"copy.deepcopy",
"numpy.sum",
"numpy.random.randn",
"cv2.cvtColor",
"random.shuffle",
"numpy.random.rand",
"numpy.zeros",
"numpy.ones",
"cv2.imread",
"cv2.warpAffine",
"random.random",
"numpy.arange",
"numpy.exp",
"albumentations.Normalize"
] |
[((2316, 2343), 'copy.deepcopy', 'copy.deepcopy', (['self.db[idx]'], {}), '(self.db[idx])\n', (2329, 2343), False, 'import copy\n'), ((2470, 2542), 'cv2.imread', 'cv2.imread', (['image_file', '(cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)'], {}), '(image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)\n', (2480, 2542), False, 'import cv2\n'), ((4155, 4240), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'trans', '(self.input_w, self.input_h)'], {'flags': 'cv2.INTER_LINEAR'}), '(img, trans, (self.input_w, self.input_h), flags=cv2.INTER_LINEAR\n )\n', (4169, 4240), False, 'import cv2\n'), ((5629, 5676), 'numpy.ones', 'np.ones', (['(self.num_joints, 1)'], {'dtype': 'np.float32'}), '((self.num_joints, 1), dtype=np.float32)\n', (5636, 5676), True, 'import numpy as np\n'), ((5746, 5821), 'numpy.zeros', 'np.zeros', (['(self.output_h, self.output_w, self.num_joints)'], {'dtype': 'np.float32'}), '((self.output_h, self.output_w, self.num_joints), dtype=np.float32)\n', (5754, 5821), True, 'import numpy as np\n'), ((2694, 2730), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (2706, 2730), False, 'import cv2\n'), ((5161, 5184), 'random.shuffle', 'random.shuffle', (['indices'], {}), '(indices)\n', (5175, 5184), False, 'import random\n'), ((6742, 6784), 'numpy.arange', 'np.arange', (['(0)', 'self.output_w', '(1)', 'np.float32'], {}), '(0, self.output_w, 1, np.float32)\n', (6751, 6784), True, 'import numpy as np\n'), ((6801, 6843), 'numpy.arange', 'np.arange', (['(0)', 'self.output_h', '(1)', 'np.float32'], {}), '(0, self.output_h, 1, np.float32)\n', (6810, 6843), True, 'import numpy as np\n'), ((1357, 1412), 'albumentations.Normalize', 'Normalize', ([], {'mean': 'config.model.mean', 'std': 'config.model.std'}), '(mean=config.model.mean, std=config.model.std)\n', (1366, 1412), False, 'from albumentations import Compose, Normalize\n'), ((6958, 7026), 'numpy.exp', 'np.exp', (['(-((x - mu_x) ** 2 + (y - mu_y) ** 2) / (2 * self.sigma ** 2))'], {}), '(-((x - mu_x) ** 2 + (y - mu_y) ** 2) / (2 * self.sigma ** 2))\n', (6964, 7026), True, 'import numpy as np\n'), ((3020, 3048), 'numpy.sum', 'np.sum', (['joints_visible[:, 0]'], {}), '(joints_visible[:, 0])\n', (3026, 3048), True, 'import numpy as np\n'), ((3101, 3117), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3115, 3117), True, 'import numpy as np\n'), ((3764, 3779), 'random.random', 'random.random', ([], {}), '()\n', (3777, 3779), False, 'import random\n'), ((3824, 3839), 'random.random', 'random.random', ([], {}), '()\n', (3837, 3839), False, 'import random\n'), ((3702, 3719), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (3717, 3719), True, 'import numpy as np\n'), ((3634, 3651), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (3649, 3651), True, 'import numpy as np\n')]
|
# <NAME>, 18/04/2018
# Project 2018, Iris Dataset Analysis
# https://web.microsoftstream.com/video/74b18405-5ee1-47f0-a42d-e8831a453a91
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html
# https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.amax.html
# https://web.microsoftstream.com/video/f0788c1c-c7bd-4347-98ac-477186938ed7
# http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html
# https://matplotlib.org/
# https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points
import numpy # http://www.numpy.org/
data = numpy.genfromtxt("data/iris.csv", delimiter = ",")
import matplotlib.pyplot as pl # https://matplotlib.org/
# Four variables, Petal length, Petal width, Sepal length and Sepal width
# To identify the data in each variable
set = "Setosa"
ver = "Versicolor"
vir = "Virginica"
petlen = data[:,2] # first column petal length
petwid = data[:,3] # second column petal width
seplen = data[:,0] # third column sepal length
sepwid = data[:,1] # fourth Column sepal width
# to calculate the maximum of each variable
petlenmax = numpy.amax(data[:,2])
petwidmax = numpy.amax(data[:,3])
seplenmax = numpy.amax(data[:,0])
sepwidmax = numpy.amax(data[:,1])
# to calculate the minimum of each variable
petlenmin = numpy.amin(data[:,2])
petwidmin = numpy.amin(data[:,3])
seplenmin = numpy.amin(data[:,0])
sepwidmin = numpy.amin(data[:,1])
# To calculate the mean of each variable
petlenmean = round(numpy.mean(data[:,2]),2)
petwidmean = round(numpy.mean(data[:,3]),2)
seplenmean = round(numpy.mean(data[:,0]),2)
sepwidmean = round(numpy.mean(data[:,1]),2)
# To calculate the standard deviation from the mean of each variable
petlenstd = round(numpy.std(data[:,2]),3)
petwidstd = round(numpy.std(data[:,3]),3)
seplenstd = round(numpy.std(data[:,0]),3)
sepwidstd = round(numpy.std(data[:,1]),3)
# To identify the data of just the Setosa class of Iris
setpetlen = data[1:50,2]
setpetwid = data[1:50,3]
setseplen = data[1:50,0]
setsepwid = data[1:50,1]
# To calculate the maximum of each variable in the Setosa class of Iris
setpetlenmax = numpy.amax(data[1:50,2])
setpetwidmax = numpy.amax(data[1:50,3])
setseplenmax = numpy.amax(data[1:50,0])
setsepwidmax = numpy.amax(data[1:50,1])
# To calculate the minimum of each variable in the Setosa class of Iris
setpetlenmin = numpy.amin(data[1:50,2])
setpetwidmin = numpy.amin(data[1:50,3])
setseplenmin = numpy.amin(data[1:50,0])
setsepwidmin = numpy.amin(data[1:50,1])
# To calculate the mean of each variable for the Setosa class of Iris
setpetlenmean = numpy.mean(data[1:50,2])
setpetwidmean = numpy.mean(data[1:50,3])
setseplenmean = numpy.mean(data[1:50,0])
setsepwidmean = numpy.mean(data[1:50,1])
# To identify the data of just the Versicolor class of Iris
verpetlen = data[51:100,2]
verpetwid = data[51:100,3]
verseplen = data[51:100,0]
versepwid = data[51:100,1]
# To calculate the maximum of each variable in the Versicolor class of Iris
verpetlenmax = numpy.amax(data[51:100,2])
verpetwidmax = numpy.amax(data[51:100,3])
verseplenmax = numpy.amax(data[51:100,0])
versepwidmax = numpy.amax(data[51:100,1])
# To calculate the minimum of each variable in the Versicolor class of Iris
verpetlenmin = numpy.amin(data[51:100,2])
verpetwidmin = numpy.amin(data[51:100,3])
verseplenmin = numpy.amin(data[51:100,0])
versepwidmin = numpy.amin(data[51:100,1])
# To calculate the mean of each variable for the Versicolor class of Iris
verpetlenmean = numpy.mean(data[51:100,2])
verpetwidmean = numpy.mean(data[51:100,3])
verseplenmean = numpy.mean(data[51:100,0])
versepwidmean = numpy.mean(data[51:100,1])
# To identify the data of just the Virginica class of Iris
virpetlen = data[101:150,2]
virpetwid = data[101:150,3]
virseplen = data[101:150,0]
virsepwid = data[101:150,1]
# To calculate the maximum of each variable in the Virginica class of Iris
virpetlenmax = numpy.amax(data[101:150,2])
virpetwidmax = numpy.amax(data[101:150,3])
virseplenmax = numpy.amax(data[101:150,0])
virsepwidmax = numpy.amax(data[101:150,1])
# To calculate the minimum of each variable in the Virginica class of Iris
virpetlenmin = numpy.amin(data[101:150,2])
virpetwidmin = numpy.amin(data[101:150,3])
virseplenmin = numpy.amin(data[101:150,0])
virsepwidmin = numpy.amin(data[101:150,1])
# To calculate the mean of each variable for the Virginica class of Iris
virpetlenmean = numpy.mean(data[101:150,2])
virpetwidmean = numpy.mean(data[101:150,3])
virseplenmean = numpy.mean(data[101:150,0])
virsepwidmean = numpy.mean(data[101:150,1])
# To calculate the standard deviation from the mean for the Virginica class of Iris
virpetlenstd = numpy.std(data[101:150,2])
virpetwidstd = numpy.std(data[101:150,3])
virseplenstd = numpy.std(data[101:150,0])
virsepwidstd = numpy.std(data[101:150,1])
if setpetlenmax > verpetlenmax and setpetlenmax > virpetlenmax:
print ("The", set, "class has the highest maximum petal length with", setpetlenmax, "cm")
elif verpetlenmax > setpetlenmax and verpetlenmax > virpetlenmax:
print ("The", ver, "class has the highest maximum petal length with", verpetlenmax, "cm")
else:
print ("The", vir , "class has the highest maximum petal length with", virpetlenmax, "cm")
if setpetlenmin < verpetlenmin and setpetlenmin < virpetlenmin:
print ("The", set, "class has the lowest minimum petal length with", setpetlenmin, "cm")
elif verpetlenmin < setpetlenmin and verpetlenmin < virpetlenmin:
print ("The", ver, "class has the lowest minimum petal length with", verpetlenmin, "cm")
else:
print ("The", vir , "class has the lowest petal minimum length with", virpetlenmin, "cm")
print ("The average petal length across all the classes is", petlenmean, "cm with a standard deviation of", petlenstd)
if setpetwidmax > verpetwidmax and setpetwidmax > virpetwidmax:
print ("The", set, "class has the highest maximum petal width with", setpetwidmax, "cm")
elif verpetwidmax > setpetwidmax and verpetwidmax > virpetwidmax:
print ("The", ver, "class has the highest maximum petal width with", verpetwidmax, "cm")
else:
print ("The", vir , "class has the highest maximum petal width with", virpetwidmax, "cm")
if setpetwidmin < verpetwidmin and setpetwidmin < virpetwidmin:
print ("The", set, "class has the lowest minimum petal width with", setpetwidmin, "cm")
elif verpetwidmin < setpetwidmin and verpetwidmin < virpetwidmin:
print ("The", ver, "class has the lowest minimum petal width with", verpetwidmin, "cm")
else:
print ("The", vir , "class has the lowest petal minimum width with", virpetwidmin, "cm")
print ("The average petal width across all the classes is", petwidmean, "cm with a standard deviation of", petwidstd)
if setseplenmax > verseplenmax and setseplenmax > virseplenmax:
print ("The", set, "class has the highest maximum sepal length with", setseplenmax, "cm")
elif verseplenmax > setseplenmax and verseplenmax > virseplenmax:
print ("The", ver, "class has the highest maximum sepal length with", verseplenmax, "cm")
else:
print ("The", vir , "class has the highest maximum sepal length with", virseplenmax, "cm")
if setseplenmin < verseplenmin and setseplenmin < virseplenmin:
print ("The", set, "class has the lowest minimum sepal length with", setseplenmin, "cm")
elif verseplenmin < setseplenmin and verseplenmin < virseplenmin:
print ("The", ver, "class has the lowest minimum sepal length with", verseplenmin, "cm")
else:
print ("The", vir , "class has the lowest sepal minimum length with", virseplenmin, "cm")
print ("The average sepal length across all the classes is", seplenmean, "cm with a standard deviation of", seplenstd)
if setsepwidmax > versepwidmax and setsepwidmax > virsepwidmax:
print ("The", set, "class has the highest maximum sepal width with", setsepwidmax, "cm")
elif versepwidmax > setsepwidmax and versepwidmax > virsepwidmax:
print ("The", ver, "class has the highest maximum sepal width with", versepwidmax, "cm")
else:
print ("The", vir , "class has the highest maximum sepal width with", virsepwidmax, "cm")
if setsepwidmin < versepwidmin and setsepwidmin < virsepwidmin:
print ("The", set, "class has the lowest minimum sepal width with", setsepwidmin, "cm")
elif versepwidmin < setsepwidmin and versepwidmin < virsepwidmin:
print ("The", ver, "class has the lowest minimum sepal width with", versepwidmin, "cm")
else:
print ("The", vir , "class has the lowest sepal minimum width with", virsepwidmin, "cm")
print ("The average sepal width across all the classes is", sepwidmean, "cm with a standard deviation of", sepwidstd)
pl.title("Petals")
pl.xlabel("Petal Length cm")
pl.ylabel("Petal Width cm")
pl.scatter(setpetlen, setpetwid)
pl.scatter(verpetlen, verpetwid)
pl.scatter(virpetlen, virpetwid)
pl.scatter(petlenmean, petwidmean)
pl.legend(["Setosa", "Versicolor", "Virginica", "Overall Mean"])
pl.show()
pl.title("Sepals")
pl.xlabel("Sepal Length cm")
pl.ylabel("Sepal Width cm")
pl.scatter(setseplen, setsepwid)
pl.scatter(verseplen, versepwid)
pl.scatter(virseplen, virsepwid)
pl.scatter(seplenmean,sepwidmean)
pl.legend(["Setosa", "Versicolor", "Virginica", "Overall Mean"])
pl.show()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.amin",
"numpy.std",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"numpy.genfromtxt",
"numpy.amax",
"numpy.mean",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] |
[((598, 646), 'numpy.genfromtxt', 'numpy.genfromtxt', (['"""data/iris.csv"""'], {'delimiter': '""","""'}), "('data/iris.csv', delimiter=',')\n", (614, 646), False, 'import numpy\n'), ((1124, 1146), 'numpy.amax', 'numpy.amax', (['data[:, 2]'], {}), '(data[:, 2])\n', (1134, 1146), False, 'import numpy\n'), ((1158, 1180), 'numpy.amax', 'numpy.amax', (['data[:, 3]'], {}), '(data[:, 3])\n', (1168, 1180), False, 'import numpy\n'), ((1192, 1214), 'numpy.amax', 'numpy.amax', (['data[:, 0]'], {}), '(data[:, 0])\n', (1202, 1214), False, 'import numpy\n'), ((1226, 1248), 'numpy.amax', 'numpy.amax', (['data[:, 1]'], {}), '(data[:, 1])\n', (1236, 1248), False, 'import numpy\n'), ((1305, 1327), 'numpy.amin', 'numpy.amin', (['data[:, 2]'], {}), '(data[:, 2])\n', (1315, 1327), False, 'import numpy\n'), ((1339, 1361), 'numpy.amin', 'numpy.amin', (['data[:, 3]'], {}), '(data[:, 3])\n', (1349, 1361), False, 'import numpy\n'), ((1373, 1395), 'numpy.amin', 'numpy.amin', (['data[:, 0]'], {}), '(data[:, 0])\n', (1383, 1395), False, 'import numpy\n'), ((1407, 1429), 'numpy.amin', 'numpy.amin', (['data[:, 1]'], {}), '(data[:, 1])\n', (1417, 1429), False, 'import numpy\n'), ((2131, 2156), 'numpy.amax', 'numpy.amax', (['data[1:50, 2]'], {}), '(data[1:50, 2])\n', (2141, 2156), False, 'import numpy\n'), ((2171, 2196), 'numpy.amax', 'numpy.amax', (['data[1:50, 3]'], {}), '(data[1:50, 3])\n', (2181, 2196), False, 'import numpy\n'), ((2211, 2236), 'numpy.amax', 'numpy.amax', (['data[1:50, 0]'], {}), '(data[1:50, 0])\n', (2221, 2236), False, 'import numpy\n'), ((2251, 2276), 'numpy.amax', 'numpy.amax', (['data[1:50, 1]'], {}), '(data[1:50, 1])\n', (2261, 2276), False, 'import numpy\n'), ((2364, 2389), 'numpy.amin', 'numpy.amin', (['data[1:50, 2]'], {}), '(data[1:50, 2])\n', (2374, 2389), False, 'import numpy\n'), ((2404, 2429), 'numpy.amin', 'numpy.amin', (['data[1:50, 3]'], {}), '(data[1:50, 3])\n', (2414, 2429), False, 'import numpy\n'), ((2444, 2469), 'numpy.amin', 'numpy.amin', (['data[1:50, 0]'], {}), '(data[1:50, 0])\n', (2454, 2469), False, 'import numpy\n'), ((2484, 2509), 'numpy.amin', 'numpy.amin', (['data[1:50, 1]'], {}), '(data[1:50, 1])\n', (2494, 2509), False, 'import numpy\n'), ((2596, 2621), 'numpy.mean', 'numpy.mean', (['data[1:50, 2]'], {}), '(data[1:50, 2])\n', (2606, 2621), False, 'import numpy\n'), ((2637, 2662), 'numpy.mean', 'numpy.mean', (['data[1:50, 3]'], {}), '(data[1:50, 3])\n', (2647, 2662), False, 'import numpy\n'), ((2678, 2703), 'numpy.mean', 'numpy.mean', (['data[1:50, 0]'], {}), '(data[1:50, 0])\n', (2688, 2703), False, 'import numpy\n'), ((2719, 2744), 'numpy.mean', 'numpy.mean', (['data[1:50, 1]'], {}), '(data[1:50, 1])\n', (2729, 2744), False, 'import numpy\n'), ((3006, 3033), 'numpy.amax', 'numpy.amax', (['data[51:100, 2]'], {}), '(data[51:100, 2])\n', (3016, 3033), False, 'import numpy\n'), ((3048, 3075), 'numpy.amax', 'numpy.amax', (['data[51:100, 3]'], {}), '(data[51:100, 3])\n', (3058, 3075), False, 'import numpy\n'), ((3090, 3117), 'numpy.amax', 'numpy.amax', (['data[51:100, 0]'], {}), '(data[51:100, 0])\n', (3100, 3117), False, 'import numpy\n'), ((3132, 3159), 'numpy.amax', 'numpy.amax', (['data[51:100, 1]'], {}), '(data[51:100, 1])\n', (3142, 3159), False, 'import numpy\n'), ((3251, 3278), 'numpy.amin', 'numpy.amin', (['data[51:100, 2]'], {}), '(data[51:100, 2])\n', (3261, 3278), False, 'import numpy\n'), ((3293, 3320), 'numpy.amin', 'numpy.amin', (['data[51:100, 3]'], {}), '(data[51:100, 3])\n', (3303, 3320), False, 'import numpy\n'), ((3335, 3362), 'numpy.amin', 'numpy.amin', (['data[51:100, 0]'], {}), '(data[51:100, 0])\n', (3345, 3362), False, 'import numpy\n'), ((3377, 3404), 'numpy.amin', 'numpy.amin', (['data[51:100, 1]'], {}), '(data[51:100, 1])\n', (3387, 3404), False, 'import numpy\n'), ((3495, 3522), 'numpy.mean', 'numpy.mean', (['data[51:100, 2]'], {}), '(data[51:100, 2])\n', (3505, 3522), False, 'import numpy\n'), ((3538, 3565), 'numpy.mean', 'numpy.mean', (['data[51:100, 3]'], {}), '(data[51:100, 3])\n', (3548, 3565), False, 'import numpy\n'), ((3581, 3608), 'numpy.mean', 'numpy.mean', (['data[51:100, 0]'], {}), '(data[51:100, 0])\n', (3591, 3608), False, 'import numpy\n'), ((3624, 3651), 'numpy.mean', 'numpy.mean', (['data[51:100, 1]'], {}), '(data[51:100, 1])\n', (3634, 3651), False, 'import numpy\n'), ((3914, 3942), 'numpy.amax', 'numpy.amax', (['data[101:150, 2]'], {}), '(data[101:150, 2])\n', (3924, 3942), False, 'import numpy\n'), ((3957, 3985), 'numpy.amax', 'numpy.amax', (['data[101:150, 3]'], {}), '(data[101:150, 3])\n', (3967, 3985), False, 'import numpy\n'), ((4000, 4028), 'numpy.amax', 'numpy.amax', (['data[101:150, 0]'], {}), '(data[101:150, 0])\n', (4010, 4028), False, 'import numpy\n'), ((4043, 4071), 'numpy.amax', 'numpy.amax', (['data[101:150, 1]'], {}), '(data[101:150, 1])\n', (4053, 4071), False, 'import numpy\n'), ((4162, 4190), 'numpy.amin', 'numpy.amin', (['data[101:150, 2]'], {}), '(data[101:150, 2])\n', (4172, 4190), False, 'import numpy\n'), ((4205, 4233), 'numpy.amin', 'numpy.amin', (['data[101:150, 3]'], {}), '(data[101:150, 3])\n', (4215, 4233), False, 'import numpy\n'), ((4248, 4276), 'numpy.amin', 'numpy.amin', (['data[101:150, 0]'], {}), '(data[101:150, 0])\n', (4258, 4276), False, 'import numpy\n'), ((4291, 4319), 'numpy.amin', 'numpy.amin', (['data[101:150, 1]'], {}), '(data[101:150, 1])\n', (4301, 4319), False, 'import numpy\n'), ((4409, 4437), 'numpy.mean', 'numpy.mean', (['data[101:150, 2]'], {}), '(data[101:150, 2])\n', (4419, 4437), False, 'import numpy\n'), ((4453, 4481), 'numpy.mean', 'numpy.mean', (['data[101:150, 3]'], {}), '(data[101:150, 3])\n', (4463, 4481), False, 'import numpy\n'), ((4497, 4525), 'numpy.mean', 'numpy.mean', (['data[101:150, 0]'], {}), '(data[101:150, 0])\n', (4507, 4525), False, 'import numpy\n'), ((4541, 4569), 'numpy.mean', 'numpy.mean', (['data[101:150, 1]'], {}), '(data[101:150, 1])\n', (4551, 4569), False, 'import numpy\n'), ((4669, 4696), 'numpy.std', 'numpy.std', (['data[101:150, 2]'], {}), '(data[101:150, 2])\n', (4678, 4696), False, 'import numpy\n'), ((4711, 4738), 'numpy.std', 'numpy.std', (['data[101:150, 3]'], {}), '(data[101:150, 3])\n', (4720, 4738), False, 'import numpy\n'), ((4753, 4780), 'numpy.std', 'numpy.std', (['data[101:150, 0]'], {}), '(data[101:150, 0])\n', (4762, 4780), False, 'import numpy\n'), ((4795, 4822), 'numpy.std', 'numpy.std', (['data[101:150, 1]'], {}), '(data[101:150, 1])\n', (4804, 4822), False, 'import numpy\n'), ((8638, 8656), 'matplotlib.pyplot.title', 'pl.title', (['"""Petals"""'], {}), "('Petals')\n", (8646, 8656), True, 'import matplotlib.pyplot as pl\n'), ((8657, 8685), 'matplotlib.pyplot.xlabel', 'pl.xlabel', (['"""Petal Length cm"""'], {}), "('Petal Length cm')\n", (8666, 8685), True, 'import matplotlib.pyplot as pl\n'), ((8686, 8713), 'matplotlib.pyplot.ylabel', 'pl.ylabel', (['"""Petal Width cm"""'], {}), "('Petal Width cm')\n", (8695, 8713), True, 'import matplotlib.pyplot as pl\n'), ((8714, 8746), 'matplotlib.pyplot.scatter', 'pl.scatter', (['setpetlen', 'setpetwid'], {}), '(setpetlen, setpetwid)\n', (8724, 8746), True, 'import matplotlib.pyplot as pl\n'), ((8747, 8779), 'matplotlib.pyplot.scatter', 'pl.scatter', (['verpetlen', 'verpetwid'], {}), '(verpetlen, verpetwid)\n', (8757, 8779), True, 'import matplotlib.pyplot as pl\n'), ((8780, 8812), 'matplotlib.pyplot.scatter', 'pl.scatter', (['virpetlen', 'virpetwid'], {}), '(virpetlen, virpetwid)\n', (8790, 8812), True, 'import matplotlib.pyplot as pl\n'), ((8813, 8847), 'matplotlib.pyplot.scatter', 'pl.scatter', (['petlenmean', 'petwidmean'], {}), '(petlenmean, petwidmean)\n', (8823, 8847), True, 'import matplotlib.pyplot as pl\n'), ((8848, 8912), 'matplotlib.pyplot.legend', 'pl.legend', (["['Setosa', 'Versicolor', 'Virginica', 'Overall Mean']"], {}), "(['Setosa', 'Versicolor', 'Virginica', 'Overall Mean'])\n", (8857, 8912), True, 'import matplotlib.pyplot as pl\n'), ((8913, 8922), 'matplotlib.pyplot.show', 'pl.show', ([], {}), '()\n', (8920, 8922), True, 'import matplotlib.pyplot as pl\n'), ((8927, 8945), 'matplotlib.pyplot.title', 'pl.title', (['"""Sepals"""'], {}), "('Sepals')\n", (8935, 8945), True, 'import matplotlib.pyplot as pl\n'), ((8946, 8974), 'matplotlib.pyplot.xlabel', 'pl.xlabel', (['"""Sepal Length cm"""'], {}), "('Sepal Length cm')\n", (8955, 8974), True, 'import matplotlib.pyplot as pl\n'), ((8975, 9002), 'matplotlib.pyplot.ylabel', 'pl.ylabel', (['"""Sepal Width cm"""'], {}), "('Sepal Width cm')\n", (8984, 9002), True, 'import matplotlib.pyplot as pl\n'), ((9003, 9035), 'matplotlib.pyplot.scatter', 'pl.scatter', (['setseplen', 'setsepwid'], {}), '(setseplen, setsepwid)\n', (9013, 9035), True, 'import matplotlib.pyplot as pl\n'), ((9036, 9068), 'matplotlib.pyplot.scatter', 'pl.scatter', (['verseplen', 'versepwid'], {}), '(verseplen, versepwid)\n', (9046, 9068), True, 'import matplotlib.pyplot as pl\n'), ((9069, 9101), 'matplotlib.pyplot.scatter', 'pl.scatter', (['virseplen', 'virsepwid'], {}), '(virseplen, virsepwid)\n', (9079, 9101), True, 'import matplotlib.pyplot as pl\n'), ((9102, 9136), 'matplotlib.pyplot.scatter', 'pl.scatter', (['seplenmean', 'sepwidmean'], {}), '(seplenmean, sepwidmean)\n', (9112, 9136), True, 'import matplotlib.pyplot as pl\n'), ((9136, 9200), 'matplotlib.pyplot.legend', 'pl.legend', (["['Setosa', 'Versicolor', 'Virginica', 'Overall Mean']"], {}), "(['Setosa', 'Versicolor', 'Virginica', 'Overall Mean'])\n", (9145, 9200), True, 'import matplotlib.pyplot as pl\n'), ((9201, 9210), 'matplotlib.pyplot.show', 'pl.show', ([], {}), '()\n', (9208, 9210), True, 'import matplotlib.pyplot as pl\n'), ((1490, 1512), 'numpy.mean', 'numpy.mean', (['data[:, 2]'], {}), '(data[:, 2])\n', (1500, 1512), False, 'import numpy\n'), ((1534, 1556), 'numpy.mean', 'numpy.mean', (['data[:, 3]'], {}), '(data[:, 3])\n', (1544, 1556), False, 'import numpy\n'), ((1578, 1600), 'numpy.mean', 'numpy.mean', (['data[:, 0]'], {}), '(data[:, 0])\n', (1588, 1600), False, 'import numpy\n'), ((1622, 1644), 'numpy.mean', 'numpy.mean', (['data[:, 1]'], {}), '(data[:, 1])\n', (1632, 1644), False, 'import numpy\n'), ((1735, 1756), 'numpy.std', 'numpy.std', (['data[:, 2]'], {}), '(data[:, 2])\n', (1744, 1756), False, 'import numpy\n'), ((1777, 1798), 'numpy.std', 'numpy.std', (['data[:, 3]'], {}), '(data[:, 3])\n', (1786, 1798), False, 'import numpy\n'), ((1819, 1840), 'numpy.std', 'numpy.std', (['data[:, 0]'], {}), '(data[:, 0])\n', (1828, 1840), False, 'import numpy\n'), ((1861, 1882), 'numpy.std', 'numpy.std', (['data[:, 1]'], {}), '(data[:, 1])\n', (1870, 1882), False, 'import numpy\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/20 16:25
# @Author : <NAME>
# @Site :
# @File : memnet.py
# @Software: PyCharm
# @Github : https://github.com/stevehamwu
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def position_encoding(sentence_size, embedding_size):
encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
ls = sentence_size + 1
le = embedding_size + 1
for i in range(1, le):
for j in range(1, ls):
encoding[i - 1, j - 1] = (i - (le - 1) / 2) * (j - (ls - 1) / 2)
encoding = 1 + 4 * encoding / embedding_size / sentence_size
return np.transpose(encoding)
class MemN2N(nn.Module):
def __init__(self,
batch_size,
vocab_size,
embedding_dim,
sentence_size,
memory_size,
hops,
num_classes,
dropout=0.5,
fix_embed=True,
name='MemN2N'):
super(MemN2N, self).__init__()
self.batch_size = batch_size
self.embedding_dim = embedding_dim
self.sentence_size = sentence_size
self.memory_size = memory_size
self.hops = hops
self.num_classes = num_classes
self.fix_embed = fix_embed
self.name = name
self.encoding = torch.from_numpy(position_encoding(1, sentence_size * embedding_dim))
self.Embedding = nn.Embedding(vocab_size, embedding_dim)
self.fc = nn.Linear(3 * embedding_dim, num_classes)
self.dropout = nn.Dropout(dropout)
def init_weights(self, embeddings):
if embeddings is not None:
self.Embedding.weight.data.copy_(embeddings)
self.Embedding.weight.requires_grad = not self.fix_embed
def set_device(self, device):
self.encoding = self.encoding.to(device)
def forward(self, stories, queries):
q_emb0 = self.Embedding(queries)
q_emb = q_emb0.view(-1, 1, 3 * self.embedding_dim)
u_0 = torch.sum(q_emb * self.encoding, 1)
u = [u_0]
for i in range(self.hops):
m_emb0 = self.Embedding(stories)
m_emb = m_emb0.view(-1, self.memory_size, 1, 3 * self.embedding_dim)
m = torch.sum(m_emb * self.encoding, -2)
u_temp = u[-1].unsqueeze(-1).transpose(-2, -1)
dotted = torch.sum(m * u_temp, -1)
probs = F.softmax(dotted, -1)
probs_temp = probs.unsqueeze(-1).transpose(-2, -1)
c_emb0 = self.Embedding(stories)
c_emb = c_emb0.view(-1, self.memory_size, 1, 3 * self.embedding_dim)
c_temp = torch.sum(c_emb * self.encoding, -2)
c = c_temp.transpose(-2, -1)
o_k = torch.sum(c * probs_temp, -1)
u_k = u[-1] + o_k
u.append(u_k)
outputs = self.dropout(self.fc(u_k))
return outputs
def gradient_noise_and_clip(self, parameters, device,
noise_stddev=1e-3, max_clip=40.0):
parameters = list(filter(lambda p: p.grad is not None, parameters))
norm = nn.utils.clip_grad_norm_(parameters, max_clip)
for p in parameters:
noise = torch.randn(p.size()) * noise_stddev
noise = noise.to(device)
p.grad.data.add_(noise)
return norm
# class MemN2N(nn.Module):
# def __init__(self,
# batch_size,
# vocab_size,
# embedding_dim,
# sentence_size,
# memory_size,
# hops,
# num_classes,
# dropout=0.5,
# fix_embed=True,
# name='MemN2N'):
# super(MemN2N, self).__init__()
# self.batch_size = batch_size
# self.embedding_dim = embedding_dim
# self.sentence_size = sentence_size
# self.memory_size = memory_size
# self.hops = hops
# self.num_classes = num_classes
# self.fix_embed = fix_embed
# self.name = name
#
# self.encoding = torch.from_numpy(position_encoding(1, sentence_size * embedding_dim))
# self.Embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)
#
# self.fc = nn.Linear(3 * embedding_dim, num_classes)
# self.dropout = nn.Dropout(dropout)
# # self.fc = nn.Sequential(
# # nn.Linear(2 * self.sentence_rnn_size, linear_hidden_dim),
# # nn.ReLU(inplace=True),
# # nn.Dropout(dropout),
# # nn.Linear(linear_hidden_dim, num_classes)
# # )
#
# def init_weights(self, embeddings):
# if embeddings is not None:
# self.Embedding = self.Embedding.from_pretrained(
# embeddings, freeze=self.fix_embed)
#
# def set_device(self, device):
# self.encoding = self.encoding.to(device)
#
# def forward(self, stories, queries):
# q_emb0 = self.Embedding(queries)
# q_emb = q_emb0.view(-1, 1, 3 * self.embedding_dim)
# u_0 = torch.sum(q_emb * self.encoding, 1, keepdim=True).expand(q_emb.size(0), stories.size(1), q_emb.size(-1))
# u = [u_0]
#
# for i in range(self.hops):
# m_emb0 = self.Embedding(stories)
# m_emb = m_emb0.view(self.batch_size, -1, self.memory_size, 1, 3 * self.embedding_dim)
# m = torch.sum(m_emb * self.encoding, -2)
#
# u_temp = u[-1].unsqueeze(-1).transpose(-2, -1)
# dotted = torch.sum(m * u_temp, -1)
# probs = F.softmax(dotted, -1)
# probs_temp = probs.unsqueeze(-1).transpose(-2, -1)
#
# c_emb0 = self.Embedding(stories)
# c_emb = c_emb0.view(self.batch_size, -1, self.memory_size, 1, 3 * self.embedding_dim)
# c_temp = torch.sum(c_emb * self.encoding, -2)
# c = c_temp.transpose(-2, -1)
# o_k = torch.sum(c * probs_temp, -1)
# u_k = u[-1] + o_k
# u.append(u_k)
#
# outputs = self.fc(u_k)
# return outputs
|
[
"torch.nn.Dropout",
"torch.nn.utils.clip_grad_norm_",
"torch.nn.Embedding",
"numpy.transpose",
"numpy.ones",
"torch.nn.functional.softmax",
"torch.nn.Linear",
"torch.sum"
] |
[((367, 425), 'numpy.ones', 'np.ones', (['(embedding_size, sentence_size)'], {'dtype': 'np.float32'}), '((embedding_size, sentence_size), dtype=np.float32)\n', (374, 425), True, 'import numpy as np\n'), ((692, 714), 'numpy.transpose', 'np.transpose', (['encoding'], {}), '(encoding)\n', (704, 714), True, 'import numpy as np\n'), ((1511, 1550), 'torch.nn.Embedding', 'nn.Embedding', (['vocab_size', 'embedding_dim'], {}), '(vocab_size, embedding_dim)\n', (1523, 1550), True, 'import torch.nn as nn\n'), ((1570, 1611), 'torch.nn.Linear', 'nn.Linear', (['(3 * embedding_dim)', 'num_classes'], {}), '(3 * embedding_dim, num_classes)\n', (1579, 1611), True, 'import torch.nn as nn\n'), ((1635, 1654), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (1645, 1654), True, 'import torch.nn as nn\n'), ((2097, 2132), 'torch.sum', 'torch.sum', (['(q_emb * self.encoding)', '(1)'], {}), '(q_emb * self.encoding, 1)\n', (2106, 2132), False, 'import torch\n'), ((3196, 3242), 'torch.nn.utils.clip_grad_norm_', 'nn.utils.clip_grad_norm_', (['parameters', 'max_clip'], {}), '(parameters, max_clip)\n', (3220, 3242), True, 'import torch.nn as nn\n'), ((2329, 2365), 'torch.sum', 'torch.sum', (['(m_emb * self.encoding)', '(-2)'], {}), '(m_emb * self.encoding, -2)\n', (2338, 2365), False, 'import torch\n'), ((2447, 2472), 'torch.sum', 'torch.sum', (['(m * u_temp)', '(-1)'], {}), '(m * u_temp, -1)\n', (2456, 2472), False, 'import torch\n'), ((2493, 2514), 'torch.nn.functional.softmax', 'F.softmax', (['dotted', '(-1)'], {}), '(dotted, -1)\n', (2502, 2514), True, 'import torch.nn.functional as F\n'), ((2726, 2762), 'torch.sum', 'torch.sum', (['(c_emb * self.encoding)', '(-2)'], {}), '(c_emb * self.encoding, -2)\n', (2735, 2762), False, 'import torch\n'), ((2823, 2852), 'torch.sum', 'torch.sum', (['(c * probs_temp)', '(-1)'], {}), '(c * probs_temp, -1)\n', (2832, 2852), False, 'import torch\n')]
|
#encoding:UTF-8
import gym
import matplotlib
import numpy as np
import sys
from collections import defaultdict
if "../" not in sys.path:
sys.path.append("../")
from lib.envs.blackjack import BlackjackEnv
from lib import plotting
matplotlib.style.use('ggplot')
env = BlackjackEnv()
def make_epsilon_greedy_policy(Q, epsilon, nA):
"""
Creates an epsilon-greedy policy based on a given Q-function and epsilon.
Args:
Q: A dictionary that maps from state -> action-values.
Each value is a numpy array of length nA (see below)
epsilon: The probability to select a random action . float between 0 and 1.
nA: Number of actions in the environment.
Returns:
A function that takes the observation as an argument and returns
the probabilities for each action in the form of a numpy array of length nA.
"""
def policy_fn(observation):
A = np.ones(nA, dtype=float) * epsilon / nA
best_action = np.argmax(Q[observation])
A[best_action] += (1.0 - epsilon)
return A
return policy_fn
def mc_control_epsilon_greedy(env, num_episodes, discount_factor=1.0, epsilon=0.1):
"""
Monte Carlo Control using Epsilon-Greedy policies.
Finds an optimal epsilon-greedy policy.
Args:
env: OpenAI gym environment.
num_episodes: Number of episodes to sample.
discount_factor: Gamma discount factor.
epsilon: Chance the sample a random action. Float betwen 0 and 1.
Returns:
A tuple (Q, policy).
Q is a dictionary mapping state -> action values.
policy is a function that takes an observation as an argument and returns
action probabilities
"""
# Keeps track of sum and count of returns for each state
# to calculate an average. We could use an array to save all
# returns (like in the book) but that's memory inefficient.
returns_sum = defaultdict(float)
returns_count = defaultdict(float)
# The final action-value function.
# A nested dictionary that maps state -> (action -> action-value).
Q = defaultdict(lambda: np.zeros(env.action_space.n))
# The policy we're following
policy = make_epsilon_greedy_policy(Q, epsilon, env.action_space.n)
for i_episode in range(1, num_episodes + 1):
if i_episode % 1000 == 0:
print("\rEpisode {}/{}.".format(i_episode, num_episodes))
sys.stdout.flush()
episode = []
state = env.reset()
for t in range(100):
probs = policy(state)
action = np.random.choice(np.arange(len(probs)), p=probs)
next_state, reward, done, _ = env.step(action)
episode.append((state, action, reward))
if done:
break
state = next_state
sa_in_episode = set([(tuple(x[0]), x[1]) for x in episode])
for state, action in sa_in_episode:
sa_pair = (state, action)
first_occurence_idx = next(i for i,x in enumerate(episode)
if x[0] == state and x[1] == action)
G = sum([x[2]*(discount_factor**i) for i,x in enumerate(episode[first_occurence_idx:])])
returns_sum[sa_pair] += G
returns_count[sa_pair] += 1.0
Q[state][action] = returns_sum[sa_pair] / returns_count[sa_pair]
return Q, policy
Q, policy = mc_control_epsilon_greedy(env, num_episodes=500000, epsilon=0.1)
# For plotting: Create value function from action-value function
# by picking the best action at each state
V = defaultdict(float)
for state, actions in Q.items():
action_value = np.max(actions)
V[state] = action_value
plotting.plot_value_function(V, title="Optimal Value Function")
|
[
"sys.path.append",
"lib.plotting.plot_value_function",
"matplotlib.style.use",
"numpy.argmax",
"numpy.zeros",
"numpy.ones",
"collections.defaultdict",
"numpy.max",
"sys.stdout.flush",
"lib.envs.blackjack.BlackjackEnv"
] |
[((237, 267), 'matplotlib.style.use', 'matplotlib.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (257, 267), False, 'import matplotlib\n'), ((275, 289), 'lib.envs.blackjack.BlackjackEnv', 'BlackjackEnv', ([], {}), '()\n', (287, 289), False, 'from lib.envs.blackjack import BlackjackEnv\n'), ((3649, 3667), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (3660, 3667), False, 'from collections import defaultdict\n'), ((3764, 3827), 'lib.plotting.plot_value_function', 'plotting.plot_value_function', (['V'], {'title': '"""Optimal Value Function"""'}), "(V, title='Optimal Value Function')\n", (3792, 3827), False, 'from lib import plotting\n'), ((143, 165), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (158, 165), False, 'import sys\n'), ((1958, 1976), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (1969, 1976), False, 'from collections import defaultdict\n'), ((1997, 2015), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (2008, 2015), False, 'from collections import defaultdict\n'), ((3720, 3735), 'numpy.max', 'np.max', (['actions'], {}), '(actions)\n', (3726, 3735), True, 'import numpy as np\n'), ((997, 1022), 'numpy.argmax', 'np.argmax', (['Q[observation]'], {}), '(Q[observation])\n', (1006, 1022), True, 'import numpy as np\n'), ((2159, 2187), 'numpy.zeros', 'np.zeros', (['env.action_space.n'], {}), '(env.action_space.n)\n', (2167, 2187), True, 'import numpy as np\n'), ((2469, 2487), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2485, 2487), False, 'import sys\n'), ((935, 959), 'numpy.ones', 'np.ones', (['nA'], {'dtype': 'float'}), '(nA, dtype=float)\n', (942, 959), True, 'import numpy as np\n')]
|
import sys
import getopt
import numpy as np
import matplotlib.pyplot as plt
import scipy
def usage():
print("""Usage:
-o, --output [output_file_name] Output file name (Required)
-h, --help Print this message (Optional)
""")
def init_params():
'''
Initializes the parameters for the log and plot directory.
'''
log_file_directory = 'logs'
plots_directory = 'plots'
def process_args():
'''
Reads the arguments from the command line. The acceptable arguments are
-h and -o. Processes them as required.
'''
print("Processing arguments ...")
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
except getopt.GetoptError as err:
print(str(err))
usage()
sys.exit(2)
global output_file_name, scenario_name
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-o", "--output"):
output_file_name = arg
try:
output_file_name
except:
print("Error: Output file name not defined")
usage()
sys.exit(2)
else:
# output_file_name = log_file_directory + "/" + output_file_name
output_file_name_split = output_file_name.split('_')
scenario_name = ""
for k,n in enumerate(output_file_name_split[1:]):
scenario_name += n
if k != len(output_file_name_split[1:]) -1:
scenario_name += '_'
print("---Output File Name: " + output_file_name)
print("Done processing argument!")
print("")
def get_complex_output():
"""
Reads from a file at output_file_name as a complex 64 bit array. Then reshapes
this into a column vector and returns.
"""
print("Getting output waveform...")
complex_output= np.fromfile(output_file_name, dtype = 'complex64').reshape(-1,1)
print("---Length: " + str(len(complex_output)))
print("Done getting output waveform!")
print("")
return complex_output
def process_output(complex_output):
'''
Reads the complex output vector. Using a rolling window of window_length,
tries to figure out the windowing for when we have silence (and ambient noise)
and when there is signal received. Based on this, estimates the SNR for the
given timestep, and produces an array of tuples, each of the type,
(timestep, SNR)
'''
t = np.arange(0, len(complex_output))
power = np.abs(complex_output)
plt.plot(t, power)
plt.show()
def main():
init_params()
process_args()
complex_output = get_complex_output()
# plt.plot(complex_output[300000:400000])
# plt.show()
process_output(complex_output)
if __name__ == '__main__':
main()
|
[
"numpy.abs",
"getopt.getopt",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"numpy.fromfile",
"sys.exit"
] |
[((2385, 2407), 'numpy.abs', 'np.abs', (['complex_output'], {}), '(complex_output)\n', (2391, 2407), True, 'import numpy as np\n'), ((2411, 2429), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'power'], {}), '(t, power)\n', (2419, 2429), True, 'import matplotlib.pyplot as plt\n'), ((2432, 2442), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2440, 2442), True, 'import matplotlib.pyplot as plt\n'), ((639, 694), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""ho:"""', "['help', 'output=']"], {}), "(sys.argv[1:], 'ho:', ['help', 'output='])\n", (652, 694), False, 'import getopt\n'), ((767, 778), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (775, 778), False, 'import sys\n'), ((907, 917), 'sys.exit', 'sys.exit', ([], {}), '()\n', (915, 917), False, 'import sys\n'), ((1100, 1111), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (1108, 1111), False, 'import sys\n'), ((1769, 1817), 'numpy.fromfile', 'np.fromfile', (['output_file_name'], {'dtype': '"""complex64"""'}), "(output_file_name, dtype='complex64')\n", (1780, 1817), True, 'import numpy as np\n')]
|
import pandas as pd
import talib
import numpy as np
import os
path = os.getcwd()+'\\'
# 读取数据
Data = pd.read_table(path+'res\\999999.txt', delim_whitespace=True, encoding='gbk')
Data = Data[:-1]
Data.columns = ['time', 'openp', 'highp', 'lowp', 'closep', 'volume', 'amount']
# 计算指标,汇总到indicators里
def myMACD(price, fastperiod=12, slowperiod=26, signalperiod=9):
ewma12 = pd.ewma(price, span=fastperiod)
ewma26 = pd.ewma(price, span=slowperiod)
dif = ewma12 - ewma26
dea = pd.ewma(dif, span=signalperiod)
bar = (dif - dea) # 有些地方的bar = (dif-dea)*2,但是talib中MACD的计算是bar = (dif-dea)*1
return dif, dea, bar
#添加数据标签
def getLabel(x):
if x == 0:
return 0
else:
return int(x/abs(x))
label = list(map(getLabel,np.diff(Data['closep'])))
label = [0]+label
MACD, signal, hist = talib.MACD(Data['closep'].values, fastperiod=12, slowperiod=26, signalperiod=9)
DIF, DEA, BAR = myMACD(Data['closep'].values, fastperiod=12, slowperiod=26, signalperiod=9)
EMA5 = talib.EMA(Data['closep'].values, timeperiod=5)
K, D = talib.STOCH(Data['highp'].values, Data['lowp'].values,
Data['closep'].values, fastk_period=14, slowk_period=3,
slowk_matype=0, slowd_period=3, slowd_matype=0)
RSI = talib.RSI(Data['closep'].values, timeperiod=14)
indicators = np.column_stack((MACD, DIF, DEA, EMA5, K, D, RSI,label))[35:]
np.savetxt(path+'res\\indicators.txt',indicators,delimiter=',',fmt='%.3f')
|
[
"talib.MACD",
"talib.EMA",
"os.getcwd",
"pandas.ewma",
"numpy.savetxt",
"talib.STOCH",
"numpy.diff",
"talib.RSI",
"numpy.column_stack",
"pandas.read_table"
] |
[((102, 180), 'pandas.read_table', 'pd.read_table', (["(path + 'res\\\\999999.txt')"], {'delim_whitespace': '(True)', 'encoding': '"""gbk"""'}), "(path + 'res\\\\999999.txt', delim_whitespace=True, encoding='gbk')\n", (115, 180), True, 'import pandas as pd\n'), ((820, 899), 'talib.MACD', 'talib.MACD', (["Data['closep'].values"], {'fastperiod': '(12)', 'slowperiod': '(26)', 'signalperiod': '(9)'}), "(Data['closep'].values, fastperiod=12, slowperiod=26, signalperiod=9)\n", (830, 899), False, 'import talib\n'), ((999, 1045), 'talib.EMA', 'talib.EMA', (["Data['closep'].values"], {'timeperiod': '(5)'}), "(Data['closep'].values, timeperiod=5)\n", (1008, 1045), False, 'import talib\n'), ((1053, 1220), 'talib.STOCH', 'talib.STOCH', (["Data['highp'].values", "Data['lowp'].values", "Data['closep'].values"], {'fastk_period': '(14)', 'slowk_period': '(3)', 'slowk_matype': '(0)', 'slowd_period': '(3)', 'slowd_matype': '(0)'}), "(Data['highp'].values, Data['lowp'].values, Data['closep'].\n values, fastk_period=14, slowk_period=3, slowk_matype=0, slowd_period=3,\n slowd_matype=0)\n", (1064, 1220), False, 'import talib\n'), ((1256, 1303), 'talib.RSI', 'talib.RSI', (["Data['closep'].values"], {'timeperiod': '(14)'}), "(Data['closep'].values, timeperiod=14)\n", (1265, 1303), False, 'import talib\n'), ((1380, 1459), 'numpy.savetxt', 'np.savetxt', (["(path + 'res\\\\indicators.txt')", 'indicators'], {'delimiter': '""","""', 'fmt': '"""%.3f"""'}), "(path + 'res\\\\indicators.txt', indicators, delimiter=',', fmt='%.3f')\n", (1390, 1459), True, 'import numpy as np\n'), ((70, 81), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (79, 81), False, 'import os\n'), ((378, 409), 'pandas.ewma', 'pd.ewma', (['price'], {'span': 'fastperiod'}), '(price, span=fastperiod)\n', (385, 409), True, 'import pandas as pd\n'), ((423, 454), 'pandas.ewma', 'pd.ewma', (['price'], {'span': 'slowperiod'}), '(price, span=slowperiod)\n', (430, 454), True, 'import pandas as pd\n'), ((491, 522), 'pandas.ewma', 'pd.ewma', (['dif'], {'span': 'signalperiod'}), '(dif, span=signalperiod)\n', (498, 522), True, 'import pandas as pd\n'), ((1317, 1374), 'numpy.column_stack', 'np.column_stack', (['(MACD, DIF, DEA, EMA5, K, D, RSI, label)'], {}), '((MACD, DIF, DEA, EMA5, K, D, RSI, label))\n', (1332, 1374), True, 'import numpy as np\n'), ((754, 777), 'numpy.diff', 'np.diff', (["Data['closep']"], {}), "(Data['closep'])\n", (761, 777), True, 'import numpy as np\n')]
|
# torch
import hydra.utils
import torch
# built-in
import copy
import os
import datetime
import time
import numpy as np
import math
# logging
import wandb
# project
import probspec_routines as ps_routines
from tester import test
import ckconv
from torchmetrics import Accuracy
import antialiasing
from optim import construct_optimizer, construct_scheduler, CLASSES_DATASET
# typing
from typing import Dict
from omegaconf import OmegaConf
def save_to_wandb(
model: torch.nn.Module,
optimizer: torch.optim.Optimizer,
lr_scheduler,
cfg: OmegaConf,
name: str = None,
epoch: int = None,
):
filename = f"{name}.pt"
if epoch is not None:
filename = "checkpoint.pt"
path = os.path.join(wandb.run.dir, filename)
torch.save(
{
"model": model.module.state_dict(),
"optimizer": optimizer.state_dict(),
"lr_scheduler": lr_scheduler.state_dict(),
"epoch": epoch,
},
path,
)
# Call wandb to save the object, syncing it directly
wandb.save(path)
def train(
model: torch.nn.Module,
dataloaders: Dict[str, torch.utils.data.DataLoader],
cfg: OmegaConf,
epoch_start: int = 0,
):
criterion = {
"AddProblem": torch.nn.functional.mse_loss,
"CopyMemory": torch.nn.CrossEntropyLoss,
"MNIST": torch.nn.CrossEntropyLoss,
"sMNIST": torch.nn.CrossEntropyLoss,
"CIFAR10": torch.nn.CrossEntropyLoss,
"sCIFAR10": torch.nn.CrossEntropyLoss,
"CIFAR100": torch.nn.CrossEntropyLoss,
"STL10": torch.nn.CrossEntropyLoss,
"Cityscapes": torch.nn.CrossEntropyLoss,
"VOC": torch.nn.CrossEntropyLoss,
"Imagenet": torch.nn.CrossEntropyLoss,
"Imagenet64": torch.nn.CrossEntropyLoss,
"Imagenet32": torch.nn.CrossEntropyLoss,
"Imagenet16": torch.nn.CrossEntropyLoss,
"Imagenet8": torch.nn.CrossEntropyLoss,
"SpeechCommands": torch.nn.CrossEntropyLoss,
"CharTrajectories": torch.nn.CrossEntropyLoss,
}[cfg.dataset]
train_function = {
"AddProblem": ps_routines.add_problem_train,
"CopyMemory": ps_routines.copy_problem_train,
"MNIST": classification_train,
"sMNIST": classification_train,
"CIFAR10": classification_train,
"sCIFAR10": classification_train,
"CIFAR100": classification_train,
"Imagenet": classification_train,
"Imagenet64": classification_train,
"Imagenet32": classification_train,
"Imagenet16": classification_train,
"Imagenet8": classification_train,
"STL10": classification_train,
"SpeechCommands": classification_train,
"CharTrajectories": classification_train,
}[cfg.dataset]
# Define optimizer and scheduler
optimizer = construct_optimizer(model, cfg)
lr_scheduler = construct_scheduler(optimizer, cfg)
# train network
_ = train_function(
model=model,
criterion=criterion,
optimizer=optimizer,
dataloaders=dataloaders,
lr_scheduler=lr_scheduler,
cfg=cfg,
epoch_start=epoch_start,
)
save_to_wandb(model, optimizer, lr_scheduler, cfg, name="final_model")
return model, optimizer, lr_scheduler
def classification_train(
model: torch.nn.Module,
criterion: torch.nn.Module,
optimizer: torch.optim.Optimizer,
dataloaders: Dict[str, torch.utils.data.DataLoader],
lr_scheduler,
cfg: OmegaConf,
epoch_start: int = 0,
):
# DEBUG
# torch.autograd.set_detect_anomaly(True)
weight_regularizer = ckconv.nn.LnLoss(
weight_loss=cfg.train.weight_decay, norm_type=2
)
limit_regularizer = ckconv.nn.LimitLnLoss(
weight_loss=cfg.train.mask_l2_norm, norm_type=2
)
# norm_regularizer = ckconv.nn.regularizers.MagnitudeRegularization(
# weight_loss=cfg.magnitude_reg, norm_type=2
# ) # TODO: This necessary?
# Permuter for psMNIST
if cfg.dataset == "sMNIST" and cfg.dataset_params.permuted:
permutation = torch.Tensor(np.random.permutation(784).astype(np.float64)).long()
# Save in the config
# cfg.dataset_params.permutation = permutation
# Noise for noise-padded sCIFAR10
if cfg.dataset == "sCIFAR10" and cfg.dataset_params.noise_padded:
rands = torch.randn(1, 1000 - 32, 96)
# Training parameters
epochs = cfg.train.epochs
# Testcases: override epochs
if cfg.testcase.load or cfg.testcase.save:
epochs = cfg.testcase.epochs
device = cfg.device
criterion = criterion().to(device)
# Log limits, before training
log_limits(model, step=0)
# Save best performing weights
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
best_top5 = 0.0
best_loss = 999
# Counter for epochs without improvement
epochs_no_improvement = 0
max_epochs_no_improvement = 100
if cfg.testcase.save or cfg.testcase.load:
testcase_losses = []
# iterate over epochs
for epoch in range(epoch_start, epochs + epoch_start):
print("Epoch {}/{}".format(epoch + 1, epochs + epoch_start))
print("-" * 30)
# Print current learning rate
for param_group in optimizer.param_groups:
print("Learning Rate: {}".format(param_group["lr"]))
print("-" * 30)
# log learning_rate of the epoch
wandb.log({"lr": optimizer.param_groups[0]["lr"]}, step=epoch + 1)
# Each epoch consist of training and validation
for phase in ["train", "validation"]:
phase_start_time = time.time()
if phase == "train":
model.train()
else:
model.eval()
# Accumulate accuracy and loss
running_loss = 0
running_corrects = 0
running_gabor_reg = 0.0
total = 0
if phase == "validation" and cfg.train.report_top5_acc:
top5 = Accuracy(
num_classes=CLASSES_DATASET[cfg.dataset],
top_k=5,
compute_on_step=False,
)
# iterate over data
for data in dataloaders[phase]:
# DALI has a different dataloader output format
if cfg.dataset == "Imagenet":
data = (data[0]["data"], data[0]["label"].squeeze(1))
inputs, labels = data
# Add padding if noise_padding
if cfg.dataset_params.noise_padded and cfg.dataset == "sCIFAR10":
inputs = torch.cat(
(
inputs.permute(0, 2, 1, 3).reshape(inputs.shape[0], 32, 96),
rands.repeat(inputs.shape[0], 1, 1),
),
dim=1,
).permute(0, 2, 1)
else:
# Make sequential if sMNIST or sCIFAR10
if cfg.dataset in ["sMNIST", "sCIFAR10"]:
_, in_channels, x, y = inputs.shape
inputs = inputs.view(-1, in_channels, x * y)
# Permute if psMNIST
if cfg.dataset_params.permuted and cfg.dataset == "sMNIST":
inputs = inputs[:, :, permutation]
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
train = phase == "train"
with torch.set_grad_enabled(train):
# FwrdPhase:
inputs = torch.dropout(inputs, cfg.net.dropout_in, train)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# Regularization:
if cfg.train.weight_decay > 0.0:
loss = loss + weight_regularizer(model)
if cfg.train.mask_l2_norm > 0.0:
loss = loss + limit_regularizer(model)
# if cfg.magnitude_reg > 0.0:
# loss = loss + norm_regularizer(model)
if cfg.kernel.regularize:
gabor_reg = antialiasing.regularize_gabornet(
model,
cfg.kernel.regularize_params.res,
cfg.kernel.regularize_params.factor,
cfg.kernel.regularize_params.target,
cfg.kernel.regularize_params.fn,
cfg.kernel.regularize_params.method,
gauss_stddevs=cfg.kernel.regularize_params.gauss_stddevs,
)
loss += gabor_reg
running_gabor_reg += gabor_reg
# DEBUG
# modules = antialiasing.get_flexconv_modules(model)
# for t in ['sines', 'gausses', 'gabor']:
# freqs = []
# for module in modules:
# freqs.append(antialiasing.gabor_layer_frequencies(module, t, config.regularize_gabornet_method))
# freqs = torch.stack(freqs)
# print(f"{t} frequencies: {freqs[0]}")
# print(f"Lambda: {config.regularize_gabornet_lambda}")
# print(f"Resolution: {config.regularize_gabornet_res}")
# print(f"Total regularization term (incl. lambda): {gabor_reg:.8f}")
if cfg.testcase.save or cfg.testcase.load:
testcase_losses.append(loss.item())
# Backward pass:
if phase == "train":
loss.backward()
if cfg.train.grad_clip > 0:
torch.nn.utils.clip_grad_norm_(
model.parameters(), cfg.train.grad_clip
)
optimizer.step()
# update the lr_scheduler
if isinstance(
lr_scheduler,
(
torch.optim.lr_scheduler.CosineAnnealingLR,
ckconv.nn.LinearWarmUp_LRScheduler,
),
):
lr_scheduler.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += (preds == labels).sum().item()
total += labels.size(0)
if phase == "validation" and cfg.train.report_top5_acc:
pred_sm = torch.nn.functional.softmax(outputs, dim=1)
# torchmetrics.Accuracy requires everything to be on CPU
top5(pred_sm.to("cpu"), labels.to("cpu"))
if total >= cfg.testcase.batches:
break
# Log GaborNet frequencies
if cfg.kernel.regularize and phase == "train":
stats = antialiasing.get_gabornet_summaries(
model,
cfg.kernel.regularize_params.target,
cfg.kernel.regularize_params.method,
)
wandb.log(stats, step=epoch + 1)
# statistics of the epoch
epoch_loss = running_loss / total
epoch_acc = running_corrects / total
epoch_gabor_reg = running_gabor_reg / total
if phase == "validation" and cfg.train.report_top5_acc:
epoch_top5 = top5.compute()
print(
"{} Loss: {:.4f} Acc: {:.4f} Top-5: {:.4f}".format(
phase, epoch_loss, epoch_acc, epoch_top5
)
)
else:
epoch_top5 = 0.0
print(
"{} Loss: {:.4f} Acc: {:.4f}".format(phase, epoch_loss, epoch_acc)
)
print(f"GaborNet regularization: {epoch_gabor_reg:.8f}")
print(datetime.datetime.now())
phase_end_time = time.time()
phase_time = phase_end_time - phase_start_time
# log statistics of the epoch
wandb.log(
{
"accuracy" + "_" + phase: epoch_acc,
"accuracy_top5" + "_" + phase: epoch_top5,
"loss" + "_" + phase: epoch_loss,
"gabor_reg" + "_" + phase: epoch_gabor_reg,
phase + "_time": phase_time,
},
step=epoch + 1,
)
# If better validation accuracy, replace best weights and compute the test performance
if phase == "validation" and epoch_acc >= best_acc:
# Updates to the weights will not happen if the accuracy is equal but loss does not diminish
if (epoch_acc == best_acc) and (epoch_loss > best_loss):
pass
else:
best_acc = epoch_acc
best_top5 = epoch_top5
best_loss = epoch_loss
best_model_wts = copy.deepcopy(model.state_dict())
save_to_wandb(model, optimizer, lr_scheduler, cfg, epoch=epoch + 1)
# Log best results so far and the weights of the model.
wandb.run.summary["best_val_accuracy"] = best_acc
wandb.run.summary["best_val_loss"] = best_loss
# Clean CUDA Memory
del inputs, outputs, labels
torch.cuda.empty_cache()
# Perform test and log results
if cfg.dataset in ["SpeechCommands", "CharTrajectories"]:
test_acc, test_top5 = test(model, dataloaders["test"], cfg)
else:
test_acc = best_acc
test_top5 = best_top5
wandb.run.summary["best_test_accuracy"] = test_acc
wandb.run.summary["best_test_top5"] = test_top5
wandb.log(
{"accuracy_test": test_acc, "accuracy_top5_test": test_top5},
step=epoch + 1,
)
# Reset counter of epochs without progress
epochs_no_improvement = 0
elif phase == "validation" and epoch_acc < best_acc:
# Otherwise, increase counter
epochs_no_improvement += 1
# Log limits
log_limits(model, epoch + 1)
# Update scheduler
if (
isinstance(lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau)
and phase == "validation"
):
lr_scheduler.step(epoch_acc)
# Update scheduler
if isinstance(lr_scheduler, torch.optim.lr_scheduler.MultiStepLR) or isinstance(
lr_scheduler, torch.optim.lr_scheduler.ExponentialLR
):
lr_scheduler.step()
print()
# Check how many epochs without improvement have passed, and, if required, stop training.
if epochs_no_improvement == max_epochs_no_improvement:
print(
f"Stopping training due to {epochs_no_improvement} epochs of no improvement in validation accuracy."
)
break
# Report best results
print("Best Val Acc: {:.4f}".format(best_acc))
if cfg.train.report_top5_acc:
print("Best Val Top-5: {:.4f}".format(best_top5))
# Load best model weights
model.load_state_dict(best_model_wts)
# Print learned limits
_print_learned_limits(model)
# Testcases: load/save losses for comparison
if cfg.testcase.save:
testcase_losses = np.array(testcase_losses)
with open(hydra.utils.to_absolute_path(cfg.testcase.path), 'wb') as f:
np.save(f, testcase_losses, allow_pickle=True)
if cfg.testcase.load:
testcase_losses = np.array(testcase_losses)
with open(hydra.utils.to_absolute_path(cfg.testcase.path), 'rb') as f:
target_losses = np.load(f, allow_pickle=True)
if np.allclose(testcase_losses, target_losses):
print("Testcase passed!")
else:
diff = np.sum(testcase_losses - target_losses)
raise AssertionError(f"Testcase failed: diff = {diff:.8f}")
# Return model
return model
def log_limits(model, step):
log = {}
limitss = get_limits(model)
for i, limits in enumerate(limitss):
log.update({f"limit_{i}_{k}": v for (k, v) in limits.items()})
wandb.log(log, step=step)
def get_limits(model):
limitss = []
for m in model.modules():
if isinstance(m, ckconv.nn.FlexConv):
limits = m.mask_params.detach().cpu()
# top, bottom, left, right
if m.kernel_dim_linear == 1:
(mean, std) = limits.squeeze()
limitss.append(
{
"mean": mean,
"std": std,
}
)
elif m.kernel_dim_linear == 2:
(mean_y, std_y), (mean_x, std_x) = limits
limitss.append(
{
"mean_y": mean_y,
"std_y": std_y,
"mean_x": mean_x,
"std_x": std_x,
}
)
return limitss
def _print_learned_limits(model):
limits_final = []
print(50 * "-")
print("Learned limits:")
for m in model.modules():
if isinstance(m, ckconv.nn.FlexConv):
limits = m.mask_params.detach().cpu()
limits_final.append(limits)
print(limits)
print(50 * "-")
|
[
"wandb.log",
"numpy.load",
"numpy.sum",
"numpy.allclose",
"torch.randn",
"optim.construct_optimizer",
"tester.test",
"torch.dropout",
"os.path.join",
"antialiasing.get_gabornet_summaries",
"antialiasing.regularize_gabornet",
"datetime.datetime.now",
"ckconv.nn.LnLoss",
"ckconv.nn.LimitLnLoss",
"numpy.save",
"torch.max",
"torch.set_grad_enabled",
"wandb.save",
"numpy.random.permutation",
"time.time",
"torchmetrics.Accuracy",
"optim.construct_scheduler",
"torch.nn.functional.softmax",
"numpy.array",
"torch.cuda.empty_cache"
] |
[((715, 752), 'os.path.join', 'os.path.join', (['wandb.run.dir', 'filename'], {}), '(wandb.run.dir, filename)\n', (727, 752), False, 'import os\n'), ((1052, 1068), 'wandb.save', 'wandb.save', (['path'], {}), '(path)\n', (1062, 1068), False, 'import wandb\n'), ((2831, 2862), 'optim.construct_optimizer', 'construct_optimizer', (['model', 'cfg'], {}), '(model, cfg)\n', (2850, 2862), False, 'from optim import construct_optimizer, construct_scheduler, CLASSES_DATASET\n'), ((2882, 2917), 'optim.construct_scheduler', 'construct_scheduler', (['optimizer', 'cfg'], {}), '(optimizer, cfg)\n', (2901, 2917), False, 'from optim import construct_optimizer, construct_scheduler, CLASSES_DATASET\n'), ((3619, 3684), 'ckconv.nn.LnLoss', 'ckconv.nn.LnLoss', ([], {'weight_loss': 'cfg.train.weight_decay', 'norm_type': '(2)'}), '(weight_loss=cfg.train.weight_decay, norm_type=2)\n', (3635, 3684), False, 'import ckconv\n'), ((3723, 3793), 'ckconv.nn.LimitLnLoss', 'ckconv.nn.LimitLnLoss', ([], {'weight_loss': 'cfg.train.mask_l2_norm', 'norm_type': '(2)'}), '(weight_loss=cfg.train.mask_l2_norm, norm_type=2)\n', (3744, 3793), False, 'import ckconv\n'), ((16937, 16962), 'wandb.log', 'wandb.log', (['log'], {'step': 'step'}), '(log, step=step)\n', (16946, 16962), False, 'import wandb\n'), ((4356, 4385), 'torch.randn', 'torch.randn', (['(1)', '(1000 - 32)', '(96)'], {}), '(1, 1000 - 32, 96)\n', (4367, 4385), False, 'import torch\n'), ((5434, 5500), 'wandb.log', 'wandb.log', (["{'lr': optimizer.param_groups[0]['lr']}"], {'step': '(epoch + 1)'}), "({'lr': optimizer.param_groups[0]['lr']}, step=epoch + 1)\n", (5443, 5500), False, 'import wandb\n'), ((16090, 16115), 'numpy.array', 'np.array', (['testcase_losses'], {}), '(testcase_losses)\n', (16098, 16115), True, 'import numpy as np\n'), ((16306, 16331), 'numpy.array', 'np.array', (['testcase_losses'], {}), '(testcase_losses)\n', (16314, 16331), True, 'import numpy as np\n'), ((16480, 16523), 'numpy.allclose', 'np.allclose', (['testcase_losses', 'target_losses'], {}), '(testcase_losses, target_losses)\n', (16491, 16523), True, 'import numpy as np\n'), ((5635, 5646), 'time.time', 'time.time', ([], {}), '()\n', (5644, 5646), False, 'import time\n'), ((12362, 12373), 'time.time', 'time.time', ([], {}), '()\n', (12371, 12373), False, 'import time\n'), ((12488, 12725), 'wandb.log', 'wandb.log', (["{('accuracy' + '_' + phase): epoch_acc, ('accuracy_top5' + '_' + phase):\n epoch_top5, ('loss' + '_' + phase): epoch_loss, ('gabor_reg' + '_' +\n phase): epoch_gabor_reg, (phase + '_time'): phase_time}"], {'step': '(epoch + 1)'}), "({('accuracy' + '_' + phase): epoch_acc, ('accuracy_top5' + '_' +\n phase): epoch_top5, ('loss' + '_' + phase): epoch_loss, ('gabor_reg' +\n '_' + phase): epoch_gabor_reg, (phase + '_time'): phase_time}, step=\n epoch + 1)\n", (12497, 12725), False, 'import wandb\n'), ((16207, 16253), 'numpy.save', 'np.save', (['f', 'testcase_losses'], {'allow_pickle': '(True)'}), '(f, testcase_losses, allow_pickle=True)\n', (16214, 16253), True, 'import numpy as np\n'), ((16439, 16468), 'numpy.load', 'np.load', (['f'], {'allow_pickle': '(True)'}), '(f, allow_pickle=True)\n', (16446, 16468), True, 'import numpy as np\n'), ((16596, 16635), 'numpy.sum', 'np.sum', (['(testcase_losses - target_losses)'], {}), '(testcase_losses - target_losses)\n', (16602, 16635), True, 'import numpy as np\n'), ((6015, 6102), 'torchmetrics.Accuracy', 'Accuracy', ([], {'num_classes': 'CLASSES_DATASET[cfg.dataset]', 'top_k': '(5)', 'compute_on_step': '(False)'}), '(num_classes=CLASSES_DATASET[cfg.dataset], top_k=5, compute_on_step\n =False)\n', (6023, 6102), False, 'from torchmetrics import Accuracy\n'), ((11295, 11416), 'antialiasing.get_gabornet_summaries', 'antialiasing.get_gabornet_summaries', (['model', 'cfg.kernel.regularize_params.target', 'cfg.kernel.regularize_params.method'], {}), '(model, cfg.kernel.regularize_params.\n target, cfg.kernel.regularize_params.method)\n', (11330, 11416), False, 'import antialiasing\n'), ((11507, 11539), 'wandb.log', 'wandb.log', (['stats'], {'step': '(epoch + 1)'}), '(stats, step=epoch + 1)\n', (11516, 11539), False, 'import wandb\n'), ((12308, 12331), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (12329, 12331), False, 'import datetime\n'), ((7564, 7593), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['train'], {}), '(train)\n', (7586, 7593), False, 'import torch\n'), ((7657, 7705), 'torch.dropout', 'torch.dropout', (['inputs', 'cfg.net.dropout_in', 'train'], {}), '(inputs, cfg.net.dropout_in, train)\n', (7670, 7705), False, 'import torch\n'), ((7781, 7802), 'torch.max', 'torch.max', (['outputs', '(1)'], {}), '(outputs, 1)\n', (7790, 7802), False, 'import torch\n'), ((10912, 10955), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['outputs'], {'dim': '(1)'}), '(outputs, dim=1)\n', (10939, 10955), False, 'import torch\n'), ((13873, 13897), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (13895, 13897), False, 'import torch\n'), ((14386, 14477), 'wandb.log', 'wandb.log', (["{'accuracy_test': test_acc, 'accuracy_top5_test': test_top5}"], {'step': '(epoch + 1)'}), "({'accuracy_test': test_acc, 'accuracy_top5_test': test_top5},\n step=epoch + 1)\n", (14395, 14477), False, 'import wandb\n'), ((8325, 8614), 'antialiasing.regularize_gabornet', 'antialiasing.regularize_gabornet', (['model', 'cfg.kernel.regularize_params.res', 'cfg.kernel.regularize_params.factor', 'cfg.kernel.regularize_params.target', 'cfg.kernel.regularize_params.fn', 'cfg.kernel.regularize_params.method'], {'gauss_stddevs': 'cfg.kernel.regularize_params.gauss_stddevs'}), '(model, cfg.kernel.regularize_params.res,\n cfg.kernel.regularize_params.factor, cfg.kernel.regularize_params.\n target, cfg.kernel.regularize_params.fn, cfg.kernel.regularize_params.\n method, gauss_stddevs=cfg.kernel.regularize_params.gauss_stddevs)\n', (8357, 8614), False, 'import antialiasing\n'), ((14073, 14110), 'tester.test', 'test', (['model', "dataloaders['test']", 'cfg'], {}), "(model, dataloaders['test'], cfg)\n", (14077, 14110), False, 'from tester import test\n'), ((4093, 4119), 'numpy.random.permutation', 'np.random.permutation', (['(784)'], {}), '(784)\n', (4114, 4119), True, 'import numpy as np\n')]
|
#%%
import torch
from torch import optim, nn
from torchvision import models, transforms
model = models.vgg16(pretrained=True)
#%%
class FeatureExtractor(nn.Module):
def __init__(self, model):
super(FeatureExtractor, self).__init__()
# Extract VGG-16 Feature Layers
self.features = list(model.features)
self.features = nn.Sequential(*self.features)
# Extract VGG-16 Average Pooling Layer
self.pooling = model.avgpool
# Convert the image into one-dimensional vector
self.flatten = nn.Flatten()
# Extract the first part of fully-connected layer from VGG16
self.fc = model.classifier[0]
def forward(self, x):
# It will take the input 'x' until it returns the feature vector called 'out'
out = self.features(x)
out = self.pooling(out)
out = self.flatten(out)
out = self.fc(out)
return out
# Initialize the model
model = models.vgg16(pretrained=True)
new_model = FeatureExtractor(model)
# Change the device to GPU
device = torch.device('cuda:0' if torch.cuda.is_available() else "cpu")
new_model = new_model.to(device)
#%%
import numpy as np
# Transform the image, so it becomes readable with the model
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.CenterCrop(512),
transforms.Resize(224),
transforms.ToTensor()
])
# Will contain the feature
features = []
#%%
import cv2
# # Read the file
img = cv2.imread('1.jpg')
# Transform the image
img = transform(img)
# Reshape the image. PyTorch model reads 4-dimensional tensor
# [batch_size, channels, width, height]
img = img.reshape(1, 3, 224, 224)
img = img.to(device)
# We only extract features, so we don't need gradient
with torch.no_grad():
# Extract the feature from the image
feature = new_model(img)
# Convert to NumPy Array, Reshape it, and save it to features variable
features.append(feature.cpu().detach().numpy().reshape(-1))
# Convert to NumPy Array
features = np.array(features)
# %%
features
# %%
len(features[0])
# %%
from lshash import LSHash
lsh = LSHash(6, 8)
df = [[0.929, 0.9404, 0.82372, 0.3335, 1.0, 0.654, 0.1, 0.72],
[0.9239, 0.94, 1.0 , 0.596, 0.973, 0.338, 0.20, 0.1 ]]
lsh.index(df[1])
lsh.query(df[0],distance_func='cosine')
# %%
lsh = 0
# %%
x = -0.02
y = -0.003
z = -0.3
d = (x-y) / (z-y)
# %%
d
# %%
a= [1, 2 ,3]
b = []
b = a + b
b
# %%
|
[
"lshash.LSHash",
"torch.nn.Sequential",
"torchvision.transforms.Resize",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.ToTensor",
"cv2.imread",
"numpy.array",
"torch.cuda.is_available",
"torchvision.transforms.CenterCrop",
"torchvision.models.vgg16",
"torch.no_grad",
"torch.nn.Flatten"
] |
[((97, 126), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (109, 126), False, 'from torchvision import models, transforms\n'), ((881, 910), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (893, 910), False, 'from torchvision import models, transforms\n'), ((1421, 1440), 'cv2.imread', 'cv2.imread', (['"""1.jpg"""'], {}), "('1.jpg')\n", (1431, 1440), False, 'import cv2\n'), ((1955, 1973), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (1963, 1973), True, 'import numpy as np\n'), ((2048, 2060), 'lshash.LSHash', 'LSHash', (['(6)', '(8)'], {}), '(6, 8)\n', (2054, 2060), False, 'from lshash import LSHash\n'), ((1700, 1715), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1713, 1715), False, 'import torch\n'), ((336, 365), 'torch.nn.Sequential', 'nn.Sequential', (['*self.features'], {}), '(*self.features)\n', (349, 365), False, 'from torch import optim, nn\n'), ((509, 521), 'torch.nn.Flatten', 'nn.Flatten', ([], {}), '()\n', (519, 521), False, 'from torch import optim, nn\n'), ((1009, 1034), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1032, 1034), False, 'import torch\n'), ((1200, 1223), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (1221, 1223), False, 'from torchvision import models, transforms\n'), ((1227, 1253), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(512)'], {}), '(512)\n', (1248, 1253), False, 'from torchvision import models, transforms\n'), ((1257, 1279), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224)'], {}), '(224)\n', (1274, 1279), False, 'from torchvision import models, transforms\n'), ((1283, 1304), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1302, 1304), False, 'from torchvision import models, transforms\n')]
|
import pandas as pd
import csv
import numpy as np
from datetime import datetime
import json
import os
from shapely.geometry import shape, Point
from fuzzywuzzy import process
## TODO implement string similarity for crime categories
## TODO reiterate through this data set once a week for discrepancies
## Aggregating Legacy and Current Crime Tracking System
df1 = pd.read_csv("https://data.boston.gov/dataset/6220d948-eae2-4e4b-8723-2dc8e67722a3/resource/12cb3883-56f5-47de-afa5-3b1cf61b257b/download/tmp3bg1m024.csv")
df = pd.read_csv("https://data.boston.gov/dataset/eefad66a-e805-4b35-b170-d26e2028c373/resource/ba5ed0e2-e901-438c-b2e0-4acfc3c452b9/download/crime-incident-reports-july-2012-august-2015-source-legacy-system.csv", low_memory=False)
## pulling test data from geojson
geo = {}
with open('./json_files/boston.geojson') as constraints:
geo = json.load(constraints)
## defining functions
def colComparison(df1,df2,colname1,colname2):
result = []
for item in set(df1[colname1]):
if item.upper() in set(df2[colname2]):
result.append(item)
else:
continue
return result
def mergeCols(col1,col2):
return np.concatenate((col1.values, col2.values))
def totime(d):
result = 0
try:
result = datetime.strptime(d, '%m/%d/%Y %H:%M:%S %p').strftime("%H")
except:
result = datetime.strptime(d, '%Y-%m-%d %H:%M:%S').strftime("%H")
return result
def toyear(d):
result = 0
try:
result = datetime.strptime(d, '%m/%d/%Y %H:%M:%S %p').strftime("%Y")
except:
result = datetime.strptime(d, '%Y-%m-%d %H:%M:%S').strftime("%Y")
return result
## classifying crime to neighborhoods
def classify(location):
result = ""
y = float(location.split(", ")[0][1:len(location.split(", ")[0])])
x = float(location.split(", ")[1][0:len(location.split(", ")[1])-1])
point = Point(x,y)
for feature in geo["features"]:
nb_name = feature["properties"]["Name"]
area = shape(feature["geometry"])
if(area.contains(point)):
if(nb_name == "Chester Square"):
print("In CS")
result = nb_name
break
else:
continue
return result
newCategories = df1["OFFENSE_CODE_GROUP"].unique()
def legacyToNew(category):
highest = process.extractOne(category, newCategories)
if(highest[1] < 50):
return category
else:
return highest[0]
# Recategorizing legacy crime categories
df["OFFENSE_CODE_GROUP"] = df["INCIDENT_TYPE_DESCRIPTION"].apply(legacyToNew)
data = {}
data["id"] = mergeCols(df["COMPNOS"],df1["INCIDENT_NUMBER"])
data["category"] = mergeCols(df["OFFENSE_CODE_GROUP"],df1["OFFENSE_CODE_GROUP"])
data["year"] = mergeCols(df["Year"],df1["YEAR"])
data["month"]= mergeCols(df["Month"],df1["MONTH"])
data["day_of_Week"]= mergeCols(df["DAY_WEEK"], df1["DAY_OF_WEEK"])
data["ucr_oart"] = mergeCols(df["UCRPART"], df1["UCR_PART"])
data["lat"] = mergeCols(df["X"], df1["Lat"])
data["long"] = mergeCols(df["Y"] , df1["Long"])
data["location"] = mergeCols(df["Location"], df1["Location"])
data["street"] = mergeCols(df["STREETNAME"], df1["STREET"])
data["date"] = mergeCols(df["FROMDATE"], df1["OCCURRED_ON_DATE"])
crime = pd.DataFrame(data)
# Creating time Field, Classifying Crime, Saving base level dataset
crime["time"] = crime["date"].apply(totime)
crime["year"] = crime["date"].apply(toyear)
print("classifying")
crime["neighborhood"] = crime["location"].apply(classify)
crime.to_csv("./csv_files/boston_crime.csv")
# Aggregating Dataset
aggregate = crime.groupby(["neighborhood","category","year","time"]).agg('count')
aggregate.rename(columns={'id':'value'}, inplace=True)
aggregate.reset_index(inplace=True)
aggregate[["neighborhood","category","year","time","value"]].to_csv("./csv_files/crime.csv")
|
[
"pandas.DataFrame",
"shapely.geometry.Point",
"json.load",
"pandas.read_csv",
"fuzzywuzzy.process.extractOne",
"datetime.datetime.strptime",
"shapely.geometry.shape",
"numpy.concatenate"
] |
[((366, 530), 'pandas.read_csv', 'pd.read_csv', (['"""https://data.boston.gov/dataset/6220d948-eae2-4e4b-8723-2dc8e67722a3/resource/12cb3883-56f5-47de-afa5-3b1cf61b257b/download/tmp3bg1m024.csv"""'], {}), "(\n 'https://data.boston.gov/dataset/6220d948-eae2-4e4b-8723-2dc8e67722a3/resource/12cb3883-56f5-47de-afa5-3b1cf61b257b/download/tmp3bg1m024.csv'\n )\n", (377, 530), True, 'import pandas as pd\n'), ((526, 762), 'pandas.read_csv', 'pd.read_csv', (['"""https://data.boston.gov/dataset/eefad66a-e805-4b35-b170-d26e2028c373/resource/ba5ed0e2-e901-438c-b2e0-4acfc3c452b9/download/crime-incident-reports-july-2012-august-2015-source-legacy-system.csv"""'], {'low_memory': '(False)'}), "(\n 'https://data.boston.gov/dataset/eefad66a-e805-4b35-b170-d26e2028c373/resource/ba5ed0e2-e901-438c-b2e0-4acfc3c452b9/download/crime-incident-reports-july-2012-august-2015-source-legacy-system.csv'\n , low_memory=False)\n", (537, 762), True, 'import pandas as pd\n'), ((3259, 3277), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (3271, 3277), True, 'import pandas as pd\n'), ((863, 885), 'json.load', 'json.load', (['constraints'], {}), '(constraints)\n', (872, 885), False, 'import json\n'), ((1177, 1219), 'numpy.concatenate', 'np.concatenate', (['(col1.values, col2.values)'], {}), '((col1.values, col2.values))\n', (1191, 1219), True, 'import numpy as np\n'), ((1897, 1908), 'shapely.geometry.Point', 'Point', (['x', 'y'], {}), '(x, y)\n', (1902, 1908), False, 'from shapely.geometry import shape, Point\n'), ((2338, 2381), 'fuzzywuzzy.process.extractOne', 'process.extractOne', (['category', 'newCategories'], {}), '(category, newCategories)\n', (2356, 2381), False, 'from fuzzywuzzy import process\n'), ((2007, 2033), 'shapely.geometry.shape', 'shape', (["feature['geometry']"], {}), "(feature['geometry'])\n", (2012, 2033), False, 'from shapely.geometry import shape, Point\n'), ((1277, 1321), 'datetime.datetime.strptime', 'datetime.strptime', (['d', '"""%m/%d/%Y %H:%M:%S %p"""'], {}), "(d, '%m/%d/%Y %H:%M:%S %p')\n", (1294, 1321), False, 'from datetime import datetime\n'), ((1498, 1542), 'datetime.datetime.strptime', 'datetime.strptime', (['d', '"""%m/%d/%Y %H:%M:%S %p"""'], {}), "(d, '%m/%d/%Y %H:%M:%S %p')\n", (1515, 1542), False, 'from datetime import datetime\n'), ((1366, 1407), 'datetime.datetime.strptime', 'datetime.strptime', (['d', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(d, '%Y-%m-%d %H:%M:%S')\n", (1383, 1407), False, 'from datetime import datetime\n'), ((1587, 1628), 'datetime.datetime.strptime', 'datetime.strptime', (['d', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(d, '%Y-%m-%d %H:%M:%S')\n", (1604, 1628), False, 'from datetime import datetime\n')]
|
import torch
from collections import OrderedDict
from torch.nn import utils, functional as F
from torch.optim import Adam
from torch.backends import cudnn
from model import build_model, weights_init
import scipy.misc as sm
import numpy as np
import os
import cv2
from loss import bce_iou_loss
# normalize the predicted SOD probability map
def normPRED(d):
ma = torch.max(d)
mi = torch.min(d)
dn = (d - mi) / (ma - mi)
return dn
Dataset_dict = {'e': 'ECSSD', 'p': 'PASCALS', 'd': 'DUTOMRON', 'h': 'HKU-IS', 's': 'SOD', 't': 'DUTS_TE'}
class Solver(object):
def __init__(self, train_loader, test_loader, config):
self.train_loader = train_loader
self.test_loader = test_loader
self.config = config
self.iter_size = config.iter_size
self.show_every = config.show_every
self.lr_decay_epoch = [20, ]
self.build_model()
self.loss = bce_iou_loss
if config.mode == 'test':
print('Loading pre-trained model from %s...' % self.config.model)
if self.config.cuda:
self.net.load_state_dict(torch.load(self.config.model))
else:
self.net.load_state_dict(torch.load(self.config.model, map_location='cpu'))
self.net.eval()
# print the network information and parameter numbers
def print_network(self, model, name):
num_params = 0
for p in model.parameters():
num_params += p.numel()
print(name)
print(model)
print("The number of parameters: {}".format(num_params))
# build the network
def build_model(self):
self.net = build_model(self.config.arch)
if self.config.cuda:
self.net = self.net.cuda()
self.net.train()
self.net.apply(weights_init)
if self.config.load == '':
self.net.base.load_state_dict(torch.load(self.config.pretrained_model))
else:
self.net.load_state_dict(torch.load(self.config.load))
self.lr = self.config.lr
self.wd = self.config.wd
self.optimizer = Adam(filter(lambda p: p.requires_grad, self.net.parameters()), lr=self.lr,
weight_decay=self.wd)
# self.print_network(self.net, 'BINet Structure')
def test(self):
self.net.eval()
for i, data_batch in enumerate(self.test_loader):
images, name, im_size = data_batch['image'], data_batch['name'][0], np.asarray(data_batch['size'])
im_size = im_size[1], im_size[0]
# print(im_size)
with torch.no_grad():
if self.config.cuda:
images = images.cuda()
preds = self.net(images)[1]
preds = normPRED(torch.sigmoid(preds))
pred = np.squeeze(preds.cpu().data.numpy())
multi_fuse = 255 * pred
multi_fuse = cv2.resize(multi_fuse, dsize=im_size, interpolation=cv2.INTER_LINEAR)
cv2.imwrite(os.path.join(self.config.test_fold, name[:-4] + '.png'), multi_fuse)
print(Dataset_dict[self.config.sal_mode] + ' Test Done!')
def deep_supervision_loss(self, preds, gt):
losses = []
for pred in preds:
losses.append(self.loss(pred, gt))
sum_loss = losses[0] + losses[1] + losses[2] / 2 + losses[3] / 4 + losses[4] / 8 + losses[5] / 8
return sum_loss
# training phase
def train(self):
iter_num = len(self.train_loader.dataset) // self.config.batch_size
for epoch in range(self.config.epoch):
self.net.zero_grad()
for i, data_batch in enumerate(self.train_loader):
sal_image, sal_label = data_batch['sal_image'], data_batch['sal_label']
if (sal_image.size(2) != sal_label.size(2)) or (sal_image.size(3) != sal_label.size(3)):
print('IMAGE ERROR, PASSING```')
continue
if self.config.cuda:
# cudnn.benchmark = True
sal_image, sal_label = sal_image.cuda(), sal_label.cuda()
sal_preds = self.net(sal_image)
sum_loss = self.deep_supervision_loss(sal_preds, sal_label)
self.optimizer.zero_grad()
sum_loss.backward()
self.optimizer.step()
if i % (self.show_every // self.config.batch_size) == 0:
if i == 0:
x_showEvery = 1
print(
'epoch: [%2d/%2d], iter: [%5d/%5d] || sum_loss : %10.4f' % (
epoch, self.config.epoch, i, iter_num, sum_loss.cpu().data))
print('Learning rate: ' + str(self.lr))
if (epoch + 1) % self.config.epoch_save == 0:
torch.save(self.net.state_dict(), '%s/models/epoch_%d.pth' % (self.config.save_folder, epoch + 1))
if epoch in self.lr_decay_epoch:
self.lr = self.lr * 0.1
self.optimizer = Adam(filter(lambda p: p.requires_grad, self.net.parameters()), lr=self.lr,
weight_decay=self.wd)
torch.save(self.net.state_dict(), '%s/models/final.pth' % self.config.save_folder)
|
[
"model.build_model",
"torch.load",
"numpy.asarray",
"torch.sigmoid",
"torch.max",
"torch.no_grad",
"os.path.join",
"torch.min",
"cv2.resize"
] |
[((367, 379), 'torch.max', 'torch.max', (['d'], {}), '(d)\n', (376, 379), False, 'import torch\n'), ((389, 401), 'torch.min', 'torch.min', (['d'], {}), '(d)\n', (398, 401), False, 'import torch\n'), ((1659, 1688), 'model.build_model', 'build_model', (['self.config.arch'], {}), '(self.config.arch)\n', (1670, 1688), False, 'from model import build_model, weights_init\n'), ((1897, 1937), 'torch.load', 'torch.load', (['self.config.pretrained_model'], {}), '(self.config.pretrained_model)\n', (1907, 1937), False, 'import torch\n'), ((1990, 2018), 'torch.load', 'torch.load', (['self.config.load'], {}), '(self.config.load)\n', (2000, 2018), False, 'import torch\n'), ((2481, 2511), 'numpy.asarray', 'np.asarray', (["data_batch['size']"], {}), "(data_batch['size'])\n", (2491, 2511), True, 'import numpy as np\n'), ((2603, 2618), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2616, 2618), False, 'import torch\n'), ((2928, 2997), 'cv2.resize', 'cv2.resize', (['multi_fuse'], {'dsize': 'im_size', 'interpolation': 'cv2.INTER_LINEAR'}), '(multi_fuse, dsize=im_size, interpolation=cv2.INTER_LINEAR)\n', (2938, 2997), False, 'import cv2\n'), ((1116, 1145), 'torch.load', 'torch.load', (['self.config.model'], {}), '(self.config.model)\n', (1126, 1145), False, 'import torch\n'), ((1206, 1255), 'torch.load', 'torch.load', (['self.config.model'], {'map_location': '"""cpu"""'}), "(self.config.model, map_location='cpu')\n", (1216, 1255), False, 'import torch\n'), ((2777, 2797), 'torch.sigmoid', 'torch.sigmoid', (['preds'], {}), '(preds)\n', (2790, 2797), False, 'import torch\n'), ((3026, 3081), 'os.path.join', 'os.path.join', (['self.config.test_fold', "(name[:-4] + '.png')"], {}), "(self.config.test_fold, name[:-4] + '.png')\n", (3038, 3081), False, 'import os\n')]
|
# --------------------------------------------------------
# P2ORM: Formulation, Inference & Application
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# --------------------------------------------------------
import numpy as np
import os
import ntpath
import torch
import scipy.io as sio
import sys
from PIL import Image
import cv2
import matplotlib.pyplot as plt
plt.switch_backend('agg') # use matplotlib without gui support
sys.path.append('../..')
from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, \
occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np
PI = 3.1416
curr_path = os.path.abspath(os.path.dirname(__file__))
def plot_train_metrics(train_writer, config, epoch, train_loss, train_mIoUs, train_mF1s, train_AP_edge):
"""plot loss and metrics on tensorboard"""
train_writer.add_scalar('loss_epoch', train_loss, epoch)
train_writer.add_scalar('AP_edge', train_AP_edge, epoch)
if config.network.task_type == 'occ_order':
train_order_mIoU = sum(train_mIoUs) / float(len(train_mIoUs))
train_writer.add_scalar('meanIoU_all', train_order_mIoU, epoch)
train_writer.add_scalar('meanIoU_E', train_mIoUs[0], epoch)
train_writer.add_scalar('meanIoU_S', train_mIoUs[1], epoch)
train_writer.add_scalar('meanF1_E', train_mF1s[0], epoch)
train_writer.add_scalar('meanF1_S', train_mF1s[1], epoch)
if config.dataset.connectivity == 8:
train_writer.add_scalar('meanIoU_SE', train_mIoUs[2], epoch)
train_writer.add_scalar('meanIoU_NE', train_mIoUs[3], epoch)
train_writer.add_scalar('meanF1_SE', train_mF1s[2], epoch)
train_writer.add_scalar('meanF1_NE', train_mF1s[3], epoch)
elif config.network.task_type == 'occ_ori':
train_writer.add_scalar('meanIoU_edge', train_mIoUs[0], epoch)
train_writer.add_scalar('meanF1_edge', train_mF1s[0], epoch)
def plot_val_metrics(val_writer, config, epoch, val_loss, val_mIoUs, val_mF1s, val_AP_edge):
val_writer.add_scalar('loss_epoch', val_loss, epoch)
val_writer.add_scalar('AP_edge', val_AP_edge, epoch)
if config.network.task_type == 'occ_order':
val_order_mIoU = sum(val_mIoUs) / float(len(val_mIoUs))
val_writer.add_scalar('loss_epoch', val_loss, epoch)
val_writer.add_scalar('meanIoU_all', val_order_mIoU, epoch)
val_writer.add_scalar('meanIoU_E', val_mIoUs[0], epoch)
val_writer.add_scalar('meanIoU_S', val_mIoUs[1], epoch)
val_writer.add_scalar('meanF1_E', val_mF1s[0], epoch)
val_writer.add_scalar('meanF1_S', val_mF1s[1], epoch)
if config.dataset.connectivity == 8:
val_writer.add_scalar('meanIoU_SE', val_mIoUs[2], epoch)
val_writer.add_scalar('meanIoU_NE', val_mIoUs[3], epoch)
val_writer.add_scalar('meanF1_SE', val_mF1s[2], epoch)
val_writer.add_scalar('meanF1_NE', val_mF1s[3], epoch)
elif config.network.task_type == 'occ_ori':
val_writer.add_scalar('meanIoU_edge', val_mIoUs[0], epoch)
val_writer.add_scalar('meanF1_edge', val_mF1s[0], epoch)
def viz_and_log(inputs, net_out, targets, viz_writers, idx, epoch, config):
"""
visualize train/val samples on tensorboard
:param inputs: network input, tensor, N,C,H,W
:param net_out: network input, tensor, N,C,H,W
:param targets: tuple, (N,H,W ; N,H,W)
"""
# viz model input
mean_values = torch.tensor(config.dataset.pixel_means, dtype=inputs.dtype).view(3, 1, 1)
std_values = torch.tensor(config.dataset.pixel_stds, dtype=inputs.dtype).view(3, 1, 1)
model_in_vis = inputs[0, :3, :, :].cpu() * std_values + mean_values # =>[0, 1]
H, W = model_in_vis.shape[-2:]
viz_writers[idx].add_image('Input', model_in_vis, epoch)
if config.network.task_type == 'occ_order':
edge_gt = targets[-1].unsqueeze(1).float() # N,1,H,W
# gen occ order pred
order_gt_E = targets[0][0, :, :].view(-1, H, W).cpu() # 1,H,W
order_gt_S = targets[1][0, :, :].view(-1, H, W).cpu()
_, ind_pred_h = net_out[0, :3, :, :].topk(1, dim=0, largest=True, sorted=True) # 1,H,W
_, ind_pred_v = net_out[0, 3:6, :, :].topk(1, dim=0, largest=True, sorted=True)
if config.dataset.connectivity == 8:
order_gt_SE = targets[2][0, :, :].view(-1, H, W).cpu() # 1,H,W
order_gt_NE = targets[3][0, :, :].view(-1, H, W).cpu()
_, ind_pred_SE = net_out[0, 6:9, :, :].topk(1, dim=0, largest=True, sorted=True) # 1,H,W
_, ind_pred_NE = net_out[0, 9:12, :, :].topk(1, dim=0, largest=True, sorted=True)
# gen occ edge prob from occ order
edge_prob_pred, _ = occ_order_pred_to_edge_prob(net_out, config.dataset.connectivity) # N,1,H,W
# plot
viz_writers[idx].add_image('occ_order_E.1.gt', order_gt_E.float() / 2, epoch)
viz_writers[idx].add_image('occ_order_S.1.gt', order_gt_S.float() / 2, epoch)
viz_writers[idx].add_image('occ_order_E.2.pred', ind_pred_h.float() / 2, epoch)
viz_writers[idx].add_image('occ_order_S.2.pred', ind_pred_v.float() / 2, epoch)
if config.dataset.connectivity == 8:
viz_writers[idx].add_image('occ_order_SE.1.gt', order_gt_SE.float() / 2, epoch)
viz_writers[idx].add_image('occ_order_NE.1.gt', order_gt_NE.float() / 2, epoch)
viz_writers[idx].add_image('occ_order_SE.2.pred', ind_pred_SE.float() / 2, epoch)
viz_writers[idx].add_image('occ_order_NE.2.pred', ind_pred_NE.float() / 2, epoch)
viz_writers[idx].add_image('Occ_edge.1.gt', edge_gt[0], epoch)
viz_writers[idx].add_image('Occ_edge.2.pred', edge_prob_pred[0], epoch)
elif config.network.task_type == 'occ_ori':
edge_gt = targets[-1].unsqueeze(1).float() # N,1,H,W
edge_prob_pred = net_out[:, 0, :, :].unsqueeze(1) # N,1,H,W
ori_gt = targets[0].unsqueeze(1).float() # N,1,H,W
ori_gt = (torch.clamp(ori_gt, -PI, PI) + PI) / PI / 2 # [-PI,PI] => [0,1]
ori_pred = net_out[:, 1, :, :].unsqueeze(1) # N,1,H,W
ori_pred = (torch.clamp(ori_pred, -PI, PI) + PI) / PI / 2 # [-PI,PI] => [0,1]
viz_writers[idx].add_image('Occ_edge.1.gt', edge_gt[0], epoch)
viz_writers[idx].add_image('Occ_edge.2.pred', edge_prob_pred[0], epoch)
viz_writers[idx].add_image('occ_ori.1.gt', ori_gt[0], epoch)
viz_writers[idx].add_image('occ_ori.2.pred', ori_pred[0], epoch)
def viz_and_save(net_in, net_out, img_abs_path, out_dir, config, epoch):
"""save current sample predictions in res dir w/ .mat predictions(if exist)"""
file_name = img_abs_path[0].split('/')[-1]
img_suffix = '.{}'.format(file_name.split('.')[-1])
img_name = file_name.replace(img_suffix, '')
# set res dirs and paths
valset_name = config.dataset.test_dataset
root_eval_dir = os.path.join(out_dir, 'test_{}_{}'.format(epoch, valset_name))
lbl_eval_dir = os.path.join(root_eval_dir, 'res_mat')
img_eval_dir = os.path.join(root_eval_dir, 'images')
if not os.path.exists(root_eval_dir): os.makedirs(root_eval_dir)
if not os.path.exists(lbl_eval_dir): os.makedirs(lbl_eval_dir)
if not os.path.exists(img_eval_dir): os.makedirs(img_eval_dir)
rgb_path = os.path.join(img_eval_dir, '{}_img_v.png'.format(img_name))
occ_edge_prob_path = os.path.join(img_eval_dir, '{}_lab_v_g.png'.format(img_name))
occ_ori_path = os.path.join(img_eval_dir, '{}_lab_v_g_ori.png'.format(img_name))
# get original img and save
mean_values = torch.tensor(config.dataset.pixel_means, dtype=net_in.dtype).view(3, 1, 1)
std_values = torch.tensor(config.dataset.pixel_stds, dtype=net_in.dtype).view(3, 1, 1)
img_in_vis = net_in[0, :3, :, :].cpu() * std_values + mean_values
img_in_vis = np.transpose(img_in_vis.numpy(), (1, 2, 0)).astype(np.float32) # 3,H,W => H,W,3
Image.fromarray((img_in_vis * 255.).astype(np.uint8)).save(rgb_path)
H, W = img_in_vis.shape[:2]
if config.network.task_type == 'occ_order':
# gen occ edge/ori/order pred
occ_edge_prob, occ_order_exist_prob = occ_order_pred_to_edge_prob(net_out, config.dataset.connectivity) # N,1,H,W
occ_ori = occ_order_pred_to_ori(net_out, config.dataset.connectivity) # N,1,H,W
_, occ_order_pair_E = net_out[0, :3, :, :].topk(1, dim=0, largest=True, sorted=True) # 1,H,W; [0,1,2]
_, occ_order_pair_S = net_out[0, 3:6, :, :].topk(1, dim=0, largest=True, sorted=True)
if config.dataset.connectivity == 8:
_, occ_order_pair_SE = net_out[0, 6:9, :, :].topk(1, dim=0, largest=True, sorted=True) # 1,H,W; [0,1,2]
_, occ_order_pair_NE = net_out[0, 9:12, :, :].topk(1, dim=0, largest=True, sorted=True)
# get pixel-wise occlusion order maps (occ_edge + occ_order along directions)
if config.dataset.connectivity == 4:
occ_order_pix = order4_to_order_pixwise(occ_edge_prob, occ_order_pair_E, occ_order_pair_S) # H,W,9
elif config.dataset.connectivity == 8:
occ_order_pix = order8_to_order_pixwise(occ_edge_prob, occ_order_pair_E, occ_order_pair_S,
occ_order_pair_SE, occ_order_pair_NE) # H,W,9
# gen occ edge prob and occ ori for vis
occ_edge_prob_vis = np.array(occ_edge_prob.cpu()[0, 0, :, :] * 255, dtype=np.uint8) # [0,1] => [0,255]
occ_ori_vis = (np.array(occ_ori.cpu())[0, 0, :, :] / PI + 1) / 2. * 255. # [-PI,PI] => [0,255]
# save pred occ order imgs
occ_order_pair_E = np.array(occ_order_pair_E.cpu()).reshape(H, W).astype(np.float32) # 1,H,W => H,W,1
occ_order_pair_S = np.array(occ_order_pair_S.cpu()).reshape(H, W).astype(np.float32) # 1,H,W => H,W,1
if config.dataset.connectivity == 8:
occ_order_pair_SE = np.array(occ_order_pair_SE.cpu()).reshape(H, W).astype(np.float32) # 1,H,W => H,W,1
occ_order_pair_NE = np.array(occ_order_pair_NE.cpu()).reshape(H, W).astype(np.float32) # 1,H,W => H,W,1
if not config.TEST.out_nms_res:
# save imgs of occ order
occ_order_E_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_E.png'.format(img_name))
occ_order_S_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_S.png'.format(img_name))
Image.fromarray((occ_order_pair_E / 2. * 255.).astype(np.uint8), mode='L').save(occ_order_E_path)
Image.fromarray((occ_order_pair_S / 2. * 255.).astype(np.uint8), mode='L').save(occ_order_S_path)
if config.dataset.connectivity == 8:
occ_order_SE_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_SE.png'.format(img_name))
occ_order_NE_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_NE.png'.format(img_name))
Image.fromarray((occ_order_pair_SE / 2. * 255.).astype(np.uint8), mode='L').save(occ_order_SE_path)
Image.fromarray((occ_order_pair_NE / 2. * 255.).astype(np.uint8), mode='L').save(occ_order_NE_path)
# save pixel-wise occ order npz
occ_order_pix_dir = os.path.join(lbl_eval_dir, 'test_order_pred')
if not os.path.exists(occ_order_pix_dir):
os.makedirs(occ_order_pix_dir)
occ_order_pix_path = os.path.join(occ_order_pix_dir, '{}-order-pix.npz'.format(img_name))
np.savez_compressed(occ_order_pix_path, order=occ_order_pix.astype(np.int8))
# save occ_edge and occ_ori
Image.fromarray(occ_edge_prob_vis, mode='L').save(occ_edge_prob_path)
Image.fromarray(occ_ori_vis.astype(np.uint8), mode='L').save(occ_ori_path)
else: # apply nms on occ_edge or occ_order (not used for evaluation in matlab)
occ_edge_prob_nms_path = os.path.join(img_eval_dir, '{}_lab_v_g_nms.png'.format(img_name))
occ_order_E_nms_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_E_nms.png'.format(img_name))
occ_order_S_nms_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_S_nms.png'.format(img_name))
occ_order_SE_nms_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_SE_nms.png'.format(img_name))
occ_order_NE_nms_path = os.path.join(img_eval_dir, '{}_lab_v_g_order_NE_nms.png'.format(img_name))
if config.TEST.nms_method == 'pixel-wise': # nms on occ_edge_prob and out occ_edge, occ_order, occ_ori
occ_edge_prob_nms, occ_order_pix_nms, occ_order_pair_nms, occ_ori_nms = \
nms_edge_order_ori(occ_edge_prob_vis, occ_order_pix, occ_ori_vis, config.TEST.occ_thresh)
occ_ori_nms_path = os.path.join(img_eval_dir, '{}_lab_v_g_ori_nms.png'.format(img_name))
Image.fromarray(occ_ori_nms.astype(np.uint8), mode='L').save(occ_ori_nms_path)
elif config.TEST.nms_method == 'pairwise': # nms occ_order_prob and out occ_edge, occ_order (not for eval)
occ_order_exist_prob_vis = np.array(occ_order_exist_prob.cpu()[0, :, :, :]*255, dtype=np.uint8).transpose((1, 2, 0)) # [0,1] => [0,255], HxWxC
occ_order_pair = np.stack((occ_order_pair_E, occ_order_pair_S, occ_order_pair_SE, occ_order_pair_NE), axis=2) # H,W,4
occ_order_pair_nms, occ_edge_prob_nms = nms_occ_order(occ_order_exist_prob_vis, occ_order_pair, config.TEST.occ_thresh)
occ_order_pix_nms = order8_to_order_pixwise_np(occ_edge_prob_nms, occ_order_pair_nms)
# save imgs of occ_edge and occ_order
Image.fromarray((occ_edge_prob_nms * 255).astype(np.uint8), mode='L').save(occ_edge_prob_nms_path)
Image.fromarray(((occ_order_pair_nms[:, :, 0]+1)/2.*255.).astype(np.uint8), mode='L').save(occ_order_E_nms_path)
Image.fromarray(((occ_order_pair_nms[:, :, 1]+1)/2.*255.).astype(np.uint8), mode='L').save(occ_order_S_nms_path)
Image.fromarray(((occ_order_pair_nms[:, :, 2]+1)/2.*255.).astype(np.uint8), mode='L').save(occ_order_SE_nms_path)
Image.fromarray(((occ_order_pair_nms[:, :, 3]+1)/2.*255.).astype(np.uint8), mode='L').save(occ_order_NE_nms_path)
# save pixel-wise occ_order after nms
occ_order_nms_dir = os.path.join(lbl_eval_dir, 'test_order_nms_pred')
if not os.path.exists(occ_order_nms_dir):
os.makedirs(occ_order_nms_dir)
occ_order_pix_nms_path = os.path.join(occ_order_nms_dir, '{}-order-pix.npz'.format(img_name))
np.savez_compressed(occ_order_pix_nms_path, order=occ_order_pix_nms.astype(np.int8))
elif config.network.task_type == 'occ_ori':
occ_edge_prob_vis = np.array(net_out.cpu()[0, 0, :, :] * 255., dtype=np.uint8) # [0, 1] => [0, 255]
occ_ori = torch.clamp(net_out[0, 1, :, :], -PI, PI)
occ_ori_vis = (np.array(occ_ori.cpu()) / PI + 1) / 2. * 255. # [-PI, PI] => [0, 255]
Image.fromarray(occ_edge_prob_vis, mode='L').save(occ_edge_prob_path)
Image.fromarray(occ_ori_vis.astype(np.uint8), mode='L').save(occ_ori_path)
# save .mat res for edge/ori eval if matlab GT exists
if config.dataset.val_w_mat_gt:
matlab_tool = MATLAB(root_eval_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (valset_name, 'test', epoch))
preds_list = [occ_edge_prob_vis, occ_ori_vis]
save_res_matlab(matlab_tool, {'lab_v_g': preds_list}, img_name)
def plot_conf_mat(confusion_mat, out_path, epoch, title=''):
"""plot confusion matrix and save"""
fig_conf = plt.figure()
axe = fig_conf.add_subplot(111)
cax = axe.matshow(confusion_mat, vmin=0, vmax=1)
fig_conf.colorbar(cax), plt.xlabel('Predicted class'), plt.ylabel('GT class')
axe.set_title(title)
fig_conf.savefig(os.path.join(out_path, '{}_{}.png'.format(title, epoch)))
def check_occ_order_pred(order_gt, order_pred):
"""
convert gt and pred to colormap to check 3-class pairwise occ order pred
:param order_gt: tensor H,W
:param order_pred: tensor H,W
:return: numpy 3,H,W
"""
H, W = order_gt.shape
order_gt = np.array(order_gt.cpu()).reshape(H, W)
order_pred = np.array(order_pred.cpu())
order_color = np.ones((H, W, 3)) / 2 # gray for no occ
order_color[order_gt == 0, :] = np.array([0, 0, 0]) # black for class 0
order_color[order_gt == 2, :] = np.array([1, 1, 1]) # white for class 2
order_color[(order_gt == 0) * (order_pred == 0), :] = np.array([0, 1, 0]) # green for Correct pred
order_color[(order_gt == 0) * (order_pred == 2), :] = np.array([1, 0, 0]) # red for inverse cls pred
order_color[(order_gt == 1) * (order_pred != 1), :] = np.array([1, 0, 0])
order_color[(order_gt == 2) * (order_pred == 2), :] = np.array([0, 1, 0])
order_color[(order_gt == 2) * (order_pred == 0), :] = np.array([1, 0, 0])
return order_color.astype(np.float32).transpose((2, 0, 1)) # H,W,3 => 3,H,W
def save_res_matlab(matlab_tool, labs_pred, image_path):
"""
save curr sample pred and gt as .mat for eval in matlab
:param matlab_tool:
:param labs_pred: dict of preds {label: value} ; value [0~255]
:param images_path:
:return:
"""
PI = 3.1416
short_path = ntpath.basename(image_path) # return file name
f_name = os.path.splitext(short_path)[0] # rm .ext
if 'rgb' in f_name: f_name = f_name.replace('-rgb', '')
org_gt_name = '{}{}'.format(f_name, matlab_tool.gt_type)
org_gt_path = os.path.join(matlab_tool.org_gt_dir, org_gt_name)
out_gt_path = os.path.join(matlab_tool.out_gt_dir, '{}.mat'.format(f_name))
for out_label, preds_np in labs_pred.items():
pred_name = '%s_%s.mat' % (f_name, out_label)
out_pred_path = os.path.join(matlab_tool.out_pred_dir, pred_name)
pred_edge = preds_np[0] # [0,255]
pred_ori = preds_np[1] # [0,255]
H, W = pred_edge.shape[:2]
if '.mat' in org_gt_name:
org_gt = sio.loadmat(org_gt_path)
gts = org_gt['gtStruct']['gt_theta'][0][0][0]
out_gt = np.zeros((H, W, gts.shape[0] * 2))
for anno_idx in range(0, gts.shape[0]): # annotator idx
edge_map = gts[anno_idx][:, :, 0] # [0, 1]
ori_map = gts[anno_idx][:, :, 1] # [-PI, PI]
out_gt[:, :, anno_idx * 2] = edge_map
out_gt[:, :, anno_idx * 2 + 1] = ori_map
elif '.png' in org_gt_name: # .png gt
edge_map = cv2.imread(org_gt_path, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255 # [0, 255] => [0, 1]
if len(edge_map.shape) == 3: edge_map = edge_map[:, :, 0]
ori_map = np.zeros((H, W))
out_gt = np.zeros((H, W, 2))
out_gt[:, :, 0] = edge_map
out_gt[:, :, 1] = ori_map
sio.savemat(out_gt_path, {'gt_edge_theta': out_gt})
pred_edge = pred_edge / 255.0 # [0, 255] => [0, 1]
pred_ori = pred_ori.astype(np.float32) / 255. * 2 * PI - PI # [0, 255] => [-PI, PI]
sio.savemat(out_pred_path, {'edge_ori': {'edge': pred_edge, 'ori': pred_ori}})
class MATLAB:
def __init__(self, res_dir, valset_name):
self.title = valset_name
self.res_dir = res_dir
self.out_root_dir = os.path.join(self.res_dir, 'res_mat')
self.out_gt_dir = os.path.join(self.out_root_dir, 'test_gt')
self.out_pred_dir = os.path.join(self.out_root_dir, 'test_pred')
if 'nyu' in valset_name:
self.org_gt_dir = os.path.join(curr_path, '../..', 'data/NYUv2_OR/data/')
self.gt_type = '.mat'
elif 'BSDSownership' in valset_name:
self.org_gt_dir = os.path.join(curr_path, '../..', 'data/BSDS300/BSDS_theta/testOri_mat')
self.gt_type = '.mat'
elif 'ibims' in valset_name or 'interiornet' in valset_name:
self.org_gt_dir = os.path.join(curr_path, '../..', 'data/iBims1_OR/data/')
self.gt_type = '.mat'
if not os.path.exists(self.out_root_dir): os.makedirs(self.out_root_dir)
if not os.path.exists(self.out_gt_dir): os.makedirs(self.out_gt_dir)
if not os.path.exists(self.out_pred_dir): os.makedirs(self.out_pred_dir)
|
[
"lib.dataset.gen_label_methods.occ_order_pred_to_ori",
"scipy.io.loadmat",
"numpy.ones",
"matplotlib.pyplot.figure",
"lib.dataset.gen_label_methods.occ_order_pred_to_edge_prob",
"os.path.join",
"lib.dataset.gen_label_methods.order8_to_order_pixwise_np",
"sys.path.append",
"lib.dataset.gen_label_methods.nms_occ_order",
"os.path.dirname",
"os.path.exists",
"lib.dataset.gen_label_methods.order8_to_order_pixwise",
"numpy.stack",
"lib.dataset.gen_label_methods.nms_edge_order_ori",
"torch.clamp",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.switch_backend",
"lib.dataset.gen_label_methods.order4_to_order_pixwise",
"ntpath.basename",
"os.makedirs",
"numpy.zeros",
"scipy.io.savemat",
"cv2.imread",
"numpy.array",
"os.path.splitext",
"PIL.Image.fromarray",
"matplotlib.pyplot.xlabel",
"torch.tensor"
] |
[((399, 424), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (417, 424), True, 'import matplotlib.pyplot as plt\n'), ((463, 487), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (478, 487), False, 'import sys\n'), ((741, 766), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (756, 766), False, 'import os\n'), ((7087, 7125), 'os.path.join', 'os.path.join', (['root_eval_dir', '"""res_mat"""'], {}), "(root_eval_dir, 'res_mat')\n", (7099, 7125), False, 'import os\n'), ((7145, 7182), 'os.path.join', 'os.path.join', (['root_eval_dir', '"""images"""'], {}), "(root_eval_dir, 'images')\n", (7157, 7182), False, 'import os\n'), ((15667, 15679), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (15677, 15679), True, 'import matplotlib.pyplot as plt\n'), ((16409, 16428), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (16417, 16428), True, 'import numpy as np\n'), ((16486, 16505), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (16494, 16505), True, 'import numpy as np\n'), ((16585, 16604), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (16593, 16604), True, 'import numpy as np\n'), ((16689, 16708), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (16697, 16708), True, 'import numpy as np\n'), ((16795, 16814), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (16803, 16814), True, 'import numpy as np\n'), ((16873, 16892), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (16881, 16892), True, 'import numpy as np\n'), ((16951, 16970), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (16959, 16970), True, 'import numpy as np\n'), ((17349, 17376), 'ntpath.basename', 'ntpath.basename', (['image_path'], {}), '(image_path)\n', (17364, 17376), False, 'import ntpath\n'), ((17592, 17641), 'os.path.join', 'os.path.join', (['matlab_tool.org_gt_dir', 'org_gt_name'], {}), '(matlab_tool.org_gt_dir, org_gt_name)\n', (17604, 17641), False, 'import os\n'), ((4815, 4880), 'lib.dataset.gen_label_methods.occ_order_pred_to_edge_prob', 'occ_order_pred_to_edge_prob', (['net_out', 'config.dataset.connectivity'], {}), '(net_out, config.dataset.connectivity)\n', (4842, 4880), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((7194, 7223), 'os.path.exists', 'os.path.exists', (['root_eval_dir'], {}), '(root_eval_dir)\n', (7208, 7223), False, 'import os\n'), ((7225, 7251), 'os.makedirs', 'os.makedirs', (['root_eval_dir'], {}), '(root_eval_dir)\n', (7236, 7251), False, 'import os\n'), ((7263, 7291), 'os.path.exists', 'os.path.exists', (['lbl_eval_dir'], {}), '(lbl_eval_dir)\n', (7277, 7291), False, 'import os\n'), ((7293, 7318), 'os.makedirs', 'os.makedirs', (['lbl_eval_dir'], {}), '(lbl_eval_dir)\n', (7304, 7318), False, 'import os\n'), ((7330, 7358), 'os.path.exists', 'os.path.exists', (['img_eval_dir'], {}), '(img_eval_dir)\n', (7344, 7358), False, 'import os\n'), ((7360, 7385), 'os.makedirs', 'os.makedirs', (['img_eval_dir'], {}), '(img_eval_dir)\n', (7371, 7385), False, 'import os\n'), ((8257, 8322), 'lib.dataset.gen_label_methods.occ_order_pred_to_edge_prob', 'occ_order_pred_to_edge_prob', (['net_out', 'config.dataset.connectivity'], {}), '(net_out, config.dataset.connectivity)\n', (8284, 8322), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((8352, 8411), 'lib.dataset.gen_label_methods.occ_order_pred_to_ori', 'occ_order_pred_to_ori', (['net_out', 'config.dataset.connectivity'], {}), '(net_out, config.dataset.connectivity)\n', (8373, 8411), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((15797, 15826), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted class"""'], {}), "('Predicted class')\n", (15807, 15826), True, 'import matplotlib.pyplot as plt\n'), ((15828, 15850), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""GT class"""'], {}), "('GT class')\n", (15838, 15850), True, 'import matplotlib.pyplot as plt\n'), ((16331, 16349), 'numpy.ones', 'np.ones', (['(H, W, 3)'], {}), '((H, W, 3))\n', (16338, 16349), True, 'import numpy as np\n'), ((17410, 17438), 'os.path.splitext', 'os.path.splitext', (['short_path'], {}), '(short_path)\n', (17426, 17438), False, 'import os\n'), ((17851, 17900), 'os.path.join', 'os.path.join', (['matlab_tool.out_pred_dir', 'pred_name'], {}), '(matlab_tool.out_pred_dir, pred_name)\n', (17863, 17900), False, 'import os\n'), ((18925, 18976), 'scipy.io.savemat', 'sio.savemat', (['out_gt_path', "{'gt_edge_theta': out_gt}"], {}), "(out_gt_path, {'gt_edge_theta': out_gt})\n", (18936, 18976), True, 'import scipy.io as sio\n'), ((19140, 19218), 'scipy.io.savemat', 'sio.savemat', (['out_pred_path', "{'edge_ori': {'edge': pred_edge, 'ori': pred_ori}}"], {}), "(out_pred_path, {'edge_ori': {'edge': pred_edge, 'ori': pred_ori}})\n", (19151, 19218), True, 'import scipy.io as sio\n'), ((19373, 19410), 'os.path.join', 'os.path.join', (['self.res_dir', '"""res_mat"""'], {}), "(self.res_dir, 'res_mat')\n", (19385, 19410), False, 'import os\n'), ((19437, 19479), 'os.path.join', 'os.path.join', (['self.out_root_dir', '"""test_gt"""'], {}), "(self.out_root_dir, 'test_gt')\n", (19449, 19479), False, 'import os\n'), ((19508, 19552), 'os.path.join', 'os.path.join', (['self.out_root_dir', '"""test_pred"""'], {}), "(self.out_root_dir, 'test_pred')\n", (19520, 19552), False, 'import os\n'), ((3555, 3615), 'torch.tensor', 'torch.tensor', (['config.dataset.pixel_means'], {'dtype': 'inputs.dtype'}), '(config.dataset.pixel_means, dtype=inputs.dtype)\n', (3567, 3615), False, 'import torch\n'), ((3647, 3706), 'torch.tensor', 'torch.tensor', (['config.dataset.pixel_stds'], {'dtype': 'inputs.dtype'}), '(config.dataset.pixel_stds, dtype=inputs.dtype)\n', (3659, 3706), False, 'import torch\n'), ((7684, 7744), 'torch.tensor', 'torch.tensor', (['config.dataset.pixel_means'], {'dtype': 'net_in.dtype'}), '(config.dataset.pixel_means, dtype=net_in.dtype)\n', (7696, 7744), False, 'import torch\n'), ((7777, 7836), 'torch.tensor', 'torch.tensor', (['config.dataset.pixel_stds'], {'dtype': 'net_in.dtype'}), '(config.dataset.pixel_stds, dtype=net_in.dtype)\n', (7789, 7836), False, 'import torch\n'), ((9050, 9124), 'lib.dataset.gen_label_methods.order4_to_order_pixwise', 'order4_to_order_pixwise', (['occ_edge_prob', 'occ_order_pair_E', 'occ_order_pair_S'], {}), '(occ_edge_prob, occ_order_pair_E, occ_order_pair_S)\n', (9073, 9124), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((11257, 11302), 'os.path.join', 'os.path.join', (['lbl_eval_dir', '"""test_order_pred"""'], {}), "(lbl_eval_dir, 'test_order_pred')\n", (11269, 11302), False, 'import os\n'), ((14365, 14414), 'os.path.join', 'os.path.join', (['lbl_eval_dir', '"""test_order_nms_pred"""'], {}), "(lbl_eval_dir, 'test_order_nms_pred')\n", (14377, 14414), False, 'import os\n'), ((14905, 14946), 'torch.clamp', 'torch.clamp', (['net_out[0, 1, :, :]', '(-PI)', 'PI'], {}), '(net_out[0, 1, :, :], -PI, PI)\n', (14916, 14946), False, 'import torch\n'), ((18079, 18103), 'scipy.io.loadmat', 'sio.loadmat', (['org_gt_path'], {}), '(org_gt_path)\n', (18090, 18103), True, 'import scipy.io as sio\n'), ((18183, 18217), 'numpy.zeros', 'np.zeros', (['(H, W, gts.shape[0] * 2)'], {}), '((H, W, gts.shape[0] * 2))\n', (18191, 18217), True, 'import numpy as np\n'), ((19617, 19672), 'os.path.join', 'os.path.join', (['curr_path', '"""../.."""', '"""data/NYUv2_OR/data/"""'], {}), "(curr_path, '../..', 'data/NYUv2_OR/data/')\n", (19629, 19672), False, 'import os\n'), ((20094, 20127), 'os.path.exists', 'os.path.exists', (['self.out_root_dir'], {}), '(self.out_root_dir)\n', (20108, 20127), False, 'import os\n'), ((20129, 20159), 'os.makedirs', 'os.makedirs', (['self.out_root_dir'], {}), '(self.out_root_dir)\n', (20140, 20159), False, 'import os\n'), ((20175, 20206), 'os.path.exists', 'os.path.exists', (['self.out_gt_dir'], {}), '(self.out_gt_dir)\n', (20189, 20206), False, 'import os\n'), ((20208, 20236), 'os.makedirs', 'os.makedirs', (['self.out_gt_dir'], {}), '(self.out_gt_dir)\n', (20219, 20236), False, 'import os\n'), ((20252, 20285), 'os.path.exists', 'os.path.exists', (['self.out_pred_dir'], {}), '(self.out_pred_dir)\n', (20266, 20285), False, 'import os\n'), ((20287, 20317), 'os.makedirs', 'os.makedirs', (['self.out_pred_dir'], {}), '(self.out_pred_dir)\n', (20298, 20317), False, 'import os\n'), ((9209, 9325), 'lib.dataset.gen_label_methods.order8_to_order_pixwise', 'order8_to_order_pixwise', (['occ_edge_prob', 'occ_order_pair_E', 'occ_order_pair_S', 'occ_order_pair_SE', 'occ_order_pair_NE'], {}), '(occ_edge_prob, occ_order_pair_E, occ_order_pair_S,\n occ_order_pair_SE, occ_order_pair_NE)\n', (9232, 9325), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((11322, 11355), 'os.path.exists', 'os.path.exists', (['occ_order_pix_dir'], {}), '(occ_order_pix_dir)\n', (11336, 11355), False, 'import os\n'), ((11373, 11403), 'os.makedirs', 'os.makedirs', (['occ_order_pix_dir'], {}), '(occ_order_pix_dir)\n', (11384, 11403), False, 'import os\n'), ((12675, 12769), 'lib.dataset.gen_label_methods.nms_edge_order_ori', 'nms_edge_order_ori', (['occ_edge_prob_vis', 'occ_order_pix', 'occ_ori_vis', 'config.TEST.occ_thresh'], {}), '(occ_edge_prob_vis, occ_order_pix, occ_ori_vis, config.\n TEST.occ_thresh)\n', (12693, 12769), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((14434, 14467), 'os.path.exists', 'os.path.exists', (['occ_order_nms_dir'], {}), '(occ_order_nms_dir)\n', (14448, 14467), False, 'import os\n'), ((14485, 14515), 'os.makedirs', 'os.makedirs', (['occ_order_nms_dir'], {}), '(occ_order_nms_dir)\n', (14496, 14515), False, 'import os\n'), ((18781, 18797), 'numpy.zeros', 'np.zeros', (['(H, W)'], {}), '((H, W))\n', (18789, 18797), True, 'import numpy as np\n'), ((18819, 18838), 'numpy.zeros', 'np.zeros', (['(H, W, 2)'], {}), '((H, W, 2))\n', (18827, 18838), True, 'import numpy as np\n'), ((19782, 19853), 'os.path.join', 'os.path.join', (['curr_path', '"""../.."""', '"""data/BSDS300/BSDS_theta/testOri_mat"""'], {}), "(curr_path, '../..', 'data/BSDS300/BSDS_theta/testOri_mat')\n", (19794, 19853), False, 'import os\n'), ((11648, 11692), 'PIL.Image.fromarray', 'Image.fromarray', (['occ_edge_prob_vis'], {'mode': '"""L"""'}), "(occ_edge_prob_vis, mode='L')\n", (11663, 11692), False, 'from PIL import Image\n'), ((13278, 13374), 'numpy.stack', 'np.stack', (['(occ_order_pair_E, occ_order_pair_S, occ_order_pair_SE, occ_order_pair_NE)'], {'axis': '(2)'}), '((occ_order_pair_E, occ_order_pair_S, occ_order_pair_SE,\n occ_order_pair_NE), axis=2)\n', (13286, 13374), True, 'import numpy as np\n'), ((13436, 13515), 'lib.dataset.gen_label_methods.nms_occ_order', 'nms_occ_order', (['occ_order_exist_prob_vis', 'occ_order_pair', 'config.TEST.occ_thresh'], {}), '(occ_order_exist_prob_vis, occ_order_pair, config.TEST.occ_thresh)\n', (13449, 13515), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((13552, 13617), 'lib.dataset.gen_label_methods.order8_to_order_pixwise_np', 'order8_to_order_pixwise_np', (['occ_edge_prob_nms', 'occ_order_pair_nms'], {}), '(occ_edge_prob_nms, occ_order_pair_nms)\n', (13578, 13617), False, 'from lib.dataset.gen_label_methods import order4_to_order_pixwise, order8_to_order_pixwise, occ_order_pred_to_edge_prob, occ_order_pred_to_ori, nms_edge_order_ori, nms_occ_order, order8_to_order_pixwise_np\n'), ((15055, 15099), 'PIL.Image.fromarray', 'Image.fromarray', (['occ_edge_prob_vis'], {'mode': '"""L"""'}), "(occ_edge_prob_vis, mode='L')\n", (15070, 15099), False, 'from PIL import Image\n'), ((19987, 20043), 'os.path.join', 'os.path.join', (['curr_path', '"""../.."""', '"""data/iBims1_OR/data/"""'], {}), "(curr_path, '../..', 'data/iBims1_OR/data/')\n", (19999, 20043), False, 'import os\n'), ((6090, 6118), 'torch.clamp', 'torch.clamp', (['ori_gt', '(-PI)', 'PI'], {}), '(ori_gt, -PI, PI)\n', (6101, 6118), False, 'import torch\n'), ((6238, 6268), 'torch.clamp', 'torch.clamp', (['ori_pred', '(-PI)', 'PI'], {}), '(ori_pred, -PI, PI)\n', (6249, 6268), False, 'import torch\n'), ((18596, 18641), 'cv2.imread', 'cv2.imread', (['org_gt_path', 'cv2.IMREAD_UNCHANGED'], {}), '(org_gt_path, cv2.IMREAD_UNCHANGED)\n', (18606, 18641), False, 'import cv2\n')]
|
import numpy
from chainer import cuda
from chainer import optimizer
class RMSpropGraves(optimizer.Optimizer):
"""<NAME> RMSprop.
See http://arxiv.org/abs/1308.0850
"""
def __init__(self, lr=1e-4, alpha=0.95, momentum=0.9, eps=1e-4):
# Default parameter values are the ones in the original paper.
self.lr = lr
self.alpha = alpha
self.eps = eps
self.momentum = momentum
def init_state_cpu(self, param, grad):
n = numpy.zeros_like(param)
g = numpy.zeros_like(param)
delta = numpy.zeros_like(param)
return n, g, delta
def init_state_gpu(self, param, grad):
n = cuda.zeros_like(param)
g = cuda.zeros_like(param)
delta = cuda.zeros_like(param)
return n, g, delta
def update_one_cpu(self, param, grad, state):
n, g, delta = state
n *= self.alpha
n += (1 - self.alpha) * grad * grad
g *= self.alpha
g += (1 - self.alpha) * grad
delta *= self.momentum
delta -= self.lr * grad / numpy.sqrt(n - g * g + self.eps)
param += delta
def update_one_gpu(self, param, grad, state):
n, g, delta = state
cuda.elementwise(
'T grad, T lr, T alpha, T momentum, T eps',
'T param, T avg_n, T avg_g, T delta',
'''avg_n = alpha * avg_n + (1 - alpha) * grad * grad;
avg_g = alpha * avg_g + (1 - alpha) * grad;
delta = delta * momentum -
lr * grad * rsqrt(avg_n - avg_g * avg_g + eps);
param += delta;''',
'rmsprop_graves')(grad,
self.lr, self.alpha, self.momentum, self.eps,
param, n, g, delta)
|
[
"chainer.cuda.elementwise",
"numpy.zeros_like",
"chainer.cuda.zeros_like",
"numpy.sqrt"
] |
[((486, 509), 'numpy.zeros_like', 'numpy.zeros_like', (['param'], {}), '(param)\n', (502, 509), False, 'import numpy\n'), ((522, 545), 'numpy.zeros_like', 'numpy.zeros_like', (['param'], {}), '(param)\n', (538, 545), False, 'import numpy\n'), ((562, 585), 'numpy.zeros_like', 'numpy.zeros_like', (['param'], {}), '(param)\n', (578, 585), False, 'import numpy\n'), ((669, 691), 'chainer.cuda.zeros_like', 'cuda.zeros_like', (['param'], {}), '(param)\n', (684, 691), False, 'from chainer import cuda\n'), ((704, 726), 'chainer.cuda.zeros_like', 'cuda.zeros_like', (['param'], {}), '(param)\n', (719, 726), False, 'from chainer import cuda\n'), ((743, 765), 'chainer.cuda.zeros_like', 'cuda.zeros_like', (['param'], {}), '(param)\n', (758, 765), False, 'from chainer import cuda\n'), ((1066, 1098), 'numpy.sqrt', 'numpy.sqrt', (['(n - g * g + self.eps)'], {}), '(n - g * g + self.eps)\n', (1076, 1098), False, 'import numpy\n'), ((1209, 1595), 'chainer.cuda.elementwise', 'cuda.elementwise', (['"""T grad, T lr, T alpha, T momentum, T eps"""', '"""T param, T avg_n, T avg_g, T delta"""', '"""avg_n = alpha * avg_n + (1 - alpha) * grad * grad;\n avg_g = alpha * avg_g + (1 - alpha) * grad;\n delta = delta * momentum -\n lr * grad * rsqrt(avg_n - avg_g * avg_g + eps);\n param += delta;"""', '"""rmsprop_graves"""'], {}), '(\'T grad, T lr, T alpha, T momentum, T eps\',\n \'T param, T avg_n, T avg_g, T delta\',\n """avg_n = alpha * avg_n + (1 - alpha) * grad * grad;\n avg_g = alpha * avg_g + (1 - alpha) * grad;\n delta = delta * momentum -\n lr * grad * rsqrt(avg_n - avg_g * avg_g + eps);\n param += delta;"""\n , \'rmsprop_graves\')\n', (1225, 1595), False, 'from chainer import cuda\n')]
|
import csv
import tqdm
import logging
import numpy as np
from os import path
from collections import deque
import chainer
import chainerrl
from chainer import serializers
from chainer.backends import cuda
from src.abstract.agent import Agent
from src.finger.model import QFunction
from src.utilities.behaviour import AgentBehaviour
from src.visualise.visualise import visualise_agent
from src.finger.finger_agent_environment import FingerAgentEnv
class FingerAgent(Agent):
def __init__(self, layout_config, agent_params, finger, train, verbose=True):
self.logger = logging.getLogger(__name__)
self.env = FingerAgentEnv(layout_config, agent_params, finger, train)
# Agent Configuration.
optimizer_name = 'Adam' if agent_params is None else agent_params['optimizer_name']
lr = 0.001 if agent_params is None else agent_params['learning_rate']
dropout_ratio = 0.2 if agent_params is None else int(agent_params['dropout_ratio'])
n_units = 512 if agent_params is None else int(agent_params['n_units'])
device_id = 0 if agent_params is None else int(agent_params['device_id'])
pre_load = False if agent_params is None else bool(agent_params['pre_load'])
self.gpu = True if agent_params is None else bool(agent_params['gpu'])
self.save_path = path.join('data', 'models', 'finger') if agent_params is None \
else agent_params['save_path']
gamma = 0.99 if agent_params is None else float(agent_params['discount'])
replay_size = 10 ** 6 if agent_params is None else int(agent_params['replay_buffer'])
self.episodes = 1000000 if agent_params is None else int(agent_params['episodes'])
self.log_interval = 1000 if agent_params is None else int(agent_params['log_interval'])
self.log_filename = agent_params['log_file']
self.verbose = verbose
self.q_func = QFunction(embed_size=self.env.observation_space.shape[0],
dropout_ratio=dropout_ratio,
n_actions=self.env.action_space.n, n_hidden_channels=n_units)
if pre_load:
serializers.load_npz(path.join(self.save_path, 'best', 'model.npz'), self.q_func)
if self.gpu:
self.q_func.to_gpu(device_id)
if optimizer_name == 'Adam':
self.optimizer = chainer.optimizers.Adam(alpha=lr)
elif optimizer_name == 'RMSprop':
self.optimizer = chainer.optimizers.RMSprop(lr=lr)
else:
self.optimizer = chainer.optimizers.MomentumSGD(lr=lr)
self.optimizer.setup(self.q_func)
# Use epsilon-greedy for exploration/exploitation with linear decay.
explorer = chainerrl.explorers.LinearDecayEpsilonGreedy(start_epsilon=0.1, end_epsilon=0.01,
decay_steps=int(self.episodes / 4),
random_action_func=self.env.action_space.sample)
# DQN uses Experience Replay.
replay_buffer = chainerrl.replay_buffers.prioritized.PrioritizedReplayBuffer(capacity=replay_size)
phi = lambda x: x.astype(np.float32, copy=False)
# Now create an agent that will interact with the environment.
self.agent = chainerrl.agents.DoubleDQN(q_function=self.q_func, optimizer=self.optimizer,
replay_buffer=replay_buffer, gamma=gamma, explorer=explorer,
replay_start_size=50000, update_interval=1000,
target_update_interval=1000,
target_update_method='soft', phi=phi)
self.error_list = deque([0], maxlen=1000)
self.reward_list = deque([0], maxlen=1000)
if train:
chainer.config.train = True
if self.verbose:
self.pbar = tqdm.tqdm(total=self.episodes, ascii=True,
bar_format='{l_bar}{n}, {remaining}\n')
else:
self.pbar = tqdm.tqdm(total=self.episodes)
else:
chainer.config.train = False
self.behaviour_log = AgentBehaviour("finger")
def train(self, episodes):
"""
Function to start agent training. Finger agent uses Double DQN with Prioritised Experience Reply.
:param episodes: number of training trials to run.
"""
progress_bar = ProgressBar(self.pbar, episodes)
chainerrl.experiments.train_agent_with_evaluation(
agent=self.agent,
env=self.env,
steps=episodes, # Train the agent for n steps
eval_n_steps=None, # We evaluate for episodes, not time
eval_n_episodes=10, # 10 episodes are sampled for each evaluation
eval_interval=self.log_interval, # Evaluate the agent after every 1000 steps
outdir=self.save_path, # Save everything to 'data/models' directory
train_max_episode_len=5, # Maximum length of each episode
successful_score=4.5, # Stopping rule
logger=self.logger,
step_hooks=[progress_bar]
)
def save_log_data(self, data, mode='w'):
"""
Function to save intermediate training logs.
:param data: list of training data to save for evaluation later.
:param mode: open file in write or append mode.
"""
with open(path.join("data", "training", self.log_filename), mode) as f:
writer = csv.writer(f)
writer.writerow(data)
def evaluate(self, sentence, **kwargs):
sat_desired = kwargs['sat_desired']
# run the sentence.
eval_log = self.type_sentence(sentence, sat_desired, True)
with open(path.join("data", "output", self.log_filename), "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(eval_log)
self.behaviour_log.save()
self.logger.info("Generating Video.")
# TODO: This is from legacy code. Need to update.
visualise_agent(True, False, path.join("data", "output", self.log_filename), None,
path.join("data", "output", "FingerAgent.mp4"))
def type_char(self, char, sat_d, is_eye_present=False):
"""
finger movement to a single character.
:param char: character to type.
:param sat_d: desired SAT to type with.
:param is_eye_present: true if eyes are on target else false
"""
# set target char key to press.
self.env.target = char
self.env.hit = 0
# set the desired sat to use.
self.env.sat_desired = self.env.sat_desired_list.index(sat_d)
# set vision status.
self.env.vision_status = is_eye_present
# calculate finger location estimate.
self.env.calc_max_finger_loc()
# set belief with current evidence.
self.env.set_belief()
# choose the best action with max Q-values
action, q_val = self.choose_best_action()
# act on the action.
_, reward, done, info = self.env.step(action)
return info['mt'], reward, done, q_val
def type_sentence(self, sentence, sat_desired, is_eye_present=False):
"""
Types the sentence using only the finger.
:param is_eye_present: true if eyes are on target else false
:param sat_desired: hwo accurately to type. value between 0 (low accuracy) to 1 (high accuracy).
:param sentence: string to be typed with finger.
:return: test_data : list with eye and action data for the typed sentence.
"""
self.env.reset()
test_data = []
self.logger.debug("Typing: %s" % sentence)
# Initial data to append to the test data which will be saved and used in visualization
test_data.append(["model time", "fingerloc x", "fingerloc y", "action x", "action y", "type"])
test_data.append([round(self.env.model_time, 4), self.env.finger_location[0], self.env.finger_location[1],
"", "", "start"])
self.behaviour_log.clear_data()
for char in sentence:
self.env.action_type = 0 # setting ballistic action
# Keep taking actions with same target until peck or max step reached.
for i in range(10):
mt, reward, done, q_val = self.type_char(char, sat_desired, is_eye_present)
self.behaviour_log.add_datapoint(time=self.env.model_time, char=char, sentence=sentence,
sat_true=self.env.sat_true_list[self.env.sat_true],
sat_desired=sat_desired, qval=q_val, actiontype=self.env.action_type,
reward=reward, entropy=self.env.finger_loc_entropy,
accuracy=self.env.hit)
if self.env.action_type == 0:
test_data.append([round(self.env.model_time, 4), self.env.finger_location[0],
self.env.finger_location[1], "", "", 'move'])
else:
test_data.append([round(self.env.model_time, 4), self.env.finger_location[0],
self.env.finger_location[1], self.env.finger_location[0],
self.env.finger_location[1], 'peck'])
if done:
break
return test_data
def choose_best_action(self):
"""
Function to choose best action given action-value map.
"""
state = self.env.preprocess_belief()
if self.gpu:
q_values = cuda.to_cpu(chainer.as_array(
self.q_func(cuda.to_gpu(state.reshape((1, self.env.observation_space.shape[0])), device=0))
.q_values).reshape((-1,)))
else:
q_values = chainer.as_array(self.q_func(state.reshape((1, self.env.observation_space.shape[0])))
.q_values).reshape((-1,))
best_action = np.where(q_values == np.amax(q_values))[0]
return np.random.choice(best_action), np.amax(q_values)
def calculate_Qvalue(self):
"""
Function that calculates MaxQ for actions.
Choose the best action type by comparing the maximum q values for both action types "move" and "peck"
:return: action-value map.
"""
action_value = {}
for action in self.env.actions:
action_value[action] = {}
action_value[action]["SAT"] = {}
action_value[action]["best_q"] = -np.inf
for sat in self.env.sat_true_list:
self.env.action_type = self.env.actions.index(action)
self.env.sat_true = self.env.sat_true_list.index(sat)
# set belief with current evidence.
self.env.set_belief()
state = self.env.preprocess_belief()
if self.gpu:
q_values = cuda.to_cpu(chainer.as_array(
self.q_func(cuda.to_gpu(state.reshape((1, self.env.observation_space.shape[0])), device=0))
.q_values).reshape((-1,)))
else:
q_values = chainer.as_array(self.q_func(state.reshape((1, self.env.observation_space.shape[0])))
.q_values).reshape((-1,))
action_value[action]["SAT"][self.env.sat_true] = {"q_values": q_values, "max_q": np.max(q_values)}
if np.max(q_values) > action_value[action]["best_q"]:
action_value[action]["best_q"] = np.max(q_values)
return action_value
def load(self):
"""
Function to load pre-trained data.
"""
serializers.load_npz(path.join(self.save_path, 'best', 'model.npz'), self.q_func)
chainer.config.train = False
class ProgressBar(chainerrl.experiments.hooks.StepHook):
"""
Hook class to update progress bar.
"""
def __init__(self, pbar, max_length):
self.pbar = pbar
self.max = max_length
def __call__(self, env, agent, step):
self.pbar.update()
if self.max <= step:
self.pbar.close()
|
[
"src.utilities.behaviour.AgentBehaviour",
"chainerrl.replay_buffers.prioritized.PrioritizedReplayBuffer",
"numpy.random.choice",
"chainer.optimizers.Adam",
"tqdm.tqdm",
"csv.writer",
"chainer.optimizers.MomentumSGD",
"collections.deque",
"numpy.amax",
"numpy.max",
"chainerrl.agents.DoubleDQN",
"src.finger.model.QFunction",
"chainer.optimizers.RMSprop",
"src.finger.finger_agent_environment.FingerAgentEnv",
"os.path.join",
"chainerrl.experiments.train_agent_with_evaluation",
"logging.getLogger"
] |
[((582, 609), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (599, 609), False, 'import logging\n'), ((630, 688), 'src.finger.finger_agent_environment.FingerAgentEnv', 'FingerAgentEnv', (['layout_config', 'agent_params', 'finger', 'train'], {}), '(layout_config, agent_params, finger, train)\n', (644, 688), False, 'from src.finger.finger_agent_environment import FingerAgentEnv\n'), ((1911, 2069), 'src.finger.model.QFunction', 'QFunction', ([], {'embed_size': 'self.env.observation_space.shape[0]', 'dropout_ratio': 'dropout_ratio', 'n_actions': 'self.env.action_space.n', 'n_hidden_channels': 'n_units'}), '(embed_size=self.env.observation_space.shape[0], dropout_ratio=\n dropout_ratio, n_actions=self.env.action_space.n, n_hidden_channels=n_units\n )\n', (1920, 2069), False, 'from src.finger.model import QFunction\n'), ((3089, 3176), 'chainerrl.replay_buffers.prioritized.PrioritizedReplayBuffer', 'chainerrl.replay_buffers.prioritized.PrioritizedReplayBuffer', ([], {'capacity': 'replay_size'}), '(capacity=\n replay_size)\n', (3149, 3176), False, 'import chainerrl\n'), ((3323, 3587), 'chainerrl.agents.DoubleDQN', 'chainerrl.agents.DoubleDQN', ([], {'q_function': 'self.q_func', 'optimizer': 'self.optimizer', 'replay_buffer': 'replay_buffer', 'gamma': 'gamma', 'explorer': 'explorer', 'replay_start_size': '(50000)', 'update_interval': '(1000)', 'target_update_interval': '(1000)', 'target_update_method': '"""soft"""', 'phi': 'phi'}), "(q_function=self.q_func, optimizer=self.optimizer,\n replay_buffer=replay_buffer, gamma=gamma, explorer=explorer,\n replay_start_size=50000, update_interval=1000, target_update_interval=\n 1000, target_update_method='soft', phi=phi)\n", (3349, 3587), False, 'import chainerrl\n'), ((3794, 3817), 'collections.deque', 'deque', (['[0]'], {'maxlen': '(1000)'}), '([0], maxlen=1000)\n', (3799, 3817), False, 'from collections import deque\n'), ((3845, 3868), 'collections.deque', 'deque', (['[0]'], {'maxlen': '(1000)'}), '([0], maxlen=1000)\n', (3850, 3868), False, 'from collections import deque\n'), ((4577, 4880), 'chainerrl.experiments.train_agent_with_evaluation', 'chainerrl.experiments.train_agent_with_evaluation', ([], {'agent': 'self.agent', 'env': 'self.env', 'steps': 'episodes', 'eval_n_steps': 'None', 'eval_n_episodes': '(10)', 'eval_interval': 'self.log_interval', 'outdir': 'self.save_path', 'train_max_episode_len': '(5)', 'successful_score': '(4.5)', 'logger': 'self.logger', 'step_hooks': '[progress_bar]'}), '(agent=self.agent, env=\n self.env, steps=episodes, eval_n_steps=None, eval_n_episodes=10,\n eval_interval=self.log_interval, outdir=self.save_path,\n train_max_episode_len=5, successful_score=4.5, logger=self.logger,\n step_hooks=[progress_bar])\n', (4626, 4880), False, 'import chainerrl\n'), ((1334, 1371), 'os.path.join', 'path.join', (['"""data"""', '"""models"""', '"""finger"""'], {}), "('data', 'models', 'finger')\n", (1343, 1371), False, 'from os import path\n'), ((2371, 2404), 'chainer.optimizers.Adam', 'chainer.optimizers.Adam', ([], {'alpha': 'lr'}), '(alpha=lr)\n', (2394, 2404), False, 'import chainer\n'), ((4266, 4290), 'src.utilities.behaviour.AgentBehaviour', 'AgentBehaviour', (['"""finger"""'], {}), "('finger')\n", (4280, 4290), False, 'from src.utilities.behaviour import AgentBehaviour\n'), ((5617, 5630), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (5627, 5630), False, 'import csv\n'), ((5960, 5973), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (5970, 5973), False, 'import csv\n'), ((6191, 6237), 'os.path.join', 'path.join', (['"""data"""', '"""output"""', 'self.log_filename'], {}), "('data', 'output', self.log_filename)\n", (6200, 6237), False, 'from os import path\n'), ((6269, 6315), 'os.path.join', 'path.join', (['"""data"""', '"""output"""', '"""FingerAgent.mp4"""'], {}), "('data', 'output', 'FingerAgent.mp4')\n", (6278, 6315), False, 'from os import path\n'), ((10318, 10347), 'numpy.random.choice', 'np.random.choice', (['best_action'], {}), '(best_action)\n', (10334, 10347), True, 'import numpy as np\n'), ((10349, 10366), 'numpy.amax', 'np.amax', (['q_values'], {}), '(q_values)\n', (10356, 10366), True, 'import numpy as np\n'), ((12035, 12081), 'os.path.join', 'path.join', (['self.save_path', '"""best"""', '"""model.npz"""'], {}), "(self.save_path, 'best', 'model.npz')\n", (12044, 12081), False, 'from os import path\n'), ((2179, 2225), 'os.path.join', 'path.join', (['self.save_path', '"""best"""', '"""model.npz"""'], {}), "(self.save_path, 'best', 'model.npz')\n", (2188, 2225), False, 'from os import path\n'), ((2476, 2509), 'chainer.optimizers.RMSprop', 'chainer.optimizers.RMSprop', ([], {'lr': 'lr'}), '(lr=lr)\n', (2502, 2509), False, 'import chainer\n'), ((2553, 2590), 'chainer.optimizers.MomentumSGD', 'chainer.optimizers.MomentumSGD', ([], {'lr': 'lr'}), '(lr=lr)\n', (2583, 2590), False, 'import chainer\n'), ((3985, 4072), 'tqdm.tqdm', 'tqdm.tqdm', ([], {'total': 'self.episodes', 'ascii': '(True)', 'bar_format': '"""{l_bar}{n}, {remaining}\n"""'}), "(total=self.episodes, ascii=True, bar_format=\n '{l_bar}{n}, {remaining}\\n')\n", (3994, 4072), False, 'import tqdm\n'), ((4147, 4177), 'tqdm.tqdm', 'tqdm.tqdm', ([], {'total': 'self.episodes'}), '(total=self.episodes)\n', (4156, 4177), False, 'import tqdm\n'), ((5534, 5582), 'os.path.join', 'path.join', (['"""data"""', '"""training"""', 'self.log_filename'], {}), "('data', 'training', self.log_filename)\n", (5543, 5582), False, 'from os import path\n'), ((5868, 5914), 'os.path.join', 'path.join', (['"""data"""', '"""output"""', 'self.log_filename'], {}), "('data', 'output', self.log_filename)\n", (5877, 5914), False, 'from os import path\n'), ((10280, 10297), 'numpy.amax', 'np.amax', (['q_values'], {}), '(q_values)\n', (10287, 10297), True, 'import numpy as np\n'), ((11730, 11746), 'numpy.max', 'np.max', (['q_values'], {}), '(q_values)\n', (11736, 11746), True, 'import numpy as np\n'), ((11768, 11784), 'numpy.max', 'np.max', (['q_values'], {}), '(q_values)\n', (11774, 11784), True, 'import numpy as np\n'), ((11872, 11888), 'numpy.max', 'np.max', (['q_values'], {}), '(q_values)\n', (11878, 11888), True, 'import numpy as np\n')]
|
import os
import sys
import cv2
import numpy as np
from tqdm import tqdm
def eval_phys_data_single_pendulum(data_filepath, num_vids, num_frms, save_path):
from eval_phys_single_pendulum import eval_physics, phys_vars_list
phys = {p_var:[] for p_var in phys_vars_list}
for n in tqdm(range(num_vids)):
seq_filepath = os.path.join(data_filepath, str(n))
frames = []
for p in range(num_frms):
frame_p = cv2.imread(os.path.join(seq_filepath, str(p)+'.png'))
frames.append(frame_p)
phys_tmp = eval_physics(frames)
for p_var in phys_vars_list:
phys[p_var].append(phys_tmp[p_var])
for p_var in phys_vars_list:
phys[p_var] = np.array(phys[p_var])
np.save(save_path, phys)
def eval_phys_data_double_pendulum(data_filepath, num_vids, num_frms, save_path):
from eval_phys_double_pendulum import eval_physics, phys_vars_list
phys = {p_var:[] for p_var in phys_vars_list}
for n in tqdm(range(num_vids)):
seq_filepath = os.path.join(data_filepath, str(n))
frames = []
for p in range(num_frms):
frame_p = cv2.imread(os.path.join(seq_filepath, str(p)+'.png'))
frames.append(frame_p)
phys_tmp = eval_physics(frames)
for p_var in phys_vars_list:
phys[p_var].append(phys_tmp[p_var])
for p_var in phys_vars_list:
phys[p_var] = np.array(phys[p_var])
# remove outliers
thresh_1 = np.nanpercentile(np.abs(phys['vel_theta_1']), 98)
thresh_2 = np.nanpercentile(np.abs(phys['vel_theta_2']), 98)
for n in range(num_vids):
for p in range(num_frms):
if (not np.isnan(phys['vel_theta_1'][n, p]) and np.abs(phys['vel_theta_1'][n, p]) >= thresh_1) \
or (not np.isnan(phys['vel_theta_2'][n, p]) and np.abs(phys['vel_theta_2'][n, p]) >= thresh_2):
phys['vel_theta_1'][n, p] = np.nan
phys['vel_theta_2'][n, p] = np.nan
phys['kinetic energy'][n, p] = np.nan
phys['total energy'][n, p] = np.nan
np.save(save_path, phys)
def eval_phys_data_elastic_pendulum(data_filepath, num_vids, num_frms, save_path):
from eval_phys_elastic_pendulum import eval_physics, phys_vars_list
phys = {p_var:[] for p_var in phys_vars_list}
for n in tqdm(range(num_vids)):
seq_filepath = os.path.join(data_filepath, str(n))
frames = []
for p in range(num_frms):
frame_p = cv2.imread(os.path.join(seq_filepath, str(p)+'.png'))
frames.append(frame_p)
phys_tmp = eval_physics(frames)
for p_var in phys_vars_list:
phys[p_var].append(phys_tmp[p_var])
for p_var in phys_vars_list:
phys[p_var] = np.array(phys[p_var])
# remove outliers
thresh_1 = np.nanpercentile(np.abs(phys['vel_theta_1']), 98)
thresh_2 = np.nanpercentile(np.abs(phys['vel_theta_2']), 98)
thresh_z = np.nanpercentile(np.abs(phys['vel_z']), 98)
for n in range(num_vids):
for p in range(num_frms):
if (not np.isnan(phys['vel_theta_1'][n, p]) and np.abs(phys['vel_theta_1'][n, p]) >= thresh_1) \
or (not np.isnan(phys['vel_theta_2'][n, p]) and np.abs(phys['vel_theta_2'][n, p]) >= thresh_2) \
or (not np.isnan(phys['vel_z'][n, p]) and np.abs(phys['vel_z'][n, p]) >= thresh_z):
phys['vel_theta_1'][n, p] = np.nan
phys['vel_theta_2'][n, p] = np.nan
phys['vel_z'][n, p] = np.nan
phys['kinetic energy'][n, p] = np.nan
phys['total energy'][n, p] = np.nan
np.save(save_path, phys)
if __name__ == '__main__':
dataset = str(sys.argv[1])
data_filepath = str(sys.argv[2])
save_path = os.path.join(data_filepath, 'phys_vars.npy')
if dataset == 'single_pendulum':
eval_phys_data_single_pendulum(data_filepath, 1200, 60, save_path)
elif dataset == 'double_pendulum':
eval_phys_data_double_pendulum(data_filepath, 1100, 60, save_path)
elif dataset == 'elastic_pendulum':
eval_phys_data_elastic_pendulum(data_filepath, 1200, 60, save_path)
else:
assert False, 'Unknown system...'
|
[
"numpy.save",
"numpy.abs",
"numpy.isnan",
"numpy.array",
"eval_phys_elastic_pendulum.eval_physics",
"os.path.join"
] |
[((746, 770), 'numpy.save', 'np.save', (['save_path', 'phys'], {}), '(save_path, phys)\n', (753, 770), True, 'import numpy as np\n'), ((2086, 2110), 'numpy.save', 'np.save', (['save_path', 'phys'], {}), '(save_path, phys)\n', (2093, 2110), True, 'import numpy as np\n'), ((3629, 3653), 'numpy.save', 'np.save', (['save_path', 'phys'], {}), '(save_path, phys)\n', (3636, 3653), True, 'import numpy as np\n'), ((3767, 3811), 'os.path.join', 'os.path.join', (['data_filepath', '"""phys_vars.npy"""'], {}), "(data_filepath, 'phys_vars.npy')\n", (3779, 3811), False, 'import os\n'), ((558, 578), 'eval_phys_elastic_pendulum.eval_physics', 'eval_physics', (['frames'], {}), '(frames)\n', (570, 578), False, 'from eval_phys_elastic_pendulum import eval_physics, phys_vars_list\n'), ((719, 740), 'numpy.array', 'np.array', (['phys[p_var]'], {}), '(phys[p_var])\n', (727, 740), True, 'import numpy as np\n'), ((1256, 1276), 'eval_phys_elastic_pendulum.eval_physics', 'eval_physics', (['frames'], {}), '(frames)\n', (1268, 1276), False, 'from eval_phys_elastic_pendulum import eval_physics, phys_vars_list\n'), ((1417, 1438), 'numpy.array', 'np.array', (['phys[p_var]'], {}), '(phys[p_var])\n', (1425, 1438), True, 'import numpy as np\n'), ((1494, 1521), 'numpy.abs', 'np.abs', (["phys['vel_theta_1']"], {}), "(phys['vel_theta_1'])\n", (1500, 1521), True, 'import numpy as np\n'), ((1559, 1586), 'numpy.abs', 'np.abs', (["phys['vel_theta_2']"], {}), "(phys['vel_theta_2'])\n", (1565, 1586), True, 'import numpy as np\n'), ((2598, 2618), 'eval_phys_elastic_pendulum.eval_physics', 'eval_physics', (['frames'], {}), '(frames)\n', (2610, 2618), False, 'from eval_phys_elastic_pendulum import eval_physics, phys_vars_list\n'), ((2759, 2780), 'numpy.array', 'np.array', (['phys[p_var]'], {}), '(phys[p_var])\n', (2767, 2780), True, 'import numpy as np\n'), ((2836, 2863), 'numpy.abs', 'np.abs', (["phys['vel_theta_1']"], {}), "(phys['vel_theta_1'])\n", (2842, 2863), True, 'import numpy as np\n'), ((2901, 2928), 'numpy.abs', 'np.abs', (["phys['vel_theta_2']"], {}), "(phys['vel_theta_2'])\n", (2907, 2928), True, 'import numpy as np\n'), ((2966, 2987), 'numpy.abs', 'np.abs', (["phys['vel_z']"], {}), "(phys['vel_z'])\n", (2972, 2987), True, 'import numpy as np\n'), ((1676, 1711), 'numpy.isnan', 'np.isnan', (["phys['vel_theta_1'][n, p]"], {}), "(phys['vel_theta_1'][n, p])\n", (1684, 1711), True, 'import numpy as np\n'), ((1716, 1749), 'numpy.abs', 'np.abs', (["phys['vel_theta_1'][n, p]"], {}), "(phys['vel_theta_1'][n, p])\n", (1722, 1749), True, 'import numpy as np\n'), ((1785, 1820), 'numpy.isnan', 'np.isnan', (["phys['vel_theta_2'][n, p]"], {}), "(phys['vel_theta_2'][n, p])\n", (1793, 1820), True, 'import numpy as np\n'), ((1825, 1858), 'numpy.abs', 'np.abs', (["phys['vel_theta_2'][n, p]"], {}), "(phys['vel_theta_2'][n, p])\n", (1831, 1858), True, 'import numpy as np\n'), ((3077, 3112), 'numpy.isnan', 'np.isnan', (["phys['vel_theta_1'][n, p]"], {}), "(phys['vel_theta_1'][n, p])\n", (3085, 3112), True, 'import numpy as np\n'), ((3117, 3150), 'numpy.abs', 'np.abs', (["phys['vel_theta_1'][n, p]"], {}), "(phys['vel_theta_1'][n, p])\n", (3123, 3150), True, 'import numpy as np\n'), ((3186, 3221), 'numpy.isnan', 'np.isnan', (["phys['vel_theta_2'][n, p]"], {}), "(phys['vel_theta_2'][n, p])\n", (3194, 3221), True, 'import numpy as np\n'), ((3226, 3259), 'numpy.abs', 'np.abs', (["phys['vel_theta_2'][n, p]"], {}), "(phys['vel_theta_2'][n, p])\n", (3232, 3259), True, 'import numpy as np\n'), ((3295, 3324), 'numpy.isnan', 'np.isnan', (["phys['vel_z'][n, p]"], {}), "(phys['vel_z'][n, p])\n", (3303, 3324), True, 'import numpy as np\n'), ((3329, 3356), 'numpy.abs', 'np.abs', (["phys['vel_z'][n, p]"], {}), "(phys['vel_z'][n, p])\n", (3335, 3356), True, 'import numpy as np\n')]
|
import pickle
import numpy as np
import librosa
import pandas as pd
from raw_audio_create_dict import split_data
dict_path = '/scratch/speech/raw_audio_dataset/raw_audio_full.pkl'
file = open(dict_path, 'rb')
data = pickle.load(file)
audio_path = '/scratch/speech/raw_audio_dataset/audio_paths_labels_updated.csv'
df = pd.read_csv(audio_path)
thresh = 128000
sr_standard = 16000
input_new = []
seq_length_new = []
for i, utterance in enumerate(data['input']):
if len(utterance) < thresh:
utterance_new = np.tile(utterance, thresh // len(utterance) + 1)
utterance_new = utterance_new[0:thresh]
input_new.append(utterance_new)
seq_length_new.append(len(utterance_new))
elif len(utterance) > thresh:
utterance_new, sr = librosa.load(df['file'][i], sr = thresh/(len(utterance)/sr_standard))
utterance_new = utterance_new[0:thresh]
input_new.append(utterance_new)
seq_length_new.append(len(utterance_new))
else:
input_new.append(utterance)
seq_length_new.append(len(utterance))
dataset_updated = {'input': np.array(input_new), 'target': np.array(data['target']), 'seq_length': seq_length_new}
full_set_new = '/scratch/speech/raw_audio_dataset/raw_audio_full_equal_lengths.pkl'
train_set_new = '/scratch/speech/raw_audio_dataset/raw_audio_train_equal_lengths.pkl'
test_set_new = '/scratch/speech/raw_audio_dataset/raw_audio_test_equal_lengths.pkl'
train, test = split_data(dataset_updated)
with open(full_set_new, 'wb') as f:
pickle.dump(dataset_updated, f)
with open(train_set_new, 'wb') as f:
pickle.dump(train, f)
with open(test_set_new, 'wb') as f:
pickle.dump(test, f)
|
[
"pickle.dump",
"pandas.read_csv",
"pickle.load",
"numpy.array",
"raw_audio_create_dict.split_data"
] |
[((217, 234), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (228, 234), False, 'import pickle\n'), ((321, 344), 'pandas.read_csv', 'pd.read_csv', (['audio_path'], {}), '(audio_path)\n', (332, 344), True, 'import pandas as pd\n'), ((1455, 1482), 'raw_audio_create_dict.split_data', 'split_data', (['dataset_updated'], {}), '(dataset_updated)\n', (1465, 1482), False, 'from raw_audio_create_dict import split_data\n'), ((1098, 1117), 'numpy.array', 'np.array', (['input_new'], {}), '(input_new)\n', (1106, 1117), True, 'import numpy as np\n'), ((1129, 1153), 'numpy.array', 'np.array', (["data['target']"], {}), "(data['target'])\n", (1137, 1153), True, 'import numpy as np\n'), ((1523, 1554), 'pickle.dump', 'pickle.dump', (['dataset_updated', 'f'], {}), '(dataset_updated, f)\n', (1534, 1554), False, 'import pickle\n'), ((1596, 1617), 'pickle.dump', 'pickle.dump', (['train', 'f'], {}), '(train, f)\n', (1607, 1617), False, 'import pickle\n'), ((1658, 1678), 'pickle.dump', 'pickle.dump', (['test', 'f'], {}), '(test, f)\n', (1669, 1678), False, 'import pickle\n')]
|
#!/usr/bin/env python
import roslib; roslib.load_manifest('numpy_eigen'); roslib.load_manifest('rostest');
import numpy_eigen
import numpy_eigen.test as npe
import numpy
import sys
# http://docs.python.org/library/unittest.html#test-cases
import unittest
import generator_config
typeTag2NumpyTypeObjectMap = dict()
typeTag2NumpyTypeObjectMap['int'] = numpy.intc
typeTag2NumpyTypeObjectMap['float'] = numpy.float32
typeTag2NumpyTypeObjectMap['double'] = numpy.float64
typeTag2NumpyTypeObjectMap['uchar'] = numpy.uint8
typeTag2NumpyTypeObjectMap['long'] = numpy.int_
class TestEigen(unittest.TestCase):
def assertMatrixClose(self,numpyM,eigenM,testType):
self.assertEqual(numpyM.size,eigenM.size)
if eigenM.ndim == 1:
# The eigen conversion code will take a 1xN or Nx1 and turn
# it into a single dimension matrix.
if numpyM.ndim == 1:
# The original matrix was 1d...compare the 1d types.
self.assertEqual(numpyM.shape[0],eigenM.shape[0], testType)
self.assertTrue(numpy.max(numpy.abs(numpyM - eigenM)) < 1e-10, testType)
elif numpyM.ndim == 2:
# The original matrix was 2d...compare the 1d dimension
# with the eigen matrix
if numpyM.shape[0] == 1:
# Row vector
self.assertEqual(numpyM.shape[1],eigenM.shape[0], testType)
if eigenM.shape[0] > 0:
self.assertTrue(numpy.max(numpy.abs(numpyM[0,:] - eigenM)) < 1e-10, testType)
elif numpyM.shape[1] == 1:
# column vector
self.assertEqual(numpyM.shape[0],eigenM.shape[0], testType)
if eigenM.shape[0] > 0:
self.assertTrue(numpy.max(numpy.abs(numpyM[:,0] - eigenM)) < 1e-10, testType)
else:
self.fail('%s: The output matrix is a vector but none of the input matrix dimensions are 1: %s' % (testType,numpyM.shape))
else:
self.fail('%s: Unexpected number of dimensions in the numpy input matrix: %d' % (testType,numpyM.ndim))
elif eigenM.ndim == 2:
self.assertEqual(numpyM.shape[0],eigenM.shape[0], testType)
self.assertEqual(numpyM.shape[1],eigenM.shape[1], testType)
if numpyM.shape[0] > 0 and numpyM.shape[1] > 0:
self.assertTrue(numpy.max(numpy.abs(numpyM - eigenM)) < 1e-10, testType)
else:
self.fail('%s: Unexpected number of dimensions in the numpy output matrix: %d' % (testType, eigenM.ndim))
def matrixTests(self,t,i,j):
assert typeTag2NumpyTypeObjectMap[t]
npType = typeTag2NumpyTypeObjectMap[t];
row_limit = generator_config.MaximalStaticDimension + 1
col_limit = generator_config.MaximalStaticDimension + 1
rows_dim_is_dynamic = (i == 'D')
cols_dim_is_dynamic = (j == 'D')
ii = i;
jj = j;
if not rows_dim_is_dynamic:
ii = int(ii)
if not cols_dim_is_dynamic:
jj = int(jj)
fname = 'test_%s_%s_%s' % (t,i,j)
for R in range(0,row_limit):
for C in range(0,col_limit):
for transposeFirst in range(1):
testType = 'Testing %s with input array[%d,%d]%s' % (fname, R, C, ('^T' if transposeFirst else ''))
# Create a random matrix.
if transposeFirst:
numpyM = numpy.random.random([C,R]).astype(dtype = npType).T
else:
numpyM = numpy.random.random([R,C]).astype(dtype = npType)
assert numpyM.dtype == npType
try:
# Try to pass it in to the pass-through function
eigenM = npe.__dict__[fname](numpyM)
# There was no error...check that this was okay.
rows_dim_is_dynamic or self.assertEqual(R, ii, testType)
cols_dim_is_dynamic or self.assertEqual(C, jj, testType)
# Check that the matrices are the same.
self.assertMatrixClose(numpyM,eigenM, testType)
except TypeError as inst:
# There was a type error. Check that this was expected.
self.assertFalse( (rows_dim_is_dynamic or R == ii) and (cols_dim_is_dynamic or C == jj), testType)
def vectorTests(self,t,i,j):
x = 1
# um...
def test_eigen(self):
if numpy_eigen.IsBroken : self.skipTest("numpy_eigen is broken (see #137)");
T = generator_config.typeTags
N = generator_config.dimTags
for t in T:
for i in N:
for j in N:
self.matrixTests(t,i,j)
if __name__ == '__main__':
import rostest
rostest.rosrun('numpy_eigen', 'test_eigen', TestEigen)
|
[
"numpy.abs",
"roslib.load_manifest",
"rostest.rosrun",
"numpy.random.random"
] |
[((37, 72), 'roslib.load_manifest', 'roslib.load_manifest', (['"""numpy_eigen"""'], {}), "('numpy_eigen')\n", (57, 72), False, 'import roslib\n'), ((74, 105), 'roslib.load_manifest', 'roslib.load_manifest', (['"""rostest"""'], {}), "('rostest')\n", (94, 105), False, 'import roslib\n'), ((5047, 5101), 'rostest.rosrun', 'rostest.rosrun', (['"""numpy_eigen"""', '"""test_eigen"""', 'TestEigen'], {}), "('numpy_eigen', 'test_eigen', TestEigen)\n", (5061, 5101), False, 'import rostest\n'), ((1083, 1109), 'numpy.abs', 'numpy.abs', (['(numpyM - eigenM)'], {}), '(numpyM - eigenM)\n', (1092, 1109), False, 'import numpy\n'), ((2462, 2488), 'numpy.abs', 'numpy.abs', (['(numpyM - eigenM)'], {}), '(numpyM - eigenM)\n', (2471, 2488), False, 'import numpy\n'), ((3689, 3716), 'numpy.random.random', 'numpy.random.random', (['[R, C]'], {}), '([R, C])\n', (3708, 3716), False, 'import numpy\n'), ((3578, 3605), 'numpy.random.random', 'numpy.random.random', (['[C, R]'], {}), '([C, R])\n', (3597, 3605), False, 'import numpy\n'), ((1525, 1557), 'numpy.abs', 'numpy.abs', (['(numpyM[0, :] - eigenM)'], {}), '(numpyM[0, :] - eigenM)\n', (1534, 1557), False, 'import numpy\n'), ((1830, 1862), 'numpy.abs', 'numpy.abs', (['(numpyM[:, 0] - eigenM)'], {}), '(numpyM[:, 0] - eigenM)\n', (1839, 1862), False, 'import numpy\n')]
|
"""
This script is for thermodynamic model for sortseq data for the paper
MAVE-NN: learning genotype-phenotype maps from multiplex assays of variant effect
<NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>
"""
# Standard imports
import numpy as np
from numpy.core.fromnumeric import sort
import pandas as pd
import warnings
import os
from datetime import datetime
import json
import argparse
import matplotlib.pyplot as plt
# Turn off Tensorflow GPU warnings
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
warnings.filterwarnings("ignore")
# Standard TensorFlow imports
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras.initializers import Constant
# Import MAVE-NN
import mavenn
# Import base class
from mavenn.src.layers.gpmap import GPMapLayer
from mavenn.src.utils import _x_to_mat
# Fix the seed, default seed is seed=1234
mavenn.src.utils.set_seed()
# Get the date to append to the saved model name
today = datetime.now()
date_str = today.strftime("%Y.%m.%d.%Hh.%Mm")
# Get the models dictionary from the json input file.
input_file = open("sortseq_thermo_param.json")
models_dict = json.load(input_file)
# Define custom G-P map layer
class sortseqGPMapLayer(GPMapLayer):
"""
Represents a four-stage thermodynamic model
containing the states:
1. free DNA
2. CPR-DNA binding
3. RNAP-DNA binding
4. CPR and RNAP both bounded to DNA and interact
"""
def __init__(self,
tf_start,
tf_end,
rnap_start,
rnap_end,
*args, **kwargs):
"""Construct layer instance."""
# Call superclass
super().__init__(*args, **kwargs)
# set attributes
self.tf_start = tf_start # transcription factor starting position
self.tf_end = tf_end # transcription factor ending position
self.L_tf = tf_end - tf_start # length of transcription factor
self.rnap_start = rnap_start # RNAP starting position
self.rnap_end = rnap_end # RNAP ending position
self.L_rnap = rnap_end - rnap_start # length of RNAP
self.C = kwargs["C"]
# define bias/chemical potential weight for TF/CRP energy
self.theta_tf_0 = self.add_weight(name='theta_tf_0',
shape=(1,),
initializer=Constant(1.),
trainable=True,
regularizer=self.regularizer)
# define bias/chemical potential weight for rnap energy
self.theta_rnap_0 = self.add_weight(name='theta_rnap_0',
shape=(1,),
initializer=Constant(1.),
trainable=True,
regularizer=self.regularizer)
# initialize the theta_tf
theta_tf_shape = (1, self.L_tf, self.C)
theta_tf_init = np.random.randn(*theta_tf_shape)/np.sqrt(self.L_tf)
# define the weights of the layer corresponds to theta_tf
self.theta_tf = self.add_weight(name='theta_tf',
shape=theta_tf_shape,
initializer=Constant(theta_tf_init),
trainable=True,
regularizer=self.regularizer)
# define theta_rnap parameters
theta_rnap_shape = (1, self.L_rnap, self.C)
theta_rnap_init = np.random.randn(*theta_rnap_shape)/np.sqrt(self.L_rnap)
# define the weights of the layer corresponds to theta_rnap
self.theta_rnap = self.add_weight(name='theta_rnap',
shape=theta_rnap_shape,
initializer=Constant(theta_rnap_init),
trainable=True,
regularizer=self.regularizer)
# define trainable real number G_I, representing interaction Gibbs energy
self.theta_dG_I = self.add_weight(name='theta_dG_I',
shape=(1,),
initializer=Constant(-4),
trainable=True,
regularizer=self.regularizer)
def call(self, x):
"""Process layer input and return output.
x: (tensor)
Input tensor that represents one-hot encoded
sequence values.
"""
# 1kT = 0.616 kcal/mol at body temperature
kT = 0.616
# extract locations of binding sites from entire lac-promoter sequence.
# for transcription factor and rnap
x_tf = x[:, self.C * self.tf_start:self.C * self.tf_end]
x_rnap = x[:, self.C * self.rnap_start: self.C * self.rnap_end]
# reshape according to tf and rnap lengths.
x_tf = tf.reshape(x_tf, [-1, self.L_tf, self.C])
x_rnap = tf.reshape(x_rnap, [-1, self.L_rnap, self.C])
# compute delta G for crp binding
G_C = self.theta_tf_0 + \
tf.reshape(K.sum(self.theta_tf * x_tf, axis=[1, 2]),
shape=[-1, 1])
# compute delta G for rnap binding
G_R = self.theta_rnap_0 + \
tf.reshape(K.sum(self.theta_rnap * x_rnap, axis=[1, 2]),
shape=[-1, 1])
G_I = self.theta_dG_I
# compute phi
numerator_of_rate = K.exp(-G_R/kT) + K.exp(-(G_C+G_R+G_I)/kT)
denom_of_rate = 1.0 + K.exp(-G_C/kT) + K.exp(-G_R/kT) + K.exp(-(G_C+G_R+G_I)/kT)
phi = numerator_of_rate/denom_of_rate
return phi
def main(args):
# Set dataset name
dataset_name = "sortseq"
# Set type of GP map
model_type = "custom"
# Set learning rate
learning_rate = args.learning_rate
# Set number of epochs
epochs = args.epochs
# Get parameters dict
params_dict = models_dict[model_type]
# Read dataset from the paper dataset instead of MAVENN dataset
data_df = pd.read_csv(f"../datasets/{dataset_name}_data.csv.gz")
print(data_df)
# Get and report sequence length
L = len(data_df.loc[0, "x"])
print(f"Sequence length: {L:d} ")
# Preview dataset
print("data_df:")
# Split dataset
trainval_df, test_df = mavenn.split_dataset(data_df)
# Preview trainval_df
print("trainval_df:")
# Define model
# Create model instance
model = mavenn.Model(
custom_gpmap=sortseqGPMapLayer,
**params_dict["model_params"],
gpmap_kwargs=params_dict["gpmap_kwargs"],
)
# Set training data
model.set_data(
x=trainval_df["x"],
y=trainval_df[[col for col in trainval_df if col.startswith("ct")]],
validation_flags=trainval_df["validation"],
)
# Train model
model.fit(learning_rate=learning_rate, epochs=epochs, **params_dict["fit_params"])
# Save trained model to file
model_name = (f"../models/sortseq_thermodynamic_mpa_{date_str}")
model.save(model_name)
# simulate new dataset with trained model
num_models = args.num_models
sim_models = model.bootstrap(data_df=data_df,
num_models=num_models,
initialize_from_self=True)
# save simulated models
for i in range(num_models):
model_name = (f"../models/sortseq_thermodynamic_mpa_model_{i}_{date_str}")
sim_models[i].save(model_name)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="sortseq Thermodynamic Model")
parser.add_argument(
"-e", "--epochs", default=2000, type=int, help="Number of epochs"
)
parser.add_argument(
"-lr", "--learning_rate", default=1e-4, type=float, help="Learning Rate"
)
parser.add_argument(
"-ns", "--num_models", default=20, type=int, help="number of simulation models"
)
args = parser.parse_args()
main(args)
|
[
"json.load",
"tensorflow.keras.backend.sum",
"argparse.ArgumentParser",
"warnings.filterwarnings",
"pandas.read_csv",
"numpy.random.randn",
"tensorflow.reshape",
"mavenn.Model",
"tensorflow.keras.initializers.Constant",
"tensorflow.keras.backend.exp",
"mavenn.split_dataset",
"mavenn.src.utils.set_seed",
"datetime.datetime.now",
"numpy.sqrt"
] |
[((500, 533), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (523, 533), False, 'import warnings\n'), ((859, 886), 'mavenn.src.utils.set_seed', 'mavenn.src.utils.set_seed', ([], {}), '()\n', (884, 886), False, 'import mavenn\n'), ((945, 959), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (957, 959), False, 'from datetime import datetime\n'), ((1122, 1143), 'json.load', 'json.load', (['input_file'], {}), '(input_file)\n', (1131, 1143), False, 'import json\n'), ((6246, 6300), 'pandas.read_csv', 'pd.read_csv', (['f"""../datasets/{dataset_name}_data.csv.gz"""'], {}), "(f'../datasets/{dataset_name}_data.csv.gz')\n", (6257, 6300), True, 'import pandas as pd\n'), ((6522, 6551), 'mavenn.split_dataset', 'mavenn.split_dataset', (['data_df'], {}), '(data_df)\n', (6542, 6551), False, 'import mavenn\n'), ((6665, 6786), 'mavenn.Model', 'mavenn.Model', ([], {'custom_gpmap': 'sortseqGPMapLayer', 'gpmap_kwargs': "params_dict['gpmap_kwargs']"}), "(custom_gpmap=sortseqGPMapLayer, **params_dict['model_params'],\n gpmap_kwargs=params_dict['gpmap_kwargs'])\n", (6677, 6786), False, 'import mavenn\n'), ((7732, 7798), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""sortseq Thermodynamic Model"""'}), "(description='sortseq Thermodynamic Model')\n", (7755, 7798), False, 'import argparse\n'), ((5095, 5136), 'tensorflow.reshape', 'tf.reshape', (['x_tf', '[-1, self.L_tf, self.C]'], {}), '(x_tf, [-1, self.L_tf, self.C])\n', (5105, 5136), True, 'import tensorflow as tf\n'), ((5154, 5199), 'tensorflow.reshape', 'tf.reshape', (['x_rnap', '[-1, self.L_rnap, self.C]'], {}), '(x_rnap, [-1, self.L_rnap, self.C])\n', (5164, 5199), True, 'import tensorflow as tf\n'), ((3084, 3116), 'numpy.random.randn', 'np.random.randn', (['*theta_tf_shape'], {}), '(*theta_tf_shape)\n', (3099, 3116), True, 'import numpy as np\n'), ((3117, 3135), 'numpy.sqrt', 'np.sqrt', (['self.L_tf'], {}), '(self.L_tf)\n', (3124, 3135), True, 'import numpy as np\n'), ((3651, 3685), 'numpy.random.randn', 'np.random.randn', (['*theta_rnap_shape'], {}), '(*theta_rnap_shape)\n', (3666, 3685), True, 'import numpy as np\n'), ((3686, 3706), 'numpy.sqrt', 'np.sqrt', (['self.L_rnap'], {}), '(self.L_rnap)\n', (3693, 3706), True, 'import numpy as np\n'), ((5657, 5673), 'tensorflow.keras.backend.exp', 'K.exp', (['(-G_R / kT)'], {}), '(-G_R / kT)\n', (5662, 5673), True, 'import tensorflow.keras.backend as K\n'), ((5674, 5704), 'tensorflow.keras.backend.exp', 'K.exp', (['(-(G_C + G_R + G_I) / kT)'], {}), '(-(G_C + G_R + G_I) / kT)\n', (5679, 5704), True, 'import tensorflow.keras.backend as K\n'), ((5763, 5793), 'tensorflow.keras.backend.exp', 'K.exp', (['(-(G_C + G_R + G_I) / kT)'], {}), '(-(G_C + G_R + G_I) / kT)\n', (5768, 5793), True, 'import tensorflow.keras.backend as K\n'), ((2443, 2456), 'tensorflow.keras.initializers.Constant', 'Constant', (['(1.0)'], {}), '(1.0)\n', (2451, 2456), False, 'from tensorflow.keras.initializers import Constant\n'), ((2829, 2842), 'tensorflow.keras.initializers.Constant', 'Constant', (['(1.0)'], {}), '(1.0)\n', (2837, 2842), False, 'from tensorflow.keras.initializers import Constant\n'), ((3382, 3405), 'tensorflow.keras.initializers.Constant', 'Constant', (['theta_tf_init'], {}), '(theta_tf_init)\n', (3390, 3405), False, 'from tensorflow.keras.initializers import Constant\n'), ((3965, 3990), 'tensorflow.keras.initializers.Constant', 'Constant', (['theta_rnap_init'], {}), '(theta_rnap_init)\n', (3973, 3990), False, 'from tensorflow.keras.initializers import Constant\n'), ((4360, 4372), 'tensorflow.keras.initializers.Constant', 'Constant', (['(-4)'], {}), '(-4)\n', (4368, 4372), False, 'from tensorflow.keras.initializers import Constant\n'), ((5300, 5340), 'tensorflow.keras.backend.sum', 'K.sum', (['(self.theta_tf * x_tf)'], {'axis': '[1, 2]'}), '(self.theta_tf * x_tf, axis=[1, 2])\n', (5305, 5340), True, 'import tensorflow.keras.backend as K\n'), ((5483, 5527), 'tensorflow.keras.backend.sum', 'K.sum', (['(self.theta_rnap * x_rnap)'], {'axis': '[1, 2]'}), '(self.theta_rnap * x_rnap, axis=[1, 2])\n', (5488, 5527), True, 'import tensorflow.keras.backend as K\n'), ((5746, 5762), 'tensorflow.keras.backend.exp', 'K.exp', (['(-G_R / kT)'], {}), '(-G_R / kT)\n', (5751, 5762), True, 'import tensorflow.keras.backend as K\n'), ((5729, 5745), 'tensorflow.keras.backend.exp', 'K.exp', (['(-G_C / kT)'], {}), '(-G_C / kT)\n', (5734, 5745), True, 'import tensorflow.keras.backend as K\n')]
|
############################################################################
# This Python file is part of PyFEM, the code that accompanies the book: #
# #
# 'Non-Linear Finite Element Analysis of Solids and Structures' #
# <NAME>, <NAME>, <NAME> and <NAME> #
# <NAME> and Sons, 2012, ISBN 978-0470666449 #
# #
# The code is written by <NAME>, <NAME> and <NAME>. #
# #
# The latest stable version can be downloaded from the web-site: #
# http://www.wiley.com/go/deborst #
# #
# A github repository, with the most up to date version of the code, #
# can be found here: #
# https://github.com/jjcremmers/PyFEM #
# #
# The code is open source and intended for educational and scientific #
# purposes only. If you use PyFEM in your research, the developers would #
# be grateful if you could cite the book. #
# #
# Disclaimer: #
# The authors reserve all rights but do not guarantee that the code is #
# free from errors. Furthermore, the authors shall not be liable in any #
# event caused by the use of the program. #
############################################################################
from pyfem.util.dataStructures import Properties
from pyfem.util.dataStructures import GlobalData
from numpy import zeros, array
from pyfem.fem.Assembly import assembleInternalForce, assembleTangentStiffness
from numpy import zeros, array
from pyfem.fem.Assembly import assembleInternalForce, assembleTangentStiffness
#################################
# Step 1: #
# Initialize (Delta a) #
#################################
class DissipationNRGSolver:
def __init__( self , props , globdat ):
self.tol = 1.0e-4
print("asd")
def run( self , props , globdat ):
globdat.cycle += 1
dofCount = len(globdat.dofs)
a = globdat.state
Da = globdat.Dstate
Da[:] = zeros( dofCount )
fint = zeros( dofCount )
fext = zeros( dofCount )
print('=================================')
print(' Load step %i' % globdat.cycle)
print('=================================')
print(' NR iter : L2-norm residual')
#fext = fext + Dfext
globdat.iiter = 0
K = assembleTangentStiffness( props, globdat )
error = 1.
while error > self.tol:
globdat.iiter += 1
da = globdat.dofs.solve( K, fext-fint )
Da[:] += da[:]
a [:] += da[:]
fint = assembleInternalForce ( props, globdat )
K = assembleTangentStiffness( props, globdat )
error = globdat.dofs.norm( fext-fint )
print(' Iter', globdat.iiter, ':', error)
if globdat.iiter == self.iterMax:
raise RuntimeError('Newton-Raphson iterations did not converge!')
# Converged
elements.commitHistory()
if globdat.cycle == 10:
globdat.active = False
|
[
"pyfem.fem.Assembly.assembleTangentStiffness",
"numpy.zeros",
"pyfem.fem.Assembly.assembleInternalForce"
] |
[((2668, 2683), 'numpy.zeros', 'zeros', (['dofCount'], {}), '(dofCount)\n', (2673, 2683), False, 'from numpy import zeros, array\n'), ((2699, 2714), 'numpy.zeros', 'zeros', (['dofCount'], {}), '(dofCount)\n', (2704, 2714), False, 'from numpy import zeros, array\n'), ((2731, 2746), 'numpy.zeros', 'zeros', (['dofCount'], {}), '(dofCount)\n', (2736, 2746), False, 'from numpy import zeros, array\n'), ((3007, 3047), 'pyfem.fem.Assembly.assembleTangentStiffness', 'assembleTangentStiffness', (['props', 'globdat'], {}), '(props, globdat)\n', (3031, 3047), False, 'from pyfem.fem.Assembly import assembleInternalForce, assembleTangentStiffness\n'), ((3253, 3290), 'pyfem.fem.Assembly.assembleInternalForce', 'assembleInternalForce', (['props', 'globdat'], {}), '(props, globdat)\n', (3274, 3290), False, 'from pyfem.fem.Assembly import assembleInternalForce, assembleTangentStiffness\n'), ((3310, 3350), 'pyfem.fem.Assembly.assembleTangentStiffness', 'assembleTangentStiffness', (['props', 'globdat'], {}), '(props, globdat)\n', (3334, 3350), False, 'from pyfem.fem.Assembly import assembleInternalForce, assembleTangentStiffness\n')]
|
# -*- encoding: utf-8 -*-
'''
@File : kdTree.py
@Contact : <EMAIL>
@Modify Time @Author @Version @Desciption
------------ ----------- -------- -----------
2020/1/4 21:27 guzhouweihu 1.0 None
'''
import math
from collections import namedtuple
import time
from random import random
import numpy as np
import heapq
from priority_queue import MaxHeap
class kdNode(object):
def __init__(self, point, split_dim, left, right):
self.point = point
self.split_dim = split_dim
self.left = left
self.right = right
class kdTree(object):
def __init__(self, dataset):
self.k = len(dataset[0])
def createNode(split_dim, dataset):
if not dataset:
return None
dataset.sort(key=lambda x: x[split_dim])
split_pos = len(dataset) // 2
mid_pnt = dataset[split_pos]
split_next_dim = (split_dim + 1) % self.k
return kdNode(mid_pnt, split_dim,
createNode(split_next_dim, dataset[:split_pos]),
createNode(split_next_dim, dataset[split_pos + 1:]))
self.root = createNode(0, dataset)
def nearest(self, x, near_k=1, p=2):
self.k_nearest = [(-np.inf, None)] * near_k
def travel(node):
if not node == None:
dist = x[node.split_dim] - node.point[node.split_dim]
travel(node.left if dist < 0 else node.right)
cur_dist = np.linalg.norm(np.array(x) - np.array(node.point), p)
heapq.heappushpop(self.k_nearest, (-cur_dist, node))
if -(self.k_nearest[0][0]) > abs(dist):
travel(node.right if dist < 0 else node.left)
travel(self.root)
self.k_nearest = np.array([i[1].point for i in heapq.nlargest(near_k, self.k_nearest)])
return self.k_nearest
def nearest_useMyqueue(self, target, near_k=1, p=2):
priorityQueue = MaxHeap(near_k, lambda x: x[0])
def travel(node):
if not node == None:
dist = target[node.split_dim] - node.point[node.split_dim]
travel(node.left if dist < 0 else node.right)
cur_dist = np.linalg.norm(np.array(target) - np.array(node.point), p)
priorityQueue.insert_keep_size((cur_dist, node))
max_item = priorityQueue.get_max()
if max_item[0] > abs(dist):
travel(node.right if dist < 0 else node.left)
travel(self.root)
res = []
for i in range(near_k):
res.insert(0, priorityQueue.del_max()[1].point)
return res
# 中序遍历
def preorder(root):
if root.left:
preorder(root.left)
print(root.point)
if root.right:
preorder(root.right)
if __name__ == "__main__":
data = [[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]]
kd = kdTree(data)
preorder(kd.root)
# 产生一个k维随机向量,每维分量值在0~1之间
def random_point(k):
return [random() for _ in range(k)]
# 产生n个k维随机向量
def random_points(k, n):
return [random_point(k) for _ in range(n)]
N = 40000
data = random_points(3, N)
kd2 = kdTree(data) # 构建包含四十万个3维空间样本点的kd树
result2 = kd2.nearest([0.1, 0.5, 0.8], 5, 2)
result3 = kd2.nearest_useMyqueue([0.1, 0.5, 0.8], 5, 2)
print(result2)
print(np.array(result3))
|
[
"heapq.heappushpop",
"heapq.nlargest",
"priority_queue.MaxHeap",
"random.random",
"numpy.array"
] |
[((2013, 2044), 'priority_queue.MaxHeap', 'MaxHeap', (['near_k', '(lambda x: x[0])'], {}), '(near_k, lambda x: x[0])\n', (2020, 2044), False, 'from priority_queue import MaxHeap\n'), ((3428, 3445), 'numpy.array', 'np.array', (['result3'], {}), '(result3)\n', (3436, 3445), True, 'import numpy as np\n'), ((3059, 3067), 'random.random', 'random', ([], {}), '()\n', (3065, 3067), False, 'from random import random\n'), ((1601, 1653), 'heapq.heappushpop', 'heapq.heappushpop', (['self.k_nearest', '(-cur_dist, node)'], {}), '(self.k_nearest, (-cur_dist, node))\n', (1618, 1653), False, 'import heapq\n'), ((1860, 1898), 'heapq.nlargest', 'heapq.nlargest', (['near_k', 'self.k_nearest'], {}), '(near_k, self.k_nearest)\n', (1874, 1898), False, 'import heapq\n'), ((1545, 1556), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1553, 1556), True, 'import numpy as np\n'), ((1559, 1579), 'numpy.array', 'np.array', (['node.point'], {}), '(node.point)\n', (1567, 1579), True, 'import numpy as np\n'), ((2284, 2300), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (2292, 2300), True, 'import numpy as np\n'), ((2303, 2323), 'numpy.array', 'np.array', (['node.point'], {}), '(node.point)\n', (2311, 2323), True, 'import numpy as np\n')]
|
'''
'''
__debug = False
from collections import namedtuple , Counter
import copy, sys
import numpy as np
try:
from src import core,file
from src.TWL06 import twl
except:
import core,file
from TWL06 import twl
def pattern(word,utf8=False):
pattern = np.zeros(len(word),dtype="int")
index = 0
if utf8: seen = ""
else: seen = bytearray("","ascii")
for i,letter in enumerate(word):
try:
if not letter in seen:
pattern[i] = index
for j,nextLetter in enumerate(word[i+1:]):
if letter == nextLetter:
pattern[i] = index
pattern[j+i+1] = index
seen.append(letter)
index += 1
except TypeError:
print("ERROR: Check that the input is a bytearray, or utf8=True is set")
return
return pattern
class tupleArray:
array = np.empty([])
def __init__(self,cipher):
wordList = cipher.strip().split(bytes([ord(" ")]))
self.array = np.empty(len(wordList),dtype=tuple)
wordTuple = namedtuple('wordTuple','word original length solved pattern')
for i,j in enumerate(wordList):
self.array[i] = wordTuple(word=bytearray(j),original=j,length=len(j),solved=np.array([False]*len(j)),pattern=pattern(j))
def show(self,file=sys.stdout):
for word in self.array:
for j,letter in enumerate(word.word):
if word.solved[j]: print(chr(letter).lower(),end="",file=file)
else: print(chr(letter).upper(),end="",file=file)
print(" ",end="",file=file)
print("\n",end="",file=file)
def scrap(self):
for word in self.array:
for i in range(len(word.word)): word.word[i] = word.original[i]
for i in range(len(word.solved)): word.solved[i] = False
def simpleCheck(self):
for word in self.array:
if word.length == 1 and word.solved[0] == True and word[0] not in bytearray("aio","ascii"): return [False,word]
elif not (False in word.solved) and not (twl.check(str(word.word,"utf-8")) or word.word in bytearray("aio","ascii")):
return [False,word]
return [True,bytearray("","ascii")]
def fullCheck(self):
for word in self.array:
for bool in word.solved:
if not bool: return False
return True
def wordPossibilities(plaintext,tupleArray):
possibilities = []
for word in tupleArray.array:
if np.array_equal(word.pattern,pattern(plaintext)):
possibilities.append(str(word.original,"utf-8"))
count = Counter(possibilities)
possibilities = sorted(possibilities, key=lambda x: -count[x])
sortedP = []
for i in possibilities:
i = bytearray(i.lower(),"ascii")
if not i in sortedP: sortedP.append(i)
return sortedP
class cipherAlphabet:
current = np.zeros(26,dtype="object")
def __init__(self):
for i,letter in enumerate(bytearray("abcdefghijklmnopqrstuvwxyz","ascii")):
self.current[i] = [letter,False]
found = []
def show(self,file=sys.stdout):
for i in range(26): print(chr(97+i),end=" ",file=file)
output = np.zeros(26,dtype=int)
for i,letter in enumerate(self.current):
if letter[1]: output[letter[0] - 97] = i + 65
print(file=file)
for i in output:
if i != 0:
print(chr(i),end=" ",file=file)
else: print(" ",end=" ",file=file)
print(file=file)
def set(self,plaintext,ciphertext):
done = bytearray("","ascii")
### CHECK:
for plain,cipher in zip(plaintext,ciphertext):
for p,c in self.found:
for i,j in zip(p,c):
if (i == plain) ^ (j == cipher):
return 1
### SET:
for plain,cipher in zip(plaintext,ciphertext):
if not (plaintext,ciphertext) in self.found:
self.found.append((plaintext,ciphertext))
index = (cipher-97)%26
if not self.current[index][1]:
self.current[index][0] = plain
self.current[index][1] = True
done += bytes([cipher])
return 0
def scrap(self,found=False):
for i,letter in enumerate(self.current):
if letter[1]:
self.current[i] = [i+97,False]
if found: self.found = []
def fill(self):
missingCipher = []
for i,letter in enumerate(self.current):
if not letter[1]: missingCipher.append(i+97)
for plain in range(97,123):
for i,cipher in enumerate(self.current):
if cipher[0] == plain and cipher[1]: break
else:
self.set(bytes([plain]),bytes([missingCipher[0]]))
missingCipher = missingCipher[1:]
def shift(alphabet,tupleArray):
for cipher,plain in enumerate(alphabet.current):
if plain[1]:
cipher += 65
plain = plain[0]
for word in tupleArray.array:
for i,letter in enumerate(word.word):
if letter == cipher and word.solved[i] == False:
word.word[i] = plain
word.solved[i] = True
return 0
def recursiveSolve(words, tupleArray, accepted=[], recursionCounter = 0,newWords=[]):
'''
It will recursively try all inputs given to it against all
possibilities in the text, depending on repeated letter patterns,
and return a list of completed words, as (plaintext, ciphertext) tuples
>>> from substitution import recursiveSolve, tupleArray
>>> t = tupleArray(bytearray("JL NJIWI","ascii"))
>>> recursiveSolve(['hi','there'],t)
[(bytearray(b'hi'), bytearray(b'jl')), (bytearray(b'there'), bytearray(b'njiwi'))]
>>> t.show()
hi there
'''
if len(words) == 0: return accepted
word = bytearray(words[0],"ascii")
alphabet = cipherAlphabet()
for i,solution in enumerate(wordPossibilities(word,tupleArray)):
tupleArray.scrap()
alphabet.scrap(found=True)
for plain,cipher in accepted: alphabet.set(plain,cipher)
if alphabet.set(word,solution) == 1:
continue
else:
shift(alphabet,tupleArray)
check = tupleArray.simpleCheck()
if __debug: print(check[1])
if not check[0] and check[1].word in newWords: check[0] = True
if not check[0]:
if __debug: bool = True
else: bool = input("is "+str(check[1].word)+" a word? ")[0] == 'y'
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
print(CURSOR_UP_ONE+ERASE_LINE+"\r",end="")
if bool:
twl.add(check[1].word)
check[0] = True
newWords.append(check[1].word)
if check[0]: maybeReturn = recursiveSolve(words[1:],tupleArray,accepted + [(word,solution)],recursionCounter+1,newWords=newWords)
else:
continue
if maybeReturn:
return maybeReturn
def flatten(L):
if L == None: yield None
for item in L:
if type(item) == type(bytearray("","ascii")):
yield item
else: yield from flatten(item)
def recursiveGuess(masterArray,alphabet,minWord=6,failCount=0,newWords=[]):
tupleArray = copy.deepcopy(masterArray)
if tupleArray.fullCheck(): return tupleArray
unknowns = []
for word in tupleArray.array:
if word.length < minWord: continue
possibles = recursiveCheck(word,alphabet)
if possibles == None: continue
for test in flatten([possibles]):
if test == word.word:
break
elif alphabet.set(test,word.original.lower()) == 1:
continue
else:
shift(alphabet,tupleArray)
check = tupleArray.simpleCheck()
if not check[0] and not check[1].word in newWords:
if __debug: bool = True
else: bool = input("is "+str(check[1].word)+" a word? ")[0] == 'y'
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
print(CURSOR_UP_ONE+ERASE_LINE+"\r",end="")
if bool:
twl.add(check[1].word)
check[0] = True
newWords.append(check[1].word)
if check[0]:
a = recursiveGuess(tupleArray,alphabet,minWord,failCount,newWords)
if a:
return a
else:
failCount += 1
break
else:
tupleArray = copy.deepcopy(masterArray)
continue
else:
return masterArray
def recursiveCheck(masterTuple,alphabet,found=None):
wordTuple = copy.deepcopy(masterTuple)
returnValue = []
if found:
for i in range(len(wordTuple.word)):
if wordTuple.word[i] == wordTuple.original[found[0]] and wordTuple.solved[i] == False:
wordTuple.word[i] = found[1]
wordTuple.solved[i] = True
start = bytearray("","ascii")
index = 0
for i,letter in enumerate(wordTuple.word):
if wordTuple.solved[i] == True:
start += bytes([letter])
else:
index = i
break
if len(start) == 0: return None
if len(start) == wordTuple.length:
if twl.check(str(wordTuple.word,'utf-8')): return wordTuple.word
else: return None
for possible in twl.children(str(start,"utf-8")):
if possible == '$': continue
for plain,_ in alphabet.found:
if ord(possible) in plain: break
else:
a = recursiveCheck(wordTuple,alphabet,(index,ord(possible)))
if a: returnValue.append(a)
return returnValue
def finalCheck(tupleArray, alphabet):
'''
This occurs when a letter is missed because it only occurs at the start of the word,
where recursiveCheck misses it as it cannot be checked directly using twl
'''
for word in tupleArray.array:
if (len(word.solved) > 1 and not word.solved[0]) and not ( False in word.solved[1:]):
possible = []
orig = word.word[0]
for l in range(26):
word.word[0] = l+97
if twl.check(str(word.word,"utf-8")):
possible.append((bytes([l+97]),bytes([orig+32])))
if len(possible) == 1:
alphabet.set(possible[0][0],possible[0][1])
word.word[0] = orig
return alphabet
|
[
"copy.deepcopy",
"TWL06.twl.add",
"numpy.empty",
"numpy.zeros",
"collections.namedtuple",
"collections.Counter"
] |
[((767, 779), 'numpy.empty', 'np.empty', (['[]'], {}), '([])\n', (775, 779), True, 'import numpy as np\n'), ((2282, 2304), 'collections.Counter', 'Counter', (['possibilities'], {}), '(possibilities)\n', (2289, 2304), False, 'from collections import namedtuple, Counter\n'), ((2535, 2563), 'numpy.zeros', 'np.zeros', (['(26)'], {'dtype': '"""object"""'}), "(26, dtype='object')\n", (2543, 2563), True, 'import numpy as np\n'), ((6297, 6323), 'copy.deepcopy', 'copy.deepcopy', (['masterArray'], {}), '(masterArray)\n', (6310, 6323), False, 'import copy, sys\n'), ((7443, 7469), 'copy.deepcopy', 'copy.deepcopy', (['masterTuple'], {}), '(masterTuple)\n', (7456, 7469), False, 'import copy, sys\n'), ((926, 988), 'collections.namedtuple', 'namedtuple', (['"""wordTuple"""', '"""word original length solved pattern"""'], {}), "('wordTuple', 'word original length solved pattern')\n", (936, 988), False, 'from collections import namedtuple, Counter\n'), ((2814, 2837), 'numpy.zeros', 'np.zeros', (['(26)'], {'dtype': 'int'}), '(26, dtype=int)\n', (2822, 2837), True, 'import numpy as np\n'), ((5775, 5797), 'TWL06.twl.add', 'twl.add', (['check[1].word'], {}), '(check[1].word)\n', (5782, 5797), False, 'from TWL06 import twl\n'), ((7303, 7329), 'copy.deepcopy', 'copy.deepcopy', (['masterArray'], {}), '(masterArray)\n', (7316, 7329), False, 'import copy, sys\n'), ((7032, 7054), 'TWL06.twl.add', 'twl.add', (['check[1].word'], {}), '(check[1].word)\n', (7039, 7054), False, 'from TWL06 import twl\n')]
|
import math
from abc import ABC
from typing import Optional, Callable
import numpy as np
from .. import distances
from .part_reward import PartReward
class PartVelocityReward(PartReward, ABC):
"""
A reward that punishes (linear and angular) movement of parts.
"""
def __init__(self, name_prefix: str, max_linear_velocity: float = 1.0,
max_angular_velocity: float = math.pi,
intermediate_timestep_reward_scale: Optional[float] = 0.0,
final_timestep_reward_scale: Optional[float] = 0.25, abbreviated_name: Optional[str] = None,
reward_condition: Optional[Callable[[], bool]] = None):
"""
:param name_prefix: the name prefix of the specific instance of the PartVelocityReward;
the complete reward name is name_prefix + "part_velocity_reward"
:param max_linear_velocity: the maximum linear velocity to use for normalizing the (unscaled)
reward to lie in [-1, 0]; the reward is clipped at -1 if the sum of
linear and angular velocity is higher than max_linear_velocity +
min_linear_velocity
:param max_angular_velocity: the maximum angular velocity to use for normalizing the (unscaled)
reward to lie in [-1, 0]
:param intermediate_timestep_reward_scale: scaling factor (applied to the reward at every step in which the gym
environment does not terminate)
:param final_timestep_reward_scale: scaling factor (applied to the reward at the step in which the gym
environment terminates)
:param abbreviated_name: an abbreviation of the name of the reward that is displayed with the
value of the reward at the end of each episode (by the gym
environment)
:param reward_condition: a custom condition that specifies if the reward is active (i.e. the
reward is only calculated if reward_condition() is True, otherwise
the calculate_reward() returns 0)
"""
super().__init__(name_prefix + "_part_velocity_reward", intermediate_timestep_reward_scale,
final_timestep_reward_scale, clip=True, abbreviated_name=abbreviated_name,
reward_condition=reward_condition)
self.__distance_measure = distances.ssd_log_distance
self.__max_cost_per_part = max_linear_velocity + max_angular_velocity
def _calculate_reward_unnormalized(self) -> float:
velocities = np.array([part.scene_object.get_velocity() for part in self._get_parts()])
linear_velocities = np.linalg.norm(velocities[:, 0], axis=-1)
angular_velocities = np.linalg.norm(velocities[:, 1], axis=-1)
average_linear_velocity = np.mean(linear_velocities)
average_angular_velocity = np.mean(angular_velocities)
cost = average_linear_velocity + average_angular_velocity
return -cost
def _get_min_reward_unnormalized(self) -> float:
return -self.__max_cost_per_part * len(self._get_parts())
|
[
"numpy.mean",
"numpy.linalg.norm"
] |
[((3156, 3197), 'numpy.linalg.norm', 'np.linalg.norm', (['velocities[:, 0]'], {'axis': '(-1)'}), '(velocities[:, 0], axis=-1)\n', (3170, 3197), True, 'import numpy as np\n'), ((3227, 3268), 'numpy.linalg.norm', 'np.linalg.norm', (['velocities[:, 1]'], {'axis': '(-1)'}), '(velocities[:, 1], axis=-1)\n', (3241, 3268), True, 'import numpy as np\n'), ((3303, 3329), 'numpy.mean', 'np.mean', (['linear_velocities'], {}), '(linear_velocities)\n', (3310, 3329), True, 'import numpy as np\n'), ((3365, 3392), 'numpy.mean', 'np.mean', (['angular_velocities'], {}), '(angular_velocities)\n', (3372, 3392), True, 'import numpy as np\n')]
|
import platform
import cv2
import timeit
import argparse
import os
import sys
import multiprocessing as mp
import geopandas
mp.set_start_method('spawn', force=True)
import utils.dataframe
import numpy as np
from utils import raster_processing, to_agol, features, dataframe
import rasterio.warp
import rasterio.crs
import torch
#import ray
from collections import defaultdict
from os import makedirs, path
from pathlib import Path
from torch.utils.data import DataLoader
from skimage.morphology import square, dilation
from tqdm import tqdm
from dataset import XViewDataset
from models import XViewFirstPlaceLocModel, XViewFirstPlaceClsModel
from loguru import logger
from osgeo import gdal
import shapely
class Options(object):
def __init__(self, pre_path='input/pre', post_path='input/post',
out_loc_path='output/loc', out_dmg_path='output/dmg', out_overlay_path='output/over',
model_config='configs/model.yaml', model_weights='weights/weight.pth',
geo_profile=None, use_gpu=False, vis=False):
self.in_pre_path = pre_path
self.in_post_path = post_path
self.out_loc_path = out_loc_path
self.out_cls_path = out_dmg_path
self.out_overlay_path = out_overlay_path
self.model_config_path = model_config
self.model_weight_path = model_weights
self.geo_profile = geo_profile
self.is_use_gpu = use_gpu
self.is_vis = vis
class Files(object):
def __init__(self, ident, pre_directory, post_directory, output_directory, pre, post):
self.ident = ident
self.pre = pre_directory.joinpath(pre).resolve()
self.post = post_directory.joinpath(post).resolve()
self.loc = output_directory.joinpath('loc').joinpath(f'{self.ident}.tif').resolve()
self.dmg = output_directory.joinpath('dmg').joinpath(f'{self.ident}.tif').resolve()
self.over = output_directory.joinpath('over').joinpath(f'{self.ident}.tif').resolve()
self.profile = self.get_profile()
self.transform = self.profile["transform"]
self.opts = Options(pre_path=self.pre,
post_path=self.post,
out_loc_path=self.loc,
out_dmg_path=self.dmg,
out_overlay_path=self.over,
geo_profile=self.profile,
vis=True,
use_gpu=True
)
def get_profile(self):
with rasterio.open(self.pre) as src:
return src.profile
def make_output_structure(output_path):
"""
Creates directory structure for outputs.
:param output_path: Output path
:return: True if succussful
"""
Path(f"{output_path}/mosaics").mkdir(parents=True, exist_ok=True)
Path(f"{output_path}/chips/pre").mkdir(parents=True, exist_ok=True)
Path(f"{output_path}/chips/post").mkdir(parents=True, exist_ok=True)
Path(f"{output_path}/loc").mkdir(parents=True, exist_ok=True)
Path(f"{output_path}/dmg").mkdir(parents=True, exist_ok=True)
Path(f"{output_path}/over").mkdir(parents=True, exist_ok=True)
Path(f"{output_path}/vector").mkdir(parents=True, exist_ok=True)
Path(f"{output_path}/vrt").mkdir(parents=True, exist_ok=True)
return True
def get_files(dirname, extensions=['.png', '.tif', '.jpg']):
"""
Gathers list of files for processing from path recursively.
:param dirname: path to parse
:param extensions: extensions to match
:return: list of files matching extensions
"""
dir_path = Path(dirname)
files = dir_path.glob('**/*')
match = [path.resolve() for path in files if path.suffix in extensions]
assert len(match) > 0, logger.critical(f'No image files found in {dir_path.resolve()}')
return match
def reproject_helper(args, raster_tuple, procnum, return_dict, resolution):
"""
Helper function for reprojection
"""
(pre_post, src_crs, raster_file) = raster_tuple
basename = raster_file.stem
dest_file = args.staging_directory.joinpath('pre').joinpath(f'{basename}.tif')
try:
return_dict[procnum] = (pre_post, raster_processing.reproject(raster_file, dest_file, src_crs, args.destination_crs, resolution))
except ValueError:
return None
def postprocess_and_write(result_dict):
"""
Postprocess results from inference and write results to file
:param result_dict: dictionary containing all required opts for each example
"""
_thr = [0.38, 0.13, 0.14]
pred_coefs = [1.0] * 4 # not 12, b/c already took mean over 3 in each subset
loc_coefs = [1.0] * 4
preds = []
_i = -1
for k,v in result_dict.items():
if 'cls' in k:
_i += 1
# Todo: I think the below can just be replaced by v['cls'] -- should check
msk = v['cls'].numpy()
preds.append(msk * pred_coefs[_i])
preds = np.asarray(preds).astype('float').sum(axis=0) / np.sum(pred_coefs) / 255
loc_preds = []
_i = -1
for k,v in result_dict.items():
if 'loc' in k:
_i += 1
msk = v['loc'].numpy()
loc_preds.append(msk * loc_coefs[_i])
loc_preds = np.asarray(loc_preds).astype('float').sum(axis=0) / np.sum(loc_coefs) / 255
msk_dmg = preds[..., 1:].argmax(axis=2) + 1
msk_loc = (1 * ((loc_preds > _thr[0]) | ((loc_preds > _thr[1]) & (msk_dmg > 1) & (msk_dmg < 4)) | ((loc_preds > _thr[2]) & (msk_dmg > 1)))).astype('uint8')
msk_dmg = msk_dmg * msk_loc
_msk = (msk_dmg == 2)
if _msk.sum() > 0:
_msk = dilation(_msk, square(5))
msk_dmg[_msk & msk_dmg == 1] = 2
msk_dmg = msk_dmg.astype('uint8')
loc = msk_loc
cls = msk_dmg
sample_result_dict = result_dict['34loc']
sample_result_dict['geo_profile'].update(dtype=rasterio.uint8)
dst = rasterio.open(sample_result_dict['out_loc_path'], 'w', **sample_result_dict['geo_profile'])
dst.write(loc, 1)
dst.close()
dst = rasterio.open(sample_result_dict['out_cls_path'], 'w', **sample_result_dict['geo_profile'])
dst.write(cls, 1)
dst.close()
if sample_result_dict['is_vis']:
raster_processing.create_composite(sample_result_dict['in_pre_path'],
cls,
sample_result_dict['out_overlay_path'],
sample_result_dict['geo_profile'],
)
def run_inference(loader, model_wrapper, write_output=False, mode='loc', return_dict=None):
results = defaultdict(list)
with torch.no_grad(): # This is really important to not explode memory with gradients!
for ii, result_dict in tqdm(enumerate(loader), total=len(loader)):
#print(result_dict['in_pre_path'])
debug=False
#if '116' in result_dict['in_pre_path'][0]:
# import ipdb; ipdb.set_trace()
# debug=True
out = model_wrapper.forward(result_dict['img'],debug=debug)
# Save prediction tensors for testing
# Todo: Create argument for turning on debug/trace/test data
# pred_path = Path('/home/ubuntu/debug/output/preds')
# makedirs(pred_path, exist_ok=True)
# torch.save(out, pred_path / f'preds_{mode}_{ii}.pt')
out = out.detach().cpu()
del result_dict['img']
if 'pre_image' in result_dict:
result_dict['pre_image'] = result_dict['pre_image'].cpu().numpy()
if 'post_img' in result_dict:
result_dict['post_image'] = result_dict['post_image'].cpu().numpy()
if mode == 'loc':
result_dict['loc'] = out
elif mode == 'cls':
result_dict['cls'] = out
else:
raise ValueError('Incorrect mode -- must be loc or cls')
# Do this one separately because you can't return a class from a dataloader
result_dict['geo_profile'] = [loader.dataset.pairs[idx].opts.geo_profile
for idx in result_dict['idx']]
for k,v in result_dict.items():
results[k] = results[k] + list(v)
# Making a list
results_list = [dict(zip(results,t)) for t in zip(*results.values())]
if write_output:
pred_folder = args.output_directory / 'preds'
logger.info('Writing results...')
makedirs(pred_folder, exist_ok=True)
for result in tqdm(results_list, total=len(results_list)):
# TODO: Multithread this to make it more efficient/maybe eliminate it from workflow
if mode == 'loc':
cv2.imwrite(path.join(pred_folder,
result['in_pre_path'].split('/')[-1].replace('.tif', '_part1.png')),
np.array(result['loc'])[...],
[cv2.IMWRITE_PNG_COMPRESSION, 9])
elif mode == 'cls':
cv2.imwrite(path.join(pred_folder, result['in_pre_path'].split('/')[-1].replace('.tif', '_part1.png')),
np.array(result['cls'])[..., :3], [cv2.IMWRITE_PNG_COMPRESSION, 9])
cv2.imwrite(path.join(pred_folder, result['in_pre_path'].split('/')[-1].replace('.tif', '_part2.png')),
np.array(result['cls'])[..., 2:], [cv2.IMWRITE_PNG_COMPRESSION, 9])
if return_dict is None:
return results_list
else:
return_dict[f'{model_wrapper.model_size}{mode}'] = results_list
def check_data(images):
"""
Check that our image pairs contain useful data. Note: This only check the first band of each file.
:param images: Images to check for data
:return: True if both images contain useful data. False if either contains no useful date.
"""
for image in images:
with rasterio.open(image) as src:
layer = src.read(1)
if layer.sum() == 0:
return False
return True
def parse_args():
parser = argparse.ArgumentParser(description='Create arguments for xView 2 handler.')
parser.add_argument('--pre_directory', metavar='/path/to/pre/files/', type=Path, required=True, help='Directory containing pre-disaster imagery. This is searched recursively.')
parser.add_argument('--post_directory', metavar='/path/to/post/files/', type=Path, required=True, help='Directory containing post-disaster imagery. This is searched recursively.')
parser.add_argument('--output_directory', metavar='/path/to/output/', type=Path, required=True, help='Directory to store output files. This will be created if it does not exist. Existing files may be overwritten.')
parser.add_argument('--n_procs', default=4, help="Number of processors for multiprocessing", type=int)
parser.add_argument('--batch_size', default=16, help="Number of chips to run inference on at once", type=int)
parser.add_argument('--num_workers', default=8, help="Number of workers loading data into RAM. Recommend 4 * num_gpu", type=int)
parser.add_argument('--pre_crs', help='The Coordinate Reference System (CRS) for the pre-disaster imagery. This will only be utilized if images lack CRS data. May be WKT, EPSG (ex. "EPSG:4326"), or PROJ string.')
parser.add_argument('--post_crs', help='The Coordinate Reference System (CRS) for the post-disaster imagery. This will only be utilized if images lack CRS data. May be WKT, EPSG (ex. "EPSG:4326"), or PROJ string.')
parser.add_argument('--destination_crs', default=None, help='The Coordinate Reference System (CRS) for the output overlays. May be WKT, EPSG (ex. "EPSG:4326"), or PROJ string. Leave blank to calculate the approriate UTM zone.') # Todo: Create warning/force change when not using a CRS that utilizes meters for base units
parser.add_argument('--dp_mode', default=False, action='store_true', help='Run models serially, but using DataParallel')
parser.add_argument('--output_resolution', default=None, help='Override minimum resolution calculator. This should be a lower resolution (higher number) than source imagery for decreased inference time. Must be in units of destinationCRS.')
parser.add_argument('--save_intermediates', default=False, action='store_true', help='Store intermediate runfiles')
parser.add_argument('--aoi_file', default=None, help='Shapefile or GeoJSON file of AOI polygons')
parser.add_argument('--agol_user', default=None, help='ArcGIS online username')
parser.add_argument('--agol_password', default=None, help='ArcGIS online password')
parser.add_argument('--agol_feature_service', default=None, help='ArcGIS online feature service to append damage polygons.')
return parser.parse_args()
@logger.catch()
def main():
t0 = timeit.default_timer()
# Determine if items are being pushed to AGOL
agol_push = to_agol.agol_arg_check(args.agol_user, args.agol_password, args.agol_feature_service)
# Make file structure
make_output_structure(args.output_directory)
# Create input CRS objects from our pre/post inputs
if args.pre_crs:
args.pre_crs = rasterio.crs.CRS.from_string(args.pre_crs)
if args.post_crs:
args.post_crs = rasterio.crs.CRS.from_string(args.post_crs)
# Retrieve files form input directories
logger.info('Retrieving files...')
pre_files = get_files(args.pre_directory)
logger.debug(f'Retrieved {len(pre_files)} pre files from {args.pre_directory}')
post_files = get_files(args.post_directory)
logger.debug(f'Retrieved {len(post_files)} pre files from {args.post_directory}')
# Create VRTs
# Todo: Why are we doing this?
pre_vrt = raster_processing.create_vrt(pre_files, args.output_directory.joinpath('vrt/pre_vrt.vrt'))
post_vrt = raster_processing.create_vrt(post_files, args.output_directory.joinpath('vrt/post_vrt.vrt'))
# Create geopandas dataframes of raster footprints
# Todo: make sure we have valid rasters before proceeding
pre_df = utils.dataframe.make_footprint_df(pre_files)
post_df = utils.dataframe.make_footprint_df(post_files)
# Create destination CRS object from argument, else determine UTM zone and create CRS object
dest_crs = utils.dataframe.get_utm(pre_df)
logger.info(f'Calculated CRS: {dest_crs}')
if args.destination_crs:
args.destination_crs = rasterio.crs.CRS.from_string(args.destination_crs)
logger.info(f'Calculated CRS overridden by passed argument: {args.destination_crs}')
else:
args.destination_crs = dest_crs
# Ensure CRS is projected. This prevents a lot of problems downstream.
assert args.destination_crs.is_projected, logger.critical('CRS is not projected. Please use a projected CRS')
# Process DF
pre_df = utils.dataframe.process_df(pre_df, args.destination_crs)
post_df = utils.dataframe.process_df(post_df, args.destination_crs)
# Get AOI files and calculate intersect
if args.aoi_file:
aoi_df = dataframe.make_aoi_df(args.aoi_file)
else:
aoi_df = None
extent = utils.dataframe.get_intersect(pre_df, post_df, args, aoi_df)
logger.info(f'Calculated extent: {extent}')
# Calculate destination resolution
res = dataframe.get_max_res(pre_df, post_df)
logger.info(f'Calculated resolution: {res}')
if args.output_resolution:
res = (args.output_resolution, args.output_resolution)
logger.info(f'Calculated resolution overridden by passed argument: {res}')
logger.info("Creating pre mosaic...")
pre_mosaic = raster_processing.create_mosaic(
[str(file) for file in pre_df.filename],
Path(f"{args.output_directory}/mosaics/pre.tif"),
pre_df.crs,
args.destination_crs,
extent,
res,
aoi_df
)
logger.info("Creating post mosaic...")
post_mosaic = raster_processing.create_mosaic(
[str(file) for file in post_df.filename],
Path(f"{args.output_directory}/mosaics/post.tif"),
post_df.crs,
args.destination_crs,
extent,
res,
aoi_df
)
logger.info('Chipping...')
pre_chips = raster_processing.create_chips(pre_mosaic, args.output_directory.joinpath('chips').joinpath('pre'), extent)
logger.debug(f'Num pre chips: {len(pre_chips)}')
post_chips = raster_processing.create_chips(post_mosaic, args.output_directory.joinpath('chips').joinpath('post'), extent)
logger.debug(f'Num post chips: {len(post_chips)}')
assert len(pre_chips) == len(post_chips), logger.error('Chip numbers mismatch')
# Defining dataset and dataloader
pairs = []
for idx, (pre, post) in enumerate(zip(pre_chips, post_chips)):
if not check_data([pre, post]):
continue
pairs.append(Files(
pre.stem,
args.pre_directory,
args.post_directory,
args.output_directory,
pre,
post)
)
eval_loc_dataset = XViewDataset(pairs, 'loc')
eval_loc_dataloader = DataLoader(eval_loc_dataset,
batch_size=args.batch_size,
num_workers=args.num_workers,
shuffle=False,
pin_memory=True)
eval_cls_dataset = XViewDataset(pairs, 'cls')
eval_cls_dataloader = DataLoader(eval_cls_dataset,
batch_size=args.batch_size,
num_workers=args.num_workers,
shuffle=False,
pin_memory=True)
# Todo: If on a one GPU machine (or other unsupported GPU count), force DP mode
if args.dp_mode:
results_dict = {}
for sz in ['34', '50', '92', '154']:
logger.info(f'Running models of size {sz}...')
return_dict = {}
loc_wrapper = XViewFirstPlaceLocModel(sz, dp_mode=args.dp_mode)
run_inference(eval_loc_dataloader,
loc_wrapper,
args.save_intermediates,
'loc',
return_dict)
del loc_wrapper
cls_wrapper = XViewFirstPlaceClsModel(sz, dp_mode=args.dp_mode)
run_inference(eval_cls_dataloader,
cls_wrapper,
args.save_intermediates,
'cls',
return_dict)
del cls_wrapper
results_dict.update({k:v for k,v in return_dict.items()})
# Todo: Make GPU partition for four GPU machines
elif torch.cuda.device_count() == 2:
# For 2-GPU machines [TESTED]
# Loading model
loc_gpus = {'34':[0,0,0],
'50':[1,1,1],
'92':[0,0,0],
'154':[1,1,1]}
cls_gpus = {'34':[1,1,1],
'50':[0,0,0],
'92':[1,1,1],
'154':[0,0,0]}
results_dict = {}
# Running inference
logger.info('Running inference...')
for sz in loc_gpus.keys():
logger.info(f'Running models of size {sz}...')
loc_wrapper = XViewFirstPlaceLocModel(sz, devices=loc_gpus[sz])
cls_wrapper = XViewFirstPlaceClsModel(sz, devices=cls_gpus[sz])
# Running inference
logger.info('Running inference...')
# Run inference in parallel processes
manager = mp.Manager()
return_dict = manager.dict()
jobs = []
# Launch multiprocessing jobs for different pytorch jobs
p1 = mp.Process(target=run_inference,
args=(eval_cls_dataloader,
cls_wrapper,
args.save_intermediates,
'cls',
return_dict))
p2 = mp.Process(target=run_inference,
args=(eval_loc_dataloader,
loc_wrapper,
args.save_intermediates,
'loc',
return_dict))
p1.start()
p2.start()
jobs.append(p1)
jobs.append(p2)
for proc in jobs:
proc.join()
results_dict.update({k:v for k,v in return_dict.items()})
elif torch.cuda.device_count() == 8:
# For 8-GPU machines
# TODO: Test!
# Loading model
loc_gpus = {'34':[0,0,0],
'50':[1,1,1],
'92':[2,2,2],
'154':[3,3,3]}
cls_gpus = {'34':[4,4,4],
'50':[5,5,5],
'92':[6,6,6],
'154':[7,7,7]}
results_dict = {}
# Run inference in parallel processes
manager = mp.Manager()
return_dict = manager.dict()
jobs = []
for sz in loc_gpus.keys():
logger.info(f'Adding jobs for size {sz}...')
loc_wrapper = XViewFirstPlaceLocModel(sz, devices=loc_gpus[sz])
cls_wrapper = XViewFirstPlaceClsModel(sz, devices=cls_gpus[sz])
# DEBUG
#run_inference(eval_loc_dataloader,
# loc_wrapper,
# True, # Don't write intermediate outputs
# 'loc',
# return_dict)
#import ipdb; ipdb.set_trace()
# Launch multiprocessing jobs for different pytorch jobs
jobs.append(mp.Process(target=run_inference,
args=(eval_cls_dataloader,
cls_wrapper,
args.save_intermediates, # Don't write intermediate outputs
'cls',
return_dict))
)
jobs.append(mp.Process(target=run_inference,
args=(eval_loc_dataloader,
loc_wrapper,
args.save_intermediates, # Don't write intermediate outputs
'loc',
return_dict))
)
logger.info('Running inference...')
for proc in jobs:
proc.start()
for proc in jobs:
proc.join()
results_dict.update({k:v for k,v in return_dict.items()})
else:
raise ValueError('Must use either 2 or 8 GPUs')
# Quick check to make sure the samples in cls and loc are in the same order
#assert(results_dict['34loc'][4]['in_pre_path'] == results_dict['34cls'][4]['in_pre_path'])
results_list = [{k:v[i] for k,v in results_dict.items()} for i in range(len(results_dict['34cls'])) ]
# Running postprocessing
p = mp.Pool(args.n_procs)
#postprocess_and_write(results_list[0])
f_p = postprocess_and_write
p.map(f_p, results_list)
# Create damage and overlay mosaics
logger.info("Creating damage mosaic")
dmg_path = Path(args.output_directory) / 'dmg'
damage_files = [x for x in get_files(dmg_path)]
damage_mosaic = raster_processing.create_mosaic(
[str(file) for file in damage_files],
Path(f'{args.output_directory}/mosaics/damage.tif'),
None,
None,
None,
res
)
logger.info("Creating overlay mosaic")
p = Path(args.output_directory) / "over"
overlay_files = [x for x in get_files(p)]
overlay_mosaic = raster_processing.create_mosaic(
[str(file) for file in overlay_files],
Path(f'{args.output_directory}/mosaics/overlay.tif'),
None,
None,
None,
res
)
# Get files for creating vector file and/or pushing to AGOL
logger.info("Generating vector data")
dmg_files = get_files(Path(args.output_directory) / 'dmg')
polygons = features.create_polys(dmg_files)
polygons.geometry = polygons.geometry.simplify(1)
aoi = features.create_aoi_poly(polygons)
centroids = features.create_centroids(polygons)
centroids.crs = polygons.crs
logger.info(f'Polygons created: {len(polygons)}')
logger.info(f"AOI hull area: {aoi.geometry[0].area}")
# Create output file
logger.info('Writing output file')
vector_out = Path(args.output_directory).joinpath('vector') / 'damage.gpkg'
features.write_output(polygons, vector_out, layer='damage')
features.write_output(aoi, vector_out, 'aoi')
features.write_output(centroids, vector_out, 'centroids')
if agol_push:
try:
to_agol.agol_helper(args, polygons, aoi, centroids)
except Exception as e:
logger.warning(f'AGOL push failed. Error: {e}')
# Complete
elapsed = timeit.default_timer() - t0
logger.success(f'Run complete in {elapsed / 60:.3f} min')
def init():
# Todo: Fix this global at some point
global args
args = parse_args()
# Configure our logger and push our inputs
# Todo: Capture sys info (gpu, procs, etc)
logger.remove()
logger.configure(
handlers=[
dict(sink=sys.stderr, format="[{level}] {message}", level='INFO'),
dict(sink=args.output_directory / 'log'/ f'xv2.log', enqueue=True, level='DEBUG', backtrace=True),
],
)
logger.opt(exception=True)
# Scrub args of AGOL username and password and log them for debugging
clean_args = {k:v for (k,v) in args.__dict__.items() if k != 'agol_password' if k != 'agol_user'}
logger.debug(f'Run from:{__file__}')
for k, v in clean_args.items():
logger.debug(f'{k}: {v}')
# Add system info to log
logger.debug(f'System: {platform.platform()}')
logger.debug(f'Python: {sys.version}')
logger.debug(f'Torch: {torch.__version__}')
logger.debug(f'GDAL: {gdal.__version__}')
logger.debug(f'Rasterio: {rasterio.__version__}')
logger.debug(f'Shapely: {shapely.__version__}')
# Log CUDA device info
cuda_dev_num = torch.cuda.device_count()
logger.debug(f'CUDA devices avail: {cuda_dev_num}')
for i in range(0, cuda_dev_num):
logger.debug(f'CUDA properties for device {i}: {torch.cuda.get_device_properties(i)}')
if cuda_dev_num == 0:
raise ValueError('No GPU devices found. GPU required for inference.')
logger.info('Starting...')
if os.name == 'nt':
from multiprocessing import freeze_support
freeze_support()
main()
if __name__ == '__main__':
init()
|
[
"utils.features.create_aoi_poly",
"numpy.sum",
"argparse.ArgumentParser",
"models.XViewFirstPlaceClsModel",
"multiprocessing.set_start_method",
"utils.to_agol.agol_arg_check",
"torch.cuda.device_count",
"collections.defaultdict",
"pathlib.Path",
"utils.dataframe.make_aoi_df",
"loguru.logger.remove",
"utils.raster_processing.reproject",
"utils.features.create_centroids",
"torch.no_grad",
"utils.dataframe.get_max_res",
"torch.utils.data.DataLoader",
"utils.to_agol.agol_helper",
"loguru.logger.warning",
"loguru.logger.catch",
"utils.features.write_output",
"utils.raster_processing.create_composite",
"os.path.resolve",
"utils.features.create_polys",
"numpy.asarray",
"models.XViewFirstPlaceLocModel",
"loguru.logger.critical",
"skimage.morphology.square",
"loguru.logger.success",
"multiprocessing.Pool",
"dataset.XViewDataset",
"loguru.logger.debug",
"loguru.logger.opt",
"os.makedirs",
"loguru.logger.error",
"timeit.default_timer",
"multiprocessing.Manager",
"platform.platform",
"loguru.logger.info",
"torch.cuda.get_device_properties",
"numpy.array",
"multiprocessing.Process",
"multiprocessing.freeze_support"
] |
[((126, 166), 'multiprocessing.set_start_method', 'mp.set_start_method', (['"""spawn"""'], {'force': '(True)'}), "('spawn', force=True)\n", (145, 166), True, 'import multiprocessing as mp\n'), ((13038, 13052), 'loguru.logger.catch', 'logger.catch', ([], {}), '()\n', (13050, 13052), False, 'from loguru import logger\n'), ((3712, 3725), 'pathlib.Path', 'Path', (['dirname'], {}), '(dirname)\n', (3716, 3725), False, 'from pathlib import Path\n'), ((6778, 6795), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (6789, 6795), False, 'from collections import defaultdict\n'), ((10332, 10408), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Create arguments for xView 2 handler."""'}), "(description='Create arguments for xView 2 handler.')\n", (10355, 10408), False, 'import argparse\n'), ((13075, 13097), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (13095, 13097), False, 'import timeit\n'), ((13165, 13255), 'utils.to_agol.agol_arg_check', 'to_agol.agol_arg_check', (['args.agol_user', 'args.agol_password', 'args.agol_feature_service'], {}), '(args.agol_user, args.agol_password, args.\n agol_feature_service)\n', (13187, 13255), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((13610, 13644), 'loguru.logger.info', 'logger.info', (['"""Retrieving files..."""'], {}), "('Retrieving files...')\n", (13621, 13644), False, 'from loguru import logger\n'), ((14561, 14603), 'loguru.logger.info', 'logger.info', (['f"""Calculated CRS: {dest_crs}"""'], {}), "(f'Calculated CRS: {dest_crs}')\n", (14572, 14603), False, 'from loguru import logger\n'), ((14980, 15047), 'loguru.logger.critical', 'logger.critical', (['"""CRS is not projected. Please use a projected CRS"""'], {}), "('CRS is not projected. Please use a projected CRS')\n", (14995, 15047), False, 'from loguru import logger\n'), ((15439, 15482), 'loguru.logger.info', 'logger.info', (['f"""Calculated extent: {extent}"""'], {}), "(f'Calculated extent: {extent}')\n", (15450, 15482), False, 'from loguru import logger\n'), ((15533, 15571), 'utils.dataframe.get_max_res', 'dataframe.get_max_res', (['pre_df', 'post_df'], {}), '(pre_df, post_df)\n', (15554, 15571), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((15576, 15620), 'loguru.logger.info', 'logger.info', (['f"""Calculated resolution: {res}"""'], {}), "(f'Calculated resolution: {res}')\n", (15587, 15620), False, 'from loguru import logger\n'), ((15804, 15841), 'loguru.logger.info', 'logger.info', (['"""Creating pre mosaic..."""'], {}), "('Creating pre mosaic...')\n", (15815, 15841), False, 'from loguru import logger\n'), ((16104, 16142), 'loguru.logger.info', 'logger.info', (['"""Creating post mosaic..."""'], {}), "('Creating post mosaic...')\n", (16115, 16142), False, 'from loguru import logger\n'), ((16409, 16435), 'loguru.logger.info', 'logger.info', (['"""Chipping..."""'], {}), "('Chipping...')\n", (16420, 16435), False, 'from loguru import logger\n'), ((16842, 16879), 'loguru.logger.error', 'logger.error', (['"""Chip numbers mismatch"""'], {}), "('Chip numbers mismatch')\n", (16854, 16879), False, 'from loguru import logger\n'), ((17290, 17316), 'dataset.XViewDataset', 'XViewDataset', (['pairs', '"""loc"""'], {}), "(pairs, 'loc')\n", (17302, 17316), False, 'from dataset import XViewDataset\n'), ((17343, 17466), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_loc_dataset'], {'batch_size': 'args.batch_size', 'num_workers': 'args.num_workers', 'shuffle': '(False)', 'pin_memory': '(True)'}), '(eval_loc_dataset, batch_size=args.batch_size, num_workers=args.\n num_workers, shuffle=False, pin_memory=True)\n', (17353, 17466), False, 'from torch.utils.data import DataLoader\n'), ((17640, 17666), 'dataset.XViewDataset', 'XViewDataset', (['pairs', '"""cls"""'], {}), "(pairs, 'cls')\n", (17652, 17666), False, 'from dataset import XViewDataset\n'), ((17693, 17816), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_cls_dataset'], {'batch_size': 'args.batch_size', 'num_workers': 'args.num_workers', 'shuffle': '(False)', 'pin_memory': '(True)'}), '(eval_cls_dataset, batch_size=args.batch_size, num_workers=args.\n num_workers, shuffle=False, pin_memory=True)\n', (17703, 17816), False, 'from torch.utils.data import DataLoader\n'), ((23399, 23420), 'multiprocessing.Pool', 'mp.Pool', (['args.n_procs'], {}), '(args.n_procs)\n', (23406, 23420), True, 'import multiprocessing as mp\n'), ((23571, 23608), 'loguru.logger.info', 'logger.info', (['"""Creating damage mosaic"""'], {}), "('Creating damage mosaic')\n", (23582, 23608), False, 'from loguru import logger\n'), ((23937, 23975), 'loguru.logger.info', 'logger.info', (['"""Creating overlay mosaic"""'], {}), "('Creating overlay mosaic')\n", (23948, 23975), False, 'from loguru import logger\n'), ((24359, 24396), 'loguru.logger.info', 'logger.info', (['"""Generating vector data"""'], {}), "('Generating vector data')\n", (24370, 24396), False, 'from loguru import logger\n'), ((24475, 24507), 'utils.features.create_polys', 'features.create_polys', (['dmg_files'], {}), '(dmg_files)\n', (24496, 24507), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((24572, 24606), 'utils.features.create_aoi_poly', 'features.create_aoi_poly', (['polygons'], {}), '(polygons)\n', (24596, 24606), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((24623, 24658), 'utils.features.create_centroids', 'features.create_centroids', (['polygons'], {}), '(polygons)\n', (24648, 24658), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((24750, 24803), 'loguru.logger.info', 'logger.info', (['f"""AOI hull area: {aoi.geometry[0].area}"""'], {}), "(f'AOI hull area: {aoi.geometry[0].area}')\n", (24761, 24803), False, 'from loguru import logger\n'), ((24834, 24868), 'loguru.logger.info', 'logger.info', (['"""Writing output file"""'], {}), "('Writing output file')\n", (24845, 24868), False, 'from loguru import logger\n'), ((24953, 25012), 'utils.features.write_output', 'features.write_output', (['polygons', 'vector_out'], {'layer': '"""damage"""'}), "(polygons, vector_out, layer='damage')\n", (24974, 25012), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((25017, 25062), 'utils.features.write_output', 'features.write_output', (['aoi', 'vector_out', '"""aoi"""'], {}), "(aoi, vector_out, 'aoi')\n", (25038, 25062), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((25067, 25124), 'utils.features.write_output', 'features.write_output', (['centroids', 'vector_out', '"""centroids"""'], {}), "(centroids, vector_out, 'centroids')\n", (25088, 25124), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((25374, 25431), 'loguru.logger.success', 'logger.success', (['f"""Run complete in {elapsed / 60:.3f} min"""'], {}), "(f'Run complete in {elapsed / 60:.3f} min')\n", (25388, 25431), False, 'from loguru import logger\n'), ((25628, 25643), 'loguru.logger.remove', 'logger.remove', ([], {}), '()\n', (25641, 25643), False, 'from loguru import logger\n'), ((25896, 25922), 'loguru.logger.opt', 'logger.opt', ([], {'exception': '(True)'}), '(exception=True)\n', (25906, 25922), False, 'from loguru import logger\n'), ((26104, 26140), 'loguru.logger.debug', 'logger.debug', (['f"""Run from:{__file__}"""'], {}), "(f'Run from:{__file__}')\n", (26116, 26140), False, 'from loguru import logger\n'), ((26296, 26334), 'loguru.logger.debug', 'logger.debug', (['f"""Python: {sys.version}"""'], {}), "(f'Python: {sys.version}')\n", (26308, 26334), False, 'from loguru import logger\n'), ((26339, 26382), 'loguru.logger.debug', 'logger.debug', (['f"""Torch: {torch.__version__}"""'], {}), "(f'Torch: {torch.__version__}')\n", (26351, 26382), False, 'from loguru import logger\n'), ((26387, 26428), 'loguru.logger.debug', 'logger.debug', (['f"""GDAL: {gdal.__version__}"""'], {}), "(f'GDAL: {gdal.__version__}')\n", (26399, 26428), False, 'from loguru import logger\n'), ((26433, 26482), 'loguru.logger.debug', 'logger.debug', (['f"""Rasterio: {rasterio.__version__}"""'], {}), "(f'Rasterio: {rasterio.__version__}')\n", (26445, 26482), False, 'from loguru import logger\n'), ((26487, 26534), 'loguru.logger.debug', 'logger.debug', (['f"""Shapely: {shapely.__version__}"""'], {}), "(f'Shapely: {shapely.__version__}')\n", (26499, 26534), False, 'from loguru import logger\n'), ((26582, 26607), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (26605, 26607), False, 'import torch\n'), ((26612, 26663), 'loguru.logger.debug', 'logger.debug', (['f"""CUDA devices avail: {cuda_dev_num}"""'], {}), "(f'CUDA devices avail: {cuda_dev_num}')\n", (26624, 26663), False, 'from loguru import logger\n'), ((26906, 26932), 'loguru.logger.info', 'logger.info', (['"""Starting..."""'], {}), "('Starting...')\n", (26917, 26932), False, 'from loguru import logger\n'), ((3775, 3789), 'os.path.resolve', 'path.resolve', ([], {}), '()\n', (3787, 3789), False, 'from os import makedirs, path\n'), ((6346, 6499), 'utils.raster_processing.create_composite', 'raster_processing.create_composite', (["sample_result_dict['in_pre_path']", 'cls', "sample_result_dict['out_overlay_path']", "sample_result_dict['geo_profile']"], {}), "(sample_result_dict['in_pre_path'], cls,\n sample_result_dict['out_overlay_path'], sample_result_dict['geo_profile'])\n", (6380, 6499), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((6805, 6820), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6818, 6820), False, 'import torch\n'), ((8650, 8683), 'loguru.logger.info', 'logger.info', (['"""Writing results..."""'], {}), "('Writing results...')\n", (8661, 8683), False, 'from loguru import logger\n'), ((8692, 8728), 'os.makedirs', 'makedirs', (['pred_folder'], {'exist_ok': '(True)'}), '(pred_folder, exist_ok=True)\n', (8700, 8728), False, 'from os import makedirs, path\n'), ((14724, 14813), 'loguru.logger.info', 'logger.info', (['f"""Calculated CRS overridden by passed argument: {args.destination_crs}"""'], {}), "(\n f'Calculated CRS overridden by passed argument: {args.destination_crs}')\n", (14735, 14813), False, 'from loguru import logger\n'), ((15292, 15328), 'utils.dataframe.make_aoi_df', 'dataframe.make_aoi_df', (['args.aoi_file'], {}), '(args.aoi_file)\n', (15313, 15328), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((15724, 15798), 'loguru.logger.info', 'logger.info', (['f"""Calculated resolution overridden by passed argument: {res}"""'], {}), "(f'Calculated resolution overridden by passed argument: {res}')\n", (15735, 15798), False, 'from loguru import logger\n'), ((15949, 15997), 'pathlib.Path', 'Path', (['f"""{args.output_directory}/mosaics/pre.tif"""'], {}), "(f'{args.output_directory}/mosaics/pre.tif')\n", (15953, 15997), False, 'from pathlib import Path\n'), ((16252, 16301), 'pathlib.Path', 'Path', (['f"""{args.output_directory}/mosaics/post.tif"""'], {}), "(f'{args.output_directory}/mosaics/post.tif')\n", (16256, 16301), False, 'from pathlib import Path\n'), ((23624, 23651), 'pathlib.Path', 'Path', (['args.output_directory'], {}), '(args.output_directory)\n', (23628, 23651), False, 'from pathlib import Path\n'), ((23819, 23870), 'pathlib.Path', 'Path', (['f"""{args.output_directory}/mosaics/damage.tif"""'], {}), "(f'{args.output_directory}/mosaics/damage.tif')\n", (23823, 23870), False, 'from pathlib import Path\n'), ((23984, 24011), 'pathlib.Path', 'Path', (['args.output_directory'], {}), '(args.output_directory)\n', (23988, 24011), False, 'from pathlib import Path\n'), ((24176, 24228), 'pathlib.Path', 'Path', (['f"""{args.output_directory}/mosaics/overlay.tif"""'], {}), "(f'{args.output_directory}/mosaics/overlay.tif')\n", (24180, 24228), False, 'from pathlib import Path\n'), ((25342, 25364), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (25362, 25364), False, 'import timeit\n'), ((26185, 26210), 'loguru.logger.debug', 'logger.debug', (['f"""{k}: {v}"""'], {}), "(f'{k}: {v}')\n", (26197, 26210), False, 'from loguru import logger\n'), ((27017, 27033), 'multiprocessing.freeze_support', 'freeze_support', ([], {}), '()\n', (27031, 27033), False, 'from multiprocessing import freeze_support\n'), ((2867, 2897), 'pathlib.Path', 'Path', (['f"""{output_path}/mosaics"""'], {}), "(f'{output_path}/mosaics')\n", (2871, 2897), False, 'from pathlib import Path\n'), ((2937, 2969), 'pathlib.Path', 'Path', (['f"""{output_path}/chips/pre"""'], {}), "(f'{output_path}/chips/pre')\n", (2941, 2969), False, 'from pathlib import Path\n'), ((3009, 3042), 'pathlib.Path', 'Path', (['f"""{output_path}/chips/post"""'], {}), "(f'{output_path}/chips/post')\n", (3013, 3042), False, 'from pathlib import Path\n'), ((3082, 3108), 'pathlib.Path', 'Path', (['f"""{output_path}/loc"""'], {}), "(f'{output_path}/loc')\n", (3086, 3108), False, 'from pathlib import Path\n'), ((3148, 3174), 'pathlib.Path', 'Path', (['f"""{output_path}/dmg"""'], {}), "(f'{output_path}/dmg')\n", (3152, 3174), False, 'from pathlib import Path\n'), ((3214, 3241), 'pathlib.Path', 'Path', (['f"""{output_path}/over"""'], {}), "(f'{output_path}/over')\n", (3218, 3241), False, 'from pathlib import Path\n'), ((3281, 3310), 'pathlib.Path', 'Path', (['f"""{output_path}/vector"""'], {}), "(f'{output_path}/vector')\n", (3285, 3310), False, 'from pathlib import Path\n'), ((3350, 3376), 'pathlib.Path', 'Path', (['f"""{output_path}/vrt"""'], {}), "(f'{output_path}/vrt')\n", (3354, 3376), False, 'from pathlib import Path\n'), ((4298, 4397), 'utils.raster_processing.reproject', 'raster_processing.reproject', (['raster_file', 'dest_file', 'src_crs', 'args.destination_crs', 'resolution'], {}), '(raster_file, dest_file, src_crs, args.\n destination_crs, resolution)\n', (4325, 4397), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((5121, 5139), 'numpy.sum', 'np.sum', (['pred_coefs'], {}), '(pred_coefs)\n', (5127, 5139), True, 'import numpy as np\n'), ((5419, 5436), 'numpy.sum', 'np.sum', (['loc_coefs'], {}), '(loc_coefs)\n', (5425, 5436), True, 'import numpy as np\n'), ((5772, 5781), 'skimage.morphology.square', 'square', (['(5)'], {}), '(5)\n', (5778, 5781), False, 'from skimage.morphology import square, dilation\n'), ((18152, 18198), 'loguru.logger.info', 'logger.info', (['f"""Running models of size {sz}..."""'], {}), "(f'Running models of size {sz}...')\n", (18163, 18198), False, 'from loguru import logger\n'), ((18254, 18303), 'models.XViewFirstPlaceLocModel', 'XViewFirstPlaceLocModel', (['sz'], {'dp_mode': 'args.dp_mode'}), '(sz, dp_mode=args.dp_mode)\n', (18277, 18303), False, 'from models import XViewFirstPlaceLocModel, XViewFirstPlaceClsModel\n'), ((18594, 18643), 'models.XViewFirstPlaceClsModel', 'XViewFirstPlaceClsModel', (['sz'], {'dp_mode': 'args.dp_mode'}), '(sz, dp_mode=args.dp_mode)\n', (18617, 18643), False, 'from models import XViewFirstPlaceLocModel, XViewFirstPlaceClsModel\n'), ((19042, 19067), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (19065, 19067), False, 'import torch\n'), ((19476, 19511), 'loguru.logger.info', 'logger.info', (['"""Running inference..."""'], {}), "('Running inference...')\n", (19487, 19511), False, 'from loguru import logger\n'), ((24423, 24450), 'pathlib.Path', 'Path', (['args.output_directory'], {}), '(args.output_directory)\n', (24427, 24450), False, 'from pathlib import Path\n'), ((25169, 25220), 'utils.to_agol.agol_helper', 'to_agol.agol_helper', (['args', 'polygons', 'aoi', 'centroids'], {}), '(args, polygons, aoi, centroids)\n', (25188, 25220), False, 'from utils import raster_processing, to_agol, features, dataframe\n'), ((19560, 19606), 'loguru.logger.info', 'logger.info', (['f"""Running models of size {sz}..."""'], {}), "(f'Running models of size {sz}...')\n", (19571, 19606), False, 'from loguru import logger\n'), ((19633, 19682), 'models.XViewFirstPlaceLocModel', 'XViewFirstPlaceLocModel', (['sz'], {'devices': 'loc_gpus[sz]'}), '(sz, devices=loc_gpus[sz])\n', (19656, 19682), False, 'from models import XViewFirstPlaceLocModel, XViewFirstPlaceClsModel\n'), ((19709, 19758), 'models.XViewFirstPlaceClsModel', 'XViewFirstPlaceClsModel', (['sz'], {'devices': 'cls_gpus[sz]'}), '(sz, devices=cls_gpus[sz])\n', (19732, 19758), False, 'from models import XViewFirstPlaceLocModel, XViewFirstPlaceClsModel\n'), ((19804, 19839), 'loguru.logger.info', 'logger.info', (['"""Running inference..."""'], {}), "('Running inference...')\n", (19815, 19839), False, 'from loguru import logger\n'), ((19913, 19925), 'multiprocessing.Manager', 'mp.Manager', ([], {}), '()\n', (19923, 19925), True, 'import multiprocessing as mp\n'), ((20076, 20198), 'multiprocessing.Process', 'mp.Process', ([], {'target': 'run_inference', 'args': "(eval_cls_dataloader, cls_wrapper, args.save_intermediates, 'cls', return_dict)"}), "(target=run_inference, args=(eval_cls_dataloader, cls_wrapper,\n args.save_intermediates, 'cls', return_dict))\n", (20086, 20198), True, 'import multiprocessing as mp\n'), ((20368, 20490), 'multiprocessing.Process', 'mp.Process', ([], {'target': 'run_inference', 'args': "(eval_loc_dataloader, loc_wrapper, args.save_intermediates, 'loc', return_dict)"}), "(target=run_inference, args=(eval_loc_dataloader, loc_wrapper,\n args.save_intermediates, 'loc', return_dict))\n", (20378, 20490), True, 'import multiprocessing as mp\n'), ((20884, 20909), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (20907, 20909), False, 'import torch\n'), ((21359, 21371), 'multiprocessing.Manager', 'mp.Manager', ([], {}), '()\n', (21369, 21371), True, 'import multiprocessing as mp\n'), ((22798, 22833), 'loguru.logger.info', 'logger.info', (['"""Running inference..."""'], {}), "('Running inference...')\n", (22809, 22833), False, 'from loguru import logger\n'), ((24886, 24913), 'pathlib.Path', 'Path', (['args.output_directory'], {}), '(args.output_directory)\n', (24890, 24913), False, 'from pathlib import Path\n'), ((25264, 25311), 'loguru.logger.warning', 'logger.warning', (['f"""AGOL push failed. Error: {e}"""'], {}), "(f'AGOL push failed. Error: {e}')\n", (25278, 25311), False, 'from loguru import logger\n'), ((26269, 26288), 'platform.platform', 'platform.platform', ([], {}), '()\n', (26286, 26288), False, 'import platform\n'), ((21475, 21519), 'loguru.logger.info', 'logger.info', (['f"""Adding jobs for size {sz}..."""'], {}), "(f'Adding jobs for size {sz}...')\n", (21486, 21519), False, 'from loguru import logger\n'), ((21546, 21595), 'models.XViewFirstPlaceLocModel', 'XViewFirstPlaceLocModel', (['sz'], {'devices': 'loc_gpus[sz]'}), '(sz, devices=loc_gpus[sz])\n', (21569, 21595), False, 'from models import XViewFirstPlaceLocModel, XViewFirstPlaceClsModel\n'), ((21622, 21671), 'models.XViewFirstPlaceClsModel', 'XViewFirstPlaceClsModel', (['sz'], {'devices': 'cls_gpus[sz]'}), '(sz, devices=cls_gpus[sz])\n', (21645, 21671), False, 'from models import XViewFirstPlaceLocModel, XViewFirstPlaceClsModel\n'), ((26757, 26792), 'torch.cuda.get_device_properties', 'torch.cuda.get_device_properties', (['i'], {}), '(i)\n', (26789, 26792), False, 'import torch\n'), ((9112, 9135), 'numpy.array', 'np.array', (["result['loc']"], {}), "(result['loc'])\n", (9120, 9135), True, 'import numpy as np\n'), ((22085, 22207), 'multiprocessing.Process', 'mp.Process', ([], {'target': 'run_inference', 'args': "(eval_cls_dataloader, cls_wrapper, args.save_intermediates, 'cls', return_dict)"}), "(target=run_inference, args=(eval_cls_dataloader, cls_wrapper,\n args.save_intermediates, 'cls', return_dict))\n", (22095, 22207), True, 'import multiprocessing as mp\n'), ((22449, 22571), 'multiprocessing.Process', 'mp.Process', ([], {'target': 'run_inference', 'args': "(eval_loc_dataloader, loc_wrapper, args.save_intermediates, 'loc', return_dict)"}), "(target=run_inference, args=(eval_loc_dataloader, loc_wrapper,\n args.save_intermediates, 'loc', return_dict))\n", (22459, 22571), True, 'import multiprocessing as mp\n'), ((5073, 5090), 'numpy.asarray', 'np.asarray', (['preds'], {}), '(preds)\n', (5083, 5090), True, 'import numpy as np\n'), ((5367, 5388), 'numpy.asarray', 'np.asarray', (['loc_preds'], {}), '(loc_preds)\n', (5377, 5388), True, 'import numpy as np\n'), ((9402, 9425), 'numpy.array', 'np.array', (["result['cls']"], {}), "(result['cls'])\n", (9410, 9425), True, 'import numpy as np\n'), ((9628, 9651), 'numpy.array', 'np.array', (["result['cls']"], {}), "(result['cls'])\n", (9636, 9651), True, 'import numpy as np\n')]
|
# -*- encoding=utf-8 -*-
# Took and modified the BaseCamera class, and changed the Camera Class
# Original Source: https://blog.miguelgrinberg.com/post/flask-video-streaming-revisited
# Original Code Repository: https://github.com/miguelgrinberg/flask-video-streaming
# Modified a little bit in inference method from face mask detection repository
# Code of inference: https://github.com/AIZOOTech/FaceMaskDetection
import io
import cv2
import time
import uuid
import gridfs
import config
import numpy as np
from smtplib import SMTP
from datetime import datetime
from threading import Thread, Timer
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from model.load_model import tf_inference
from email.mime.multipart import MIMEMultipart
from model.utils import decode_bbox, single_class_non_max_suppression
ALERT_TRIGGER = dict() # Used for fixing a time period to the alert
class BaseCamera(object):
threads = dict() # background thread that reads frames from camera
frames = dict() # current frame is stored here by background thread
sources = dict()
def __init__(self, _id, source):
"""Start the background camera thread if it isn't running yet."""
self._id = str(_id)
self.sources[self._id] = source
if BaseCamera.threads.get(self._id) is None:
# start background frame thread
BaseCamera.threads[self._id] = Thread(
target=self._thread,
args=(self._id, self.sources[self._id])
)
BaseCamera.threads[self._id].start()
# wait until frames are available
while self.get_frame() is None:
time.sleep(0)
def get_frame(self):
"""Return the current camera frame."""
try:
return BaseCamera.frames[self._id]
except:
return None
@staticmethod
def _frames(_id, source):
""""Generator that returns frames from the camera."""
raise RuntimeError('Must be implemented by subclasses.')
@classmethod
def _thread(cls, _id, source):
"""Camera background thread."""
print('Starting camera thread.')
frames_iterator = cls._frames(_id, source)
for frame in frames_iterator:
BaseCamera.frames[_id] = frame
time.sleep(0)
class Camera(BaseCamera):
def __init__(self, _id):
cam = config.db['cameras'].find_one({'_id': _id})
super(Camera, self).__init__(_id, cam['url'])
@staticmethod
def _frames(_id, source):
global ALERT_TRIGGER
camera = cv2.VideoCapture(source)
ALERT_TRIGGER[_id] = False
status = True
if camera.isOpened():
while status:
(status, img) = camera.read()
if status:
settings = config.db['settings'].find_one({"id": 0})
has_violation = inference(img,
settings['confidence'],
iou_thresh=0.5,
target_shape=(260, 260),
draw_result=True
)
jpg = cv2.imencode('.jpg', img)[1]
if has_violation and not ALERT_TRIGGER[_id]:
ALERT_TRIGGER[_id] = True
_trigger = Timer(settings['lock_duration'], trigger, args=(_id,))
_trigger.start()
_alert = Thread(target=alert, args=(jpg, _id))
_alert.start()
io_buf = io.BytesIO(jpg)
frame = io_buf.getvalue()
io_buf.close()
yield frame
def inference(image,
conf_thresh=0.5,
iou_thresh=0.4,
target_shape=(160, 160),
draw_result=True
):
'''
Main function of detection inference
:param image: 3D numpy array of image
:param conf_thresh: the min threshold of classification probabity.
:param iou_thresh: the IOU threshold of NMS
:param target_shape: the model input size.
:param draw_result: whether to daw bounding box to the image.
:param show_result: whether to display the image.
:return:
'''
has_violation = False
height, width, _ = image.shape
image_resized = cv2.resize(image, target_shape)
image_np = image_resized / 255.0
image_exp = np.expand_dims(image_np, axis=0)
y_bboxes_output, y_cls_output = tf_inference(
config.SESS, config.GRAPH, image_exp
)
# remove the batch dimension, for batch is always 1 for inference.
y_bboxes = decode_bbox(config.ANCHORS_EXP, y_bboxes_output)[0]
y_cls = y_cls_output[0]
# To speed up, do single class NMS, not multiple classes NMS.
bbox_max_scores = np.max(y_cls, axis=1)
bbox_max_score_classes = np.argmax(y_cls, axis=1)
# keep_idx is the alive bounding box after nms.
keep_idxs = single_class_non_max_suppression(y_bboxes,
bbox_max_scores,
conf_thresh=conf_thresh,
iou_thresh=iou_thresh,
)
for idx in keep_idxs:
conf = float(bbox_max_scores[idx])
class_id = bbox_max_score_classes[idx]
bbox = y_bboxes[idx]
# clip the coordinate, avoid the value exceed the image boundary.
xmin = max(0, int(bbox[0] * width))
ymin = max(0, int(bbox[1] * height))
xmax = min(int(bbox[2] * width), width)
ymax = min(int(bbox[3] * height), height)
if draw_result:
if class_id == 0:
color = (0, 255, 0)
else:
has_violation = True
color = (0, 0, 255)
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
cv2.putText(image, "%s: %.2f" % (config.ID2CLASS[class_id], conf),
(xmin + 2, ymin - 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.8,
color
)
return has_violation
def trigger(_id):
global ALERT_TRIGGER
ALERT_TRIGGER[_id] = False
def alert(image, _id):
cam = config.db['cameras'].find_one({'_id': uuid.UUID(_id)})
if cam['supervisor_id'] != -1:
sec = config.db['security'].find_one({
'_id': uuid.UUID(cam['supervisor_id'])
})
send_mail(sec, cam, image)
store_image(cam, image)
def send_mail(receiver, camera, image):
msg = MIMEMultipart()
msg['Subject'] = 'IDFMI Alert'
msg['From'] = config.EMAIL_ADDRESS
msg['To'] = receiver['email']
msg.attach(MIMEText(
f"""Dear Mr. {receiver['last_name']},
We have detected a violation on {camera['location']}.
You can find the violation picture attached with this email.
Please check the picture.
regards,
IDFMI Team"""
))
msg.attach(MIMEImage(image.tostring(), name="ViolationPic.jpg"))
smtp = SMTP(config.SMTP_SERVER, config.SMTP_PORT)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(config.EMAIL_ADDRESS, config.EMAIL_PASSWORD)
smtp.sendmail(config.EMAIL_ADDRESS, receiver['email'], msg.as_string())
smtp.quit()
def store_image(camera, image):
# searching for the location of the camera
roomName = camera['location']
fs = gridfs.GridFS(config.db) # gridFS instance
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # get time
# Converting the picture to bytes
io_buf = io.BytesIO(image)
frame = io_buf.getvalue()
io_buf.close()
fs.put(frame, date=now, room=roomName) # save image into DB.
|
[
"model.utils.decode_bbox",
"threading.Timer",
"numpy.argmax",
"email.mime.text.MIMEText",
"model.utils.single_class_non_max_suppression",
"cv2.rectangle",
"cv2.imencode",
"smtplib.SMTP",
"email.mime.multipart.MIMEMultipart",
"numpy.max",
"uuid.UUID",
"datetime.datetime.now",
"cv2.resize",
"threading.Thread",
"io.BytesIO",
"model.load_model.tf_inference",
"time.sleep",
"cv2.putText",
"numpy.expand_dims",
"cv2.VideoCapture",
"gridfs.GridFS"
] |
[((4487, 4518), 'cv2.resize', 'cv2.resize', (['image', 'target_shape'], {}), '(image, target_shape)\n', (4497, 4518), False, 'import cv2\n'), ((4572, 4604), 'numpy.expand_dims', 'np.expand_dims', (['image_np'], {'axis': '(0)'}), '(image_np, axis=0)\n', (4586, 4604), True, 'import numpy as np\n'), ((4641, 4691), 'model.load_model.tf_inference', 'tf_inference', (['config.SESS', 'config.GRAPH', 'image_exp'], {}), '(config.SESS, config.GRAPH, image_exp)\n', (4653, 4691), False, 'from model.load_model import tf_inference\n'), ((4965, 4986), 'numpy.max', 'np.max', (['y_cls'], {'axis': '(1)'}), '(y_cls, axis=1)\n', (4971, 4986), True, 'import numpy as np\n'), ((5016, 5040), 'numpy.argmax', 'np.argmax', (['y_cls'], {'axis': '(1)'}), '(y_cls, axis=1)\n', (5025, 5040), True, 'import numpy as np\n'), ((5110, 5222), 'model.utils.single_class_non_max_suppression', 'single_class_non_max_suppression', (['y_bboxes', 'bbox_max_scores'], {'conf_thresh': 'conf_thresh', 'iou_thresh': 'iou_thresh'}), '(y_bboxes, bbox_max_scores, conf_thresh=\n conf_thresh, iou_thresh=iou_thresh)\n', (5142, 5222), False, 'from model.utils import decode_bbox, single_class_non_max_suppression\n'), ((6888, 6903), 'email.mime.multipart.MIMEMultipart', 'MIMEMultipart', ([], {}), '()\n', (6901, 6903), False, 'from email.mime.multipart import MIMEMultipart\n'), ((7383, 7425), 'smtplib.SMTP', 'SMTP', (['config.SMTP_SERVER', 'config.SMTP_PORT'], {}), '(config.SMTP_SERVER, config.SMTP_PORT)\n', (7387, 7425), False, 'from smtplib import SMTP\n'), ((7754, 7778), 'gridfs.GridFS', 'gridfs.GridFS', (['config.db'], {}), '(config.db)\n', (7767, 7778), False, 'import gridfs\n'), ((7917, 7934), 'io.BytesIO', 'io.BytesIO', (['image'], {}), '(image)\n', (7927, 7934), False, 'import io\n'), ((2616, 2640), 'cv2.VideoCapture', 'cv2.VideoCapture', (['source'], {}), '(source)\n', (2632, 2640), False, 'import cv2\n'), ((4797, 4845), 'model.utils.decode_bbox', 'decode_bbox', (['config.ANCHORS_EXP', 'y_bboxes_output'], {}), '(config.ANCHORS_EXP, y_bboxes_output)\n', (4808, 4845), False, 'from model.utils import decode_bbox, single_class_non_max_suppression\n'), ((7027, 7292), 'email.mime.text.MIMEText', 'MIMEText', (['f"""Dear Mr. {receiver[\'last_name\']},\n\n We have detected a violation on {camera[\'location\']}. \n You can find the violation picture attached with this email. \n Please check the picture.\n\n regards,\n IDFMI Team"""'], {}), '(\n f"""Dear Mr. {receiver[\'last_name\']},\n\n We have detected a violation on {camera[\'location\']}. \n You can find the violation picture attached with this email. \n Please check the picture.\n\n regards,\n IDFMI Team"""\n )\n', (7035, 7292), False, 'from email.mime.text import MIMEText\n'), ((1421, 1489), 'threading.Thread', 'Thread', ([], {'target': 'self._thread', 'args': '(self._id, self.sources[self._id])'}), '(target=self._thread, args=(self._id, self.sources[self._id]))\n', (1427, 1489), False, 'from threading import Thread, Timer\n'), ((2338, 2351), 'time.sleep', 'time.sleep', (['(0)'], {}), '(0)\n', (2348, 2351), False, 'import time\n'), ((6017, 6075), 'cv2.rectangle', 'cv2.rectangle', (['image', '(xmin, ymin)', '(xmax, ymax)', 'color', '(2)'], {}), '(image, (xmin, ymin), (xmax, ymax), color, 2)\n', (6030, 6075), False, 'import cv2\n'), ((6088, 6219), 'cv2.putText', 'cv2.putText', (['image', "('%s: %.2f' % (config.ID2CLASS[class_id], conf))", '(xmin + 2, ymin - 2)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.8)', 'color'], {}), "(image, '%s: %.2f' % (config.ID2CLASS[class_id], conf), (xmin + \n 2, ymin - 2), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color)\n", (6099, 6219), False, 'import cv2\n'), ((6608, 6622), 'uuid.UUID', 'uuid.UUID', (['_id'], {}), '(_id)\n', (6617, 6622), False, 'import uuid\n'), ((7808, 7822), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (7820, 7822), False, 'from datetime import datetime\n'), ((1693, 1706), 'time.sleep', 'time.sleep', (['(0)'], {}), '(0)\n', (1703, 1706), False, 'import time\n'), ((6726, 6757), 'uuid.UUID', 'uuid.UUID', (["cam['supervisor_id']"], {}), "(cam['supervisor_id'])\n", (6735, 6757), False, 'import uuid\n'), ((3708, 3723), 'io.BytesIO', 'io.BytesIO', (['jpg'], {}), '(jpg)\n', (3718, 3723), False, 'import io\n'), ((3293, 3318), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'img'], {}), "('.jpg', img)\n", (3305, 3318), False, 'import cv2\n'), ((3472, 3526), 'threading.Timer', 'Timer', (["settings['lock_duration']", 'trigger'], {'args': '(_id,)'}), "(settings['lock_duration'], trigger, args=(_id,))\n", (3477, 3526), False, 'from threading import Thread, Timer\n'), ((3601, 3638), 'threading.Thread', 'Thread', ([], {'target': 'alert', 'args': '(jpg, _id)'}), '(target=alert, args=(jpg, _id))\n', (3607, 3638), False, 'from threading import Thread, Timer\n')]
|
from pathlib import Path
from typing import Iterable
from os.path import basename, splitext
import sys
from difflib import context_diff
import click
import numpy as np
from sadedegel.dataset._core import safe_json_load
from sadedegel.dataset import load_sentence_corpus, file_paths
def file_diff(i1: Iterable, i2: Iterable):
l1, l2 = list(i1), list(i2)
if len(l1) != len(l2):
click.secho(f"Iterable sizes are not equal {len(l1)} != {len(l2)}")
s1, s2 = set(l1), set(l2)
if len(s1) != len(s2):
click.secho(f"Set sizes are not equal {len(s1)} != {len(s2)}")
for e1 in list(s1):
if e1 not in s2:
click.secho(f"{e1} in I1 but not in I2")
for e2 in list(s2):
if e2 not in s1:
click.secho(f"{e2} in I2 but not in I1")
@click.command()
def cli():
sents = load_sentence_corpus(False)
fns = [splitext(basename(fp))[0] for fp in file_paths()]
reference = dict((fn, sent['sentences']) for fn, sent in zip(fns, sents))
for fn in fns:
anno_path = Path('sadedegel/work/Labeled') / f"{fn}_labeled.json"
if anno_path.exists():
anno = safe_json_load(anno_path)
anno_sents = [s['content'] for s in anno['sentences']]
_ = np.array([s['deletedInRound'] for s in anno['sentences']])
refe_sents = reference[fn]
if refe_sents != anno_sents:
click.secho(f"Mismatch in number of sentences for document {fn}", fg="red")
diff = context_diff(refe_sents, anno_sents)
click.secho('\n'.join(diff), fg="red")
sys.exit(1)
else:
click.secho(f"MATCH: {fn}", fg="green")
else:
click.secho(f"Annotated corpus member {anno_path} not found.", fg="red")
if __name__ == '__main__':
cli()
|
[
"sadedegel.dataset._core.safe_json_load",
"os.path.basename",
"sadedegel.dataset.load_sentence_corpus",
"click.command",
"difflib.context_diff",
"sadedegel.dataset.file_paths",
"pathlib.Path",
"numpy.array",
"click.secho",
"sys.exit"
] |
[((802, 817), 'click.command', 'click.command', ([], {}), '()\n', (815, 817), False, 'import click\n'), ((841, 868), 'sadedegel.dataset.load_sentence_corpus', 'load_sentence_corpus', (['(False)'], {}), '(False)\n', (861, 868), False, 'from sadedegel.dataset import load_sentence_corpus, file_paths\n'), ((655, 695), 'click.secho', 'click.secho', (['f"""{e1} in I1 but not in I2"""'], {}), "(f'{e1} in I1 but not in I2')\n", (666, 695), False, 'import click\n'), ((758, 798), 'click.secho', 'click.secho', (['f"""{e2} in I2 but not in I1"""'], {}), "(f'{e2} in I2 but not in I1')\n", (769, 798), False, 'import click\n'), ((917, 929), 'sadedegel.dataset.file_paths', 'file_paths', ([], {}), '()\n', (927, 929), False, 'from sadedegel.dataset import load_sentence_corpus, file_paths\n'), ((1050, 1080), 'pathlib.Path', 'Path', (['"""sadedegel/work/Labeled"""'], {}), "('sadedegel/work/Labeled')\n", (1054, 1080), False, 'from pathlib import Path\n'), ((1155, 1180), 'sadedegel.dataset._core.safe_json_load', 'safe_json_load', (['anno_path'], {}), '(anno_path)\n', (1169, 1180), False, 'from sadedegel.dataset._core import safe_json_load\n'), ((1265, 1323), 'numpy.array', 'np.array', (["[s['deletedInRound'] for s in anno['sentences']]"], {}), "([s['deletedInRound'] for s in anno['sentences']])\n", (1273, 1323), True, 'import numpy as np\n'), ((1745, 1817), 'click.secho', 'click.secho', (['f"""Annotated corpus member {anno_path} not found."""'], {'fg': '"""red"""'}), "(f'Annotated corpus member {anno_path} not found.', fg='red')\n", (1756, 1817), False, 'import click\n'), ((890, 902), 'os.path.basename', 'basename', (['fp'], {}), '(fp)\n', (898, 902), False, 'from os.path import basename, splitext\n'), ((1422, 1497), 'click.secho', 'click.secho', (['f"""Mismatch in number of sentences for document {fn}"""'], {'fg': '"""red"""'}), "(f'Mismatch in number of sentences for document {fn}', fg='red')\n", (1433, 1497), False, 'import click\n'), ((1522, 1558), 'difflib.context_diff', 'context_diff', (['refe_sents', 'anno_sents'], {}), '(refe_sents, anno_sents)\n', (1534, 1558), False, 'from difflib import context_diff\n'), ((1632, 1643), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1640, 1643), False, 'import sys\n'), ((1678, 1717), 'click.secho', 'click.secho', (['f"""MATCH: {fn}"""'], {'fg': '"""green"""'}), "(f'MATCH: {fn}', fg='green')\n", (1689, 1717), False, 'import click\n')]
|
import slidingwindow as sw
import numpy as np
import cv2
def splitAlphaMask(image):
"""
Splits the last channel of an image from the rest of the channels.
Useful for splitting away the alpha channel of an image and treating
it as the image mask.
The input image should be a NumPy array of shape [h,w,c].
The return value is a tuple of the image channels and the mask.
"""
channels = image[:, :, 0 : image.shape[2]-1]
mask = image[:, :, image.shape[2]-1]
return channels, mask
def isolatePixels(image, mask, maskValue):
"""
Creates a copy of the supplied image where all pixels whose mask
value does not match the specified value are set to zero.
"""
pixelsToIgnore = np.nonzero(mask != maskValue)
isolated = image.copy()
isolated[pixelsToIgnore] = 0
return isolated
def extractConnectedComponents(image, mask, ignoreZero = False, preciseBounds = False):
"""
Uses the OpenCV "connected components" algorithm to extract individual
image segments that are represented by contiguous areas of identical
values in the image mask.
The return value is a dictionary whose keys are the unique values in the
mask, and whose values are the list of bounds representing each of the
contiguous areas for each key.
If `preciseBounds` is False then each list item is a simple rectangle,
represented by tuple of (x,y,w,h).
If `preciseBounds` is True then each list item is a rotated rectangle,
represented by a tuple of (centre, size, rotation).
"""
# Create the dictionary to hold the mappings from mask value to list of bounds
instancesForValues = {}
# Iterate over each unique value in the mask
maskValues = np.unique(mask)
for maskValue in maskValues:
# If we have been asked to ignore mask value zero, do so
if maskValue == 0 and ignoreZero == True:
continue
# Zero-out the pixels for all of the other mask values
valueInstances = isolatePixels(mask, mask, maskValue)
# Use the "connected components" algorithm to extract the subsets for each contiguous area of the current mask value
ret, markers, stats, centroids = cv2.connectedComponentsWithStats(valueInstances)
# Add the bounds for each identified instance to our mappings
instancesForValues[maskValue] = []
instances = np.unique(markers)
for instance in instances:
# Ignore instance zero, which contains the entire image
if instance != 0:
# Determine if we are retrieving simple bounds or precise bounds for each instance
if preciseBounds == True:
# Compute the precise bounds of the instance
contiguous = np.ascontiguousarray(isolatePixels(mask, markers, instance), dtype=np.uint8)
_, contours, hierarchy = cv2.findContours(contiguous, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
instancesForValues[maskValue].append(cv2.minAreaRect(contours[0]))
else:
# Extract the simple bounds of the instance
x = stats[instance, cv2.CC_STAT_LEFT]
y = stats[instance, cv2.CC_STAT_TOP]
w = stats[instance, cv2.CC_STAT_WIDTH]
h = stats[instance, cv2.CC_STAT_HEIGHT]
instancesForValues[maskValue].append( (x,y,w,h) )
return instancesForValues
def extract(image, bounds):
"""
Extracts a subset of an image, given a tuple of (x,y,w,h).
"""
x,y,w,h = bounds
return sw.SlidingWindow(x, y, w, h, sw.DimOrder.HeightWidthChannel).apply(image)
|
[
"slidingwindow.SlidingWindow",
"numpy.unique",
"numpy.nonzero",
"cv2.connectedComponentsWithStats",
"cv2.minAreaRect",
"cv2.findContours"
] |
[((689, 718), 'numpy.nonzero', 'np.nonzero', (['(mask != maskValue)'], {}), '(mask != maskValue)\n', (699, 718), True, 'import numpy as np\n'), ((1646, 1661), 'numpy.unique', 'np.unique', (['mask'], {}), '(mask)\n', (1655, 1661), True, 'import numpy as np\n'), ((2085, 2133), 'cv2.connectedComponentsWithStats', 'cv2.connectedComponentsWithStats', (['valueInstances'], {}), '(valueInstances)\n', (2117, 2133), False, 'import cv2\n'), ((2252, 2270), 'numpy.unique', 'np.unique', (['markers'], {}), '(markers)\n', (2261, 2270), True, 'import numpy as np\n'), ((3285, 3345), 'slidingwindow.SlidingWindow', 'sw.SlidingWindow', (['x', 'y', 'w', 'h', 'sw.DimOrder.HeightWidthChannel'], {}), '(x, y, w, h, sw.DimOrder.HeightWidthChannel)\n', (3301, 3345), True, 'import slidingwindow as sw\n'), ((2687, 2757), 'cv2.findContours', 'cv2.findContours', (['contiguous', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_NONE'], {}), '(contiguous, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n', (2703, 2757), False, 'import cv2\n'), ((2800, 2828), 'cv2.minAreaRect', 'cv2.minAreaRect', (['contours[0]'], {}), '(contours[0])\n', (2815, 2828), False, 'import cv2\n')]
|
# Copyright 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Callable, List
import numpy as np
from sklearn.metrics import confusion_matrix
import torch
from torch import nn
class Deep(nn.Module):
def __init__(self, configuration_list: List[int], activation=None, is_cuda: bool = False):
super().__init__()
if activation is None:
activation = lambda x: x
_weights_list = []
_bias_list = []
for i in range(len(configuration_list) - 1):
weights_prototype = torch.tensor(np.zeros((configuration_list[i], configuration_list[i + 1])),
dtype=torch.float,
device="cuda" if is_cuda else None)
_weights_list.append(nn.Parameter(nn.init.xavier_normal_(weights_prototype), requires_grad=True))
_bias_list.append(nn.Parameter(torch.zeros(configuration_list[i + 1],
device="cuda" if is_cuda else None), requires_grad=True))
self._weights = nn.ParameterList(_weights_list)
self._biases = nn.ParameterList(_bias_list)
self._activation = activation
@property
def weights(self) -> nn.ParameterList:
return self._weights
@weights.setter
def weights(self, value):
self._weights = value
@property
def biases(self) -> nn.ParameterList:
return self._biases
@biases.setter
def biases(self, value):
self._biases = value
@property
def activation(self) -> Callable:
return self._activation
def forward(self, inputs) -> torch.Tensor:
for weights, bias in zip(self.weights, self.biases):
inputs = inputs.mm(weights) + bias
inputs = self.activation(inputs)
_probs = torch.softmax(inputs, dim=1)
return _probs
def get_loss(self, inputs, y_true) -> torch.Tensor:
# Shape: (inputs.length, output_units)
_outputs = self.forward(inputs)
# Add 1e-13 to prevent NaN
_logmul_outputs = torch.log(_outputs + 1e-13) * y_true
_logsum = torch.sum(_logmul_outputs, dim=1)
_logsum_mean = torch.mean(_logsum)
# Convert to positive number
return -_logsum_mean
def count_params(self):
name_and_dim_tuples = list()
for parameter in self.named_parameters():
name_and_dim_tuples.append((parameter[0], tuple(parameter[1].shape)))
total_parameters = np.sum(p.numel() for p in self.parameters())
return {"layers": name_and_dim_tuples, "element_count": total_parameters}
def train(model: nn.Module, x, y, n_epochs: int, learning_rate: float, verbose: int = 0):
optimizer = torch.optim.SGD(params=model.parameters(), lr=learning_rate, momentum=0.99)
for epoch in range(1, n_epochs + 1):
loss = model.get_loss(x, y)
loss.backward()
optimizer.step()
if verbose > 0:
print(f"Epoha {epoch}:\tgubitak = {loss:.06f}")
optimizer.zero_grad()
def eval(model, inputs):
return model.forward(inputs).detach().cpu().numpy()
def eval_metrics(model, inputs, y_real, prefix: str or None = None):
if prefix is None:
prefix = ""
y_pred = eval(model, inputs).argmax(axis=1)
y_real = y_real.detach().cpu().numpy()
cm = confusion_matrix(y_real, y_pred)
cm_diag = np.diag(cm)
sums = [np.sum(cm, axis=y) for y in [None, 0, 1]]
sums[0] = np.maximum(1, sums[0])
for i in range(1, len(sums)):
sums[i][sums[i] == 0] = 1
accuracy = np.sum(cm_diag) / sums[0]
precision, recall = [np.mean(cm_diag / x) for x in sums[1:]]
f1 = (2 * precision * recall) / (precision + recall)
return {f"{prefix}acc": accuracy, f"{prefix}pr": precision, f"{prefix}re": recall, f"{prefix}f1": f1}
|
[
"torch.mean",
"numpy.maximum",
"numpy.sum",
"torch.nn.init.xavier_normal_",
"numpy.zeros",
"torch.softmax",
"numpy.mean",
"torch.nn.ParameterList",
"torch.zeros",
"sklearn.metrics.confusion_matrix",
"torch.sum",
"torch.log",
"numpy.diag"
] |
[((3934, 3966), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_real', 'y_pred'], {}), '(y_real, y_pred)\n', (3950, 3966), False, 'from sklearn.metrics import confusion_matrix\n'), ((3981, 3992), 'numpy.diag', 'np.diag', (['cm'], {}), '(cm)\n', (3988, 3992), True, 'import numpy as np\n'), ((4063, 4085), 'numpy.maximum', 'np.maximum', (['(1)', 'sums[0]'], {}), '(1, sums[0])\n', (4073, 4085), True, 'import numpy as np\n'), ((1639, 1670), 'torch.nn.ParameterList', 'nn.ParameterList', (['_weights_list'], {}), '(_weights_list)\n', (1655, 1670), False, 'from torch import nn\n'), ((1694, 1722), 'torch.nn.ParameterList', 'nn.ParameterList', (['_bias_list'], {}), '(_bias_list)\n', (1710, 1722), False, 'from torch import nn\n'), ((2396, 2424), 'torch.softmax', 'torch.softmax', (['inputs'], {'dim': '(1)'}), '(inputs, dim=1)\n', (2409, 2424), False, 'import torch\n'), ((2709, 2742), 'torch.sum', 'torch.sum', (['_logmul_outputs'], {'dim': '(1)'}), '(_logmul_outputs, dim=1)\n', (2718, 2742), False, 'import torch\n'), ((2766, 2785), 'torch.mean', 'torch.mean', (['_logsum'], {}), '(_logsum)\n', (2776, 2785), False, 'import torch\n'), ((4006, 4024), 'numpy.sum', 'np.sum', (['cm'], {'axis': 'y'}), '(cm, axis=y)\n', (4012, 4024), True, 'import numpy as np\n'), ((4170, 4185), 'numpy.sum', 'np.sum', (['cm_diag'], {}), '(cm_diag)\n', (4176, 4185), True, 'import numpy as np\n'), ((4221, 4241), 'numpy.mean', 'np.mean', (['(cm_diag / x)'], {}), '(cm_diag / x)\n', (4228, 4241), True, 'import numpy as np\n'), ((2654, 2681), 'torch.log', 'torch.log', (['(_outputs + 1e-13)'], {}), '(_outputs + 1e-13)\n', (2663, 2681), False, 'import torch\n'), ((1101, 1161), 'numpy.zeros', 'np.zeros', (['(configuration_list[i], configuration_list[i + 1])'], {}), '((configuration_list[i], configuration_list[i + 1]))\n', (1109, 1161), True, 'import numpy as np\n'), ((1355, 1396), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['weights_prototype'], {}), '(weights_prototype)\n', (1377, 1396), False, 'from torch import nn\n'), ((1462, 1536), 'torch.zeros', 'torch.zeros', (['configuration_list[i + 1]'], {'device': "('cuda' if is_cuda else None)"}), "(configuration_list[i + 1], device='cuda' if is_cuda else None)\n", (1473, 1536), False, 'import torch\n')]
|
'''
Copyright 2022 Airbus SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import math
import numpy as np
import pandas as pd
from os.path import join, dirname
from copy import deepcopy
from climateeconomics.core.core_resources.resource_model.resource_model import ResourceModel
from energy_models.core.stream_type.resources_models.resource_glossary import ResourceGlossary
from climateeconomics.core.tools.Hubbert_Curve import compute_Hubbert_regression
from sos_trades_core.tools.base_functions.exp_min import compute_dfunc_with_exp_min,\
compute_func_with_exp_min
class OrderOfMagnitude():
KILO = 'k'
# USD_PER_USton = 'USD/USton'
# MILLION_TONNES='million_tonnes'
magnitude_factor = {
KILO: 10 ** 3
# USD_PER_USton:1/0.907
# MILLION_TONNES: 10**6
}
class CopperResourceModel(ResourceModel):
"""
Resource model
General implementation of a resource model, to be inherited by specific models for each type of resource
"""
resource_name=ResourceGlossary.Copper['name']
def configure_parameters(self, inputs_dict):
super().configure_parameters(inputs_dict)
self.sectorisation_dict = inputs_dict['sectorisation']
self.resource_max_price = inputs_dict['resource_max_price']
#Units conversion
oil_barrel_to_tonnes = 6.84
bcm_to_Mt = 1 / 1.379
kU_to_Mt = 10 ** -6
#To convert from 1E6 oil_barrel to Mt
conversion_factor = 1.0
#Average copper price rise and decrease
price_rise = 1.494
price_decrease = 0.95
def convert_demand(self, demand):
self.resource_demand=demand
self.resource_demand[self.resource_name]=demand[self.resource_name]
def get_global_demand(self, demand):
energy_demand = self.sectorisation_dict['power_generation']
self.resource_demand=demand
self.resource_demand[self.resource_name]=demand[self.resource_name] * (100 / energy_demand)
self.conversion_factor = 100 / energy_demand
def sigmoid(self, ratio, sigmoid_min ):
'''
function sigmoid redefined for the ratio :
sigmoid([-10;10])->[0;1] becomes sigmoid([1;0])->[sigmoid_min, resource_max_price] (ratio = 1 matches sigmoids' lower bound, and ratio = 0 matches sigmoid's upper bound)
'''
x= -20*ratio +10
sig = 1/ (1 + math.exp(-x))
return sig*(self.resource_max_price-sigmoid_min) + sigmoid_min
def compute_price(self):
"""
price function depends on the ratio use_stock/demand
price(ratio) = (price_max - price_min)(1-ratio) + price_min
"""
# dataframe initialization
self.resource_price['price'] = np.insert(np.zeros(len(self.years)-1), 0, self.resource_price_data.loc[0, 'price'])
resource_price_dict = self.resource_price.to_dict()
self.resource_demand = self.resources_demand[['years', self.resource_name]]
self.get_global_demand(self.resource_demand)
demand = deepcopy(self.resource_demand[self.resource_name].values)
demand_limited = compute_func_with_exp_min(
np.array(demand), 1.0e-10)
self.ratio_usable_demand = np.maximum(self.use_stock[self.sub_resource_list[0]].values / demand_limited, 1E-15)
for year_cost in self.years[1:] :
resource_price_dict['price'][year_cost] = \
(self.resource_max_price - self.resource_price_data.loc[0, 'price']) *\
(1- self.ratio_usable_demand[year_cost - self.year_start]) + self.resource_price_data.loc[0, 'price']
self.resource_price= pd.DataFrame.from_dict(resource_price_dict)
def get_d_price_d_demand (self, year_start, year_end, nb_years, grad_use, grad_price):
ascending_price_resource_list = list(
self.resource_price_data.sort_values(by=['price'])['resource_type'])
demand = deepcopy(self.resource_demand[self.resource_name].values)
demand_limited = compute_func_with_exp_min(np.array(demand), 1.0e-10)
grad_demand_limited = compute_dfunc_with_exp_min(np.array(demand), 1.0e-10)
self.ratio_usable_demand = np.maximum(self.use_stock[self.sub_resource_list[0]].values / demand_limited, 1E-15)
# # ------------------------------------------------
# # price is cst *u/v function with u = use and v = demand
# # price gradient is cst * (u'v - uv') / v^2
for year_demand in range(year_start + 1, year_end + 1):
for resource_type in ascending_price_resource_list:
for year in range(year_start + 1, year_demand + 1):
#grad_price = cst * u'v / v^2 (cst < 0)
if self.use_stock[self.sub_resource_list[0]][year_demand]/demand_limited[year_demand - year_start] > 1E-15 :
grad_price[year_demand - year_start, year - year_start] = \
-(self.resource_max_price - self.resource_price_data.loc[0, 'price']) * \
grad_use[resource_type][year_demand - year_start, year - year_start]* grad_demand_limited[year_demand - year_start] / demand_limited[year_demand - year_start]
## grad_price -= cst * uv' / v^2 (cst < 0)
if year == year_demand :
grad_price[year_demand - year_start, year - year_start] += (self.resource_max_price - self.resource_price_data.loc[0, 'price']) *\
self.use_stock[self.sub_resource_list[0]][year_demand]\
* self.conversion_factor * grad_demand_limited[year_demand - year_start]/ demand_limited[year_demand - year_start] **2
return grad_price
|
[
"copy.deepcopy",
"math.exp",
"numpy.maximum",
"pandas.DataFrame.from_dict",
"numpy.array"
] |
[((3565, 3622), 'copy.deepcopy', 'deepcopy', (['self.resource_demand[self.resource_name].values'], {}), '(self.resource_demand[self.resource_name].values)\n', (3573, 3622), False, 'from copy import deepcopy\n'), ((3757, 3845), 'numpy.maximum', 'np.maximum', (['(self.use_stock[self.sub_resource_list[0]].values / demand_limited)', '(1e-15)'], {}), '(self.use_stock[self.sub_resource_list[0]].values /\n demand_limited, 1e-15)\n', (3767, 3845), True, 'import numpy as np\n'), ((4205, 4248), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['resource_price_dict'], {}), '(resource_price_dict)\n', (4227, 4248), True, 'import pandas as pd\n'), ((4496, 4553), 'copy.deepcopy', 'deepcopy', (['self.resource_demand[self.resource_name].values'], {}), '(self.resource_demand[self.resource_name].values)\n', (4504, 4553), False, 'from copy import deepcopy\n'), ((4766, 4854), 'numpy.maximum', 'np.maximum', (['(self.use_stock[self.sub_resource_list[0]].values / demand_limited)', '(1e-15)'], {}), '(self.use_stock[self.sub_resource_list[0]].values /\n demand_limited, 1e-15)\n', (4776, 4854), True, 'import numpy as np\n'), ((3693, 3709), 'numpy.array', 'np.array', (['demand'], {}), '(demand)\n', (3701, 3709), True, 'import numpy as np\n'), ((4611, 4627), 'numpy.array', 'np.array', (['demand'], {}), '(demand)\n', (4619, 4627), True, 'import numpy as np\n'), ((4695, 4711), 'numpy.array', 'np.array', (['demand'], {}), '(demand)\n', (4703, 4711), True, 'import numpy as np\n'), ((2889, 2901), 'math.exp', 'math.exp', (['(-x)'], {}), '(-x)\n', (2897, 2901), False, 'import math\n')]
|
"""
Collection of utility functions
"""
from numpy.random import RandomState
import pandas as pd
import numpy as np
import os
import functools
from networkx.algorithms import bipartite
import logging
def make_random_bipartite_data(group1, group2, p, seed):
"""
:type group1: list
:param group1: Ids of first group
:type group2: list
:param group2: Ids of second group
:type p: float
:param p: probability of existence of 1 edge
:type seed: int
:param seed: seed for random generator
:rtype: list
:return: all edges in the graph
"""
logging.info(" creating a bipartite graph between {} items in group1, {} "
"items in group2 and edge probability {}".format(
len(group1), len(group2), p))
if len(group1) == 0 or len(group2) == 0 or p == 0:
return []
bp = pd.DataFrame.from_records(list(bipartite.random_graph(len(group1), len(group2), p, seed).edges()),
columns=["from", "to"])
logging.info(" (bipartite index created, now resolving item values)")
# as all "to" nodes are from the second group,
# but numbered by networkx in range(len(group1),len(group1)+len(group2))
# we need to deduct len(group1) to have proper indexes.
bp["to"] -= len(group1)
bp["from"] = bp.apply(lambda x: group1[x["from"]], axis=1)
bp["to"] = bp.apply(lambda x: group2[x["to"]], axis=1)
logging.info(" (resolution done, now converting to tuples)")
out = [tuple(x) for x in bp.to_records(index=False)]
logging.info(" (exiting bipartite)")
return out
def assign_random_proportions(name1, name2, group1, group2, seed):
state = RandomState(seed)
assignments = state.rand(len(group1), len(group2))
assignments = assignments / assignments.sum(axis=1, keepdims=True)
data = pd.DataFrame(assignments, index=group1,
columns=group2).stack().reset_index(level=[0, 1])
data.rename(columns={"level_0": name1,
"level_1": name2,
0: "weight"},
inplace=True)
return data
def make_random_assign(set1, set2, seed):
"""Assign randomly a member of set2 to each member of set1
:return: a dataframe with as many rows as set1
"""
chosen_froms = RandomState(seed).choice(set2, size=len(set1))
return pd.DataFrame({"set1": set1, "chosen_from_set2": chosen_froms})
def merge_2_dicts(dict1, dict2, value_merge_func=None):
"""
:param dict1: first dictionary to be merged
:param dict2: first dictionary to be merged
:param value_merge_func: specifies how to merge 2 values if present in
both dictionaries
:type value_merge_func: function (value1, value) => value
:return:
"""
if dict1 is None and dict2 is None:
return {}
if dict2 is None:
return dict1
if dict1 is None:
return dict2
def merged_value(key):
if key not in dict1:
return dict2[key]
elif key not in dict2:
return dict1[key]
else:
if value_merge_func is None:
raise ValueError(
"Conflict in merged dictionaries: merge function not "
"provided but key {} exists in both dictionaries".format(
key))
return value_merge_func(dict1[key], dict2[key])
keys = set(dict1.keys()) | set(dict2.keys())
return {key: merged_value(key) for key in keys}
def df_concat(d1, d2):
return pd.concat([d1, d2], ignore_index=True, copy=False)
def merge_dicts(dicts, merge_func=None):
"""
:param dicts: list of dictionnaries to be merged
:type dicts: list[dict]
:param merge_func:
:type merge_func: function
:return: one single dictionary containing all entries received
"""
from itertools import tee
# check if the input list or iterator is empty
dict_backup, test = tee(iter(dicts))
try:
next(test)
except StopIteration:
return {}
return functools.reduce(lambda d1, d2: merge_2_dicts(d1, d2, merge_func), dict_backup)
def setup_logging():
logging.basicConfig(
format='%(asctime)s %(message)s',
level=logging.INFO)
# stolen from http://stackoverflow.com/questions/1835018/
# python-check-if-an-object-is-a-list-or-tuple-but-not-string#answer-1835259
def is_sequence(arg):
return type(arg) is list or type(arg) is tuple or type(arg) is set
def build_ids(size, id_start=0, prefix="id_", max_length=10):
"""
builds a sequencial list of string ids of specified size
"""
return [prefix + str(x).zfill(max_length)
for x in np.arange(id_start, id_start + size)]
def log_dataframe_sample(msg, df):
if df.shape[0] == 0:
logging.info("{}: [empty]".format(msg))
else:
logging.info("{}: \n {}".format(msg, df.sample(min(df.shape[0], 15))))
def cap_to_total(values, target_total):
"""
return a copy of values with the largest values possible s.t.:
- all return values are <= the original ones
- their sum is == total
-
"""
excedent = np.sum(values) - target_total
if excedent <= 0:
return values
elif values[-1] >= excedent:
return values[:-1] + [values[-1] - excedent]
else:
return cap_to_total(values[:-1], target_total) + [0]
def ensure_folder_exists(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def ensure_non_existing_dir(folder):
"""
makes sure the specified directory does not exist, potentially deleting
any file or folder it contains
"""
if not os.path.exists(folder):
return
if os.path.isfile(folder):
os.remove(folder)
else:
for f in os.listdir(folder):
full_path = os.path.join(folder, f)
ensure_non_existing_dir(full_path)
os.rmdir(folder)
def latest_date_before(starting_date, upper_bound, time_step):
"""
Looks for the latest result_date s.t
result_date = starting_date + n * time_step for any integer n
result_date <= upper_bound
:type starting_date: pd.Timestamp
:type upper_bound: pd.Timestamp
:type time_step: pd.Timedelta
:return: pd.Timestamp
"""
result = starting_date
while result > upper_bound:
result -= time_step
while upper_bound - result >= time_step:
result += time_step
return result
def load_all_logs(folder):
"""
loads all csv file contained in this folder and retun them as one
dictionary where the key is the filename without the extension
"""
all_logs = {}
for file_name in os.listdir(folder):
full_path = os.path.join(folder, file_name)
logs = pd.read_csv(full_path, index_col=None)
log_id = file_name[:-4]
all_logs[log_id] = logs
return all_logs
|
[
"pandas.DataFrame",
"os.listdir",
"os.remove",
"numpy.sum",
"os.makedirs",
"logging.basicConfig",
"pandas.read_csv",
"os.path.exists",
"numpy.random.RandomState",
"logging.info",
"os.path.isfile",
"numpy.arange",
"os.rmdir",
"os.path.join",
"pandas.concat"
] |
[((1027, 1097), 'logging.info', 'logging.info', (['""" (bipartite index created, now resolving item values)"""'], {}), "(' (bipartite index created, now resolving item values)')\n", (1039, 1097), False, 'import logging\n'), ((1442, 1503), 'logging.info', 'logging.info', (['""" (resolution done, now converting to tuples)"""'], {}), "(' (resolution done, now converting to tuples)')\n", (1454, 1503), False, 'import logging\n'), ((1565, 1602), 'logging.info', 'logging.info', (['""" (exiting bipartite)"""'], {}), "(' (exiting bipartite)')\n", (1577, 1602), False, 'import logging\n'), ((1700, 1717), 'numpy.random.RandomState', 'RandomState', (['seed'], {}), '(seed)\n', (1711, 1717), False, 'from numpy.random import RandomState\n'), ((2385, 2447), 'pandas.DataFrame', 'pd.DataFrame', (["{'set1': set1, 'chosen_from_set2': chosen_froms}"], {}), "({'set1': set1, 'chosen_from_set2': chosen_froms})\n", (2397, 2447), True, 'import pandas as pd\n'), ((3556, 3606), 'pandas.concat', 'pd.concat', (['[d1, d2]'], {'ignore_index': '(True)', 'copy': '(False)'}), '([d1, d2], ignore_index=True, copy=False)\n', (3565, 3606), True, 'import pandas as pd\n'), ((4182, 4255), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s %(message)s', level=logging.INFO)\n", (4201, 4255), False, 'import logging\n'), ((5739, 5761), 'os.path.isfile', 'os.path.isfile', (['folder'], {}), '(folder)\n', (5753, 5761), False, 'import os\n'), ((6729, 6747), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (6739, 6747), False, 'import os\n'), ((5184, 5198), 'numpy.sum', 'np.sum', (['values'], {}), '(values)\n', (5190, 5198), True, 'import numpy as np\n'), ((5462, 5484), 'os.path.exists', 'os.path.exists', (['folder'], {}), '(folder)\n', (5476, 5484), False, 'import os\n'), ((5494, 5513), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (5505, 5513), False, 'import os\n'), ((5692, 5714), 'os.path.exists', 'os.path.exists', (['folder'], {}), '(folder)\n', (5706, 5714), False, 'import os\n'), ((5771, 5788), 'os.remove', 'os.remove', (['folder'], {}), '(folder)\n', (5780, 5788), False, 'import os\n'), ((5817, 5835), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (5827, 5835), False, 'import os\n'), ((5940, 5956), 'os.rmdir', 'os.rmdir', (['folder'], {}), '(folder)\n', (5948, 5956), False, 'import os\n'), ((6769, 6800), 'os.path.join', 'os.path.join', (['folder', 'file_name'], {}), '(folder, file_name)\n', (6781, 6800), False, 'import os\n'), ((6816, 6854), 'pandas.read_csv', 'pd.read_csv', (['full_path'], {'index_col': 'None'}), '(full_path, index_col=None)\n', (6827, 6854), True, 'import pandas as pd\n'), ((2327, 2344), 'numpy.random.RandomState', 'RandomState', (['seed'], {}), '(seed)\n', (2338, 2344), False, 'from numpy.random import RandomState\n'), ((4711, 4747), 'numpy.arange', 'np.arange', (['id_start', '(id_start + size)'], {}), '(id_start, id_start + size)\n', (4720, 4747), True, 'import numpy as np\n'), ((5861, 5884), 'os.path.join', 'os.path.join', (['folder', 'f'], {}), '(folder, f)\n', (5873, 5884), False, 'import os\n'), ((1855, 1910), 'pandas.DataFrame', 'pd.DataFrame', (['assignments'], {'index': 'group1', 'columns': 'group2'}), '(assignments, index=group1, columns=group2)\n', (1867, 1910), True, 'import pandas as pd\n')]
|
import sys
path = '../../../'
sys.path.append(path)
from pdeopt.tools import get_data
import numpy as np
directories = [ 'Starter10/',
'Starter11/',
'Starter111/',
'Starter2/',
'Starter439/',
'Starter66/',
'Starter744/',
'Starter7552/',
'Starter758/',
'Starter7822/']
# I want to have these methods in my tabular:
method_tuple = [
[2 , '5. FOM proj. BFGS'],
[25,'1(a) standard lag.'],
[54,'1(b) standard uni.'],
[26,'Qian et al. 2017'],
]
max_time_0 = 0.
max_time_1 = 0.
max_time_2 = 0.
max_time_3 = 0.
min_time_0 = 10000.
min_time_1 = 10000.
min_time_2 = 10000.
min_time_3 = 10000.
sum_0 = []
sum_1 = []
sum_2 = []
sum_3 = []
max_iter_0 = 0.
max_iter_1 = 0.
max_iter_2 = 0.
max_iter_3 = 0.
min_iter_0 = 10000.
min_iter_1 = 10000.
min_iter_2 = 10000.
min_iter_3 = 10000.
iters_0 = []
iters_1 = []
iters_2 = []
iters_3 = []
sum_FOC_0 = []
sum_FOC_1 = []
sum_FOC_2 = []
sum_FOC_3 = []
# print('THIS IS THE MU FOR EXC10')
mu_opt = [0.01, 0.1, 8.37317446, 6.57227607, 0.46651735, 1.88354107]
mu_opt_norm = np.linalg.norm(mu_opt)
sum_muerror_0 = []
sum_muerror_1 = []
sum_muerror_2 = []
sum_muerror_3 = []
for directory in directories:
times_full_0 , _ , mu_error_0, FOC_0 = get_data(directory,method_tuple[0][0], mu_error_=True, FOC=True)
total_time = times_full_0[-1]
sum_muerror_0.append(mu_error_0[-1])
sum_FOC_0.append(FOC_0[-1])
sum_0.append(total_time)
min_time_0 = min(min_time_0, total_time)
max_time_0 = max(max_time_0, total_time)
iterations = len(times_full_0)-1
iters_0.append(iterations)
min_iter_0 = min(min_iter_0, iterations)
max_iter_0 = max(max_iter_0, iterations)
times_full_1 , _ , mu_error_1, FOC_1 = get_data(directory,method_tuple[1][0], mu_error_=True, FOC=True)
total_time = times_full_1[-1]
sum_muerror_1.append(mu_error_1[-1])
sum_FOC_1.append(FOC_1[-1])
sum_1.append(total_time)
min_time_1 = min(min_time_1, total_time)
max_time_1 = max(max_time_1, total_time)
iterations = len(times_full_1)-1
iters_1.append(iterations)
min_iter_1 = min(min_iter_1, iterations)
max_iter_1 = max(max_iter_1, iterations)
times_full_2 , _ , mu_error_2, FOC_2 = get_data(directory,method_tuple[2][0], mu_error_=True, FOC=True)
total_time = times_full_2[-1]
sum_muerror_2.append(mu_error_2[-1])
sum_FOC_2.append(FOC_2[-1])
sum_2.append(total_time)
min_time_2 = min(min_time_2, total_time)
max_time_2 = max(max_time_2, total_time)
iterations = len(times_full_2)-1
iters_2.append(iterations)
min_iter_2 = min(min_iter_2, iterations)
max_iter_2 = max(max_iter_2, iterations)
times_full_3 , _ , mu_error_3, FOC_3 = get_data(directory,method_tuple[3][0], mu_error_=True, FOC=True)
total_time = times_full_3[-1]
sum_muerror_3.append(mu_error_3[-1])
sum_FOC_3.append(FOC_3[-1])
sum_3.append(total_time)
min_time_3 = min(min_time_3, total_time)
max_time_3 = max(max_time_3, total_time)
iterations = len(times_full_3)-1
iters_3.append(iterations)
min_iter_3 = min(min_iter_3, iterations)
max_iter_3 = max(max_iter_3, iterations)
average_times_0 = sum(sum_0)/len(directories)
average_times_1 = sum(sum_1)/len(directories)
average_times_2 = sum(sum_2)/len(directories)
average_times_3 = sum(sum_3)/len(directories)
average_iters_0 = sum(iters_0)/len(directories)
average_iters_1 = sum(iters_1)/len(directories)
average_iters_2 = sum(iters_2)/len(directories)
average_iters_3 = sum(iters_3)/len(directories)
average_mu_error_0 = sum(sum_muerror_0)/len(directories)
average_mu_error_1 = sum(sum_muerror_1)/len(directories)
average_mu_error_2 = sum(sum_muerror_2)/len(directories)
average_mu_error_3 = sum(sum_muerror_3)/len(directories)
average_FOC_0 = sum(sum_FOC_0)/len(directories)
average_FOC_1 = sum(sum_FOC_1)/len(directories)
average_FOC_2 = sum(sum_FOC_2)/len(directories)
average_FOC_3 = sum(sum_FOC_3)/len(directories)
from tabulate import tabulate
print('AVERAGE time of the algorithms min and max:\n ')
headers = ['Method', 'average [s]', 'min [s]', 'max [s]', 'av. speed-up']
table = [[method_tuple[0][1], average_times_0, min_time_0, max_time_0, '--'],
[method_tuple[3][1], average_times_3, min_time_3, max_time_3, average_times_0/average_times_3],
[method_tuple[1][1], average_times_1, min_time_1, max_time_1, average_times_0/average_times_1],
[method_tuple[2][1], average_times_2, min_time_2, max_time_2, average_times_0/average_times_2]
]
print(tabulate(table, headers=headers, tablefmt='github', floatfmt='.2f'))
#print(tabulate(table, headers=headers, tablefmt='latex', floatfmt='.2f'))
print()
print('AVERAGE ITERATIONS of the algorithms min and max:\n ')
headers = ['Method', 'average it.', 'min it.', 'max it.', 'av. rel.error.', 'av. FOC cond.']
table = [[method_tuple[0][1], average_iters_0, min_iter_0, max_iter_0, average_mu_error_0/mu_opt_norm, average_FOC_0],
[method_tuple[3][1], average_iters_3, min_iter_3, max_iter_3, average_mu_error_3/mu_opt_norm, average_FOC_3],
[method_tuple[1][1], average_iters_1, min_iter_1, max_iter_1, average_mu_error_1/mu_opt_norm, average_FOC_1],
[method_tuple[2][1], average_iters_2, min_iter_2, max_iter_2, average_mu_error_2/mu_opt_norm, average_FOC_2]
]
print(tabulate(table, headers=headers, tablefmt='github', floatfmt='.8f'))
#print(tabulate(table, headers=headers, tablefmt='latex', floatfmt='.8f'))
print()
print()
# all together
headers = ['Method', 'average [s]', 'min [s]', 'max [s]', 'speed-up', 'av. it. ', 'min it.', 'max it.', 'rel.error.', 'FOC cond.']
table = [[method_tuple[0][1], average_times_0, min_time_0, max_time_0, '--' , average_iters_0, min_iter_0, max_iter_0, average_mu_error_0/mu_opt_norm, average_FOC_0],
[method_tuple[3][1], average_times_3, min_time_3, max_time_3, average_times_0/average_times_3, average_iters_3, min_iter_3, max_iter_3, average_mu_error_3/mu_opt_norm, average_FOC_3],
[method_tuple[1][1], average_times_1, min_time_1, max_time_1, average_times_0/average_times_1, average_iters_1, min_iter_1, max_iter_1, average_mu_error_1/mu_opt_norm, average_FOC_1],
[method_tuple[2][1], average_times_2, min_time_2, max_time_2, average_times_0/average_times_2, average_iters_2, min_iter_2, max_iter_2, average_mu_error_2/mu_opt_norm, average_FOC_2]
]
print(tabulate(table, headers=headers, tablefmt='github', floatfmt='.8f'))
|
[
"sys.path.append",
"tabulate.tabulate",
"numpy.linalg.norm",
"pdeopt.tools.get_data"
] |
[((30, 51), 'sys.path.append', 'sys.path.append', (['path'], {}), '(path)\n', (45, 51), False, 'import sys\n'), ((1265, 1287), 'numpy.linalg.norm', 'np.linalg.norm', (['mu_opt'], {}), '(mu_opt)\n', (1279, 1287), True, 'import numpy as np\n'), ((1440, 1505), 'pdeopt.tools.get_data', 'get_data', (['directory', 'method_tuple[0][0]'], {'mu_error_': '(True)', 'FOC': '(True)'}), '(directory, method_tuple[0][0], mu_error_=True, FOC=True)\n', (1448, 1505), False, 'from pdeopt.tools import get_data\n'), ((1942, 2007), 'pdeopt.tools.get_data', 'get_data', (['directory', 'method_tuple[1][0]'], {'mu_error_': '(True)', 'FOC': '(True)'}), '(directory, method_tuple[1][0], mu_error_=True, FOC=True)\n', (1950, 2007), False, 'from pdeopt.tools import get_data\n'), ((2445, 2510), 'pdeopt.tools.get_data', 'get_data', (['directory', 'method_tuple[2][0]'], {'mu_error_': '(True)', 'FOC': '(True)'}), '(directory, method_tuple[2][0], mu_error_=True, FOC=True)\n', (2453, 2510), False, 'from pdeopt.tools import get_data\n'), ((2947, 3012), 'pdeopt.tools.get_data', 'get_data', (['directory', 'method_tuple[3][0]'], {'mu_error_': '(True)', 'FOC': '(True)'}), '(directory, method_tuple[3][0], mu_error_=True, FOC=True)\n', (2955, 3012), False, 'from pdeopt.tools import get_data\n'), ((4782, 4849), 'tabulate.tabulate', 'tabulate', (['table'], {'headers': 'headers', 'tablefmt': '"""github"""', 'floatfmt': '""".2f"""'}), "(table, headers=headers, tablefmt='github', floatfmt='.2f')\n", (4790, 4849), False, 'from tabulate import tabulate\n'), ((5581, 5648), 'tabulate.tabulate', 'tabulate', (['table'], {'headers': 'headers', 'tablefmt': '"""github"""', 'floatfmt': '""".8f"""'}), "(table, headers=headers, tablefmt='github', floatfmt='.8f')\n", (5589, 5648), False, 'from tabulate import tabulate\n'), ((6675, 6742), 'tabulate.tabulate', 'tabulate', (['table'], {'headers': 'headers', 'tablefmt': '"""github"""', 'floatfmt': '""".8f"""'}), "(table, headers=headers, tablefmt='github', floatfmt='.8f')\n", (6683, 6742), False, 'from tabulate import tabulate\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.